hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
ba21c0ea464ce484f28172803ba839e9799ed9c6
4,261
cpp
C++
MainSource/DialogSave.cpp
bareboat-necessities/SdrGlut
54a35ea4bb0d2f0937e670751e32d1aead4d0619
[ "MIT" ]
null
null
null
MainSource/DialogSave.cpp
bareboat-necessities/SdrGlut
54a35ea4bb0d2f0937e670751e32d1aead4d0619
[ "MIT" ]
null
null
null
MainSource/DialogSave.cpp
bareboat-necessities/SdrGlut
54a35ea4bb0d2f0937e670751e32d1aead4d0619
[ "MIT" ]
null
null
null
/* * DialogSave.cpp * * * Created by Dale Ranta on 10/25/11. * Copyright 2011 Dale Ranta. All rights reserved. * */ #include "firstFile.h" #include <cstdio> #include <cstdlib> #include "DialogSave.h" #include "DialogFolder.h" #include "ulibTypes.h" #include "SceneList.h" #include "Utilities.h" #include <GL/glui.h> static GLUI_FileBrowser *fb; static GLUI *glui; static int type; static int boxSelection; static char text1b[255]="saveAudio.raw"; static char text2b[255]="savefile.iq"; static char text3b[255]="saveFluence.fbl"; static char text4b[255]="doc.kml"; static char text5b[255]="aresPreferences.pref"; static GLUI_EditText *edittext1b; static void control_cb(int control); static struct Scene *sceneLocal; static void (*callBack)(struct Scene *scene,char *name); static int datatype; static GLUI_Listbox *box; static void fillbox(void); static int listBoxIdMax=-1; int dialogSave(struct Scene *scene); extern "C" int goCD(char *name); int dialogSaveC(struct Scene *scene, void (*callBacki)(struct Scene *scene,char *name), int typei,char *namein) { datatype=typei; callBack=callBacki; if(namein){ mstrncpy(text2b,(char *)namein,sizeof(text2b)); } return dialogSave(scene); } int dialogSave(struct Scene *scene) { char *tpointer; if(glui){ glui->close(); } listBoxIdMax=-1; sceneLocal=scene; glui = GLUI_Master.create_glui( "Save File" ); GLUI_Panel *obj_panel = glui->add_panel( "Save File" ); box=glui->add_listbox_to_panel(obj_panel, " ",&boxSelection, 10, control_cb); box->set_w(480); fb = new GLUI_FileBrowser(obj_panel, "", false, 1,control_cb); fb->set_h(380); fb->set_w(580); fb->fillbox=fillbox; if(datatype == 0){ tpointer=text1b; }else if(datatype == 2){ tpointer=text3b; }else if(datatype == 3){ tpointer=text4b; }else if(datatype == 4){ tpointer=text5b; }else{ tpointer=text2b; } edittext1b = glui->add_edittext_to_panel(obj_panel, "Name :", GLUI_EDITTEXT_TEXT, tpointer ); edittext1b->w=280; glui->add_column(true); new GLUI_Button(glui, "New", 3, control_cb); new GLUI_Button(glui, "Save", 4, control_cb); new GLUI_Button(glui, "Cancel", 2, control_cb); // glui->set_main_gfx_window( glutGetWindow() ); fillbox(); return 0; } extern "C" char *strsave(char *s,int tag); static void fillbox() { char Directory[1024]; char name[1024]; char *list[2048]; char *np,c; unsigned int n; int nn,ni,k; if(!GetWorking(Directory,sizeof(Directory))){ WarningPrint("fillbox Working directory error\n"); return; } n=0; ni=0; np=name; while((c=Directory[n++]) && n < sizeof(Directory)){ if(c == FILE_NAME_SEPERATOR_CHAR){ if(np != name){ *np=0; list[ni++]=strsave(name,9827); } np=name; continue; } *np++ = c; } if(np != name){ *np=0; list[ni++]=strsave(name,9828); } for(nn=0;nn<listBoxIdMax;++nn){ box->delete_item(nn); } k=0; for(nn=ni-1;nn>=0;--nn){ box->add_item(k++,list[nn]); cFree((char *)list[nn]); } listBoxIdMax=k; } static void callMe(struct Scene *scene) { if(scene != sceneLocal)return; if(!fb)return; fillbox(); fb->fbreaddir("."); } static void control_cb(int control) { std::string file_name; if(sceneLocal){ if(SceneSetWindow(sceneLocal)){ WarningPrint("Window Not Found - Dialog Closed\n"); glui->close(); glui=NULL; return; } } if(control == 1) { file_name = ""; file_name = fb->get_file(); WarningPrint("control %d filename %s type %d\n",control,file_name.c_str(),type+1); //LoadFiles (sceneLocal,(char *)file_name.c_str(),type+1); glui->close(); //doCommands(1); glui=NULL; fb=NULL; } else if(control == 2) { glui->close(); glui=NULL; fb=NULL; } else if(control == 3) { dialogFolder(sceneLocal,callMe); } else if(control == 4) { /* WarningPrint("Save %s\n",edittext1b->get_text()); */ glui->close(); if(callBack)(*callBack)(sceneLocal,(char *)edittext1b->get_text()); glui=NULL; fb=NULL; } else if(control == 10) { /* WarningPrint("boxSelection %d\n",boxSelection); */ for(int n=0; n<boxSelection; ++n){ goCD((char *)"../"); } fillbox(); fb->fbreaddir("."); } }
17.903361
111
0.64445
bareboat-necessities
ba22014ee4d1d251f4320a3f4b06de5c05d3de17
743
hpp
C++
header/actors-framework/executor/policy/unprofiled.hpp
0xBYTESHIFT/actors-framework
e5a9fc86978bd42d2db55c2f6014aed0d0149ed7
[ "BSD-3-Clause" ]
null
null
null
header/actors-framework/executor/policy/unprofiled.hpp
0xBYTESHIFT/actors-framework
e5a9fc86978bd42d2db55c2f6014aed0d0149ed7
[ "BSD-3-Clause" ]
null
null
null
header/actors-framework/executor/policy/unprofiled.hpp
0xBYTESHIFT/actors-framework
e5a9fc86978bd42d2db55c2f6014aed0d0149ed7
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <actors-framework/executor/executable.hpp> namespace actors_framework::executor { class unprofiled { public: virtual ~unprofiled() = default; template<class Worker> void before_shutdown(Worker*) {} template<class Worker> void before_resume(Worker*, executable*) {} template<class Worker> void after_resume(Worker*, executable*) {} template<class Worker> void after_completion(Worker*, executable*) {} protected: template<class WorkerOrCoordinator> static auto cast(WorkerOrCoordinator* self) -> decltype(self->data()) { return self->data(); } }; } // namespace actors_framework::executor
23.967742
79
0.637954
0xBYTESHIFT
ba229cbb099217b27e0a5219d84d89e7fdd0629e
3,776
hpp
C++
include/wrenbind17/variable.hpp
PossiblyAShrub/wrenbind17
4857a3825b7f772bde8aeb1cd8b60716b3d890c0
[ "MIT" ]
41
2019-08-03T16:38:35.000Z
2022-03-04T22:30:26.000Z
include/wrenbind17/variable.hpp
PossiblyAShrub/wrenbind17
4857a3825b7f772bde8aeb1cd8b60716b3d890c0
[ "MIT" ]
8
2019-08-05T12:42:06.000Z
2022-02-16T22:49:25.000Z
include/wrenbind17/variable.hpp
PossiblyAShrub/wrenbind17
4857a3825b7f772bde8aeb1cd8b60716b3d890c0
[ "MIT" ]
5
2020-07-26T19:10:10.000Z
2021-12-23T05:35:52.000Z
#pragma once #include "method.hpp" #include "pop.hpp" #include "push.hpp" /** * @ingroup wrenbind17 */ namespace wrenbind17 { /** * @ingroup wrenbind17 * @brief Holds some Wren variable which can be a class or class instance * @details You can use this to pass around Wren classes or class instances. * You can also use this to get Wren class methods. You can also call a Wren * function from C++ side and pass this Variable into Wren. To get this variable, * either call a Wren function that returns some class (or class instance), or * use wrenbind17::VM::find() function that looks up a class (or class instance) * based on the module name. * @note This variable can safely outlive the wrenbind17::VM class. If that happens * then functions of this class will throw wrenbind17::RuntimeError exception. This * holder will not try to free the Wren variable if the VM has been terminated. You * don't have to worry about the lifetime of this holder. (uses weak pointers). */ class Variable { public: Variable() { } Variable(const std::shared_ptr<Handle>& handle) : handle(handle) { } ~Variable() { reset(); } /*! * @brief Looks up a function from this Wren variable. * @details The signature must match Wren function signature. * For example: `main()` or `foo(_,_)` etc. Use underscores to specify * parameters of that function. * @throws RuntimeError if this variable is invalid or the Wren VM has terminated. */ Method func(const std::string& signature) { if (const auto ptr = handle->getVmWeak().lock()) { auto* h = wrenMakeCallHandle(ptr.get(), signature.c_str()); return Method(handle, std::make_shared<Handle>(ptr, h)); } else { throw RuntimeError("Invalid handle"); } } Handle& getHandle() { return *handle; } const Handle& getHandle() const { return *handle; } operator bool() const { return handle.operator bool(); } void reset() { handle.reset(); } private: std::shared_ptr<Handle> handle; }; template <> inline Variable detail::getSlot<Variable>(WrenVM* vm, const int idx) { validate<WrenType::WREN_TYPE_UNKNOWN>(vm, idx); return Variable(std::make_shared<Handle>(getSharedVm(vm), wrenGetSlotHandle(vm, idx))); } template <> inline bool detail::is<Variable>(WrenVM* vm, const int idx) { return wrenGetSlotType(vm, idx) == WREN_TYPE_UNKNOWN; } template <> inline void detail::PushHelper<Variable>::f(WrenVM* vm, int idx, const Variable& value) { wrenSetSlotHandle(value.getHandle().getVm(), idx, value.getHandle().getHandle()); } template <> inline void detail::PushHelper<Variable>::f(WrenVM* vm, int idx, Variable&& value) { wrenSetSlotHandle(value.getHandle().getVm(), idx, value.getHandle().getHandle()); } template <> inline void detail::PushHelper<const Variable>::f(WrenVM* vm, int idx, const Variable value) { wrenSetSlotHandle(value.getHandle().getVm(), idx, value.getHandle().getHandle()); } template <> inline void detail::PushHelper<const Variable&>::f(WrenVM* vm, int idx, const Variable& value) { wrenSetSlotHandle(value.getHandle().getVm(), idx, value.getHandle().getHandle()); } template <> inline void detail::PushHelper<Variable&>::f(WrenVM* vm, int idx, Variable& value) { wrenSetSlotHandle(value.getHandle().getVm(), idx, value.getHandle().getHandle()); } } // namespace wrenbind17
37.76
112
0.62553
PossiblyAShrub
ba24e59706fa0a3b6049ff1d2174853d54721916
15,179
cpp
C++
ChkdraftLib/Windows/DialogWindows/MapSettings/Forces.cpp
heinermann/Chkdraft
e79332d3a7a6b89b028246ff641bcbe266039dca
[ "MIT" ]
25
2015-03-10T21:50:09.000Z
2020-08-13T08:01:30.000Z
ChkdraftLib/Windows/DialogWindows/MapSettings/Forces.cpp
heinermann/Chkdraft
e79332d3a7a6b89b028246ff641bcbe266039dca
[ "MIT" ]
45
2015-01-05T15:05:37.000Z
2020-09-25T04:18:26.000Z
ChkdraftLib/Windows/DialogWindows/MapSettings/Forces.cpp
heinermann/Chkdraft
e79332d3a7a6b89b028246ff641bcbe266039dca
[ "MIT" ]
11
2015-08-14T04:19:10.000Z
2017-04-01T18:57:05.000Z
#include "Forces.h" #include "../../../Chkdraft.h" #include <string> enum_t(Id, u32, { EDIT_F1NAME = ID_FIRST, EDIT_F4NAME = (EDIT_F1NAME+3), LB_F1PLAYERS, LB_F4PLAYERS = (LB_F1PLAYERS+3), CHECK_F1ALLIED, CHECK_F2ALLIED, CHECK_F3ALLIED, CHECK_F4ALLIED, CHECK_F1RANDOM, CHECK_F2RANDOM, CHECK_F3RANDOM, CHECK_F4RANDOM, CHECK_F1VISION, CHECK_F2VISION, CHECK_F3VISION, CHECK_F4VISION, CHECK_F1AV, CHECK_F2AV, CHECK_F3AV, CHECK_F4AV }); UINT WM_DRAGNOTIFY(WM_NULL); ForcesWindow::ForcesWindow() : playerBeingDragged(255) { for ( int i=0; i<4; i++ ) possibleForceNameUpdate[i] = false; } ForcesWindow::~ForcesWindow() { } bool ForcesWindow::CreateThis(HWND hParent, u64 windowId) { if ( getHandle() != NULL ) return SetParent(hParent); if ( ClassWindow::RegisterWindowClass(0, NULL, NULL, NULL, NULL, "Forces", NULL, false) && ClassWindow::CreateClassWindow(0, "Forces", WS_VISIBLE|WS_CHILD, 4, 22, 592, 524, hParent, (HMENU)windowId) ) { HWND hForces = getHandle(); textAboutForces.CreateThis(hForces, 5, 10, 587, 20, "Designate player forces, set force names, and force properties. It is recommended to separate computer and human players", 0); const char* forceGroups[] = { "Force 1", "Force 2", "Force 3", "Force 4" }; for ( int y=0; y<2; y++ ) { for ( int x=0; x<2; x++ ) { int force = x+y*2; u8 forceFlags = CM->players.getForceFlags((Chk::Force)force); bool allied = forceFlags & Chk::ForceFlags::RandomAllies; bool vision = forceFlags & Chk::ForceFlags::SharedVision; bool random = forceFlags & Chk::ForceFlags::RandomizeStartLocation; bool av = forceFlags & Chk::ForceFlags::AlliedVictory; groupForce[force].CreateThis(hForces, 5+293*x, 50+239*y, 288, 234, forceGroups[force], 0); editForceName[force].CreateThis(hForces, 20+293*x, 70+239*y, 268, 20, false, Id::EDIT_F1NAME+force); auto forceName = CM->strings.getForceName<ChkdString>((Chk::Force)force); editForceName[force].SetText(forceName != nullptr && !forceName->empty() ? forceName->c_str() : ""); dragForces[force].CreateThis(hForces, 20+293*x, 95+239*y, 268, 121, Id::LB_F1PLAYERS+force); checkAllied[force].CreateThis(hForces, 15+293*x, 232+239*y, 100, 20, allied, "Allied", Id::CHECK_F1ALLIED+force); checkSharedVision[force].CreateThis(hForces, 15+293*x, 252+239*y, 100, 20, vision, "Share Vision", Id::CHECK_F1VISION+force); checkRandomizeStart[force].CreateThis(hForces, 125+293*x, 232+239*y, 150, 20, random, "Randomize Start Location", Id::CHECK_F1RANDOM+force); checkAlliedVictory[force].CreateThis(hForces, 125+293*x, 252+239*y, 150, 20, av, "Enable Allied Victory", Id::CHECK_F1AV+force); } } if ( WM_DRAGNOTIFY == WM_NULL ) WM_DRAGNOTIFY = RegisterWindowMessage(DRAGLISTMSGSTRING); return true; } else return false; } bool ForcesWindow::DestroyThis() { playerBeingDragged = 255; return true; } void ForcesWindow::RefreshWindow() { HWND hWnd = getHandle(); if ( CM != nullptr ) { for ( int force=0; force<4; force++ ) { u8 forceFlags = CM->players.getForceFlags((Chk::Force)force); bool allied = forceFlags & Chk::ForceFlags::RandomAllies; bool vision = forceFlags & Chk::ForceFlags::SharedVision; bool random = forceFlags & Chk::ForceFlags::RandomizeStartLocation; bool av = forceFlags & Chk::ForceFlags::AlliedVictory; auto forceName = CM->strings.getForceName<ChkdString>((Chk::Force)force); editForceName[force].SetWinText(forceName != nullptr && !forceName->empty() ? forceName->c_str() : ""); if ( allied ) SendMessage(GetDlgItem(hWnd, Id::CHECK_F1ALLIED+force), BM_SETCHECK, BST_CHECKED , 0); else SendMessage(GetDlgItem(hWnd, Id::CHECK_F1ALLIED+force), BM_SETCHECK, BST_UNCHECKED, 0); if ( vision ) SendMessage(GetDlgItem(hWnd, Id::CHECK_F1VISION+force), BM_SETCHECK, BST_CHECKED , 0); else SendMessage(GetDlgItem(hWnd, Id::CHECK_F1VISION+force), BM_SETCHECK, BST_UNCHECKED, 0); if ( random ) SendMessage(GetDlgItem(hWnd, Id::CHECK_F1RANDOM+force), BM_SETCHECK, BST_CHECKED , 0); else SendMessage(GetDlgItem(hWnd, Id::CHECK_F1RANDOM+force), BM_SETCHECK, BST_UNCHECKED, 0); if ( av ) SendMessage(GetDlgItem(hWnd, Id::CHECK_F1AV +force), BM_SETCHECK, BST_CHECKED , 0); else SendMessage(GetDlgItem(hWnd, Id::CHECK_F1AV +force), BM_SETCHECK, BST_UNCHECKED, 0); } for ( int i=0; i<4; i++ ) { HWND hListBox = GetDlgItem(hWnd, Id::LB_F1PLAYERS+i); if ( hListBox != NULL ) while ( SendMessage(hListBox, LB_DELETESTRING, 0, 0) != LB_ERR ); } for ( u8 slot=0; slot<8; slot++ ) { u8 displayOwner(CM->GetPlayerOwnerStringId(slot)); Chk::Force force = CM->players.getPlayerForce(slot); Chk::PlayerColor color = CM->players.getPlayerColor(slot); Chk::Race race = CM->players.getPlayerRace(slot); std::stringstream ssplayer; std::string playerColorStr = ""; if ( color < playerColors.size() ) playerColorStr = playerColors.at(color); std::string playerOwnerStr = ""; if ( displayOwner < playerOwners.size() ) playerOwnerStr = playerOwners.at(displayOwner); std::string playerRaceStr = ""; if ( race < playerRaces.size() ) playerRaceStr = playerRaces.at(race); ssplayer << "Player " << (slot+1) << " - " << playerColorStr << " - " << playerRaces.at(race) << " (" << playerOwners.at(displayOwner) << ")"; HWND hListBox = GetDlgItem(hWnd, Id::LB_F1PLAYERS+(int)force); if ( hListBox != NULL ) SendMessage(hListBox, LB_ADDSTRING, 0, (LPARAM)icux::toUistring(ssplayer.str()).c_str()); } } } LRESULT ForcesWindow::Command(HWND hWnd, WPARAM wParam, LPARAM lParam) { switch ( HIWORD(wParam) ) { case BN_CLICKED: { LRESULT state = SendMessage((HWND)lParam, BM_GETCHECK, 0, 0); if ( CM != nullptr ) { Id buttonId = (Id)LOWORD(wParam); switch ( buttonId ) { case Id::CHECK_F1ALLIED: case Id::CHECK_F2ALLIED: case Id::CHECK_F3ALLIED: case Id::CHECK_F4ALLIED: { Chk::Force force = Chk::Force(LOWORD(wParam) - Id::CHECK_F1ALLIED); if ( state == BST_CHECKED ) CM->players.setForceFlags(force, CM->players.getForceFlags(force) | Chk::ForceFlags::RandomAllies); else CM->players.setForceFlags(force, CM->players.getForceFlags(force) & Chk::ForceFlags::xRandomAllies); CM->notifyChange(false); } break; case Id::CHECK_F1VISION: case Id::CHECK_F2VISION: case Id::CHECK_F3VISION: case Id::CHECK_F4VISION: { Chk::Force force = Chk::Force(buttonId-Id::CHECK_F1VISION); if ( state == BST_CHECKED ) CM->players.setForceFlags(force, CM->players.getForceFlags(force) | Chk::ForceFlags::SharedVision); else CM->players.setForceFlags(force, CM->players.getForceFlags(force) & Chk::ForceFlags::xSharedVision); CM->notifyChange(false); } break; case Id::CHECK_F1RANDOM: case Id::CHECK_F2RANDOM: case Id::CHECK_F3RANDOM: case Id::CHECK_F4RANDOM: { Chk::Force force = Chk::Force(buttonId-Id::CHECK_F1RANDOM); if ( state == BST_CHECKED ) CM->players.setForceFlags(force, CM->players.getForceFlags(force) | Chk::ForceFlags::RandomizeStartLocation); else CM->players.setForceFlags(force, CM->players.getForceFlags(force) & Chk::ForceFlags::xRandomizeStartLocation); CM->notifyChange(false); } break; case Id::CHECK_F1AV: case Id::CHECK_F2AV: case Id::CHECK_F3AV: case Id::CHECK_F4AV: { Chk::Force force = Chk::Force(buttonId-Id::CHECK_F1AV); if ( state == BST_CHECKED ) CM->players.setForceFlags(force, CM->players.getForceFlags(force) | Chk::ForceFlags::AlliedVictory); else CM->players.setForceFlags(force, CM->players.getForceFlags(force) & Chk::ForceFlags::xAlliedVictory); CM->notifyChange(false); } break; } } } break; case EN_CHANGE: if ( LOWORD(wParam) >= Id::EDIT_F1NAME && LOWORD(wParam) <= Id::EDIT_F4NAME ) possibleForceNameUpdate[LOWORD(wParam) - Id::EDIT_F1NAME] = true; break; case EN_KILLFOCUS: if ( LOWORD(wParam) >= Id::EDIT_F1NAME && LOWORD(wParam) <= Id::EDIT_F4NAME ) CheckReplaceForceName(Chk::Force(LOWORD(wParam) - Id::EDIT_F1NAME)); break; } return ClassWindow::Command(hWnd, wParam, lParam); } LRESULT ForcesWindow::WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch ( msg ) { case WM_SHOWWINDOW: if ( wParam == TRUE ) { RefreshWindow(); chkd.mapSettingsWindow.SetWinText("Map Settings"); } else { for ( size_t i=0; i<4; i++ ) CheckReplaceForceName((Chk::Force)i); } break; default: { if ( WM_DRAGNOTIFY != WM_NULL && msg == WM_DRAGNOTIFY ) { DRAGLISTINFO* dragInfo = (DRAGLISTINFO*)lParam; switch ( dragInfo->uNotification ) { case DL_BEGINDRAG: { int index = LBItemFromPt(dragInfo->hWnd, dragInfo->ptCursor, FALSE); LRESULT length = SendMessage(dragInfo->hWnd, LB_GETTEXTLEN, index, 0)+1; std::unique_ptr<TCHAR> str = std::unique_ptr<TCHAR>(new TCHAR[length]); length = SendMessage(dragInfo->hWnd, LB_GETTEXT, index, (LPARAM)str.get()); if ( length != LB_ERR && length > 8 && str.get()[7] >= '1' && str.get()[7] <= '8' ) { playerBeingDragged = str.get()[7]-'1'; for ( int id=Id::LB_F1PLAYERS; id<=Id::LB_F4PLAYERS; id++ ) { HWND hForceLb = GetDlgItem(hWnd, id); if ( hForceLb != dragInfo->hWnd && hForceLb != NULL ) SendMessage(GetDlgItem(hWnd, id), LB_SETCURSEL, -1, 0); } return TRUE; } else return FALSE; } break; case DL_CANCELDRAG: playerBeingDragged = 255; return ClassWindow::WndProc(hWnd, msg, wParam, lParam); break; case DL_DRAGGING: { HWND hUnder = WindowFromPoint(dragInfo->ptCursor); if ( hUnder != NULL ) { LONG windowID = GetWindowLong(hUnder, GWL_ID); if ( windowID >= Id::LB_F1PLAYERS && windowID <= Id::LB_F4PLAYERS ) return DL_MOVECURSOR; } return DL_STOPCURSOR; } break; case DL_DROPPED: { HWND hUnder = WindowFromPoint(dragInfo->ptCursor); if ( hUnder != NULL && playerBeingDragged < 8 ) { LONG windowID = GetWindowLong(hUnder, GWL_ID); if ( windowID >= Id::LB_F1PLAYERS && windowID <= Id::LB_F4PLAYERS ) { Chk::Force force = Chk::Force(windowID-Id::LB_F1PLAYERS); if ( CM != nullptr ) { CM->players.setPlayerForce(playerBeingDragged, force); RefreshWindow(); std::stringstream ssPlayer; ssPlayer << "Player " << playerBeingDragged+1; SendMessage(GetDlgItem(hWnd, Id::LB_F1PLAYERS+force), LB_SELECTSTRING, -1, (LPARAM)icux::toUistring(ssPlayer.str()).c_str()); CM->notifyChange(false); chkd.trigEditorWindow.RefreshWindow(); SetFocus(getHandle()); } } } playerBeingDragged = 255; return ClassWindow::WndProc(hWnd, msg, wParam, lParam); } break; default: return ClassWindow::WndProc(hWnd, msg, wParam, lParam); break; } } else return ClassWindow::WndProc(hWnd, msg, wParam, lParam); } break; } return 0; } void ForcesWindow::CheckReplaceForceName(Chk::Force force) { ChkdString newMapForce; if ( (size_t)force < 4 && possibleForceNameUpdate[(size_t)force] == true && editForceName[(size_t)force].GetWinText(newMapForce) && newMapForce.length() > 0 ) { CM->strings.setForceName<ChkdString>(force, newMapForce); CM->strings.deleteUnusedStrings(Chk::Scope::Both); CM->notifyChange(false); CM->refreshScenario(); possibleForceNameUpdate[(size_t)force] = false; } }
43.617816
169
0.512155
heinermann
ba27bb7d3e13e8016ec8a522d8c90488b79d725f
2,834
hpp
C++
third_party/boost/include/boost/atomic/detail/fp_ops_generic.hpp
fmilano/CppMicroServices
b7e79edb558a63e45f6788e4a8b4e787cf956689
[ "Apache-2.0" ]
588
2015-10-07T15:55:08.000Z
2022-03-29T00:35:44.000Z
third_party/boost/include/boost/atomic/detail/fp_ops_generic.hpp
fmilano/CppMicroServices
b7e79edb558a63e45f6788e4a8b4e787cf956689
[ "Apache-2.0" ]
459
2015-10-05T23:29:59.000Z
2022-03-29T14:13:37.000Z
third_party/boost/include/boost/atomic/detail/fp_ops_generic.hpp
fmilano/CppMicroServices
b7e79edb558a63e45f6788e4a8b4e787cf956689
[ "Apache-2.0" ]
218
2015-11-04T08:19:48.000Z
2022-03-24T02:17:08.000Z
/* * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) * * Copyright (c) 2018 Andrey Semashev */ /*! * \file atomic/detail/fp_ops_generic.hpp * * This header contains generic implementation of the floating point atomic operations. */ #ifndef BOOST_ATOMIC_DETAIL_FP_OPS_GENERIC_HPP_INCLUDED_ #define BOOST_ATOMIC_DETAIL_FP_OPS_GENERIC_HPP_INCLUDED_ #include <cstddef> #include <boost/memory_order.hpp> #include <boost/atomic/detail/config.hpp> #include <boost/atomic/detail/bitwise_fp_cast.hpp> #include <boost/atomic/detail/storage_traits.hpp> #include <boost/atomic/detail/fp_operations_fwd.hpp> #ifdef BOOST_HAS_PRAGMA_ONCE #pragma once #endif namespace boost { namespace atomics { namespace detail { //! Generic implementation of floating point operations template< typename Base, typename Value, std::size_t Size > struct generic_fp_operations : public Base { typedef Base base_type; typedef typename base_type::storage_type storage_type; typedef Value value_type; static BOOST_FORCEINLINE value_type fetch_add(storage_type volatile& storage, value_type v, memory_order order) BOOST_NOEXCEPT { storage_type old_storage, new_storage; value_type old_val, new_val; atomics::detail::non_atomic_load(storage, old_storage); do { old_val = atomics::detail::bitwise_fp_cast< value_type >(old_storage); new_val = old_val + v; new_storage = atomics::detail::bitwise_fp_cast< storage_type >(new_val); } while (!base_type::compare_exchange_weak(storage, old_storage, new_storage, order, memory_order_relaxed)); return old_val; } static BOOST_FORCEINLINE value_type fetch_sub(storage_type volatile& storage, value_type v, memory_order order) BOOST_NOEXCEPT { storage_type old_storage, new_storage; value_type old_val, new_val; atomics::detail::non_atomic_load(storage, old_storage); do { old_val = atomics::detail::bitwise_fp_cast< value_type >(old_storage); new_val = old_val - v; new_storage = atomics::detail::bitwise_fp_cast< storage_type >(new_val); } while (!base_type::compare_exchange_weak(storage, old_storage, new_storage, order, memory_order_relaxed)); return old_val; } }; // Default fp_operations template definition will be used unless specialized for a specific platform template< typename Base, typename Value, std::size_t Size > struct fp_operations< Base, Value, Size, true > : public generic_fp_operations< Base, Value, Size > { }; } // namespace detail } // namespace atomics } // namespace boost #endif // BOOST_ATOMIC_DETAIL_FP_OPS_GENERIC_HPP_INCLUDED_
33.738095
130
0.729358
fmilano
ba2bea98ce509d07595de4584ec68018eb5a3c19
6,680
cpp
C++
source/render_vulkan/VulkanTexture.cpp
zjhlogo/blink
025da3506b34e3f0b02be524c97ae1f39c4c5854
[ "Apache-2.0" ]
null
null
null
source/render_vulkan/VulkanTexture.cpp
zjhlogo/blink
025da3506b34e3f0b02be524c97ae1f39c4c5854
[ "Apache-2.0" ]
null
null
null
source/render_vulkan/VulkanTexture.cpp
zjhlogo/blink
025da3506b34e3f0b02be524c97ae1f39c4c5854
[ "Apache-2.0" ]
null
null
null
/*! * \file VulkanTexture.cpp * * \author zjhlogo * \date 2020/01/19 * * */ #include "VulkanTexture.h" #include "VulkanBuffer.h" #include "VulkanCommandBuffer.h" #include "VulkanCommandPool.h" #include "VulkanContext.h" #include "VulkanImage.h" #include "VulkanLogicalDevice.h" #include "VulkanMemory.h" #include "utils/VulkanUtils.h" #define STB_IMAGE_IMPLEMENTATION #include <tinygltf/stb_image.h> namespace blink { VulkanTexture::VulkanTexture(VulkanLogicalDevice& logicalDevice, VulkanCommandPool& pool) : m_logicalDevice(logicalDevice) , m_commandPool(pool) { } VulkanTexture::~VulkanTexture() { destroy(); } bool VulkanTexture::createTexture2D(const tstring& texFile) { int texWidth = 0; int texHeight = 0; int texChannels = 0; stbi_uc* pixels = stbi_load(texFile.c_str(), &texWidth, &texHeight, &texChannels, STBI_rgb_alpha); if (!pixels) return nullptr; bool success = createTexture2D(pixels, texWidth, texHeight, texChannels); stbi_image_free(pixels); return success; } bool VulkanTexture::createTexture2D(void* pixels, int width, int height, int channels) { if (!createTextureImage(pixels, width, height, channels)) return false; if (m_textureImage->createImageView(VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_ASPECT_COLOR_BIT) == nullptr) { return false; } if (!createTextureSampler()) return false; return true; } bool VulkanTexture::createDepthTexture(int width, int height) { destroyTextureImage(); VkFormat depthFormat = VulkanUtils::findSupportedFormat(m_logicalDevice.getContext()->getPickedPhysicalDevice(), {VK_FORMAT_D32_SFLOAT, VK_FORMAT_D32_SFLOAT_S8_UINT, VK_FORMAT_D24_UNORM_S8_UINT}, VK_IMAGE_TILING_OPTIMAL, VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT); // create depth image m_textureImage = new VulkanImage(m_logicalDevice); m_textureImage->createImage(VK_IMAGE_TYPE_2D, width, height, depthFormat, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT); m_textureImage->allocateImageMemory(); m_textureImage->createImageView(depthFormat, VK_IMAGE_ASPECT_DEPTH_BIT); m_textureImage->transitionImageLayout(m_commandPool, depthFormat, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); return true; } void VulkanTexture::destroy() { destroyTextureSampler(); destroyTextureImage(); } VulkanImage* VulkanTexture::createTextureImage(void* pixels, int width, int height, int channels) { destroyTextureImage(); VkDeviceSize imageSize = width * height * 4; // create staging buffer VulkanBuffer* stagingBuffer = new VulkanBuffer(m_logicalDevice); stagingBuffer->createBuffer(imageSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_SHARING_MODE_EXCLUSIVE); VulkanMemory* bufferMemory = stagingBuffer->allocateBufferMemory(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); // copy buffer into staging buffer memory bufferMemory->uploadData(pixels, imageSize, 0); // create image m_textureImage = new VulkanImage(m_logicalDevice); m_textureImage->createImage(VK_IMAGE_TYPE_2D, width, height, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT); m_textureImage->allocateImageMemory(); m_textureImage->transitionImageLayout(m_commandPool, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); // copy buffer to image { VulkanCommandBuffer commandBuffer(m_logicalDevice, m_commandPool); commandBuffer.create(); commandBuffer.beginCommand(); VkBufferImageCopy region; region.bufferOffset = 0; region.bufferRowLength = 0; region.bufferImageHeight = 0; region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; region.imageSubresource.mipLevel = 0; region.imageSubresource.baseArrayLayer = 0; region.imageSubresource.layerCount = 1; region.imageOffset = {0, 0, 0}; region.imageExtent = {(uint32_t)width, (uint32_t)height, 1}; vkCmdCopyBufferToImage(commandBuffer, *stagingBuffer, *m_textureImage, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &region); commandBuffer.endCommand(); commandBuffer.submitCommand(); commandBuffer.destroy(); } m_textureImage->transitionImageLayout(m_commandPool, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); // destroy staging buffer SAFE_DELETE(stagingBuffer); return m_textureImage; } void VulkanTexture::destroyTextureImage() { SAFE_DELETE(m_textureImage); } VkSampler VulkanTexture::createTextureSampler() { destroyTextureSampler(); VkSamplerCreateInfo samplerInfo{}; samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; samplerInfo.magFilter = VK_FILTER_LINEAR; samplerInfo.minFilter = VK_FILTER_LINEAR; samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT; samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT; samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT; samplerInfo.anisotropyEnable = VK_TRUE; samplerInfo.maxAnisotropy = 16; samplerInfo.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK; samplerInfo.unnormalizedCoordinates = VK_FALSE; samplerInfo.compareEnable = VK_FALSE; samplerInfo.compareOp = VK_COMPARE_OP_ALWAYS; samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; samplerInfo.mipLodBias = 0.0f; samplerInfo.minLod = 0.0f; samplerInfo.maxLod = 0.0f; vkCreateSampler(m_logicalDevice, &samplerInfo, nullptr, &m_textureSampler); return m_textureSampler; } void VulkanTexture::destroyTextureSampler() { if (m_textureSampler != nullptr) { vkDestroySampler(m_logicalDevice, m_textureSampler, nullptr); m_textureSampler = nullptr; } } } // namespace blink
36.906077
157
0.672455
zjhlogo
ba2e1d82b447f75197be43c503ddd8e625484c61
399
hpp
C++
libs/input/include/sge/input/focus/event/discover_fwd.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
libs/input/include/sge/input/focus/event/discover_fwd.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
libs/input/include/sge/input/focus/event/discover_fwd.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef SGE_INPUT_FOCUS_EVENT_DISCOVER_FWD_HPP_INCLUDED #define SGE_INPUT_FOCUS_EVENT_DISCOVER_FWD_HPP_INCLUDED namespace sge::input::focus::event { class discover; } #endif
23.470588
61
0.75188
cpreh
ba2f24a995bb78b279e001e644c895d135cbe5dc
1,697
hpp
C++
src/Ets2/Save.hpp
TruckerMP/ETS2Sync-Helper-4
2a8b9df1d4db1e59635762147725fcec84eaf211
[ "Apache-2.0" ]
1
2018-12-08T07:31:13.000Z
2018-12-08T07:31:13.000Z
src/Ets2/Save.hpp
TruckerMP/ETS2Sync-Helper-4
2a8b9df1d4db1e59635762147725fcec84eaf211
[ "Apache-2.0" ]
null
null
null
src/Ets2/Save.hpp
TruckerMP/ETS2Sync-Helper-4
2a8b9df1d4db1e59635762147725fcec84eaf211
[ "Apache-2.0" ]
2
2019-05-10T14:13:53.000Z
2019-11-05T20:25:12.000Z
#pragma once #include "Object.hpp" #include "ObjectList.hpp" #include <string> #include <map> namespace Ets2 { class Save; typedef ObjectList<Save> SaveList; class Save : public Object { public: Save(const std::wstring directory); static const int DLC_SCANDINAVIA = 1 << 0; static const int DLC_GOINGEAST = 1 << 1; static const int DLC_HIGHPOWERCARGO = 1 << 2; static const int DLC_FRANCE = 1 << 3; static const int DLC_ALL = DLC_SCANDINAVIA | DLC_GOINGEAST | DLC_HIGHPOWERCARGO | DLC_FRANCE; struct Job { std::string cargo; int variant; std::string target; int urgency; int distance; int ferryTime; int ferryPrice; }; typedef std::map<std::string, std::vector<Job>> JobList; void setGame(Game game); int getDlcs() const; bool replaceJobList(const JobList& jobs, const std::function<bool(int progress)>& callback) const; private: static const std::wstring SII_BASENAME; static const std::wstring SAVE_BASENAME; static const std::string NAME_ATTRIBUTE; static const std::string SAVE_TIME_ATTRIBUTE; static const std::string DEPEND_ATTRIBUTE; static const std::wstring DEPEND_SCANDINAVIA; static const std::wstring DEPEND_GOINGEAST; static const std::wstring DEPEND_HIGHPOWERCARGO; static const std::wstring DEPEND_FRANCE; static const std::string ECONOMY_UNIT; static const std::string GAME_TIME_ATTRIBUTE; static const std::string COMPANY_UNIT; static const std::string JOB_UNIT; static const std::string COMPANY_NAME_PREFIX; int mDlcs; virtual void processAttribute(Parser::Sii::Context context, const std::string& attribute, const std::string& value) override; virtual bool validate() override; }; }
28.283333
127
0.741897
TruckerMP
ba3651cd61a10b478b51c85b5ca384a1b73d12a1
17,028
cpp
C++
src/1.4/dom/domAsset.cpp
maemo5/android-source-browsing.platform--external--collada
538700ec332c8306a1283f8dfdb016e493905e6f
[ "MIT" ]
null
null
null
src/1.4/dom/domAsset.cpp
maemo5/android-source-browsing.platform--external--collada
538700ec332c8306a1283f8dfdb016e493905e6f
[ "MIT" ]
null
null
null
src/1.4/dom/domAsset.cpp
maemo5/android-source-browsing.platform--external--collada
538700ec332c8306a1283f8dfdb016e493905e6f
[ "MIT" ]
null
null
null
/* * Copyright 2006 Sony Computer Entertainment Inc. * * Licensed under the MIT Open Source License, for details please see license.txt or the website * http://www.opensource.org/licenses/mit-license.php * */ #include <dae.h> #include <dae/daeDom.h> #include <dom/domAsset.h> #include <dae/daeMetaCMPolicy.h> #include <dae/daeMetaSequence.h> #include <dae/daeMetaChoice.h> #include <dae/daeMetaGroup.h> #include <dae/daeMetaAny.h> #include <dae/daeMetaElementAttribute.h> daeElementRef domAsset::create(DAE& dae) { domAssetRef ref = new domAsset(dae); return ref; } daeMetaElement * domAsset::registerElement(DAE& dae) { daeMetaElement* meta = dae.getMeta(ID()); if ( meta != NULL ) return meta; meta = new daeMetaElement(dae); dae.setMeta(ID(), *meta); meta->setName( "asset" ); meta->registerClass(domAsset::create); daeMetaCMPolicy *cm = NULL; daeMetaElementAttribute *mea = NULL; cm = new daeMetaSequence( meta, cm, 0, 1, 1 ); mea = new daeMetaElementArrayAttribute( meta, cm, 0, 0, -1 ); mea->setName( "contributor" ); mea->setOffset( daeOffsetOf(domAsset,elemContributor_array) ); mea->setElementType( domAsset::domContributor::registerElement(dae) ); cm->appendChild( mea ); mea = new daeMetaElementAttribute( meta, cm, 1, 1, 1 ); mea->setName( "created" ); mea->setOffset( daeOffsetOf(domAsset,elemCreated) ); mea->setElementType( domAsset::domCreated::registerElement(dae) ); cm->appendChild( mea ); mea = new daeMetaElementAttribute( meta, cm, 2, 0, 1 ); mea->setName( "keywords" ); mea->setOffset( daeOffsetOf(domAsset,elemKeywords) ); mea->setElementType( domAsset::domKeywords::registerElement(dae) ); cm->appendChild( mea ); mea = new daeMetaElementAttribute( meta, cm, 3, 1, 1 ); mea->setName( "modified" ); mea->setOffset( daeOffsetOf(domAsset,elemModified) ); mea->setElementType( domAsset::domModified::registerElement(dae) ); cm->appendChild( mea ); mea = new daeMetaElementAttribute( meta, cm, 4, 0, 1 ); mea->setName( "revision" ); mea->setOffset( daeOffsetOf(domAsset,elemRevision) ); mea->setElementType( domAsset::domRevision::registerElement(dae) ); cm->appendChild( mea ); mea = new daeMetaElementAttribute( meta, cm, 5, 0, 1 ); mea->setName( "subject" ); mea->setOffset( daeOffsetOf(domAsset,elemSubject) ); mea->setElementType( domAsset::domSubject::registerElement(dae) ); cm->appendChild( mea ); mea = new daeMetaElementAttribute( meta, cm, 6, 0, 1 ); mea->setName( "title" ); mea->setOffset( daeOffsetOf(domAsset,elemTitle) ); mea->setElementType( domAsset::domTitle::registerElement(dae) ); cm->appendChild( mea ); mea = new daeMetaElementAttribute( meta, cm, 7, 0, 1 ); mea->setName( "unit" ); mea->setOffset( daeOffsetOf(domAsset,elemUnit) ); mea->setElementType( domAsset::domUnit::registerElement(dae) ); cm->appendChild( mea ); mea = new daeMetaElementAttribute( meta, cm, 8, 0, 1 ); mea->setName( "up_axis" ); mea->setOffset( daeOffsetOf(domAsset,elemUp_axis) ); mea->setElementType( domAsset::domUp_axis::registerElement(dae) ); cm->appendChild( mea ); cm->setMaxOrdinal( 8 ); meta->setCMRoot( cm ); meta->setElementSize(sizeof(domAsset)); meta->validate(); return meta; } daeElementRef domAsset::domContributor::create(DAE& dae) { domAsset::domContributorRef ref = new domAsset::domContributor(dae); return ref; } daeMetaElement * domAsset::domContributor::registerElement(DAE& dae) { daeMetaElement* meta = dae.getMeta(ID()); if ( meta != NULL ) return meta; meta = new daeMetaElement(dae); dae.setMeta(ID(), *meta); meta->setName( "contributor" ); meta->registerClass(domAsset::domContributor::create); meta->setIsInnerClass( true ); daeMetaCMPolicy *cm = NULL; daeMetaElementAttribute *mea = NULL; cm = new daeMetaSequence( meta, cm, 0, 1, 1 ); mea = new daeMetaElementAttribute( meta, cm, 0, 0, 1 ); mea->setName( "author" ); mea->setOffset( daeOffsetOf(domAsset::domContributor,elemAuthor) ); mea->setElementType( domAsset::domContributor::domAuthor::registerElement(dae) ); cm->appendChild( mea ); mea = new daeMetaElementAttribute( meta, cm, 1, 0, 1 ); mea->setName( "authoring_tool" ); mea->setOffset( daeOffsetOf(domAsset::domContributor,elemAuthoring_tool) ); mea->setElementType( domAsset::domContributor::domAuthoring_tool::registerElement(dae) ); cm->appendChild( mea ); mea = new daeMetaElementAttribute( meta, cm, 2, 0, 1 ); mea->setName( "comments" ); mea->setOffset( daeOffsetOf(domAsset::domContributor,elemComments) ); mea->setElementType( domAsset::domContributor::domComments::registerElement(dae) ); cm->appendChild( mea ); mea = new daeMetaElementAttribute( meta, cm, 3, 0, 1 ); mea->setName( "copyright" ); mea->setOffset( daeOffsetOf(domAsset::domContributor,elemCopyright) ); mea->setElementType( domAsset::domContributor::domCopyright::registerElement(dae) ); cm->appendChild( mea ); mea = new daeMetaElementAttribute( meta, cm, 4, 0, 1 ); mea->setName( "source_data" ); mea->setOffset( daeOffsetOf(domAsset::domContributor,elemSource_data) ); mea->setElementType( domAsset::domContributor::domSource_data::registerElement(dae) ); cm->appendChild( mea ); cm->setMaxOrdinal( 4 ); meta->setCMRoot( cm ); meta->setElementSize(sizeof(domAsset::domContributor)); meta->validate(); return meta; } daeElementRef domAsset::domContributor::domAuthor::create(DAE& dae) { domAsset::domContributor::domAuthorRef ref = new domAsset::domContributor::domAuthor(dae); return ref; } daeMetaElement * domAsset::domContributor::domAuthor::registerElement(DAE& dae) { daeMetaElement* meta = dae.getMeta(ID()); if ( meta != NULL ) return meta; meta = new daeMetaElement(dae); dae.setMeta(ID(), *meta); meta->setName( "author" ); meta->registerClass(domAsset::domContributor::domAuthor::create); meta->setIsInnerClass( true ); // Add attribute: _value { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "_value" ); ma->setType( dae.getAtomicTypes().get("xsString")); ma->setOffset( daeOffsetOf( domAsset::domContributor::domAuthor , _value )); ma->setContainer( meta ); meta->appendAttribute(ma); } meta->setElementSize(sizeof(domAsset::domContributor::domAuthor)); meta->validate(); return meta; } daeElementRef domAsset::domContributor::domAuthoring_tool::create(DAE& dae) { domAsset::domContributor::domAuthoring_toolRef ref = new domAsset::domContributor::domAuthoring_tool(dae); return ref; } daeMetaElement * domAsset::domContributor::domAuthoring_tool::registerElement(DAE& dae) { daeMetaElement* meta = dae.getMeta(ID()); if ( meta != NULL ) return meta; meta = new daeMetaElement(dae); dae.setMeta(ID(), *meta); meta->setName( "authoring_tool" ); meta->registerClass(domAsset::domContributor::domAuthoring_tool::create); meta->setIsInnerClass( true ); // Add attribute: _value { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "_value" ); ma->setType( dae.getAtomicTypes().get("xsString")); ma->setOffset( daeOffsetOf( domAsset::domContributor::domAuthoring_tool , _value )); ma->setContainer( meta ); meta->appendAttribute(ma); } meta->setElementSize(sizeof(domAsset::domContributor::domAuthoring_tool)); meta->validate(); return meta; } daeElementRef domAsset::domContributor::domComments::create(DAE& dae) { domAsset::domContributor::domCommentsRef ref = new domAsset::domContributor::domComments(dae); return ref; } daeMetaElement * domAsset::domContributor::domComments::registerElement(DAE& dae) { daeMetaElement* meta = dae.getMeta(ID()); if ( meta != NULL ) return meta; meta = new daeMetaElement(dae); dae.setMeta(ID(), *meta); meta->setName( "comments" ); meta->registerClass(domAsset::domContributor::domComments::create); meta->setIsInnerClass( true ); // Add attribute: _value { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "_value" ); ma->setType( dae.getAtomicTypes().get("xsString")); ma->setOffset( daeOffsetOf( domAsset::domContributor::domComments , _value )); ma->setContainer( meta ); meta->appendAttribute(ma); } meta->setElementSize(sizeof(domAsset::domContributor::domComments)); meta->validate(); return meta; } daeElementRef domAsset::domContributor::domCopyright::create(DAE& dae) { domAsset::domContributor::domCopyrightRef ref = new domAsset::domContributor::domCopyright(dae); return ref; } daeMetaElement * domAsset::domContributor::domCopyright::registerElement(DAE& dae) { daeMetaElement* meta = dae.getMeta(ID()); if ( meta != NULL ) return meta; meta = new daeMetaElement(dae); dae.setMeta(ID(), *meta); meta->setName( "copyright" ); meta->registerClass(domAsset::domContributor::domCopyright::create); meta->setIsInnerClass( true ); // Add attribute: _value { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "_value" ); ma->setType( dae.getAtomicTypes().get("xsString")); ma->setOffset( daeOffsetOf( domAsset::domContributor::domCopyright , _value )); ma->setContainer( meta ); meta->appendAttribute(ma); } meta->setElementSize(sizeof(domAsset::domContributor::domCopyright)); meta->validate(); return meta; } daeElementRef domAsset::domContributor::domSource_data::create(DAE& dae) { domAsset::domContributor::domSource_dataRef ref = new domAsset::domContributor::domSource_data(dae); return ref; } daeMetaElement * domAsset::domContributor::domSource_data::registerElement(DAE& dae) { daeMetaElement* meta = dae.getMeta(ID()); if ( meta != NULL ) return meta; meta = new daeMetaElement(dae); dae.setMeta(ID(), *meta); meta->setName( "source_data" ); meta->registerClass(domAsset::domContributor::domSource_data::create); meta->setIsInnerClass( true ); // Add attribute: _value { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "_value" ); ma->setType( dae.getAtomicTypes().get("xsAnyURI")); ma->setOffset( daeOffsetOf( domAsset::domContributor::domSource_data , _value )); ma->setContainer( meta ); meta->appendAttribute(ma); } meta->setElementSize(sizeof(domAsset::domContributor::domSource_data)); meta->validate(); return meta; } daeElementRef domAsset::domCreated::create(DAE& dae) { domAsset::domCreatedRef ref = new domAsset::domCreated(dae); return ref; } daeMetaElement * domAsset::domCreated::registerElement(DAE& dae) { daeMetaElement* meta = dae.getMeta(ID()); if ( meta != NULL ) return meta; meta = new daeMetaElement(dae); dae.setMeta(ID(), *meta); meta->setName( "created" ); meta->registerClass(domAsset::domCreated::create); meta->setIsInnerClass( true ); // Add attribute: _value { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "_value" ); ma->setType( dae.getAtomicTypes().get("xsDateTime")); ma->setOffset( daeOffsetOf( domAsset::domCreated , _value )); ma->setContainer( meta ); meta->appendAttribute(ma); } meta->setElementSize(sizeof(domAsset::domCreated)); meta->validate(); return meta; } daeElementRef domAsset::domKeywords::create(DAE& dae) { domAsset::domKeywordsRef ref = new domAsset::domKeywords(dae); return ref; } daeMetaElement * domAsset::domKeywords::registerElement(DAE& dae) { daeMetaElement* meta = dae.getMeta(ID()); if ( meta != NULL ) return meta; meta = new daeMetaElement(dae); dae.setMeta(ID(), *meta); meta->setName( "keywords" ); meta->registerClass(domAsset::domKeywords::create); meta->setIsInnerClass( true ); // Add attribute: _value { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "_value" ); ma->setType( dae.getAtomicTypes().get("xsString")); ma->setOffset( daeOffsetOf( domAsset::domKeywords , _value )); ma->setContainer( meta ); meta->appendAttribute(ma); } meta->setElementSize(sizeof(domAsset::domKeywords)); meta->validate(); return meta; } daeElementRef domAsset::domModified::create(DAE& dae) { domAsset::domModifiedRef ref = new domAsset::domModified(dae); return ref; } daeMetaElement * domAsset::domModified::registerElement(DAE& dae) { daeMetaElement* meta = dae.getMeta(ID()); if ( meta != NULL ) return meta; meta = new daeMetaElement(dae); dae.setMeta(ID(), *meta); meta->setName( "modified" ); meta->registerClass(domAsset::domModified::create); meta->setIsInnerClass( true ); // Add attribute: _value { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "_value" ); ma->setType( dae.getAtomicTypes().get("xsDateTime")); ma->setOffset( daeOffsetOf( domAsset::domModified , _value )); ma->setContainer( meta ); meta->appendAttribute(ma); } meta->setElementSize(sizeof(domAsset::domModified)); meta->validate(); return meta; } daeElementRef domAsset::domRevision::create(DAE& dae) { domAsset::domRevisionRef ref = new domAsset::domRevision(dae); return ref; } daeMetaElement * domAsset::domRevision::registerElement(DAE& dae) { daeMetaElement* meta = dae.getMeta(ID()); if ( meta != NULL ) return meta; meta = new daeMetaElement(dae); dae.setMeta(ID(), *meta); meta->setName( "revision" ); meta->registerClass(domAsset::domRevision::create); meta->setIsInnerClass( true ); // Add attribute: _value { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "_value" ); ma->setType( dae.getAtomicTypes().get("xsString")); ma->setOffset( daeOffsetOf( domAsset::domRevision , _value )); ma->setContainer( meta ); meta->appendAttribute(ma); } meta->setElementSize(sizeof(domAsset::domRevision)); meta->validate(); return meta; } daeElementRef domAsset::domSubject::create(DAE& dae) { domAsset::domSubjectRef ref = new domAsset::domSubject(dae); return ref; } daeMetaElement * domAsset::domSubject::registerElement(DAE& dae) { daeMetaElement* meta = dae.getMeta(ID()); if ( meta != NULL ) return meta; meta = new daeMetaElement(dae); dae.setMeta(ID(), *meta); meta->setName( "subject" ); meta->registerClass(domAsset::domSubject::create); meta->setIsInnerClass( true ); // Add attribute: _value { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "_value" ); ma->setType( dae.getAtomicTypes().get("xsString")); ma->setOffset( daeOffsetOf( domAsset::domSubject , _value )); ma->setContainer( meta ); meta->appendAttribute(ma); } meta->setElementSize(sizeof(domAsset::domSubject)); meta->validate(); return meta; } daeElementRef domAsset::domTitle::create(DAE& dae) { domAsset::domTitleRef ref = new domAsset::domTitle(dae); return ref; } daeMetaElement * domAsset::domTitle::registerElement(DAE& dae) { daeMetaElement* meta = dae.getMeta(ID()); if ( meta != NULL ) return meta; meta = new daeMetaElement(dae); dae.setMeta(ID(), *meta); meta->setName( "title" ); meta->registerClass(domAsset::domTitle::create); meta->setIsInnerClass( true ); // Add attribute: _value { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "_value" ); ma->setType( dae.getAtomicTypes().get("xsString")); ma->setOffset( daeOffsetOf( domAsset::domTitle , _value )); ma->setContainer( meta ); meta->appendAttribute(ma); } meta->setElementSize(sizeof(domAsset::domTitle)); meta->validate(); return meta; } daeElementRef domAsset::domUnit::create(DAE& dae) { domAsset::domUnitRef ref = new domAsset::domUnit(dae); return ref; } daeMetaElement * domAsset::domUnit::registerElement(DAE& dae) { daeMetaElement* meta = dae.getMeta(ID()); if ( meta != NULL ) return meta; meta = new daeMetaElement(dae); dae.setMeta(ID(), *meta); meta->setName( "unit" ); meta->registerClass(domAsset::domUnit::create); meta->setIsInnerClass( true ); // Add attribute: meter { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "meter" ); ma->setType( dae.getAtomicTypes().get("Float")); ma->setOffset( daeOffsetOf( domAsset::domUnit , attrMeter )); ma->setContainer( meta ); ma->setDefaultString( "1.0"); meta->appendAttribute(ma); } // Add attribute: name { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "name" ); ma->setType( dae.getAtomicTypes().get("xsNMTOKEN")); ma->setOffset( daeOffsetOf( domAsset::domUnit , attrName )); ma->setContainer( meta ); ma->setDefaultString( "meter"); meta->appendAttribute(ma); } meta->setElementSize(sizeof(domAsset::domUnit)); meta->validate(); return meta; } daeElementRef domAsset::domUp_axis::create(DAE& dae) { domAsset::domUp_axisRef ref = new domAsset::domUp_axis(dae); return ref; } daeMetaElement * domAsset::domUp_axis::registerElement(DAE& dae) { daeMetaElement* meta = dae.getMeta(ID()); if ( meta != NULL ) return meta; meta = new daeMetaElement(dae); dae.setMeta(ID(), *meta); meta->setName( "up_axis" ); meta->registerClass(domAsset::domUp_axis::create); meta->setIsInnerClass( true ); // Add attribute: _value { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "_value" ); ma->setType( dae.getAtomicTypes().get("UpAxisType")); ma->setOffset( daeOffsetOf( domAsset::domUp_axis , _value )); ma->setContainer( meta ); meta->appendAttribute(ma); } meta->setElementSize(sizeof(domAsset::domUp_axis)); meta->validate(); return meta; }
26.156682
107
0.715821
maemo5
ba3686cdac9c33a43881ea3578523eb1d7747cc6
376
cpp
C++
Tests/Test_6_Input/scripts/A.cpp
TonyDecvA180XN/Cmple
a49a8ed466ac2ef10fd7006074c160859ca52a15
[ "MIT" ]
23
2021-09-06T20:28:30.000Z
2022-01-08T08:56:03.000Z
Tests/Test_6_Input/scripts/A.cpp
TonyDecvA180XN/Cmple
a49a8ed466ac2ef10fd7006074c160859ca52a15
[ "MIT" ]
null
null
null
Tests/Test_6_Input/scripts/A.cpp
TonyDecvA180XN/Cmple
a49a8ed466ac2ef10fd7006074c160859ca52a15
[ "MIT" ]
null
null
null
B b[10]; bool flag = false; Create { for (int i = 0; i < 10; i++) { b[i] = create_object_B(); for (int j = 0; j < 10; j++) { b[i]&x[j] = i * j; } } } Destroy { } Update { if (!flag) { flag = true; for (int i = 0; i < 10; i++) { destroy_object_B(b[i]); } } } Draw3D { } Draw2D { }
11.393939
38
0.369681
TonyDecvA180XN
ba3904a36b4b21b37a220a260b0764ad4abad790
397
cpp
C++
leetcode/326_Power_of_Three.cpp
longztian/cpp
59203f41162f40a46badf69093d287250e5cbab6
[ "MIT" ]
null
null
null
leetcode/326_Power_of_Three.cpp
longztian/cpp
59203f41162f40a46badf69093d287250e5cbab6
[ "MIT" ]
null
null
null
leetcode/326_Power_of_Three.cpp
longztian/cpp
59203f41162f40a46badf69093d287250e5cbab6
[ "MIT" ]
null
null
null
class Solution { public: bool isPowerOfThree(int n) { /* if ( n <= 3 ) return n == 3 || n == 1; while( n > 3 ) { if( n % 3 ) return false; n /= 3; } return n == 3 || n == 1; */ int max = pow(3, static_cast<int>(log(numeric_limits<int>::max()) / log(3))); return n > 0 && max % n == 0; } };
19.85
85
0.38539
longztian
ba39dd5e3808f0f2f73153301a3cb835f21ebc56
35,424
cpp
C++
Code/Engine/RendererDX11/Context/Implementation/ContextDX11.cpp
fereeh/ezEngine
14e46cb2a1492812888602796db7ddd66e2b7110
[ "MIT" ]
1
2021-06-23T14:44:02.000Z
2021-06-23T14:44:02.000Z
Code/Engine/RendererDX11/Context/Implementation/ContextDX11.cpp
fereeh/ezEngine
14e46cb2a1492812888602796db7ddd66e2b7110
[ "MIT" ]
null
null
null
Code/Engine/RendererDX11/Context/Implementation/ContextDX11.cpp
fereeh/ezEngine
14e46cb2a1492812888602796db7ddd66e2b7110
[ "MIT" ]
null
null
null
#include <RendererDX11PCH.h> #include <RendererDX11/Context/ContextDX11.h> #include <RendererDX11/Device/DeviceDX11.h> #include <RendererDX11/Resources/BufferDX11.h> #include <RendererDX11/Resources/FenceDX11.h> #include <RendererDX11/Resources/QueryDX11.h> #include <RendererDX11/Resources/RenderTargetViewDX11.h> #include <RendererDX11/Resources/ResourceViewDX11.h> #include <RendererDX11/Resources/TextureDX11.h> #include <RendererDX11/Resources/UnorderedAccessViewDX11.h> #include <RendererDX11/Shader/ShaderDX11.h> #include <RendererDX11/Shader/VertexDeclarationDX11.h> #include <RendererDX11/State/StateDX11.h> #include <d3d11_1.h> ezGALContextDX11::ezGALContextDX11(ezGALDevice* pDevice, ID3D11DeviceContext* pDXContext) : ezGALContext(pDevice) , m_pDXContext(pDXContext) , m_pDXAnnotation(nullptr) , m_pBoundDepthStencilTarget(nullptr) , m_uiBoundRenderTargetCount(0) { EZ_ASSERT_RELEASE(m_pDXContext != nullptr, "Invalid DX context!"); if (FAILED(m_pDXContext->QueryInterface(__uuidof(ID3DUserDefinedAnnotation), (void**)&m_pDXAnnotation))) { ezLog::Warning("Failed to get annotation interface. GALContext marker will not work"); } for (ezUInt32 i = 0; i < EZ_GAL_MAX_RENDERTARGET_COUNT; i++) { m_pBoundRenderTargets[i] = nullptr; } for (ezUInt32 i = 0; i < EZ_GAL_MAX_VERTEX_BUFFER_COUNT; i++) { m_pBoundVertexBuffers[i] = nullptr; m_VertexBufferOffsets[i] = 0; m_VertexBufferStrides[i] = 0; } m_BoundVertexBuffersRange.Reset(); for (ezUInt32 i = 0; i < EZ_GAL_MAX_CONSTANT_BUFFER_COUNT; i++) { m_pBoundConstantBuffers[i] = nullptr; } for (ezUInt32 s = 0; s < ezGALShaderStage::ENUM_COUNT; s++) { for (ezUInt32 i = 0; i < EZ_GAL_MAX_SAMPLER_COUNT; i++) { m_pBoundSamplerStates[s][i] = nullptr; } m_BoundShaderResourceViewsRange[s].Reset(); m_BoundSamplerStatesRange[s].Reset(); m_BoundConstantBuffersRange[s].Reset(); m_pBoundShaders[s] = nullptr; } m_pBoundUnoderedAccessViewsRange.Reset(); } ezGALContextDX11::~ezGALContextDX11() { EZ_GAL_DX11_RELEASE(m_pDXContext); EZ_GAL_DX11_RELEASE(m_pDXAnnotation); } // Draw functions void ezGALContextDX11::ClearPlatform(const ezColor& ClearColor, ezUInt32 uiRenderTargetClearMask, bool bClearDepth, bool bClearStencil, float fDepthClear, ezUInt8 uiStencilClear) { for (ezUInt32 i = 0; i < m_uiBoundRenderTargetCount; i++) { if (uiRenderTargetClearMask & (1u << i) && m_pBoundRenderTargets[i]) { m_pDXContext->ClearRenderTargetView(m_pBoundRenderTargets[i], ClearColor.GetData()); } } if ((bClearDepth || bClearStencil) && m_pBoundDepthStencilTarget) { ezUInt32 uiClearFlags = bClearDepth ? D3D11_CLEAR_DEPTH : 0; uiClearFlags |= bClearStencil ? D3D11_CLEAR_STENCIL : 0; m_pDXContext->ClearDepthStencilView(m_pBoundDepthStencilTarget, uiClearFlags, fDepthClear, uiStencilClear); } } void ezGALContextDX11::ClearUnorderedAccessViewPlatform(const ezGALUnorderedAccessView* pUnorderedAccessView, ezVec4 clearValues) { const ezGALUnorderedAccessViewDX11* pUnorderedAccessViewDX11 = static_cast<const ezGALUnorderedAccessViewDX11*>(pUnorderedAccessView); m_pDXContext->ClearUnorderedAccessViewFloat(pUnorderedAccessViewDX11->GetDXResourceView(), &clearValues.x); } void ezGALContextDX11::ClearUnorderedAccessViewPlatform(const ezGALUnorderedAccessView* pUnorderedAccessView, ezVec4U32 clearValues) { const ezGALUnorderedAccessViewDX11* pUnorderedAccessViewDX11 = static_cast<const ezGALUnorderedAccessViewDX11*>(pUnorderedAccessView); m_pDXContext->ClearUnorderedAccessViewUint(pUnorderedAccessViewDX11->GetDXResourceView(), &clearValues.x); } void ezGALContextDX11::DrawPlatform(ezUInt32 uiVertexCount, ezUInt32 uiStartVertex) { FlushDeferredStateChanges(); m_pDXContext->Draw(uiVertexCount, uiStartVertex); } void ezGALContextDX11::DrawIndexedPlatform(ezUInt32 uiIndexCount, ezUInt32 uiStartIndex) { FlushDeferredStateChanges(); #if EZ_ENABLED(EZ_COMPILE_FOR_DEBUG) m_pDXContext->DrawIndexed(uiIndexCount, uiStartIndex, 0); // In debug builds, with a debugger attached, the engine will break on D3D errors // this can be very annoying when an error happens repeatedly // you can disable it at runtime, by using the debugger to set bChangeBreakPolicy to 'true', or dragging the // the instruction pointer into the if volatile bool bChangeBreakPolicy = false; if (bChangeBreakPolicy) { ezGALDeviceDX11* pDevice = static_cast<ezGALDeviceDX11*>(GetDevice()); if (pDevice->m_pDebug) { ID3D11InfoQueue* pInfoQueue = nullptr; if (SUCCEEDED(pDevice->m_pDebug->QueryInterface(__uuidof(ID3D11InfoQueue), (void**)&pInfoQueue))) { // modify these, if you want to keep certain things enabled static BOOL bBreakOnCorruption = FALSE; static BOOL bBreakOnError = FALSE; static BOOL bBreakOnWarning = FALSE; pInfoQueue->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_CORRUPTION, bBreakOnCorruption); pInfoQueue->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_ERROR, bBreakOnError); pInfoQueue->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_WARNING, bBreakOnWarning); } } } #else m_pDXContext->DrawIndexed(uiIndexCount, uiStartIndex, 0); #endif } void ezGALContextDX11::DrawIndexedInstancedPlatform(ezUInt32 uiIndexCountPerInstance, ezUInt32 uiInstanceCount, ezUInt32 uiStartIndex) { FlushDeferredStateChanges(); m_pDXContext->DrawIndexedInstanced(uiIndexCountPerInstance, uiInstanceCount, uiStartIndex, 0, 0); } void ezGALContextDX11::DrawIndexedInstancedIndirectPlatform(const ezGALBuffer* pIndirectArgumentBuffer, ezUInt32 uiArgumentOffsetInBytes) { FlushDeferredStateChanges(); m_pDXContext->DrawIndexedInstancedIndirect(static_cast<const ezGALBufferDX11*>(pIndirectArgumentBuffer)->GetDXBuffer(), uiArgumentOffsetInBytes); } void ezGALContextDX11::DrawInstancedPlatform(ezUInt32 uiVertexCountPerInstance, ezUInt32 uiInstanceCount, ezUInt32 uiStartVertex) { FlushDeferredStateChanges(); m_pDXContext->DrawInstanced(uiVertexCountPerInstance, uiInstanceCount, uiStartVertex, 0); } void ezGALContextDX11::DrawInstancedIndirectPlatform(const ezGALBuffer* pIndirectArgumentBuffer, ezUInt32 uiArgumentOffsetInBytes) { FlushDeferredStateChanges(); m_pDXContext->DrawInstancedIndirect(static_cast<const ezGALBufferDX11*>(pIndirectArgumentBuffer)->GetDXBuffer(), uiArgumentOffsetInBytes); } void ezGALContextDX11::DrawAutoPlatform() { FlushDeferredStateChanges(); m_pDXContext->DrawAuto(); } void ezGALContextDX11::BeginStreamOutPlatform() { FlushDeferredStateChanges(); } void ezGALContextDX11::EndStreamOutPlatform() { EZ_ASSERT_NOT_IMPLEMENTED; } static void SetShaderResources(ezGALShaderStage::Enum stage, ID3D11DeviceContext* pContext, ezUInt32 uiStartSlot, ezUInt32 uiNumSlots, ID3D11ShaderResourceView** pShaderResourceViews) { switch (stage) { case ezGALShaderStage::VertexShader: pContext->VSSetShaderResources(uiStartSlot, uiNumSlots, pShaderResourceViews); break; case ezGALShaderStage::HullShader: pContext->HSSetShaderResources(uiStartSlot, uiNumSlots, pShaderResourceViews); break; case ezGALShaderStage::DomainShader: pContext->DSSetShaderResources(uiStartSlot, uiNumSlots, pShaderResourceViews); break; case ezGALShaderStage::GeometryShader: pContext->GSSetShaderResources(uiStartSlot, uiNumSlots, pShaderResourceViews); break; case ezGALShaderStage::PixelShader: pContext->PSSetShaderResources(uiStartSlot, uiNumSlots, pShaderResourceViews); break; case ezGALShaderStage::ComputeShader: pContext->CSSetShaderResources(uiStartSlot, uiNumSlots, pShaderResourceViews); break; default: EZ_ASSERT_NOT_IMPLEMENTED; } } static void SetConstantBuffers(ezGALShaderStage::Enum stage, ID3D11DeviceContext* pContext, ezUInt32 uiStartSlot, ezUInt32 uiNumSlots, ID3D11Buffer** pConstantBuffers) { switch (stage) { case ezGALShaderStage::VertexShader: pContext->VSSetConstantBuffers(uiStartSlot, uiNumSlots, pConstantBuffers); break; case ezGALShaderStage::HullShader: pContext->HSSetConstantBuffers(uiStartSlot, uiNumSlots, pConstantBuffers); break; case ezGALShaderStage::DomainShader: pContext->DSSetConstantBuffers(uiStartSlot, uiNumSlots, pConstantBuffers); break; case ezGALShaderStage::GeometryShader: pContext->GSSetConstantBuffers(uiStartSlot, uiNumSlots, pConstantBuffers); break; case ezGALShaderStage::PixelShader: pContext->PSSetConstantBuffers(uiStartSlot, uiNumSlots, pConstantBuffers); break; case ezGALShaderStage::ComputeShader: pContext->CSSetConstantBuffers(uiStartSlot, uiNumSlots, pConstantBuffers); break; default: EZ_ASSERT_NOT_IMPLEMENTED; } } static void SetSamplers(ezGALShaderStage::Enum stage, ID3D11DeviceContext* pContext, ezUInt32 uiStartSlot, ezUInt32 uiNumSlots, ID3D11SamplerState** pSamplerStates) { switch (stage) { case ezGALShaderStage::VertexShader: pContext->VSSetSamplers(uiStartSlot, uiNumSlots, pSamplerStates); break; case ezGALShaderStage::HullShader: pContext->HSSetSamplers(uiStartSlot, uiNumSlots, pSamplerStates); break; case ezGALShaderStage::DomainShader: pContext->DSSetSamplers(uiStartSlot, uiNumSlots, pSamplerStates); break; case ezGALShaderStage::GeometryShader: pContext->GSSetSamplers(uiStartSlot, uiNumSlots, pSamplerStates); break; case ezGALShaderStage::PixelShader: pContext->PSSetSamplers(uiStartSlot, uiNumSlots, pSamplerStates); break; case ezGALShaderStage::ComputeShader: pContext->CSSetSamplers(uiStartSlot, uiNumSlots, pSamplerStates); break; default: EZ_ASSERT_NOT_IMPLEMENTED; } } // Some state changes are deferred so they can be updated faster void ezGALContextDX11::FlushDeferredStateChanges() { if (m_BoundVertexBuffersRange.IsValid()) { const ezUInt32 uiStartSlot = m_BoundVertexBuffersRange.m_uiMin; const ezUInt32 uiNumSlots = m_BoundVertexBuffersRange.GetCount(); m_pDXContext->IASetVertexBuffers(uiStartSlot, uiNumSlots, m_pBoundVertexBuffers + uiStartSlot, m_VertexBufferStrides + uiStartSlot, m_VertexBufferOffsets + uiStartSlot); m_BoundVertexBuffersRange.Reset(); } for (ezUInt32 stage = 0; stage < ezGALShaderStage::ENUM_COUNT; ++stage) { if (m_pBoundShaders[stage] != nullptr && m_BoundConstantBuffersRange[stage].IsValid()) { const ezUInt32 uiStartSlot = m_BoundConstantBuffersRange[stage].m_uiMin; const ezUInt32 uiNumSlots = m_BoundConstantBuffersRange[stage].GetCount(); SetConstantBuffers((ezGALShaderStage::Enum)stage, m_pDXContext, uiStartSlot, uiNumSlots, m_pBoundConstantBuffers + uiStartSlot); m_BoundConstantBuffersRange[stage].Reset(); } } // Do UAV bindings before SRV since UAV are outputs which need to be unbound before they are potentially rebound as SRV again. if (m_pBoundUnoderedAccessViewsRange.IsValid()) { const ezUInt32 uiStartSlot = m_pBoundUnoderedAccessViewsRange.m_uiMin; const ezUInt32 uiNumSlots = m_pBoundUnoderedAccessViewsRange.GetCount(); m_pDXContext->CSSetUnorderedAccessViews(uiStartSlot, uiNumSlots, m_pBoundUnoderedAccessViews.GetData() + uiStartSlot, nullptr); // Todo: Count reset. m_pBoundUnoderedAccessViewsRange.Reset(); } for (ezUInt32 stage = 0; stage < ezGALShaderStage::ENUM_COUNT; ++stage) { // Need to do bindings even on inactive shader stages since we might miss unbindings otherwise! if (m_BoundShaderResourceViewsRange[stage].IsValid()) { const ezUInt32 uiStartSlot = m_BoundShaderResourceViewsRange[stage].m_uiMin; const ezUInt32 uiNumSlots = m_BoundShaderResourceViewsRange[stage].GetCount(); SetShaderResources((ezGALShaderStage::Enum)stage, m_pDXContext, uiStartSlot, uiNumSlots, m_pBoundShaderResourceViews[stage].GetData() + uiStartSlot); m_BoundShaderResourceViewsRange[stage].Reset(); } // Don't need to unset sampler stages for unbound shader stages. if (m_pBoundShaders[stage] == nullptr) continue; if (m_BoundSamplerStatesRange[stage].IsValid()) { const ezUInt32 uiStartSlot = m_BoundSamplerStatesRange[stage].m_uiMin; const ezUInt32 uiNumSlots = m_BoundSamplerStatesRange[stage].GetCount(); SetSamplers((ezGALShaderStage::Enum)stage, m_pDXContext, uiStartSlot, uiNumSlots, m_pBoundSamplerStates[stage] + uiStartSlot); m_BoundSamplerStatesRange[stage].Reset(); } } } // Dispatch void ezGALContextDX11::DispatchPlatform(ezUInt32 uiThreadGroupCountX, ezUInt32 uiThreadGroupCountY, ezUInt32 uiThreadGroupCountZ) { FlushDeferredStateChanges(); m_pDXContext->Dispatch(uiThreadGroupCountX, uiThreadGroupCountY, uiThreadGroupCountZ); } void ezGALContextDX11::DispatchIndirectPlatform(const ezGALBuffer* pIndirectArgumentBuffer, ezUInt32 uiArgumentOffsetInBytes) { FlushDeferredStateChanges(); m_pDXContext->DispatchIndirect(static_cast<const ezGALBufferDX11*>(pIndirectArgumentBuffer)->GetDXBuffer(), uiArgumentOffsetInBytes); } // State setting functions void ezGALContextDX11::SetShaderPlatform(const ezGALShader* pShader) { ID3D11VertexShader* pVS = nullptr; ID3D11HullShader* pHS = nullptr; ID3D11DomainShader* pDS = nullptr; ID3D11GeometryShader* pGS = nullptr; ID3D11PixelShader* pPS = nullptr; ID3D11ComputeShader* pCS = nullptr; if (pShader != nullptr) { const ezGALShaderDX11* pDXShader = static_cast<const ezGALShaderDX11*>(pShader); pVS = pDXShader->GetDXVertexShader(); pHS = pDXShader->GetDXHullShader(); pDS = pDXShader->GetDXDomainShader(); pGS = pDXShader->GetDXGeometryShader(); pPS = pDXShader->GetDXPixelShader(); pCS = pDXShader->GetDXComputeShader(); } if (pVS != m_pBoundShaders[ezGALShaderStage::VertexShader]) { m_pDXContext->VSSetShader(pVS, nullptr, 0); m_pBoundShaders[ezGALShaderStage::VertexShader] = pVS; } if (pHS != m_pBoundShaders[ezGALShaderStage::HullShader]) { m_pDXContext->HSSetShader(pHS, nullptr, 0); m_pBoundShaders[ezGALShaderStage::HullShader] = pHS; } if (pDS != m_pBoundShaders[ezGALShaderStage::DomainShader]) { m_pDXContext->DSSetShader(pDS, nullptr, 0); m_pBoundShaders[ezGALShaderStage::DomainShader] = pDS; } if (pGS != m_pBoundShaders[ezGALShaderStage::GeometryShader]) { m_pDXContext->GSSetShader(pGS, nullptr, 0); m_pBoundShaders[ezGALShaderStage::GeometryShader] = pGS; } if (pPS != m_pBoundShaders[ezGALShaderStage::PixelShader]) { m_pDXContext->PSSetShader(pPS, nullptr, 0); m_pBoundShaders[ezGALShaderStage::PixelShader] = pPS; } if (pCS != m_pBoundShaders[ezGALShaderStage::ComputeShader]) { m_pDXContext->CSSetShader(pCS, nullptr, 0); m_pBoundShaders[ezGALShaderStage::ComputeShader] = pCS; } } void ezGALContextDX11::SetIndexBufferPlatform(const ezGALBuffer* pIndexBuffer) { if (pIndexBuffer != nullptr) { const ezGALBufferDX11* pDX11Buffer = static_cast<const ezGALBufferDX11*>(pIndexBuffer); m_pDXContext->IASetIndexBuffer(pDX11Buffer->GetDXBuffer(), pDX11Buffer->GetIndexFormat(), 0 /* \todo: Expose */); } else { m_pDXContext->IASetIndexBuffer(nullptr, DXGI_FORMAT_R16_UINT, 0); } } void ezGALContextDX11::SetVertexBufferPlatform(ezUInt32 uiSlot, const ezGALBuffer* pVertexBuffer) { EZ_ASSERT_DEV(uiSlot < EZ_GAL_MAX_VERTEX_BUFFER_COUNT, "Invalid slot index"); m_pBoundVertexBuffers[uiSlot] = pVertexBuffer != nullptr ? static_cast<const ezGALBufferDX11*>(pVertexBuffer)->GetDXBuffer() : nullptr; m_VertexBufferStrides[uiSlot] = pVertexBuffer != nullptr ? pVertexBuffer->GetDescription().m_uiStructSize : 0; m_BoundVertexBuffersRange.SetToIncludeValue(uiSlot); } void ezGALContextDX11::SetVertexDeclarationPlatform(const ezGALVertexDeclaration* pVertexDeclaration) { m_pDXContext->IASetInputLayout( pVertexDeclaration != nullptr ? static_cast<const ezGALVertexDeclarationDX11*>(pVertexDeclaration)->GetDXInputLayout() : nullptr); } static const D3D11_PRIMITIVE_TOPOLOGY GALTopologyToDX11[ezGALPrimitiveTopology::ENUM_COUNT] = { D3D11_PRIMITIVE_TOPOLOGY_POINTLIST, D3D11_PRIMITIVE_TOPOLOGY_LINELIST, D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST, }; void ezGALContextDX11::SetPrimitiveTopologyPlatform(ezGALPrimitiveTopology::Enum Topology) { m_pDXContext->IASetPrimitiveTopology(GALTopologyToDX11[Topology]); } void ezGALContextDX11::SetConstantBufferPlatform(ezUInt32 uiSlot, const ezGALBuffer* pBuffer) { /// \todo Check if the device supports the slot index? m_pBoundConstantBuffers[uiSlot] = pBuffer != nullptr ? static_cast<const ezGALBufferDX11*>(pBuffer)->GetDXBuffer() : nullptr; // The GAL doesn't care about stages for constant buffer, but we need to handle this internaly. for (ezUInt32 stage = 0; stage < ezGALShaderStage::ENUM_COUNT; ++stage) m_BoundConstantBuffersRange[stage].SetToIncludeValue(uiSlot); } void ezGALContextDX11::SetSamplerStatePlatform(ezGALShaderStage::Enum Stage, ezUInt32 uiSlot, const ezGALSamplerState* pSamplerState) { /// \todo Check if the device supports the stage / the slot index m_pBoundSamplerStates[Stage][uiSlot] = pSamplerState != nullptr ? static_cast<const ezGALSamplerStateDX11*>(pSamplerState)->GetDXSamplerState() : nullptr; m_BoundSamplerStatesRange[Stage].SetToIncludeValue(uiSlot); } void ezGALContextDX11::SetResourceViewPlatform(ezGALShaderStage::Enum Stage, ezUInt32 uiSlot, const ezGALResourceView* pResourceView) { auto& boundShaderResourceViews = m_pBoundShaderResourceViews[Stage]; boundShaderResourceViews.EnsureCount(uiSlot + 1); boundShaderResourceViews[uiSlot] = pResourceView != nullptr ? static_cast<const ezGALResourceViewDX11*>(pResourceView)->GetDXResourceView() : nullptr; m_BoundShaderResourceViewsRange[Stage].SetToIncludeValue(uiSlot); } void ezGALContextDX11::SetRenderTargetSetupPlatform(ezArrayPtr<const ezGALRenderTargetView*> pRenderTargetViews, const ezGALRenderTargetView* pDepthStencilView) { for (ezUInt32 i = 0; i < EZ_GAL_MAX_RENDERTARGET_COUNT; i++) { m_pBoundRenderTargets[i] = nullptr; } m_pBoundDepthStencilTarget = nullptr; if (!pRenderTargetViews.IsEmpty() || pDepthStencilView != nullptr) { for (ezUInt32 i = 0; i < pRenderTargetViews.GetCount(); i++) { if (pRenderTargetViews[i] != nullptr) { m_pBoundRenderTargets[i] = static_cast<const ezGALRenderTargetViewDX11*>(pRenderTargetViews[i])->GetRenderTargetView(); } } if (pDepthStencilView != nullptr) { m_pBoundDepthStencilTarget = static_cast<const ezGALRenderTargetViewDX11*>(pDepthStencilView)->GetDepthStencilView(); } // Bind rendertargets, bind max(new rt count, old rt count) to overwrite bound rts if new count < old count m_pDXContext->OMSetRenderTargets(ezMath::Max(pRenderTargetViews.GetCount(), m_uiBoundRenderTargetCount), m_pBoundRenderTargets, m_pBoundDepthStencilTarget); m_uiBoundRenderTargetCount = pRenderTargetViews.GetCount(); } else { m_pBoundDepthStencilTarget = nullptr; m_pDXContext->OMSetRenderTargets(0, nullptr, nullptr); m_uiBoundRenderTargetCount = 0; } } void ezGALContextDX11::SetUnorderedAccessViewPlatform(ezUInt32 uiSlot, const ezGALUnorderedAccessView* pUnorderedAccessView) { m_pBoundUnoderedAccessViews.EnsureCount(uiSlot + 1); m_pBoundUnoderedAccessViews[uiSlot] = pUnorderedAccessView != nullptr ? static_cast<const ezGALUnorderedAccessViewDX11*>(pUnorderedAccessView)->GetDXResourceView() : nullptr; m_pBoundUnoderedAccessViewsRange.SetToIncludeValue(uiSlot); } void ezGALContextDX11::SetBlendStatePlatform(const ezGALBlendState* pBlendState, const ezColor& BlendFactor, ezUInt32 uiSampleMask) { FLOAT BlendFactors[4] = {BlendFactor.r, BlendFactor.g, BlendFactor.b, BlendFactor.a}; m_pDXContext->OMSetBlendState(pBlendState != nullptr ? static_cast<const ezGALBlendStateDX11*>(pBlendState)->GetDXBlendState() : nullptr, BlendFactors, uiSampleMask); } void ezGALContextDX11::SetDepthStencilStatePlatform(const ezGALDepthStencilState* pDepthStencilState, ezUInt8 uiStencilRefValue) { m_pDXContext->OMSetDepthStencilState(pDepthStencilState != nullptr ? static_cast<const ezGALDepthStencilStateDX11*>(pDepthStencilState)->GetDXDepthStencilState() : nullptr, uiStencilRefValue); } void ezGALContextDX11::SetRasterizerStatePlatform(const ezGALRasterizerState* pRasterizerState) { m_pDXContext->RSSetState( pRasterizerState != nullptr ? static_cast<const ezGALRasterizerStateDX11*>(pRasterizerState)->GetDXRasterizerState() : nullptr); } void ezGALContextDX11::SetViewportPlatform(const ezRectFloat& rect, float fMinDepth, float fMaxDepth) { D3D11_VIEWPORT Viewport; Viewport.TopLeftX = rect.x; Viewport.TopLeftY = rect.y; Viewport.Width = rect.width; Viewport.Height = rect.height; Viewport.MinDepth = fMinDepth; Viewport.MaxDepth = fMaxDepth; m_pDXContext->RSSetViewports(1, &Viewport); } void ezGALContextDX11::SetScissorRectPlatform(const ezRectU32& rect) { D3D11_RECT ScissorRect; ScissorRect.left = rect.x; ScissorRect.top = rect.y; ScissorRect.right = rect.x + rect.width; ScissorRect.bottom = rect.y + rect.height; m_pDXContext->RSSetScissorRects(1, &ScissorRect); } void ezGALContextDX11::SetStreamOutBufferPlatform(ezUInt32 uiSlot, const ezGALBuffer* pBuffer, ezUInt32 uiOffset) { EZ_ASSERT_NOT_IMPLEMENTED; } // Fence & Query functions void ezGALContextDX11::InsertFencePlatform(const ezGALFence* pFence) { m_pDXContext->End(static_cast<const ezGALFenceDX11*>(pFence)->GetDXFence()); } bool ezGALContextDX11::IsFenceReachedPlatform(const ezGALFence* pFence) { BOOL data = FALSE; if (m_pDXContext->GetData(static_cast<const ezGALFenceDX11*>(pFence)->GetDXFence(), &data, sizeof(data), 0) == S_OK) { EZ_ASSERT_DEV(data == TRUE, "Implementation error"); return true; } return false; } void ezGALContextDX11::WaitForFencePlatform(const ezGALFence* pFence) { BOOL data = FALSE; while (m_pDXContext->GetData(static_cast<const ezGALFenceDX11*>(pFence)->GetDXFence(), &data, sizeof(data), 0) != S_OK) { ezThreadUtils::YieldTimeSlice(); } EZ_ASSERT_DEV(data == TRUE, "Implementation error"); } void ezGALContextDX11::BeginQueryPlatform(const ezGALQuery* pQuery) { m_pDXContext->Begin(static_cast<const ezGALQueryDX11*>(pQuery)->GetDXQuery()); } void ezGALContextDX11::EndQueryPlatform(const ezGALQuery* pQuery) { m_pDXContext->End(static_cast<const ezGALQueryDX11*>(pQuery)->GetDXQuery()); } ezResult ezGALContextDX11::GetQueryResultPlatform(const ezGALQuery* pQuery, ezUInt64& uiQueryResult) { return m_pDXContext->GetData(static_cast<const ezGALQueryDX11*>(pQuery)->GetDXQuery(), &uiQueryResult, sizeof(ezUInt64), D3D11_ASYNC_GETDATA_DONOTFLUSH) == S_FALSE ? EZ_FAILURE : EZ_SUCCESS; } void ezGALContextDX11::InsertTimestampPlatform(ezGALTimestampHandle hTimestamp) { ID3D11Query* pDXQuery = static_cast<ezGALDeviceDX11*>(GetDevice())->GetTimestamp(hTimestamp); m_pDXContext->End(pDXQuery); } // Resource update functions void ezGALContextDX11::CopyBufferPlatform(const ezGALBuffer* pDestination, const ezGALBuffer* pSource) { ID3D11Buffer* pDXDestination = static_cast<const ezGALBufferDX11*>(pDestination)->GetDXBuffer(); ID3D11Buffer* pDXSource = static_cast<const ezGALBufferDX11*>(pSource)->GetDXBuffer(); m_pDXContext->CopyResource(pDXDestination, pDXSource); } void ezGALContextDX11::CopyBufferRegionPlatform(const ezGALBuffer* pDestination, ezUInt32 uiDestOffset, const ezGALBuffer* pSource, ezUInt32 uiSourceOffset, ezUInt32 uiByteCount) { ID3D11Buffer* pDXDestination = static_cast<const ezGALBufferDX11*>(pDestination)->GetDXBuffer(); ID3D11Buffer* pDXSource = static_cast<const ezGALBufferDX11*>(pSource)->GetDXBuffer(); D3D11_BOX srcBox = {uiSourceOffset, 0, 0, uiSourceOffset + uiByteCount, 1, 1}; m_pDXContext->CopySubresourceRegion(pDXDestination, 0, uiDestOffset, 0, 0, pDXSource, 0, &srcBox); } void ezGALContextDX11::UpdateBufferPlatform(const ezGALBuffer* pDestination, ezUInt32 uiDestOffset, ezArrayPtr<const ezUInt8> pSourceData, ezGALUpdateMode::Enum updateMode) { EZ_CHECK_ALIGNMENT_16(pSourceData.GetPtr()); ID3D11Buffer* pDXDestination = static_cast<const ezGALBufferDX11*>(pDestination)->GetDXBuffer(); if (pDestination->GetDescription().m_BufferType == ezGALBufferType::ConstantBuffer) { EZ_ASSERT_DEV(uiDestOffset == 0 && pSourceData.GetCount() == pDestination->GetSize(), "Constant buffers can't be updated partially (and we don't check for DX11.1)!"); D3D11_MAPPED_SUBRESOURCE MapResult; if (SUCCEEDED(m_pDXContext->Map(pDXDestination, 0, D3D11_MAP_WRITE_DISCARD, 0, &MapResult))) { memcpy(MapResult.pData, pSourceData.GetPtr(), pSourceData.GetCount()); m_pDXContext->Unmap(pDXDestination, 0); } } else { if (updateMode == ezGALUpdateMode::CopyToTempStorage) { if (ID3D11Resource* pDXTempBuffer = static_cast<ezGALDeviceDX11*>(GetDevice())->FindTempBuffer(pSourceData.GetCount())) { D3D11_MAPPED_SUBRESOURCE MapResult; HRESULT hRes = m_pDXContext->Map(pDXTempBuffer, 0, D3D11_MAP_WRITE, 0, &MapResult); EZ_ASSERT_DEV(SUCCEEDED(hRes), "Implementation error"); memcpy(MapResult.pData, pSourceData.GetPtr(), pSourceData.GetCount()); m_pDXContext->Unmap(pDXTempBuffer, 0); D3D11_BOX srcBox = {0, 0, 0, pSourceData.GetCount(), 1, 1}; m_pDXContext->CopySubresourceRegion(pDXDestination, 0, uiDestOffset, 0, 0, pDXTempBuffer, 0, &srcBox); } else { EZ_REPORT_FAILURE("Could not find a temp buffer for update."); } } else { D3D11_MAP mapType = (updateMode == ezGALUpdateMode::Discard) ? D3D11_MAP_WRITE_DISCARD : D3D11_MAP_WRITE_NO_OVERWRITE; D3D11_MAPPED_SUBRESOURCE MapResult; if (SUCCEEDED(m_pDXContext->Map(pDXDestination, 0, mapType, 0, &MapResult))) { memcpy(ezMemoryUtils::AddByteOffset(MapResult.pData, uiDestOffset), pSourceData.GetPtr(), pSourceData.GetCount()); m_pDXContext->Unmap(pDXDestination, 0); } } } } void ezGALContextDX11::CopyTexturePlatform(const ezGALTexture* pDestination, const ezGALTexture* pSource) { ID3D11Resource* pDXDestination = static_cast<const ezGALTextureDX11*>(pDestination)->GetDXTexture(); ID3D11Resource* pDXSource = static_cast<const ezGALTextureDX11*>(pSource)->GetDXTexture(); m_pDXContext->CopyResource(pDXDestination, pDXSource); } void ezGALContextDX11::CopyTextureRegionPlatform(const ezGALTexture* pDestination, const ezGALTextureSubresource& DestinationSubResource, const ezVec3U32& DestinationPoint, const ezGALTexture* pSource, const ezGALTextureSubresource& SourceSubResource, const ezBoundingBoxu32& Box) { ID3D11Resource* pDXDestination = static_cast<const ezGALTextureDX11*>(pDestination)->GetDXTexture(); ID3D11Resource* pDXSource = static_cast<const ezGALTextureDX11*>(pSource)->GetDXTexture(); ezUInt32 dstSubResource = D3D11CalcSubresource(DestinationSubResource.m_uiMipLevel, DestinationSubResource.m_uiArraySlice, pDestination->GetDescription().m_uiMipLevelCount); ezUInt32 srcSubResource = D3D11CalcSubresource(SourceSubResource.m_uiMipLevel, SourceSubResource.m_uiArraySlice, pSource->GetDescription().m_uiMipLevelCount); D3D11_BOX srcBox = {Box.m_vMin.x, Box.m_vMin.y, Box.m_vMin.z, Box.m_vMax.x, Box.m_vMax.y, Box.m_vMax.z}; m_pDXContext->CopySubresourceRegion(pDXDestination, dstSubResource, DestinationPoint.x, DestinationPoint.y, DestinationPoint.z, pDXSource, srcSubResource, &srcBox); } void ezGALContextDX11::UpdateTexturePlatform(const ezGALTexture* pDestination, const ezGALTextureSubresource& DestinationSubResource, const ezBoundingBoxu32& DestinationBox, const ezGALSystemMemoryDescription& pSourceData) { ID3D11Resource* pDXDestination = static_cast<const ezGALTextureDX11*>(pDestination)->GetDXTexture(); ezUInt32 uiWidth = ezMath::Max(DestinationBox.m_vMax.x - DestinationBox.m_vMin.x, 1u); ezUInt32 uiHeight = ezMath::Max(DestinationBox.m_vMax.y - DestinationBox.m_vMin.y, 1u); ezUInt32 uiDepth = ezMath::Max(DestinationBox.m_vMax.z - DestinationBox.m_vMin.z, 1u); ezGALResourceFormat::Enum format = pDestination->GetDescription().m_Format; if (ID3D11Resource* pDXTempTexture = static_cast<ezGALDeviceDX11*>(GetDevice())->FindTempTexture(uiWidth, uiHeight, uiDepth, format)) { D3D11_MAPPED_SUBRESOURCE MapResult; HRESULT hRes = m_pDXContext->Map(pDXTempTexture, 0, D3D11_MAP_WRITE, 0, &MapResult); EZ_ASSERT_DEV(SUCCEEDED(hRes), "Implementation error"); ezUInt32 uiRowPitch = uiWidth * ezGALResourceFormat::GetBitsPerElement(format) / 8; ezUInt32 uiSlicePitch = uiRowPitch * uiHeight; EZ_ASSERT_DEV(pSourceData.m_uiRowPitch == uiRowPitch, "Invalid row pitch. Expected {0} got {1}", uiRowPitch, pSourceData.m_uiRowPitch); EZ_ASSERT_DEV(pSourceData.m_uiSlicePitch == 0 || pSourceData.m_uiSlicePitch == uiSlicePitch, "Invalid slice pitch. Expected {0} got {1}", uiSlicePitch, pSourceData.m_uiSlicePitch); memcpy(MapResult.pData, pSourceData.m_pData, uiSlicePitch * uiDepth); m_pDXContext->Unmap(pDXTempTexture, 0); ezUInt32 dstSubResource = D3D11CalcSubresource(DestinationSubResource.m_uiMipLevel, DestinationSubResource.m_uiArraySlice, pDestination->GetDescription().m_uiMipLevelCount); D3D11_BOX srcBox = {0, 0, 0, uiWidth, uiHeight, uiDepth}; m_pDXContext->CopySubresourceRegion(pDXDestination, dstSubResource, DestinationBox.m_vMin.x, DestinationBox.m_vMin.y, DestinationBox.m_vMin.z, pDXTempTexture, 0, &srcBox); } else { EZ_REPORT_FAILURE("Could not find a temp texture for update."); } } void ezGALContextDX11::ResolveTexturePlatform(const ezGALTexture* pDestination, const ezGALTextureSubresource& DestinationSubResource, const ezGALTexture* pSource, const ezGALTextureSubresource& SourceSubResource) { ID3D11Resource* pDXDestination = static_cast<const ezGALTextureDX11*>(pDestination)->GetDXTexture(); ID3D11Resource* pDXSource = static_cast<const ezGALTextureDX11*>(pSource)->GetDXTexture(); ezUInt32 dstSubResource = D3D11CalcSubresource(DestinationSubResource.m_uiMipLevel, DestinationSubResource.m_uiArraySlice, pDestination->GetDescription().m_uiMipLevelCount); ezUInt32 srcSubResource = D3D11CalcSubresource(SourceSubResource.m_uiMipLevel, SourceSubResource.m_uiArraySlice, pSource->GetDescription().m_uiMipLevelCount); DXGI_FORMAT DXFormat = static_cast<ezGALDeviceDX11*>(GetDevice()) ->GetFormatLookupTable() .GetFormatInfo(pDestination->GetDescription().m_Format) .m_eResourceViewType; m_pDXContext->ResolveSubresource(pDXDestination, dstSubResource, pDXSource, srcSubResource, DXFormat); } void ezGALContextDX11::ReadbackTexturePlatform(const ezGALTexture* pTexture) { const ezGALTextureDX11* pDXTexture = static_cast<const ezGALTextureDX11*>(pTexture); // MSAA textures (e.g. backbuffers) need to be converted to non MSAA versions const bool bMSAASourceTexture = pDXTexture->GetDescription().m_SampleCount != ezGALMSAASampleCount::None; EZ_ASSERT_DEV(pDXTexture->GetDXStagingTexture() != nullptr, "No staging resource available for read-back"); EZ_ASSERT_DEV(pDXTexture->GetDXTexture() != nullptr, "Texture object is invalid"); if (bMSAASourceTexture) { /// \todo Other mip levels etc? m_pDXContext->ResolveSubresource(pDXTexture->GetDXStagingTexture(), 0, pDXTexture->GetDXTexture(), 0, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB); } else { m_pDXContext->CopyResource(pDXTexture->GetDXStagingTexture(), pDXTexture->GetDXTexture()); } } void ezGALContextDX11::CopyTextureReadbackResultPlatform(const ezGALTexture* pTexture, const ezArrayPtr<ezGALSystemMemoryDescription>* pData) { const ezGALTextureDX11* pDXTexture = static_cast<const ezGALTextureDX11*>(pTexture); EZ_ASSERT_DEV(pDXTexture->GetDXStagingTexture() != nullptr, "No staging resource available for read-back"); D3D11_MAPPED_SUBRESOURCE Mapped; if (SUCCEEDED(m_pDXContext->Map(pDXTexture->GetDXStagingTexture(), 0, D3D11_MAP_READ, 0, &Mapped))) { if (Mapped.RowPitch == (*pData)[0].m_uiRowPitch) { const ezUInt32 uiMemorySize = ezGALResourceFormat::GetBitsPerElement(pDXTexture->GetDescription().m_Format) * pDXTexture->GetDescription().m_uiWidth * pDXTexture->GetDescription().m_uiHeight / 8; memcpy((*pData)[0].m_pData, Mapped.pData, uiMemorySize); } else { // Copy row by row for (ezUInt32 y = 0; y < pDXTexture->GetDescription().m_uiHeight; ++y) { const void* pSource = ezMemoryUtils::AddByteOffset(Mapped.pData, y * Mapped.RowPitch); void* pDest = ezMemoryUtils::AddByteOffset((*pData)[0].m_pData, y * (*pData)[0].m_uiRowPitch); memcpy(pDest, pSource, ezGALResourceFormat::GetBitsPerElement(pDXTexture->GetDescription().m_Format) * pDXTexture->GetDescription().m_uiWidth / 8); } } m_pDXContext->Unmap(pDXTexture->GetDXStagingTexture(), 0); } } void ezGALContextDX11::GenerateMipMapsPlatform(const ezGALResourceView* pResourceView) { const ezGALResourceViewDX11* pDXResourceView = static_cast<const ezGALResourceViewDX11*>(pResourceView); m_pDXContext->GenerateMips(pDXResourceView->GetDXResourceView()); } void ezGALContextDX11::FlushPlatform() { FlushDeferredStateChanges(); } // Debug helper functions void ezGALContextDX11::PushMarkerPlatform(const char* szMarker) { if (m_pDXAnnotation != nullptr) { ezStringWChar wsMarker(szMarker); m_pDXAnnotation->BeginEvent(wsMarker.GetData()); } } void ezGALContextDX11::PopMarkerPlatform() { if (m_pDXAnnotation != nullptr) { m_pDXAnnotation->EndEvent(); } } void ezGALContextDX11::InsertEventMarkerPlatform(const char* szMarker) { if (m_pDXAnnotation != nullptr) { ezStringWChar wsMarker(szMarker); m_pDXAnnotation->SetMarker(wsMarker.GetData()); } } EZ_STATICLINK_FILE(RendererDX11, RendererDX11_Context_Implementation_ContextDX11);
39.185841
140
0.744919
fereeh
ba3ea210342eeae39acff888a5b1dab668ab1339
27,710
cpp
C++
cppcache/src/ClientMetadataService.cpp
mivanac/geode-native
8b161cc9c212aa99f871a309ee97d41355df163f
[ "Apache-2.0" ]
null
null
null
cppcache/src/ClientMetadataService.cpp
mivanac/geode-native
8b161cc9c212aa99f871a309ee97d41355df163f
[ "Apache-2.0" ]
null
null
null
cppcache/src/ClientMetadataService.cpp
mivanac/geode-native
8b161cc9c212aa99f871a309ee97d41355df163f
[ "Apache-2.0" ]
null
null
null
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ClientMetadataService.hpp" #include <climits> #include <cstdlib> #include <boost/thread/lock_types.hpp> #include <geode/FixedPartitionResolver.hpp> #include "ClientMetadata.hpp" #include "TcrConnectionManager.hpp" #include "TcrMessage.hpp" #include "ThinClientPoolDM.hpp" #include "util/queue.hpp" namespace apache { namespace geode { namespace client { const BucketStatus::clock::time_point BucketStatus::m_noTimeout{}; const char* ClientMetadataService::NC_CMDSvcThread = "NC CMDSvcThread"; ClientMetadataService::ClientMetadataService(ThinClientPoolDM* pool) : m_run(false), m_pool(pool), m_cache(m_pool->getConnectionManager().getCacheImpl()), m_regionQueue(false), m_bucketWaitTimeout(m_cache->getDistributedSystem() .getSystemProperties() .bucketWaitTimeout()), m_appDomainContext(createAppDomainContext()) {} void ClientMetadataService::start() { m_run = true; if (m_appDomainContext) { m_thread = std::thread([this] { m_appDomainContext->run([&] { this->svc(); }); }); } else { m_thread = std::thread(&ClientMetadataService::svc, this); } } void ClientMetadataService::stop() { m_run = false; m_regionQueueCondition.notify_one(); m_thread.join(); } void ClientMetadataService::svc() { DistributedSystemImpl::setThreadName(NC_CMDSvcThread); LOGINFO("ClientMetadataService started for pool " + m_pool->getName()); while (m_run) { std::unique_lock<std::mutex> lock(m_regionQueueMutex); m_regionQueueCondition.wait( lock, [this] { return !m_run || !m_regionQueue.empty(); }); if (!m_run) { break; } auto regionFullPath = std::move(m_regionQueue.front()); m_regionQueue.pop_front(); queue::coalesce(m_regionQueue, regionFullPath); if (!m_cache->isCacheDestroyPending()) { lock.unlock(); getClientPRMetadata(regionFullPath.c_str()); } else { break; } } LOGINFO("ClientMetadataService stopped for pool " + m_pool->getName()); } void ClientMetadataService::getClientPRMetadata(const char* regionFullPath) { if (regionFullPath == nullptr) return; // That means metadata for the region not found, So only for the first time // for a particular region use GetClientPartitionAttributesOp // TcrMessage to fetch the metadata and put it into map for later use.send // this message to server and get metadata from server. TcrMessageReply reply(true, nullptr); std::string path(regionFullPath); std::shared_ptr<ClientMetadata> cptr = nullptr; { boost::shared_lock<decltype(m_regionMetadataLock)> lock( m_regionMetadataLock); const auto& itr = m_regionMetaDataMap.find(path); if (itr != m_regionMetaDataMap.end()) { cptr = itr->second; } } std::shared_ptr<ClientMetadata> newCptr = nullptr; if (cptr == nullptr) { TcrMessageGetClientPartitionAttributes request( new DataOutput(m_cache->createDataOutput(m_pool)), regionFullPath); GfErrType err = m_pool->sendSyncRequest(request, reply); if (err == GF_NOERR && reply.getMessageType() == TcrMessage::RESPONSE_CLIENT_PARTITION_ATTRIBUTES) { cptr = std::make_shared<ClientMetadata>(reply.getNumBuckets(), reply.getColocatedWith(), m_pool, reply.getFpaSet()); if (m_bucketWaitTimeout > std::chrono::milliseconds::zero() && reply.getNumBuckets() > 0) { boost::unique_lock<decltype(m_PRbucketStatusLock)> lock( m_PRbucketStatusLock); m_bucketStatus[regionFullPath] = std::unique_ptr<PRbuckets>(new PRbuckets(reply.getNumBuckets())); } LOGDEBUG("ClientMetadata buckets %d ", reply.getNumBuckets()); } } if (cptr == nullptr) { return; } auto&& colocatedWith = cptr->getColocatedWith(); if (colocatedWith.empty()) { newCptr = SendClientPRMetadata(regionFullPath, cptr); // now we will get new instance so assign it again if (newCptr != nullptr) { cptr->setPreviousone(nullptr); newCptr->setPreviousone(cptr); boost::unique_lock<decltype(m_regionMetadataLock)> lock( m_regionMetadataLock); m_regionMetaDataMap[path] = newCptr; LOGINFO("Updated client meta data"); } } else { newCptr = SendClientPRMetadata(colocatedWith.c_str(), cptr); if (newCptr) { cptr->setPreviousone(nullptr); newCptr->setPreviousone(cptr); // now we will get new instance so assign it again boost::unique_lock<decltype(m_regionMetadataLock)> lock( m_regionMetadataLock); m_regionMetaDataMap[colocatedWith.c_str()] = newCptr; m_regionMetaDataMap[path] = newCptr; LOGINFO("Updated client meta data"); } } } std::shared_ptr<ClientMetadata> ClientMetadataService::SendClientPRMetadata( const char* regionPath, std::shared_ptr<ClientMetadata> cptr) { TcrMessageGetClientPrMetadata request( new DataOutput(m_cache->createDataOutput(m_pool)), regionPath); TcrMessageReply reply(true, nullptr); // send this message to server and get metadata from server. LOGFINE("Now sending GET_CLIENT_PR_METADATA for getting from server: %s", regionPath); std::shared_ptr<Region> region = nullptr; GfErrType err = m_pool->sendSyncRequest(request, reply); if (err == GF_NOERR && reply.getMessageType() == TcrMessage::RESPONSE_CLIENT_PR_METADATA) { region = m_cache->getRegion(regionPath); if (region != nullptr) { if (auto lregion = std::dynamic_pointer_cast<LocalRegion>(region)) { lregion->getRegionStats()->incMetaDataRefreshCount(); } } auto metadata = reply.getMetadata(); if (metadata == nullptr) return nullptr; if (metadata->empty()) { delete metadata; return nullptr; } auto newCptr = std::make_shared<ClientMetadata>(*cptr); for (const auto& v : *metadata) { if (!v.empty()) { newCptr->updateBucketServerLocations(v.at(0)->getBucketId(), v); } } delete metadata; return newCptr; } return nullptr; } void ClientMetadataService::getBucketServerLocation( const std::shared_ptr<Region>& region, const std::shared_ptr<CacheableKey>& key, const std::shared_ptr<Cacheable>& value, const std::shared_ptr<Serializable>& aCallbackArgument, bool isPrimary, std::shared_ptr<BucketServerLocation>& serverLocation, int8_t& version) { if (region != nullptr) { boost::shared_lock<decltype(m_regionMetadataLock)> lock( m_regionMetadataLock); LOGDEBUG( "ClientMetadataService::getBucketServerLocation m_regionMetaDataMap " "size is %d", m_regionMetaDataMap.size()); std::string path(region->getFullPath()); std::shared_ptr<ClientMetadata> cptr = nullptr; const auto& itr = m_regionMetaDataMap.find(path); if (itr != m_regionMetaDataMap.end()) { cptr = itr->second; } if (!cptr) { return; } std::shared_ptr<CacheableKey> resolvekey; const auto& resolver = region->getAttributes().getPartitionResolver(); EntryEvent event(region, key, value, nullptr, aCallbackArgument, false); int bucketId = 0; if (resolver == nullptr) { resolvekey = key; } else { resolvekey = resolver->getRoutingObject(event); if (resolvekey == nullptr) { throw IllegalStateException( "The RoutingObject returned by PartitionResolver is null."); } } if (auto&& fpResolver = std::dynamic_pointer_cast<FixedPartitionResolver>(resolver)) { auto&& partition = fpResolver->getPartitionName(event); bucketId = cptr->assignFixedBucketId(partition.c_str(), resolvekey); if (bucketId == -1) { return; } } else { if (cptr->getTotalNumBuckets() > 0) { bucketId = std::abs(resolvekey->hashcode() % cptr->getTotalNumBuckets()); } } cptr->getServerLocation(bucketId, isPrimary, serverLocation, version); } } std::shared_ptr<ClientMetadata> ClientMetadataService::getClientMetadata( const std::string& regionFullPath) { boost::shared_lock<decltype(m_regionMetadataLock)> lock(m_regionMetadataLock); const auto& entry = m_regionMetaDataMap.find(regionFullPath); if (entry == m_regionMetaDataMap.end()) { return nullptr; } return entry->second; } std::shared_ptr<ClientMetadata> ClientMetadataService::getClientMetadata( const std::shared_ptr<Region>& region) { return getClientMetadata(region->getFullPath()); } void ClientMetadataService::enqueueForMetadataRefresh( const std::string& regionFullPath, int8_t serverGroupFlag) { auto region = m_cache->getRegion(regionFullPath); std::string serverGroup = m_pool->getServerGroup(); if (serverGroup.length() != 0) { m_cache->setServerGroupFlag(serverGroupFlag); if (serverGroupFlag == 2) { LOGFINER( "Network hop but, from within same server-group, so no metadata " "fetch from the server"); return; } } if (region != nullptr) { auto tcrRegion = dynamic_cast<ThinClientRegion*>(region.get()); { TryWriteGuard guardRegionMetaDataRefresh( tcrRegion->getMataDataMutex(), tcrRegion->getMetaDataRefreshed()); if (tcrRegion->getMetaDataRefreshed()) { return; } LOGFINE("Network hop so fetching single hop metadata from the server"); m_cache->setNetworkHopFlag(true); tcrRegion->setMetaDataRefreshed(true); { std::lock_guard<decltype(m_regionQueueMutex)> lock(m_regionQueueMutex); m_regionQueue.push_back(regionFullPath); } m_regionQueueCondition.notify_one(); } } } std::shared_ptr<ClientMetadataService::ServerToFilterMap> ClientMetadataService::getServerToFilterMap( const std::vector<std::shared_ptr<CacheableKey>>& keys, const std::shared_ptr<Region>& region, bool isPrimary) { auto clientMetadata = getClientMetadata(region); if (!clientMetadata) { return nullptr; } auto serverToFilterMap = std::make_shared<ServerToFilterMap>(); std::vector<std::shared_ptr<CacheableKey>> keysWhichLeft; std::map<int, std::shared_ptr<BucketServerLocation>> buckets; for (const auto& key : keys) { LOGDEBUG("cmds = %s", key->toString().c_str()); const auto resolver = region->getAttributes().getPartitionResolver(); std::shared_ptr<CacheableKey> resolveKey; if (resolver == nullptr) { // client has not registered PartitionResolver // Assuming even PR at server side is not using PartitionResolver resolveKey = key; } else { EntryEvent event(region, key, nullptr, nullptr, nullptr, false); resolveKey = resolver->getRoutingObject(event); } int bucketId = std::abs(resolveKey->hashcode() % clientMetadata->getTotalNumBuckets()); std::shared_ptr<std::vector<std::shared_ptr<CacheableKey>>> keyList = nullptr; const auto& bucketsIter = buckets.find(bucketId); if (bucketsIter == buckets.end()) { int8_t version = -1; // auto serverLocation = std::make_shared<BucketServerLocation>(); std::shared_ptr<BucketServerLocation> serverLocation = nullptr; clientMetadata->getServerLocation(bucketId, isPrimary, serverLocation, version); if (!(serverLocation && serverLocation->isValid())) { keysWhichLeft.push_back(key); continue; } buckets[bucketId] = serverLocation; const auto& itrRes = serverToFilterMap->find(serverLocation); if (itrRes == serverToFilterMap->end()) { keyList = std::make_shared<std::vector<std::shared_ptr<CacheableKey>>>(); serverToFilterMap->emplace(serverLocation, keyList); } else { keyList = itrRes->second; } LOGDEBUG("new keylist buckets =%d res = %d", buckets.size(), serverToFilterMap->size()); } else { keyList = (*serverToFilterMap)[bucketsIter->second]; } keyList->push_back(key); } if (!keysWhichLeft.empty() && !serverToFilterMap->empty()) { // add left keys in result auto keyLefts = keysWhichLeft.size(); auto totalServers = serverToFilterMap->size(); auto perServer = keyLefts / totalServers + 1; size_t keyIdx = 0; for (const auto& locationIter : *serverToFilterMap) { const auto values = locationIter.second; for (size_t i = 0; i < perServer; i++) { if (keyIdx < keyLefts) { values->push_back(keysWhichLeft.at(keyIdx++)); } else { break; } } if (keyIdx >= keyLefts) break; // done } } else if (serverToFilterMap->empty()) { // not be able to map any key return nullptr; // it will force all keys to send to one server } return serverToFilterMap; } void ClientMetadataService::markPrimaryBucketForTimeout( const std::shared_ptr<Region>& region, const std::shared_ptr<CacheableKey>& key, const std::shared_ptr<Cacheable>& value, const std::shared_ptr<Serializable>& aCallbackArgument, bool, std::shared_ptr<BucketServerLocation>& serverLocation, int8_t& version) { if (m_bucketWaitTimeout == std::chrono::milliseconds::zero()) return; boost::unique_lock<decltype(m_PRbucketStatusLock)> lock(m_PRbucketStatusLock); getBucketServerLocation(region, key, value, aCallbackArgument, false /*look for secondary host*/, serverLocation, version); if (serverLocation && serverLocation->isValid()) { LOGDEBUG("Server host and port are %s:%d", serverLocation->getServerName().c_str(), serverLocation->getPort()); int32_t bId = serverLocation->getBucketId(); const auto& bs = m_bucketStatus.find(region->getFullPath()); if (bs != m_bucketStatus.end()) { bs->second->setBucketTimeout(bId); LOGDEBUG("marking bucket %d as timeout ", bId); } } } std::shared_ptr<ClientMetadataService::BucketToKeysMap> ClientMetadataService::groupByBucketOnClientSide( const std::shared_ptr<Region>& region, const std::shared_ptr<CacheableVector>& keySet, const std::shared_ptr<ClientMetadata>& metadata) { auto bucketToKeysMap = std::make_shared<BucketToKeysMap>(); for (const auto& k : *keySet) { const auto key = std::dynamic_pointer_cast<CacheableKey>(k); const auto resolver = region->getAttributes().getPartitionResolver(); std::shared_ptr<CacheableKey> resolvekey; EntryEvent event(region, key, nullptr, nullptr, nullptr, false); int bucketId = -1; if (resolver) { resolvekey = resolver->getRoutingObject(event); if (!resolvekey) { throw IllegalStateException( "The RoutingObject returned by PartitionResolver is null."); } } else { resolvekey = key; } if (auto&& fpResolver = std::dynamic_pointer_cast<FixedPartitionResolver>(resolver)) { auto&& partition = fpResolver->getPartitionName(event); bucketId = metadata->assignFixedBucketId(partition.c_str(), resolvekey); if (bucketId == -1) { this->enqueueForMetadataRefresh(region->getFullPath(), 0); } } else { if (metadata->getTotalNumBuckets() > 0) { bucketId = std::abs(resolvekey->hashcode() % metadata->getTotalNumBuckets()); } } std::shared_ptr<CacheableHashSet> bucketKeys; const auto& iter = bucketToKeysMap->find(bucketId); if (iter == bucketToKeysMap->end()) { bucketKeys = CacheableHashSet::create(); bucketToKeysMap->emplace(bucketId, bucketKeys); } else { bucketKeys = iter->second; } bucketKeys->insert(key); } return bucketToKeysMap; } std::shared_ptr<ClientMetadataService::ServerToKeysMap> ClientMetadataService::getServerToFilterMapFESHOP( const std::shared_ptr<CacheableVector>& routingKeys, const std::shared_ptr<Region>& region, bool isPrimary) { auto cptr = getClientMetadata(region->getFullPath()); if (!cptr) { enqueueForMetadataRefresh(region->getFullPath(), 0); return nullptr; } if (!routingKeys) { return nullptr; } const auto bucketToKeysMap = groupByBucketOnClientSide(region, routingKeys, cptr); BucketSet bucketSet(bucketToKeysMap->size()); for (const auto& iter : *bucketToKeysMap) { bucketSet.insert(iter.first); } LOGDEBUG( "ClientMetadataService::getServerToFilterMapFESHOP: bucketSet size = %d ", bucketSet.size()); const auto serverToBuckets = groupByServerToBuckets(cptr, bucketSet, isPrimary); if (serverToBuckets == nullptr) { return nullptr; } auto serverToKeysMap = std::make_shared<ServerToKeysMap>(); for (const auto& serverToBucket : *serverToBuckets) { const auto& serverLocation = serverToBucket.first; const auto& buckets = serverToBucket.second; for (const auto& bucket : *buckets) { std::shared_ptr<CacheableHashSet> serverToKeysEntry; const auto& iter = serverToKeysMap->find(serverLocation); if (iter == serverToKeysMap->end()) { serverToKeysEntry = CacheableHashSet::create(); serverToKeysMap->emplace(serverLocation, serverToKeysEntry); } else { serverToKeysEntry = iter->second; } const auto& bucketToKeys = bucketToKeysMap->find(bucket); if (bucketToKeys != bucketToKeysMap->end()) { const auto& bucketKeys = bucketToKeys->second; serverToKeysEntry->insert(bucketKeys->begin(), bucketKeys->end()); } } } return serverToKeysMap; } std::shared_ptr<BucketServerLocation> ClientMetadataService::findNextServer( const ClientMetadataService::ServerToBucketsMap& serverToBucketsMap, const ClientMetadataService::BucketSet& currentBucketSet) { size_t max = 0; std::vector<std::shared_ptr<BucketServerLocation>> nodesOfEqualSize; for (const auto& serverToBucketEntry : serverToBucketsMap) { const auto& serverLocation = serverToBucketEntry.first; BucketSet buckets(*(serverToBucketEntry.second)); LOGDEBUG( "ClientMetadataService::findNextServer currentBucketSet->size() = %d " "bucketSet->size() = %d ", currentBucketSet.size(), buckets.size()); for (const auto& currentBucketSetIter : currentBucketSet) { buckets.erase(currentBucketSetIter); LOGDEBUG("ClientMetadataService::findNextServer bucketSet->size() = %d ", buckets.size()); } auto size = buckets.size(); if (max < size) { max = size; nodesOfEqualSize.clear(); nodesOfEqualSize.push_back(serverLocation); } else if (max == size) { nodesOfEqualSize.push_back(serverLocation); } } auto nodeSize = nodesOfEqualSize.size(); if (nodeSize > 0) { RandGen randgen; auto random = randgen(nodeSize); return nodesOfEqualSize.at(random); } return nullptr; } std::shared_ptr<ClientMetadataService::ServerToBucketsMap> ClientMetadataService::pruneNodes( const std::shared_ptr<ClientMetadata>& metadata, const BucketSet& buckets) { BucketSet bucketSetWithoutServer; ServerToBucketsMap serverToBucketsMap; auto prunedServerToBucketsMap = std::make_shared<ServerToBucketsMap>(); for (const auto& bucketId : buckets) { const auto locations = metadata->adviseServerLocations(bucketId); if (locations.size() == 0) { LOGDEBUG( "ClientMetadataService::pruneNodes Since no server location " "available for bucketId = %d putting it into " "bucketSetWithoutServer ", bucketId); bucketSetWithoutServer.insert(bucketId); continue; } for (const auto& location : locations) { std::shared_ptr<BucketSet> bucketSet; const auto& itrRes = serverToBucketsMap.find(location); if (itrRes == serverToBucketsMap.end()) { bucketSet = std::make_shared<BucketSet>(); serverToBucketsMap.emplace(location, bucketSet); } else { bucketSet = itrRes->second; } bucketSet->insert(bucketId); } } auto itrRes = serverToBucketsMap.begin(); std::shared_ptr<BucketServerLocation> randomFirstServer; if (serverToBucketsMap.empty()) { LOGDEBUG( "ClientMetadataService::pruneNodes serverToBucketsMap is empty so " "returning nullptr"); return nullptr; } else { size_t size = serverToBucketsMap.size(); LOGDEBUG( "ClientMetadataService::pruneNodes Total size of serverToBucketsMap = " "%d ", size); for (size_t idx = 0; idx < RandGen{}(size); idx++) { itrRes++; } randomFirstServer = itrRes->first; } const auto& itrRes1 = serverToBucketsMap.find(randomFirstServer); const auto bucketSet = itrRes1->second; BucketSet currentBucketSet(*bucketSet); prunedServerToBucketsMap->emplace(randomFirstServer, bucketSet); serverToBucketsMap.erase(randomFirstServer); while (buckets != currentBucketSet) { auto server = findNextServer(serverToBucketsMap, currentBucketSet); if (server == nullptr) { LOGDEBUG( "ClientMetadataService::pruneNodes findNextServer returned no " "server"); break; } const auto& bucketSet2 = serverToBucketsMap.find(server)->second; LOGDEBUG( "ClientMetadataService::pruneNodes currentBucketSet->size() = %d " "bucketSet2->size() = %d ", currentBucketSet.size(), bucketSet2->size()); for (const auto& currentBucketSetIter : currentBucketSet) { bucketSet2->erase(currentBucketSetIter); LOGDEBUG("ClientMetadataService::pruneNodes bucketSet2->size() = %d ", bucketSet2->size()); } if (bucketSet2->empty()) { LOGDEBUG( "ClientMetadataService::pruneNodes bucketSet2 is empty() so removing " "server from serverToBucketsMap"); serverToBucketsMap.erase(server); continue; } for (const auto& itr : *bucketSet2) { currentBucketSet.insert(itr); } prunedServerToBucketsMap->emplace(server, bucketSet2); serverToBucketsMap.erase(server); } const auto& itrRes2 = prunedServerToBucketsMap->begin(); for (const auto& itr : bucketSetWithoutServer) { itrRes2->second->insert(itr); } return prunedServerToBucketsMap; } std::shared_ptr<ClientMetadataService::ServerToBucketsMap> ClientMetadataService::groupByServerToAllBuckets( const std::shared_ptr<Region>& region, bool optimizeForWrite) { auto cptr = getClientMetadata(region->getFullPath()); if (cptr == nullptr) { enqueueForMetadataRefresh(region->getFullPath(), false); return nullptr; } int totalBuckets = cptr->getTotalNumBuckets(); BucketSet bucketSet(totalBuckets); for (int i = 0; i < totalBuckets; i++) { bucketSet.insert(i); } return groupByServerToBuckets(cptr, bucketSet, optimizeForWrite); } std::shared_ptr<ClientMetadataService::ServerToBucketsMap> ClientMetadataService::groupByServerToBuckets( const std::shared_ptr<ClientMetadata>& metadata, const BucketSet& bucketSet, bool optimizeForWrite) { if (optimizeForWrite) { auto serverToBucketsMap = std::make_shared<ServerToBucketsMap>(); BucketSet bucketsWithoutServer(bucketSet.size()); for (const auto& bucketId : bucketSet) { const auto serverLocation = metadata->advisePrimaryServerLocation(bucketId); if (serverLocation == nullptr) { bucketsWithoutServer.insert(bucketId); continue; } else if (!serverLocation->isValid()) { bucketsWithoutServer.insert(bucketId); continue; } std::shared_ptr<BucketSet> buckets; const auto& itrRes = serverToBucketsMap->find(serverLocation); if (itrRes == serverToBucketsMap->end()) { buckets = std::make_shared<BucketSet>(); serverToBucketsMap->emplace(serverLocation, buckets); } else { buckets = itrRes->second; } buckets->insert(bucketId); } if (!serverToBucketsMap->empty()) { const auto& itrRes = serverToBucketsMap->begin(); for (const auto& itr : bucketsWithoutServer) { itrRes->second->insert(itr); LOGDEBUG( "ClientMetadataService::groupByServerToBuckets inserting " "bucketsWithoutServer"); } } return serverToBucketsMap; } else { return pruneNodes(metadata, bucketSet); } } void ClientMetadataService::markPrimaryBucketForTimeoutButLookSecondaryBucket( const std::shared_ptr<Region>& region, const std::shared_ptr<CacheableKey>& key, const std::shared_ptr<Cacheable>& value, const std::shared_ptr<Serializable>& aCallbackArgument, bool, std::shared_ptr<BucketServerLocation>& serverLocation, int8_t& version) { if (m_bucketWaitTimeout == std::chrono::milliseconds::zero()) return; boost::unique_lock<decltype(m_PRbucketStatusLock)> lock(m_PRbucketStatusLock); PRbuckets* prBuckets = nullptr; const auto& bs = m_bucketStatus.find(region->getFullPath()); if (bs != m_bucketStatus.end()) { prBuckets = bs->second.get(); } if (prBuckets == nullptr) return; getBucketServerLocation(region, key, value, aCallbackArgument, true, serverLocation, version); std::shared_ptr<ClientMetadata> cptr = nullptr; { boost::shared_lock<decltype(m_regionMetadataLock)> lock( m_regionMetadataLock); const auto& cptrIter = m_regionMetaDataMap.find(region->getFullPath()); if (cptrIter != m_regionMetaDataMap.end()) { cptr = cptrIter->second; } if (cptr == nullptr) { return; } } LOGFINE("Setting in markPrimaryBucketForTimeoutButLookSecondaryBucket"); auto totalBuckets = cptr->getTotalNumBuckets(); for (decltype(totalBuckets) i = 0; i < totalBuckets; i++) { int8_t version; std::shared_ptr<BucketServerLocation> bsl; cptr->getServerLocation(i, false, bsl, version); if (bsl == serverLocation) { prBuckets->setBucketTimeout(i); LOGFINE( "markPrimaryBucketForTimeoutButLookSecondaryBucket::setting bucket " "timeout..."); } } } bool ClientMetadataService::isBucketMarkedForTimeout(const char* regionFullPath, int32_t bucketid) { if (m_bucketWaitTimeout == std::chrono::milliseconds::zero()) return false; boost::shared_lock<decltype(m_PRbucketStatusLock)> lock(m_PRbucketStatusLock); const auto& bs = m_bucketStatus.find(regionFullPath); if (bs != m_bucketStatus.end()) { bool m = bs->second->isBucketTimedOut(bucketid, m_bucketWaitTimeout); if (m) { m_cache->incBlackListBucketTimeouts(); } LOGFINE("isBucketMarkedForTimeout:: for bucket %d returning = %d", bucketid, m); return m; } return false; } } // namespace client } // namespace geode } // namespace apache
33.792683
80
0.678672
mivanac
ba4148f0fc8532e3c256d8a227c08674ffe0c7ec
941
hpp
C++
q_lib/include/q/detail/count_bits.hpp
ebai101/Q
92c3dc11714a56eb2c799f168875803109c95549
[ "MIT" ]
null
null
null
q_lib/include/q/detail/count_bits.hpp
ebai101/Q
92c3dc11714a56eb2c799f168875803109c95549
[ "MIT" ]
null
null
null
q_lib/include/q/detail/count_bits.hpp
ebai101/Q
92c3dc11714a56eb2c799f168875803109c95549
[ "MIT" ]
null
null
null
/*============================================================================= Copyright (c) 2014-2019 Joel de Guzman. All rights reserved. Distributed under the MIT License [ https://opensource.org/licenses/MIT ] =============================================================================*/ #if !defined(CYCFI_Q_COUNT_BITS_HPP_MARCH_12_2018) #define CYCFI_Q_COUNT_BITS_HPP_MARCH_12_2018 #ifdef _MSC_VER # include <intrin.h> # include <nmmintrin.h> #endif namespace cycfi::q::detail { inline std::uint32_t count_bits(std::uint32_t i) { #if defined(_MSC_VER) return __popcnt(i); #elif defined(__GNUC__) return __builtin_popcount(i); #else # error Unsupported compiler #endif } inline std::uint64_t count_bits(std::uint64_t i) { #if defined(_MSC_VER) return _mm_popcnt_u64(i); #elif defined(__GNUC__) return __builtin_popcountll(i); #else # error Unsupported compiler #endif } } #endif
22.95122
79
0.606801
ebai101
ba418ea9d6863658a7ced2bd4dbb7e151d1c3204
530
cpp
C++
Algorithms/BinarySearch.cpp
Ritvikjain/DataStructures-And-Algorithms
27f2d48343aeb91c67376ae2fee429ca92dbd353
[ "MIT" ]
null
null
null
Algorithms/BinarySearch.cpp
Ritvikjain/DataStructures-And-Algorithms
27f2d48343aeb91c67376ae2fee429ca92dbd353
[ "MIT" ]
null
null
null
Algorithms/BinarySearch.cpp
Ritvikjain/DataStructures-And-Algorithms
27f2d48343aeb91c67376ae2fee429ca92dbd353
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; int BinarySearch(int a[],int l,int r,int f) { if(l<=r) { int mid=(l+r)/2; if(a[mid]==f) { return mid; } else if(f<a[mid]) { r=mid-1; } else { l=mid+1; } BinarySearch(a,l,r,f); } else return -1; } int main() { int n; cin>>n; int arr[n]; for(int i=0;i<n;i++) { cin>>arr[i]; } cout<<"Enter no. to search: "; int f; cin>>f; int pos=BinarySearch(arr,0,n-1,f); if(pos==-1) cout<<"Element not found"; else cout<<"Found at position: "<<pos+1; }
12.325581
43
0.543396
Ritvikjain
ba42f2478703f7c6f956c8ff4f58972e6e9428d0
2,701
cpp
C++
GameFramework_ThirdParty/FCollada/FCollada/DLLEntry.cpp
GavWood/tutorials
d5140129b6acd6d61f6feedcd352c12e4ebabd40
[ "BSD-2-Clause" ]
8
2017-10-26T14:26:55.000Z
2022-01-07T07:35:39.000Z
GameFramework_ThirdParty/FCollada/FCollada/DLLEntry.cpp
GavWood/tutorials
d5140129b6acd6d61f6feedcd352c12e4ebabd40
[ "BSD-2-Clause" ]
1
2018-01-27T19:21:07.000Z
2018-01-31T13:55:09.000Z
GameFramework_ThirdParty/FCollada/FCollada/DLLEntry.cpp
GavWood/Game-Framework
d5140129b6acd6d61f6feedcd352c12e4ebabd40
[ "BSD-2-Clause" ]
1
2021-07-21T17:37:33.000Z
2021-07-21T17:37:33.000Z
/* Copyright (C) 2005-2007 Feeling Software Inc. Portions of the code are: Copyright (C) 2005-2007 Sony Computer Entertainment America MIT License: http://www.opensource.org/licenses/mit-license.php */ #include "StdAfx.h" #ifdef FCOLLADA_DLL #ifdef WIN32 HINSTANCE hInstance = NULL; BOOL WINAPI DllMain(HINSTANCE _hInstance, ULONG fdwReason, LPVOID UNUSED(lpvReserved)) { static int initCount = 0; switch (fdwReason) { case DLL_PROCESS_ATTACH: case DLL_THREAD_ATTACH: // Initialize and Release are ref-counted. if (initCount == 0) { //FCollada::Initialize(); } initCount++; break; case DLL_PROCESS_DETACH: case DLL_THREAD_DETACH: // Initialize and Release are ref-counted. --initCount; if (initCount == 0) { //FCollada::Release(); } break; case DLL_PROCESS_VERIFIER: default: break; } hInstance = _hInstance; return TRUE; } #elif defined(__APPLE__) || defined(LINUX) void __attribute((constructor)) DllEntry(void) { } void __attribute((destructor)) DllTerminate(void) { } #endif // WIN32 #include "FMath/FMColor.h" #include "FMath/FMRandom.h" #include "FUDebug.h" #include "FULogFile.h" #include "FUBoundingBox.h" #include "FUBoundingSphere.h" #include "FCDocument.h" #include "FCDAnimationClipTools.h" #include "FCDLibrary.h" #include "FCDSceneNode.h" #include "FCDSceneNodeTools.h" #include "FCDSceneNodeIterator.h" #include "FCDParticleModifier.h" // Trick the linker so that it adds the functionalities of the classes that are not used internally. FCOLLADA_EXPORT void TrickLinker() { // FMColor FMColor* color = NULL; float* f = NULL; color->ToFloats(f, 4); // FULogFile FULogFile* logFile = NULL; logFile->WriteLine("Test"); // FUBoundingBox and FUBoundingSphere FUBoundingBox bb; FUBoundingSphere ss; if (!bb.Overlaps(ss)) { // FUDebug DEBUG_OUT("Tricking Linker..."); } // FCDAnimationClipTools FUObjectRef<FCDocument> d = FCollada::NewTopDocument(); FCDAnimationClipTools::ResetAnimationClipTimes(d, 0.0f); // FCDSceneNodeTools FCDSceneNode* n = d->GetVisualSceneLibrary()->AddEntity(); FCDSceneNodeIterator it(n); it.GetNode(); FCDSceneNodeTools::GenerateSampledAnimation(n); FMMatrix44List mat44s = FCDSceneNodeTools::GetSampledAnimationMatrices(); FCDSceneNodeTools::ClearSampledAnimation(); //FCDParticleModifier* x = FCDEmitterParticle::CreateInstance(FCDParticleModifier::VELOCITY_ALIGN, *d); extern void TrickLinkerFCDLibrary(); TrickLinkerFCDLibrary(); extern void TrickLinker3(); TrickLinker3(); // FCDSceneNodeIterator. extern void TrickLinkerFUParameter(); TrickLinkerFUParameter(); extern void TrickLinkerEffectParameter(); TrickLinkerEffectParameter(); } #endif // FCOLLADA_DLL
23.08547
104
0.749352
GavWood
ba44340a037f2ba5c15fc2f40c851568130f4305
2,647
cpp
C++
io/PVPFile.cpp
PetaVision/ObsoletePV
e99a42bf4292e944b252e144b5e07442b0715697
[ "MIT" ]
null
null
null
io/PVPFile.cpp
PetaVision/ObsoletePV
e99a42bf4292e944b252e144b5e07442b0715697
[ "MIT" ]
null
null
null
io/PVPFile.cpp
PetaVision/ObsoletePV
e99a42bf4292e944b252e144b5e07442b0715697
[ "MIT" ]
null
null
null
/* * PVPFile.cpp * * Created on: Jun 4, 2014 * Author: pschultz */ #include "PVPFile.hpp" namespace PV { PVPFile::PVPFile(const char * path, enum PVPFileMode mode, int pvpfileType, InterColComm * icComm) { initialize_base(); int status = initialize(path, mode, pvpfileType, icComm); if (status != PV_SUCCESS) { throw errno; } } PVPFile::PVPFile() { initialize_base(); // derived classes should call PVPFile::initialize from their initialize method, to preserve polymorphism } int PVPFile::initialize_base() { // Set member variables to safe values PVPFileType = 0; numFrames = 0; currentFrame = 0; icComm = NULL; stream = NULL; header = NULL; headertime = 0.0; return PV_SUCCESS; } int PVPFile::initialize(const char * path, enum PVPFileMode mode, int pvpfileType, InterColComm * icComm) { // For now, make sure the compiler sizes agree, but we should make the code more flexible assert(sizeof(int)==PVPFILE_SIZEOF_INT); assert(sizeof(long)==PVPFILE_SIZEOF_LONG); assert(sizeof(double)==PVPFILE_SIZEOF_DOUBLE); assert(sizeof(float)==PVPFILE_SIZEOF_FLOAT); assert(sizeof(short)==PVPFILE_SIZEOF_SHORT); int status = PV_SUCCESS; this->icComm = icComm; this->mode = mode; return initfile(path, mode, icComm); } int PVPFile::initfile(const char * path, enum PVPFileMode mode, InterColComm * icComm) { int status = PV_SUCCESS; const char * fopenmode = NULL; bool verifyWrites = false; errno = 0; switch(mode) { case PVPFILE_READ: fopenmode = "r"; break; case PVPFILE_WRITE: fopenmode = "w"; break; case PVPFILE_WRITE_READBACK: fopenmode = "w"; verifyWrites = true; break; case PVPFILE_APPEND: fopenmode = "r+"; struct stat statbuf; if (isRoot()) { errno = 0; status = PV_stat(path, &statbuf); if (status!=0) { if (errno == ENOENT) { // If file doesn't exist, create it and close it. errno = 0; stream = PV_fopen(path, "w", false/*verifyWrites*/); if (stream != NULL) { status = PV_fclose(stream); } } } } break; default: assert(0); break; } if (isRoot() && status==PV_SUCCESS) { stream = PV_fopen(path, fopenmode, verifyWrites); } MPI_Bcast(&errno, 1, MPI_INT, rootProc(), icComm->communicator()); status = errno ? PV_FAILURE : PV_SUCCESS; return status; } PVPFile::~PVPFile() { if (isRoot()) { PV_fclose(stream); } free(header); } } /* namespace PV */
26.47
108
0.613903
PetaVision
ba46efca2094eaefde1b2336feac0d68a1dd1b79
1,960
cpp
C++
src/bind/window/teleport_vdesktop.cpp
dmlerner/win-vind
f5c25bc0e082b9600ef19c02ba4f565bc3b14cfe
[ "MIT" ]
null
null
null
src/bind/window/teleport_vdesktop.cpp
dmlerner/win-vind
f5c25bc0e082b9600ef19c02ba4f565bc3b14cfe
[ "MIT" ]
null
null
null
src/bind/window/teleport_vdesktop.cpp
dmlerner/win-vind
f5c25bc0e082b9600ef19c02ba4f565bc3b14cfe
[ "MIT" ]
null
null
null
#include "teleport_vdesktop.hpp" #include "core/ntype_logger.hpp" #include "util/smartcom.hpp" #include "util/winwrap.hpp" #include <windows.h> // #include <shobjidl.h> namespace vind { namespace bind { TeleportOverVDesktop::TeleportOverVDesktop() : BindedFuncVoid("teleport_over_vdesktop") {} void TeleportOverVDesktop::sprocess(unsigned int desktop_id) { #ifdef DEBUG /* if(util::is_failed(CoInitialize(NULL))) { throw RUNTIME_EXCEPT("COM initialization failed") ; } auto co_uninit = [] (char* ptr) { if(ptr) { delete ptr ; ptr = nullptr ; } CoUninitialize() ; } ; std::unique_ptr<char, decltype(co_uninit)> smart_uninit{new char(), co_uninit} ; SmartCom<IVirtualDesktopManager> vdm{} ; if(util::is_failed(CoCreateInstance( CLSID_VirtualDesktopManager, NULL, CLSCTX_ALL, IID_IVirtualDesktopManager, reinterpret_cast<void**>(&vdm)))) { throw RUNTIME_EXCEPT("IVirtualDesktopManager creation failed.") ; } auto hwnd = GetForegroundWindow() ; GUID id ; if(util::is_failed(vdm->GetWindowDesktopId(hwnd, &id))) { std::cout << "failed\n" ; } std::cout << "ID: " << id.Data1 << "." << id.Data2 << "." << id.Data3 << "." << id.Data4 << std::endl ; */ #endif } void TeleportOverVDesktop::sprocess(core::NTypeLogger& parent_lgr) { #ifdef DEBUG if(!parent_lgr.is_long_pressing()) { sprocess(1) ; } #endif } void TeleportOverVDesktop::sprocess(const core::CharLogger& UNUSED(parent_lgr)) { #ifdef DEBUG sprocess(1) ; #endif } } }
28.405797
115
0.526531
dmlerner
ba4b355c947aeee48545395d0ceb54748d9e6b7a
2,491
cpp
C++
greedy-algorithms/basic-principles/minimize-cash-flow.cpp
dushimsam/deep-dive-in-algorithms
0c6a04b3115ba789ab4aca68cce51c9a3c3a075a
[ "MIT" ]
null
null
null
greedy-algorithms/basic-principles/minimize-cash-flow.cpp
dushimsam/deep-dive-in-algorithms
0c6a04b3115ba789ab4aca68cce51c9a3c3a075a
[ "MIT" ]
null
null
null
greedy-algorithms/basic-principles/minimize-cash-flow.cpp
dushimsam/deep-dive-in-algorithms
0c6a04b3115ba789ab4aca68cce51c9a3c3a075a
[ "MIT" ]
null
null
null
#include<iostream> #include<bits/stdc++.h> using namespace std; /** ALGORITHM 1. Settle the net amount for each person. = (amount_received - amount_sent) 2. Get the most_credited_amount:amount.getMax() , and the most_debited_amount: amount.getMin() 3. Find the minimum of the two. 4. Deduct to the creditor that min amount , and add to the debtor the same amount. 5. Repeat 2,3,4 until the most_debited_amount and most_debited_amount = 0; **/ class CashFlow { vector<int> amount; public: CashFlow(); CashFlow(vector<vector<int>> cashflows, int persons) { for (int i = 0; i < persons; i++) amount.push_back(0); for (int i = 0; i < persons;i++) { for (int j = 0; j < persons;j++) { // Take the amount in which that person should pay and deduct that which you should pay him as well. int net_amount = cashflows[j][i] - cashflows[i][j]; amount[i] += net_amount; } } minimizeCashFlow(amount); for (int i : amount) cout << "Amount " << i << endl; } int getIndexOfMax() { int max = 0; for (int i = 0;i < amount.size();i++) { if (amount[i] > max) { max = i; } } return max; } int getIndexOfMin() { int min = 0; for (int i = 0;i < amount.size();i++) { if (amount[i] < min) { min = i; } } return min; } void minimizeCashFlow(vector<int> amount) { int credMax = *max_element(amount.begin(), amount.end()); int debtMax = *min_element(amount.begin(), amount.end()); cout << "Max Cred " << credMax << endl; cout << "Min Debt " << debtMax << endl; if (credMax == 0 && debtMax == 0) return; int minOfTwo = min(-debtMax, credMax); int indexMaxCred = getIndexOfMax(); int indexMaxDebt = getIndexOfMin(); amount[indexMaxDebt] += minOfTwo; amount[indexMaxCred] -= minOfTwo; cout << "Min Of Two " << minOfTwo << endl; // minimizeCashFlow(amount); } }; int main() { // graph[i][j] indicates the amount that person i needs to // pay person j vector<vector<int>> cashflows = { {0, 1000, 2000}, {0, 0, 5000}, {0, 0, 0} }; int persons = 3; CashFlow cashFlow(cashflows, persons); return 0; }
24.663366
116
0.531112
dushimsam
ba4c6ac107782b7fb75be146bfa2ded7c64afbc7
705
hpp
C++
EiRas/Framework/EiRas/PlatformDependency/OnMetal/Material/GraphicsResourceMetalAdapter.hpp
MonsterENT/EiRas
b29592da60b1a9085f5a2d8fa4ed01b43660f712
[ "MIT" ]
1
2019-12-24T10:12:16.000Z
2019-12-24T10:12:16.000Z
EiRas/Framework/EiRas/PlatformDependency/OnMetal/Material/GraphicsResourceMetalAdapter.hpp
MonsterENT/EiRas
b29592da60b1a9085f5a2d8fa4ed01b43660f712
[ "MIT" ]
null
null
null
EiRas/Framework/EiRas/PlatformDependency/OnMetal/Material/GraphicsResourceMetalAdapter.hpp
MonsterENT/EiRas
b29592da60b1a9085f5a2d8fa4ed01b43660f712
[ "MIT" ]
null
null
null
// // GraphicsResourceMetalAdapter.hpp // EiRasMetalBuild // // Created by MonsterENT on 12/8/19. // Copyright © 2019 MonsterENT. All rights reserved. // #ifndef GraphicsResourceMetalAdapter_hpp #define GraphicsResourceMetalAdapter_hpp #include <Global/GlobalDefine.h> #include <string> namespace MaterialSys { void* createConstantBufferMetal(std::string name, int bufferSize, bool initResource); void* createShaderResourceTexture(std::string name, _uint width, _uint height, void* texData, bool* buildStatusFlag); void* createDefaultBufferMetal(std::string name, int bufferSize, bool initResource); void setResourceMetal(void* ptr, void* res); } #endif /* GraphicsResourceMetalAdapter_hpp */
26.111111
117
0.785816
MonsterENT
ba4e5ccd6b3bf8ca2762fc331228de296c7321bc
746
hpp
C++
include/vmp_analyzer.hpp
invlpg/vmpfix
089cfd941a949877093442fd8f951a84f0794d99
[ "Unlicense" ]
null
null
null
include/vmp_analyzer.hpp
invlpg/vmpfix
089cfd941a949877093442fd8f951a84f0794d99
[ "Unlicense" ]
null
null
null
include/vmp_analyzer.hpp
invlpg/vmpfix
089cfd941a949877093442fd8f951a84f0794d99
[ "Unlicense" ]
null
null
null
#pragma once #include <linuxpe> #include <vector> #include "image_desc.hpp" enum class stub_type_t { jump, call, move }; struct vmp_stub_t { stub_type_t type; // Address of resolved api. // uint64_t resolved_api; // Address of original call/jmp/mov instuction. // uint64_t ins_address; // Original instruction size. // uint64_t ins_size; // In case of `lea` output reg is filled by Zydis. // uint64_t output_reg; std::string to_string() const; }; void init_section_names(const std::vector<std::string>& names); std::vector<vmp_stub_t> collect_stubs(image_t* img); std::vector<uint8_t> encode_stub(const vmp_stub_t& stub, uint64_t iat, bool is_64);
24.064516
63
0.655496
invlpg
ba4eccb48c450aa6f122ae6efc9385549b17236d
4,471
cc
C++
lib/lf/quad/test/make_quad_rule_tests.cc
Pascal-So/lehrfempp
e2716e914169eec7ee59e822ea3ab303143eacd1
[ "MIT" ]
null
null
null
lib/lf/quad/test/make_quad_rule_tests.cc
Pascal-So/lehrfempp
e2716e914169eec7ee59e822ea3ab303143eacd1
[ "MIT" ]
null
null
null
lib/lf/quad/test/make_quad_rule_tests.cc
Pascal-So/lehrfempp
e2716e914169eec7ee59e822ea3ab303143eacd1
[ "MIT" ]
null
null
null
/** * @file * @brief Test the order of quadrature rules by testing it with monomials * @author Raffael Casagrande * @date 2018-08-19 06:54:02 * @copyright MIT License */ #include <gtest/gtest.h> #include <lf/quad/quad.h> #include <boost/math/special_functions/factorials.hpp> namespace lf::quad::test { double integrate(QuadRule qr, std::vector<int> monomialCoefficients) { double result = 0; for (int i = 0; i < qr.Points().cols(); ++i) { double temp = 1; for (int j = 0; j < monomialCoefficients.size(); ++j) { temp *= std::pow(qr.Points()(j, i), monomialCoefficients[j]); } result += temp * qr.Weights()(i); } return result; } void checkQuadRule(QuadRule qr, double precision = 1e-12, bool check_order_exact = true) { EXPECT_EQ(qr.Points().cols(), qr.Weights().size()); EXPECT_EQ(qr.Points().rows(), qr.RefEl().Dimension()); auto order = qr.Degree(); if (qr.RefEl() == base::RefEl::kSegment()) { for (int i = 0; i <= order; ++i) { // integrate x^i EXPECT_DOUBLE_EQ(integrate(qr, {i}), 1. / (1. + i)) << "Failure for i = " << i; } // try integrate one order too high: EXPECT_GT(std::abs(integrate(qr, {static_cast<int>(order) + 1}) - 1. / (2. + order)), 1e-10); } else if (qr.RefEl() == base::RefEl::kTria()) { // TRIA /////////////////////////////////////////////////////////////////////////// auto exact_value = [](int i, int j) { return boost::math::factorial<double>(i) * boost::math::factorial<double>(j + 1) / ((1 + j) * boost::math::factorial<double>(2 + i + j)); }; for (int i = 0; i <= order; ++i) { for (int j = 0; j <= order - i; ++j) { // integrate x^i y^j double qr_val = integrate(qr, {i, j}); EXPECT_NEAR(qr_val / exact_value(i, j), 1, precision) << "Failure for x^" << i << "*y^" << j << ": " << qr_val << " <-> " << exact_value(i, j); } } if (check_order_exact) { // Make sure that at least on of the order+1 polynomials is not integrated // correctly bool one_fails = false; for (int i = -1; i <= static_cast<int>(order); ++i) { if (std::abs(integrate(qr, {i + 1, static_cast<int>(order - i)}) - exact_value(i + 1, order - i)) > 1e-12) { one_fails = true; break; } } EXPECT_TRUE(one_fails) << "order = " << (int)order; } } else if (qr.RefEl() == base::RefEl::kQuad()) { // QUAD /////////////////////////////////////////////////////////////////////////// for (int i = 0; i <= order; ++i) { for (int j = 0; j <= order; ++j) { // integrate x^i y^j double qr_val = integrate(qr, {i, j}); double ext_val = 1. / ((1. + i) * (1. + j)); EXPECT_DOUBLE_EQ(qr_val, ext_val) << "Failure for x^" << i << "*y^" << j << ": " << qr_val << " <-> " << ext_val; } } // make sure that not all of the higher polynomials integrate correctly: bool atLeastOneFails = false; for (int i = 0; i <= order + 1; ++i) { if (std::abs(integrate(qr, {static_cast<int>(order + 1), i}) - 1. / ((2. + order) * (1. + i))) > 1e-10) { atLeastOneFails = true; break; } if (std::abs(integrate(qr, {i, static_cast<int>(order + 1)}) - 1. / ((2. + order) * (1. + i))) > 1e-10) { atLeastOneFails = true; break; } } EXPECT_TRUE(atLeastOneFails); } } TEST(qr_IntegrationTest, Segment) { for (int i = 1; i < 10; ++i) { checkQuadRule(make_QuadRule(base::RefEl::kSegment(), i)); } } TEST(qr_IntegrationTest, Quad) { checkQuadRule(make_QuadRule(base::RefEl::kQuad(), 1)); checkQuadRule(make_QuadRule(base::RefEl::kQuad(), 2)); checkQuadRule(make_QuadRule(base::RefEl::kQuad(), 3)); } TEST(qr_IntegrationTest, Tria) { // make sure that also the tensor product versions are tested. for (int i = 1; i < 55; ++i) { checkQuadRule(make_QuadRule(base::RefEl::kTria(), i), 1e-12, i < 10); } } // Test midpoint quadrature rule for triangles TEST(qr_IntegrationTest, mp) { checkQuadRule(make_TriaQR_EdgeMidpointRule(), 1e-12, true); checkQuadRule(make_QuadQR_EdgeMidpointRule(), 1e-12, true); } TEST(qr_IntegrationTest, P6O4) { checkQuadRule(make_TriaQR_P6O4(), 1e-12, true); } } // namespace lf::quad::test
32.875
80
0.528517
Pascal-So
ba502d34e215d686d665d5940bb650a7a43b3944
70,931
hpp
C++
include/athena/DNAOp.hpp
encounter/athena
6adba82abd8b7f48e6eca9f74361d0c605bc9ec8
[ "MIT" ]
null
null
null
include/athena/DNAOp.hpp
encounter/athena
6adba82abd8b7f48e6eca9f74361d0c605bc9ec8
[ "MIT" ]
null
null
null
include/athena/DNAOp.hpp
encounter/athena
6adba82abd8b7f48e6eca9f74361d0c605bc9ec8
[ "MIT" ]
null
null
null
#pragma once #include <cstddef> #include <cstdint> #include <string> #include <type_traits> #include <vector> #include "athena/ChecksumsLiterals.hpp" #include "athena/IStreamReader.hpp" #include "athena/IStreamWriter.hpp" #include "athena/YAMLDocReader.hpp" #include "athena/YAMLDocWriter.hpp" namespace athena::io { struct PropId { std::string_view name; uint32_t rcrc32 = 0xffffffff; uint64_t crc64 = 0x0; template <class T> constexpr T opget() const; constexpr PropId() = default; constexpr explicit PropId(std::string_view name, uint32_t rcrc32, uint64_t crc64) : name(name), rcrc32(rcrc32), crc64(crc64) {} constexpr explicit PropId(std::string_view name) : name(name) , rcrc32(athena::checksums::literals::rcrc32_rec(0xFFFFFFFF, name.data())) , crc64(athena::checksums::literals::crc64_rec(0xFFFFFFFFFFFFFFFF, name.data())) {} constexpr PropId(std::string_view name, uint32_t rcrc32) : name(name), rcrc32(rcrc32), crc64(athena::checksums::literals::crc64_rec(0xFFFFFFFFFFFFFFFF, name.data())) {} }; template <> constexpr uint32_t PropId::opget<uint32_t>() const { return rcrc32; } template <> constexpr uint64_t PropId::opget<uint64_t>() const { return crc64; } namespace literals { constexpr PropId operator"" _propid(const char* s, size_t len) { return PropId{s}; } } // namespace literals #define AT_PROP_CASE(...) case athena::io::PropId(__VA_ARGS__).opget<typename Op::PropT>() #if defined(__atdna__) #define AT_OVERRIDE_RCRC32(rcrc32) __attribute__((annotate("rcrc32=" #rcrc32))) #else #define AT_OVERRIDE_RCRC32(rcrc32) #endif #if defined(__atdna__) #define AT_SPECIALIZE_PARMS(...) __attribute__((annotate("specparms=" #__VA_ARGS__))) #else #define AT_SPECIALIZE_PARMS(...) #endif enum class PropType { None, CRC32, CRC64 }; template <class T> using __IsPODType = std::disjunction< std::is_arithmetic<std::remove_cv_t<T>>, std::is_convertible<std::remove_cv_t<T>&, atVec2f&>, std::is_convertible<std::remove_cv_t<T>&, atVec3f&>, std::is_convertible<std::remove_cv_t<T>&, atVec4f&>, std::is_convertible<std::remove_cv_t<T>&, atVec2d&>, std::is_convertible<std::remove_cv_t<T>&, atVec3d&>, std::is_convertible<std::remove_cv_t<T>&, atVec4d&>>; template <class T> constexpr bool __IsPODType_v = __IsPODType<T>::value; template <class T> using __CastPODType = std::conditional_t< std::is_convertible_v<std::remove_cv_t<T>&, atVec2f&>, atVec2f, std::conditional_t< std::is_convertible_v<std::remove_cv_t<T>&, atVec3f&>, atVec3f, std::conditional_t< std::is_convertible_v<std::remove_cv_t<T>&, atVec4f&>, atVec4f, std::conditional_t< std::is_convertible_v<std::remove_cv_t<T>&, atVec2d&>, atVec2d, std::conditional_t<std::is_convertible_v<std::remove_cv_t<T>&, atVec3d&>, atVec3d, std::conditional_t<std::is_convertible_v<std::remove_cv_t<T>&, atVec4d&>, atVec4d, std::remove_cv_t<T>>>>>>>; template <Endian DNAE> uint16_t __Read16(IStreamReader& r) { return DNAE == Endian::Big ? r.readUint16Big() : r.readUint16Little(); } template <Endian DNAE> void __Write16(IStreamWriter& w, uint16_t v) { DNAE == Endian::Big ? w.writeUint16Big(v) : w.writeUint16Little(v); } template <Endian DNAE> uint32_t __Read32(IStreamReader& r) { return DNAE == Endian::Big ? r.readUint32Big() : r.readUint32Little(); } template <Endian DNAE> void __Write32(IStreamWriter& w, uint32_t v) { DNAE == Endian::Big ? w.writeUint32Big(v) : w.writeUint32Little(v); } template <Endian DNAE> uint64_t __Read64(IStreamReader& r) { return DNAE == Endian::Big ? r.readUint64Big() : r.readUint64Little(); } template <Endian DNAE> void __Write64(IStreamWriter& w, uint64_t v) { DNAE == Endian::Big ? w.writeUint64Big(v) : w.writeUint64Little(v); } template <PropType PropOp> struct BinarySize { using PropT = std::conditional_t<PropOp == PropType::CRC64, uint64_t, uint32_t>; using StreamT = size_t; template <class T, Endian DNAE> static std::enable_if_t<std::is_enum_v<T>> Do(const PropId& id, T& var, StreamT& s) { if (PropOp != PropType::None) { /* Accessed via Enumerate, header */ s += 6; } using PODType = std::underlying_type_t<T>; BinarySize<PropType::None>::Do<PODType, DNAE>(id, *reinterpret_cast<PODType*>(&var), s); } template <class T, Endian DNAE> static std::enable_if_t<__IsPODType_v<T>> Do(const PropId& id, T& var, StreamT& s) { if (PropOp != PropType::None) { /* Accessed via Enumerate, header */ s += 6; } using CastT = __CastPODType<T>; BinarySize<PropType::None>::Do<CastT, DNAE>(id, static_cast<CastT&>(const_cast<std::remove_cv_t<T>&>(var)), s); } template <class T, Endian DNAE> static std::enable_if_t<__IsDNARecord_v<T> && PropOp != PropType::None> Do(const PropId& id, T& var, StreamT& s) { /* Accessed via Enumerate, header */ s += 6; var.template Enumerate<BinarySize<PropOp>>(s); } template <class T, Endian DNAE> static std::enable_if_t<__IsDNARecord_v<T> && PropOp == PropType::None> Do(const PropId& id, T& var, StreamT& s) { var.template Enumerate<BinarySize<PropType::None>>(s); } template <class T, Endian DNAE> static std::enable_if_t<std::is_array_v<T>> Do(const PropId& id, T& var, StreamT& s) { for (auto& v : var) BinarySize<PropOp>::Do<std::remove_reference_t<decltype(v)>, DNAE>(id, v, s); } template <class T, Endian DNAE> static void DoSize(const PropId& id, T& var, StreamT& s) { BinarySize<PropOp>::Do<T, DNAE>(id, var, s); } template <class T, class S, Endian DNAE> static std::enable_if_t<!std::is_same_v<T, bool>> Do(const PropId& id, std::vector<T>& vector, const S& count, StreamT& s) { for (T& v : vector) BinarySize<PropOp>::Do<T, DNAE>(id, v, s); } template <class T, class S, Endian DNAE> static std::enable_if_t<std::is_same_v<T, bool>> Do(const PropId& id, std::vector<T>& vector, const S& count, StreamT& s) { /* libc++ specializes vector<bool> as a bitstream */ s += vector.size(); } static void Do(const PropId& id, std::unique_ptr<atUint8[]>& buf, size_t count, StreamT& s) { if (buf) s += count; } template <class T, Endian DNAE> static std::enable_if_t<std::is_same_v<T, std::string>> Do(const PropId& id, T& str, StreamT& s) { s += str.size() + 1; } static void Do(const PropId& id, std::string& str, atInt32 count, StreamT& s) { if (count < 0) s += str.size() + 1; else s += count; } template <class T, Endian DNAE> static std::enable_if_t<std::is_same_v<T, std::wstring>> Do(const PropId& id, T& str, StreamT& s) { s += str.size() * 2 + 2; } template <Endian DNAE> static void Do(const PropId& id, std::wstring& str, atInt32 count, StreamT& s) { if (count < 0) s += str.size() * 2 + 2; else s += count * 2; } static void DoSeek(atInt64 amount, SeekOrigin whence, StreamT& s) { switch (whence) { case SeekOrigin::Begin: s = amount; break; case SeekOrigin::Current: s += amount; break; default: break; } } static void DoAlign(atInt64 amount, StreamT& s) { s = (s + amount - 1) / amount * amount; } }; #define __BINARY_SIZE_S(type, endian) \ template <> \ template <> \ inline void BinarySize<PropType::None>::Do<type, endian>(const PropId& id, type& var, BinarySize::StreamT& s) __BINARY_SIZE_S(bool, Endian::Big) { s += 1; } __BINARY_SIZE_S(atInt8, Endian::Big) { s += 1; } __BINARY_SIZE_S(atUint8, Endian::Big) { s += 1; } __BINARY_SIZE_S(atInt16, Endian::Big) { s += 2; } __BINARY_SIZE_S(atUint16, Endian::Big) { s += 2; } __BINARY_SIZE_S(atInt32, Endian::Big) { s += 4; } __BINARY_SIZE_S(atUint32, Endian::Big) { s += 4; } __BINARY_SIZE_S(atInt64, Endian::Big) { s += 8; } __BINARY_SIZE_S(atUint64, Endian::Big) { s += 8; } __BINARY_SIZE_S(float, Endian::Big) { s += 4; } __BINARY_SIZE_S(double, Endian::Big) { s += 8; } __BINARY_SIZE_S(atVec2f, Endian::Big) { s += 8; } __BINARY_SIZE_S(atVec2d, Endian::Big) { s += 16; } __BINARY_SIZE_S(atVec3f, Endian::Big) { s += 12; } __BINARY_SIZE_S(atVec3d, Endian::Big) { s += 24; } __BINARY_SIZE_S(atVec4f, Endian::Big) { s += 16; } __BINARY_SIZE_S(atVec4d, Endian::Big) { s += 32; } __BINARY_SIZE_S(bool, Endian::Little) { s += 1; } __BINARY_SIZE_S(atInt8, Endian::Little) { s += 1; } __BINARY_SIZE_S(atUint8, Endian::Little) { s += 1; } __BINARY_SIZE_S(atInt16, Endian::Little) { s += 2; } __BINARY_SIZE_S(atUint16, Endian::Little) { s += 2; } __BINARY_SIZE_S(atInt32, Endian::Little) { s += 4; } __BINARY_SIZE_S(atUint32, Endian::Little) { s += 4; } __BINARY_SIZE_S(atInt64, Endian::Little) { s += 8; } __BINARY_SIZE_S(atUint64, Endian::Little) { s += 8; } __BINARY_SIZE_S(float, Endian::Little) { s += 4; } __BINARY_SIZE_S(double, Endian::Little) { s += 8; } __BINARY_SIZE_S(atVec2f, Endian::Little) { s += 8; } __BINARY_SIZE_S(atVec2d, Endian::Little) { s += 16; } __BINARY_SIZE_S(atVec3f, Endian::Little) { s += 12; } __BINARY_SIZE_S(atVec3d, Endian::Little) { s += 24; } __BINARY_SIZE_S(atVec4f, Endian::Little) { s += 16; } __BINARY_SIZE_S(atVec4d, Endian::Little) { s += 32; } template <PropType PropOp> struct PropCount { using PropT = std::conditional_t<PropOp == PropType::CRC64, uint64_t, uint32_t>; using StreamT = size_t; template <class T, Endian DNAE> static void Do(const PropId& id, T& var, StreamT& s) { /* Only reports one level of properties */ s += 1; } template <class T, Endian DNAE> static void DoSize(const PropId& id, T& var, StreamT& s) { PropCount<PropOp>::Do<T, DNAE>(id, var, s); } template <class T, class S, Endian DNAE> static void Do(const PropId& id, std::vector<T>& vector, const S& count, StreamT& s) { /* Only reports one level of properties */ s += 1; } static void Do(const PropId& id, std::unique_ptr<atUint8[]>& buf, size_t count, StreamT& s) { /* Only reports one level of properties */ s += 1; } template <class T, Endian DNAE> static std::enable_if_t<std::is_same_v<T, std::string>> Do(const PropId& id, T& str, StreamT& s) { /* Only reports one level of properties */ s += 1; } static void Do(const PropId& id, std::string& str, atInt32 count, StreamT& s) { /* Only reports one level of properties */ s += 1; } template <class T, Endian DNAE> static std::enable_if_t<std::is_same_v<T, std::wstring>> Do(const PropId& id, T& str, StreamT& s) { /* Only reports one level of properties */ s += 1; } template <Endian DNAE> static void Do(const PropId& id, std::wstring& str, atInt32 count, StreamT& s) { /* Only reports one level of properties */ s += 1; } static void DoSeek(atInt64 amount, SeekOrigin whence, StreamT& s) {} static void DoAlign(atInt64 amount, StreamT& s) {} }; template <PropType PropOp> struct Read { using PropT = std::conditional_t<PropOp == PropType::CRC64, uint64_t, uint32_t>; using StreamT = IStreamReader; template <class T, Endian DNAE> static std::enable_if_t<std::is_enum_v<T>> Do(const PropId& id, T& var, StreamT& r) { using PODType = std::underlying_type_t<T>; Read<PropType::None>::Do<PODType, DNAE>(id, *reinterpret_cast<PODType*>(&var), r); } template <class T, Endian DNAE> static std::enable_if_t<__IsPODType_v<T>> Do(const PropId& id, T& var, StreamT& r) { using CastT = __CastPODType<T>; Read<PropType::None>::Do<CastT, DNAE>(id, static_cast<CastT&>(var), r); } template <class T, Endian DNAE> static std::enable_if_t<__IsDNARecord<T>() && PropOp == PropType::None> Do(const PropId& id, T& var, StreamT& r) { var.template Enumerate<Read<PropType::None>>(r); } template <class T, Endian DNAE> static std::enable_if_t<__IsDNARecord<T>() && PropOp != PropType::None> Do(const PropId& id, T& var, StreamT& r) { /* Accessed via Lookup, no header */ atUint16 propCount = __Read16<T::DNAEndian>(r); for (atUint32 i = 0; i < propCount; ++i) { atUint64 hash; if (PropOp == PropType::CRC64) hash = __Read64<T::DNAEndian>(r); else hash = __Read32<T::DNAEndian>(r); atInt64 size = __Read16<T::DNAEndian>(r); atInt64 start = r.position(); var.template Lookup<Read<PropOp>>(hash, r); atInt64 actualRead = r.position() - start; if (actualRead != size) r.seek(size - actualRead); } } template <class T, Endian DNAE> static std::enable_if_t<std::is_array_v<T>> Do(const PropId& id, T& var, StreamT& s) { for (auto& v : var) Read<PropOp>::Do<std::remove_reference_t<decltype(v)>, DNAE>(id, v, s); } template <class T, Endian DNAE> static void DoSize(const PropId& id, T& var, StreamT& s) { Read<PropOp>::Do<T, DNAE>(id, var, s); } template <class T, class S, Endian DNAE> static std::enable_if_t<!std::is_same_v<T, bool>> Do(const PropId& id, std::vector<T>& vector, const S& count, StreamT& r) { vector.clear(); vector.reserve(count); for (size_t i = 0; i < static_cast<size_t>(count); ++i) { vector.emplace_back(); Read<PropOp>::Do<T, DNAE>(id, vector.back(), r); } } template <class T, class S, Endian DNAE> static std::enable_if_t<std::is_same_v<T, bool>> Do(const PropId& id, std::vector<T>& vector, const S& count, StreamT& r) { /* libc++ specializes vector<bool> as a bitstream */ vector.clear(); vector.reserve(count); for (size_t i = 0; i < count; ++i) vector.push_back(r.readBool()); } static void Do(const PropId& id, std::unique_ptr<atUint8[]>& buf, size_t count, StreamT& r) { buf.reset(new atUint8[count]); r.readUBytesToBuf(buf.get(), count); } template <class T, Endian DNAE> static std::enable_if_t<std::is_same_v<T, std::string>> Do(const PropId& id, T& str, StreamT& r) { str = r.readString(); } static void Do(const PropId& id, std::string& str, atInt32 count, StreamT& r) { str = r.readString(count); } template <class T, Endian DNAE> static std::enable_if_t<std::is_same_v<T, std::wstring>> Do(const PropId& id, T& str, StreamT& r) { Read<PropType::None>::Do<DNAE>(id, str, r); } template <Endian DNAE> static void Do(const PropId& id, std::wstring& str, atInt32 count, StreamT& r) { Read<PropType::None>::Do<DNAE>(id, str, count, r); } static void DoSeek(atInt64 amount, SeekOrigin whence, StreamT& r) { r.seek(amount, whence); } static void DoAlign(atInt64 amount, StreamT& r) { r.seek((r.position() + amount - 1) / amount * amount, athena::SeekOrigin::Begin); } }; #define __READ_S(type, endian) \ template <> \ template <> \ inline void Read<PropType::None>::Do<type, endian>(const PropId& id, type& var, Read::StreamT& r) #define __READ_WSTR_S(endian) \ template <> \ template <> \ inline void Read<PropType::None>::Do<std::wstring, endian>(const PropId& id, std::wstring& str, Read::StreamT& r) #define __READ_WSTRC_S(endian) \ template <> \ template <> \ inline void Read<PropType::None>::Do<endian>(const PropId& id, std::wstring& str, atInt32 count, Read::StreamT& r) __READ_S(bool, Endian::Big) { var = r.readBool(); } __READ_S(atInt8, Endian::Big) { var = r.readByte(); } __READ_S(atUint8, Endian::Big) { var = r.readUByte(); } __READ_S(atInt16, Endian::Big) { var = r.readInt16Big(); } __READ_S(atUint16, Endian::Big) { var = r.readUint16Big(); } __READ_S(atInt32, Endian::Big) { var = r.readInt32Big(); } __READ_S(atUint32, Endian::Big) { var = r.readUint32Big(); } __READ_S(atInt64, Endian::Big) { var = r.readInt64Big(); } __READ_S(atUint64, Endian::Big) { var = r.readUint64Big(); } __READ_S(float, Endian::Big) { var = r.readFloatBig(); } __READ_S(double, Endian::Big) { var = r.readDoubleBig(); } __READ_S(atVec2f, Endian::Big) { var = r.readVec2fBig(); } __READ_S(atVec2d, Endian::Big) { var = r.readVec2dBig(); } __READ_S(atVec3f, Endian::Big) { var = r.readVec3fBig(); } __READ_S(atVec3d, Endian::Big) { var = r.readVec3dBig(); } __READ_S(atVec4f, Endian::Big) { var = r.readVec4fBig(); } __READ_S(atVec4d, Endian::Big) { var = r.readVec4dBig(); } __READ_WSTR_S(Endian::Big) { str = r.readWStringBig(); } __READ_WSTRC_S(Endian::Big) { str = r.readWStringBig(count); } __READ_S(bool, Endian::Little) { var = r.readBool(); } __READ_S(atInt8, Endian::Little) { var = r.readByte(); } __READ_S(atUint8, Endian::Little) { var = r.readUByte(); } __READ_S(atInt16, Endian::Little) { var = r.readInt16Little(); } __READ_S(atUint16, Endian::Little) { var = r.readUint16Little(); } __READ_S(atInt32, Endian::Little) { var = r.readInt32Little(); } __READ_S(atUint32, Endian::Little) { var = r.readUint32Little(); } __READ_S(atInt64, Endian::Little) { var = r.readInt64Little(); } __READ_S(atUint64, Endian::Little) { var = r.readUint64Little(); } __READ_S(float, Endian::Little) { var = r.readFloatLittle(); } __READ_S(double, Endian::Little) { var = r.readDoubleLittle(); } __READ_S(atVec2f, Endian::Little) { var = r.readVec2fLittle(); } __READ_S(atVec2d, Endian::Little) { var = r.readVec2dLittle(); } __READ_S(atVec3f, Endian::Little) { var = r.readVec3fLittle(); } __READ_S(atVec3d, Endian::Little) { var = r.readVec3dLittle(); } __READ_S(atVec4f, Endian::Little) { var = r.readVec4fLittle(); } __READ_S(atVec4d, Endian::Little) { var = r.readVec4dLittle(); } __READ_WSTR_S(Endian::Little) { str = r.readWStringLittle(); } __READ_WSTRC_S(Endian::Little) { str = r.readWStringLittle(count); } template <PropType PropOp> struct Write { using PropT = std::conditional_t<PropOp == PropType::CRC64, uint64_t, uint32_t>; using StreamT = IStreamWriter; template <class T, Endian DNAE> static std::enable_if_t<std::is_enum_v<T>> Do(const PropId& id, T& var, StreamT& w) { if (PropOp != PropType::None) { /* Accessed via Enumerate, header */ if (PropOp == PropType::CRC64) __Write64<DNAE>(w, id.crc64); else __Write32<DNAE>(w, id.rcrc32); size_t binarySize = 0; BinarySize<PropType::None>::Do<T, DNAE>(id, var, binarySize); DNAE == Endian::Big ? w.writeUint16Big(atUint16(binarySize)) : w.writeUint16Little(atUint16(binarySize)); } using PODType = std::underlying_type_t<T>; Write<PropType::None>::Do<PODType, DNAE>(id, *reinterpret_cast<PODType*>(&var), w); } template <class T, Endian DNAE> static std::enable_if_t<__IsPODType_v<T>> Do(const PropId& id, T& var, StreamT& w) { using CastT = __CastPODType<T>; if (PropOp != PropType::None) { /* Accessed via Enumerate, header */ if (PropOp == PropType::CRC64) __Write64<DNAE>(w, id.crc64); else __Write32<DNAE>(w, id.rcrc32); size_t binarySize = 0; BinarySize<PropType::None>::Do<CastT, DNAE>(id, static_cast<CastT&>(const_cast<std::remove_cv_t<T>&>(var)), binarySize); __Write16<DNAE>(w, atUint16(binarySize)); } Write<PropType::None>::Do<CastT, DNAE>(id, static_cast<CastT&>(const_cast<std::remove_cv_t<T>&>(var)), w); } template <class T, Endian DNAE> static std::enable_if_t<__IsDNARecord<T>() && PropOp != PropType::None> Do(const PropId& id, T& var, StreamT& w) { /* Accessed via Enumerate, header */ if (PropOp == PropType::CRC64) __Write64<T::DNAEndian>(w, id.crc64); else __Write32<T::DNAEndian>(w, id.rcrc32); size_t binarySize = 0; var.template Enumerate<BinarySize<PropOp>>(binarySize); __Write16<T::DNAEndian>(w, atUint16(binarySize)); size_t propCount = 0; var.template Enumerate<PropCount<PropOp>>(propCount); __Write16<T::DNAEndian>(w, atUint16(propCount)); var.template Enumerate<Write<PropOp>>(w); } template <class T, Endian DNAE> static std::enable_if_t<__IsDNARecord<T>() && PropOp == PropType::None> Do(const PropId& id, T& var, StreamT& w) { var.template Enumerate<Write<PropType::None>>(w); } template <class T, Endian DNAE> static std::enable_if_t<std::is_array_v<T>> Do(const PropId& id, T& var, StreamT& s) { for (auto& v : var) Write<PropOp>::Do<std::remove_reference_t<decltype(v)>, DNAE>(id, v, s); } template <class T, Endian DNAE> static void DoSize(const PropId& id, T& var, StreamT& s) { Write<PropOp>::Do<T, DNAE>(id, var, s); } template <class T, class S, Endian DNAE> static std::enable_if_t<!std::is_same_v<T, bool>> Do(const PropId& id, std::vector<T>& vector, const S& count, StreamT& w) { for (T& v : vector) Write<PropOp>::Do<T, DNAE>(id, v, w); } template <class T, class S, Endian DNAE> static std::enable_if_t<std::is_same_v<T, bool>> Do(const PropId& id, std::vector<T>& vector, const S& count, StreamT& w) { /* libc++ specializes vector<bool> as a bitstream */ for (const T& v : vector) w.writeBool(v); } static void Do(const PropId& id, std::unique_ptr<atUint8[]>& buf, size_t count, StreamT& w) { if (buf) w.writeUBytes(buf.get(), count); } template <class T, Endian DNAE> static std::enable_if_t<std::is_same_v<T, std::string>> Do(const PropId& id, std::string& str, StreamT& w) { w.writeString(str); } static void Do(const PropId& id, std::string& str, atInt32 count, StreamT& w) { w.writeString(str, count); } template <class T, Endian DNAE> static std::enable_if_t<std::is_same_v<T, std::wstring>> Do(const PropId& id, std::wstring& str, StreamT& w) { Write<PropType::None>::Do<DNAE>(id, str, w); } template <Endian DNAE> static void Do(const PropId& id, std::wstring& str, atInt32 count, StreamT& w) { Write<PropType::None>::Do<DNAE>(id, str, count, w); } static void DoSeek(atInt64 amount, SeekOrigin whence, StreamT& w) { w.seek(amount, whence); } static void DoAlign(atInt64 amount, StreamT& w) { w.writeZeroTo((w.position() + amount - 1) / amount * amount); } }; #define __WRITE_S(type, endian) \ template <> \ template <> \ inline void Write<PropType::None>::Do<type, endian>(const PropId& id, type& var, Write::StreamT& w) #define __WRITE_WSTR_S(endian) \ template <> \ template <> \ inline void Write<PropType::None>::Do<std::wstring, endian>(const PropId& id, std::wstring& str, Write::StreamT& w) #define __WRITE_WSTRC_S(endian) \ template <> \ template <> \ inline void Write<PropType::None>::Do<endian>(const PropId& id, std::wstring& str, atInt32 count, Write::StreamT& w) __WRITE_S(bool, Endian::Big) { w.writeBool(var); } __WRITE_S(atInt8, Endian::Big) { w.writeByte(var); } __WRITE_S(atUint8, Endian::Big) { w.writeUByte(var); } __WRITE_S(atInt16, Endian::Big) { w.writeInt16Big(var); } __WRITE_S(atUint16, Endian::Big) { w.writeUint16Big(var); } __WRITE_S(atInt32, Endian::Big) { w.writeInt32Big(var); } __WRITE_S(atUint32, Endian::Big) { w.writeUint32Big(var); } __WRITE_S(atInt64, Endian::Big) { w.writeInt64Big(var); } __WRITE_S(atUint64, Endian::Big) { w.writeUint64Big(var); } __WRITE_S(float, Endian::Big) { w.writeFloatBig(var); } __WRITE_S(double, Endian::Big) { w.writeDoubleBig(var); } __WRITE_S(atVec2f, Endian::Big) { w.writeVec2fBig(var); } __WRITE_S(atVec2d, Endian::Big) { w.writeVec2dBig(var); } __WRITE_S(atVec3f, Endian::Big) { w.writeVec3fBig(var); } __WRITE_S(atVec3d, Endian::Big) { w.writeVec3dBig(var); } __WRITE_S(atVec4f, Endian::Big) { w.writeVec4fBig(var); } __WRITE_S(atVec4d, Endian::Big) { w.writeVec4dBig(var); } __WRITE_WSTR_S(Endian::Big) { w.writeWStringBig(str); } __WRITE_WSTRC_S(Endian::Big) { w.writeWStringBig(str, count); } __WRITE_S(bool, Endian::Little) { w.writeBool(var); } __WRITE_S(atInt8, Endian::Little) { w.writeByte(var); } __WRITE_S(atUint8, Endian::Little) { w.writeUByte(var); } __WRITE_S(atInt16, Endian::Little) { w.writeInt16Little(var); } __WRITE_S(atUint16, Endian::Little) { w.writeUint16Little(var); } __WRITE_S(atInt32, Endian::Little) { w.writeInt32Little(var); } __WRITE_S(atUint32, Endian::Little) { w.writeUint32Little(var); } __WRITE_S(atInt64, Endian::Little) { w.writeInt64Little(var); } __WRITE_S(atUint64, Endian::Little) { w.writeUint64Little(var); } __WRITE_S(float, Endian::Little) { w.writeFloatLittle(var); } __WRITE_S(double, Endian::Little) { w.writeDoubleLittle(var); } __WRITE_S(atVec2f, Endian::Little) { w.writeVec2fLittle(var); } __WRITE_S(atVec2d, Endian::Little) { w.writeVec2dLittle(var); } __WRITE_S(atVec3f, Endian::Little) { w.writeVec3fLittle(var); } __WRITE_S(atVec3d, Endian::Little) { w.writeVec3dLittle(var); } __WRITE_S(atVec4f, Endian::Little) { w.writeVec4fLittle(var); } __WRITE_S(atVec4d, Endian::Little) { w.writeVec4dLittle(var); } __WRITE_WSTR_S(Endian::Little) { w.writeWStringLittle(str); } __WRITE_WSTRC_S(Endian::Little) { w.writeWStringLittle(str, count); } template <PropType PropOp> struct ReadYaml { using PropT = std::conditional_t<PropOp == PropType::CRC64, uint64_t, uint32_t>; using StreamT = YAMLDocReader; template <class T, Endian DNAE> static std::enable_if_t<std::is_enum_v<T>> Do(const PropId& id, T& var, StreamT& r) { using PODType = std::underlying_type_t<T>; ReadYaml<PropType::None>::Do<PODType, DNAE>(id, *reinterpret_cast<PODType*>(&var), r); } template <class T, Endian DNAE> static std::enable_if_t<__IsPODType_v<T>> Do(const PropId& id, T& var, StreamT& r) { using CastT = __CastPODType<T>; ReadYaml<PropType::None>::Do<CastT, DNAE>(id, static_cast<CastT&>(var), r); } template <class T, Endian DNAE> static std::enable_if_t<__IsDNARecord_v<T>> Do(const PropId& id, T& var, StreamT& r) { if (auto rec = r.enterSubRecord(id.name)) var.template Enumerate<ReadYaml<PropOp>>(r); } template <class T, Endian DNAE> static std::enable_if_t<std::is_array_v<T>> Do(const PropId& id, T& var, StreamT& r) { size_t _count; if (auto __v = r.enterSubVector(id.name, _count)) for (size_t i = 0; i < _count && i < std::extent_v<T>; ++i) ReadYaml<PropOp>::Do<std::remove_reference_t<decltype(var[i])>, DNAE>({}, var[i], r); } template <class T, Endian DNAE> static void DoSize(const PropId& id, T& var, StreamT& s) { /* Squelch size field access */ } template <class T, class S, Endian DNAE> static std::enable_if_t<!std::is_same_v<T, bool>> Do(const PropId& id, std::vector<T>& vector, const S& count, StreamT& r) { size_t _count; vector.clear(); if (auto __v = r.enterSubVector(id.name, _count)) { vector.reserve(_count); for (size_t i = 0; i < _count; ++i) { vector.emplace_back(); ReadYaml<PropOp>::Do<T, DNAE>({}, vector.back(), r); } } /* Horrible reference abuse (but it works) */ const_cast<S&>(count) = vector.size(); } template <class T, class S, Endian DNAE> static std::enable_if_t<std::is_same_v<T, bool>> Do(const PropId& id, std::vector<T>& vector, const S& count, StreamT& r) { /* libc++ specializes vector<bool> as a bitstream */ size_t _count; vector.clear(); if (auto __v = r.enterSubVector(id.name, _count)) { vector.reserve(_count); for (size_t i = 0; i < _count; ++i) vector.push_back(r.readBool()); } /* Horrible reference abuse (but it works) */ const_cast<S&>(count) = vector.size(); } static void Do(const PropId& id, std::unique_ptr<atUint8[]>& buf, size_t count, StreamT& r) { buf = r.readUBytes(id.name); } template <class T, Endian DNAE> static std::enable_if_t<std::is_same_v<T, std::string>> Do(const PropId& id, T& str, StreamT& r) { str = r.readString(id.name); } static void Do(const PropId& id, std::string& str, atInt32 count, StreamT& r) { str = r.readString(id.name); } template <class T, Endian DNAE> static std::enable_if_t<std::is_same_v<T, std::wstring>> Do(const PropId& id, T& str, StreamT& r) { str = r.readWString(id.name); } template <Endian DNAE> static void Do(const PropId& id, std::wstring& str, atInt32 count, StreamT& r) { str = r.readWString(id.name); } static void DoSeek(atInt64 amount, SeekOrigin whence, StreamT& r) {} static void DoAlign(atInt64 amount, StreamT& r) {} }; #define __READ_YAML_S(type, endian) \ template <> \ template <> \ inline void ReadYaml<PropType::None>::Do<type, endian>(const PropId& id, type& var, ReadYaml::StreamT& r) __READ_YAML_S(bool, Endian::Big) { var = r.readBool(id.name); } __READ_YAML_S(atInt8, Endian::Big) { var = r.readByte(id.name); } __READ_YAML_S(atUint8, Endian::Big) { var = r.readUByte(id.name); } __READ_YAML_S(atInt16, Endian::Big) { var = r.readInt16(id.name); } __READ_YAML_S(atUint16, Endian::Big) { var = r.readUint16(id.name); } __READ_YAML_S(atInt32, Endian::Big) { var = r.readInt32(id.name); } __READ_YAML_S(atUint32, Endian::Big) { var = r.readUint32(id.name); } __READ_YAML_S(atInt64, Endian::Big) { var = r.readInt64(id.name); } __READ_YAML_S(atUint64, Endian::Big) { var = r.readUint64(id.name); } __READ_YAML_S(float, Endian::Big) { var = r.readFloat(id.name); } __READ_YAML_S(double, Endian::Big) { var = r.readDouble(id.name); } __READ_YAML_S(atVec2f, Endian::Big) { var = r.readVec2f(id.name); } __READ_YAML_S(atVec2d, Endian::Big) { var = r.readVec2d(id.name); } __READ_YAML_S(atVec3f, Endian::Big) { var = r.readVec3f(id.name); } __READ_YAML_S(atVec3d, Endian::Big) { var = r.readVec3d(id.name); } __READ_YAML_S(atVec4f, Endian::Big) { var = r.readVec4f(id.name); } __READ_YAML_S(atVec4d, Endian::Big) { var = r.readVec4d(id.name); } __READ_YAML_S(bool, Endian::Little) { var = r.readBool(id.name); } __READ_YAML_S(atInt8, Endian::Little) { var = r.readByte(id.name); } __READ_YAML_S(atUint8, Endian::Little) { var = r.readUByte(id.name); } __READ_YAML_S(atInt16, Endian::Little) { var = r.readInt16(id.name); } __READ_YAML_S(atUint16, Endian::Little) { var = r.readUint16(id.name); } __READ_YAML_S(atInt32, Endian::Little) { var = r.readInt32(id.name); } __READ_YAML_S(atUint32, Endian::Little) { var = r.readUint32(id.name); } __READ_YAML_S(atInt64, Endian::Little) { var = r.readInt64(id.name); } __READ_YAML_S(atUint64, Endian::Little) { var = r.readUint64(id.name); } __READ_YAML_S(float, Endian::Little) { var = r.readFloat(id.name); } __READ_YAML_S(double, Endian::Little) { var = r.readDouble(id.name); } __READ_YAML_S(atVec2f, Endian::Little) { var = r.readVec2f(id.name); } __READ_YAML_S(atVec2d, Endian::Little) { var = r.readVec2d(id.name); } __READ_YAML_S(atVec3f, Endian::Little) { var = r.readVec3f(id.name); } __READ_YAML_S(atVec3d, Endian::Little) { var = r.readVec3d(id.name); } __READ_YAML_S(atVec4f, Endian::Little) { var = r.readVec4f(id.name); } __READ_YAML_S(atVec4d, Endian::Little) { var = r.readVec4d(id.name); } template <PropType PropOp> struct WriteYaml { using PropT = std::conditional_t<PropOp == PropType::CRC64, uint64_t, uint32_t>; using StreamT = YAMLDocWriter; template <class T, Endian DNAE> static std::enable_if_t<std::is_enum_v<T>> Do(const PropId& id, T& var, StreamT& w) { using PODType = std::underlying_type_t<T>; WriteYaml<PropType::None>::Do<PODType, DNAE>(id, *reinterpret_cast<PODType*>(&var), w); } template <class T, Endian DNAE> static std::enable_if_t<__IsPODType_v<T>> Do(const PropId& id, T& var, StreamT& w) { using CastT = __CastPODType<T>; WriteYaml<PropType::None>::Do<CastT, DNAE>(id, static_cast<CastT&>(const_cast<std::remove_cv_t<T>&>(var)), w); } template <class T, Endian DNAE> static std::enable_if_t<__IsDNARecord_v<T>> Do(const PropId& id, T& var, StreamT& w) { if (auto rec = w.enterSubRecord(id.name)) var.template Enumerate<WriteYaml<PropOp>>(w); } template <class T, Endian DNAE> static std::enable_if_t<std::is_array_v<T>> Do(const PropId& id, T& var, StreamT& w) { if (auto __v = w.enterSubVector(id.name)) for (auto& v : var) WriteYaml<PropOp>::Do<std::remove_reference_t<decltype(v)>, DNAE>({}, v, w); } template <class T, Endian DNAE> static void DoSize(const PropId& id, T& var, StreamT& s) { /* Squelch size field access */ } template <class T, class S, Endian DNAE> static std::enable_if_t<!std::is_same_v<T, bool>> Do(const PropId& id, std::vector<T>& vector, const S& count, StreamT& w) { if (auto __v = w.enterSubVector(id.name)) for (T& v : vector) WriteYaml<PropOp>::Do<T, DNAE>(id, v, w); } template <class T, class S, Endian DNAE> static std::enable_if_t<std::is_same_v<T, bool>> Do(const PropId& id, std::vector<T>& vector, const S& count, StreamT& w) { /* libc++ specializes vector<bool> as a bitstream */ if (auto __v = w.enterSubVector(id.name)) for (const T& v : vector) w.writeBool(v); } static void Do(const PropId& id, std::unique_ptr<atUint8[]>& buf, size_t count, StreamT& w) { w.writeUBytes(id.name, buf, count); } template <class T, Endian DNAE> static std::enable_if_t<std::is_same_v<T, std::string>> Do(const PropId& id, T& str, StreamT& w) { w.writeString(id.name, str); } static void Do(const PropId& id, std::string& str, atInt32 count, StreamT& w) { w.writeString(id.name, str); } template <class T, Endian DNAE> static std::enable_if_t<std::is_same_v<T, std::wstring>> Do(const PropId& id, T& str, StreamT& w) { w.writeWString(id.name, str); } template <Endian DNAE> static void Do(const PropId& id, std::wstring& str, atInt32 count, StreamT& w) { w.writeWString(id.name, str); } static void DoSeek(atInt64 amount, SeekOrigin whence, StreamT& w) {} static void DoAlign(atInt64 amount, StreamT& w) {} }; #define __WRITE_YAML_S(type, endian) \ template <> \ template <> \ inline void WriteYaml<PropType::None>::Do<type, endian>(const PropId& id, type& var, WriteYaml::StreamT& w) __WRITE_YAML_S(bool, Endian::Big) { w.writeBool(id.name, var); } __WRITE_YAML_S(atInt8, Endian::Big) { w.writeByte(id.name, var); } __WRITE_YAML_S(atUint8, Endian::Big) { w.writeUByte(id.name, var); } __WRITE_YAML_S(atInt16, Endian::Big) { w.writeInt16(id.name, var); } __WRITE_YAML_S(atUint16, Endian::Big) { w.writeUint16(id.name, var); } __WRITE_YAML_S(atInt32, Endian::Big) { w.writeInt32(id.name, var); } __WRITE_YAML_S(atUint32, Endian::Big) { w.writeUint32(id.name, var); } __WRITE_YAML_S(atInt64, Endian::Big) { w.writeInt64(id.name, var); } __WRITE_YAML_S(atUint64, Endian::Big) { w.writeUint64(id.name, var); } __WRITE_YAML_S(float, Endian::Big) { w.writeFloat(id.name, var); } __WRITE_YAML_S(double, Endian::Big) { w.writeDouble(id.name, var); } __WRITE_YAML_S(atVec2f, Endian::Big) { w.writeVec2f(id.name, var); } __WRITE_YAML_S(atVec2d, Endian::Big) { w.writeVec2d(id.name, var); } __WRITE_YAML_S(atVec3f, Endian::Big) { w.writeVec3f(id.name, var); } __WRITE_YAML_S(atVec3d, Endian::Big) { w.writeVec3d(id.name, var); } __WRITE_YAML_S(atVec4f, Endian::Big) { w.writeVec4f(id.name, var); } __WRITE_YAML_S(atVec4d, Endian::Big) { w.writeVec4d(id.name, var); } __WRITE_YAML_S(bool, Endian::Little) { w.writeBool(id.name, var); } __WRITE_YAML_S(atInt8, Endian::Little) { w.writeByte(id.name, var); } __WRITE_YAML_S(atUint8, Endian::Little) { w.writeUByte(id.name, var); } __WRITE_YAML_S(atInt16, Endian::Little) { w.writeInt16(id.name, var); } __WRITE_YAML_S(atUint16, Endian::Little) { w.writeUint16(id.name, var); } __WRITE_YAML_S(atInt32, Endian::Little) { w.writeInt32(id.name, var); } __WRITE_YAML_S(atUint32, Endian::Little) { w.writeUint32(id.name, var); } __WRITE_YAML_S(atInt64, Endian::Little) { w.writeInt64(id.name, var); } __WRITE_YAML_S(atUint64, Endian::Little) { w.writeUint64(id.name, var); } __WRITE_YAML_S(float, Endian::Little) { w.writeFloat(id.name, var); } __WRITE_YAML_S(double, Endian::Little) { w.writeDouble(id.name, var); } __WRITE_YAML_S(atVec2f, Endian::Little) { w.writeVec2f(id.name, var); } __WRITE_YAML_S(atVec2d, Endian::Little) { w.writeVec2d(id.name, var); } __WRITE_YAML_S(atVec3f, Endian::Little) { w.writeVec3f(id.name, var); } __WRITE_YAML_S(atVec3d, Endian::Little) { w.writeVec3d(id.name, var); } __WRITE_YAML_S(atVec4f, Endian::Little) { w.writeVec4f(id.name, var); } __WRITE_YAML_S(atVec4d, Endian::Little) { w.writeVec4d(id.name, var); } template <class Op, class T, Endian DNAE> void __Do(const PropId& id, T& var, typename Op::StreamT& s) { Op::template Do<T, DNAE>(id, var, s); } template <class Op, class T, Endian DNAE> void __DoSize(const PropId& id, T& var, typename Op::StreamT& s) { Op::template DoSize<T, DNAE>(id, var, s); } template <class Op, class T, class S, Endian DNAE> void __Do(const PropId& id, std::vector<T>& vector, const S& count, typename Op::StreamT& s) { Op::template Do<T, S, DNAE>(id, vector, count, s); } template <class Op> void __Do(const PropId& id, std::unique_ptr<atUint8[]>& buf, size_t count, typename Op::StreamT& s) { Op::Do(id, buf, count, s); } template <class Op> void __Do(const PropId& id, std::string& str, atInt32 count, typename Op::StreamT& s) { Op::Do(id, str, count, s); } template <class Op, Endian DNAE> void __Do(const PropId& id, std::wstring& str, atInt32 count, typename Op::StreamT& s) { Op::template Do<DNAE>(id, str, count, s); } template <class Op> void __DoSeek(atInt64 delta, athena::SeekOrigin whence, typename Op::StreamT& s) { Op::DoSeek(delta, whence, s); } template <class Op> void __DoAlign(atInt64 amount, typename Op::StreamT& s) { Op::DoAlign(amount, s); } template <class T> void __Read(T& obj, athena::io::IStreamReader& r) { __Do<Read<PropType::None>, T, T::DNAEndian>({}, obj, r); } template <class T> void __Write(const T& obj, athena::io::IStreamWriter& w) { __Do<Write<PropType::None>, T, T::DNAEndian>({}, const_cast<T&>(obj), w); } template <class T> void __BinarySize(const T& obj, size_t& s) { __Do<BinarySize<PropType::None>, T, T::DNAEndian>({}, const_cast<T&>(obj), s); } template <class T> void __PropCount(const T& obj, size_t& s) { const_cast<T&>(obj).template Enumerate<PropCount<PropType::None>>(s); } template <class T> void __ReadYaml(T& obj, athena::io::YAMLDocReader& r) { obj.template Enumerate<ReadYaml<PropType::None>>(r); } template <class T> void __WriteYaml(const T& obj, athena::io::YAMLDocWriter& w) { const_cast<T&>(obj).template Enumerate<WriteYaml<PropType::None>>(w); } template <class T> void __ReadProp(T& obj, athena::io::IStreamReader& r) { /* Read root 0xffffffff hash (hashed empty string) */ T::DNAEndian == Endian::Big ? r.readUint32Big() : r.readUint32Little(); atInt64 size = T::DNAEndian == Endian::Big ? r.readUint16Big() : r.readUint16Little(); atInt64 start = r.position(); __Do<Read<PropType::CRC32>, T, T::DNAEndian>({}, obj, r); atInt64 actualRead = r.position() - start; if (actualRead != size) r.seek(size - actualRead); } template <class T> void __WriteProp(const T& obj, athena::io::IStreamWriter& w) { __Do<Write<PropType::CRC32>, T, T::DNAEndian>({}, const_cast<T&>(obj), w); } template <class T> void __BinarySizeProp(const T& obj, size_t& s) { __Do<BinarySize<PropType::CRC32>, T, T::DNAEndian>({}, const_cast<T&>(obj), s); } template <class T> void __ReadProp64(T& obj, athena::io::IStreamReader& r) { /* Read root 0x0 hash (hashed empty string) */ T::DNAEndian == Endian::Big ? r.readUint64Big() : r.readUint64Little(); atInt64 size = T::DNAEndian == Endian::Big ? r.readUint16Big() : r.readUint16Little(); atInt64 start = r.position(); __Do<Read<PropType::CRC64>, T, T::DNAEndian>({}, obj, r); atInt64 actualRead = r.position() - start; if (actualRead != size) r.seek(size - actualRead); } template <class T> void __WriteProp64(const T& obj, athena::io::IStreamWriter& w) { __Do<Write<PropType::CRC64>, T, T::DNAEndian>({}, const_cast<T&>(obj), w); } template <class T> void __BinarySizeProp64(const T& obj, size_t& s) { __Do<BinarySize<PropType::CRC64>, T, T::DNAEndian>({}, const_cast<T&>(obj), s); } } // namespace athena::io #define AT_DECL_DNA_DO \ template <class Op, athena::Endian DNAE = DNAEndian, class T> \ void Do(const athena::io::PropId& _id, T& var, typename Op::StreamT& s) { \ athena::io::__Do<Op, T, DNAE>(_id, var, s); \ } \ template <class Op, athena::Endian DNAE = DNAEndian, class T> \ void DoSize(const athena::io::PropId& _id, T& var, typename Op::StreamT& s) { \ athena::io::__DoSize<Op, T, DNAE>(_id, var, s); \ } \ template <class Op, athena::Endian DNAE = DNAEndian, class T, class S> \ void Do(const athena::io::PropId& _id, std::vector<T>& var, const S& count, typename Op::StreamT& s) { \ athena::io::__Do<Op, T, S, DNAE>(_id, var, count, s); \ } \ template <class Op> \ void Do(const athena::io::PropId& _id, std::unique_ptr<atUint8[]>& buf, size_t count, typename Op::StreamT& s) { \ athena::io::__Do<Op>(_id, buf, count, s); \ } \ template <class Op> \ void Do(const athena::io::PropId& _id, std::string& str, atInt32 count, typename Op::StreamT& s) { \ athena::io::__Do<Op>(_id, str, count, s); \ } \ template <class Op, athena::Endian DNAE = DNAEndian> \ void Do(const athena::io::PropId& _id, std::wstring& str, atInt32 count, typename Op::StreamT& s) { \ athena::io::__Do<Op, DNAE>(_id, str, count, s); \ } \ template <class Op> \ void DoSeek(atInt64 delta, athena::SeekOrigin whence, typename Op::StreamT& s) { \ athena::io::__DoSeek<Op>(delta, whence, s); \ } \ template <class Op> \ void DoAlign(atInt64 amount, typename Op::StreamT& s) { \ athena::io::__DoAlign<Op>(amount, s); \ } \ template <class Op> \ void Enumerate(typename Op::StreamT& s); \ static std::string_view DNAType(); #define AT_DECL_DNA \ AT_DECL_DNA_DO \ void read(athena::io::IStreamReader& r) { athena::io::__Read(*this, r); } \ void write(athena::io::IStreamWriter& w) const { athena::io::__Write(*this, w); } \ void binarySize(size_t& s) const { athena::io::__BinarySize(*this, s); } #define AT_DECL_DNA_YAML \ AT_DECL_DNA \ void read(athena::io::YAMLDocReader& r) { athena::io::__ReadYaml(*this, r); } \ void write(athena::io::YAMLDocWriter& w) const { athena::io::__WriteYaml(*this, w); } #define AT_DECL_EXPLICIT_DNA \ AT_DECL_DNA \ Delete __d; #define AT_DECL_EXPLICIT_DNAV \ AT_DECL_DNAV \ Delete __d; #define AT_DECL_EXPLICIT_DNAV_NO_TYPE \ AT_DECL_DNAV_NO_TYPE \ Delete __d; #define AT_DECL_EXPLICIT_DNA_YAML \ AT_DECL_DNA_YAML \ Delete __d; #define AT_DECL_EXPLICIT_DNA_YAMLV \ AT_DECL_DNA_YAMLV \ Delete __d; #define AT_DECL_EXPLICIT_DNA_YAMLV_NO_TYPE \ AT_DECL_DNA_YAMLV_NO_TYPE \ Delete __d; #define AT_DECL_DNAV \ AT_DECL_DNA_DO \ void read(athena::io::IStreamReader& r) override { athena::io::__Read(*this, r); } \ void write(athena::io::IStreamWriter& w) const override { athena::io::__Write(*this, w); } \ void binarySize(size_t& s) const override { athena::io::__BinarySize(*this, s); } \ std::string_view DNATypeV() const override { return DNAType(); } #define AT_DECL_DNAV_NO_TYPE \ AT_DECL_DNA_DO \ void read(athena::io::IStreamReader& r) override { athena::io::__Read(*this, r); } \ void write(athena::io::IStreamWriter& w) const override { athena::io::__Write(*this, w); } \ void binarySize(size_t& s) const override { athena::io::__BinarySize(*this, s); } #define AT_DECL_DNA_YAMLV \ AT_DECL_DNAV \ void read(athena::io::YAMLDocReader& r) override { athena::io::__ReadYaml(*this, r); } \ void write(athena::io::YAMLDocWriter& w) const override { athena::io::__WriteYaml(*this, w); } #define AT_DECL_DNA_YAMLV_NO_TYPE \ AT_DECL_DNAV_NO_TYPE \ void read(athena::io::YAMLDocReader& r) override { athena::io::__ReadYaml(*this, r); } \ void write(athena::io::YAMLDocWriter& w) const override { athena::io::__WriteYaml(*this, w); } #define AT_SPECIALIZE_DNA(...) \ template void __VA_ARGS__::Enumerate<athena::io::Read<athena::io::PropType::None>>( \ athena::io::Read<athena::io::PropType::None>::StreamT & s); \ template void __VA_ARGS__::Enumerate<athena::io::Write<athena::io::PropType::None>>( \ athena::io::Write<athena::io::PropType::None>::StreamT & s); \ template void __VA_ARGS__::Enumerate<athena::io::BinarySize<athena::io::PropType::None>>( \ athena::io::BinarySize<athena::io::PropType::None>::StreamT & s); #define AT_SPECIALIZE_DNA_YAML(...) \ AT_SPECIALIZE_DNA(__VA_ARGS__) \ template void __VA_ARGS__::Enumerate<athena::io::ReadYaml<athena::io::PropType::None>>( \ athena::io::ReadYaml<athena::io::PropType::None>::StreamT & s); \ template void __VA_ARGS__::Enumerate<athena::io::WriteYaml<athena::io::PropType::None>>( \ athena::io::WriteYaml<athena::io::PropType::None>::StreamT & s); #define AT_DECL_PROPDNA \ template <class Op, athena::Endian DNAE = DNAEndian, class T> \ void Do(const athena::io::PropId& _id, T& var, typename Op::StreamT& s) { \ athena::io::__Do<Op, T, DNAE>(_id, var, s); \ } \ template <class Op, athena::Endian DNAE = DNAEndian, class T> \ void DoSize(const athena::io::PropId& _id, T& var, typename Op::StreamT& s) { \ athena::io::__DoSize<Op, T, DNAE>(_id, var, s); \ } \ template <class Op, athena::Endian DNAE = DNAEndian, class T, class S> \ void Do(const athena::io::PropId& _id, std::vector<T>& var, const S& count, typename Op::StreamT& s) { \ athena::io::__Do<Op, T, S, DNAE>(_id, var, count, s); \ } \ template <class Op> \ void Do(const athena::io::PropId& _id, std::unique_ptr<atUint8[]>& buf, size_t count, typename Op::StreamT& s) { \ athena::io::__Do<Op>(_id, buf, count, s); \ } \ template <class Op> \ void Do(const athena::io::PropId& _id, std::string& str, atInt32 count, typename Op::StreamT& s) { \ athena::io::__Do<Op>(_id, str, count, s); \ } \ template <class Op, athena::Endian DNAE = DNAEndian> \ void Do(const athena::io::PropId& _id, std::wstring& str, atInt32 count, typename Op::StreamT& s) { \ athena::io::__Do<Op, DNAE>(_id, str, count, s); \ } \ template <class Op> \ void DoSeek(atInt64 delta, athena::SeekOrigin whence, typename Op::StreamT& s) { \ athena::io::__DoSeek<Op>(delta, whence, s); \ } \ template <class Op> \ void DoAlign(atInt64 amount, typename Op::StreamT& s) { \ athena::io::__DoAlign<Op>(amount, s); \ } \ template <class Op> \ void Enumerate(typename Op::StreamT& s); \ template <class Op> \ bool Lookup(uint64_t hash, typename Op::StreamT& s); \ static std::string_view DNAType(); \ void read(athena::io::IStreamReader& r) { athena::io::__Read(*this, r); } \ void write(athena::io::IStreamWriter& w) const { athena::io::__Write(*this, w); } \ void binarySize(size_t& s) const { athena::io::__BinarySize(*this, s); } \ void read(athena::io::YAMLDocReader& r) { athena::io::__ReadYaml(*this, r); } \ void write(athena::io::YAMLDocWriter& w) const { athena::io::__WriteYaml(*this, w); } \ void readProp(athena::io::IStreamReader& r) { athena::io::__ReadProp(*this, r); } \ void writeProp(athena::io::IStreamWriter& w) const { athena::io::__WriteProp(*this, w); } \ void binarySizeProp(size_t& s) const { athena::io::__BinarySizeProp(*this, s); } \ void propCount(size_t& s) const { athena::io::__PropCount(*this, s); } \ void readProp64(athena::io::IStreamReader& r) { athena::io::__ReadProp64(*this, r); } \ void writeProp64(athena::io::IStreamWriter& w) const { athena::io::__WriteProp64(*this, w); } \ void binarySizeProp64(size_t& s) const { athena::io::__BinarySizeProp64(*this, s); } #define AT_DECL_EXPLICIT_PROPDNA \ AT_DECL_PROPDNA \ Delete __d; #define AT_SPECIALIZE_PROPDNA(...) \ template void __VA_ARGS__::Enumerate<athena::io::Read<athena::io::PropType::None>>( \ athena::io::Read<athena::io::PropType::None>::StreamT & s); \ template void __VA_ARGS__::Enumerate<athena::io::Write<athena::io::PropType::None>>( \ athena::io::Write<athena::io::PropType::None>::StreamT & s); \ template void __VA_ARGS__::Enumerate<athena::io::BinarySize<athena::io::PropType::None>>( \ athena::io::BinarySize<athena::io::PropType::None>::StreamT & s); \ template void __VA_ARGS__::Enumerate<athena::io::ReadYaml<athena::io::PropType::None>>( \ athena::io::ReadYaml<athena::io::PropType::None>::StreamT & s); \ template void __VA_ARGS__::Enumerate<athena::io::WriteYaml<athena::io::PropType::None>>( \ athena::io::WriteYaml<athena::io::PropType::None>::StreamT & s); \ template bool __VA_ARGS__::Lookup<athena::io::Read<athena::io::PropType::CRC32>>( \ uint64_t hash, athena::io::Read<athena::io::PropType::CRC32>::StreamT & s); \ template void __VA_ARGS__::Enumerate<athena::io::Read<athena::io::PropType::CRC32>>( \ athena::io::Read<athena::io::PropType::CRC32>::StreamT & s); \ template bool __VA_ARGS__::Lookup<athena::io::Write<athena::io::PropType::CRC32>>( \ uint64_t hash, athena::io::Write<athena::io::PropType::CRC32>::StreamT & s); \ template void __VA_ARGS__::Enumerate<athena::io::Write<athena::io::PropType::CRC32>>( \ athena::io::Write<athena::io::PropType::CRC32>::StreamT & s); \ template bool __VA_ARGS__::Lookup<athena::io::BinarySize<athena::io::PropType::CRC32>>( \ uint64_t hash, athena::io::BinarySize<athena::io::PropType::CRC32>::StreamT & s); \ template void __VA_ARGS__::Enumerate<athena::io::BinarySize<athena::io::PropType::CRC32>>( \ athena::io::BinarySize<athena::io::PropType::CRC32>::StreamT & s); \ template bool __VA_ARGS__::Lookup<athena::io::PropCount<athena::io::PropType::CRC32>>( \ uint64_t hash, athena::io::PropCount<athena::io::PropType::CRC32>::StreamT & s); \ template void __VA_ARGS__::Enumerate<athena::io::PropCount<athena::io::PropType::CRC32>>( \ athena::io::PropCount<athena::io::PropType::CRC32>::StreamT & s); \ template bool __VA_ARGS__::Lookup<athena::io::ReadYaml<athena::io::PropType::CRC32>>( \ uint64_t hash, athena::io::ReadYaml<athena::io::PropType::CRC32>::StreamT & s); \ template void __VA_ARGS__::Enumerate<athena::io::ReadYaml<athena::io::PropType::CRC32>>( \ athena::io::ReadYaml<athena::io::PropType::CRC32>::StreamT & s); \ template bool __VA_ARGS__::Lookup<athena::io::WriteYaml<athena::io::PropType::CRC32>>( \ uint64_t hash, athena::io::WriteYaml<athena::io::PropType::CRC32>::StreamT & s); \ template void __VA_ARGS__::Enumerate<athena::io::WriteYaml<athena::io::PropType::CRC32>>( \ athena::io::WriteYaml<athena::io::PropType::CRC32>::StreamT & s); \ template bool __VA_ARGS__::Lookup<athena::io::Read<athena::io::PropType::CRC64>>( \ uint64_t hash, athena::io::Read<athena::io::PropType::CRC64>::StreamT & s); \ template void __VA_ARGS__::Enumerate<athena::io::Read<athena::io::PropType::CRC64>>( \ athena::io::Read<athena::io::PropType::CRC64>::StreamT & s); \ template bool __VA_ARGS__::Lookup<athena::io::Write<athena::io::PropType::CRC64>>( \ uint64_t hash, athena::io::Write<athena::io::PropType::CRC64>::StreamT & s); \ template void __VA_ARGS__::Enumerate<athena::io::Write<athena::io::PropType::CRC64>>( \ athena::io::Write<athena::io::PropType::CRC64>::StreamT & s); \ template bool __VA_ARGS__::Lookup<athena::io::BinarySize<athena::io::PropType::CRC64>>( \ uint64_t hash, athena::io::BinarySize<athena::io::PropType::CRC64>::StreamT & s); \ template void __VA_ARGS__::Enumerate<athena::io::BinarySize<athena::io::PropType::CRC64>>( \ athena::io::BinarySize<athena::io::PropType::CRC64>::StreamT & s); \ template bool __VA_ARGS__::Lookup<athena::io::PropCount<athena::io::PropType::CRC64>>( \ uint64_t hash, athena::io::PropCount<athena::io::PropType::CRC64>::StreamT & s); \ template void __VA_ARGS__::Enumerate<athena::io::PropCount<athena::io::PropType::CRC64>>( \ athena::io::PropCount<athena::io::PropType::CRC64>::StreamT & s); \ template bool __VA_ARGS__::Lookup<athena::io::ReadYaml<athena::io::PropType::CRC64>>( \ uint64_t hash, athena::io::ReadYaml<athena::io::PropType::CRC64>::StreamT & s); \ template void __VA_ARGS__::Enumerate<athena::io::ReadYaml<athena::io::PropType::CRC64>>( \ athena::io::ReadYaml<athena::io::PropType::CRC64>::StreamT & s); \ template bool __VA_ARGS__::Lookup<athena::io::WriteYaml<athena::io::PropType::CRC64>>( \ uint64_t hash, athena::io::WriteYaml<athena::io::PropType::CRC64>::StreamT & s); \ template void __VA_ARGS__::Enumerate<athena::io::WriteYaml<athena::io::PropType::CRC64>>( \ athena::io::WriteYaml<athena::io::PropType::CRC64>::StreamT & s); #define AT_SUBDECL_DNA \ void _read(athena::io::IStreamReader& r); \ void _write(athena::io::IStreamWriter& w) const; \ void _binarySize(size_t& s) const; \ void _read(athena::io::YAMLDocReader& r); \ void _write(athena::io::YAMLDocWriter& w) const; #define AT_SUBDECL_DNA_YAML \ AT_SUBDECL_DNA \ void _read(athena::io::YAMLDocReader& r); \ void _write(athena::io::YAMLDocWriter& w) const; #define AT_SUBSPECIALIZE_DNA(...) \ template <> \ template <> \ void __VA_ARGS__::Enumerate<athena::io::DNA<athena::Endian::Big>::BinarySize>(typename BinarySize::StreamT & s) { \ _binarySize(s); \ } \ template <> \ template <> \ void __VA_ARGS__::Enumerate<athena::io::DNA<athena::Endian::Big>::Read>(typename Read::StreamT & r) { \ _read(r); \ } \ template <> \ template <> \ void __VA_ARGS__::Enumerate<athena::io::DNA<athena::Endian::Big>::Write>(typename Write::StreamT & w) { \ _write(w); \ } #define AT_SUBSPECIALIZE_DNA_YAML(...) \ template <> \ template <> \ void __VA_ARGS__::Enumerate<athena::io::DNA<athena::Endian::Big>::ReadYaml>(typename ReadYaml::StreamT & r) { \ _read(r); \ } \ template <> \ template <> \ void __VA_ARGS__::Enumerate<athena::io::DNA<athena::Endian::Big>::WriteYaml>(typename WriteYaml::StreamT & w) { \ _write(w); \ } \ AT_SUBSPECIALIZE_DNA(__VA_ARGS__)
60.264231
120
0.508438
encounter
ba51165e96451b70f16f2cf07ad03e27bab61119
521
cpp
C++
01-Arrays/containsWater.cpp
codewithdev/Amazon-SDE-Test-Series-
707cf1665f4798551d9e073fac273565b7407e1c
[ "Apache-2.0" ]
1
2020-07-18T11:08:27.000Z
2020-07-18T11:08:27.000Z
01-Arrays/containsWater.cpp
codewithdev/Amazon-SDE-Test-Series-
707cf1665f4798551d9e073fac273565b7407e1c
[ "Apache-2.0" ]
null
null
null
01-Arrays/containsWater.cpp
codewithdev/Amazon-SDE-Test-Series-
707cf1665f4798551d9e073fac273565b7407e1c
[ "Apache-2.0" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int maxArea(int *arr,int n); long long maxArea(long long a[], int n){ int i=0; int j=n-1; int res=0; while(i<j){ int curr=0; if(a[i]<=a[j]){ curr= (j-i)*a[i]; i++; } else{ curr= (j-i)*a[j]; j--; } if(curr>res){ res= curr; } if(i==j){ break; } } return res; } int main(){ int t; cin>>t; while(t--){ int n; cin>>n; long long arr[n]; for(int i=0;i<n;i++){ cin>>arr[i]; } cout<<maxArea(arr,n)<<endl; } return 0; }
12.707317
40
0.50096
codewithdev
ba5302c7f4eecfcee55261c95723e940e9000770
1,285
cpp
C++
rice/VM.cpp
jameskilton/rice
8f9093d758aa15ded2c112f6d3e3537cc968477d
[ "BSD-2-Clause" ]
11
2015-02-09T12:13:45.000Z
2019-11-25T01:14:31.000Z
rice/VM.cpp
jameskilton/rice
8f9093d758aa15ded2c112f6d3e3537cc968477d
[ "BSD-2-Clause" ]
3
2016-12-26T19:31:29.000Z
2021-04-13T12:32:58.000Z
rice/VM.cpp
jameskilton/rice
8f9093d758aa15ded2c112f6d3e3537cc968477d
[ "BSD-2-Clause" ]
2
2019-11-25T01:14:35.000Z
2021-09-29T04:57:36.000Z
#include "VM.hpp" #include "detail/ruby.hpp" #include "detail/env.hpp" #include "detail/ruby_version_code.hpp" #include <stdexcept> Rice::VM:: VM(char * app_name) { init_stack(); init(1, &app_name); } Rice::VM:: VM(int argc, char * argv[]) { init_stack(); init(argc, argv); } Rice::VM:: VM(std::vector<const char *> const & args) { check_not_initialized(); init_stack(); init(args.size(), const_cast<char * *>(&args[0])); } Rice::VM:: ~VM() { init_stack(); } #if RICE__RUBY_VERSION_CODE < 186 extern "C" void Init_stack(VALUE *); #endif void Rice::VM:: init_stack() { #if RICE__RUBY_VERSION_CODE >= 186 RUBY_INIT_STACK; #else VALUE v; Init_stack(&v); #endif } void Rice::VM:: run() { #if RICE__RUBY_VERSION_CODE >= 190 ruby_run_node(node_); #else ruby_run(); #endif } extern "C" { #if RICE__RUBY_VERSION_CODE < 190 RUBY_EXTERN VALUE * rb_gc_stack_start; #endif } void Rice::VM:: check_not_initialized() const { #if RICE__RUBY_VERSION_CODE < 190 if(rb_gc_stack_start) { throw std::runtime_error("Only one VM allowed per application"); } #endif // TODO: how to do this check on 1.9? } void Rice::VM:: init(int argc, char * argv[]) { ruby_init(); #if RICE__RUBY_VERSION_CODE >= 190 node_ = #endif ruby_options(argc, argv); }
13.817204
68
0.668482
jameskilton
ba534857fdd40cba6a9abbe782cae5f33ac2cbe0
1,181
hpp
C++
source/d3d12/d3d12_command_queue_downlevel.hpp
Moroque/reshade
bf1d263780a817130f6547dca0432dfe64c8beda
[ "BSD-3-Clause" ]
79
2021-02-21T08:39:36.000Z
2022-03-16T21:37:47.000Z
source/d3d12/d3d12_command_queue_downlevel.hpp
kingeric1992/reshade
22f57c10ea87ee83ceb7a5d0cb737cdfb02dedb2
[ "BSD-3-Clause" ]
null
null
null
source/d3d12/d3d12_command_queue_downlevel.hpp
kingeric1992/reshade
22f57c10ea87ee83ceb7a5d0cb737cdfb02dedb2
[ "BSD-3-Clause" ]
8
2021-04-14T21:37:23.000Z
2022-03-29T22:20:51.000Z
/* * Copyright (C) 2014 Patrick Mours. All rights reserved. * License: https://github.com/crosire/reshade#license */ #pragma once #include <D3D12Downlevel.h> #include "reshade_api_swapchain.hpp" struct D3D12CommandQueue; struct DECLSPEC_UUID("98CF28C0-F383-487E-A61E-3A638FEE29BD") D3D12CommandQueueDownlevel final : ID3D12CommandQueueDownlevel, public reshade::d3d12::swapchain_impl { D3D12CommandQueueDownlevel(D3D12CommandQueue *queue, ID3D12CommandQueueDownlevel *original); D3D12CommandQueueDownlevel(const D3D12CommandQueueDownlevel &) = delete; D3D12CommandQueueDownlevel &operator=(const D3D12CommandQueueDownlevel &) = delete; #pragma region IUnknown HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppvObj) override; ULONG STDMETHODCALLTYPE AddRef() override; ULONG STDMETHODCALLTYPE Release() override; #pragma endregion #pragma region ID3D12CommandQueueDownlevel HRESULT STDMETHODCALLTYPE Present(ID3D12GraphicsCommandList *pOpenCommandList, ID3D12Resource *pSourceTex2D, HWND hWindow, D3D12_DOWNLEVEL_PRESENT_FLAGS Flags) override; #pragma endregion ID3D12CommandQueueDownlevel *_orig; D3D12CommandQueue *const _parent_queue; };
36.90625
170
0.825572
Moroque
ba5537d04ccbf4bee80924d591f7bb6b33c3b034
24,801
cpp
C++
SystemTools/test/Backup_Fixture.cpp
mbeckh/SystemTools
7cd0784cb948fdedb87f20cdd0b0e9b3c983a740
[ "Apache-2.0" ]
null
null
null
SystemTools/test/Backup_Fixture.cpp
mbeckh/SystemTools
7cd0784cb948fdedb87f20cdd0b0e9b3c983a740
[ "Apache-2.0" ]
6
2020-07-09T22:47:16.000Z
2020-10-25T12:34:18.000Z
SystemTools/test/Backup_Fixture.cpp
mbeckh/SystemTools
7cd0784cb948fdedb87f20cdd0b0e9b3c983a740
[ "Apache-2.0" ]
null
null
null
/* Copyright 2020 Michael Beckh Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "Backup_Fixture.h" #include "BackupFileSystem_Fake.h" #include "BackupStrategy_Mock.h" #include "TestUtils.h" // IWYU pragma: keep #include "systools/Backup.h" #include "systools/BackupStrategy.h" #include "systools/DirectoryScanner.h" #include "systools/Path.h" #include <llamalog/llamalog.h> #include <m3c/lazy_string.h> #include <gtest/gtest-spi.h> // IWYU pragma: keep #include <detours_gmock.h> #include <algorithm> #include <exception> #include <memory> #include <new> #include <string_view> #include <unordered_map> #include <utility> namespace testing { Message& operator<<(Message& msg, const std::wstring_view& sv) { return msg << internal::String::ShowWideCString(sv.data()); } } // namespace testing namespace systools::test { namespace t = testing; namespace { #pragma warning(suppress : 4100) MATCHER_P2(PathWithExactFilename, path, filename, "") { static_assert(std::is_convertible_v<arg_type, const Path&>); static_assert(std::is_convertible_v<path_type, const Path&>); static_assert(std::is_convertible_v<filename_type, const std::wstring&>); return arg.GetParent() == path && arg.GetFilename().sv() == filename; } #define WIN32_FUNCTIONS(fn_) \ fn_(6, BOOL, WINAPI, AdjustTokenPrivileges, \ (HANDLE TokenHandle, BOOL DisableAllPrivileges, PTOKEN_PRIVILEGES NewState, DWORD BufferLength, PTOKEN_PRIVILEGES PreviousState, PDWORD ReturnLength), \ (TokenHandle, DisableAllPrivileges, NewState, BufferLength, PreviousState, ReturnLength), \ detours_gmock::SetLastErrorAndReturn(ERROR_SUCCESS, TRUE)); DTGM_DECLARE_API_MOCK(Win32, WIN32_FUNCTIONS); } // namespace // Keep the mock definitions out of the header. class Backup_Mock { public: void TearDown() { t::Mock::VerifyAndClearExpectations(&m_win32); DTGM_DETACH_API_MOCK(Win32); } private: DTGM_DEFINE_STRICT_API_MOCK(Win32, m_win32); }; Backup_Fixture::Backup_Fixture(bool enableRootScan) : m_src(m_srcVolume) , m_ref(m_targetVolume / L"ref") , m_dst(m_targetVolume / L"dst") , m_root(Root()) , m_pMock(new t::NiceMock<Backup_Mock>()) { m_root.src().ref().dst().enablePathFunctions(true); if (enableRootScan) { m_root.enableScan(); } m_root.build(); } Backup_Fixture::~Backup_Fixture() { delete m_pMock; } void Backup_Fixture::SetUp() { ON_CALL(m_strategy, Exists(t::_)) .WillByDefault(t::Invoke(&m_fileSystem, &BackupFileSystem_Fake::Exists)); ON_CALL(m_strategy, IsDirectory(t::_)) .WillByDefault(t::Invoke(&m_fileSystem, &BackupFileSystem_Fake::IsDirectory)); ON_CALL(m_strategy, Compare(t::_, t::_, t::_)) .WillByDefault(t::WithArgs<0, 1>(t::Invoke(&m_fileSystem, &BackupFileSystem_Fake::Compare))); ON_CALL(m_strategy, CreateDirectory(t::_, t::_, t::_)) .WillByDefault(t::Invoke(&m_fileSystem, &BackupFileSystem_Fake::CreateDirectory)); ON_CALL(m_strategy, CreateDirectoryRecursive(t::_)) .WillByDefault(t::Invoke(&m_fileSystem, &BackupFileSystem_Fake::CreateDirectoryRecursive)); ON_CALL(m_strategy, SetAttributes(t::_, t::_)) .WillByDefault(t::Invoke(&m_fileSystem, &BackupFileSystem_Fake::SetAttributes)); ON_CALL(m_strategy, SetSecurity(t::_, t::_)) .WillByDefault(t::Invoke(&m_fileSystem, &BackupFileSystem_Fake::SetSecurity)); ON_CALL(m_strategy, Rename(t::_, t::_)) .WillByDefault(t::Invoke(&m_fileSystem, &BackupFileSystem_Fake::Rename)); ON_CALL(m_strategy, Copy(t::_, t::_)) .WillByDefault(t::Invoke(&m_fileSystem, &BackupFileSystem_Fake::Copy)); ON_CALL(m_strategy, CreateHardLink(t::_, t::_)) .WillByDefault(t::Invoke(&m_fileSystem, &BackupFileSystem_Fake::CreateHardLink)); ON_CALL(m_strategy, Delete(t::_)) .WillByDefault(t::Invoke(&m_fileSystem, &BackupFileSystem_Fake::Delete)); ON_CALL(m_strategy, Scan(t::_, t::_, t::_, t::_, t::_, t::_)) .WillByDefault(t::WithArgs<0, 2, 3, 4, 5>(t::Invoke(&m_fileSystem, &BackupFileSystem_Fake::Scan))); EXPECT_CALL(m_strategy, WaitForScan(t::_)) .Times(t::AnyNumber()); } void Backup_Fixture::TearDown() { m_pMock->TearDown(); } void Backup_Fixture::VerifyFileSystem(const std::vector<Path>& backupFolders, const std::unordered_map<Path, BackupFileSystem_Fake::Entry>& before, const std::unordered_map<Path, BackupFileSystem_Fake::Entry>& after) const { std::vector<Path> dstBackup; dstBackup.reserve(backupFolders.size()); for (const Path& path : backupFolders) { dstBackup.push_back(m_dst / path.sv().substr(m_src.size())); } std::unordered_map<Path, BackupFileSystem_Fake::Entry> srcBefore; srcBefore.max_load_factor(0.75f); srcBefore.reserve(before.size() / 2); std::unordered_map<Path, BackupFileSystem_Fake::Entry> refBefore; refBefore.max_load_factor(0.75f); refBefore.reserve(before.size() / 2); std::unordered_map<Path, BackupFileSystem_Fake::Entry> dstIgnoredBefore; dstIgnoredBefore.max_load_factor(0.75f); dstIgnoredBefore.reserve(before.size() / 16); for (const auto& entry : before) { const auto& path = entry.first.sv(); if (path.starts_with(m_src.sv())) { ASSERT_TRUE(srcBefore.insert({entry.first, entry.second}).second) << "Error inserting " << path; } else if (path.starts_with(m_ref.sv())) { ASSERT_TRUE(refBefore.insert({entry.first, entry.second}).second) << "Error inserting " << path; } else if (path.starts_with(m_dst.sv())) { if (std::none_of(dstBackup.cbegin(), dstBackup.cend(), [path](const Path& base) { return (path.size() == base.size() && base == path) || (path.size() > base.size() && path[base.size()] == L'\\' && base == path.substr(0, base.size())); })) { ASSERT_TRUE(dstIgnoredBefore.insert({entry.first, entry.second}).second) << "Error inserting " << path; } } } std::unordered_map<Path, BackupFileSystem_Fake::Entry> srcCompare(srcBefore); std::unordered_map<Path, BackupFileSystem_Fake::Entry> dstAfter; dstAfter.max_load_factor(0.75f); dstAfter.reserve(after.size() / 2); for (const auto& entry : after) { const auto& path = entry.first.sv(); if (path.starts_with(m_src.sv())) { auto node = srcBefore.extract(entry.first); EXPECT_FALSE(node.empty()) << path.data() << " has been created"; if (!node.empty()) { EXPECT_EQ(node.mapped(), entry.second) << path.data() << " has been altered"; } } else if (path.starts_with(m_ref.sv())) { auto node = refBefore.extract(entry.first); EXPECT_FALSE(node.empty()) << path.data() << " has been created"; if (!node.empty()) { EXPECT_EQ(node.mapped(), entry.second) << path.data() << " has been altered"; } } else if (path.starts_with(m_dst.sv())) { if (std::none_of(dstBackup.cbegin(), dstBackup.cend(), [path](const Path& base) { return (path.size() == base.size() && base == path) || (path.size() > base.size() && path[base.size()] == L'\\' && base == path.substr(0, base.size())); })) { auto node = dstIgnoredBefore.extract(entry.first); if (node.empty() && entry.first == m_dst) { // creation of dst root path is allowed continue; } EXPECT_FALSE(node.empty()) << path.data() << " has been created"; if (!node.empty()) { EXPECT_EQ(node.mapped(), entry.second) << path.data() << " has been altered"; } } else { auto sub = path.substr(m_dst.size()); const Path srcPath(m_src, sub.data(), sub.size()); auto node = srcCompare.extract(srcPath); EXPECT_FALSE(node.empty()) << path.data() << " was expected to not exist"; if (!node.empty()) { EXPECT_EQ(node.mapped().size, entry.second.size) << path.data() << " mismatch to src"; EXPECT_EQ(node.mapped().creationTime, entry.second.creationTime) << path.data() << " mismatch to src"; EXPECT_EQ(node.mapped().lastWriteTime, entry.second.lastWriteTime) << path.data() << " mismatch to src"; EXPECT_EQ(node.mapped().attributes & BackupStrategy::kCopyAttributeMask, entry.second.attributes & BackupStrategy::kCopyAttributeMask) << path.data() << " mismatch to src"; EXPECT_EQ(node.mapped().filename, entry.second.filename) << path.data() << " mismatch to src"; EXPECT_EQ(node.mapped().content, entry.second.content) << path.data() << " mismatch to src"; } } } } EXPECT_THAT(srcBefore, t::IsEmpty()) << "Files have been removed from src"; EXPECT_THAT(refBefore, t::IsEmpty()) << "Files have been removed from ref"; EXPECT_THAT(dstIgnoredBefore, t::IsEmpty()) << "Files have been removed from dst"; // remove any folders which are not part of the backup for (auto it = srcCompare.begin(); it != srcCompare.end();) { if (std::any_of(backupFolders.cbegin(), backupFolders.cend(), [&it](const Path& path) { return Path(it->first.sv().substr(0, path.size())) == Path(path); })) { ++it; } else { it = srcCompare.erase(it); } } EXPECT_THAT(srcCompare, t::IsEmpty()) << "Files have not been copied"; } const std::unordered_map<Path, BackupFileSystem_Fake::Entry>& Backup_Fixture::Files() const noexcept { return m_fileSystem.GetFiles(); } Backup::Statistics Backup_Fixture::VerifyBackup(const std::vector<Path>& backupFolders) { return RunVerified(backupFolders, [this](const auto& backupFolders) { Backup backup(m_strategy); return backup.CreateBackup(backupFolders, m_ref, m_dst); }); } // // FileBuilder // FileBuilder::FileBuilder(Backup_Fixture& backupFixture) : m_backupFixture(backupFixture) , m_root(true) , m_srcEntry(Filename(L""), true) , m_refEntry(m_srcEntry.CreateCopy()) , m_dstEntry(m_srcEntry.CreateCopy()) { } FileBuilder::FileBuilder(Backup_Fixture& backupFixture, const std::wstring& filename, const bool directory) : m_backupFixture(backupFixture) , m_srcEntry(Filename(filename), directory) , m_refEntry(m_srcEntry.CreateCopy()) , m_dstEntry(m_srcEntry.CreateCopy()) { } FileBuilder& FileBuilder::src() { m_src = m_inSrc = true; return *this; } FileBuilder& FileBuilder::ref() { m_ref = m_inRef = true; return *this; } FileBuilder& FileBuilder::dst() { m_dst = m_inDst = true; return *this; } FileBuilder& FileBuilder::change() { m_src = false; m_ref = false; m_dst = false; return *this; } FileBuilder& FileBuilder::size(const std::uint64_t value) { if (m_src) { m_srcEntry.size = value; } if (m_ref) { m_refEntry.size = value; } if (m_dst) { m_dstEntry.size = value; } return *this; } FileBuilder& FileBuilder::creationTime(const std::int64_t value) { if (m_src) { m_srcEntry.creationTime = value; } if (m_ref) { m_refEntry.creationTime = value; } if (m_dst) { m_dstEntry.creationTime = value; } return *this; } FileBuilder& FileBuilder::lastWriteTime(const std::int64_t value) { if (m_src) { m_srcEntry.lastWriteTime = value; } if (m_ref) { m_refEntry.lastWriteTime = value; } if (m_dst) { m_dstEntry.lastWriteTime = value; } return *this; } FileBuilder& FileBuilder::attributes(const DWORD value) { if (m_src) { m_srcEntry.attributes = value | (m_srcEntry.attributes & FILE_ATTRIBUTE_DIRECTORY); } if (m_ref) { m_refEntry.attributes = value | (m_refEntry.attributes & FILE_ATTRIBUTE_DIRECTORY); } if (m_dst) { m_dstEntry.attributes = value | (m_dstEntry.attributes & FILE_ATTRIBUTE_DIRECTORY); } return *this; } FileBuilder& FileBuilder::filename(const std::wstring& value) { if (m_src) { m_srcEntry.filename = value; } if (m_ref) { m_refEntry.filename = value; } if (m_dst) { m_dstEntry.filename = value; } return *this; } FileBuilder& FileBuilder::content(const std::string& value) { if (m_src) { m_srcEntry.content = value; } if (m_ref) { m_refEntry.content = value; } if (m_dst) { m_dstEntry.content = value; } return *this; } FileBuilder& FileBuilder::fileId(const std::uint32_t value) { if (m_src) { m_srcEntry.fileId = value; } if (m_ref) { m_refEntry.fileId = value; } if (m_dst) { m_dstEntry.fileId = value; } return *this; } FileBuilder& FileBuilder::build() { if (!m_inSrc && !m_inRef && !m_inDst) { THROW(std::exception(), "{} neither exists in source, reference or destination", m_srcEntry.filename); } const Path mySrcPath = srcPath(); const Path myRefPath = refPath(); const Path myDstPath = dstPath(); if (m_inSrc) { m_backupFixture.m_fileSystem.Add(mySrcPath, m_srcEntry, m_root); } if (m_inRef) { m_backupFixture.m_fileSystem.Add(myRefPath, m_refEntry, m_root); } if (m_inDst) { m_backupFixture.m_fileSystem.Add(myDstPath, m_dstEntry, m_root); } if (m_srcEnablePathFunctions && !m_disableExpect) { auto times = m_srcEnablePathFunctions == 1 ? t::Exactly(1) : t::AnyNumber(); EXPECT_CALL(m_backupFixture.m_strategy, Exists(mySrcPath)).Times(times); EXPECT_CALL(m_backupFixture.m_strategy, IsDirectory(mySrcPath)).Times(times); } if (m_refEnablePathFunctions && !m_disableExpect) { auto times = m_refEnablePathFunctions == 1 ? t::Exactly(1) : t::AnyNumber(); EXPECT_CALL(m_backupFixture.m_strategy, Exists(myRefPath)).Times(times); EXPECT_CALL(m_backupFixture.m_strategy, IsDirectory(myRefPath)).Times(times); } if (m_dstEnablePathFunctions && !m_disableExpect) { auto times = m_dstEnablePathFunctions == 1 ? t::Exactly(1) : t::AnyNumber(); EXPECT_CALL(m_backupFixture.m_strategy, Exists(myDstPath)).Times(times); EXPECT_CALL(m_backupFixture.m_strategy, IsDirectory(myDstPath)).Times(times); } if (m_srcEnableScan) { EXPECT_CALL(m_backupFixture.m_strategy, Scan(mySrcPath, t::_, t::_, t::_, t::_, t::_)).RetiresOnSaturation(); } if (m_refEnableScan) { EXPECT_CALL(m_backupFixture.m_strategy, Scan(myRefPath, t::_, t::_, t::_, t::_, t::_)).RetiresOnSaturation(); } if (m_dstEnableScan) { EXPECT_CALL(m_backupFixture.m_strategy, Scan(myDstPath, t::_, t::_, t::_, t::_, t::_)).RetiresOnSaturation(); } if (m_root || m_disableExpect) { return *this; } // set-up the expectations if (m_srcEntry.IsDirectory()) { // Scan all src directories if (m_inSrc) { EXPECT_CALL(m_backupFixture.m_strategy, Scan(mySrcPath, t::_, t::_, t::_, t::_, t::_)).RetiresOnSaturation(); } // Scan ref directories only if src exists if (m_inSrc && m_inRef) { EXPECT_CALL(m_backupFixture.m_strategy, Scan(myRefPath, t::_, t::_, t::_, t::_, t::_)).RetiresOnSaturation(); } // Scan all dst directories if (m_inDst) { EXPECT_CALL(m_backupFixture.m_strategy, Scan(myDstPath, t::_, t::_, t::_, t::_, t::_)).RetiresOnSaturation(); } // Create directories missing in dst if (m_inSrc && !m_inDst) { EXPECT_CALL(m_backupFixture.m_strategy, CreateDirectory(PathWithExactFilename(myDstPath.GetParent(), m_srcEntry.filename), mySrcPath, t::_)).RetiresOnSaturation(); } // rename if src and dst only differ by case if (m_inSrc && m_inDst && m_srcEntry.filename != m_dstEntry.filename) { EXPECT_CALL(m_backupFixture.m_strategy, Rename(myDstPath, PathWithExactFilename(myDstPath.GetParent(), m_srcEntry.filename))).RetiresOnSaturation(); } // set attributes for all directories in dst that exist in src if (m_inSrc) { EXPECT_CALL(m_backupFixture.m_strategy, SetAttributes(myDstPath, t::AllOf( t::Property(&ScannedFile::GetCreationTime, m_srcEntry.creationTime), t::Property(&ScannedFile::GetLastWriteTime, m_srcEntry.lastWriteTime), t::Property(&ScannedFile::GetAttributes, m_srcEntry.attributes)))) .RetiresOnSaturation(); } // delete directories in dst that no longer exist in src if (!m_inSrc && m_inDst) { EXPECT_CALL(m_backupFixture.m_strategy, Delete(myDstPath)).RetiresOnSaturation(); } } else { const bool srcRefSameAttributes = m_inSrc && m_inRef && m_srcEntry.HasSameAttributes(m_refEntry); const bool srcDstSameAttributes = m_inSrc && m_inDst && m_srcEntry.HasSameAttributes(m_dstEntry); const bool srcRefIdentical = srcRefSameAttributes && m_srcEntry.content == m_refEntry.content; const bool srcDstIdentical = srcDstSameAttributes && m_srcEntry.content == m_dstEntry.content; const bool refDstSameFile = m_inRef && m_inDst && m_refEntry.fileId == m_dstEntry.fileId; // compare files that exist in src and dst if attributes match if (m_inSrc && m_inDst && srcDstSameAttributes) { EXPECT_CALL(m_backupFixture.m_strategy, Compare(mySrcPath, myDstPath, t::_)).RetiresOnSaturation(); } // rename files that are identical but use different case if (m_inSrc && m_inDst && srcDstIdentical && m_srcEntry.filename != m_dstEntry.filename) { EXPECT_CALL(m_backupFixture.m_strategy, Rename(myDstPath, PathWithExactFilename(myDstPath.GetParent(), m_srcEntry.filename))).RetiresOnSaturation(); } // delete files from dst which exist in src but are not identical if (m_inSrc && m_inDst && !srcDstIdentical) { EXPECT_CALL(m_backupFixture.m_strategy, Delete(myDstPath)).RetiresOnSaturation(); } // delete files from dst which do not exist in src if (!m_inSrc && m_inDst) { EXPECT_CALL(m_backupFixture.m_strategy, Delete(myDstPath)).RetiresOnSaturation(); } // compare all files that exist in src and ref if attributes match but not match in dst was found // also skip compare if ref and dst are hard-linked if (m_inSrc && m_inRef && srcRefSameAttributes && !srcDstIdentical && !refDstSameFile) { EXPECT_CALL(m_backupFixture.m_strategy, Compare(mySrcPath, myRefPath, t::_)).RetiresOnSaturation(); } // create hard link if found in ref but not in dst if (m_inSrc && m_inRef && srcRefIdentical && !srcDstIdentical) { EXPECT_CALL(m_backupFixture.m_strategy, CreateHardLink(PathWithExactFilename(myDstPath.GetParent(), m_srcEntry.filename), myRefPath)).RetiresOnSaturation(); } if (m_inSrc && !srcRefIdentical && !srcDstIdentical) { EXPECT_CALL(m_backupFixture.m_strategy, Copy(mySrcPath, PathWithExactFilename(myDstPath.GetParent(), m_srcEntry.filename))).RetiresOnSaturation(); EXPECT_CALL(m_backupFixture.m_strategy, SetAttributes(myDstPath, t::AllOf( t::Property(&ScannedFile::GetCreationTime, m_srcEntry.creationTime), t::Property(&ScannedFile::GetLastWriteTime, m_srcEntry.lastWriteTime), t::Property(&ScannedFile::GetAttributes, m_srcEntry.attributes)))) .RetiresOnSaturation(); } } return *this; } void FileBuilder::addTo(FileBuilder& parent) { if (m_pParent) { THROW(std::exception(), "{} already in file system", srcPath()); }; m_pParent = &parent; build(); } FileBuilder& FileBuilder::enablePathFunctions(const bool anyNumber) { if (m_src) { m_srcEnablePathFunctions = anyNumber ? 2 : 1; } if (m_ref) { m_refEnablePathFunctions = anyNumber ? 2 : 1; } if (m_dst) { m_dstEnablePathFunctions = anyNumber ? 2 : 1; } return *this; } FileBuilder& FileBuilder::enableScan() { if (m_src) { m_srcEnableScan = true; } if (m_ref) { m_refEnableScan = true; } if (m_dst) { m_dstEnableScan = true; } return *this; } FileBuilder& FileBuilder::disableExpect() { m_disableExpect = true; return *this; } FileBuilder& FileBuilder::remove() { if (m_src) { m_backupFixture.m_fileSystem.Delete(srcPath()); } if (m_ref) { m_backupFixture.m_fileSystem.Delete(refPath()); } if (m_dst) { m_backupFixture.m_fileSystem.Delete(dstPath()); } return *this; } Path FileBuilder::srcPath() const { if (m_pParent) { return m_pParent->srcPath() / m_srcEntry.filename; } if (!m_root) { THROW(std::exception(), "{} must be root", m_srcEntry.filename); } return m_backupFixture.m_src; } Path FileBuilder::refPath() const { if (m_pParent) { return m_pParent->refPath() / m_refEntry.filename; } if (!m_root) { THROW(std::exception(), "{} must be root", m_refEntry.filename); } return m_backupFixture.m_ref; } Path FileBuilder::dstPath() const { if (m_pParent) { return m_pParent->dstPath() / m_dstEntry.filename; } if (!m_root) { THROW(std::exception(), "{} must be root", m_dstEntry.filename); } return m_backupFixture.m_dst; } class Backup_Fixture_Test : public Backup_Fixture { protected: Backup_Fixture_Test() : Backup_Fixture(false) { } }; TEST_F(Backup_Fixture_Test, CheckSetup_Basic) { m_root.children( Folder(L"FolderSrc").disableExpect().src(), File(L"FileRef").disableExpect().ref(), Folder(L"FolderDst").disableExpect().dst()); ASSERT_THAT(Files(), t::Contains(t::Key(m_src / L"FolderSrc"))); ASSERT_THAT(Files(), t::Contains(t::Key(m_ref / L"FileRef"))); ASSERT_THAT(Files(), t::Contains(t::Key(m_dst / L"FolderDst"))); EXPECT_TRUE(Files().at(m_src / L"FolderSrc").IsDirectory()); EXPECT_FALSE(Files().at(m_ref / L"FileRef").IsDirectory()); EXPECT_TRUE(Files().at(m_dst / L"FolderDst").IsDirectory()); } TEST_F(Backup_Fixture_Test, CheckSetup_Removed) { m_root.children( Folder(L"FolderSrc").disableExpect().src(), Folder(L"FolderRef").disableExpect().ref(), Folder(L"FolderDst").disableExpect().dst()); // check for a particular error message, therefore requires #include TestUtils.h EXPECT_NONFATAL_FAILURE(RunVerified({}, [this](const auto&) { m_fileSystem.Delete(m_src / L"FolderSrc"); }), "FolderSrc"); EXPECT_NONFATAL_FAILURE(RunVerified({}, [this](const auto&) { m_fileSystem.Delete(m_ref / L"FolderRef"); }), "FolderRef"); EXPECT_NONFATAL_FAILURE(RunVerified({}, [this](const auto&) { m_fileSystem.Delete(m_dst / L"FolderDst"); }), "FolderDst"); } TEST_F(Backup_Fixture_Test, CheckSetup_Created) { m_root.children( Folder(L"FolderSrc").disableExpect().src(), Folder(L"FolderRef").disableExpect().ref(), Folder(L"FolderDst").disableExpect().dst()); // just make something to supply as a security source ScannedFile file(Filename(L""), {}, {}, {}, 0, {}, {}); file.GetSecurity().pSecurityDescriptor.reset(new BackupFileSystem_Fake::security_type("")); EXPECT_NONFATAL_FAILURE(RunVerified({}, [this, file](const auto&) { m_fileSystem.CreateDirectory(m_src / L"NewSrc", m_src / L"FolderSrc", file); }), "NewSrc has been created"); EXPECT_NONFATAL_FAILURE(RunVerified({}, [this, file](const auto&) { m_fileSystem.CreateDirectory(m_ref / L"NewRef", m_ref / L"FolderRef", file); }), "NewRef has been created"); EXPECT_NONFATAL_FAILURE(RunVerified({}, [this, file](const auto&) { m_fileSystem.CreateDirectory(m_dst / L"NewDst", m_dst / L"FolderDst", file); }), "NewDst has been created"); } TEST_F(Backup_Fixture_Test, CheckSetup_Renamed) { m_root.children( Folder(L"FolderSrc").disableExpect().src(), Folder(L"FolderRef").disableExpect().ref(), Folder(L"FolderDst").disableExpect().dst()); EXPECT_NONFATAL_FAILURE(RunVerified({}, [this](const auto&) { m_fileSystem.Rename(m_src / L"FolderSrc", m_src / L"foldersrc"); }), "foldersrc has been altered"); EXPECT_NONFATAL_FAILURE(RunVerified({}, [this](const auto&) { m_fileSystem.Rename(m_ref / L"FolderRef", m_ref / L"folderref"); }), "folderref has been altered"); EXPECT_NONFATAL_FAILURE(RunVerified({}, [this](const auto&) { m_fileSystem.Rename(m_dst / L"FolderDst", m_dst / L"folderdst"); }), "folderdst has been altered"); } TEST_F(Backup_Fixture_Test, CheckSetup_ChangedAttributes) { m_root.children( Folder(L"FolderSrc").disableExpect().src(), Folder(L"FolderRef").disableExpect().ref(), Folder(L"FolderDst").disableExpect().dst()); EXPECT_NONFATAL_FAILURE(RunVerified({}, [this](const auto&) { const ScannedFile scannedFile(Filename(L"FolderSrc"), LARGE_INTEGER{.QuadPart = 0}, LARGE_INTEGER{.QuadPart = 0}, LARGE_INTEGER{.QuadPart = 0}, 0, {},{}); m_fileSystem.SetAttributes(m_src / L"FolderSrc", scannedFile); }), "FolderSrc has been altered"); EXPECT_NONFATAL_FAILURE(RunVerified({}, [this](const auto&) { const ScannedFile scannedFile(Filename(L"FolderRef"), LARGE_INTEGER{.QuadPart = 0}, LARGE_INTEGER{.QuadPart = 0}, LARGE_INTEGER{.QuadPart = 0}, 0, {},{}); m_fileSystem.SetAttributes(m_ref / L"FolderRef", scannedFile); }), "FolderRef has been altered"); EXPECT_NONFATAL_FAILURE(RunVerified({}, [this](const auto&) { const ScannedFile scannedFile(Filename(L"FolderDst"), LARGE_INTEGER{.QuadPart = 0}, LARGE_INTEGER{.QuadPart = 0}, LARGE_INTEGER{.QuadPart = 0}, 0, {},{}); m_fileSystem.SetAttributes(m_dst / L"FolderDst", scannedFile); }), "FolderDst has been altered"); } } // namespace systools::test
36.100437
224
0.702754
mbeckh
ba5f28277cd8144d76207f2f5d39f977fd5c978a
3,047
cc
C++
src/ila-mngr/p_simplify_semantic.cc
LeeOHzzZ/ILAng
24225294ac133e5d08af5037350ede8f78610c45
[ "MIT" ]
21
2019-03-18T18:35:35.000Z
2022-01-27T06:57:47.000Z
src/ila-mngr/p_simplify_semantic.cc
LeeOHzzZ/ILAng
24225294ac133e5d08af5037350ede8f78610c45
[ "MIT" ]
105
2019-01-19T07:09:25.000Z
2021-01-11T20:06:24.000Z
src/ila-mngr/p_simplify_semantic.cc
LeeOHzzZ/ILAng
24225294ac133e5d08af5037350ede8f78610c45
[ "MIT" ]
7
2019-01-28T19:48:09.000Z
2020-11-05T14:42:05.000Z
/// \file /// Simplify instruction state update functions. #include <ilang/ila-mngr/pass.h> #include <ilang/target-smt/z3_expr_adapter.h> #include <ilang/util/log.h> namespace ilang { namespace pass { class FuncObjEqSubtree { public: FuncObjEqSubtree(const ExprPtr& target, const ExprPtr& assump) : target_(target), assump_(assump) {} ExprPtr get(const ExprPtr& e) const { auto pos = rule_.find(e); ILA_CHECK(pos != rule_.end()) << "No mapping for " << e; return pos->second; } bool pre(const ExprPtr& e) const { auto pos = rule_.find(e); return pos != rule_.end(); // if found --> break } void post(const ExprPtr& e) { auto dst = Rewrite(e); rule_.insert({e, dst}); } private: ExprMap rule_; ExprPtr target_; ExprPtr assump_; ExprPtr candidate_ = nullptr; ExprPtr Rewrite(const ExprPtr& e) { // assump -> (e == target) auto CheckEqModAssump = [=](const ExprPtr& x) { z3::context ctx; z3::solver s(ctx); auto gen = Z3ExprAdapter(ctx); auto ass = gen.GetExpr(assump_); auto tar = gen.GetExpr(target_); auto can = gen.GetExpr(x); s.add(ass && (can != tar)); return (s.check() == z3::unsat); }; // skip target itself if (e == target_) { return candidate_ ? candidate_ : e; } // check equivalence if not found yet and have a same type if (!candidate_ && e->sort() == target_->sort()) { if (CheckEqModAssump(e)) { candidate_ = e; } } return e; } }; // class FuncObjSimpInstrUpdateRedundant bool SimplifySemantic(const InstrLvlAbsCnstPtr& m, const int& timeout) { ILA_NOT_NULL(m); ILA_INFO << "Start pass: semantic simplification"; // pattern - equivalent sub-tree modulo valid and decode auto SimpEqSubtree = [=](const ExprPtr& e, const InstrPtr& i) { auto host = i->host(); ILA_NOT_NULL(host); auto valid = host->valid(); ILA_NOT_NULL(valid); auto decode = i->decode(); ILA_NOT_NULL(decode); auto func = FuncObjEqSubtree(e, asthub::And(valid, decode)); e->DepthFirstVisitPrePost(func); auto new_update = func.get(e); if (new_update != e) { ILA_DLOG("PassSimpSemantic") << "Equivalent sub-tree of " << i; } return new_update; }; if (timeout > 0) { z3::set_param("timeout", timeout); } auto visiter = [&SimpEqSubtree](const InstrLvlAbsCnstPtr& current) { try { // only simplify instructions for (size_t i = 0; i < current->instr_num(); i++) { auto instr = current->instr(i); // DO NOT rewrite decode (valid & decode used as the env.) // state updates for (const auto& state : instr->updated_states()) { instr->ForceAddUpdate(state, SimpEqSubtree(instr->update(state), instr)); } } } catch (...) { ILA_ERROR << "Fail simplify " << current; } }; m->DepthFirstVisit(visiter); z3::reset_params(); return true; } } // namespace pass } // namespace ilang
23.620155
76
0.605514
LeeOHzzZ
ba5f3ba12c7716897119188ab4a7ba560e09dd30
469
cpp
C++
src/examples/012Chapter/12-1-7-dynamic-arrays/dynamic_arrays.cpp
artgonzalez/cpp-primer
0317e11b5821860d38a236f24c6f7d76638386f3
[ "MIT" ]
null
null
null
src/examples/012Chapter/12-1-7-dynamic-arrays/dynamic_arrays.cpp
artgonzalez/cpp-primer
0317e11b5821860d38a236f24c6f7d76638386f3
[ "MIT" ]
null
null
null
src/examples/012Chapter/12-1-7-dynamic-arrays/dynamic_arrays.cpp
artgonzalez/cpp-primer
0317e11b5821860d38a236f24c6f7d76638386f3
[ "MIT" ]
null
null
null
#include "dynamic_arrays.h" using std::cout; using std::shared_ptr; int* get_dynamic_array(const std::size_t cnt) { cout<<"Create\n"; return new int[cnt](); } void delete_dynamic_array(int * array) { cout<<"\ndelete\n"; delete[] array; } void use_dynamic_array() { const size_t cnt = 25; shared_ptr<int[]> nums (get_dynamic_array(cnt), delete_dynamic_array); for(size_t i=0; i < cnt; ++i) { cout<<nums[i]<<" "; } }
16.75
74
0.616205
artgonzalez
ba5f8a218f0bccd99e4c1e7bd2c756dc159d345d
254
cpp
C++
cssmh/hacks/Bunnyhop.cpp
rdbo/cssmh-external
f9c4ba3b735c691cf185670e2f0794643ce0284a
[ "MIT" ]
1
2022-01-06T01:58:18.000Z
2022-01-06T01:58:18.000Z
cssmh/hacks/Bunnyhop.cpp
rdbo/cssmh-external
f9c4ba3b735c691cf185670e2f0794643ce0284a
[ "MIT" ]
null
null
null
cssmh/hacks/Bunnyhop.cpp
rdbo/cssmh-external
f9c4ba3b735c691cf185670e2f0794643ce0284a
[ "MIT" ]
1
2022-01-09T11:28:50.000Z
2022-01-09T11:28:50.000Z
#include <base.hpp> void Hack::Bunnyhop() { if (CSSMH::EnableBunnyhop && CSSMH::KeyBhop.GetKeyState() == KeyInfo::PRESSED && CSSMH::LocalPlayer.flags & FL_ONGROUND) Memory::WriteMemory<int32_t>(CSSMH::GameOverlay->target_pid, CSSMH::InJumpBtn, 6); }
31.75
121
0.728346
rdbo
ba61ade0e01c16df3100554d68ef1543c1727e85
2,505
cpp
C++
Model Loader/Mesh.cpp
jreverett/Model-Loader
215d6a2c60e1c933b7fa7527d1aa07bf2c84e01d
[ "MIT" ]
null
null
null
Model Loader/Mesh.cpp
jreverett/Model-Loader
215d6a2c60e1c933b7fa7527d1aa07bf2c84e01d
[ "MIT" ]
null
null
null
Model Loader/Mesh.cpp
jreverett/Model-Loader
215d6a2c60e1c933b7fa7527d1aa07bf2c84e01d
[ "MIT" ]
null
null
null
#include "Mesh.h" Mesh::Mesh() { } void Mesh::draw(Shader shader) { unsigned int diffueNr = 1; unsigned int specularNr = 1; unsigned int normalNr = 1; unsigned int heightNr = 1; shader.use(); for (unsigned int i = 0; i < textures.size(); i++) { glActiveTexture(GL_TEXTURE0 + i); // get texture number (diffuseNr) std::string number; std::string type = textures[i].type; if (type == "texture_diffuse") number = std::to_string(diffueNr++); else if (type == "texture_specular") number = std::to_string(specularNr++); else if (type == "texture_normal") number = std::to_string(normalNr++); glUniform1i(glGetUniformLocation(shader.ID, (type + number).c_str()), i); // bind the texture glBindTexture(GL_TEXTURE_2D, textures[i].id); } shader.setVec4("material.diffuse", mtlData.Kd); //shader.setVec3("material.ambient", mtlData.Ka); //shader.setVec3("material.specular", mtlData.Ks); //shader.setFloat("material.shininess", mtlData.Ni); glBindVertexArray(VAO); glDrawArrays(GL_TRIANGLES, 0, vecData.vertices.size()); glBindVertexArray(0); // reset active texture glActiveTexture(GL_TEXTURE0); } void Mesh::setupMesh(Shader shader) { /////////////////////////////////////////////////////////// // Setup Buffers glGenVertexArrays(1, &VAO); glBindVertexArray(VAO); glGenBuffers(NUM_VERTEX_BUFFERS, vertexBuffers); // position buffer glBindBuffer(GL_ARRAY_BUFFER, vertexBuffers[VertexBufferValue::TRIANGLES]); glBufferData(GL_ARRAY_BUFFER, vecData.vertices.size() * sizeof(glm::vec3), &vecData.vertices[0], GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0); glEnableVertexAttribArray(0); // normal buffer glBindBuffer(GL_ARRAY_BUFFER, vertexBuffers[VertexBufferValue::NORMALS]); glBufferData(GL_ARRAY_BUFFER, vecData.normals.size() * sizeof(glm::vec3), &vecData.normals[0], GL_STATIC_DRAW); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, (void*)0); glEnableVertexAttribArray(1); // texture buffer if (!vecData.uvs.empty()) { glBindBuffer(GL_ARRAY_BUFFER, vertexBuffers[VertexBufferValue::TEXTURES]); glBufferData(GL_ARRAY_BUFFER, vecData.uvs.size() * sizeof(glm::vec2), &vecData.uvs[0], GL_STATIC_DRAW); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 0, (void*)0); glEnableVertexAttribArray(2); } shader.use(); if (textures.empty()) glUniform1i(glGetUniformLocation(shader.ID, "hasTexture"), false); else glUniform1i(glGetUniformLocation(shader.ID, "hasTexture"), true); }
26.935484
114
0.707385
jreverett
ba624c7320ac8a71c23184392b9bb977a0b782f5
1,043
hpp
C++
stan/math/fwd/mat/functor/jacobian.hpp
jrmie/math
2850ec262181075a5843968e805dc9ad1654e069
[ "BSD-3-Clause" ]
null
null
null
stan/math/fwd/mat/functor/jacobian.hpp
jrmie/math
2850ec262181075a5843968e805dc9ad1654e069
[ "BSD-3-Clause" ]
null
null
null
stan/math/fwd/mat/functor/jacobian.hpp
jrmie/math
2850ec262181075a5843968e805dc9ad1654e069
[ "BSD-3-Clause" ]
null
null
null
#ifndef STAN_MATH_FWD_MAT_FUNCTOR_JACOBIAN_HPP #define STAN_MATH_FWD_MAT_FUNCTOR_JACOBIAN_HPP #include <stan/math/fwd/core.hpp> #include <stan/math/prim/mat/fun/Eigen.hpp> #include <vector> namespace stan { namespace math { template <typename T, typename F> void jacobian(const F& f, const Eigen::Matrix<T, Eigen::Dynamic, 1>& x, Eigen::Matrix<T, Eigen::Dynamic, 1>& fx, Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& J) { using Eigen::Dynamic; using Eigen::Matrix; Matrix<fvar<T>, Dynamic, 1> x_fvar(x.size()); for (int i = 0; i < x.size(); ++i) { for (int k = 0; k < x.size(); ++k) x_fvar(k) = fvar<T>(x(k), i == k); Matrix<fvar<T>, Dynamic, 1> fx_fvar = f(x_fvar); if (i == 0) { J.resize(fx_fvar.size(), x.size()); fx.resize(fx_fvar.size()); for (int k = 0; k < fx_fvar.size(); ++k) fx(k) = fx_fvar(k).val_; } for (int k = 0; k < fx_fvar.size(); ++k) { J(k, i) = fx_fvar(k).d_; } } } } // namespace math } // namespace stan #endif
28.189189
71
0.588686
jrmie
ba63d5af8d663488f681c564a5397a8c4cd44dfc
6,777
hpp
C++
include/GlobalNamespace/StandardScoreSyncStateDeltaNetSerializable.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/StandardScoreSyncStateDeltaNetSerializable.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/StandardScoreSyncStateDeltaNetSerializable.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: LiteNetLib.Utils.INetSerializable #include "LiteNetLib/Utils/INetSerializable.hpp" // Including type: IPoolablePacket #include "GlobalNamespace/IPoolablePacket.hpp" // Including type: ISyncStateDeltaSerializable`1 #include "GlobalNamespace/ISyncStateDeltaSerializable_1.hpp" // Including type: StandardScoreSyncState #include "GlobalNamespace/StandardScoreSyncState.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: GlobalNamespace namespace GlobalNamespace { // Forward declaring type: PacketPool`1<T> template<typename T> class PacketPool_1; } // Forward declaring namespace: LiteNetLib::Utils namespace LiteNetLib::Utils { // Forward declaring type: NetDataWriter class NetDataWriter; // Forward declaring type: NetDataReader class NetDataReader; } // Completed forward declares // Type namespace: namespace GlobalNamespace { // Size: 0x2C #pragma pack(push, 1) // Autogenerated type: StandardScoreSyncStateDeltaNetSerializable class StandardScoreSyncStateDeltaNetSerializable : public ::Il2CppObject/*, public LiteNetLib::Utils::INetSerializable, public GlobalNamespace::IPoolablePacket, public GlobalNamespace::ISyncStateDeltaSerializable_1<GlobalNamespace::StandardScoreSyncState>*/ { public: // private StandardScoreSyncState _delta // Size: 0x14 // Offset: 0x10 GlobalNamespace::StandardScoreSyncState delta; // Field size check static_assert(sizeof(GlobalNamespace::StandardScoreSyncState) == 0x14); // [CompilerGeneratedAttribute] Offset: 0xDF00EC // private SyncStateId <baseId>k__BackingField // Size: 0x1 // Offset: 0x24 GlobalNamespace::SyncStateId baseId; // Field size check static_assert(sizeof(GlobalNamespace::SyncStateId) == 0x1); // Padding between fields: baseId and: timeOffsetMs char __padding1[0x3] = {}; // [CompilerGeneratedAttribute] Offset: 0xDF00FC // private System.Int32 <timeOffsetMs>k__BackingField // Size: 0x4 // Offset: 0x28 int timeOffsetMs; // Field size check static_assert(sizeof(int) == 0x4); // Creating value type constructor for type: StandardScoreSyncStateDeltaNetSerializable StandardScoreSyncStateDeltaNetSerializable(GlobalNamespace::StandardScoreSyncState delta_ = {}, GlobalNamespace::SyncStateId baseId_ = {}, int timeOffsetMs_ = {}) noexcept : delta{delta_}, baseId{baseId_}, timeOffsetMs{timeOffsetMs_} {} // Creating interface conversion operator: operator LiteNetLib::Utils::INetSerializable operator LiteNetLib::Utils::INetSerializable() noexcept { return *reinterpret_cast<LiteNetLib::Utils::INetSerializable*>(this); } // Creating interface conversion operator: operator GlobalNamespace::IPoolablePacket operator GlobalNamespace::IPoolablePacket() noexcept { return *reinterpret_cast<GlobalNamespace::IPoolablePacket*>(this); } // Creating interface conversion operator: operator GlobalNamespace::ISyncStateDeltaSerializable_1<GlobalNamespace::StandardScoreSyncState> operator GlobalNamespace::ISyncStateDeltaSerializable_1<GlobalNamespace::StandardScoreSyncState>() noexcept { return *reinterpret_cast<GlobalNamespace::ISyncStateDeltaSerializable_1<GlobalNamespace::StandardScoreSyncState>*>(this); } // Get static field: static public readonly PacketPool`1<StandardScoreSyncStateDeltaNetSerializable> pool static GlobalNamespace::PacketPool_1<GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable*>* _get_pool(); // Set static field: static public readonly PacketPool`1<StandardScoreSyncStateDeltaNetSerializable> pool static void _set_pool(GlobalNamespace::PacketPool_1<GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable*>* value); // public SyncStateId get_baseId() // Offset: 0x2367FCC GlobalNamespace::SyncStateId get_baseId(); // public System.Void set_baseId(SyncStateId value) // Offset: 0x2367FD4 void set_baseId(GlobalNamespace::SyncStateId value); // public System.Int32 get_timeOffsetMs() // Offset: 0x2367FDC int get_timeOffsetMs(); // public System.Void set_timeOffsetMs(System.Int32 value) // Offset: 0x2367FE4 void set_timeOffsetMs(int value); // public StandardScoreSyncState get_delta() // Offset: 0x2367FEC GlobalNamespace::StandardScoreSyncState get_delta(); // public System.Void set_delta(StandardScoreSyncState value) // Offset: 0x2368000 void set_delta(GlobalNamespace::StandardScoreSyncState value); // static private System.Void NoDomainReloadInit() // Offset: 0x2368014 static void NoDomainReloadInit(); // public System.Void Serialize(LiteNetLib.Utils.NetDataWriter writer) // Offset: 0x2368090 void Serialize(LiteNetLib::Utils::NetDataWriter* writer); // public System.Void Deserialize(LiteNetLib.Utils.NetDataReader reader) // Offset: 0x2368178 void Deserialize(LiteNetLib::Utils::NetDataReader* reader); // public System.Void Release() // Offset: 0x236821C void Release(); // static private System.Void .cctor() // Offset: 0x23682A8 static void _cctor(); // public System.Void .ctor() // Offset: 0x23682A0 // Implemented from: System.Object // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static StandardScoreSyncStateDeltaNetSerializable* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<StandardScoreSyncStateDeltaNetSerializable*, creationType>())); } }; // StandardScoreSyncStateDeltaNetSerializable #pragma pack(pop) static check_size<sizeof(StandardScoreSyncStateDeltaNetSerializable), 40 + sizeof(int)> __GlobalNamespace_StandardScoreSyncStateDeltaNetSerializableSizeCheck; static_assert(sizeof(StandardScoreSyncStateDeltaNetSerializable) == 0x2C); } DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable*, "", "StandardScoreSyncStateDeltaNetSerializable");
52.130769
262
0.75048
darknight1050
ba63d77a21683a0ee6bf5112e72b18c01dc1195f
4,158
cpp
C++
cpp/core/vec.cpp
equivalence1/ml_lib
92d75ab73bc2d77ba8fa66022c803c06cad66f21
[ "Apache-2.0" ]
1
2019-02-15T09:40:43.000Z
2019-02-15T09:40:43.000Z
cpp/core/vec.cpp
equivalence1/ml_lib
92d75ab73bc2d77ba8fa66022c803c06cad66f21
[ "Apache-2.0" ]
null
null
null
cpp/core/vec.cpp
equivalence1/ml_lib
92d75ab73bc2d77ba8fa66022c803c06cad66f21
[ "Apache-2.0" ]
2
2018-09-29T10:17:26.000Z
2018-10-03T20:33:31.000Z
#include "vec.h" #include "vec_factory.h" #include "torch_helpers.h" #include "matrix.h" void Vec::set(int64_t index, double value) { data().accessor<float, 1>()[index] = value; } double Vec::get(int64_t index) const { return data().accessor<float, 1>()[index]; } int64_t Vec::dim() const { return TorchHelpers::totalSize(data()); } Vec Vec::append(float val) const { auto data = this->data(); auto valT = torch::ones({1}, torch::kFloat); valT *= val; auto newData = torch::cat({data, valT}); auto res = Vec(0); res.data_ = newData; return res; } // ////TODO: should be placeholder Vec::Vec(int64_t dim, float value) : Buffer<float>(torch::ones({dim}, TorchHelpers::tensorOptionsOnDevice(CurrentDevice())) * value) { } Vec::Vec(int64_t dim, const ComputeDevice& device) : Buffer<float>(torch::zeros({dim}, TorchHelpers::tensorOptionsOnDevice(device))) { } Vec Vec::slice(int64_t from, int64_t size) { assert(data().dim() == 1); return Vec(data().slice(0, from, from + size)); } Vec Vec::slice(int64_t from, int64_t size) const { return Vec(data().slice(0, from, from + size)); } Vec& Vec::operator+=(const Vec& other) { data() += other; return *this; } Vec& Vec::operator-=(const Vec& other) { data() -= other; return *this; } Vec& Vec::operator*=(const Vec& other) { data() *= other; return *this; } Vec& Vec::operator/=(const Vec& other) { data() /= other; return *this; } Vec& Vec::operator+=(Scalar value) { data() += value; return *this; } Vec& Vec::operator-=(Scalar value) { data() -= value; return *this; } Vec& Vec::operator*=(Scalar value) { data() *= value; return *this; } Vec& Vec::operator/=(Scalar value) { data() /= value; return *this; } Vec& Vec::operator^=(const Vec& other) { data().pow_(other); return *this; } Vec& Vec::operator^=(Scalar q) { data().pow_(q); return *this; } Vec operator+(const Vec& left, const Vec& right) { auto result = VecFactory::uninitializedCopy(left); at::add_out(result, left, right); return result; } Vec operator-(const Vec& left, const Vec& right) { auto result = VecFactory::uninitializedCopy(left); at::sub_out(result, left, right); return result; } Vec operator*(const Vec& left, const Vec& right) { auto result = VecFactory::uninitializedCopy(left); at::mul_out(result, left, right); return result; } Vec operator/(const Vec& left, const Vec& right) { auto result = VecFactory::uninitializedCopy(left); at::div_out(result, left, right); return result; } Vec operator^(const Vec& left, Scalar q) { auto result = VecFactory::uninitializedCopy(left); at::pow_out(result, left, q); return result; } Vec operator+(const Vec& left, Scalar right) { auto result = VecFactory::clone(left); result += right; return result; } Vec operator-(const Vec& left, Scalar right) { auto result = VecFactory::clone(left); result -= right; return result; } Vec operator*(const Vec& left, Scalar right) { auto result = VecFactory::clone(left); result *= right; return result; } Vec operator/(const Vec& left, Scalar right) { auto result = VecFactory::clone(left); result /= right; return result; } Vec operator^(const Vec& left, const Vec& right) { auto result = VecFactory::clone(left); result ^= right; return result; } Vec operator>(const Vec& left, Scalar right) { return Vec(left.data().gt(right).to(torch::ScalarType::Float)); } Vec operator<(const Vec& left, Scalar right) { return Vec(left.data().lt(right).to(torch::ScalarType::Float)); } Vec eq(const Vec& left, Scalar right) { return Vec(left.data().eq(right).to(torch::ScalarType::Float)); } Vec eq(const Vec& left, const Vec& right) { return Vec(left.data().eq(right).to(torch::ScalarType::Float)); } Vec operator!=(const Vec& left, Scalar right) { return Vec(left.data().ne(right).to(torch::ScalarType::Float)); } double l2(const Vec& x) { double res = 0; auto xRef = x.arrayRef(); for (float i : xRef) { res += i * i; } return res; }
24.458824
103
0.635642
equivalence1
ba641c95152fa5814889739ed6ab3c2df08195f5
3,728
cpp
C++
lib/Runtime/Language/SimdUint16x8Operation.cpp
satheeshravi/ChakraCore
3bf47ff12bf80ab06fb7ea6925ec7579985ac1f5
[ "MIT" ]
null
null
null
lib/Runtime/Language/SimdUint16x8Operation.cpp
satheeshravi/ChakraCore
3bf47ff12bf80ab06fb7ea6925ec7579985ac1f5
[ "MIT" ]
null
null
null
lib/Runtime/Language/SimdUint16x8Operation.cpp
satheeshravi/ChakraCore
3bf47ff12bf80ab06fb7ea6925ec7579985ac1f5
[ "MIT" ]
null
null
null
//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- #include "RuntimeLanguagePch.h" #if defined(_M_ARM32_OR_ARM64) namespace Js { SIMDValue SIMDUint16x8Operation::OpUint16x8(uint16 x0, uint16 x1, uint16 x2, uint16 x3 , uint16 x4, uint16 x5, uint16 x6, uint16 x7) { SIMDValue result; result.u16[0] = x0; result.u16[1] = x1; result.u16[2] = x2; result.u16[3] = x3; result.u16[4] = x4; result.u16[5] = x5; result.u16[6] = x6; result.u16[7] = x7; return result; } SIMDValue SIMDUint16x8Operation::OpMul(const SIMDValue& aValue, const SIMDValue& bValue) { SIMDValue result; for(uint idx = 0; idx < 8; ++idx) { result.u16[idx] = aValue.u16[idx] * bValue.u16[idx]; } return result; } SIMDValue SIMDUint16x8Operation::OpMin(const SIMDValue& aValue, const SIMDValue& bValue) { SIMDValue result; for (uint idx = 0; idx < 8; ++idx) { result.u16[idx] = (aValue.u16[idx] < bValue.u16[idx]) ? aValue.u16[idx] : bValue.u16[idx]; } return result; } SIMDValue SIMDUint16x8Operation::OpMax(const SIMDValue& aValue, const SIMDValue& bValue) { SIMDValue result; for (uint idx = 0; idx < 8; ++idx) { result.u16[idx] = (aValue.u16[idx] > bValue.u16[idx]) ? aValue.u16[idx] : bValue.u16[idx]; } return result; } SIMDValue SIMDUint16x8Operation::OpLessThan(const SIMDValue& aValue, const SIMDValue& bValue) //arun::ToDo return bool types { SIMDValue result; for(uint idx = 0; idx < 8; ++idx) { result.u16[idx] = (aValue.u16[idx] < bValue.u16[idx]) ? 0xff : 0x0; } return result; } SIMDValue SIMDUint16x8Operation::OpLessThanOrEqual(const SIMDValue& aValue, const SIMDValue& bValue) //arun::ToDo return bool types { SIMDValue result; for (uint idx = 0; idx < 8; ++idx) { result.u16[idx] = (aValue.u16[idx] <= bValue.u16[idx]) ? 0xff : 0x0; } return result; } SIMDValue SIMDUint16x8Operation::OpShiftRightByScalar(const SIMDValue& value, int count) { SIMDValue result; if (count > 16) //Similar to polyfill, maximum shift will happen if the shift amounts and invalid { count = 16; } for (uint idx = 0; idx < 8; ++idx) { result.u16[idx] = (value.u16[idx] >> count); } return result; } SIMDValue SIMDUint16x8Operation::OpAddSaturate(const SIMDValue& aValue, const SIMDValue& bValue) { SIMDValue result; for (uint idx = 0; idx < 8; ++idx) { uint32 a = (uint32)aValue.u16[idx]; uint32 b = (uint32)bValue.u16[idx]; result.u16[idx] = ((a + b) > MAXUINT16) ? MAXUINT16 : (uint16)(a + b); } return result; } SIMDValue SIMDUint16x8Operation::OpSubSaturate(const SIMDValue& aValue, const SIMDValue& bValue) { SIMDValue result; for (uint idx = 0; idx < 8; ++idx) { int a = (int)aValue.u16[idx]; int b = (int)bValue.u16[idx]; result.u16[idx] = ((a - b) < 0) ? 0 : (uint16)(a - b); } return result; } } #endif
28.242424
135
0.525751
satheeshravi
ba6598cb981f5fc18797eb5dc3d25d6a33be6f38
1,509
hpp
C++
pythran/pythonic/numpy/bincount.hpp
Gladiator1977/pythran
5a57c8cb2de71f974d60615be87d030eb61132ac
[ "BSD-3-Clause" ]
1
2018-03-24T00:33:03.000Z
2018-03-24T00:33:03.000Z
pythran/pythonic/numpy/bincount.hpp
Acidburn0zzz/pythran
6dae026b60118d3b9ddd83775d3c57768a0865e5
[ "BSD-3-Clause" ]
null
null
null
pythran/pythonic/numpy/bincount.hpp
Acidburn0zzz/pythran
6dae026b60118d3b9ddd83775d3c57768a0865e5
[ "BSD-3-Clause" ]
null
null
null
#ifndef PYTHONIC_NUMPY_BINCOUNT_HPP #define PYTHONIC_NUMPY_BINCOUNT_HPP #include "pythonic/include/numpy/bincount.hpp" #include "pythonic/numpy/max.hpp" PYTHONIC_NS_BEGIN namespace numpy { template <class T, size_t N> types::ndarray<long, 1> bincount(types::ndarray<T, N> const &expr, types::none_type weights, types::none<long> minlength) { long length = 0; if (minlength) length = (long)minlength; length = std::max(length, 1 + max(expr)); types::ndarray<long, 1> out(types::make_tuple(length), 0L); for (auto iter = expr.fbegin(), end = expr.fend(); iter != end; ++iter) ++out[*iter]; return out; } template <class T, size_t N, class E> types::ndarray< decltype(std::declval<long>() * std::declval<typename E::dtype>()), 1> bincount(types::ndarray<T, N> const &expr, E const &weights, types::none<long> minlength) { long length = 0; if (minlength) length = (long)minlength; length = std::max(length, 1 + max(expr)); types::ndarray<decltype(std::declval<long>() * std::declval<typename E::dtype>()), 1> out(types::make_tuple(length), 0L); auto iweight = weights.fbegin(); for (auto iter = expr.fbegin(), end = expr.fend(); iter != end; ++iter, ++iweight) out[*iter] += *iweight; return out; } DEFINE_FUNCTOR(pythonic::numpy, bincount); } PYTHONIC_NS_END #endif
29.019231
76
0.595096
Gladiator1977
ba679429b018b631f4df61aa6f74a0f16e8ca04c
836
hpp
C++
include/tinycoro/io/EpollAsyncAutoResetEvent.hpp
asmei1/tinycoro
5b6d3dc9412c8c9e369f652707894a586a8bd9a8
[ "MIT" ]
7
2020-12-21T02:16:33.000Z
2022-03-18T23:57:05.000Z
include/tinycoro/io/EpollAsyncAutoResetEvent.hpp
asmei1/tinycoro
5b6d3dc9412c8c9e369f652707894a586a8bd9a8
[ "MIT" ]
null
null
null
include/tinycoro/io/EpollAsyncAutoResetEvent.hpp
asmei1/tinycoro
5b6d3dc9412c8c9e369f652707894a586a8bd9a8
[ "MIT" ]
null
null
null
// // Created by Asmei on 12/2/2020. // #ifndef TINYCORO_IOEVENT_H #define TINYCORO_IOEVENT_H #include <coroutine> #include <utility> #include "IOOperation.hpp" namespace tinycoro::io { /* * A simple class with set and auto clear mechanism, that allow to wait one thread * until an event is signalled by a thread calling a set() function. * * State set is automatically set to "not set" state after wake up thread. */ class EpollAsyncAutoResetEvent : public IOOperation { public: EpollAsyncAutoResetEvent(IOContext& context); ~EpollAsyncAutoResetEvent(); bool await_ready() noexcept; void await_suspend(std::coroutine_handle<> awaitingCoro); void await_resume(); void set(); }; } // namespace tinycoro::io #endif // TINYCORO_IOEVENT_H
22.594595
86
0.674641
asmei1
ba6a4c86329910c6de143df224b6c5af5f979ac1
491
cpp
C++
DaedalicTestAutomationPlugin/Source/DaedalicTestAutomationPlugin/Private/DaeTestResult.cpp
DeadMonkeyEntertaiment/ue4-test-automation
d5ba1e22c52bdabdd331766f9272dfc1d4b20962
[ "MIT" ]
617
2017-04-16T13:34:20.000Z
2022-03-31T23:43:47.000Z
DaedalicTestAutomationPlugin/Source/DaedalicTestAutomationPlugin/Private/DaeTestResult.cpp
DeadMonkeyEntertaiment/ue4-test-automation
d5ba1e22c52bdabdd331766f9272dfc1d4b20962
[ "MIT" ]
178
2017-04-05T19:30:21.000Z
2022-03-11T05:44:03.000Z
DaedalicTestAutomationPlugin/Source/DaedalicTestAutomationPlugin/Private/DaeTestResult.cpp
DeadMonkeyEntertaiment/ue4-test-automation
d5ba1e22c52bdabdd331766f9272dfc1d4b20962
[ "MIT" ]
147
2017-06-27T08:35:09.000Z
2022-03-28T03:06:17.000Z
#include "DaeTestResult.h" FDaeTestResult::FDaeTestResult() : FDaeTestResult(FString(), 0.0f) { } FDaeTestResult::FDaeTestResult(FString InTestName, float InTimeSeconds) : TestName(InTestName) , TimeSeconds(InTimeSeconds) { } bool FDaeTestResult::WasSuccessful() const { return !HasFailed() && !WasSkipped(); } bool FDaeTestResult::HasFailed() const { return !FailureMessage.IsEmpty(); } bool FDaeTestResult::WasSkipped() const { return !SkipReason.IsEmpty(); }
17.535714
71
0.720978
DeadMonkeyEntertaiment
ba6cf992572b43add1960a145e19ec3d8cf3cdff
41,588
cpp
C++
DESERT_Framework/DESERT/data_link/uwsr/uwsr.cpp
zhiweita/desert
2c40c5a6f5c4dd3f6c1108162056d96f21fc151f
[ "BSD-3-Clause" ]
7
2020-04-14T19:38:20.000Z
2022-01-14T08:06:10.000Z
DESERT_Framework/DESERT/data_link/uwsr/uwsr.cpp
zhiweita/desert
2c40c5a6f5c4dd3f6c1108162056d96f21fc151f
[ "BSD-3-Clause" ]
1
2021-07-10T04:05:04.000Z
2021-07-12T13:57:24.000Z
DESERT_Framework/DESERT/data_link/uwsr/uwsr.cpp
zhiweita/desert
2c40c5a6f5c4dd3f6c1108162056d96f21fc151f
[ "BSD-3-Clause" ]
5
2020-05-07T13:07:26.000Z
2022-01-14T03:01:09.000Z
// // Copyright (c) 2017 Regents of the SIGNET lab, University of Padova. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. Neither the name of the University of Padova (SIGNET lab) nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // /** * @file uwsr.cpp * @author Saiful Azad * @version 1.0.0 * * @brief Implementation of UWSR protocol */ #include "uwsr.h" #include <mac.h> #include <cmath> #include <climits> #include <iomanip> #include <rng.h> #include <algorithm> #include <vector> #include <ctime> #include <cstdlib> /** * Class that represents the binding with tcl scripting language */ static class UWSRModuleClass : public TclClass { public: /** * Constructor of the class */ UWSRModuleClass() : TclClass("Module/UW/USR") { } TclObject * create(int, const char *const *) { return (new MMacUWSR()); } } class_module_uwsr; void MMacUWSR::AckTimer::expire(Event *e) { timer_status = UWSR_EXPIRED; module->incrPktsLostCount(); if (module->curr_state == UWSR_STATE_WAIT_ACK || module->curr_state == UWSR_STATE_PRE_TX_DATA) { if (module->uwsr_debug) cout << NOW << " MMacUWSR(" << module->addr << ") timer expire() current state = " << module->status_info[module->curr_state] << "; ACK not received, next state = " << module->status_info[UWSR_STATE_BACKOFF] << endl; module->refreshReason(UWSR_REASON_ACK_TIMEOUT); module->eraseExpiredItemsFrommapAckandCalc(); module->stateBackoff(); } else { if (module->uwsr_debug) cout << NOW << " MMacUWSR(" << module->addr << ")::AckTimer::expired() in state " << module->status_info[module->curr_state] << endl; } } void MMacUWSR::BackOffTimer::expire(Event *e) { timer_status = UWSR_EXPIRED; if (module->curr_state == UWSR_STATE_BACKOFF) { if (module->uwsr_debug) cout << NOW << " MMacUWSR(" << module->addr << ") timer expire() current state = " << module->status_info[module->curr_state] << "; backoff expired, next state = " << module->status_info[UWSR_STATE_IDLE] << endl; module->refreshReason(UWSR_REASON_BACKOFF_TIMEOUT); module->exitBackoff(); module->stateIdle(); } else { if (module->uwsr_debug) cout << NOW << " MMacUWSR(" << module->addr << ")::BackoffTimer::expired() " << endl; } } void MMacUWSR::ListenTimer::expire(Event *e) { timer_status = UWSR_EXPIRED; if (module->curr_state == UWSR_STATE_LISTEN) { if (module->uwsr_debug) cout << NOW << " MMacUWSR(" << module->addr << ")::timer expire() current state = " << module->status_info[module->curr_state] << "; listening period expired, next state = " << module->status_info[UWSR_STATE_PRE_TX_DATA] << endl; module->refreshReason(UWSR_REASON_LISTEN_TIMEOUT); module->statePreTxData(); } else { if (module->uwsr_debug) cout << NOW << " MMacUWSR(" << module->addr << ")::ListenTimer::expired() " << endl; } } void MMacUWSR::WaitTxTimer::expire(Event *e) { timer_status = UWSR_EXPIRED; if (module->curr_state == UWSR_STATE_PRE_TX_DATA || module->curr_state == UWSR_STATE_RX_IN_PRE_TX_DATA) { if (module->uwsr_debug) cout << NOW << " MMacUWSR(" << module->addr << ")::timer expire() current state = " << module->status_info[module->curr_state] << "; wait tx period expired, next state = " << module->status_info[UWSR_STATE_TX_DATA] << endl; module->refreshReason(UWSR_REASON_WAIT_TX_TIMEOUT); module->stateTxData(); } else { if (module->uwsr_debug) cout << NOW << " MMacUWSR(" << module->addr << ")::wait tx timer expired() " << endl; } } const double MMacUWSR::prop_speed = 1500.0; bool MMacUWSR::initialized = false; map<MMacUWSR::UWSR_STATUS, string> MMacUWSR::status_info; map<MMacUWSR::UWSR_REASON_STATUS, string> MMacUWSR::reason_info; map<MMacUWSR::UWSR_PKT_TYPE, string> MMacUWSR::pkt_type_info; MMacUWSR::MMacUWSR() : wait_tx_timer(this) , ack_timer(this) , listen_timer(this) , backoff_timer(this) , txsn(1) , last_sent_data_id(-1) , curr_data_pkt(0) , last_data_id_rx(-1) , print_transitions(false) , has_buffer_queue(true) , curr_state(UWSR_STATE_IDLE) , prev_state(UWSR_STATE_IDLE) , prev_prev_state(UWSR_STATE_IDLE) , last_reason(UWSR_REASON_NOT_SET) , start_tx_time(0) , srtt(0) , sumrtt(0) , sumrtt2(0) , rttsamples(0) , round_trip_time(0) , wait_tx_time(0) , sumwtt(0) , wttsamples(0) , recv_data_id(-1) , backoff_count(0) , pkt_tx_count(0) , curr_tx_rounds(0) , pkts_sent_1RTT(0) , acks_rcv_1RTT(0) , pkts_lost_counter(0) , prv_mac_addr(-1) , window_size(0) , hit_count(0) , total_pkts_tx(0) , latest_ack_timeout(0) { mac2phy_delay_ = 1e-19; curr_tx_rounds = 0; bind("HDR_size_", (int *) &HDR_size); bind("ACK_size_", (int *) &ACK_size); bind("max_tx_tries_", (int *) &max_tx_tries); bind("wait_costant_", (double *) &wait_constant); bind("uwsr_debug", (double *) &uwsr_debug); // degug mode bind("max_payload_", (int *) &max_payload); bind("ACK_timeout_", (double *) &ACK_timeout); bind("alpha_", (double *) &alpha_); bind("backoff_tuner_", (double *) &backoff_tuner); bind("buffer_pkts_", (int *) &buffer_pkts); bind("max_backoff_counter_", (int *) &max_backoff_counter); bind("listen_time_", &listen_time); bind("guard_time_", (double *) &guard_time); bind("node_speed_", (double *) &node_speed); bind("var_k_", (double *) &var_k); bind("uwsr_debug_", (int *) &uwsr_debug); if (max_tx_tries <= 0) max_tx_tries = INT_MAX; if (buffer_pkts > 0) has_buffer_queue = true; if (listen_time <= 0.0) listen_time = 1e-19; } MMacUWSR::~MMacUWSR() { } // TCL command interpreter int MMacUWSR::command(int argc, const char *const *argv) { Tcl &tcl = Tcl::instance(); if (argc == 2) { if (strcasecmp(argv[1], "initialize") == 0) { if (initialized == false) initInfo(); if (print_transitions) fout.open("/tmp/UWSRstateTransitions.txt", ios_base::app); return TCL_OK; } else if (strcasecmp(argv[1], "printTransitions") == 0) { print_transitions = true; return TCL_OK; } // stats functions else if (strcasecmp(argv[1], "getQueueSize") == 0) { tcl.resultf("%d", mapPacket.size()); return TCL_OK; } else if (strcasecmp(argv[1], "getBackoffCount") == 0) { tcl.resultf("%d", getBackoffCount()); return TCL_OK; } else if (strcasecmp(argv[1], "getAvgPktsTxIn1RTT") == 0) { tcl.resultf("%f", getAvgPktsTxIn1RTT()); return TCL_OK; } } else if (argc == 3) { if (strcasecmp(argv[1], "setMacAddr") == 0) { addr = atoi(argv[2]); if (debug_) cout << "UwSR MAC address of current node is " << addr << endl; return TCL_OK; } } return MMac::command(argc, argv); } void MMacUWSR::initInfo() { initialized = true; if ((print_transitions) && (system(NULL))) { system("rm -f /tmp/UWSRstateTransitions.txt"); system("touch /tmp/UWSRstateTransitions.txt"); } status_info[UWSR_STATE_IDLE] = "Idle state"; status_info[UWSR_STATE_BACKOFF] = "Backoff state"; status_info[UWSR_STATE_TX_DATA] = "Transmit DATA state"; status_info[UWSR_STATE_TX_ACK] = "Transmit ACK state"; status_info[UWSR_STATE_WAIT_ACK] = "Wait for ACK state"; status_info[UWSR_STATE_DATA_RX] = "DATA received state"; status_info[UWSR_STATE_ACK_RX] = "ACK received state"; status_info[UWSR_STATE_LISTEN] = "Listening channel state"; status_info[UWSR_STATE_RX_IDLE] = "Start rx Idle state"; status_info[UWSR_STATE_RX_BACKOFF] = "Start rx Backoff state"; status_info[UWSR_STATE_RX_LISTEN] = "Start rx Listen state"; status_info[UWSR_STATE_RX_WAIT_ACK] = "Start rx Wait ACK state"; status_info[UWSR_STATE_CHK_LISTEN_TIMEOUT] = "Check Listen timeout state"; status_info[UWSR_STATE_CHK_BACKOFF_TIMEOUT] = "Check Backoff timeout state"; status_info[UWSR_STATE_CHK_ACK_TIMEOUT] = "Check Wait ACK timeout state"; status_info[UWSR_STATE_WRONG_PKT_RX] = "Wrong Pkt Rx state"; status_info[UWSR_STATE_WAIT_TX] = "Waiting for transmitting another packet"; status_info[UWSR_STATE_CHK_WAIT_TX_TIMEOUT] = "Check wait tx timeout state"; status_info[UWSR_STATE_WAIT_ACK_WAIT_TX] = "Moving from wait tx state to rx wait ack state"; status_info[UWSR_STATE_RX_DATA_TX_DATA] = "Data receive in txData state and moving to new state"; reason_info[UWSR_REASON_DATA_PENDING] = "DATA pending from upper layers"; reason_info[UWSR_REASON_DATA_RX] = "DATA received"; reason_info[UWSR_REASON_DATA_TX] = "DATA transmitted"; reason_info[UWSR_REASON_ACK_TX] = "ACK tranmsitted"; reason_info[UWSR_REASON_ACK_RX] = "ACK received"; reason_info[UWSR_REASON_BACKOFF_TIMEOUT] = "Backoff expired"; reason_info[UWSR_REASON_ACK_TIMEOUT] = "ACK timeout"; reason_info[UWSR_REASON_DATA_EMPTY] = "DATA queue empty"; reason_info[UWSR_REASON_MAX_TX_TRIES] = "DATA dropped due to max tx rounds"; reason_info[UWSR_REASON_LISTEN] = "DATA pending, listening to channel"; reason_info[UWSR_REASON_LISTEN_TIMEOUT] = "DATA pending, end of listening period"; reason_info[UWSR_REASON_START_RX] = "Start rx pkt"; reason_info[UWSR_REASON_PKT_NOT_FOR_ME] = "Received an erroneous pkt"; reason_info[UWSR_REASON_BACKOFF_PENDING] = "Backoff timer pending"; reason_info[UWSR_REASON_WAIT_ACK_PENDING] = "Wait for ACK timer pending"; reason_info[UWSR_REASON_LISTEN_PENDING] = "Listen to channel pending"; reason_info[UWSR_REASON_PKT_ERROR] = "Erroneous pkt"; reason_info[UWSR_REASON_WAIT_TX] = "Waiting for transmitting another packet"; reason_info[UWSR_REASON_WAIT_TX_PENDING] = "Transmission pending"; reason_info[UWSR_REASON_WAIT_TX_TIMEOUT] = "Waiting for tx timeout"; pkt_type_info[UWSR_ACK_PKT] = "ACK pkt"; pkt_type_info[UWSR_DATA_PKT] = "DATA pkt"; pkt_type_info[UWSR_DATAMAX_PKT] = "MAX payload DATA pkt"; } void MMacUWSR::updateTxStatus(macAddress mac_addr, int rcv_acks) { map<macAddress, txStatusPair>::iterator it_tx; it_tx = mapTxStatus.find(mac_addr); if (it_tx == mapTxStatus.end()) { mapTxStatus.insert( make_pair(mac_addr, make_pair(getPktsSentIn1RTT(), rcv_acks))); } else { if ((it_tx->second).first != getPktsSentIn1RTT()) (it_tx->second).first = getPktsSentIn1RTT(); if ((it_tx->second).second != rcv_acks) (it_tx->second).second = rcv_acks; } } int MMacUWSR::calWindowSize(macAddress mac_addr) { map<macAddress, txStatusPair>::iterator it_tx; it_tx = mapTxStatus.find(mac_addr); if (it_tx == mapTxStatus.end()) { window_size = 1; } else { if ((it_tx->second).first == (it_tx->second).second) window_size = max(window_size, ((it_tx->second).first + 1)); else window_size = (floor((it_tx->second).first * var_k)); } if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::window size " << max(1, window_size) << endl; return max(1, window_size); } void MMacUWSR::putRTTInMap(int mac_addr, double rtt) { double time = NOW; if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::putRTTInMap() mac add " << mac_addr << "rtt " << rtt << "time " << time << endl; map<macAddress, rttPair>::iterator it_d; it_d = mapRTT.find(mac_addr); if (it_d == mapRTT.end()) { mapRTT.insert(make_pair(mac_addr, make_pair(rtt, time))); } else { if (rtt != (it_d->second).first || time != (it_d->second).second) { (it_d->second).first = rtt; (it_d->second).second = time; } else { // do nothing. keep the RTT saved in the map } } } int MMacUWSR::getPktsCanSendIn1RTT(int mac_addr) { if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::getPktsCanSendIn1RTT() rcv mac addr " << mac_addr << endl; int pkts_can_send_1RTT = 1; map<macAddress, rttPair>::iterator it_d = mapRTT.find(mac_addr); if (it_d != mapRTT.end()) { double tx_time = (computeTxTime(UWSR_DATA_PKT) + computeTxTime(UWSR_ACK_PKT) + guard_time); double apprx_travel_dis = 2 * node_speed * (NOW - (it_d->second).second); double apprx_curr_rtt = (it_d->second).first - (apprx_travel_dis / prop_speed); pkts_can_send_1RTT = max(1, (int) (floor(apprx_curr_rtt / tx_time))); } if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::No pkts can send in 1 RTT is " << pkts_can_send_1RTT << endl; if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::Window size: " << window_size << endl; if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::Pkts can transmit in 1 RTT is " << min(window_size, pkts_can_send_1RTT) << endl; return min(calWindowSize(mac_addr), pkts_can_send_1RTT); } bool MMacUWSR::chkItemInmapTxRounds(int mac_addr, int seq_num) { map<usrPair, txRounds>::iterator it_t; it_t = mapTxRounds.find(make_pair(mac_addr, seq_num)); if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::chkItemInmapTxRounds()" << endl; if (it_t != mapTxRounds.end()) return true; else return false; } double MMacUWSR::calcWaitTxTime(int mac_addr) { if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::calcWaitTxTime() rcv mac addr " << mac_addr << endl; double wait_time; double rtt_time; double pkts_can_tx; map<macAddress, rttPair>::iterator it_d; it_d = mapRTT.find(mac_addr); if (it_d == mapRTT.end()) { cerr << NOW << " MMacUWSR(" << addr << ")::calcWaitTxTime() is accessed in inappropriate time" << endl; exit(1); } else rtt_time = (it_d->second).first; pkts_can_tx = getPktsCanSendIn1RTT(mac_addr); wait_time = ((computeTxTime(UWSR_ACK_PKT) / 2 + rtt_time - (pkts_can_tx - 1) * computeTxTime(UWSR_DATA_PKT)) / (pkts_can_tx - 0.5)); if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::round trip time " << rtt_time << endl; if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::calcWaitTxTime() wait time " << wait_time << endl; return wait_time; } bool MMacUWSR::checkMultipleTx(int rcv_mac_addr) { if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::checkMultipleTx() rcv mac addr " << rcv_mac_addr << endl; Packet *nxt_data_pkt; map<usrPair, Packet *>::iterator it_p; map<usrPair, AckTimer>::iterator it_a; int nxt_mac_addr; if (mapPacket.size() == 0) return false; else if (mapPacket.size() <= mapAckTimer.size()) return false; else if (getPktsCanSendIn1RTT(rcv_mac_addr) < 2) return false; else { for (it_p = mapPacket.begin(); it_p != mapPacket.end(); it_p++) { it_a = mapAckTimer.find((*it_p).first); if ((*it_a).first != (*it_p).first) { nxt_data_pkt = (*it_p).second; if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::Next Packet transmitting: " << nxt_data_pkt << endl; hdr_mac *mach = HDR_MAC(nxt_data_pkt); nxt_mac_addr = mach->macDA(); if (rcv_mac_addr == nxt_mac_addr) break; } else nxt_mac_addr = -1; } if (rcv_mac_addr == nxt_mac_addr && getPktsCanSendIn1RTT(rcv_mac_addr) > getPktsSentIn1RTT()) return true; else return false; } } int MMacUWSR::checkAckTimer(CHECK_ACK_TIMER type) { int iteration_count = 0; int active_count = 0; int idle_count = 0; int expired_count = 0; int value = 0; map<usrPair, AckTimer>::iterator it_a; for (it_a = mapAckTimer.begin(); it_a != mapAckTimer.end(); it_a++) { if (((*it_a).second).isActive()) { active_count += 1; } else if (((*it_a).second).isExpired()) { expired_count += 1; } else if (((*it_a).second).isIdle()) { idle_count += 1; } else { cerr << "Ack Timer is in wrong state" << endl; exit(1); } iteration_count += 1; } if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::No of item in ack map: " << mapAckTimer.size() << endl; if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::No of iteration count: " << iteration_count << endl; if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::No of active count: " << active_count << endl; if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::No of expired count: " << expired_count << endl; if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::No of idle count: " << idle_count << endl; if (type == CHECK_ACTIVE) { if (mapAckTimer.size() == 0) { value = 1; } else { value = floor(active_count / mapAckTimer.size()); } } else if (type == CHECK_EXPIRED) { value = expired_count; } else if (type == CHECK_IDLE) { value = idle_count; } else { if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::Ack Timer is in wrong state" << endl; exit(1); } if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::returning value: " << value << endl; return value; } void MMacUWSR::eraseExpiredItemsFrommapAckandCalc() { if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::Erasing expired items from map ack and calc" << endl; map<usrPair, AckTimer>::iterator it_a1, it_a2; it_a1 = mapAckTimer.begin(); while (it_a1 != mapAckTimer.end()) { it_a2 = it_a1; it_a1++; if (((*it_a2).second).isExpired()) { int mac_addr = (it_a2->first).first; int seq_num = (it_a2->first).second; eraseItemFrommapAckTimer(mac_addr, seq_num); eraseItemFrommapCalcAck(mac_addr, seq_num); } else { // do nothing } } } double MMacUWSR::computeTxTime(UWSR_PKT_TYPE type) { map<usrPair, Packet *>::iterator it_p; double duration; Packet *temp_data_pkt; if (type == UWSR_DATA_PKT) { if (!mapPacket.empty()) { it_p = mapPacket.begin(); temp_data_pkt = ((*it_p).second)->copy(); hdr_cmn *ch = HDR_CMN(temp_data_pkt); ch->size() = HDR_size + ch->size(); } else { temp_data_pkt = Packet::alloc(); hdr_cmn *ch = HDR_CMN(temp_data_pkt); ch->size() = HDR_size + max_payload; } } else if (type == UWSR_ACK_PKT) { temp_data_pkt = Packet::alloc(); hdr_cmn *ch = HDR_CMN(temp_data_pkt); ch->size() = ACK_size; } duration = Mac2PhyTxDuration(temp_data_pkt); Packet::free(temp_data_pkt); return (duration); } void MMacUWSR::exitBackoff() { backoff_timer.stop(); } double MMacUWSR::getBackoffTime() { incrTotalBackoffTimes(); double random = RNG::defaultrng()->uniform_double(); backoff_timer.incrCounter(); double counter = backoff_timer.getCounter(); if (counter > max_backoff_counter) counter = max_backoff_counter; double backoff_duration = backoff_tuner * random * 2.0 * ACK_timeout * pow(2.0, counter); backoffSumDuration(backoff_duration); if (uwsr_debug) { cout << NOW << " MMacUWSR(" << addr << ")::getBackoffTime() backoff time = " << backoff_duration << " latest ack timeout = " << (latest_ack_timeout - NOW) << endl; } return max((latest_ack_timeout - NOW) + wait_constant, backoff_duration); } void MMacUWSR::recvFromUpperLayers(Packet *p) { if (((has_buffer_queue == true) && (mapPacket.size() < buffer_pkts)) || (has_buffer_queue == false)) { initPkt(p, UWSR_DATA_PKT); putPktInQueue(p); incrUpperDataRx(); waitStartTime(); if (curr_state == UWSR_STATE_IDLE) { refreshReason(UWSR_REASON_DATA_PENDING); stateListen(); } } else { incrDiscardedPktsTx(); drop(p, 1, UWSR_DROP_REASON_BUFFER_FULL); } } void MMacUWSR::initPkt(Packet *p, UWSR_PKT_TYPE type, int dest_addr) { hdr_cmn *ch = hdr_cmn::access(p); hdr_mac *mach = HDR_MAC(p); int curr_size = ch->size(); switch (type) { case (UWSR_DATA_PKT): { ch->size() = curr_size + HDR_size; } break; case (UWSR_ACK_PKT): { ch->ptype() = PT_MMAC_ACK; ch->size() = ACK_size; ch->uid() = recv_data_id; mach->set(MF_CONTROL, addr, dest_addr); mach->macSA() = addr; mach->macDA() = dest_addr; } break; } } void MMacUWSR::Mac2PhyStartTx(Packet *p) { if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::Mac2PhyStartTx() start tx packet" << endl; MMac::Mac2PhyStartTx(p); } void MMacUWSR::Phy2MacEndTx(const Packet *p) { hdr_cmn *ch = hdr_cmn::access(p); int seq_num = ch->uid(); hdr_mac *mach = HDR_MAC(p); int dst_mac_addr = mach->macDA(); prv_mac_addr = dst_mac_addr; if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::Phy2MacEndTx() end tx packet" << endl; if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::Phy2MacEndTx() dst mac addr " << dst_mac_addr << endl; switch (curr_state) { case (UWSR_STATE_TX_DATA): { refreshReason(UWSR_REASON_DATA_TX); incrPktsSentIn1RTT(); double wait_time, ack_time; double ack_timeout_time; map<int, rttPair>::iterator it_d; it_d = mapRTT.find(dst_mac_addr); if (it_d == mapRTT.end()) ack_timeout_time = ACK_timeout + 2 * wait_constant; else ack_timeout_time = getRTTInMap(dst_mac_addr) + 2 * wait_constant; ack_time = NOW + ack_timeout_time; putAckTimerInMap(dst_mac_addr, seq_num); map<usrPair, AckTimer>::iterator it_a; it_a = mapAckTimer.find(make_pair(dst_mac_addr, seq_num)); ((*it_a).second).stop(); ((*it_a).second).schedule(ack_timeout_time); if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::Phy2MacEndTx(), ack_timeout_time: " << ack_time << " latest_ack_timeout " << latest_ack_timeout << endl; if (ack_time > latest_ack_timeout) latest_ack_timeout = ack_time; if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::Phy2MacEndTx(), ack_timeout_time: " << ack_time << " latest_ack_timeout " << latest_ack_timeout << endl; if (checkMultipleTx(dst_mac_addr)) { if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::Phy2MacEndTx() DATA sent,from " << status_info[curr_state] << " to " << status_info[UWSR_STATE_PRE_TX_DATA] << endl; wait_time = calcWaitTxTime(dst_mac_addr); wait_tx_timer.stop(); wait_tx_timer.incrCounter(); wait_tx_timer.schedule(wait_time); statePreTxData(); } else { if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::Phy2MacEndTx() DATA sent,from " << status_info[curr_state] << " to " << status_info[UWSR_STATE_WAIT_ACK] << endl; updateTxStatus(dst_mac_addr, 0); calTotalPktsTx(); stateWaitAck(); } } break; case (UWSR_STATE_TX_ACK): { refreshReason(UWSR_REASON_ACK_TX); if (prev_prev_state == UWSR_STATE_RX_BACKOFF) { if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::Phy2MacEndTx() ack sent, from " << status_info[curr_state] << " to " << status_info[UWSR_STATE_CHK_BACKOFF_TIMEOUT] << endl; stateCheckBackoffExpired(); } else if (prev_prev_state == UWSR_STATE_RX_WAIT_ACK) { if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::Phy2MacEndTx() ack sent, from " << status_info[curr_state] << " to " << status_info[UWSR_STATE_CHK_BACKOFF_TIMEOUT] << endl; stateCheckAckExpired(); } else if (prev_prev_state == UWSR_STATE_RX_IN_PRE_TX_DATA) { if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::Phy2MacEndTx() ack sent, from " << status_info[curr_state] << " to " << status_info[UWSR_STATE_CHK_BACKOFF_TIMEOUT] << endl; stateCheckWaitTxExpired(); } else if (prev_prev_state == UWSR_STATE_RX_LISTEN) { if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::Phy2MacEndTx() ack sent, from " << status_info[curr_state] << " to " << status_info[UWSR_STATE_CHK_LISTEN_TIMEOUT] << endl; stateCheckListenExpired(); } else if (prev_prev_state == UWSR_STATE_RX_IDLE) { if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::Phy2MacEndTx() ack sent, from " << status_info[curr_state] << " to " << status_info[UWSR_STATE_IDLE] << endl; stateIdle(); } else { cerr << NOW << " MMacUWSR(" << addr << ")::Phy2MacEndTx() logical error in timers, current " "state = " << status_info[curr_state] << endl; exit(1); } } break; default: { cerr << NOW << " MMacUWSR(" << addr << ")::Phy2MacEndTx() logical error, current state = " << status_info[curr_state] << endl; exit(1); } break; } } void MMacUWSR::Phy2MacStartRx(const Packet *p) { if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::Phy2MacStartRx() rx Packet " << endl; refreshReason(UWSR_REASON_START_RX); switch (curr_state) { case (UWSR_STATE_IDLE): stateRxIdle(); break; case (UWSR_STATE_LISTEN): stateRxListen(); break; case (UWSR_STATE_BACKOFF): stateRxBackoff(); break; case (UWSR_STATE_PRE_TX_DATA): stateRxinPreTxData(); break; case (UWSR_STATE_WAIT_ACK): stateRxWaitAck(); break; default: { cerr << NOW << " MMacUWSR(" << addr << ")::Phy2MacStartRx() logical warning, current state = " << status_info[curr_state] << endl; } } } void MMacUWSR::Phy2MacEndRx(Packet *p) { hdr_cmn *ch = HDR_CMN(p); packet_t rx_pkt_type = ch->ptype(); hdr_mac *mach = HDR_MAC(p); hdr_MPhy *ph = HDR_MPHY(p); int source_mac = mach->macSA(); int dest_mac = mach->macDA(); double gen_time = ph->txtime; double received_time = ph->rxtime; double diff_time = received_time - gen_time; putRTTInMap(source_mac, 2 * diff_time); double distance = diff_time * prop_speed; int seq_num = getPktSeqNum(p); map<usrPair, AckTimer>::iterator it_a; if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::Phy2MacEndRx() " << status_info[curr_state] << ", received a pkt type = " << ch->ptype() << ", src addr = " << mach->macSA() << " dest addr = " << mach->macDA() << " RTT = " << 2 * diff_time << ", estimated distance between nodes = " << distance << " m " << endl; if (ch->error()) { if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::Phy2MacEndRx() dropping corrupted pkt " << endl; incrErrorPktsRx(); refreshReason(UWSR_REASON_PKT_ERROR); drop(p, 1, UWSR_DROP_REASON_ERROR); stateRxPacketNotForMe(NULL); } else { if (dest_mac == addr || dest_mac == MAC_BROADCAST) { if (rx_pkt_type == PT_MMAC_ACK) { it_a = mapAckTimer.find(make_pair(source_mac, seq_num)); if (it_a != mapAckTimer.end()) { refreshReason(UWSR_REASON_ACK_RX); stateRxAck(p); } else { drop(p, 1, UWSR_DROP_REASON_ERROR); stateRxPacketNotForMe(NULL); } } else { refreshReason(UWSR_REASON_DATA_RX); stateRxData(p); } } else { refreshReason(UWSR_REASON_PKT_NOT_FOR_ME); stateRxPacketNotForMe(p); } } } void MMacUWSR::stateTxData() { refreshState(UWSR_STATE_TX_DATA); if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::stateTxData" << endl; Packet *data_pkt = curr_data_pkt->copy(); // copio pkt int seq_num = getPktSeqNum(data_pkt); int mac_addr = getMacAddress(data_pkt); start_tx_time = NOW; map<usrPair, txStartTime>::iterator it_ca; it_ca = mapCalcAck.find(make_pair(mac_addr, seq_num)); if (it_ca == mapCalcAck.end()) putStartTxTimeInMap(mac_addr, seq_num, start_tx_time); incrDataPktsTx(); Mac2PhyStartTx(data_pkt); } void MMacUWSR::txAck(int dest_addr) { Packet *ack_pkt = Packet::alloc(); initPkt(ack_pkt, UWSR_ACK_PKT, dest_addr); incrAckPktsTx(); Mac2PhyStartTx(ack_pkt); } void MMacUWSR::stateRxPacketNotForMe(Packet *p) { if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::stateRxPacketNotForMe() pkt for another address. Dropping " "pkt" << endl; if (p != NULL) Packet::free(p); refreshState(UWSR_STATE_WRONG_PKT_RX); switch (prev_state) { case UWSR_STATE_RX_IDLE: stateIdle(); break; case UWSR_STATE_RX_LISTEN: stateCheckListenExpired(); break; case UWSR_STATE_RX_BACKOFF: stateCheckBackoffExpired(); break; case UWSR_STATE_RX_IN_PRE_TX_DATA: stateCheckWaitTxExpired(); break; case UWSR_STATE_RX_WAIT_ACK: stateCheckAckExpired(); break; default: cerr << NOW << " MMacUWSR(" << addr << ")::stateRxPacketNotForMe() logical error, current state = " << status_info[curr_state] << endl; curr_state = prev_state; prev_state = prev_prev_state; break; } } void MMacUWSR::stateCheckListenExpired() { refreshState(UWSR_STATE_CHK_LISTEN_TIMEOUT); if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::stateCheckListenExpired()" << endl; if (print_transitions) printStateInfo(); if (listen_timer.isActive()) { refreshReason(UWSR_REASON_LISTEN_PENDING); refreshState(UWSR_STATE_LISTEN); } else if (listen_timer.isExpired()) { refreshReason(UWSR_REASON_LISTEN_TIMEOUT); if (!(prev_state == UWSR_STATE_TX_ACK || prev_state == UWSR_STATE_WRONG_PKT_RX || prev_state == UWSR_STATE_ACK_RX || prev_state == UWSR_STATE_DATA_RX)) stateTxData(); else stateListen(); } else { cerr << NOW << " MMacUWSR(" << addr << ")::stateCheckListenExpired() listen_timer logical error, " "current timer state = " << status_info[curr_state] << endl; exit(1); } } void MMacUWSR::stateCheckAckExpired() { refreshState(UWSR_STATE_CHK_ACK_TIMEOUT); if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::stateCheckAckExpired()" << endl; if (print_transitions) printStateInfo(); if (mapAckTimer.size() == 0) stateIdle(); else if (checkAckTimer(CHECK_ACTIVE)) { refreshReason(UWSR_REASON_WAIT_ACK_PENDING); refreshState(UWSR_STATE_WAIT_ACK); } else if (checkAckTimer(CHECK_EXPIRED) > 0) { refreshReason(UWSR_REASON_ACK_TIMEOUT); eraseExpiredItemsFrommapAckandCalc(); stateBackoff(); } else { cerr << NOW << " MMacUWSR(" << addr << ")::stateCheckAckExpired() ack_timer logical error, current " "timer state = " << status_info[curr_state] << endl; exit(1); } } void MMacUWSR::stateCheckBackoffExpired() { refreshState(UWSR_STATE_CHK_BACKOFF_TIMEOUT); if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::stateCheckBackoffExpired()" << endl; if (print_transitions) printStateInfo(); if (backoff_timer.isActive()) { refreshReason(UWSR_REASON_BACKOFF_PENDING); stateBackoff(); } else if (backoff_timer.isExpired()) { refreshReason(UWSR_REASON_BACKOFF_TIMEOUT); exitBackoff(); stateIdle(); } else { cerr << NOW << " MMacUWSR(" << addr << ")::stateCheckBackoffExpired() backoff_timer logical error, " "current timer state = " << status_info[curr_state] << endl; exit(1); } } void MMacUWSR::stateCheckWaitTxExpired() { refreshState(UWSR_STATE_CHK_WAIT_TX_TIMEOUT); if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::stateCheckWaitTxExpired()" << endl; if (print_transitions) printStateInfo(); if (checkAckTimer(CHECK_EXPIRED) > 0) { refreshReason(UWSR_REASON_ACK_TIMEOUT); eraseExpiredItemsFrommapAckandCalc(); stateBackoff(); } else if (checkAckTimer(CHECK_ACTIVE)) { if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::wait tx is active:" << wait_tx_timer.isActive() << endl; if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::wait tx is expired:" << wait_tx_timer.isExpired() << endl; if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::wait tx is idle:" << wait_tx_timer.isIdle() << endl; if (wait_tx_timer.isActive()) { refreshReason(UWSR_REASON_WAIT_TX_PENDING); refreshState(UWSR_STATE_PRE_TX_DATA); } else if (wait_tx_timer.isExpired()) { refreshReason(UWSR_REASON_WAIT_TX_TIMEOUT); refreshState(UWSR_STATE_PRE_TX_DATA); stateTxData(); } else { cerr << NOW << " MMacUWSR(" << addr << ")::stateCheckWaitTxExpired() wait_tx_timer logical error, " "current timer state = " << status_info[curr_state] << endl; exit(1); } } else { cerr << NOW << " MMacUWSR(" << addr << ")::stateCheckAckExpired() ack_timer logical error, current " "timer state = " << status_info[curr_state] << endl; exit(1); } } void MMacUWSR::stateIdle() { rstPktsLostCount(); if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::stateIdle(), Pkts sent in one RTT: " << getPktsSentIn1RTT() << endl; rstPktsSentIn1RTT(); rstAcksRcvIn1RTT(); backoff_timer.stop(); listen_timer.stop(); wait_tx_timer.stop(); refreshState(UWSR_STATE_IDLE); if (print_transitions) printStateInfo(); if (!mapPacket.empty()) { refreshReason(UWSR_REASON_LISTEN); stateListen(); } } void MMacUWSR::stateRxIdle() { refreshState(UWSR_STATE_RX_IDLE); if (print_transitions) printStateInfo(); } void MMacUWSR::stateListen() { listen_timer.stop(); refreshState(UWSR_STATE_LISTEN); listen_timer.incrCounter(); double time = listen_time * RNG::defaultrng()->uniform_double() + wait_constant; if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::stateListen() listen time = " << time << endl; if (print_transitions) printStateInfo(); listen_timer.schedule(time); } void MMacUWSR::stateRxListen() { refreshState(UWSR_STATE_RX_LISTEN); if (print_transitions) printStateInfo(); } void MMacUWSR::stateBackoff() { rstPktsLostCount(); wait_tx_timer.stop(); refreshState(UWSR_STATE_BACKOFF); setBackoffCount(); if (backoff_timer.isFrozen()) backoff_timer.unFreeze(); else backoff_timer.schedule(getBackoffTime()); if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::stateBackoff() get backoff time " << getBackoffTime() << endl; if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::stateBackoff() " << endl; if (print_transitions) printStateInfo(backoff_timer.getDuration()); } void MMacUWSR::stateRxBackoff() { backoff_timer.freeze(); refreshState(UWSR_STATE_RX_BACKOFF); if (print_transitions) printStateInfo(); } bool MMacUWSR::prepBeforeTx(int mac_addr, int seq_num) { if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::prepBeforeTx(), is item in tx rounds map " << chkItemInmapTxRounds(mac_addr, seq_num) << endl; if (chkItemInmapTxRounds(mac_addr, seq_num)) { if (getCurrTxRounds(mac_addr, seq_num) < max_tx_tries + 1) { last_sent_data_id = seq_num; incrCurrTxRounds(mac_addr, seq_num); return true; } else { eraseItemFromPktQueue(mac_addr, seq_num); eraseItemFromTxRounds(mac_addr, seq_num); eraseItemFrommapAckTimer(mac_addr, seq_num); incrDroppedPktsTx(); refreshReason(UWSR_REASON_MAX_TX_TRIES); if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::stateTxData() curr_tx_rounds " << curr_tx_rounds << " > max_tx_tries = " << max_tx_tries << endl; return false; } } else { listen_timer.resetCounter(); backoff_timer.resetCounter(); setCurrTxRounds(mac_addr, seq_num); return true; } } void MMacUWSR::statePreTxData() { refreshState(UWSR_STATE_PRE_TX_DATA); if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::Time require to transmit a data packet: " << computeTxTime(UWSR_DATA_PKT) << endl; if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::Time require to transmit an ack packet: " << computeTxTime(UWSR_ACK_PKT) << endl; if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::statePreTxData() " << endl; if (print_transitions) printStateInfo(); map<usrPair, Packet *>::iterator it_p; map<usrPair, AckTimer>::iterator it_a; int curr_mac_addr; int seq_num; it_p = mapPacket.begin(); if (mapPacket.size() == 0) { stateIdle(); } else if (mapAckTimer.size() == 0) { curr_data_pkt = (*it_p).second; if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::Packet transmitting: " << curr_data_pkt << endl; seq_num = getPktSeqNum(curr_data_pkt); if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::seq_num: " << seq_num << endl; hdr_mac *mach = HDR_MAC(curr_data_pkt); curr_mac_addr = mach->macDA(); if (prepBeforeTx(curr_mac_addr, seq_num)) { if (prev_state == UWSR_STATE_LISTEN) { stateTxData(); } else { stateCheckWaitTxExpired(); } } else stateIdle(); } else if (mapPacket.size() > mapAckTimer.size()) { // int seq_num; for (it_p = mapPacket.begin(); it_p != mapPacket.end(); it_p++) { it_a = mapAckTimer.find((*it_p).first); if ((*it_a).first != (*it_p).first) { // it_p = mapPacket.begin(); curr_data_pkt = (*it_p).second; if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::Packet transmitting: " << curr_data_pkt << endl; seq_num = getPktSeqNum(curr_data_pkt); if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::seq_num: " << seq_num << endl; hdr_mac *mach = HDR_MAC(curr_data_pkt); curr_mac_addr = mach->macDA(); if (prev_state == UWSR_STATE_TX_DATA) { if (curr_mac_addr == prv_mac_addr) break; // else continue; } else break; } } if (prepBeforeTx(curr_mac_addr, seq_num)) { if (prev_state == UWSR_STATE_LISTEN) { stateTxData(); } else { stateCheckWaitTxExpired(); } } else stateIdle(); } else { stateCheckAckExpired(); } } void MMacUWSR::stateWaitAck() { refreshState(UWSR_STATE_WAIT_ACK); if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::stateWaitAck() " << endl; if (print_transitions) printStateInfo(); } void MMacUWSR::stateRxWaitAck() { refreshState(UWSR_STATE_RX_WAIT_ACK); if (print_transitions) printStateInfo(); } void MMacUWSR::stateRxinPreTxData() { refreshState(UWSR_STATE_RX_IN_PRE_TX_DATA); if (print_transitions) printStateInfo(); } void MMacUWSR::stateTxAck(int dest_addr) { refreshState(UWSR_STATE_TX_ACK); if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::stateTxAck() dest addr " << dest_addr << endl; if (print_transitions) printStateInfo(); txAck(dest_addr); } void MMacUWSR::stateRxData(Packet *data_pkt) { refreshState(UWSR_STATE_DATA_RX); if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::stateRxData() " << endl; refreshReason(UWSR_REASON_DATA_RX); hdr_mac *mach = HDR_MAC(data_pkt); int dst_addr = mach->macSA(); hdr_cmn *ch = hdr_cmn::access(data_pkt); ch->size() = ch->size() - HDR_size; recv_data_id = ch->uid(); incrDataPktsRx(); sendUp(data_pkt); // mando agli strati superiori il pkt stateTxAck(dst_addr); } void MMacUWSR::stateRxAck(Packet *p) { refreshState(UWSR_STATE_ACK_RX); if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::stateRxAck() " << endl; hdr_mac *mach = HDR_MAC(p); int curr_mac_addr = mach->macSA(); int seq_num = getPktSeqNum(p); map<usrPair, AckTimer>::iterator it_a; map<usrPair, txStartTime>::iterator it_ca; it_a = mapAckTimer.find(make_pair(curr_mac_addr, seq_num)); ((*it_a).second).stop(); it_ca = mapCalcAck.find(make_pair(curr_mac_addr, seq_num)); double start_tx_time = ((*it_ca).second); eraseItemFromPktQueue(curr_mac_addr, seq_num); eraseItemFromTxRounds(curr_mac_addr, seq_num); eraseItemFrommapAckTimer(curr_mac_addr, seq_num); eraseItemFrommapCalcAck(curr_mac_addr, seq_num); incrAckPktsRx(); incrAcksRcvIn1RTT(); updateTxStatus(curr_mac_addr, getAcksRcvIn1RTT()); Packet::free(p); refreshReason(UWSR_REASON_ACK_RX); switch (prev_state) { case UWSR_STATE_RX_IDLE: stateIdle(); break; case UWSR_STATE_RX_LISTEN: stateCheckListenExpired(); break; case UWSR_STATE_RX_BACKOFF: stateCheckBackoffExpired(); break; case UWSR_STATE_RX_WAIT_ACK: if (mapAckTimer.size() > 0) stateCheckAckExpired(); else stateIdle(); break; case UWSR_STATE_RX_IN_PRE_TX_DATA: { if (mapPacket.size() == 0) stateIdle(); else stateCheckWaitTxExpired(); } break; default: cerr << NOW << " MMacUWSR(" << addr << ")::stateRxAck() logical error, prev state = " << status_info[prev_state] << endl; exit(1); } } void MMacUWSR::printStateInfo(double delay) { if (uwsr_debug) cout << NOW << " MMacUWSR(" << addr << ")::printStateInfo() " << "from " << status_info[prev_state] << " to " << status_info[curr_state] << ". Reason: " << reason_info[last_reason] << endl; if (curr_state == UWSR_STATE_BACKOFF) { fout << left << setw(10) << NOW << " MMacUWSR(" << addr << ")::printStateInfo() " << "from " << status_info[prev_state] << " to " << status_info[curr_state] << ". Reason: " << reason_info[last_reason] << ". Backoff duration = " << delay << endl; } else { fout << left << setw(10) << NOW << " MMacUWSR(" << addr << ")::printStateInfo() " << "from " << status_info[prev_state] << " to " << status_info[curr_state] << ". Reason: " << reason_info[last_reason] << endl; } } void MMacUWSR::waitForUser() { std::string response; std::cout << "Press Enter to continue"; std::getline(std::cin, response); }
25.751084
78
0.665745
zhiweita
ba6e98b0643febbef65ac30b6dcbe7b173e91508
3,657
cpp
C++
jerome/xml/record_writer.cpp
leuski-ict/jerome
6141a21c50903e98a04c79899164e7d0e82fe1c2
[ "Apache-2.0" ]
3
2018-06-11T10:48:54.000Z
2021-05-30T07:10:15.000Z
jerome/xml/record_writer.cpp
leuski-ict/jerome
6141a21c50903e98a04c79899164e7d0e82fe1c2
[ "Apache-2.0" ]
null
null
null
jerome/xml/record_writer.cpp
leuski-ict/jerome
6141a21c50903e98a04c79899164e7d0e82fe1c2
[ "Apache-2.0" ]
null
null
null
// // record_writer.cpp // // Created by Anton Leuski on 8/31/15. // Copyright (c) 2015 Anton Leuski & ICT/USC. All rights reserved. // // This file is part of Jerome. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "writer_manip.hpp" #include "record_writer.hpp" namespace jerome { // namespace xml { // namespace detail { // template <typename T> // static std::ostream& writeRecord( // std::ostream& os, // const RecordTags& inRecordTags, // const ordered_multimap<String,T>& inRecord) // { // os // << xml::startElement(inRecordTags.element); // // os << record(RecordTags()); // // for(const auto& p : inRecord) { // os // << xml::startElement(inRecordTags.item) // << xml::attribute(inRecordTags.nameAttribute, p.first, inRecordTags.defaultName) // << p.second // << xml::endElement; // } // // return os // << xml::endElement; // } // // struct RecordTagsStorage { // static const int xindex; // static RecordTagsStorage& fromStream(std::ios_base& os); // static void callback(std::ios_base::event evt, std::ios_base& str, int idx); // static RecordTagsStorage* pointer(std::ios_base& os) { // return static_cast<RecordTagsStorage*>(os.pword(xindex)); // } // // RecordTags recordTags; // RecordTags recordOfRecordTags; // }; // // const int RecordTagsStorage::xindex = std::ios_base::xalloc(); // // RecordTagsStorage& RecordTagsStorage::fromStream(std::ios_base& os) // { // RecordTagsStorage* p = pointer(os); // if (!p) { // p = new RecordTagsStorage; // os.pword(xindex) = p; // os.register_callback(callback, xindex); // } // return *p; // } // // void RecordTagsStorage::callback(std::ios_base::event evt, std::ios_base& os, int idx) // { // if (evt == std::ios_base::erase_event) { // RecordTagsStorage* p = pointer(os); // delete p; // os.pword(xindex) = nullptr; // } else if (evt == std::ios_base::copyfmt_event) { // RecordTagsStorage* p = pointer(os); // if (p) p = new RecordTagsStorage(*p); // os.pword(xindex) = p; // } // } // // } // // std::ostream& operator << (std::ostream& os, const record& inRecord) // { // detail::RecordTagsStorage s(detail::RecordTagsStorage::fromStream(os)); // s.recordTags = inRecord.mTags; // if (inRecord.mOtherTags) s.recordOfRecordTags = *inRecord.mOtherTags; // return os; // } // // } // using namespace jerome::xml::detail; // // std::ostream& operator << (std::ostream& os, const Record& inRecord) // { // return writeRecord(os, RecordTagsStorage::fromStream(os).recordTags, // inRecord); // } // // std::ostream& operator << (std::ostream& os, const RecordOfRecords& inRecord) // { // return writeRecord(os, RecordTagsStorage::fromStream(os).recordOfRecordTags, // inRecord); // } }
30.991525
94
0.591742
leuski-ict
ba6efdb490e36cace6d88e9e5a892e15d3a83340
502
cpp
C++
UnitTest/Windows/UnitTest_CommonFunc/main.cpp
LalaChen/SDEngine
ae5931308ae8b02f4237a1e26ef8448f773f9b7a
[ "MIT" ]
null
null
null
UnitTest/Windows/UnitTest_CommonFunc/main.cpp
LalaChen/SDEngine
ae5931308ae8b02f4237a1e26ef8448f773f9b7a
[ "MIT" ]
null
null
null
UnitTest/Windows/UnitTest_CommonFunc/main.cpp
LalaChen/SDEngine
ae5931308ae8b02f4237a1e26ef8448f773f9b7a
[ "MIT" ]
null
null
null
#include <iostream> #include "SDEngineCommonFunction.h" using namespace SDE::Basic; int main(int argc, char **argv) { std::cout << "SDEngine Common Func Unit Test" << std::endl; //1. String Format. { int six = 666666; std::string result; result = StringFormat("Test six = %d and convert string", six); std::cout << "Test 1 : StringFormat => " << result << ". size = "<< result.size() <<". length = "<< result.length()<< std::endl; } return 0; }
25.1
136
0.577689
LalaChen
ba77ba2419c1db41e35c9cbf061c16a9a8c8c053
2,864
cpp
C++
testfizz.cpp
atishbits/101
4b4a8e56d82fe2706f065ded7877deebe8f6164f
[ "MIT" ]
null
null
null
testfizz.cpp
atishbits/101
4b4a8e56d82fe2706f065ded7877deebe8f6164f
[ "MIT" ]
null
null
null
testfizz.cpp
atishbits/101
4b4a8e56d82fe2706f065ded7877deebe8f6164f
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; void patternStartEnd(const vector<string>& input, int i=3) { bool done = false; bool anymatch = false; int pos = 0; string curr; int start; while (!done) { if(i%3 == 0 && i%5 == 0) { curr = "fizzbuzz"; //TODO: the if/else block below should be bundled into a single bool //needrecurr(..) function if(anymatch) {//we expect it to match //else we need to recurr if(curr.compare(input[pos]) != 0) { patternStartEnd(input, i+1); done = true; } else { //check end condition if(pos == input.size() - 1) { done = true; cout << "[" << start << "," << i << "]" << endl; } pos++; } } else { if(curr.compare(input[pos]) == 0) { start = i; pos++; anymatch = true; } } } else if(i%3 == 0) { curr = "fizz"; if(anymatch) {//we expect it to match //else we need to recurr if(curr.compare(input[pos]) != 0) { patternStartEnd(input, i+1); done = true; } else { //check end condition if(pos == input.size() - 1) { done = true; cout << "[" << start << "," << i << "]" << endl; } pos++; } } else { if(curr.compare(input[pos]) == 0) { start = i; pos++; anymatch = true; } } } else if(i%5 == 0) { curr = "buzz"; if(anymatch) {//we expect it to match //else we need to recurr if(curr.compare(input[pos]) != 0) { patternStartEnd(input, i+1); done = true; } else { //check end condition if(pos == input.size() - 1) { done = true; cout << "[" << start << "," << i << "]" << endl; } pos++; } } else { if(curr.compare(input[pos]) == 0) { start = i; pos++; anymatch = true; } } } i = i+1; } } int main() { const vector<string> input = {"buzz", "fizz", "fizzbuzz"}; //const vector<string> input = {"fizz", "buzz", "fizz", "fizzbuzz"}; patternStartEnd(input); }
30.468085
78
0.350908
atishbits
ba78d57702ca4a332cb585f7b24da31f39596dbf
6,438
cpp
C++
Unix/samples/Providers/PersonProviderCXX/TestEmbeddedOperations_Class_Provider.cpp
Beguiled/omi
1c824681ee86f32314f430db972e5d3938f10fd4
[ "MIT" ]
165
2016-08-18T22:06:39.000Z
2019-05-05T11:09:37.000Z
Unix/samples/Providers/PersonProviderCXX/TestEmbeddedOperations_Class_Provider.cpp
snchennapragada/omi
4fa565207d3445d1f44bfc7b890f9ea5ea7b41d0
[ "MIT" ]
409
2016-08-18T20:52:56.000Z
2019-05-06T10:03:11.000Z
Unix/samples/Providers/PersonProviderCXX/TestEmbeddedOperations_Class_Provider.cpp
snchennapragada/omi
4fa565207d3445d1f44bfc7b890f9ea5ea7b41d0
[ "MIT" ]
72
2016-08-23T02:30:08.000Z
2019-04-30T22:57:03.000Z
/* **============================================================================== ** ** Copyright (c) Microsoft Corporation. All rights reserved. See file LICENSE ** for license information. ** **============================================================================== */ /* @migen@ */ #include <MI.h> #include "TestEmbeddedOperations_Class_Provider.h" #include "X_TestEmbeddedObjectNotReferenced.h" MI_BEGIN_NAMESPACE TestEmbeddedOperations_Class_Provider::TestEmbeddedOperations_Class_Provider( Module* module) : m_Module(module) { } TestEmbeddedOperations_Class_Provider::~TestEmbeddedOperations_Class_Provider() { } void TestEmbeddedOperations_Class_Provider::EnumerateInstances( Context& context, const String& nameSpace, const PropertySet& propertySet, bool keysOnly, const MI_Filter* filter) { context.Post(MI_RESULT_NOT_SUPPORTED); } void TestEmbeddedOperations_Class_Provider::GetInstance( Context& context, const String& nameSpace, const TestEmbeddedOperations_Class& instance_ref, const PropertySet& propertySet) { if (!instance_ref.key().exists || instance_ref.key_value() != 1) { context.Post(MI_RESULT_NOT_FOUND); return; } TestEmbeddedOperations_Class res; MSFT_Person_Class person; person.Last_value(MI_T("Smith")); person.First_value(MI_T("John")); person.Key_value(7); res.key_value(1); res.person_value(person); MSFT_Person_ClassA threePersons; // add three persons person.Last_value(MI_T("Black")); person.First_value(MI_T("John")); person.Key_value(7); threePersons.PushBack(person); person.Last_value(MI_T("White")); person.First_value(MI_T("Bill")); person.Key_value(8); threePersons.PushBack(person); person.Last_value(MI_T("Brown")); person.First_value(MI_T("Ben")); person.Key_value(9); threePersons.PushBack(person); res.threePersons_value(threePersons); context.Post(res); context.Post(MI_RESULT_OK); } void TestEmbeddedOperations_Class_Provider::CreateInstance( Context& context, const String& nameSpace, const TestEmbeddedOperations_Class& new_instance) { context.Post(MI_RESULT_NOT_SUPPORTED); } void TestEmbeddedOperations_Class_Provider::ModifyInstance( Context& context, const String& nameSpace, const TestEmbeddedOperations_Class& new_instance, const PropertySet& propertySet) { context.Post(MI_RESULT_NOT_SUPPORTED); } void TestEmbeddedOperations_Class_Provider::DeleteInstance( Context& context, const String& nameSpace, const TestEmbeddedOperations_Class& instance_ref) { context.Post(MI_RESULT_NOT_SUPPORTED); } void TestEmbeddedOperations_Class_Provider::Invoke_TestEmbedded( Context& context, const String& nameSpace, const TestEmbeddedOperations_Class& instance, const TestEmbeddedOperations_TestEmbedded_Class& in_param ) { // INPUT: // objectsArray - 2 instances of MSFT_Base // objectSingle - MSFT_Person // testObjectsArray - 3 objects // testObjectSingle - not set // OUTPUT // objectsArray - 2 instances of MSFT_Animal with the same keys and species "test" // objectSingle - the same // testObjectsArray - last 2 objects of input // testObjectSingle - key is a sum of input objects //[static, EmbeddedInstance("X_TestObject")] //String TestEmbedded( // [EmbeddedObject, IN, OUT] // String objectsArray[], // [EmbeddedObject, IN, OUT] // String objectSingle, // // [EmbeddedInstance("X_TestObject"), in,out] // String testObjectsArray[], // [EmbeddedInstance("X_TestObject"), in,out] // String testObjectSingle //); TestEmbeddedOperations_TestEmbedded_Class res; X_TestObject_Class item; X_TestObject_ClassA items; /* get last two elements */ if (in_param.testObjectsArray().exists && in_param.testObjectsArray_value().GetSize() > 1) { for ( unsigned int i = in_param.testObjectsArray_value().GetSize() - 2; i < in_param.testObjectsArray_value().GetSize(); i++ ) { items.PushBack(in_param.testObjectsArray_value()[i]); } res.testObjectsArray_value(items); } Uint64 id = 0; if (in_param.testObjectsArray().exists) { for ( unsigned int i = 0; i < in_param.testObjectsArray_value().GetSize(); i++ ) { id += in_param.testObjectsArray_value()[i].id_value(); } item.id_value(id); res.MIReturn_value(item); } if (in_param.objectsArray().exists) { // objectsArray InstanceA objs; MSFT_Animal_Class obj; obj.Species_value(MI_T("test")); for ( unsigned int i = 0; i < in_param.objectsArray_value().GetSize(); i++ ) { obj.Key_value(((MSFT_Base_Class&)in_param.objectsArray_value()[i]).Key_value()); objs.PushBack(obj); } res.objectsArray_value(objs); } context.Post(res); context.Post(MI_RESULT_OK); } void TestEmbeddedOperations_Class_Provider::Invoke_TestEmbeddedInstanceReturnKey20100609( Context& context, const String& nameSpace, const TestEmbeddedOperations_Class& instance, const TestEmbeddedOperations_TestEmbeddedInstanceReturnKey20100609_Class& in_param ) { TestEmbeddedOperations_TestEmbeddedInstanceReturnKey20100609_Class res; X_TestEmbeddedInstanceMIReturnObject_Class inst; inst.id_value(20100609); res.MIReturn_value(inst); context.Post(res); context.Post(MI_RESULT_OK); } void TestEmbeddedOperations_Class_Provider::Invoke_TestEmbeddedObjectReturnKey20100609( Context& context, const String& nameSpace, const TestEmbeddedOperations_Class& instance, const TestEmbeddedOperations_TestEmbeddedObjectReturnKey20100609_Class& in_param ) { TestEmbeddedOperations_TestEmbeddedObjectReturnKey20100609_Class res; X_TestEmbeddedObjectNotReferenced_Class inst; inst.ObjectID_value(20100609); res.MIReturn_value(inst); context.Post(res); context.Post(MI_RESULT_OK); } MI_END_NAMESPACE MI_BEGIN_NAMESPACE void TestEmbeddedOperations_Class_Provider::Load( Context& context) { context.Post(MI_RESULT_OK); } void TestEmbeddedOperations_Class_Provider::Unload( Context& context) { context.Post(MI_RESULT_OK); } MI_END_NAMESPACE
27.279661
134
0.691364
Beguiled
ba78eeb6d4b80fe8390bc7c96e8d87a9a5e2e773
2,812
cpp
C++
SysLib/Network/Files/Link_Detail_File.cpp
kravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
2
2018-04-27T11:07:02.000Z
2020-04-24T06:53:21.000Z
SysLib/Network/Files/Link_Detail_File.cpp
idkravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
null
null
null
SysLib/Network/Files/Link_Detail_File.cpp
idkravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
null
null
null
//********************************************************* // Link_Detail_File.cpp - Link Detail File Input/Output //********************************************************* #include "Link_Detail_File.hpp" //----------------------------------------------------------- // Link_Detail_File constructors //----------------------------------------------------------- Link_Detail_File::Link_Detail_File (Access_Type access, Format_Type format, bool notes_flag) : Db_Header (access, format, notes_flag) { Setup (); } Link_Detail_File::Link_Detail_File (char *filename, Access_Type access, Format_Type format, bool notes_flag) : Db_Header (access, format, notes_flag) { Setup (); Open (filename); } //----------------------------------------------------------- // Link_Detail_File destructor //----------------------------------------------------------- Link_Detail_File::~Link_Detail_File (void) { } //----------------------------------------------------------- // Setup //----------------------------------------------------------- void Link_Detail_File::Setup (void) { File_Type ("Link Detail File"); File_ID ("Detail"); link = dir = control = left = left_thru = thru = right_thru = right = use = lanes = period = 0; } //--------------------------------------------------------- // Create_Fields //--------------------------------------------------------- bool Link_Detail_File::Create_Fields (void) { Add_Field ("LINK", INTEGER, 10); Add_Field ("DIR", INTEGER, 1); Add_Field ("CONTROL", STRING, 16); Add_Field ("LEFT", INTEGER, 2); Add_Field ("LEFT_THRU", INTEGER, 2); Add_Field ("THRU", INTEGER, 2); Add_Field ("RIGHT_THRU", INTEGER, 2); Add_Field ("RIGHT", INTEGER, 2); Add_Field ("USE_TYPE", STRING, FIELD_BUFFER); Add_Field ("USE_LANES", INTEGER, 2); Add_Field ("USE_PERIOD", STRING, FIELD_BUFFER); if (Notes_Flag ()) { Add_Field ("NOTES", STRING, FIELD_BUFFER); } return (Set_Field_Numbers ()); } //----------------------------------------------------------- // Set_Field_Numbers //----------------------------------------------------------- bool Link_Detail_File::Set_Field_Numbers (void) { //---- required fields ---- link = Required_Field ("LINK"); dir = Optional_Field ("DIR"); if (!link || !dir) return (false); //---- optional fields ---- control = Optional_Field ("CONTROL", "WARRANT"); left = Optional_Field ("LEFT", "LEFT_LANES", "LEFT_TURN"); left_thru = Optional_Field ("LEFT_THRU"); thru = Optional_Field ("THRU", "THRU_LANES"); right_thru = Optional_Field ("RIGHT_THRU"); right = Optional_Field ("RIGHT", "RIGHT_LANES", "RIGHT_TURN"); use = Optional_Field ("USE_TYPE", "USE"); lanes = Optional_Field ("USE_LANES", "LANES"); period = Optional_Field ("USE_PERIOD", "PERIOD"); Notes_Field (Optional_Field ("NOTES")); return (true); }
28.989691
111
0.515292
kravitz
ba7a4ee459664c9059fd4c216a900a73b6bc47fe
413,266
cpp
C++
sourceCode/dotNet4.6/vb/language/compiler/binder/bindable.cpp
csoap/csoap.github.io
2a8db44eb63425deff147652b65c5912f065334e
[ "Apache-2.0" ]
5
2017-03-03T02:13:16.000Z
2021-08-18T09:59:56.000Z
sourceCode/dotNet4.6/vb/language/compiler/binder/bindable.cpp
295007712/295007712.github.io
25241dbf774427545c3ece6534be6667848a6faf
[ "Apache-2.0" ]
null
null
null
sourceCode/dotNet4.6/vb/language/compiler/binder/bindable.cpp
295007712/295007712.github.io
25241dbf774427545c3ece6534be6667848a6faf
[ "Apache-2.0" ]
4
2016-11-15T05:20:12.000Z
2021-11-13T16:32:11.000Z
//------------------------------------------------------------------------------------------------- // // Copyright (c) Microsoft Corporation. All rights reserved. // // Does the work to move a module from Declared state to Bindable state. // //------------------------------------------------------------------------------------------------- #include "StdAfx.h" // // Globals // // !!! Ordering based on ACCESS enumeration order in types.h static WCHAR *AccessTableStrings[ 7 ] = { L"Compiler", // maps to ACCESS_CompilerControlled (privatescope aka compilercontrolled) L"Private", L"Protected", // maps to ACCESS_IntersectionProtectedFriend L"Protected", L"Friend", L"Protected Friend", L"Public" }; #if IDE bool IsInCompilationThread(Compiler *Compiler) { bool Result = false; if (Compiler) { if (Compiler->IsCompilationInMainThread()) { Result = GetCompilerSharedState()->IsInMainThread(); } else { Result = GetCompilerSharedState()->IsInBackgroundThread(); } } //VSASSERT(Result, "debugging!!!"); return Result; } #endif IDE void Bindable::ValidateInterfaceInheritance(BCSYM_Interface *Interface) { // Make sure they aren't doing something like: Inherits I1,...I1, etc. // CheckForDuplicateInherits(Interface); for(BCSYM_Implements *BaseImplements = Interface->GetFirstImplements(); BaseImplements; BaseImplements = BaseImplements->GetNext()) { if (BaseImplements->IsBad()) continue; BCSYM_NamedRoot *BaseInterface = BaseImplements->GetRoot()->PNamedRoot(); if (BaseInterface->IsBad()) continue; bool IsBaseBad = false; if (BaseImplements->GetRawRoot()->IsNamedType()) { if (!VerifyBaseNotGenericParam( BaseImplements->GetRawRoot()->PNamedType())) { return; } IsBaseBad = !VerifyBaseNotNestedInDerived( BaseImplements->GetRawRoot()->PNamedType()); } if (!BaseInterface->IsInterface()) { // Error already generated for if (!BaseInterface->IsGenericParam()) { ReportErrorOnSymbol( ERRID_InheritsFromNonInterface, CurrentErrorLog(Interface), BaseImplements); IsBaseBad = true; } } // No more inheritance validation for this base, if base has already been // detected to be bad // if (IsBaseBad) { BaseImplements->SetIsBad(); continue; } // Make sure that we aren't exposing an interface with a restricted type, // e.g. a public interface can't inherit from a private interface // if (!VerifyAccessExposureOfBaseClassOrInterface( Interface, BaseImplements->GetRawRoot())) { BaseImplements->SetIsBad(); } } } /***************************************************************************** ;CheckForDuplicateInherits Make sure they aren't inheriting the same interface twice. Different than a cycles check, i.e. we are looking for Inherits i1, ... i1 *****************************************************************************/ void Bindable::CheckForDuplicateInherits ( BCSYM_Interface *InterfaceBeingChecked ) { BCSYM_Implements *FirstInheritsStatement = InterfaceBeingChecked->GetFirstImplements(); // Only do this work if there is more than one entry in this list // if (FirstInheritsStatement != NULL && FirstInheritsStatement->GetNext() != NULL) { NorlsAllocator ScratchAllocator(NORLSLOC); Symbols SymbolFactory(CurrentCompilerInstance(), &ScratchAllocator, NULL); // The inherits list is built backwards by declared, e.g. the // last Inherits statement as read in the class is the first // one encountered in the list // for (BCSYM_Implements *InheritsStatement = FirstInheritsStatement; InheritsStatement != NULL; InheritsStatement = InheritsStatement->GetNext()) { // don't process horked inherits statements if (InheritsStatement->IsBad() || InheritsStatement->GetRoot()->IsBad()) { continue; } BCSYM_NamedRoot *CurrentBaseInterface = InheritsStatement->GetRoot()->PNamedRoot(); for (BCSYM_Implements *PossiblyMatchingExistingBase = FirstInheritsStatement; PossiblyMatchingExistingBase != InheritsStatement; PossiblyMatchingExistingBase = PossiblyMatchingExistingBase->GetNext()) { if (PossiblyMatchingExistingBase->IsBad() || PossiblyMatchingExistingBase->GetRoot()->IsBad()) { continue; } unsigned CompareFlags = PossiblyMatchingExistingBase->GetRoot()->PNamedRoot() == CurrentBaseInterface ? BCSYM::CompareReferencedTypes( PossiblyMatchingExistingBase->GetRoot(), (GenericBinding *)NULL, InheritsStatement->GetRoot(), (GenericBinding *)NULL, &SymbolFactory) : EQ_Shape; if ((CompareFlags & EQ_Shape) == 0) { // The inherits list is built FILO so mark the one that // comes earlier in the list as being bad since from the // user's point of view, it is the rightmost on the line. if ((CompareFlags & EQ_GenericTypeParams) == 0) { // Duplicate inherits StringBuffer InterfaceName; InheritsStatement->GetRoot()->GetBasicRep( CurrentCompilerInstance(), InterfaceBeingChecked->GetContainingClass(), &InterfaceName, NULL, NULL, FALSE ); ReportErrorOnSymbol( ERRID_DuplicateInInherits1, CurrentErrorLog(InterfaceBeingChecked), InheritsStatement, InterfaceName.GetString()); } else { // Different inherits, but differ only by type params and could unify StringBuffer InterfaceName; StringBuffer OtherInterfaceName; InheritsStatement->GetRoot()->GetBasicRep( CurrentCompilerInstance(), InterfaceBeingChecked->GetContainingClass(), &InterfaceName, NULL, NULL, FALSE ); PossiblyMatchingExistingBase->GetRoot()->GetBasicRep( CurrentCompilerInstance(), InterfaceBeingChecked->GetContainingClass(), &OtherInterfaceName, NULL, NULL, FALSE ); ReportErrorOnSymbol( ERRID_InterfaceUnifiesWithInterface2, CurrentErrorLog(InterfaceBeingChecked), InheritsStatement, InterfaceName.GetString(), OtherInterfaceName.GetString()); } // Mark it bad so we don't try to do any further semantics // with this symbol. // InheritsStatement->SetIsBad(); break; } else { BCSYM *UnifyingInterface1 = NULL; BCSYM *UnifyingInterface2 = NULL; BCSYM *Interface1 = InheritsStatement->GetRoot(); BCSYM *Interface2 = PossiblyMatchingExistingBase->GetRoot(); if (CanInterfacesOrBasesUnify( Interface1, Interface2, &SymbolFactory, &UnifyingInterface1, &UnifyingInterface2, true)) // Skip direct comparison between the passed in interfaces because the comparison // has already been done above. { AssertIfNull(UnifyingInterface1); AssertIfNull(UnifyingInterface2); ERRID ErrId = ERRID_None; StringBuffer Name1; StringBuffer Name2; StringBuffer Name3; StringBuffer Name4; if (UnifyingInterface1 == Interface1) { ErrId = ERRID_InterfaceUnifiesWithBase3; Interface1->GetBasicRep( CurrentCompilerInstance(), InterfaceBeingChecked->GetContainingClass(), &Name1, NULL, NULL, FALSE ); UnifyingInterface2->GetBasicRep( CurrentCompilerInstance(), InterfaceBeingChecked->GetContainingClass(), &Name2, NULL, NULL, FALSE ); Interface2->GetBasicRep( CurrentCompilerInstance(), InterfaceBeingChecked->GetContainingClass(), &Name3, NULL, NULL, FALSE ); } else if (UnifyingInterface2 == Interface2) { ErrId = ERRID_BaseUnifiesWithInterfaces3; Interface1->GetBasicRep( CurrentCompilerInstance(), InterfaceBeingChecked->GetContainingClass(), &Name1, NULL, NULL, FALSE ); UnifyingInterface1->GetBasicRep( CurrentCompilerInstance(), InterfaceBeingChecked->GetContainingClass(), &Name2, NULL, NULL, FALSE ); Interface2->GetBasicRep( CurrentCompilerInstance(), InterfaceBeingChecked->GetContainingClass(), &Name3, NULL, NULL, FALSE ); } else { ErrId = ERRID_InterfaceBaseUnifiesWithBase4; Interface1->GetBasicRep( CurrentCompilerInstance(), InterfaceBeingChecked->GetContainingClass(), &Name1, NULL, NULL, FALSE ); UnifyingInterface1->GetBasicRep( CurrentCompilerInstance(), InterfaceBeingChecked->GetContainingClass(), &Name2, NULL, NULL, FALSE ); UnifyingInterface2->GetBasicRep( CurrentCompilerInstance(), InterfaceBeingChecked->GetContainingClass(), &Name3, NULL, NULL, FALSE ); Interface2->GetBasicRep( CurrentCompilerInstance(), InterfaceBeingChecked->GetContainingClass(), &Name4, NULL, NULL, FALSE ); } ReportErrorOnSymbol( ErrId, CurrentErrorLog(InterfaceBeingChecked), InheritsStatement, Name1.GetString(), Name2.GetString(), Name3.GetString(), Name4.GetString()); // Mark it bad so we don't try to do any further semantics // with this symbol. // InheritsStatement->SetIsBad(); break; } } } } } } bool Bindable::CanInterfacesOrBasesUnify ( BCSYM *Interface1, BCSYM *Interface2, Symbols *SymbolFactory, BCSYM **UnifyingInterface1, BCSYM **UnifyingInterface2, bool SkipDirectComparison ) { AssertIfNull(Interface1); AssertIfFalse(Interface1->IsContainer()); AssertIfNull(Interface2); AssertIfFalse(Interface2->IsContainer()); AssertIfNull(SymbolFactory); AssertIfNull(UnifyingInterface1); AssertIfNull(UnifyingInterface2); if (Interface1->IsGenericTypeBinding() && CanInterface1UnifyWithInterface2OrItsBases( Interface1->PGenericTypeBinding(), Interface2, SymbolFactory, UnifyingInterface1, UnifyingInterface2, SkipDirectComparison)) { return true; } BasesIter Interface1Bases(Interface1->PContainer()); BCSYM_GenericTypeBinding *BaseBinding = NULL; while (BCSYM *Base = Interface1Bases.GetNextBase(&BaseBinding)) { if (BaseBinding) { Base = Interface1->IsGenericBinding() ? ReplaceGenericParametersWithArguments( BaseBinding, Interface1->PGenericBinding(), *SymbolFactory) : BaseBinding; } if (CanInterfacesOrBasesUnify( Base, Interface2, SymbolFactory, UnifyingInterface1, UnifyingInterface2, false)) { return true; } } return false; } bool Bindable::CanInterface1UnifyWithInterface2OrItsBases ( BCSYM_GenericTypeBinding *Interface1, BCSYM *Interface2, Symbols *SymbolFactory, BCSYM **UnifyingInterface1, BCSYM **UnifyingInterface2, bool SkipDirectComparison ) { AssertIfNull(Interface1); AssertIfFalse(Interface1->IsContainer()); AssertIfNull(Interface2); AssertIfFalse(Interface2->IsContainer()); AssertIfNull(SymbolFactory); AssertIfNull(UnifyingInterface1); AssertIfNull(UnifyingInterface2); if (!SkipDirectComparison && CanInterfacesUnify(Interface1, Interface2, SymbolFactory, CurrentCompilerInstance())) { *UnifyingInterface1 = Interface1; *UnifyingInterface2 = Interface2; return true; } BasesIter Interface2Bases(Interface2->PContainer()); BCSYM_GenericTypeBinding *BaseBinding = NULL; while (BCSYM *Base = Interface2Bases.GetNextBase(&BaseBinding)) { if (BaseBinding) { Base = Interface2->IsGenericBinding() ? ReplaceGenericParametersWithArguments( BaseBinding, Interface2->PGenericBinding(), *SymbolFactory) : BaseBinding; } if (CanInterface1UnifyWithInterface2OrItsBases( Interface1, Base, SymbolFactory, UnifyingInterface1, UnifyingInterface2, false)) { return true; } } return false; } bool Bindable::CanInterfacesUnify ( BCSYM *Interface1, BCSYM *Interface2, Symbols *SymbolFactory, Compiler *CompilerInstance ) { AssertIfNull(Interface1); AssertIfNull(Interface2); AssertIfNull(SymbolFactory); unsigned CompareFlags = BCSYM::CompareReferencedTypes( Interface1, (GenericBinding *)NULL, Interface2, (GenericBinding *)NULL, SymbolFactory); return ((CompareFlags & (EQ_Shape | EQ_GenericTypeParams)) == EQ_GenericTypeParams); } /***************************************************************************** ;DoClassInheritanceValidationNotRequiringOtherBoundBasesInfo Checks to make sure we don't inherit from non-classes, mustinherit classes, etc. or restricted classes (can't inherit from System.Array, for instance). *****************************************************************************/ void Bindable::DoClassInheritanceValidationNotRequiringOtherBoundBasesInfo ( BCSYM_Class *MainClass // [in] class to check ) { VSASSERT(!MainClass->IsPartialType(), "Partial type unexpected!!!"); BCSYM *RawLogicalBaseClass = NULL; BCSYM *LogicalBaseClass = NULL; bool ExplicitlySpecifiedBaseFound = false; for(BCSYM_Class *Class = MainClass; Class; Class = Class->GetNextPartialType()) { // Note: Do not use the GetBaseClass, GetCompileBaseClass accessors here because // they dig through to the logical base and at this point of time, the logical base // is still being determined. // BCSYM *RawBase = Class->GetRawBase(); if (!RawBase || Class->IsBaseBad() || Class->IsBaseInvolvedInCycle()) { continue; } BCSYM *Base = RawBase->DigThroughNamedType(); if (!Base || Base->IsBad()) continue; Compiler *CompilerInstance = CurrentCompilerInstance(); CompilerHost *CompilerHost = CurrentCompilerHost(); bool IsBaseBad = false; if (Class->GetRawBase() && Class->GetRawBase()->IsNamedType()) { if (!VerifyBaseNotGenericParam(Class->GetRawBase()->PNamedType())) { continue; } IsBaseBad = !VerifyBaseNotNestedInDerived( Class->GetRawBase()->PNamedType()); } // There are some types you can't inherit from... // if (Base == CompilerHost->GetFXSymbolProvider()->GetType(FX::ArrayType) || Base == CompilerHost->GetFXSymbolProvider()->GetType(FX::DelegateType) || Base == CompilerHost->GetFXSymbolProvider()->GetType(FX::MultiCastDelegateType) || Base == CompilerHost->GetFXSymbolProvider()->GetType(FX::EnumType) || Base == CompilerHost->GetFXSymbolProvider()->GetType(FX::ValueTypeType)) { ReportErrorAtLocation( ERRID_InheritsFromRestrictedType1, CurrentErrorLog(Class), Class->GetInheritsLocation(), Base->PClass()->GetName()); MarkBaseClassBad(Class); continue; } if (!IsClass(Base)) { ReportErrorAtLocation( ERRID_InheritsFromNonClass, CurrentErrorLog(Class), Class->GetInheritsLocation()); MarkBaseClassBad(Class); continue; } if (Base->PClass()->IsNotInheritable()) { ReportErrorAtLocation( ERRID_InheritsFromCantInherit3, CurrentErrorLog(Class), Class->GetInheritsLocation(), Class->GetName(), Base->PNamedRoot()->GetName(), StringOfSymbol(CompilerInstance, Base)); MarkBaseClassBad(Class); continue; } // if bad inheritance has already been detected, then do not proceed with further validation. // if (IsBaseBad) { continue; } if (!Class->IsBaseExplicitlySpecified()) { if (!ExplicitlySpecifiedBaseFound) { LogicalBaseClass = Base; RawLogicalBaseClass = Class->GetRawBase(); } } else if (!ExplicitlySpecifiedBaseFound) { LogicalBaseClass = Base; RawLogicalBaseClass = Class->GetRawBase(); ExplicitlySpecifiedBaseFound = true; } else if (!BCSYM::AreTypesEqual(Base, LogicalBaseClass)) { // Base class '|1' specified for class '|2' cannot be different from the base class '|3' of one of its other partial types. ReportErrorAtLocation( ERRID_BaseMismatchForPartialClass3, CurrentErrorLog(Class), Class->GetInheritsLocation(), GetQualifiedErrorName(Base), Class->GetName(), GetQualifiedErrorName(LogicalBaseClass)); MarkBaseClassBad(Class); continue; } } // Change the main type's base class to point to the first explicitly specified good base class. // if (RawLogicalBaseClass) { MainClass->SetRawBase(RawLogicalBaseClass); VSASSERT(!RawLogicalBaseClass->ChaseToType()->IsGenericBadNamedRoot(), "Bad base unexpected!!!"); MainClass->SetIsBaseBad(false); } else { MarkBaseClassBad(MainClass); } } /***************************************************************************** ;DoClassInheritanceValidationRequiringOtherBoundBasesInfo Checks to make sure we don't have public classes inheriting from private classes, i.e. access exposure. Also check that generic classes don't inherit from attribute classes. Note that this needs to be invoked only after inheritance cycle detection for the class being validated is completed because these checks walk inheritance chains. *****************************************************************************/ void Bindable::DoClassInheritanceValidationRequiringOtherBoundBasesInfo ( BCSYM_Class *MainClass // [in] class to check ) { VSASSERT(!MainClass->IsPartialType(), "Partial type unexpected!!!"); if (MainClass->IsBaseBad() || MainClass->IsBaseInvolvedInCycle()) { return; } // Note: Do not use the GetBaseClass, GetCompileBaseClass accessors here because // they dig through to the logical base and at this point of time, the logical base // is still being determined. // BCSYM *RawBase = MainClass->GetRawBase(); // Non-named types not expected to be bad for the scenarios being validated here. // if (!RawBase || !RawBase->IsNamedType()) { return; } BCSYM *Base = RawBase->DigThroughNamedType(); if (!Base || Base->IsBad()) { return; } // Generic type cannot be attributes. So they cannot inherit from System.Attribute nor // System.Security.Permissions.SecurityAttribute either directly or indirectly if (IsGenericOrHasGenericParent(MainClass) && (CurrentCompilerHost()->GetFXSymbolProvider()->IsTypeAvailable(FX::AttributeType) && TypeHelpers::IsOrInheritsFrom( Base, CurrentCompilerHost()->GetFXSymbolProvider()->GetType(FX::AttributeType)) || (CurrentCompilerHost()->GetFXSymbolProvider()->IsTypeAvailable(FX::SecurityAttributeType) && TypeHelpers::IsOrInheritsFrom( Base, CurrentCompilerHost()->GetFXSymbolProvider()->GetType(FX::SecurityAttributeType))))) { // Class that is or nested in a generic type cannot inherit from an attribute class. ReportErrorOnSymbol( ERRID_GenericClassCannotInheritAttr, CurrentErrorLog(RawBase->PNamedType()), RawBase); MarkBaseClassBad(MainClass); return; } // Verify that we don't have public classes/interfaces inheriting from private ones, etc. // if (!VerifyAccessExposureOfBaseClassOrInterface( MainClass, MainClass->GetRawBase())) { MarkBaseClassBad(MainClass); return; } } // Return true if Base is valid, else false // bool Bindable::VerifyBaseNotNestedInDerived ( BCSYM_NamedType *Base ) { if (Base->GetSymbol() && Base->GetSymbol()->IsNamedRoot()) { VSASSERT(!Base->GetSymbol()->IsGenericBadNamedRoot(), "How did a bad root get here ?"); BCSYM_NamedRoot *BoundBase = Base->GetSymbol()->PNamedRoot(); if (!BoundBase->IsGenericParam() && IsTypeNestedIn(BoundBase, CurrentContainer())) { ReportErrorOnSymbol( ERRID_NestedBase2, CurrentErrorLog(Base), Base, StringOfSymbol(CurrentCompilerInstance(), CurrentContainer()), CurrentContainer()->GetName()); Base->SetSymbol(Symbols::GetGenericBadNamedRoot()); return false; } } return true; } bool Bindable::IsTypeNestedIn ( BCSYM_NamedRoot *ProbableNestedType, BCSYM_Container *ProbableEnclosingContainer ) { if (!ProbableNestedType || !ProbableEnclosingContainer) { return false; } for (BCSYM_Container *Parent = ProbableNestedType->GetContainer(); Parent; Parent = Parent->GetContainer()) { if (ProbableEnclosingContainer->IsSameContainer(Parent)) { return true; } } return false; } // Return true if Base is valid, else false // bool Bindable::VerifyBaseNotGenericParam ( BCSYM_NamedType *Base ) { if (Base->GetSymbol() && Base->GetSymbol()->IsNamedRoot()) { VSASSERT(!Base->GetSymbol()->IsGenericBadNamedRoot(), "How did a bad root get here ?"); BCSYM_NamedRoot *BoundBase = Base->GetSymbol()->PNamedRoot(); if (BoundBase->IsGenericParam()) { ReportErrorOnSymbol( ERRID_GenericParamBase2, CurrentErrorLog(Base), Base, StringOfSymbol(CurrentCompilerInstance(), CurrentContainer()), CurrentContainer()->GetName()); Base->SetSymbol(Symbols::GetGenericBadNamedRoot()); return false; } } return true; } void Bindable::MarkBaseClassBad ( BCSYM_Class *DerivedClass ) { BCSYM * rawBase = DerivedClass->GetRawBase(); if (rawBase && rawBase->IsNamedType()) { rawBase->PNamedType()->SetSymbol(Symbols::GetGenericBadNamedRoot()); } DerivedClass->SetIsBaseBad(true); } /***************************************************************************** ;DimAsNewSemantics A variable has been delcared 'as New', e.g. dim x as new y. Verify that it is ok to create it, i.e. it has to be an object, there must be an appropriate constructor that takes no arguments, the class must not be abstract, etc. *****************************************************************************/ void Bindable::DimAsNewSemantics ( BCSYM *SymbolToCheck, ERRID &Error ) { // Get past aliasing SymbolToCheck = SymbolToCheck->DigThroughAlias(); // don't look at symbols that we know have problems already // if (SymbolToCheck->IsBad()) { return; } // Semantics checks it out // Error = CheckConstraintsOnNew(SymbolToCheck); } bool Bindable::IsTypeValidForConstantVariable ( BCSYM *Type ) { // Constants must be typed as an intrinsic or Enum type // Note: Constants cannot have Structure types // if (Type->IsObject() || Type->IsIntrinsicType() || Type->IsEnum()) { return true; } return false; } void Bindable::ResolvePartialTypesForContainer ( BCSYM_Container *Container, CompilationCaches *IDECompilationCaches ) { // The ordering of the conditions in this "if" are particularly important // in order to avoid unnecessarily creating BindableInstances for MetaData // Containers // if (Container->IsBindingDone() || DefinedInMetaData(Container) || Container->GetBindableInstance()->GetStatusOfResolvePartialTypes() == Done) { return; } Bindable *BindableInstanceForContainer = Container->GetBindableInstance(); BindableInstanceForContainer->SetIDECompilationCaches(IDECompilationCaches); BindableInstanceForContainer->ResolvePartialTypesForContainer(); BindableInstanceForContainer->SetIDECompilationCaches(NULL); } // The reason this is split into a separate task from ResolvePartialTypesForContainer // is that if we made it one single task, then Resolving the partial types for // any container would complete this task for all the types in the symbol table. // So what is wrong with that ? - Yes, it is not wrong or a perf. hit, but we want // to keep Binding a container as lightweight (binding other stuff only when absolutely // needed) as possible so that other parts of the compiler (mainly UI) could make // use of this per container model to be more responsive to the user in the future. // void Bindable::ResolvePartialTypesForNestedContainers ( BCSYM_Container *Container, CompilationCaches *IDECompilationCaches ) { // The ordering of the conditions in this "if" are particularly important // in order to avoid unnecessarily creating BindableInstances for MetaData // Containers // if (Container->IsBindingDone() || DefinedInMetaData(Container) || Container->GetBindableInstance()-> GetStatusOfResolvePartialTypesForNestedContainers() == Done) { return; } ResolvePartialTypesForContainer(Container, IDECompilationCaches); Bindable *BindableInstanceForContainer = Container->GetBindableInstance(); VSASSERT( BindableInstanceForContainer->GetStatusOfResolvePartialTypes() == Done, "How can this task start before its previous task is done ?"); BindableInstanceForContainer->SetIDECompilationCaches(IDECompilationCaches); BindableInstanceForContainer->ResolvePartialTypesForNestedContainers(); BindableInstanceForContainer->SetIDECompilationCaches(NULL); } // This is needed so that when a name is being bound to a type in this container, // a type that is in the future going to be marked as duplicate and bad is not bound // to. In order to enable this scenario, the duplicates need to indentified and // marked as such before hand. This method is the helper that GetHash invokes // to guarantee this. // void Bindable::EnsurePartialTypesAreResolved ( BCSYM_Container *Container, CompilationCaches *IDECompilationCaches ) { if (Container->IsBindingDone() || DefinedInMetaData(Container)) { return; } // If not in the transition from declared to bound, then this // is not necessary because then the information is either // not needed or already available. // if (!Container->GetCompilerFile()->GetProject()->IsDeclaredToBoundCompilationInProgress()) { return; } #if IDE if (!IsInCompilationThread(Container->GetCompiler())) { return; } #endif IDE if (Container->GetBindableInstance()-> GetStatusOfResolvePartialTypesForNestedContainers() != NotStarted) { return; } if (Container->GetBindableInstance()-> GetStatusOfResolvePartialTypes() == InProgress) { return; } #if DEBUG && IDE BCSYM_Container *CurrentContainer; if (Container->IsPartialTypeAndHasMainType()) { CurrentContainer = Container->GetMainType(); } else { CurrentContainer = Container; } do { CompilationState CurrentState = CurrentContainer->GetSourceFile()->GetCompState(); CompilationState CurrentDecompilationState = CurrentContainer->GetSourceFile()->GetDecompilationState(); VSASSERT( CurrentState == CS_Declared && CurrentState == CurrentDecompilationState, "This should not be invoked in any other state!!!"); VSASSERT( CurrentContainer->GetSourceFile()->GetProject()->GetDecompilationState() == CS_Declared, "This should not be invoked in any other state!!!"); } while (CurrentContainer = CurrentContainer->GetNextPartialType()); #endif ResolvePartialTypesForContainer(Container, IDECompilationCaches); ResolvePartialTypesForNestedContainers(Container, IDECompilationCaches); } void Bindable::ResolveFileLevelImports ( CompilerFile *File, CompilationCaches *IDECompilationCaches ) { if (!File) { return; } if (File->IsMetaDataFile()) { return; } SourceFile *SourceFile = File->PSourceFile(); if (SourceFile->HaveImportsBeenResolved()) { return; } VSASSERT(!SourceFile->AreImportsBeingResolved(), "unexpected cyclic dependency detected when resolving imports!!!"); // Indicate in progress // SourceFile->SetAreImportsBeingResolved(true); // Bind all of the "imports" clauses ResolveImports( SourceFile->GetUnnamedNamespace(), SourceFile, SourceFile->GetProject(), SourceFile->SymbolStorage(), SourceFile->GetLineMarkerTable(), SourceFile->GetCurrentErrorTable(), SourceFile->GetCompiler(), IDECompilationCaches); // Remove indication of in progress // SourceFile->SetAreImportsBeingResolved(false); SourceFile->SetHaveImportsBeenResolved(true); } void Bindable::ResolveBasesForContainer ( BCSYM_Container *Container, CompilationCaches *IDECompilationCaches ) { // Resolve Bases not needed for MetaData symbols // The ordering of the conditions in this "if" are particularly important // in order to avoid unnecessarily creating BindableInstances for MetaData // Containers // if (Container->IsBindingDone() || DefinedInMetaData(Container) || Container->GetBindableInstance()->GetStatusOfResolveBases() == Done) { return; } ResolvePartialTypesForNestedContainers(Container, IDECompilationCaches); Bindable *BindableInstanceForContainer = Container->GetBindableInstance(); BindableInstanceForContainer->SetIDECompilationCaches(IDECompilationCaches); if (Container->IsPartialType() && Container->GetMainType()) { BindableInstanceForContainer-> SetStatusOfResolveBases(InProgress); ResolveBasesForContainer(Container->GetMainType(), IDECompilationCaches); BindableInstanceForContainer-> SetStatusOfResolveBases(Done); } else { //Ensure that File Level imports have been resolved for(BCSYM_Container *CurrentType = Container; CurrentType; CurrentType = CurrentType->GetNextPartialType()) { ResolveFileLevelImports(CurrentType->GetCompilerFile(), IDECompilationCaches); } BindableInstanceForContainer->ResolveBasesForContainer(); } BindableInstanceForContainer->SetIDECompilationCaches(NULL); } void Bindable::ResolveAllNamedTypesForContainer ( BCSYM_Container *Container, CompilationCaches *IDECompilationCaches ) { // Resolve Named Types not needed for MetaData container // The ordering of the conditions in this "if" are particularly important // in order to avoid unnecessarily creating BindableInstances for MetaData // Containers // if (Container->IsBindingDone() || DefinedInMetaData(Container) || Container->GetBindableInstance()->GetStatusOfResolveNameTypes() == Done) { return; } // Make sure the previous step is done ResolveBasesForContainer(Container, IDECompilationCaches); Bindable *BindableInstanceForContainer = Container->GetBindableInstance(); if (Container->IsPartialType() && Container->GetMainType()) { BindableInstanceForContainer-> SetStatusOfResolveNamedTypes(InProgress); ResolveAllNamedTypesForContainer(Container->GetMainType(), IDECompilationCaches); BindableInstanceForContainer-> SetStatusOfResolveNamedTypes(Done); } else { BindableInstanceForContainer->ResolveAllNamedTypesForContainer(TypeResolveNoFlags); } } void Bindable::DetectStructMemberCyclesForContainer ( BCSYM_Container *Container, CompilationCaches *IDECompilationCaches ) { // Detecting struct member cycles not needed for MetaData container // The ordering of the conditions in this "if" are particularly important // in order to avoid unnecessarily creating BindableInstances for MetaData // Containers // if (Container->IsBindingDone() || DefinedInMetaData(Container) || Container->GetBindableInstance()->GetStatusOfDetectStructMemberCycles() == Done) { return; } // Make sure the previous step is done ResolveAllNamedTypesForContainer(Container, IDECompilationCaches); Bindable *BindableInstanceForContainer = Container->GetBindableInstance(); BindableInstanceForContainer->SetIDECompilationCaches(IDECompilationCaches); if (Container->IsPartialType() && Container->GetMainType()) { BindableInstanceForContainer-> SetStatusOfDetectStructMemberCycles(InProgress); DetectStructMemberCyclesForContainer(Container->GetMainType(), IDECompilationCaches); BindableInstanceForContainer-> SetStatusOfDetectStructMemberCycles(Done); } else { BindableInstanceForContainer->DetectStructMemberCyclesForContainer(); } BindableInstanceForContainer->SetIDECompilationCaches(NULL); } void Bindable::ResolveShadowingOverloadingOverridingAndCheckGenericsForContainer ( BCSYM_Container *Container, CompilationCaches *IDECompilationCaches ) { // The ordering of the conditions in this "if" are particularly important // in order to avoid unnecessarily creating BindableInstances for MetaData // Containers // if (Container->IsBindingDone()) { return; } // Metadata containers need this too, but the task is then done // through a different API BindMetaDataContainer // if (DefinedInMetaData(Container)) { BindMetaDataContainer(Container, IDECompilationCaches); return; } if (Container->GetBindableInstance()->GetStatusOfResolveShadowingOverloadingAndOverriding() == Done) { return; } // Make sure the previous step is done ResolveAllNamedTypesForContainer(Container, IDECompilationCaches); Bindable *BindableInstanceForContainer = Container->GetBindableInstance(); BindableInstanceForContainer->SetIDECompilationCaches(IDECompilationCaches); if (Container->IsPartialType() && Container->GetMainType()) { BindableInstanceForContainer-> SetStatusOfResolveShadowingOverloadingAndOverriding(InProgress); ResolveShadowingOverloadingOverridingAndCheckGenericsForContainer(Container->GetMainType(), IDECompilationCaches); BindableInstanceForContainer-> SetStatusOfResolveShadowingOverloadingAndOverriding(Done); } else { // Generic constraints cannot be checked until named types are resolved, because // the constraint types need to have been resolved. BindableInstanceForContainer->CheckGenericConstraintsForContainer(); BindableInstanceForContainer->CheckVarianceValidityOfContainer(IDECompilationCaches); BindableInstanceForContainer->ResolveShadowingOverloadingAndOverridingForContainer(); } BindableInstanceForContainer->SetIDECompilationCaches(NULL); } void Bindable::----AttributesOnAllSymbolsInContainer ( BCSYM_Container *Container, CompilationCaches *IDECompilationCaches ) { // Cracking of attributes not needed for MetaData symbols. Done in metaimport itself // when importing symbols. That is needed so early to determine default property, // withevents properties. // // The ordering of the conditions in this "if" are particularly important // in order to avoid unnecessarily creating BindableInstances for MetaData // Containers // if (Container->IsBindingDone() || DefinedInMetaData(Container) || Container->GetBindableInstance()->GetStatusOf----AttributesOnAllSymbolsInContainer() == Done) { return; } // Make sure the previous step is done ResolveShadowingOverloadingOverridingAndCheckGenericsForContainer(Container, IDECompilationCaches); Bindable *BindableInstanceForContainer = Container->GetBindableInstance(); BindableInstanceForContainer->SetIDECompilationCaches(IDECompilationCaches); if (Container->IsPartialType() && Container->GetMainType()) { BindableInstanceForContainer-> SetStatusOf----AttributesOnAllSymbolsInContainer(InProgress); ----AttributesOnAllSymbolsInContainer(Container->GetMainType(), IDECompilationCaches); BindableInstanceForContainer-> SetStatusOf----AttributesOnAllSymbolsInContainer(Done); } else { BindableInstanceForContainer->----AttributesOnAllSymbolsInContainer(); } BindableInstanceForContainer->SetIDECompilationCaches(NULL); } void Bindable::VerifyAttributesOnAllSymbolsInContainer ( BCSYM_Container *Container, CompilationCaches *IDECompilationCaches ) { // The ordering of the conditions in this "if" are particularly important // in order to avoid unnecessarily creating BindableInstances for MetaData // Containers // if (Container->IsBindingDone() || DefinedInMetaData(Container) || Container->GetBindableInstance()->GetStatusOfVerifyAttributesOnAllSymbolsInContainer() == Done) { return; } // Make sure the previous step is done ----AttributesOnAllSymbolsInContainer(Container, IDECompilationCaches); Bindable *BindableInstanceForContainer = Container->GetBindableInstance(); BindableInstanceForContainer->SetIDECompilationCaches(IDECompilationCaches); if (Container->IsPartialType() && Container->GetMainType()) { BindableInstanceForContainer-> SetStatusOfVerifyAttributesOnAllSymbolsInContainer(InProgress); VerifyAttributesOnAllSymbolsInContainer(Container->GetMainType(), IDECompilationCaches); BindableInstanceForContainer-> SetStatusOfVerifyAttributesOnAllSymbolsInContainer(Done); } else { BindableInstanceForContainer->VerifyAttributesOnAllSymbolsInContainer(); } BindableInstanceForContainer->SetIDECompilationCaches(NULL); } void Bindable::ValidateWithEventsVarsAndHookUpHandlersInContainer ( BCSYM_Container *Container, CompilationCaches *IDECompilationCaches ) { // Validate Events not needed for metadata containers // The ordering of the conditions in this "if" are particularly important // in order to avoid unnecessarily creating BindableInstances for MetaData // Containers // if (Container->IsBindingDone() || DefinedInMetaData(Container) || Container->GetBindableInstance()->GetStatusOfValidateWithEventsVarsAndHookUpHandlers() == Done) { return; } // Make sure the previous step is done VerifyAttributesOnAllSymbolsInContainer(Container, IDECompilationCaches); Bindable *BindableInstanceForContainer = Container->GetBindableInstance(); BindableInstanceForContainer->SetIDECompilationCaches(IDECompilationCaches); if (Container->IsPartialType() && Container->GetMainType()) { BindableInstanceForContainer-> SetStatusOfValidateWithEventsVarsAndHookUpHandlers(InProgress); ValidateWithEventsVarsAndHookUpHandlersInContainer(Container->GetMainType(), IDECompilationCaches); BindableInstanceForContainer-> SetStatusOfValidateWithEventsVarsAndHookUpHandlers(Done); } else { BindableInstanceForContainer->ValidateWithEventsVarsAndHookUpHandlersInContainer(); } BindableInstanceForContainer->SetIDECompilationCaches(NULL); } void Bindable::ResolveImplementsInContainer ( BCSYM_Container *Container, CompilationCaches *IDECompilationCaches ) { // Resolve Implements not needed for MetaData symbols // The ordering of the conditions in this "if" are particularly important // in order to avoid unnecessarily creating BindableInstances for MetaData // Containers // if (Container->IsBindingDone() || DefinedInMetaData(Container) || Container->GetBindableInstance()->GetStatusOfResolveImplementsInContainer() == Done) { return; } // Make sure the previous step is done ValidateWithEventsVarsAndHookUpHandlersInContainer(Container, IDECompilationCaches); Bindable *BindableInstanceForContainer = Container->GetBindableInstance(); BindableInstanceForContainer->SetIDECompilationCaches(IDECompilationCaches); if (Container->IsPartialType() && Container->GetMainType()) { BindableInstanceForContainer-> SetStatusOfResolveImplementsInContainer(InProgress); ResolveImplementsInContainer(Container->GetMainType(), IDECompilationCaches); BindableInstanceForContainer-> SetStatusOfResolveImplementsInContainer(Done); } else { BindableInstanceForContainer->ResolveImplementsInContainer(); } BindableInstanceForContainer->SetIDECompilationCaches(NULL); } void Bindable::VerifyOperatorsInContainer ( BCSYM_Container *Container, CompilationCaches *IDECompilationCaches ) { // The ordering of the conditions in this "if" are particularly important // in order to avoid unnecessarily creating BindableInstances for MetaData // Containers // if (Container->IsBindingDone() || DefinedInMetaData(Container) || Container->GetBindableInstance()->GetStatusOfVerifyOperatorsInContainer() == Done) { return; } ResolveImplementsInContainer(Container, IDECompilationCaches); Bindable *BindableInstanceForContainer = Container->GetBindableInstance(); BindableInstanceForContainer->SetIDECompilationCaches(IDECompilationCaches); if (Container->IsPartialType() && Container->GetMainType()) { BindableInstanceForContainer-> SetStatusOfVerifyOperatorsInContainer(InProgress); VerifyOperatorsInContainer(Container->GetMainType(), IDECompilationCaches); BindableInstanceForContainer-> SetStatusOfVerifyOperatorsInContainer(Done); } else { BindableInstanceForContainer->VerifyOperatorsInContainer(); } BindableInstanceForContainer->SetIDECompilationCaches(NULL); } void Bindable::GenSyntheticCodeForContainer ( BCSYM_Container *Container, CompilationCaches *IDECompilationCaches ) { // Synthetic code gen not needed for metadata containers // The ordering of the conditions in this "if" are particularly important // in order to avoid unnecessarily creating BindableInstances for MetaData // Containers // if (Container->IsBindingDone() || DefinedInMetaData(Container) || Container->GetBindableInstance()->GetStatusOfGenSyntheticCodeForContainer() == Done) { return; } // We can't generate the synthetic code for a member until we've done all of // the implements work because the symbol for an implemented event isn't // complete until the implements is resolved and the delegate in the interface // is found. We must also wait until operators are verified because synthetic code // will not be produced for malformed synthetic division operators. // VerifyOperatorsInContainer(Container, IDECompilationCaches); Bindable *BindableInstanceForContainer = Container->GetBindableInstance(); BindableInstanceForContainer->SetIDECompilationCaches(IDECompilationCaches); if (Container->IsPartialType() && Container->GetMainType()) { BindableInstanceForContainer-> SetStatusOfGenSyntheticCodeForContainer(InProgress); GenSyntheticCodeForContainer(Container->GetMainType(), IDECompilationCaches); BindableInstanceForContainer-> SetStatusOfGenSyntheticCodeForContainer(Done); } else { BindableInstanceForContainer->GenSyntheticCodeForContainer(); } BindableInstanceForContainer->SetIDECompilationCaches(NULL); } void Bindable::ScanContainerForObsoleteUsage ( BCSYM_Container *Container, CompilationCaches *IDECompilationCaches, bool NeedToCheckObsolsete ) { // Scan for obsolete usage not needed for metadata container // The ordering of the conditions in this "if" are particularly important // in order to avoid unnecessarily creating BindableInstances for MetaData // Containers // if (Container->IsBindingDone() || DefinedInMetaData(Container) || Container->GetBindableInstance()->GetStatusOfScanContainerForObsoleteUsage() == Done) { return; } GenSyntheticCodeForContainer(Container, IDECompilationCaches); // Bindable *BindableInstanceForContainer = Container->GetBindableInstance(); BindableInstanceForContainer->SetIDECompilationCaches(IDECompilationCaches); if (Container->IsPartialType() && Container->GetMainType()) { BindableInstanceForContainer-> SetStatusOfScanContainerForObsoleteUsage(InProgress); ScanContainerForObsoleteUsage(Container->GetMainType(), IDECompilationCaches, NeedToCheckObsolsete); BindableInstanceForContainer-> SetStatusOfScanContainerForObsoleteUsage(Done); } else { BindableInstanceForContainer->ScanContainerForObsoleteUsage(NeedToCheckObsolsete); } BindableInstanceForContainer->SetIDECompilationCaches(NULL); } void Bindable::ScanContainerForResultTypeChecks ( BCSYM_Container *Container, CompilationCaches *IDECompilationCaches ) { // Scan for obsolete usage not needed for metadata container // The ordering of the conditions in this "if" are particularly important // in order to avoid unnecessarily creating BindableInstances for MetaData // Containers // if (Container->IsBindingDone() || DefinedInMetaData(Container) || Container->GetBindableInstance()->GetStatusOfScanContainerForReturnTypeCheck() == Done) { return; } // Bindable *BindableInstanceForContainer = Container->GetBindableInstance(); BindableInstanceForContainer->SetIDECompilationCaches(IDECompilationCaches); if (Container->IsPartialType() && Container->GetMainType()) { BindableInstanceForContainer-> SetStatusOfScanContainerForReturnTypeCheck(InProgress); ScanContainerForResultTypeChecks(Container->GetMainType(), IDECompilationCaches); BindableInstanceForContainer-> SetStatusOfScanContainerForReturnTypeCheck(Done); } else { BindableInstanceForContainer->ScanContainerForResultTypeChecks(); } BindableInstanceForContainer->SetIDECompilationCaches(NULL); } // This should only be invoked by metaimport!! Have added an assert to verify this. // All this hoopla is needed for MetaData containers because we need to delete the // Bindable Instance after the task unlike Source containers where the bindable // instance is guaranteed to be deleted because the complete binding process is // alway invoked on them. // void Bindable::BindMetaDataContainer ( BCSYM_Container *Container, CompilationCaches *IDECompilationCaches ) { VSASSERT( DefinedInMetaData(Container), "Non-metadata containers unexpected!!"); // Note - Access the m_phash directly and do not go through GetHash because it // would call this function again and thus result in infinite recursion i.e. a // stack overflow. // CompilerIdeLock spLock(Container->GetCompilerFile()-> GetCompiler()->GetMetaImportCritSec()); if (Container->IsBindingDone()) { Container->DeleteBindableInstance(); return; } Bindable *BindableInstanceForContainer = Container->GetBindableInstance(); if (BindableInstanceForContainer->GetStatusOfResolveShadowingOverloadingAndOverriding() == InProgress || BindableInstanceForContainer->GetStatusOfResolveShadowingOverloadingAndOverriding() == Done) { return; } BindableInstanceForContainer->SetIDECompilationCaches(IDECompilationCaches); BindableInstanceForContainer->ResolveShadowingOverloadingAndOverridingForContainer(); if (IsClass(Container)) { BindableInstanceForContainer->InheritWellKnowAttributesFromBases(); } BindableInstanceForContainer->SetIDECompilationCaches(NULL); // This is the last task for metadata containers Container->SetBindingDone(true); // Clean up the Bindable Instance Container->DeleteBindableInstance(); } void Bindable::ValidateExtensionAttributeOnMetaDataClass(BCSYM_Class * pClass) { if (! IsBad(pClass)) { BCITER_CHILD iter(pClass); BCSYM_NamedRoot * pCur = NULL; while (pCur = iter.GetNext()) { if (pCur->IsProc()) { Attribute::VerifyExtensionAttributeUsage(pCur->PProc(), NULL, m_CompilerHost); } } } } void Bindable::BindSourceFile ( SourceFile *SourceFile, CompilationCaches *IDECompilationCaches ) { #if IDE // we need to check this because binding is not done completely until MyClass, etc. // have been resolved. So although binding the containers is done, the file's state // may not have been promoted to CS_Bound. So we might try to bind the containers // of this file again. So inorder to guard against any such issues, we need this check. // if (SourceFile->IsBindingContainersDone()) { return; } #endif // Bind all of the "imports" clauses ResolveFileLevelImports(SourceFile, IDECompilationCaches); BindContainerAndNestedTypes(SourceFile->GetUnnamedNamespace(), IDECompilationCaches); #if IDE SourceFile->SetBindingContainersDone(); #endif } // This should only be used when Binding SourceFiles i.e. VB source code // This should not be used when importing metadata because we want to load // metadata symbols on demand. // void Bindable::BindContainerAndNestedTypes ( BCSYM_Container *Container, CompilationCaches *IDECompilationCaches ) { // MetaData containers are not allowed here in order to keep the // loading of nested types "on demand". // VSASSERT( !DefinedInMetaData(Container), "Metadata containers not allowed here!!"); BindContainer(Container, IDECompilationCaches); // iterate Container for all nested types and do bindable for them too // for(BCSYM_Container *NestedType = Container->GetNestedTypes(); NestedType; NestedType = NestedType->GetNextNestedType()) { BindContainerAndNestedTypes(NestedType, IDECompilationCaches); } // Note: Normally the bindable instance of the container is deleted at the end of BindContainer(Container) // In some cases the instance can wrongly be reassigned to a new bindable during the binding of the nested // containers. See bug VSWhidbey 344045 for an example. if (Container->GetBindableInstanceIfAlreadyExists() && !IsMyGroupCollection(Container)) { // See bug VSWhidbey 344045 for more details. VSFAIL("Bindable instance unexpected!!!"); Container->DeleteBindableInstance(); } } void Bindable::BindContainer ( BCSYM_Container *Container, CompilationCaches *IDECompilationCaches ) { VSASSERT( Container, "How can we bind a NULL container ?"); // Some containers might already be bound due to the other // parts of the compiler like codemodel preemptively binding // containers which their clients are interested in. // if (Container->IsBindingDone()) { return; } // Ensure project level imports and app objects are resolved because lookup during // the binding of this container might involve looking in them. // Container->GetContainingProject()->ResolveProjectLevelImports(IDECompilationCaches); ResolvePartialTypesForContainer(Container, IDECompilationCaches); ResolvePartialTypesForNestedContainers(Container, IDECompilationCaches); // Resolve Bases // ResolveBasesForContainer(Container, IDECompilationCaches); // Resolve NamedTypes // Resolve all the namedtypes for this container // Note: We cannot do ResolveBase and ResolveNamedTypes in one step because // when we are in the middle of resolving a base, ResolveNamedTypes for // another class (say a parent class) might start and fail for some named // type when trying to bind against a member in the base that we are currently // resolving.Need an eg. ? // ResolveAllNamedTypesForContainer(Container, IDECompilationCaches); // Detect structure member cycles // Eg: // Structure S1 // Dim x as S1 'Cycle here // End Structure // DetectStructMemberCyclesForContainer(Container, IDECompilationCaches); // Resolve Shadowing, Overloading And Overriding for container // Besides these, the following tasks are also done here // - Evaluate Constant expressions // - Validate withevent variables in handles clauses and synthetsize any // properties needed to handle WithEventVariableInBase.Event events. // - Validate generic constraints // - Validate generic variance // (Generics are check here because they depend on generic-constraint-names // having been resolve). // ResolveShadowingOverloadingOverridingAndCheckGenericsForContainer(Container, IDECompilationCaches); // - ---- Attributes on All Symbols in the container. // - Also Inherit well known inheritable attributes from bases // - Determine if this container can be used as a valid attribute // ----AttributesOnAllSymbolsInContainer(Container, IDECompilationCaches); // Verify attribute usage // VerifyAttributesOnAllSymbolsInContainer(Container, IDECompilationCaches); // - Validate all WithEvent variables in container // - Hookup handlers specified in the handles clauses in the container // to the appropriate events. // ValidateWithEventsVarsAndHookUpHandlersInContainer(Container, IDECompilationCaches); // Resolve all the implements clauses and connect the implementing // members to the implemented members. // ResolveImplementsInContainer(Container, IDECompilationCaches); // Verify user-defined operators are correctly formed. // VerifyOperatorsInContainer(Container, IDECompilationCaches); // We can't generate the synthetic code for a member until we've done // ResolveImplements because the delegate for an implementing event isn't // known until the implements is resolved and the delegate of the // implemented event in the interface is found. // This also does Access Exposure validation. We cannot verify the Access // Exposure for the same reason that the event's delegate might not be known. // GenSyntheticCodeForContainer(Container, IDECompilationCaches); // Scan for use of Obsolete types and members // ScanContainerForObsoleteUsage(Container, IDECompilationCaches, !ObsoleteChecker::IsObsoleteOrHasObsoleteContainer(Container)); // Some ResultType checks have been cached until after ResolveProjectLevelImports // ScanContainerForResultTypeChecks(Container, IDECompilationCaches); // Mark the container as Binding done and delete the Bindable instance associated // with the Container // // But if the container has the MyCollection Attribute in which case properties // might need to be injected into it later, then we will delay the binding // completion. // if (!IsMyGroupCollection(Container)) { Container->SetBindingDone(true); Container->DeleteBindableInstance(); } } void Bindable::ResolveBasesForContainer() { //This function resolves bases for the //- Container's Parents //- Container //- and for the Container's bases // //This function processes non-classes and non-interfaces too. Why ? //Because if the container is a structure which itself is inside another //class, then we still have to resolve bases for the structure's parent class. //This is need so that ResolveNamedTypes on this container can bind to types //in the Parent's bases too. The only exception being namespaces and modules //which cannot be nested in classes or interfaces. BCSYM_Container *Container = CurrentContainer(); if (Container->IsNamespace() || IsStdModule(Container)) { SetStatusOfResolveBases(Done); return; } // If this Class/Interface has already been processed for this, return if (GetStatusOfResolveBases() == Done) { return; } if (GetStatusOfResolveBases() == InProgress) { // Possible cycle - flag in order to do a thorough cycle check after base // resolution is done // SetPossibleInheritanceCycleDetected(true); // Check if any parent cycle ? // BCSYM *CurrentBase = GetCurrentBase() ? GetCurrentBase()->GetSymbol() : NULL; BCSYM_Container *CurrentBoundBase = NULL; while (CurrentBase) { if (!CurrentBase->IsContainer()) { CurrentBoundBase = NULL; break; } CurrentBoundBase = CurrentBase->PContainer(); if (CurrentBoundBase->IsSameContainer(Container)) { CurrentBoundBase = NULL; break; } if (GetStatusOfResolveBases(CurrentBoundBase) == NotStarted) { break; } CurrentBase = CurrentBoundBase->GetBindableInstance()->GetCurrentBase(); } if (CurrentBoundBase) { // this implies that this base's parent's base is being resolved // this will then error out at the below parent check. // ResolveBasesForContainer(CurrentBoundBase, m_CompilationCaches); } return; } // Resolve bases for parent because this affects the resolving of named types in the // current container. Walk up the parent hierarchy because if the parent is a structure // which itself is inside another class, then we still have to resolve base for the // structure's parent class. // BCSYM_Container *Parent = Container->GetContainer(); if (Parent) { if (GetStatusOfResolveBases(Parent) == InProgress) { // BaseOfParent could be NULL if this is triggered when resolving the namedtype // that represents the parent's base // BCSYM_NamedType *BaseOfParent = Parent->GetBindableInstance()->GetCurrentBase(); if (BaseOfParent && BaseOfParent->GetSymbol() && !BaseOfParent->GetSymbol()->IsBad()) { ReportErrorOnSymbol( ERRID_CircularBaseDependencies4, CurrentErrorLog(BaseOfParent), BaseOfParent, StringOfSymbol(CurrentCompilerInstance(), Parent), Parent->GetName(), StringOfSymbol(CurrentCompilerInstance(), Container), Container->GetName()); BaseOfParent->SetSymbol(Symbols::GetGenericBadNamedRoot()); } // This is so that cycle detection is forced on the current container after // it bases are resolved later. See bug VSWhidbey 187738. // SetPossibleInheritanceCycleDetected(true); return; } else { ResolveBasesForContainer(Parent, m_CompilationCaches); // This class's bases could itself get triggered off through its parents, // after we break the circular parent - nested type dependencies. // If this Class/Interface has already been processed for this, return // else continue on and complete the task now. // if (GetStatusOfResolveBases() == Done) { return; } } } // Mark the Class/Interface indicating that work is in progress to resolve its bases // SetStatusOfResolveBases(InProgress); if (IsClass(Container)) { ResolveBaseForClass(Container->PClass()); } else if (IsInterface(Container)) { ResolveBasesForInterface(Container->PInterface()); } SetStatusOfResolveBases(Done); } ////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////// // VARIANCE // // CheckVarianceValidityOfContainer - this is the only entrypoint for validity-checking of variance. // It is called for each container (including nested containers) in each source file. // If it is called for each container in each sourcefile of a program, then we guarantee that either // (1) the program had something already marked IsBad(), or (2) we produce a variance-validity error // message, or (3) the program is variance-valid. // // The variance-validity-checker never marks anything as IsBad(). // // Variance validity is defined in $2 of the VB Variance Specification. Each of the validity-checking // functions cites (and quotes verbatim) the portion of the spec that it implements. // // One thing to note: we only ever check variance-validity of bindable members // (i.e. ones written by the user); we don't check compiler-generated members. ////////////////////////////////////////////////////////////////////////////////////////////////////// void Bindable::CheckVarianceValidityOfContainer ( CompilationCaches *IDECompilationCaches ) { BCSYM_Container *Container = this->CurrentContainer(); VSASSERT(Container, "unexpected NULL CurrentContainer"); // We only check variance on the maintype, not on partials. if (Container->IsPartialType()) { VSASSERT(Container->IsPartialTypeAndHasMainType(), "unexpected partial type with no maintype"); return; } // Variance spec $2: // An enum is valid. A namespace and a module are valid if and // only if every nested type is valid. if (IsNamespace(Container)) { } else if (IsStdModule(Container)) { } else if (IsInterface(Container)) { CheckVarianceValidityOfInterface(Container->PInterface()); CheckVarianceAmbiguity(Container, IDECompilationCaches); } else if (Container->IsDelegate()) { CheckVarianceValidityOfDelegate(Container->PClass()); } else if (IsClass(Container) || Container->IsStruct() || Container->IsEnum()) { CheckVarianceValidityOfClassOrStructOrEnum(Container->PClass()); CheckVarianceAmbiguity(Container, IDECompilationCaches); } else { VSFAIL("Unexpected container type when checking for variance-validity"); } } void Bindable::CheckVarianceValidityOfClassOrStructOrEnum(BCSYM_Container *Container) { VSASSERT(Container, "unexpected NULL class/struct/enum"); VSASSERT(IsClass(Container) || Container->IsStruct() || Container->IsEnum(), "expected a class/struct container"); if (Container->IsBad()) { return; } // Variance spec $2: // A class/struct is valid if and only if // * its own generic parameters are invariant, and // * it has no generic methods with variant generic parameters, and // * every nested type is valid. // // The test that nested types are valid isn't needed, since CheckVarianceValidityOfContainer // will anyways be called on them all. (and for any invalid nested type, we report the // error on it, rather than on this container.) // // On a separate topic, here we also implement a check that this class/struct/enum isn't // contained (even nested) inside a variant interface. See the comments in // CheckVarianceValidityOfInterface for why. // // 1. own generic parameters are invariant. // NB. Container->GetFirstGenericParam() will return null if it's not a generic container for (GenericParameter *gParam=Container->GetFirstGenericParam(); gParam; gParam=gParam->GetNextParam()) { VSASSERT(gParam, "unexpected NULL generic param"); if (!gParam->IsBad() && gParam->GetVariance()!=Variance_None) { // Only interface and delegate types can be specified as variant ReportErrorOnSymbol(ERRID_VarianceDisallowedHere, CurrentErrorLog(gParam), gParam); // we'll set the variance to what the user presumably will correct it to be, so that // future errors make more sense gParam->SetVariance(Variance_None); } } // 2. no generic methods with variant generic parameters // Has already been dealt with in ValidateGenericParameters() // 3. isn't contained (not even nested) in a variant interface for (BCSYM_Container *parent = Container->GetContainingClassOrInterface(); parent; parent=parent->GetContainingClassOrInterface()) { if (TypeHelpers::HasVariance(parent)) { // This type declaration cannot go inside a variant Interface ReportErrorOnSymbol(ERRID_VarianceInterfaceNesting, CurrentErrorLog(Container), Container); break; // Incidentally, all parent containers are validated before their child containers. // So if we had "Class C(Of Out T) : Structure S : End Structure : End Class", then the // outer class would have been validated first, and there'd have been an error on the // variance of T, and we'd have silently changed it to "Variance_None". That means that // we won't now report an error for "S" being inside a variant container. Good. We shouldn't. // NB. We won't mark this container as bad. That's because the user will likely fix the // problem by moving the container into a place where it's allowed. So we can still // make useful reports on the rest of the code which references this container. } } } void Bindable::CheckVarianceValidityOfDelegate(BCSYM_Class *Delegate) { VSASSERT(Delegate, "unexpected NULL delegate"); if (Delegate->IsBad()) { return; } // Variance spec $2 // A delegate "Delegate Function/Sub Foo(Of T1, ... Tn)Signature" is valid if and only if // * the signature is valid. // // That delegate becomes "Class Foo(Of T1, ... Tn) : Function Invoke(...) As ... : End Class // So we just need to pick up the "Invoke" method and check that it's valid. // NB. that delegates can have variance in their generic params, and hence so can e.g. "Class Foo(Of Out T1)" // This is the only place in the CLI where a class can have variant generic params. // Note: delegates that are synthesized from events are already dealt with in CheckVarianceValidityOfInterface, // so we won't examine them again here: if (Delegate->CreatedByEventDecl()!=NULL) { return; } Declaration *Invoke = GetInvokeFromDelegate(Delegate, this->CurrentCompilerInstance()); VSASSERT(Invoke, "unexpected null invoke method in delegate"); if (Invoke->IsBad()) { return; } VSASSERT(Invoke->IsMethodDecl(), "unexpected non-decl invoke in delegate"); CheckVarianceValidityOfSignature(Invoke->PMethodDecl()); } void Bindable::CheckVarianceValidityOfInterface(BCSYM_Interface *Interface) { VSASSERT(Interface, "unexpected NULL interface"); if (Interface->IsBad()) { return; } // Variance spec $2: // An interface I is valid if and only if // * every method signature in I is valid and has no variant generic parameters, and // * every property in I is valid, and // * every event in I is valid, and // * every immediate base interface type of I is valid covariantly, and // * the interface is either invariant or it lacks nested classes and structs, and // * every nested type is valid. // // A property "Property Foo as T" is valid if and only if either // * The property is read-only and T is valid covariantly, or // * The property is write-only and T is valid invariantly, or // * The property is readable and writable and T is invariant. // // An event "Event e as D" is valid if and only if // * the delegate type D is valid contravariantly // // An event "Event e(Signature)" is valid if and only if // * it is not contained (not even nested) in a variant interface // // The test that nested types are valid isn't needed, since CheckVarianceValidityOfContainer // will anyways be called on them all. (and for any invalid nested type, we report the // error on it, rather than on this container.) // // The check that an interface lacks nested classes and structs is done inside // CheckVarianceValidityOfClassOrStruct. Why? Because we have to look for indirectly // nested classes/structs, not just immediate ones. And it seemed nicer for classes/structs // to look UP for variant containers, rather than for interfaces to look DOWN for class/struct contents. // 1. every method signature in I is valid, and properties are valid BCITER_CHILD Members(Interface); while (BCSYM_NamedRoot *Member = Members.GetNext()) { if (Member->IsBad()) { continue; } else if (Member->IsMethodDecl() && !Member->IsEventDecl()) // nb. a MethodImpl is also a MethodDecl. { CheckVarianceValidityOfSignature(Member->PMethodDecl()); } else if (Member->IsProperty()) { BCSYM_Property *Property = Member->PProperty(); BCSYM *Type = Property->GetType(); VSASSERT(Type, "unexpected NULL property type"); if (Type->IsBad()) { continue; } // Gettable: requires covariance. Settable: requires contravariance. Gettable and settable: requires invariance. Variance_Kind RequiredVariance; VarianceContextEnum Context; if (Property->IsReadOnly()) { RequiredVariance = Variance_Out; Context = VarianceContextReadOnlyProperty; } else if (Property->IsWriteOnly()) { RequiredVariance = Variance_In; Context = VarianceContextWriteOnlyProperty; } else { RequiredVariance = Variance_None; Context = VarianceContextProperty; } CheckThatTypeSatisfiesVariance(Type, RequiredVariance, Interface, Context, Property->GetRawType(), CurrentErrorLog(Property)); // A property might be declared with extra parameters, so we have to check that these are variance-valid. // If it's readonly then these extra params will be found in the getter; if it's writeonly then they'll // be found in the setter; if it's readable and writable then they'll be found in both. But we'll // only check one of these accessors, since we don't want such parameter errors to be reported twice. // Note: the CheckVarianceValidityOfSignature() function will ignore the property-type when asked to check // accessors, because the property-type shouldn't really be considered part of the property signature proper. // That's good, because we've already reported any errors on the property-type above. BCSYM_Proc *Accessor = Property->IsWriteOnly() ? Property->SetProperty() : Property->GetProperty(); VSASSERT(Accessor!=NULL, "unexpected property without gettor or settor"); CheckVarianceValidityOfSignature(Accessor); } else if (Member->IsEventDecl()) { BCSYM_EventDecl *Event = Member->PEventDecl(); BCSYM *Delegate = Event->GetDelegate(); if (!Delegate || !Delegate->IsDelegate() || Delegate->IsBad()) { continue; } if (Delegate->PClass()->CreatedByEventDecl() == Event) { // Some events are declared as "Event e1(ByVal x as T), with a synthesized delegate type. // These aren't allowed inside variant interfaces. BCSYM_Container *OutermostVariantInterface = NULL; for (BCSYM_Container *parent = Event->GetContainingClassOrInterface(); parent; parent = parent->GetContainingClassOrInterface()) { if (TypeHelpers::HasVariance(parent)) { OutermostVariantInterface = parent; } } if (OutermostVariantInterface!=NULL) { // "Event definitions with parameters are not allowed in an interface such as '|1' that has // 'In' or 'Out' type parameters. Consider declaring the event by using a delegate type which // is not defined within '|1'. For example, 'Event |2 As Action(Of ...)'." ERRID ErrId = ERRID_VariancePreventsSynthesizedEvents2; ReportErrorOnSymbol(ErrId, CurrentErrorLog(Event), Event, GetQualifiedErrorName(OutermostVariantInterface), Event->GetName()); // And we mark the event as bad because the only way to fix the event is by redoing it entirely. Event->SetIsBad(); } } else { // Other events are declared as "Event e1 as SomeDelegateType" // If there are errors in the variance of SomeDelegateType, we report them on it. CheckThatTypeSatisfiesVariance(Delegate, Variance_In, Interface, VarianceContextComplex, Event->GetRawDelegate(), CurrentErrorLog(Member)); } } } // 2. no generic methods with variant generic parameters // Has already been dealt with in ValidateGenericParameters // 3. every immediate base interface is valid covariantly. // Actually, the only type that's invalid covariantly and allowable as a base interface, // is a generic instantiation X(T1,...) where we've instantiated it wrongly (e.g. given it "Out Ti" // for a generic parameter that was declared as an "In"). Look what happens: // Interface IZoo(Of In T) | Dim x as IZoo(Of Animal) // Inherits IReadOnly(Of T) | Dim y as IZoo(Of Mammal) = x ' through contravariance of IZoo // End Interface | Dim z as IReadOnly(Of Mammal) = y ' through inheritance from IZoo // Now we might give "z" to someone who's expecting to read only Mammals, even though we know the zoo // contains all kinds of animals. for (BCSYM_Implements *BaseImplements = Interface->GetFirstImplements(); BaseImplements; BaseImplements = BaseImplements->GetNext()) { VSASSERT(BaseImplements!=NULL, "unexpected NULL baseimplements"); if (BaseImplements->IsBad()) { continue; } BCSYM *BaseInterface = BaseImplements->GetRoot(); // this may be a generic binding context VSASSERT(BaseInterface!=NULL, "unexpected NULL baseinterface"); if (BaseInterface->IsBad()) { continue; } CheckThatTypeSatisfiesVariance(BaseInterface, Variance_Out, Interface, VarianceContextComplex, BaseImplements, CurrentErrorLog(Interface)); } } void Bindable::CheckVarianceValidityOfSignature(BCSYM_Proc *Signature) { VSASSERT(Signature, "unexpected NULL signature"); if (Signature->IsBad()) { return; } // Variance spec $2: // A signature "Function F(Of U1...Un)(P1, ..., Pn) as Tr" or "Sub F(Of U1...Un)(P1, ..., Pn)" // is valid if and only if // * the type of each ByVal parameter Pi is valid contravariantly, and // * the type of each ByRef parameter Pi is valid invariantly, and // * (in the case of functions), Tr is valid covariantly, and // * the type of each type constraint on each U1...Un is valid contravariantly. // This function can also be called to check the signatures of property-accessors. // But note that the BCSYM_MethodDecl of a "getter" stores the property-type as // a return-type, and that of a "setter" stores the property-type as the last // parameter. We don't consider these to be part of the signature proper, so we // don't check them here. (The validity of property-types is checked by the // CheckVarianceValidityOfInterface function). bool SuppressCheckOfReturnType = Signature->IsPropertyGet(); bool SuppressCheckOfLastParam = Signature->IsPropertySet(); // 1. Each ByVal Pi is valid contravariantly, and each ByRef Pi is valid invariantly for (BCSYM_Param *param = Signature->GetFirstParam(); param; param=param->GetNext()) { if (param->IsBad()) { continue; } if (SuppressCheckOfLastParam && param->GetNext()==NULL) { continue; } Variance_Kind RequiredVariance = Variance_In; VarianceContextEnum Context = VarianceContextByVal; BCSYM *paramType = param->GetType(); VSASSERT(paramType!=NULL, "unexpected NULL paramType"); if (paramType->IsBad()) { continue; } if (param->IsByRefKeywordUsed()) { RequiredVariance = Variance_None; Context = VarianceContextByRef; VSASSERT(paramType->IsPointerType(), "expected ByRef parameter to be a pointer type"); paramType = paramType->PPointerType()->GetRoot(); VSASSERT(paramType!=NULL, "unexpected NULL type from pointer type"); if (paramType->IsBad()) { continue; } } CheckThatTypeSatisfiesVariance(paramType, RequiredVariance, Signature->GetContainingClassOrInterface(), Context, param->GetRawType(), CurrentErrorLog(Signature)); } // 2. Tr is valid covariantly BCSYM *Tr = Signature->GetType(); if (Tr!=NULL && !Tr->IsBad() && !SuppressCheckOfReturnType) { CheckThatTypeSatisfiesVariance(Tr, Variance_Out, Signature->GetContainingClassOrInterface(), VarianceContextReturn, Signature->GetRawType(), CurrentErrorLog(Signature)); } // 3. each constraint on U1...Un is valid contravariantly // "It is character-building to consider why this is required" [Eric Lippert, 2008] // Interface IReadOnly(Of Out T) | Class Zoo(Of T) | Dim m As IReadOnly(Of Mammal) = new Zoo(Of Mammal) ' OK through inheritance // Sub Fun(Of U As T)() | Implements IReadOnly(Of T) | Dim a as IReadOnly(Of Animal) = m ' OK through covariance // End Interface | End Class | a.Fun(Of Fish)() ' BAD: Fish is an Animal (satisfies "U as T"), but fun is expecting a mammal! for (BCSYM_GenericParam *gParam=Signature->GetFirstGenericParam(); gParam; gParam=gParam->GetNextParam()) { if (gParam->IsBad()) { continue; } for (BCSYM_GenericTypeConstraint *Constraint=gParam->GetTypeConstraints(); Constraint; Constraint=Constraint->Next()) { if (Constraint->IsBad()) { continue; } BCSYM *Tconstraint = Constraint->GetType(); VSASSERT(Tconstraint!=NULL, "unexpected NULL Tconstraint"); if (Tconstraint->IsBad()) { continue; } CheckThatTypeSatisfiesVariance(Tconstraint, Variance_In, Signature->GetContainingClassOrInterface(), VarianceContextConstraint, Constraint, CurrentErrorLog(gParam)); } } } void Bindable::CheckThatTypeSatisfiesVariance( BCSYM *Type, Variance_Kind RequiredVariance, BCSYM_Container *Container, VarianceContextEnum Context, BCSYM *ErrorSymbol, ErrorTable *ErrorTable) { CheckThatTypeSatisfiesVariance_Helper(Type, RequiredVariance, Container, Context, ErrorSymbol, ErrorTable, NULL, NULL, false); } void Bindable::CheckThatTypeSatisfiesVariance_Helper( BCSYM *Type, // We will check this type... Variance_Kind RequiredVariance, // ...to make sure it can deliver this kind of variance BCSYM_Container *Container, // The container where we're trying to refer to the type VarianceContextEnum Context, // And where specifically in that container we're trying to refer to the type BCSYM *ErrorSymbol, // If it can't, we report an error squiggly under this symbol ErrorTable *ErrorTable, // in this error table _In_opt_ BCSYM_GenericBinding *ErrorBinding, // This is the binding that immediately contains Type (if Type is contained by a binding) _In_opt_ BCSYM_GenericParam *ErrorParam, // and this is the generic parameter that it was bound to int ErrorBindingNesting // Was that generic at the very top level of ErrorSymbol? (if so, it will simplify error messages) ) { VSASSERT(Type!=NULL, "unexpected NULL type"); VSASSERT(ErrorSymbol!=NULL, "please supply a symbol under which this error will be reported"); VSASSERT((ErrorBinding==NULL) == (ErrorParam==NULL), "Please supply an ErrorBinding if and only if you supply an ErrorParam"); VSASSERT(ErrorBinding==NULL || ErrorBinding->GetGeneric()!=NULL, "Unexpected: a generic binding of no particular generic type"); VSASSERT(ErrorBinding==NULL || ErrorBinding->GetArgumentCount()>0, "Unexpected: a generic binding with no generic arguments"); if (Type->IsBad()) { return; } // Variance spec $2: // // A type T is valid invariantly if and only if: // * it is valid covariantly, and // * it is valid contravariantly. // // A type T is valid covariantly if and only if one of the following hold: either // * T is a generic parameter which was not declared contravariant, or // * T is an array type U() where U is valid covariantly, or // * T is a construction X1(Of T11...)...Xn(Of Tn1...) of some generic struct/class/interface/delegate Xn // declared as X1(Of X11...)...Xn(Of Xn1...) such that for each i and j, // - if Xij was declared covariant then Tij is valid covariantly // - if Xij was declared contravariant then Tij is valid contravariantly // - if Xij was declared invariant then Tij is valid invariantly // * or T is a non-generic struct/class/interface/delegate/enum. // // A type T is valid contravariantly if and only if one of the following hold: either // * T is a generic parameter which was not declared covariant, or // * T is an array type U() where U is valid contravariantly, or // * T is a construction X1(Of T11...)...Xn(Of Tn1...) of some generic struct/class/interface/delegate Xn // declared as X1(Of X11...)...Xn(Of Xn1...) such that for each i and j, // - if Xij was declared covariant then Tij is valid contravariantly // - if Xij was declared contravariant then Tij is valid covariantly // - if Xij was declared invariant then Tij is valid invariantly // * or T is a non-generic struct/class/interface/delegate/enum. // // // In all cases, if a type fails a variance validity check, then it ultimately failed // because somewhere there were one or more generic parameters "T" which were declared with // the wrong kind of variance. In particular, they were either declared In when they'd have // to be Out or InOut, or they were declared Out when they'd have to be In or InOut. // We mark all these as errors. // // BUT... CLS restrictions say that in any generic type, all nested types first copy their // containers's generic parameters. This restriction is embodied in the BCSYM structure. // SOURCE: BCSYM: IL: // Interface I(Of Out T1) Interface"I"/genericparams=T1 .interface I(Of Out T1) // Interface J : End Interface Interface"J"/no genericparams .interface J(Of Out T1) // Sub f(ByVal x as J) ... GenericTypeBinding(J,args=[], .proc f(x As J(Of T1)) // End Interface parentargs=I[T1]) // Observe that, by construction, any time we use a nested type like J in a contravariant position // then it's bound to be invalid. If we naively applied the previous paragraph then we'd emit a // confusing error to the user like "J is invalid because T1 is an Out parameter". So we want // to do a better job of reporting errors. In particular, // * If we are checking a GenericTypeBinding (e.g. x as J(Of T1)) for contravariant validity, look up // to find the outermost ancester binding (e.g. parentargs=I[T1]) which is of a variant interface. // If this is also the outermost variant container of the current context, then it's an error. // 1. if T is a generic parameter which was declared wrongly if (Type->IsGenericParam()) { if ((Type->PGenericParam()->GetVariance()==Variance_Out && RequiredVariance!=Variance_Out) || (Type->PGenericParam()->GetVariance()==Variance_In && RequiredVariance!=Variance_In)) { // The error is either because we have an "Out" param and Out is inappropriate here, // or we used an "In" param and In is inappropriate here. This flag says which: bool InappropriateOut = (Type->PGenericParam()->GetVariance()==Variance_Out); if (ErrorBinding!=NULL && ErrorBinding->GetGeneric()->IsBad()) { return; } // OKAY, so now we need to report an error. Simple enough, but we've tried to give helpful // context-specific error messages to the user, and so the code has to work through a lot // of special cases. if (Context == VarianceContextByVal) { // "Type '|1' cannot be used as a ByVal parameter type because '|1' is an 'Out' type parameter." VSASSERT(InappropriateOut, "unexpected: an variance error in ByVal must be due to an inappropriate out"); ReportErrorOnSymbol(ERRID_VarianceOutByValDisallowed1, ErrorTable, ErrorSymbol, GetQualifiedErrorName(Type)); } else if (Context == VarianceContextByRef) { // "Type '|1' cannot be used in this context because 'In' and 'Out' type parameters cannot be used for ByRef parameter types, and '|1' is an 'Out/In' type parameter." ERRID ErrId = InappropriateOut ? ERRID_VarianceOutByRefDisallowed1 : ERRID_VarianceInByRefDisallowed1; ReportErrorOnSymbol(ErrId, ErrorTable, ErrorSymbol, GetQualifiedErrorName(Type)); } else if (Context == VarianceContextReturn) { // "Type '|1' cannot be used as a return type because '|1' is an 'In' type parameter." VSASSERT(!InappropriateOut, "unexpected: a variance error in Return Type must be due to an inappropriate in"); ReportErrorOnSymbol(ERRID_VarianceInReturnDisallowed1, ErrorTable, ErrorSymbol, GetQualifiedErrorName(Type)); } else if (Context == VarianceContextConstraint) { // "Type '|1' cannot be used as a generic type constraint because '|1' is an 'Out' type parameter." VSASSERT(InappropriateOut, "unexpected: a variance error in Constraint must be due to an inappropriate out"); ReportErrorOnSymbol(ERRID_VarianceOutConstraintDisallowed1, ErrorTable, ErrorSymbol, GetQualifiedErrorName(Type)); } else if (Context == VarianceContextNullable) { StringBuffer sb; // "Type '|1' cannot be used in '|2' because 'In' and 'Out' type parameters cannot be made nullable, and '|1' is an 'In/Out' type parameter." ERRID ErrId = InappropriateOut ? ERRID_VarianceOutNullableDisallowed2 : ERRID_VarianceInNullableDisallowed2; ReportErrorOnSymbol(ErrId, ErrorTable, ErrorSymbol, GetQualifiedErrorName(Type), ErrorTable->ExtractErrorName(ErrorSymbol, NULL, sb)); } else if (Context == VarianceContextReadOnlyProperty) { // "Type '|1' cannot be used as a ReadOnly property type because '|1' is an 'In' type parameter." VSASSERT(!InappropriateOut, "unexpected: a variance error in ReadOnlyProperty must be due to an inappropriate in"); ReportErrorOnSymbol(ERRID_VarianceInReadOnlyPropertyDisallowed1, ErrorTable, ErrorSymbol, GetQualifiedErrorName(Type)); } else if (Context == VarianceContextWriteOnlyProperty) { // "Type '|1' cannot be used as a WriteOnly property type because '|1' is an 'Out' type parameter." VSASSERT(InappropriateOut, "unexpected: a variance error in WriteOnlyProperty must be due to an inappropriate out"); ReportErrorOnSymbol(ERRID_VarianceOutWriteOnlyPropertyDisallowed1, ErrorTable, ErrorSymbol, GetQualifiedErrorName(Type)); } else if (Context == VarianceContextProperty) { // "Type '|1' cannot be used as a property type in this context because '|1' is an 'Out/In' type parameter and the property is not marked ReadOnly/WriteOnly.") ERRID ErrId = InappropriateOut ? ERRID_VarianceOutPropertyDisallowed1 : ERRID_VarianceInPropertyDisallowed1; ReportErrorOnSymbol(ErrId, ErrorTable, ErrorSymbol, GetQualifiedErrorName(Type)); } // Otherwise, we're in "VarianceContextComplex" property. And so the error message needs // to spell out precisely where in the context we are: // "Type '|1' cannot be used in this context because '|1' is an 'Out|In' type parameter." // "Type '|1' cannot be used for the '|2' in '|3' in this context because '|1' is an 'Out|In' type parameter." // "Type '|1' cannot be used in '|2' in this context because '|1' is an 'Out|In' type parameter." // "Type '|1' cannot be used in '|2' for the '|3' in '|4' in this context because '|1' is an 'Out' type parameter." // We need the "in '|2' here" clause when ErrorBindingIsNested, to show which instantiation we're talking about. // We need the "for the '|3' in '|4'" when ErrorBinding->GetGenericParamCount()>1 else if (ErrorBinding==NULL) { // "Type '|1' cannot be used in this context because '|1' is an 'Out|In' type parameter." // Used for simple errors where the erroneous generic-param is NOT inside a generic binding: // e.g. "Sub f(ByVal a as O)" for some parameter declared as "Out O" // gives the error "An 'Out' parameter like 'O' cannot be user here". ERRID ErrId = InappropriateOut ? ERRID_VarianceOutParamDisallowed1 : ERRID_VarianceInParamDisallowed1; ReportErrorOnSymbol(ErrId, ErrorTable, ErrorSymbol, GetQualifiedErrorName(Type)); } else if (ErrorBindingNesting<=1 && ErrorBinding->GetArgumentCount()<=1) { // "Type '|1' cannot be used in this context because '|1' is an 'Out|In' type parameter." // e.g. "Sub f(ByVal a As IEnumerable(Of O))" yields // "An 'Out' parameter like 'O' cannot be used here." ERRID ErrId = InappropriateOut ? ERRID_VarianceOutParamDisallowed1 : ERRID_VarianceInParamDisallowed1; ReportErrorOnSymbol(ErrId, ErrorTable, ErrorSymbol, GetQualifiedErrorName(Type)); } else if (ErrorBindingNesting<=1 && ErrorBinding->GetArgumentCount()>1) { // "Type '|1' cannot be used for the '|2' in '|3' in this context because '|1' is an 'Out|In' type parameter." // e.g. "Sub f(ByVal a As IDoubleEnumerable(Of O,I)) yields // "An 'Out' parameter like 'O' cannot be used for type parameter 'T1' of 'IDoubleEnumerable(Of T1,T2)'." ERRID ErrId = InappropriateOut ? ERRID_VarianceOutParamDisallowedForGeneric3 : ERRID_VarianceInParamDisallowedForGeneric3; ReportErrorOnSymbol(ErrId, ErrorTable, ErrorSymbol, GetQualifiedErrorName(Type), GetQualifiedErrorName(ErrorParam), GetQualifiedErrorName(ErrorBinding->GetGeneric())); } else if (ErrorBindingNesting>1 && ErrorBinding->GetArgumentCount()<=1) { // "Type '|1' cannot be used in '|2' in this context because '|1' is an 'Out|In' type parameter." // e.g. "Sub f(ByVal a as Func(Of IEnumerable(Of O), IEnumerable(Of O))" yields // "In 'IEnumerable(Of O)' here, an 'Out' parameter like 'O' cannot be used." ERRID ErrId = InappropriateOut ? ERRID_VarianceOutParamDisallowedHere2 : ERRID_VarianceInParamDisallowedHere2; ReportErrorOnSymbol(ErrId, ErrorTable, ErrorSymbol, GetQualifiedErrorName(Type), GetQualifiedErrorName(ErrorBinding)); } else if (ErrorBindingNesting>1 && ErrorBinding->GetArgumentCount()>1) { // "Type '|1' cannot be used in '|2' for the '|3' in '|4' in this context because '|1' is an 'Out' type parameter." // e.g. "Sub f(ByVal a as IEnumerable(Of Func(Of O,O))" yields // "In 'Func(Of O,O)' here, an 'Out' parameter like 'O' cannot be used for type parameter 'Tresult' of 'Func(Of Tresult,T)'." ERRID ErrId = InappropriateOut ? ERRID_VarianceOutParamDisallowedHereForGeneric4 : ERRID_VarianceInParamDisallowedHereForGeneric4; ReportErrorOnSymbol(ErrId, ErrorTable, ErrorSymbol, GetQualifiedErrorName(Type), GetQualifiedErrorName(ErrorBinding), GetQualifiedErrorName(ErrorParam), GetQualifiedErrorName(ErrorBinding->GetGeneric())); } else { VSFAIL("InternalCompilerError: we should already have covered all cases of Context/ErrorBindingNesting/ErrorBindingArgCount"); ReportErrorOnSymbol(ERRID_InternalCompilerError, ErrorTable, ErrorSymbol); } } } // 2. if T is an array U(): else if (Type->IsArrayType()) { BCSYM_ArrayType *ArrayType = Type->PArrayType(); CheckThatTypeSatisfiesVariance_Helper( ArrayType->GetRoot(), RequiredVariance, Container, Context, ErrorSymbol, ErrorTable, ErrorBinding, ErrorParam, ErrorBindingNesting); } // 3. T is a construction X1(Of T11...)...Xn(Of Tn1...) of some generic struct/class/interface/delegate X1(Of X11...)...Xn(Of Xn1...) else if (Type->IsGenericBinding()) { // Special check, discussed above, for better error-reporting when we find a generic binding in an // illegal contravariant position if (RequiredVariance != Variance_Out) { BCSYM_NamedRoot *OutermostVarianceContainerOfBinding = NULL; // for (BCSYM_GenericBinding *GenericBinding=Type->PGenericBinding()->GetParentBinding(); GenericBinding; GenericBinding=GenericBinding->GetParentBinding()) { if (TypeHelpers::HasVariance(GenericBinding)) { OutermostVarianceContainerOfBinding = GenericBinding->GetGeneric(); VSASSERT(OutermostVarianceContainerOfBinding!=NULL, "Expected generic-binding to have non-null generic"); } } BCSYM_NamedRoot *OutermostVarianceContainerOfContext = NULL; // for (BCSYM_Container *Parent = Container; Parent; Parent=Parent->GetContainingClassOrInterface()) { if (TypeHelpers::HasVariance(Parent)) { OutermostVarianceContainerOfContext = Parent; } } if (OutermostVarianceContainerOfBinding!=NULL && OutermostVarianceContainerOfBinding == OutermostVarianceContainerOfContext ) { BCSYM_NamedRoot *NestedType = Type->PGenericBinding()->GetGeneric(); VSASSERT(NestedType!=NULL, "Expected generic-binding to have non-null generic"); // ERRID_VarianceTypeDisallowed2. "Type '|1' cannot be used in this context because both the context and the definition of '|1' are nested within type '|2', and '|2' has 'In' or 'Out' type parameters. Consider moving '|1' outside of '|2'." // ERRID_VarianceTypeDisallowedForGeneric4. "Type '|1' cannot be used for the '|3' in '|4' in this context because both the context and the definition of '|1' are nested within type '|2', and '|2' has 'In' or 'Out' type parameters. Consider moving '|1' outside of '|2'." // ERRID_VarianceTypeDisallowedHere3. "Type '|1' cannot be used in '|3' in this context because both the context and the definition of '|1' are nested within type '|2', and '|2' has 'In' or 'Out' type parameters. Consider moving '|1' outside of '|2'." // ERRID_VarianceTypeDisallowedHereForGeneric5. "Type '|1' cannot be used for the '|4' of '|5' in '|3' in this context because both the context and the definition of '|1' are nested within type '|2', and '|2' has 'In' or 'Out' type parameters. Consider moving '|1' outside of '|2'." if (ErrorBinding==NULL) { ReportErrorOnSymbol(ERRID_VarianceTypeDisallowed2, ErrorTable, ErrorSymbol, GetQualifiedErrorName(NestedType), GetQualifiedErrorName(OutermostVarianceContainerOfBinding)); } else if (ErrorBindingNesting<=1 && ErrorBinding->GetArgumentCount()<=1) { ReportErrorOnSymbol(ERRID_VarianceTypeDisallowed2, ErrorTable, ErrorSymbol, GetQualifiedErrorName(NestedType), GetQualifiedErrorName(OutermostVarianceContainerOfBinding)); } else if (ErrorBindingNesting<=1 && ErrorBinding->GetArgumentCount()>1) { ReportErrorOnSymbol(ERRID_VarianceTypeDisallowedForGeneric4, ErrorTable, ErrorSymbol, GetQualifiedErrorName(NestedType), GetQualifiedErrorName(OutermostVarianceContainerOfBinding), GetQualifiedErrorName(ErrorParam), GetQualifiedErrorName(ErrorBinding->GetGeneric())); } else if (ErrorBindingNesting>1 && ErrorBinding->GetArgumentCount()<=1) { ReportErrorOnSymbol(ERRID_VarianceTypeDisallowedHere3, ErrorTable, ErrorSymbol, GetQualifiedErrorName(NestedType), GetQualifiedErrorName(OutermostVarianceContainerOfBinding), GetQualifiedErrorName(ErrorBinding)); } else if (ErrorBindingNesting>1 && ErrorBinding->GetArgumentCount()>1) { ReportErrorOnSymbol(ERRID_VarianceTypeDisallowedHereForGeneric5, ErrorTable, ErrorSymbol, GetQualifiedErrorName(NestedType), GetQualifiedErrorName(OutermostVarianceContainerOfBinding), GetQualifiedErrorName(ErrorBinding), GetQualifiedErrorName(ErrorParam), GetQualifiedErrorName(ErrorBinding->GetGeneric())); } else { VSFAIL("InternalCompilerError: impossible combination of nested/argcount"); ReportErrorOnSymbol(ERRID_InternalCompilerError, ErrorTable, ErrorSymbol); } return; } } // The general code below will catch the case of nullables "T?" or "Nullable(Of T)", which require T to // be inviarant. But we want more specific error reporting for this case, so we check for it first. if (TypeHelpers::IsNullableType(Type, this->m_CompilerHost)) { BCSYM_GenericBinding *GenericBinding = Type->PGenericBinding(); VSASSERT(GenericBinding->GetGenericParamCount()==1 && GenericBinding->GetFirstGenericParam()->GetVariance() == Variance_None, "unexpected: a nullable type should have one generic parameter with no variance"); CheckThatTypeSatisfiesVariance_Helper(GenericBinding->GetArgument(0), Variance_None, Container, VarianceContextNullable, ErrorSymbol, ErrorTable, ErrorBinding, ErrorParam, ErrorBindingNesting); return; } // "Type" will refer to the last generic binding, Xn(Of Tn1...). So we have to check all the way up to X1. for (BCSYM_GenericBinding *GenericBinding=Type->PGenericBinding(); GenericBinding; GenericBinding=GenericBinding->GetParentBinding()) { int ArgumentIndex = 0; for (BCSYM_GenericParam *gParam=GenericBinding->GetFirstGenericParam(); gParam; gParam=gParam->GetNextParam(), ArgumentIndex++) { BCSYM *gArgument = GenericBinding->GetArgument(ArgumentIndex); Variance_Kind SubRequiredVariance = RequiredVariance==Variance_None ? Variance_None : (RequiredVariance==Variance_Out ? gParam->GetVariance() : InvertVariance(gParam->GetVariance())); // nb. the InvertVariance() here is the only difference between covariantly-valid and contravariantly-valid // for generic constructions. CheckThatTypeSatisfiesVariance_Helper( gArgument, SubRequiredVariance, Container, VarianceContextComplex, ErrorSymbol, ErrorTable, GenericBinding, gParam, ErrorBindingNesting+1); } } } else if (Type->IsClass() || Type->IsInterface()) // Type->IsClass() also covers StdModule, Struct, Enum and Delegate. { // Non-generic types intrinsically satisfy all variance requirements. } else { VSFAIL("unexpected type when checking variance"); } } Variance_Kind Bindable::InvertVariance(Variance_Kind v) { switch (v) { case Variance_Out: return Variance_In; case Variance_In: return Variance_Out; case Variance_None: return Variance_None; default: VSFAIL("bad variance"); return v; } } // "AmbiguousClashData": this datastructure is used by CheckVarianceAmbiguity. // It detects ambiguity-clashes between pairs of "implements" declarations in a class/interface. // For each clash, it stores Key=one of the pair, and Value=AmbiguousClashData. // The AmbiguousClashData includes the other element of the pair, and also the // actual culprit interfaces that caused the clash. Note that it's possible for an implements // declaration to INHERIT from cuplrits, rather than being the culprit itself. // e.g. Class C : I1, I2, where I1:R(Of Mammal), and I2:R(Of Fish). struct AmbiguousClashData { BCSYM_Implements *otherDeclaration; BCSYM_GenericTypeBinding *left, *right; // "left" and "right" are the two interfaces that caused the clash. AmbiguousClashData( BCSYM_Implements *otherDeclaration, BCSYM_GenericTypeBinding *left, BCSYM_GenericTypeBinding *right) : otherDeclaration(otherDeclaration), left(left),right(right) { } AmbiguousClashData() { } }; // "AmbiguousInterfaceData": this datastructure is used by CheckVarianceAmbiguity. // The function searches through all "implements" declarations in a class/interface, // and also for all the interfaces that these declarations inherit from. // Note that a given interface might be inherited by several different "implements" declarations, // e.g. Class C : I1, I2, where I1:R(Of Mammal) and I2:R(Of Mammal) struct AmbiguousInterfaceData { BCSYM_GenericTypeBinding *iface; // an interface that we're going to investigate HashSet<BCSYM_Implements*> implementsDeclarations; }; // PopulateInterfaceListWithGenerics: // This function scans the list of interfaces starting from "firstImplements", along with every interface // that those interfaces inherit. For every one that's a generic type binding with variant parameters, // it gets put in "bins". There may be several bins. Each bin contains bindings of one particular // generic interface: e.g. one bin will contain IEnumerable(Of String) and IEnumerable(Of Object), // and another bin will contain IFred(Of Alf) and IFred(Of Jones) and IFred(Of Wilbur). // Note: we assume that the caller has already resolved partial types for "Container" in case it's a class. // Interfaces can't be partial, anyways. void PopulateInterfaceListWithGenerics( DynamicArray<DynamicArray<AmbiguousInterfaceData>> &bins, // store results here BCSYM *container, // scan all the interfaces implemented by this container int depth, // inheritance depth that we're at BCSYM_Implements *declaration, // If depth>0 then we use "declaration" for the declaration it came from Symbols &SymbolFactory ) { VSASSERT(depth==0 || declaration!=NULL, "unexpected: when walking up the hierarchy, we should have kept track of which declaration we started from"); VSASSERT(container!=NULL && ((container->IsClass() && depth==0) || container->IsInterface()), "please invoke PopulateInterfaceList with a container or an interface"); // note: container is either a GenericBinding of a Class/Interface, or is a Class/Interface itself. // The functions IsClass() and IsInterface() above both peer through GenericBindings to the unbound Generic itself. // And below, container->PContainer() does likewise to enumerate the implemented interfaces of the unboundGeneric. // Then (Dev10#570404) we reapply any generic binding contexts that are needed. BCITER_ImplInterfaces ImplInterfacesIter(container->PContainer()); while (BCSYM_Implements *implements = ImplInterfacesIter.GetNext()) { if (implements->IsBad() || implements->GetRoot()==NULL || implements->GetRoot()->IsBad() || !implements->GetRoot()->IsInterface()) { // in all these error conditions we won't even bother looking for ambiguity problems... continue; } BCSYM *iface = implements->GetRoot(); if (container->IsGenericBinding()) { // Dev10#570404: e.g. if container was "IList(Of String)", then ImplInterfaces would iterate // over the implemented interfaces of IList(Of T) giving ICollection(Of T) and IEnumerable(Of T), // and then we have to reapply the {String/T} binding onto each of those implemented interfaces: iface = ReplaceGenericParametersWithArguments(iface, container->PGenericBinding(), SymbolFactory); } // We want to associate each interface with the interface-declaration it came from. In the original // class's list of declarations, that will be just the same as "implements". But further up the interface // inheritance hierarchy, it won't be... we deal with that through "declaration" if (depth==0) { declaration = implements; } VSASSERT(declaration!=NULL && declaration->PImplements(), "unexpected: an implements declaration that wasn't a BCSYM_Implements declaration"); // Recursive search through the interface's inherited interfaces PopulateInterfaceListWithGenerics(bins, iface, depth+1, declaration, SymbolFactory); if (iface->IsGenericTypeBinding() && TypeHelpers::HasVariance(iface)) { // Now we have to add "iface" into the appropriate bin. // First find the bin (creating a new bin if necessary) ULONG bindex; for (bindex=0; bindex<bins.Count(); bindex++) { VSASSERT(bins.Array()[bindex].Count()>0, "unexpected: an empty bin"); if (BCSYM::AreTypesEqual(bins.Array()[bindex].Array()[0].iface->GetGeneric(), iface->PGenericTypeBinding()->GetGeneric())) { break; } } if (bindex == bins.Count()) { bins.CreateNew(); } DynamicArray<AmbiguousInterfaceData> &bin = bins.Array()[bindex]; // Next, add a new AmbiguousInterfaceData only if it's not already there ULONG dataIndex; for (dataIndex=0; dataIndex<bin.Count(); dataIndex++) { if (BCSYM::AreTypesEqual(bin.Array()[dataIndex].iface, iface)) { break; } } if (dataIndex == bin.Count()) { bin.CreateNew(); bin.Array()[dataIndex].iface = iface->PGenericTypeBinding(); } AmbiguousInterfaceData &interfaceData = bin.Array()[dataIndex]; // Finally, add baseInterface to the interfaceData's list if it's not already present. interfaceData.implementsDeclarations.Add(declaration); } } } void Bindable::CheckVarianceAmbiguity(BCSYM_Container *Container, CompilationCaches *IDECompilationCaches) { // What is "Variance Ambiguity"? Here's an example: // Class ReflectionType // Implements IEnumerable(Of Field) // Implements IEnumerable(Of Method) // Public Sub GetEnumeratorF() As IEnumerator(Of Field) Implements IEnumerable(Of Field).GetEnumerator ... // Public Sub GetEnumeratorM() As IEnumerator(Of Method) Implements IEnumberale(Of Method).GetEnumerator ... // End Class // Dim x as new ReflectionType // Dim y as IEnumerable(Of Member) = x // Dim z = y.GetEnumerator() // // Note that, through variance, both IEnumerable(Of Field) and IEnumerable(Of Method) have widening // conversions to IEnumerable(Of Member). So it's ambiguous whether the initialization of "z" would // invoke GetEnumeratorF or GetEnumeratorM. This function avoids such ambiguity at the declaration // level, i.e. it reports a warning on the two implements classes inside ReflectionType that they // may lead to ambiguity. // For an interface which inherits a list of interfaces, or for a class which imports a list of interfaces, // we check whether any of those interfaces (or the ones reachable through inheritance) might lead // to variance-conversion-ambiguity. // (for simplicity on callers, this function might also be called when Container is any other kind of // container; they'll always have a null "Implements" clause. But if the language were changed so that // an enum could implement interfaces, for instance, then we'll end up doing the right thing.) NorlsAllocator ScratchAllocator(NORLSLOC); Symbols SymbolFactory(CurrentCompilerInstance(), &ScratchAllocator, NULL); // First step: gather up the list of interfaces into separate bins. // Each bin contains interfaces with the same variant generic root, but different bindings of it. // Note: the outer DynamicArray takes care of calling destructors on each of the inner DynamicArrays. // And the inner DynamicArrays would notionally call the destructor of their contents, but their // contents are just pointers to BCSYM_GenericTypeBinding, so they're not touched. DynamicArray<DynamicArray<AmbiguousInterfaceData>> bins; ResolvePartialTypesForContainer(Container, IDECompilationCaches); PopulateInterfaceListWithGenerics(bins, Container, 0, NULL, SymbolFactory); if (bins.Count() == 0) { return; } // What we produce in the end should be a list of which implements clauses clashed with which // other implements clauses, for error reporting. But our various collection classes aren't up // to the job. So we'll keep simpler clash data. It'll still be decent enough to give good // error reports. If clashes has a pair (X, {Y,a,b}) then it means that the implements // delcaration "X" clashed with the implements declaration "Y", and the culprits for this clash // were the two interfaces "a" and "b". Note that it's possible for X==Y (in the case // that we imported clashing metadata). DynamicHashTable<BCSYM_Implements*, AmbiguousClashData, VBAllocWrapper> clashes; // Second step: within each bin, do a pairwise comparison of each interface to look for ambiguity. // Note that the ambiguity tests are symmetric. for (ULONG ibin=0; ibin<bins.Count(); ibin++) { DynamicArray<AmbiguousInterfaceData> &bin = bins.Array()[ibin]; for (ULONG outer=0; outer<bin.Count(); outer++) { for (ULONG inner=outer+1; inner<bin.Count(); inner++) { BCSYM_GenericTypeBinding *left = bin.Array()[outer].iface; BCSYM_GenericTypeBinding *right = bin.Array()[inner].iface; VSASSERT(left!=NULL && right!=NULL && left->IsInterface() && right->IsInterface(), "unexpected: non-interfaces in a bin"); VSASSERT(!BCSYM::AreTypesEqual(left,right), "unexpected: equal types in a bin"); VSASSERT(BCSYM::AreTypesEqual(left->GetGeneric(), right->GetGeneric()), "unexpected: types with different generics in the same bin"); // We have something like left=ICocon(Of Mammal, int32[]), right=ICocon(Of Fish, int32[]) // for some interface ICocon(Of Out T, In U). And we have to decide if left and right // might lead to ambiguous member-lookup later on in execution. // // To do this: go through each type parameter T, U... // * For "Out T", judge whether the arguments Mammal/Fish cause ambiguity or prevent it. // * For "In T", judge whether the arguments int32[]/int32[] cause ambiguity or prevent it. // // "Causing/preventing ambiguity" is as follows. // * Covariant parameters "Out T": ambiguity is caused when the two type arguments Mammal/Fish // are non-identical non-object types not known to be values. Ambiguity is prevented when // Mammal/Fish are non-identical non-generic types of which at least one is a value type. // * Contravariant parameters "In U": ambiguity is caused when the two type arguments int32[]/int32[] // are non-identical types not known to be values. Ambiguity is prevented when int32[]/int32[] // are non-identical non-generic types of which at least one is a value type. // * Invariant parameters "V": these never cause ambiguity. They prevent ambiguity when // they are provided with two non-identical non-generic arguments. // // Given all that, ambiguity was prevented in any positions, then left/right are fine. // Otherwise, if ambiguity wasn't caused in any positions, then left/right are fine. // Otherwise, left/right have an ambiguity... int causesAmbiguityCount = 0; int preventsAmbiguityCount = 0; // A generic binding is constructed in layers, e.g. C(Of Z).I(Of X,Y). So we have to // iterate over those layers... for (BCSYM_GenericTypeBinding *leftBinding=left, *rightBinding=right; leftBinding!=NULL && rightBinding!=NULL && preventsAmbiguityCount==0; leftBinding = leftBinding->GetParentBinding(), rightBinding = rightBinding->GetParentBinding()) { VSASSERT(BCSYM::AreTypesEqual(leftBinding->GetGeneric(), rightBinding->GetGeneric()), "unexpected: different generic bindings"); BCSYM_NamedRoot *genericType = left->GetGenericType(); // Within each layer, we have to iterate over each parameter int argumentIndex = 0; for (BCSYM_GenericParam *gParam = genericType->GetFirstGenericParam(); gParam && preventsAmbiguityCount==0; gParam=gParam->GetNextParam(), argumentIndex++) { BCSYM *leftArgument = leftBinding->GetArgument(argumentIndex); BCSYM *rightArgument = rightBinding->GetArgument(argumentIndex); VSASSERT(leftArgument!=NULL && rightArgument!=NULL, "unexpected: null type arguments to a generic type binding"); bool areEqual = BCSYM::AreTypesEqual(leftArgument, rightArgument); switch (gParam->GetVariance()) { case Variance_Out: { if (!areEqual && !TypeHelpers::IsValueType(leftArgument) && !TypeHelpers::IsValueType(rightArgument) && !leftArgument->IsObject() && !rightArgument->IsObject()) { causesAmbiguityCount++; } else if (!areEqual && !leftArgument->IsGeneric() && !rightArgument->IsGeneric() && (TypeHelpers::IsValueType(leftArgument) || TypeHelpers::IsValueType(rightArgument))) { preventsAmbiguityCount++; } break; } case Variance_In: { if (!areEqual && !TypeHelpers::IsValueType(leftArgument) && !TypeHelpers::IsValueType(rightArgument)) { causesAmbiguityCount++; } else if (!areEqual && !leftArgument->IsGeneric() && !rightArgument->IsGeneric() && (TypeHelpers::IsValueType(leftArgument) || TypeHelpers::IsValueType(rightArgument))) { preventsAmbiguityCount++; } break; } case Variance_None: { if (!areEqual && !leftArgument->IsGeneric() && !rightArgument->IsGeneric()) { preventsAmbiguityCount++; } break; } default: { VSFAIL("unexpected: unknown variance"); preventsAmbiguityCount++; } } // end switch(Variance) } // end for each argument index in a layer of generic binding } // end for layers of generic binding // At this point, all that remains is to add this ambiguity (if there was one) // to our list "clashes" which records which implements declarations clashed with which other ones. if (preventsAmbiguityCount>0 || causesAmbiguityCount==0) { continue; } // The thing is, the interface "left" might have come from several different Implements declarations. // And "right" might also have come from several different declarations. // e.g. Class C : implements I1 : implements I2 : implements I3, // where "Interface I1 : implements R(Of Fish)" and "I2: implements R(Of Mammal)" and "I3: implements R(Of Mammal)". // It's even possible (if we imported metadata that had variance ambiguity) that // a single interface I1 might contain clashes INSIDE itself. // VSASSERT(bin.Array()[outer].implementsDeclarations.Count()>0 && bin.Array()[inner].implementsDeclarations.Count()>0, "unexpected: clashing left/right interfaces, but apparently the interfaces didn't come from any declaration!"); HashSetIterator<BCSYM_Implements*> leftDeclarations(&bin.Array()[outer].implementsDeclarations); while (leftDeclarations.MoveNext()) { BCSYM_Implements *leftDeclaration = leftDeclarations.Current(); HashSetIterator<BCSYM_Implements*> rightDeclarations(&bin.Array()[inner].implementsDeclarations); while (rightDeclarations.MoveNext()) { BCSYM_Implements *rightDeclaration = rightDeclarations.Current(); VSASSERT(leftDeclaration!=NULL && rightDeclaration!=NULL, "unexpected: null left/right declarations"); // In the following, if a clash had previously been added because of a clash inside // a single interface declaration with itself (e.g. due to bad metadata), then // we can probably find a more interesting clash to report to the user... if (!clashes.Contains(leftDeclaration) || clashes.GetValue(leftDeclaration).otherDeclaration == leftDeclaration) { clashes.SetValue(leftDeclaration, AmbiguousClashData(rightDeclaration, left, right)); } if (!clashes.Contains(rightDeclaration) || clashes.GetValue(rightDeclaration).otherDeclaration == rightDeclaration) { clashes.SetValue(rightDeclaration, AmbiguousClashData(leftDeclaration, right, left)); } } // end while rightDeclarations.MoveNext } // end while leftDeclarations.MoveNext } // end for inner GenericTypeBinding within bin } // end for outer GenericTypeBinding within bin } // end for bin // Now, at the end, we have "clashes". For each ambiguous interface declaration, it reports // another interface that it's ambiguous with. if (clashes.Count()==0) { return; } HashTableIterator<BCSYM_Implements*,AmbiguousClashData,VBAllocWrapper> clash(&clashes); while (clash.MoveNext()) { BCSYM_Implements *leftDeclaration = clash.Current().Key(); BCSYM_Implements *rightDeclaration = clash.Current().Value().otherDeclaration; BCSYM_GenericTypeBinding *leftCulprit = clash.Current().Value().left; BCSYM_GenericTypeBinding *rightCulprit = clash.Current().Value().right; if (leftDeclaration==NULL || rightDeclaration==NULL || leftCulprit==NULL || rightCulprit==NULL || !BCSYM::AreTypesEqual(leftCulprit->GetGeneric(), rightCulprit->GetGeneric())) { VSFAIL("InternalCompilerError: we somehow ended up with inconsistent clash data");; ReportErrorOnSymbol(ERRID_InternalCompilerError, CurrentErrorLog(Container), Container); continue; } if (leftDeclaration->IsBad() || rightDeclaration->IsBad()) { continue; } // "Interface '|1' is ambiguous with another implemented interface '|2' due to the 'In' and 'Out' parameters in '|3'." // Note: we use GetBasicRep on the generic to show its full name, including In/Out annotations. StringBuffer FullGenericName; leftCulprit->GetGeneric()->GetBasicRep(this->m_CompilerHost->GetCompiler(), Container, &FullGenericName); ReportErrorOnSymbol(WRNID_VarianceDeclarationAmbiguous3, CurrentErrorLog(Container), leftDeclaration, GetQualifiedErrorName(leftDeclaration->GetRoot()), GetQualifiedErrorName(rightDeclaration->GetRoot()), FullGenericName.GetString()); } } ////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////// // Returns True only if Class Or Interface // Returns False if Module or Structure of Enum or any other non-Class // bool Bindable::IsClassOrInterface(BCSYM *Container) { return (IsClass(Container) || IsInterface(Container)); } bool Bindable::IsClass ( BCSYM *Container ) { return (Container && (Container->IsClass() && !Container->PClass()->IsStdModule() && !Container->PClass()->IsStruct() && !Container->PClass()->IsEnum() && !Container->PClass()->IsDelegate())); } bool Bindable::IsInterface ( BCSYM *Container ) { return (Container && Container->IsInterface()); } bool Bindable::IsStdModule ( BCSYM *Container ) { return Container && Container->IsClass() && Container->PClass()->IsStdModule(); } bool Bindable::IsUnnamedNamespace ( BCSYM *PossibleNamespace, Compiler *CompilerInstance ) { bool UnnamedNamespace = PossibleNamespace && PossibleNamespace->IsNamespace() && StringPool::IsEqual( PossibleNamespace->PNamespace()->GetName(), STRING_CONST(CompilerInstance, EmptyString)); VSASSERT(!UnnamedNamespace || !PossibleNamespace->PNamespace()->GetContainer(), "Unnamed Namespace expected to be at the root of the symbol hierarchy!!!"); return UnnamedNamespace; } void Bindable::ResolveBaseForClass ( BCSYM_Class *Class ) { for(BCSYM_Class *PartialType = Class; PartialType; PartialType = PartialType->GetNextPartialType()->PClass()) { BCSYM *BaseClass = PartialType->GetRawBase(); if (!BaseClass) { continue; } // Resolve the named type of the base if (BaseClass->IsNamedType()) { ResolveBaseType(BaseClass->PNamedType()); BCSYM *BoundBaseClass = BaseClass->DigThroughNamedType(); if (IsClass(BoundBaseClass) && (PossibleInheritanceCycleDetected() || GetStatusOfResolveBases(BoundBaseClass->PClass()) == InProgress)) { SetCurrentBase(BaseClass->PNamedType()); // Check for cycles on the current container after resolving a base // if (DoesBaseCauseInheritanceCycle(Class, BoundBaseClass->PClass(), BaseClass->GetLocation())) { // Break the cycle by marking the Container as having cycles so that // other folks don't loop infinitely over the bases // Class->SetBaseInvolvedInCycle(true); } SetCurrentBase(NULL); } } } // Note that this call might change the raw base of the class itself sometine // for partial types. So after this call, the base should be got again from the // class symbol. // DoClassInheritanceValidationNotRequiringOtherBoundBasesInfo(Class); // Make sure that the base is also resolved // This recursive call makes sure that all the bases up the // inheritance hierarchy are also processed completely. // BCSYM *BoundBaseClass = Class->GetBaseClass(); BCSYM *BaseClass = Class->GetRawBase(); if (BoundBaseClass && !BoundBaseClass->IsBad()) { if (BaseClass->IsNamedType()) { SetCurrentBase(BaseClass->PNamedType()); VSASSERT( BoundBaseClass->IsClass(), "Validate should have marked non-class inherits as bad!!!"); ResolveBasesForContainer(BoundBaseClass->PClass(), m_CompilationCaches); // This class's bases could itself get triggered off through its parents, // after we break the circular parent - nested type dependencies. // If this Class/Interface has already been processed for this, return // else continue on and complete the task now. // The parent - nested type cycle detection algorithm is kind of reentrant, // so... // if (GetStatusOfResolveBases() == Done) { return; } SetCurrentBase(NULL); } else { VSASSERT( BoundBaseClass->IsContainer() && DefinedInMetaData(BoundBaseClass->PContainer()), "How can a non-metadata class be set as the default base for any class ?"); // If ever for any reason this restriction is gone, then the Parent cycle detection which // depends on the CurrentBase being set to a named type will have to be changed. } // Note that this needs to be invoked only after inheritance cycle detection for the class // being validated is completed because these checks walk inheritance chains. // DoClassInheritanceValidationRequiringOtherBoundBasesInfo(Class); } } void Bindable::ResolveBasesForInterface ( BCSYM_Interface *Interface ) { BCSYM_Implements *HeadOfBasesList = Interface->GetFirstImplements(); for (BCSYM_Implements *CurrentBase = HeadOfBasesList; CurrentBase; CurrentBase = CurrentBase->GetNext()) { BCSYM *BaseInterface = CurrentBase->GetRawRoot(); if (!BaseInterface) { continue; } if (BaseInterface->IsNamedType()) { ResolveBaseType(BaseInterface->PNamedType()); BCSYM *BoundBaseInterface = BaseInterface->DigThroughNamedType(); if (IsInterface(BoundBaseInterface) && (PossibleInheritanceCycleDetected() || GetStatusOfResolveBases(BoundBaseInterface->PInterface()) == InProgress)) { SetCurrentBase(CurrentBase->GetRawRoot()->PNamedType()); // Check for cycles on the current container after resolving a base // if (DoesBaseCauseInheritanceCycle(Interface, BoundBaseInterface->PInterface(), CurrentBase->GetLocation())) { // Break the cycle by marking the Container as having cycles so that // other folks don't loop infinitely over the bases // CurrentBase->SetIsBad(); } SetCurrentBase(NULL); } } } // validate base interfaces here ValidateInterfaceInheritance(Interface); for (BCSYM_Implements *CurrentBase = HeadOfBasesList; CurrentBase; CurrentBase = CurrentBase->GetNext()) { if (CurrentBase->IsBad()) continue; BCSYM *BoundBaseInterface = CurrentBase->GetRoot(); if (!BoundBaseInterface || BoundBaseInterface->IsGenericBadNamedRoot()) { continue; } SetCurrentBase(CurrentBase->GetRawRoot()->PNamedType()); VSASSERT( BoundBaseInterface->IsInterface(), "Validation should have marked non-interface inherits as bad!!!"); ResolveBasesForContainer(BoundBaseInterface->PInterface(), m_CompilationCaches); // This class's bases could itself get triggered off through its parents, // after we break the circular parent - nested type dependencies. // If this Class/Interface has already been processed for this, return // else continue on and complete the task now. // The parent - nested type cycle detection algorithm is kind of reentrant, // so... // if (GetStatusOfResolveBases() == Done) { return; } SetCurrentBase(NULL); } } bool Bindable::DoesBaseCauseInheritanceCycle ( BCSYM_Container *Container, BCSYM_Container *Base, Location *InheritsLocation ) { DynamicArray<BCSYM_Container *> ContainersInCycle; Location *Location = NULL; if (DetectInheritanceCycle( Container, Base, &ContainersInCycle)) { // This Container is the node at which the cycle was detected VSASSERT( ContainersInCycle.Element(0)->IsSameContainer(Container), "Cycle detected - but the start and end of the cycle are not the same !!!"); ContainersInCycle.AddElement(Container); // Report Cycles Error ReportInheritanceCyclesError( &ContainersInCycle, InheritsLocation); // Note: Don't mark this bad since we want this Container to still go through the // rest of bindable and also for intellisense, etc. to show up for it. // The cycle is broken in DetectInheritanceCycle // Cycle Present return true; } return false; } bool Bindable::DetectInheritanceCycle ( BCSYM_Container *ContainerToVerify, BCSYM_Container *BaseContainer, DynamicArray<BCSYM_Container *> *ContainersInCycle ) { if (ContainerToVerify->IsSameContainer(BaseContainer)) { ContainersInCycle->AddElement(BaseContainer); return true; } BasesIter Bases(BaseContainer); for (BCSYM_Container *Base = Bases.GetNextBase(); Base; Base = Bases.GetNextBase()) { if (Base->IsBad()) { continue; } if (DetectInheritanceCycle(ContainerToVerify, Base, ContainersInCycle)) { ContainersInCycle->AddElement(BaseContainer); return true; } } return false; } void Bindable::ReportInheritanceCyclesError ( DynamicArray<BCSYM_Container *> *ClassesInCycle, Location *Location ) { int Count = ClassesInCycle->Count(); STRING *Derived, *Base; VSASSERT( Count >= 2, "How can we have a cycle here ?"); BCSYM_Container *ErrorRoot = ClassesInCycle->Element(0); StringBuffer CycleDesc; // Append the Inheritance path followed to detect the cycle for (int Index = Count - 1; Index >= 1; Index--) { Derived = ClassesInCycle->Element(Index)->GetName(); Base = ClassesInCycle->Element(Index - 1)->GetName(); ResLoadStringRepl( ERRID_InheritsFrom2, &CycleDesc, Derived, Base); } VSASSERT(CurrentContainer() == ClassesInCycle->Element(0), "Unexpected container as cycle originator!!!"); // Initialize with the error specifying the error node at which the cycle was detected ReportErrorAtLocation( IsInterface(ClassesInCycle->Element(0)) ? ERRID_InterfaceCycle1 : ERRID_InheritanceCycle1, CurrentErrorLog(GetCurrentBase()), Location, ErrorRoot->GetName(), CycleDesc.GetString()); } // this is an entry point for BCSYM_Class And BCSYM_Interface to Resolve bases on demand void Bindable::ResolveBasesIfNotStarted ( BCSYM_Container *Container, CompilationCaches *IDECompilationCaches ) { if (DefinedInMetaData(Container) || Container->IsBindingDone()) { return; } #if IDE if (!IsInCompilationThread(Container->GetCompiler())) { return; } #endif IDE // VSASSERT( !Container->GetSourceFile() || Container->GetSourceFile()->GetCompState() >= CS_Bound || (Container->GetSourceFile()->GetCompState() == (CS_Bound - 1) && Container->GetSourceFile()->GetProject()->GetCompState() == (CS_Bound - 1)), "This should only be invoked after this file has reached bound or when transitioning from previous state to Bound!!!"); if (Container->GetMainType()) { Container = Container->GetMainType(); } if (Container->GetBindableInstance()->GetStatusOfResolveBases() == NotStarted) { Bindable::ResolveBasesForContainer(Container, IDECompilationCaches); } } Bindable::TaskTriState Bindable::GetStatusOfResolveBases ( BCSYM_Container *Container ) { // Metadata containers not allowed in here if (DefinedInMetaData(Container) || Container->IsBindingDone()) { return Done; } return Container->GetBindableInstance()->GetStatusOfResolveBases(); } // Entry point for Obsoletechecker // IsContainerReadyForObsoleteChecking here will only return true // if the current Container Context's Attributes have already been ----ed. // This is a helper for obsolete checker to avoid circular dependencies when // doing obsolete checking and attribute cracking might be required on other // containers on demand when doing name binding for earlier stages // #if DEBUG bool Bindable::IsContainerReadyForObsoleteChecking ( BCSYM_Container *Container ) { // Metadata containers are always ready for Obsolete checking // because there will not be any circular dependencies when // processing metadata containers. // if (DefinedInMetaData(Container) || // Yes, obsolete checker gets Conditional Compilation constants // too for obsolete checking!!! Container->IsCCContainer()) { return true; } BCSYM_Container *ContainerToCheck; if (Container->IsPartialTypeAndHasMainType()) { ContainerToCheck = Container->GetMainType(); } else { ContainerToCheck = Container; } if (ContainerToCheck && (ContainerToCheck->IsBindingDone() || ContainerToCheck->GetBindableInstance()->GetStatusOf----AttributesOnAllSymbolsInContainer() == Done)) { return true; } return false; } #endif DEBUG void Bindable::ResolveNamedType ( BCSYM_NamedType *NamedType, TypeResolutionFlags Flags, NameFlags NameInterpretFlags, bool DisableNameLookupCaching ) { ResolveNamedType( NamedType, CurrentAllocator(), CurrentErrorLog(NamedType->GetContext()), CurrentCompilerInstance(), CurrentCompilerHost(), CurrentSourceFile(NamedType->GetContext()), // Don't perform obsolete checks. Will do the // obsolete checking for the whole container later. Flags & ~TypeResolvePerformObsoleteChecks, m_CompilationCaches, NameInterpretFlags, DisableNameLookupCaching); } void Bindable::ResolveAllNamedTypesForContainer ( TypeResolutionFlags Flags // [in] indicates how to resolve the type ) { if (GetStatusOfResolveNameTypes() == Done) { return; } // This could happen if there are structure fields in current container // and we are inturn resolving named types in that structure. // if (GetStatusOfResolveNameTypes() == InProgress) { SetStructureMemberCycleDetected(true); return; } // Mark the current container indicating that work is in progress to resolve its named types SetStatusOfResolveNamedTypes(InProgress); BCSYM_Container *Container = CurrentContainer(); // Resolve all named types in this container // do { for(BCSYM_NamedType *NamedType = Container->GetNamedTypesList(); NamedType; NamedType = NamedType->GetNext()) { ResolveNamedType(NamedType, TypeResolveNoFlags); } } while (Container = Container->GetNextPartialType()); // Validate the generic parameters if any. They need to be validated this // early because other entities could potentially traverse the constraints // after this when they in turn validate constraints, etc. // Check that any specified constraints on type parameters of the container are valid. // Note that it is advantageous to do this task earlier here than later in shadowing // semantics so that we could possibly avoid checking constraint against bad constraint // types. // // Note that it is imperative that this checking be done here in order to break cycles // between type parameter constraints. // ValidateGenericParameters(CurrentContainer()); // Note that it is imperative that this checking be done herein order to break cycles // between type parameter constraints. // BCITER_CHILD_ALL Members(CurrentContainer()); while (BCSYM_NamedRoot *Member = Members.GetNext()) { if (Member->IsProc()) { ValidateGenericParameters(Member->PProc()); } } // Resolve the named types for all the delegates nested within the current container // This is needed because delegate clashes with other members, etc. which show the // signature of clashing member in the error message will need the named types resolved. // // Given that sometimes we treat delegates less as containers and more as methods, this // is necessary. Eg: reporting errors, etc., // Container = CurrentContainer(); do { for (BCSYM_Container *PossibleDelegate = Container->GetNestedTypes(); PossibleDelegate; PossibleDelegate = PossibleDelegate->GetNextNestedType()) { if (!PossibleDelegate->IsDelegate()) { continue; } ResolveAllNamedTypesForContainer(PossibleDelegate, m_CompilationCaches); } } while (Container = Container->GetNextPartialType()); // check structure layout cycles // CheckStructureMemberCycles(); ReTypeEnumMembersIfNecessary(); #if IDE if (CurrentContainer()->GetSourceFile()->GetProject()->GenerateENCableCode()) { GenerateENCTrackingCode(); GenerateENCHiddenRefreshCode(); } #endif IDE // Mark the current container indicating that work to resolve its named types is done SetStatusOfResolveNamedTypes(Done); } #if IDE void Bindable::GenerateENCTrackingCode() { if (!IsClass(CurrentContainer())) { return; } // Do not generate these all the time. // If no accessible withevents or events in class or bases, then // don't generate. BCSYM_Class *Class = CurrentContainer()->PClass(); if (!Class || Class->IsMustInherit()) { return; } Compiler *CompilerInstance = CurrentCompilerInstance(); bool fHasEvents = false; BCSYM_Class *BaseClass = Class; do { BCITER_CHILD iter; iter.Init(BaseClass, false, true); BCSYM_NamedRoot *Named; while ((Named = iter.GetNext()) != NULL) { if ((Named->IsEventDecl() || Named->IsVariable() && Named->PVariable()->IsWithEvents()) && IsTypeAccessible(Named, NULL, Class)) { fHasEvents = true; break; } } if (fHasEvents) { break; } BaseClass = BaseClass->GetCompilerBaseClass(); } while (BaseClass && !BaseClass->IsMustInherit()); if (!fHasEvents) { return; } // Generate field // // Private Shared __ENCList As New ArrayList // or // Private Shared __ENCList As New System.Collections.Generic.List(Of WeakReference) Symbols SymbolAllocator(CompilerInstance, CurrentAllocator(), NULL); const DECLFLAGS CommonFlags = DECLF_ShadowsKeywordUsed | DECLF_Private | DECLF_Hidden | DECLF_Bracketed; Type* TypeOfENCTrackingList = DetermineTypeOfENCTrackingList( &SymbolAllocator); if (!TypeOfENCTrackingList) { VSASSERT(false, "Class libraries does not support WeakRefernece and (ArrayList or List(Of WeakReference))"); return; } // Alloc and fill in the variable BCSYM_Variable *Variable = SymbolAllocator.AllocVariable(false, true); SymbolAllocator.GetVariable( NULL, // no location STRING_CONST(CompilerInstance, ENCTrackingList), // Name STRING_CONST(CompilerInstance, ENCTrackingList), // Emitted Name CommonFlags | DECLF_Shared | DECLF_Dim | DECLF_New, VAR_Member, TypeOfENCTrackingList, NULL, NULL, Variable); Variable->SetIsENCTrackingList(); // Generate method // // Private Shared Sub __ENCIterate() // Alloc and fill in the proc BCSYM_SyntheticMethod *Iterator = SymbolAllocator.AllocSyntheticMethod(false); SymbolAllocator.GetProc( NULL, // no location STRING_CONST(CompilerInstance, ENCTrackingListIterator), // Name STRING_CONST(CompilerInstance, ENCTrackingListIterator), // Emitted Name NULL, NULL, CommonFlags | DECLF_Shared, NULL, // Sub NULL, // No params NULL, NULL, // no lib name NULL, // no alias name SYNTH_IterateENCTrackingList, NULL, // no generic params NULL, Iterator); // Generate method // // Private Shared Sub __ENCAddToList(ByVal Value As Object) BCSYM_Param *ParamFirst = NULL, *LastParam = NULL; SymbolAllocator.GetParam( NULL, // no location STRING_CONST(CompilerInstance, ValueParam), // Name CurrentCompilerHost()->GetFXSymbolProvider()->GetObjectType(), // Type NULL, NULL, &ParamFirst, &LastParam, false); // Not a return type param BCSYM_SyntheticMethod *AddToList = SymbolAllocator.AllocSyntheticMethod(false); SymbolAllocator.GetProc( NULL, // no location STRING_CONST(CompilerInstance, ENCTrackingListAddTo), // Name STRING_CONST(CompilerInstance, ENCTrackingListAddTo), // Emitted Name NULL, NULL, CommonFlags | DECLF_Shared, NULL, // Sub ParamFirst, NULL, NULL, // no lib name NULL, // no alias name SYNTH_AddToENCTrackingList, NULL, // no generic params NULL, AddToList); // Generate method // // Private Sub __ENCUpdateHandlers // Alloc and fill in the proc BCSYM_SyntheticMethod *UpdateHandler = SymbolAllocator.AllocSyntheticMethod(false); SymbolAllocator.GetProc( NULL, // no location STRING_CONST(CompilerInstance, ENCUpdateHandlers), // Name STRING_CONST(CompilerInstance, ENCUpdateHandlers), // Emitted Name NULL, NULL, CommonFlags, NULL, // Sub NULL, // No params NULL, NULL, // no lib name NULL, // no alias name SYNTH_ENCUpdateHandler, NULL, // no generic params NULL, UpdateHandler); // Add the symbols to the the container's bindable members hash Symbols::AddSymbolToHash( Class->GetHash(), Variable, true, // set the parent of this member Class->IsStdModule(), false); // container is not namespace Symbols::AddSymbolToHash( Class->GetHash(), Iterator, true, // set the parent of this member Class->IsStdModule(), false); // container is not namespace Symbols::AddSymbolToHash( Class->GetHash(), AddToList, true, // set the parent of this member Class->IsStdModule(), false); // container is not namespace Symbols::AddSymbolToHash( Class->GetHash(), UpdateHandler, true, // set the parent of this member Class->IsStdModule(), false); // container is not namespace #if IDE // Add these to the list of symbols created in bindable. // This list is used to delete these from their respective hashes during decompilation // from bindable. // SymbolAllocator.GetAliasOfSymbol( Variable, ACCESS_Private, Class->GetBindableSymbolList()); SymbolAllocator.GetAliasOfSymbol( Iterator, ACCESS_Private, Class->GetBindableSymbolList()); SymbolAllocator.GetAliasOfSymbol( AddToList, ACCESS_Private, Class->GetBindableSymbolList()); SymbolAllocator.GetAliasOfSymbol( UpdateHandler, ACCESS_Private, Class->GetBindableSymbolList()); #endif // Make sure a shared constructor is present, else synthesize one // // This is needed so that the shared ArrayList variable can be initialized. // const BuildSharedConstructor = true; if (!Class->GetSharedConstructor(CurrentCompilerInstance())) { // Synthesize one SynthesizeConstructor(BuildSharedConstructor); } } Type* Bindable::DetermineTypeOfENCTrackingList ( Symbols* SymbolAllocator ) { // Get and verify WeakReferenceSymbol. ClassOrRecordType* WeakReferenceSymbol = GetAndVerifyCOMClassSymbol(FX::WeakReferenceType); if (WeakReferenceSymbol == NULL) { return NULL; } // Get and verify List(Of T) ClassOrRecordType* GenericListSymbol = GetAndVerifyCOMClassSymbol(FX::GenericListType); ClassOrRecordType* ArrayListSymbol = GetAndVerifyCOMClassSymbol(FX::ArrayListType); if (GenericListSymbol != NULL && // Always pick GenericList unless we have ArrayList, wich is NOT obsolete and GenericList is obsolete. !(ArrayListSymbol != NULL && !ArrayListSymbol->IsObsolete() && GenericListSymbol->IsObsolete())) { GenericBinding *ListOfWeakReferenceOpenBinding = SynthesizeOpenGenericBinding( GenericListSymbol, *SymbolAllocator); ListOfWeakReferenceOpenBinding->GetArguments()[0] = WeakReferenceSymbol; return SymbolAllocator->GetGenericBinding( false, GenericListSymbol, ListOfWeakReferenceOpenBinding->GetArguments(), ListOfWeakReferenceOpenBinding->GetArgumentCount(), NULL); } else { return GetAndVerifyCOMClassSymbol(FX::ArrayListType); } } ClassOrRecordType* Bindable::GetAndVerifyCOMClassSymbol ( FX::TypeName Symbol ) { ClassOrRecordType* ClassType = NULL; if (CurrentCompilerHost()->GetFXSymbolProvider()->IsTypeAvailable(Symbol)) { Type* Type = CurrentCompilerHost()->GetFXSymbolProvider()->GetType(Symbol); Assume(Type->IsClass(), L"Must be a Class"); ClassType = Type->PClass(); if (ClassType && !IsAccessible(ClassType)) { ClassType = NULL; } } return ClassType; } void Bindable::GenerateENCHiddenRefreshCode ( ) { if (!IsClass(CurrentContainer()) && !IsStructure(CurrentContainer()) && !IsStdModule(CurrentContainer())) { return; } BCSYM_Class *Class = CurrentContainer()->PClass(); if (Class->IsMustInherit() && !Class->IsStdModule()) { return; } Compiler *CompilerInstance = CurrentCompilerInstance(); Symbols SymbolAllocator(CompilerInstance, CurrentAllocator(), NULL); const DECLFLAGS CommonFlags = DECLF_ShadowsKeywordUsed | DECLF_Private | DECLF_Hidden | DECLF_Bracketed; // Generate method // // Private Sub __ENCHiddenRefresh if (!IsStdModule(Class)) { // Alloc and fill in the proc BCSYM_SyntheticMethod *HiddenRefresh = SymbolAllocator.AllocSyntheticMethod(false); SymbolAllocator.GetProc( NULL, // no location STRING_CONST(CompilerInstance, ENCHiddenRefresh), // Name STRING_CONST(CompilerInstance, ENCHiddenRefresh), // Emitted Name NULL, NULL, CommonFlags, NULL, // Sub NULL, // No params NULL, NULL, // no lib name NULL, // no alias name SYNTH_ENCHiddenRefresh, NULL, // no generic params NULL, HiddenRefresh); // Add the symbols to the the container's bindable members hash Symbols::AddSymbolToHash( Class->GetHash(), HiddenRefresh, true, // set the parent of this member Class->IsStdModule(), false); // container is not namespace #if IDE SymbolAllocator.GetAliasOfSymbol( HiddenRefresh, ACCESS_Private, Class->GetBindableSymbolList()); #endif } // // Private Sub __ENCSharedHiddenRefresh // Alloc and fill in the proc BCSYM_SyntheticMethod *SharedHiddenRefresh = SymbolAllocator.AllocSyntheticMethod(false); SymbolAllocator.GetProc( NULL, // no location STRING_CONST(CompilerInstance, ENCSharedHiddenRefresh), // Name STRING_CONST(CompilerInstance, ENCSharedHiddenRefresh), // Emitted Name NULL, NULL, CommonFlags | DECLF_Shared, NULL, // Sub NULL, // No params NULL, NULL, // no lib name NULL, // no alias name SYNTH_ENCSharedHiddenRefresh, NULL, // no generic params NULL, SharedHiddenRefresh); // Add the symbols to the the container's bindable members hash Symbols::AddSymbolToHash( Class->GetHash(), SharedHiddenRefresh, true, // set the parent of this member Class->IsStdModule(), false); // container is not namespace #if IDE SymbolAllocator.GetAliasOfSymbol( SharedHiddenRefresh, ACCESS_Private, Class->GetBindableSymbolList()); #endif } #endif IDE void Bindable::ValidateGenericParameters ( BCSYM_Container *MainContainer ) { // Check that for every partial of this container, for every generic parameter, it has the same // name and constraints. "Same constraints" means set-equality on the set of constraints, as implemented // by CompareConstraints(...). // The rest of the compiler assumes that the "Main Container" for a class (i.e. the one passed as // argument to this function) will be populated by this function with a complete list of classes constraints. // If the spec allowed each partial to declare different constraints, then this function would need // to gather them together or copy them into the Main Container. It would also need a flag by which it // knows that they're generated constraints that should be cleared when the class is decompiled. // // But, things are simpler thanks to Spec$7.11: "Partial types with type parameters can declare constraints // on the type parameters, but the constraints from each partial declaration must match. Thus, constraints // are special in that they are not automatically combined like other modifiers." for (BCSYM_Container *ContainerToCheck = MainContainer; ContainerToCheck; ContainerToCheck = ContainerToCheck->GetNextPartialType()) { bool ConstraintsFound; ValidateGenericParamsAndDirectConstraints(ContainerToCheck->GetFirstGenericParam(), ConstraintsFound); if (ContainerToCheck == MainContainer) continue; BCSYM_Container *SecondaryContainer = ContainerToCheck; // Now check, for each generic param, that its names and constraints match. for (BCSYM_GenericParam *MainParam = MainContainer->GetFirstGenericParam(), *SecondaryParam = SecondaryContainer->GetFirstGenericParam(); MainParam && SecondaryParam; MainParam = MainParam->GetNextParam(), SecondaryParam = SecondaryParam->GetNextParam()) { bool NamesMatch = StringPool::IsEqual(MainParam->GetName(), SecondaryParam->GetName()); if (!NamesMatch) { // Type parameter name '|1' does not match the name '|2' of the corresponding type // parameter defined on one of the other partial types of '|3'. ReportErrorOnSymbol( ERRID_PartialTypeTypeParamNameMismatch3, CurrentErrorLog(SecondaryParam), SecondaryParam, SecondaryParam->GetName(), MainParam->GetName(), SecondaryContainer->GetName()); } bool ConstraintsMatch = CompareConstraints(MainParam, NULL, SecondaryParam, NULL, NULL); if (!ConstraintsMatch) { // Constraints for this type parameter do not match the constraints on the corresponding // type parameter defined on one of the other partial types of '|1'. ReportErrorOnSymbol( ERRID_PartialTypeConstraintMismatch1, CurrentErrorLog(SecondaryParam), SecondaryParam, SecondaryContainer->GetName()); } } } // The following function expects MainContainer to have the complete set of constraints: // ValidateIndirectConstraintsForGenericParams( MainContainer->GetFirstGenericParam(), CurrentErrorLog(MainContainer)); } void Bindable::ValidateGenericParameters ( BCSYM_Proc *Generic ) { if (!Generic->IsGeneric()) { return; } bool ConstraintsFound; ValidateGenericParamsAndDirectConstraints( Generic->GetFirstGenericParam(), ConstraintsFound); ValidateIndirectConstraintsForGenericParams( Generic->GetFirstGenericParam(), CurrentErrorLog(Generic)); // VB Variance Spec $2: no members can be declared variant for (GenericParameter *param=Generic->GetFirstGenericParam(); param; param=param->GetNextParam()) { VSASSERT(param, "unexpected NULL param"); if (param->IsBad()) { continue; } if (param->GetVariance()!=Variance_None) { // Only interface and delegate types can be specified as variant ReportErrorOnSymbol(ERRID_VarianceDisallowedHere, CurrentErrorLog(param), param); param->SetIsBadVariance(); } } } void Bindable::ValidateGenericParamsAndDirectConstraints ( BCSYM_GenericParam *ParameterList, bool &ConstraintsFound ) { ConstraintsFound = false; ValidateNameShadowingForGenericParams(ParameterList); ValidateDirectConstraintsForGenericParams(ParameterList, ConstraintsFound); } void Bindable::ValidateNameShadowingForGenericParams ( BCSYM_GenericParam *ParameterList ) { for (BCSYM_GenericParam *Parameter = ParameterList; Parameter; Parameter = Parameter->GetNextParam()) { BCSYM_NamedRoot *ParameterParent = Parameter->GetParent(); // Skip name clash validation for the partial components of a type in order to avoid redundant errors. // if (ParameterParent->IsClass() && ParameterParent->PClass()->IsPartialType()) { continue; } // Check that this parameter does not have the same name as a parameter of an enclosing generic type. // for (BCSYM_NamedRoot *Parent = ParameterParent->GetParent(); Parent->IsType(); Parent = Parent->GetParent()) { BCSYM_Hash *ParamsHash = Parent->GetGenericParamsHash(); if (ParamsHash && ParamsHash->SimpleBind(Parameter->GetName())) { ReportErrorAtLocation( WRNID_ShadowingGenericParamWithParam1, CurrentErrorLog(Parameter), Parameter->GetLocation(), Parameter->GetName()); } } if (!ParameterParent->IsContainer()) { continue; } // Check that no member of the type has the same name as this parameter. BCSYM_NamedRoot *TypeMember = ParameterParent->PContainer()->GetHash()->SimpleBind(Parameter->GetName()); if (TypeMember) { BCSYM_NamedRoot *SourceOfTypeMember = NULL; if (!IsSynthetic(TypeMember, &SourceOfTypeMember)) { ReportErrorAtLocation( ERRID_ShadowingGenericParamWithMember1, CurrentErrorLog(TypeMember), TypeMember->GetLocation(), TypeMember->GetName()); } else { VSASSERT(SourceOfTypeMember, "How can a synthetic member not have a source member ?"); ReportErrorAtLocation( ERRID_SyntMemberShadowsGenericParam3, CurrentErrorLog(SourceOfTypeMember), SourceOfTypeMember->GetLocation(), StringOfSymbol(CurrentCompilerInstance(), SourceOfTypeMember), SourceOfTypeMember->GetName(), TypeMember->GetName()); } } } } void Bindable::ValidateDirectConstraintsForGenericParams ( BCSYM_GenericParam *ParameterList, bool &ConstraintsFound ) { CompilerHost *CompilerHost = CurrentSourceFile(CurrentContainer())->GetCompilerHost(); bool DisallowRedundancy = true; if (ParameterList) { // Bug VSWhidbey 365493. // // Overriding methods and Private methods that implement interface methods are allowed // to have redundancy and special types in constraints. BCSYM_NamedRoot *Parent = ParameterList->GetParent(); if (Parent->IsProc() && (Parent->PProc()->IsOverridesKeywordUsed() || (Parent->PProc()->GetAccess() == ACCESS_Private && Parent->PProc()->GetImplementsList() != NULL))) { DisallowRedundancy = false; } } for (BCSYM_GenericParam *Parameter = ParameterList; Parameter; Parameter = Parameter->GetNextParam()) { // Validate that the constraints on the parameter are well formed. VSASSERT( !DefinedInMetaData(CurrentContainer()), "Metadata container unexpected!!!"); bool HasReferenceConstraint = false; bool HasValueConstraint = false; BCSYM *ClassConstraintType = NULL; for (BCSYM_GenericConstraint *Constraint = Parameter->GetConstraints(); Constraint; Constraint = Constraint->Next()) { ConstraintsFound = true; // Reset the badness of the constraint. We don't reset this during // decompilation, instead just reset it here. // Constraint->SetIsBadConstraint(false); ValidateDirectConstraint( Constraint, Parameter, CompilerHost, HasReferenceConstraint, HasValueConstraint, ClassConstraintType, DisallowRedundancy); } } } // Check the given direct constraint for clashes with other constraints specified directly on the type // parameter given by "Parameter". // void Bindable::ValidateDirectConstraint ( BCSYM_GenericConstraint *Constraint, BCSYM_GenericParam *Parameter, CompilerHost *CompilerHost, bool &HasReferenceConstraint, bool &HasValueConstraint, BCSYM *&ClassConstraintType, bool DisallowRedundancy ) { VSASSERT(!Constraint->IsBadConstraint(), "Bad constraint unexpected!!!"); // !DirectConstraintCompare: // Constraint clashes being checked among constraints of which atleast one is specified on another type parameter which // has either directly or indirect been supplied as a constraint to the type parameter given by "Parameter". ErrorTable *ErrorLog = CurrentErrorLog(Parameter); if (Constraint->IsReferenceConstraint()) { if (ClassConstraintType && DisallowRedundancy) { ReportErrorAtLocation( ERRID_RefAndClassTypeConstrCombined, ErrorLog, Constraint->GetLocation()); Constraint->SetIsBadConstraint(true); } else { HasReferenceConstraint = true; } } else if (Constraint->IsValueConstraint()) { if (ClassConstraintType && DisallowRedundancy) { ReportErrorAtLocation( ERRID_ValueAndClassTypeConstrCombined, ErrorLog, Constraint->GetLocation()); Constraint->SetIsBadConstraint(true); } else { HasValueConstraint = true; } } if (!Constraint->IsGenericTypeConstraint()) { return; } BCSYM *ConstraintType = Constraint->PGenericTypeConstraint()->GetType(); if (!ConstraintType || ConstraintType->IsBad()) { Constraint->SetIsBadConstraint(true); return; } for(BCSYM_GenericTypeConstraint *ExistingConstraint = Parameter->GetTypeConstraints(); ExistingConstraint != Constraint; ExistingConstraint = ExistingConstraint->Next()) { BCSYM *ExistingConstraintType = ExistingConstraint->GetType(); if (!ExistingConstraintType || ExistingConstraintType->IsBad()) { continue; } if (BCSYM::AreTypesEqual(ConstraintType, ExistingConstraintType)) { if (ErrorLog) { StringBuffer ConstraintBuffer; ReportErrorAtLocation( ERRID_ConstraintAlreadyExists1, ErrorLog, Constraint->GetLocation(), ErrorLog->ExtractErrorName(ConstraintType, CurrentContainer(), ConstraintBuffer)); } Constraint->SetIsBadConstraint(true); break; } } // Continue all the other error checking even if it is a duplicate so that all the // other errors are reported at both the original and the duplicate locations. if (!ValidateConstraintType( ConstraintType, Constraint->GetLocation(), Parameter->GetName(), ErrorLog, CompilerHost, CurrentCompilerInstance(), CurrentAllocator(), HasReferenceConstraint, HasValueConstraint, ClassConstraintType, DisallowRedundancy)) { Constraint->SetIsBadConstraint(true); } } // Returns false if the constraint type is not valid // else returns true. // bool Bindable::ValidateConstraintType ( BCSYM *ConstraintType, Location *ConstraintLocation, // can be NULL _In_opt_z_ STRING *GenericParameterName, // can be NULL ErrorTable *ErrorLog, // can be NULL CompilerHost *CompilerHost, Compiler *CompilerInstance, NorlsAllocator *Allocator, bool &HasReferenceConstraint, bool &HasValueConstraint, BCSYM *&ClassConstraintType, bool DisallowRedundancy ) { bool IsBad = false; if (IsClass(ConstraintType)) { if (HasReferenceConstraint && DisallowRedundancy) { if (ErrorLog) { ReportErrorAtLocation( ERRID_RefAndClassTypeConstrCombined, ErrorLog, ConstraintLocation); } IsBad = true; } else if (HasValueConstraint && DisallowRedundancy) { if (ErrorLog) { ReportErrorAtLocation( ERRID_ValueAndClassTypeConstrCombined, ErrorLog, ConstraintLocation); } IsBad = true; } else { if (DisallowRedundancy) { if (ClassConstraintType) { if (ErrorLog) { ReportErrorAtLocation( ERRID_MultipleClassConstraints1, ErrorLog, ConstraintLocation, GenericParameterName); } IsBad = true; } if (ConstraintType->PClass()->IsNotInheritable()) { if (ErrorLog) { ReportErrorAtLocation( ERRID_ClassConstraintNotInheritable1, ErrorLog, ConstraintLocation, ConstraintType->GetErrorName(CompilerInstance)); } IsBad = true; } else if (ConstraintType == CompilerHost->GetFXSymbolProvider()->GetType(FX::ArrayType) || ConstraintType == CompilerHost->GetFXSymbolProvider()->GetType(FX::DelegateType) || ConstraintType == CompilerHost->GetFXSymbolProvider()->GetType(FX::MultiCastDelegateType) || ConstraintType == CompilerHost->GetFXSymbolProvider()->GetType(FX::EnumType) || ConstraintType == CompilerHost->GetFXSymbolProvider()->GetType(FX::ValueTypeType) || ConstraintType == CompilerHost->GetFXSymbolProvider()->GetType(FX::ObjectType)) { if (ErrorLog) { ReportErrorAtLocation( ERRID_ConstraintIsRestrictedType1, ErrorLog, ConstraintLocation, ConstraintType->GetErrorName(CompilerInstance)); } IsBad = true; } else if (!ClassConstraintType) { ClassConstraintType = ConstraintType; } } else if (!ClassConstraintType) // && Disallow redundancy { ClassConstraintType = ConstraintType; } } } else if (ConstraintType->IsGenericParam()) { if (DisallowRedundancy && ConstraintType->PGenericParam()->HasValueConstraint()) { if (ErrorLog) { ReportErrorAtLocation( ERRID_TypeParamWithStructConstAsConst, ErrorLog, ConstraintLocation); } IsBad = true; } } else if (!IsInterface(ConstraintType)) { if (DisallowRedundancy) { if (ErrorLog) { ReportErrorAtLocation( ERRID_ConstNotClassInterfaceOrTypeParam1, ErrorLog, ConstraintLocation, ConstraintType->GetErrorName(CompilerInstance)); } IsBad = true; } else if (!ClassConstraintType) // && Disallow redundancy { ClassConstraintType = ConstraintType; } } return !IsBad; } bool Bindable::IsValidConstraintType ( BCSYM *ConstraintType, CompilerHost *CompilerHost, Compiler *CompilerInstance, NorlsAllocator *Allocator, bool DisallowRedundancy ) { bool HasReferenceConstraint = false; bool HasValueConstraint = false; BCSYM *ClassConstraintType = NULL; return ValidateConstraintType( ConstraintType, NULL, NULL, NULL, CompilerHost, CompilerInstance, Allocator, HasReferenceConstraint, HasValueConstraint, ClassConstraintType, DisallowRedundancy); } void Bindable::ValidateIndirectConstraintsForGenericParams ( BCSYM_GenericParam *ParameterList, ErrorTable *ErrorLog ) { if (!ParameterList) { return; } unsigned int Count = 0; for (BCSYM_GenericParam *Parameter = ParameterList; Parameter; Parameter = Parameter->GetNextParam()) { Count++; } const unsigned int MaxParams = 12; BCSYM_GenericTypeConstraint *CurrentConstraintsBuffer[MaxParams]; bool ParametersCheckedBuffer[MaxParams]; BCSYM_GenericTypeConstraint **CurrentConstraints = CurrentConstraintsBuffer; bool *ParametersChecked = ParametersCheckedBuffer; if (Count > MaxParams) { NorlsAllocator TempAllocator(NORLSLOC); if (!VBMath::TryMultiply(sizeof(BCSYM_GenericTypeConstraint *),Count) || !VBMath::TryMultiply(sizeof(bool),Count)) { return; // Overflow } CurrentConstraints = (BCSYM_GenericTypeConstraint **)TempAllocator.Alloc(Count * sizeof(BCSYM_GenericTypeConstraint *)); ParametersChecked = (bool *)TempAllocator.Alloc(Count * sizeof(bool)); CheckAllGenericParamsForConstraintCycles( ParameterList, CurrentConstraints, ParametersChecked, ErrorLog); // Re-init the ParametersChecked flags so that they can be used during the // constraint clash checking to avoid redundant errors i.e. in orer to avoid // comparing constraints with constraints of other type parameters that could // be marked bad when they inturn are checked for clashes. This will also avoid // conflicting errors by avoiding comparisons with conflicting constraints on // type parameters. // // Note that ParametersChecked could indeed be used as ParametersNotChecked and // thus reinitialization avoided, but this reinit is cheap considering the number // of type parameters that are usually present and also this is a better design // than depending on implementation details of CheckAllGenericParamsForConstraint- // -Cycles. // memset(ParametersChecked, 0, Count * sizeof(ParametersChecked[0])); CheckAllGenericParamsForIndirectConstraintClashes( ParameterList, ParametersChecked, ErrorLog); } else { memset(CurrentConstraintsBuffer, 0, sizeof(CurrentConstraintsBuffer)); memset(ParametersCheckedBuffer, 0, sizeof(ParametersCheckedBuffer)); CheckAllGenericParamsForConstraintCycles( ParameterList, CurrentConstraints, ParametersChecked, ErrorLog); // Re-init the ParametersChecked flags so that they can be used during the // constraint clash checking to avoid redundant errors i.e. in orer to avoid // comparing constraints with constraints of other type parameters that could // be marked bad when they inturn are checked for clashes. This will also avoid // conflicting errors by avoiding comparisons with conflicting constraints on // type parameters. // // Note that ParametersChecked could indeed be used as ParametersNotChecked and // thus reinitialization avoided, but this reinit is cheap considering the number // of type parameters that are usually present and also this is a better design // than depending on implementation details of CheckAllGenericParamsForConstraint- // -Cycles. // memset(ParametersCheckedBuffer, 0, sizeof(ParametersCheckedBuffer)); CheckAllGenericParamsForIndirectConstraintClashes( ParameterList, ParametersChecked, ErrorLog); } } void Bindable::CheckAllGenericParamsForConstraintCycles ( BCSYM_GenericParam *ParameterList, BCSYM_GenericTypeConstraint *CurrentConstraints[], bool ParametersChecked[], ErrorTable *ErrorLog ) { // Note that we only prevent T1 As T2, T2 As T1 kind of circular dependencies // and do not prevent T1 As C1(Of T2), T2 As T1 kind of circular dependencies. for (BCSYM_GenericParam *Parameter = ParameterList; Parameter; Parameter = Parameter->GetNextParam()) { if (!ParametersChecked[Parameter->GetPosition()]) { CheckGenericParamForConstraintCycles( Parameter, CurrentConstraints, ParametersChecked, ErrorLog); } } } void Bindable::CheckGenericParamForConstraintCycles ( BCSYM_GenericParam *Parameter, BCSYM_GenericTypeConstraint *CurrentConstraints[], bool ParametersChecked[], ErrorTable *ErrorLog ) { // Note that we only prevent T1 As T2, T2 As T1 kind of circular dependencies // and do not prevent T1 As C1(Of T2), T2 As T1 kind of circular dependencies. unsigned int ParamIndex = Parameter->GetPosition(); if (CurrentConstraints[ParamIndex]) { // Cycle detected ReportConstraintCycleError(ErrorLog, Parameter, CurrentConstraints, ParamIndex); CurrentConstraints[ParamIndex]->SetIsBadConstraint(true); return; } for (BCSYM_GenericTypeConstraint *Constraint = Parameter->GetTypeConstraints(); Constraint; Constraint = Constraint->Next()) { if (Constraint->IsBadConstraint() || !Constraint->GetType()->IsGenericParam()) { continue; } // Type param from parent cannot cause cycles // if (Constraint->GetType()->PGenericParam()->GetParent() == Parameter->GetParent()) { CurrentConstraints[ParamIndex] = Constraint; CheckGenericParamForConstraintCycles( Constraint->GetType()->PGenericParam(), CurrentConstraints, ParametersChecked, ErrorLog); } } CurrentConstraints[ParamIndex] = NULL; ParametersChecked[ParamIndex] = true; #if DEBUG Parameter->SetConstraintCycleCheckingDone(true); #endif } void Bindable::ReportConstraintCycleError ( ErrorTable *ErrorLog, BCSYM_GenericParam *Parameter, BCSYM_GenericTypeConstraint *ConstraintsInCycle[], unsigned int CycleInitiatingConstraintIndex ) { StringBuffer CycleDesc; BCSYM_GenericParam *PrevParam = Parameter; unsigned int Current = CycleInitiatingConstraintIndex; do { VSASSERT(ConstraintsInCycle[Current] && ConstraintsInCycle[Current]->GetType()->IsGenericParam(), "Unexpected constraint type in constraint cycle!!!!"); BCSYM_GenericParam *CurrentParam = ConstraintsInCycle[Current]->GetType()->PGenericParam(); ResLoadStringRepl( ERRID_ConstraintCycleLink2, &CycleDesc, PrevParam->GetName(), CurrentParam->GetName()); PrevParam = CurrentParam; Current = CurrentParam->GetPosition(); } while (Current != CycleInitiatingConstraintIndex); ReportErrorAtLocation( ERRID_ConstraintCycle2, ErrorLog, ConstraintsInCycle[CycleInitiatingConstraintIndex]->GetLocation(), Parameter->GetName(), CycleDesc.GetString()); } void Bindable::CheckAllGenericParamsForIndirectConstraintClashes ( BCSYM_GenericParam *ParameterList, bool ParametersChecked[], ErrorTable *ErrorLog ) { for (BCSYM_GenericParam *Parameter = ParameterList; Parameter; Parameter = Parameter->GetNextParam()) { CheckGenericParamForIndirectConstraintClash( Parameter, ParametersChecked, ErrorLog); } } void Bindable::CheckGenericParamForIndirectConstraintClash ( BCSYM_GenericParam *Parameter, bool ParametersChecked[], ErrorTable *ErrorLog ) { // Definitely bad constraint combinations: // struct and class // struct and a class type constraint // two unrelated class type constraints unsigned int ParamIndex = Parameter->GetPosition(); // If this type parameter has already been checked, then return immediately // if (ParametersChecked[ParamIndex]) { return; } ValidateIndirectConstraints(Parameter, ParametersChecked, ErrorLog); ParametersChecked[ParamIndex] = true; } void Bindable::ValidateIndirectConstraints ( BCSYM_GenericParam *Parameter, bool ParametersChecked[], ErrorTable *ErrorLog ) { BCITER_Constraints Iter1(Parameter, true, CurrentCompilerInstance()); BCITER_Constraints Iter2(Parameter, true, CurrentCompilerInstance()); while (BCSYM_GenericConstraint *Constraint = Iter1.Next()) { VSASSERT(!Constraint->IsBadConstraint(), "Bad constraint unexpected!!!"); if (Iter1.CurrentGenericParamContext() != Parameter) { // For constraints of type parameter type, first validate the constraints of the type // parameter type and then only validate its constraints against the constraints of // the current parameter. This is required to avoid conflicting errors. // BCSYM_GenericParam *GenericParamTypeConstraint = Iter1.CurrentGenericParamContext(); BCSYM_NamedRoot *ParentOfGenericParam = GenericParamTypeConstraint->GetParent(); if (ParentOfGenericParam == CurrentContainer()) { CheckGenericParamForIndirectConstraintClash( GenericParamTypeConstraint, ParametersChecked, ErrorLog); } else if (ParentOfGenericParam->IsContainer()) { ResolveAllNamedTypesForContainer(ParentOfGenericParam->PContainer(), m_CompilationCaches); } } Iter2.Reset(); while (BCSYM_GenericConstraint *PossiblyClashingConstraint = Iter2.Next()) { VSASSERT(!PossiblyClashingConstraint->IsBadConstraint(), "Bad constraint unexpected!!!"); // Validating direct constraints already completed previously, so skip. // if (Iter1.FirstGenericParamContext() == Parameter && Iter2.FirstGenericParamContext() == Parameter) { // But for overriding members which can have multiple class constraints, need // to wait till here to check for conflicts between the direct class constraints. // // The reason this check needs to be delayed till here is to avoid walking the // constraints of the type parameter before cycle checking has been completed. if (ConstraintsConflict(Constraint, PossiblyClashingConstraint)) { if (ErrorLog) { StringBuffer ConstraintString1; StringBuffer ConstraintString2; ReportErrorAtLocation( ERRID_ConflictingDirectConstraints3, ErrorLog, PossiblyClashingConstraint->GetLocation(), GetErrorNameForConstraint(PossiblyClashingConstraint, &ConstraintString1), GetErrorNameForConstraint(Constraint, &ConstraintString2), Parameter->GetName()); } PossiblyClashingConstraint->SetIsBadConstraint(true); } continue; } // Checking the indirect constraint with all the constraints before the type parameter // constraint through which the indirect constraint is seen if (Iter1.FirstGenericParamContext() == Iter2.FirstGenericParamContext()) { break; } if (ConstraintsConflict(Constraint, PossiblyClashingConstraint)) { // Indirect constraint '|1' obtained from the type parameter constraint '|2' conflicts // with the indirect constraint '|3' obtained from the type parameter constraint '|4'. if (Iter1.FirstGenericParamContext() == Parameter) { if (ErrorLog) { StringBuffer Buffer1; StringBuffer Buffer2; ReportErrorAtLocation( ERRID_ConstraintClashDirectIndirect3, ErrorLog, Constraint->GetLocation(), GetErrorNameForConstraint(Constraint, &Buffer1), GetErrorNameForConstraint(PossiblyClashingConstraint, &Buffer2), Iter2.FirstGenericParamContext()->GetName()); } Constraint->SetIsBadConstraint(true); } else if (Iter2.FirstGenericParamContext() == Parameter) { if (ErrorLog) { StringBuffer Buffer1; StringBuffer Buffer2; ReportErrorAtLocation( ERRID_ConstraintClashIndirectDirect3, ErrorLog, Iter1.FirstGenericParamConstraintContext()->GetLocation(), GetErrorNameForConstraint(Constraint, &Buffer1), Iter1.FirstGenericParamContext()->GetName(), GetErrorNameForConstraint(PossiblyClashingConstraint, &Buffer2)); } Iter1.FirstGenericParamConstraintContext()->SetIsBadConstraint(true); } else { if (ErrorLog) { StringBuffer Buffer1; StringBuffer Buffer2; ReportErrorAtLocation( ERRID_ConstraintClashIndirectIndirect4, ErrorLog, Iter1.FirstGenericParamConstraintContext()->GetLocation(), GetErrorNameForConstraint(Constraint, &Buffer1), Iter1.FirstGenericParamContext()->GetName(), GetErrorNameForConstraint(PossiblyClashingConstraint, &Buffer2), Iter2.FirstGenericParamContext()->GetName()); } Iter1.FirstGenericParamConstraintContext()->SetIsBadConstraint(true); } break; } } } } bool Bindable::ConstraintsConflict ( BCSYM_GenericConstraint *Constraint1, BCSYM_GenericConstraint *Constraint2 ) { VSASSERT(!Constraint1->IsBadConstraint(), "Bad constraint unexpected!!!"); VSASSERT(!Constraint2->IsBadConstraint(), "Bad constraint unexpected!!!"); // Interface constraints do not clash with any other constraints. // Bug VSWhidbey 449053. if ((Constraint1->IsGenericTypeConstraint() && IsInterface(Constraint1->PGenericTypeConstraint()->GetType())) || (Constraint2->IsGenericTypeConstraint() && IsInterface(Constraint2->PGenericTypeConstraint()->GetType()))) { return false; } Symbols SymbolFactory(CurrentCompilerInstance(), CurrentAllocator(), NULL); // "structure" constraint and non-value type conflict. BCSYM *PossibleValueType = NULL; if (Constraint1->IsValueConstraint()) { PossibleValueType = Constraint2->IsGenericTypeConstraint() ? Constraint2->PGenericTypeConstraint()->GetType() : NULL; } else if (Constraint2->IsValueConstraint()) { PossibleValueType = Constraint1->IsGenericTypeConstraint() ? Constraint1->PGenericTypeConstraint()->GetType() : NULL; } if (PossibleValueType && !ValidateValueConstraintForType( PossibleValueType, NULL, NULL, NULL, NULL, CurrentCompilerHost(), CurrentCompilerInstance(), false) && !TypeHelpers::IsOrInheritsFrom( CurrentCompilerHost()->GetFXSymbolProvider()->GetType(FX::EnumType), PossibleValueType, SymbolFactory, true, NULL, false, NULL, NULL)) { return true; } // "class" constraint and value type conflict. BCSYM *PossibleReferenceType = NULL; if (Constraint1->IsReferenceConstraint()) { PossibleReferenceType = Constraint2->IsGenericTypeConstraint() ? Constraint2->PGenericTypeConstraint()->GetType() : NULL; } else if (Constraint2->IsReferenceConstraint()) { PossibleReferenceType = Constraint1->IsGenericTypeConstraint() ? Constraint1->PGenericTypeConstraint()->GetType() : NULL; } if (PossibleReferenceType && !ValidateReferenceConstraintForType( PossibleReferenceType, NULL, NULL, NULL, NULL)) { return true; } // Note that Derived and Base classes do not clash. The base class is just redundant and // we do allow redundancy for indirect constraints. if (Constraint1->IsGenericTypeConstraint() && Constraint2->IsGenericTypeConstraint() && !ValidateTypeConstraintForType( Constraint1->PGenericTypeConstraint()->GetType(), Constraint2->PGenericTypeConstraint()->GetType(), CurrentCompilerHost(), &SymbolFactory) && !ValidateTypeConstraintForType( Constraint2->PGenericTypeConstraint()->GetType(), Constraint1->PGenericTypeConstraint()->GetType(), CurrentCompilerHost(), &SymbolFactory)) { return true; } return false; } WCHAR * Bindable::GetErrorNameForConstraint ( BCSYM_GenericConstraint *Constraint, StringBuffer *Buffer ) { WCHAR *Result = NULL; if (Constraint->IsReferenceConstraint()) { Result = CurrentCompilerInstance()->TokenToString(tkCLASS); } else if (Constraint->IsValueConstraint()) { Result = CurrentCompilerInstance()->TokenToString(tkSTRUCTURE); } else if (Constraint->IsNewConstraint()) { Result = CurrentCompilerInstance()->TokenToString(tkNEW); } else { VSASSERT(Constraint->IsGenericTypeConstraint(), "Unexpected constraint kind!!!"); BCSYM *Type = Constraint->PGenericTypeConstraint()->GetType(); if (Type->IsNamedType()) { Result = GetQualifiedErrorName(Type); } else { Type->GetBasicRep(CurrentCompilerInstance(), CurrentContainer(), Buffer); Result = Buffer->GetString(); } } return Result; } void Bindable::CheckGenericConstraintsForContainer ( ) { Symbols SymbolFactory( CurrentCompilerInstance(), CurrentAllocator(), NULL, CurrentGenericBindingCache()); BCSYM_Container *Container = CurrentContainer(); // Validate the argument types in all named types in the container. // Even in the case of partial types, only their main type is expected here // VSASSERT(!Container->IsPartialTypeAndHasMainType(), "Partial type unexpected!!!"); for (BCSYM_Container *CurrentContainer = Container; CurrentContainer; CurrentContainer = CurrentContainer->GetNextPartialType()) { for (BCSYM_NamedType *NamedType = CurrentContainer->GetNamedTypesList(); NamedType; NamedType = NamedType->GetNext()) { CheckGenericConstraints( NamedType, CurrentErrorLog(NamedType), CurrentCompilerHost(), CurrentCompilerInstance(), &SymbolFactory, m_CompilationCaches); // Check any member variable or Auto Property with "As New" to ensure that the type of the variable can be instantiated. // // Need to delay DimAsNewSemantics for member variables because the constraint type for type params in the parent // will not yet be bound nor cycle checking done during ResolveAllNamedTypes. // if (NamedType->GetSymbol() && NamedType->GetContext() && ( ( NamedType->GetContext()->IsProperty() && NamedType->GetContext()->PProperty()->IsAutoProperty() && NamedType->GetContext()->PProperty()->IsNewAutoProperty()) || ( NamedType->GetContext()->IsVariable() && NamedType->GetContext()->PVariable()->IsNew() ) ) && NamedType->GetContext()->PMember()->GetRawType() == NamedType) { ERRID ErrId = NOERROR; DimAsNewSemantics( NamedType->GetSymbol(), ErrId); if (ErrId != NOERROR) { // Log error discovered above // Build the qualified name. StringBuffer QualifiedName; unsigned CountOfNames = NamedType->GetNameCount(); for(unsigned i = 0; i < CountOfNames; i++) { if (NamedType->GetNameArray()[i]) { QualifiedName.AppendString(NamedType->GetNameArray()[i]); if (i != CountOfNames - 1) { QualifiedName.AppendChar( L'.'); } } } ReportErrorOnSymbol( ErrId, CurrentErrorLog(NamedType), NamedType, QualifiedName.GetString()); // not used by all errids that come through here // Invalidate the namedtype to prevent any other downstream errors. NamedType->SetSymbol(Symbols::GetGenericBadNamedRoot()); } } } } if (IsClass(Container)) { CheckGenericConstraints( Container->PClass()->GetRawBase(), Container->PClass()->GetRawBase()->IsNamedType() ? CurrentErrorLog(Container->PClass()->GetRawBase()->PNamedType()) : CurrentErrorLog(Container), CurrentCompilerHost(), CurrentCompilerInstance(), &SymbolFactory, m_CompilationCaches, true); // check constraints for the bindings among the type arguments too } else if (IsInterface(Container)) { for (BCSYM_Implements *BaseImplements = Container->PInterface()->GetFirstImplements(); BaseImplements; BaseImplements = BaseImplements->GetNext()) { if (BaseImplements->IsBad()) { continue; } CheckGenericConstraints( BaseImplements->GetRawRoot(), CurrentErrorLog(Container), CurrentCompilerHost(), CurrentCompilerInstance(), &SymbolFactory, m_CompilationCaches, true); // check constraints for the bindings among the type arguments too } } else if (IsNamespace(Container)) { for(ImportedTarget *CurrentImport = Container->PNamespace()->GetImports(); CurrentImport; CurrentImport = CurrentImport->m_pNext) { if (CurrentImport->m_hasError) { continue; } if (CurrentImport->m_pTarget && CurrentImport->m_pTarget->IsGenericTypeBinding()) { CheckGenericConstraintsForImportsTarget( CurrentImport, CurrentErrorLog(Container), CurrentCompilerHost(), CurrentCompilerInstance(), &SymbolFactory, m_CompilationCaches); } } } } void Bindable::CheckStructureMemberCycles() { BCSYM_Container *Container = CurrentContainer(); if (!IsStructure(Container)) { return; } do { for(BCSYM_NamedType *NamedType = Container->GetNamedTypesList(); NamedType; NamedType = NamedType->GetNext()) { BCSYM_Container *StructType; BCSYM_GenericTypeBinding *StructTypeBindingContext; StructType = IsTypeStructAndIsTypeOfAValidInstanceMemberVariable( NamedType, StructTypeBindingContext); if (!StructType) { continue; } ResolveAllNamedTypesForContainer(StructType, m_CompilationCaches); // For generics, cycles could possibly be created // after substitution. In order to detect such cases, // we need to consider the possiblity even if // one generic binding exists. // if (StructTypeBindingContext) { SetStructureMemberCycleDetected(true); // NOTE: do not break out here!!! We need to complete // resolve named types for all the structs that are // used as types of instance member variables in this // structure. So continue with the loop. // } } } while (Container = Container->GetNextPartialType()); return; } BCSYM_Class * Bindable::IsTypeStructAndIsTypeOfAValidInstanceMemberVariable ( BCSYM_NamedType *NamedType, BCSYM_GenericTypeBinding *&BindingContextForMemberVariableType ) { VSASSERT( NamedType->DigThroughNamedType(), "Unresolved named type unexpected!!!"); BindingContextForMemberVariableType = NULL; if (NamedType->DigThroughNamedType()->IsBad()) { return NULL; } BCSYM_NamedRoot *ContextOfNamedType = NamedType->GetContext(); if (!ContextOfNamedType) { return NULL; } // Only Instance Member variables having structures type could possibly cause embedded // type cycles. if (ContextOfNamedType->IsBad() || !(ContextOfNamedType->IsVariable() || (ContextOfNamedType->IsProperty() && ContextOfNamedType->PProperty()->IsAutoProperty())) || ContextOfNamedType->PMember()->IsShared()) { return NULL; } // Note: Array variables don't count because although the Array element type might // be of this type, the Array itself is a different type. // BCSYM *TypeOfMemberVar = ContextOfNamedType->PMember()->GetType()->DigThroughAlias(); VSASSERT( TypeOfMemberVar, "How can a named type not be bound yet at least to a bad type ?"); if (!IsStructure(TypeOfMemberVar)) { return NULL; } VSASSERT(NamedType->GetSymbol(), "Named type should already have been bound!!!"); BCSYM *PossibleStructType = NamedType->GetSymbol(); if (!IsStructure(PossibleStructType)) { return NULL; } if (PossibleStructType->IsGenericTypeBinding()) { BindingContextForMemberVariableType = PossibleStructType->PGenericTypeBinding(); } return PossibleStructType->PClass(); } void Bindable::DetectStructMemberCyclesForContainer() { VSASSERT(GetStatusOfDetectStructMemberCycles() == NotStarted, "Reentrancy during structure member cycle unexpected!!!"); // Mark the current container indicating that structure member cycle detection work is in progress SetStatusOfDetectStructMemberCycles(InProgress); BCSYM_Container *Container = CurrentContainer(); if (!IsStructure(Container)) { // Mark the current container indicating that structure member cycle detection work is done SetStatusOfDetectStructMemberCycles(Done); return; } if (StructureMemberCycleDetected() && !Container->PClass()->IsStructCycleCheckingDone()) { NorlsAllocator TempAllocator(NORLSLOC); Symbols SymbolAllocator( CurrentCompilerInstance(), &TempAllocator, NULL, NULL); BCSYM_GenericTypeBinding *OpenBindingForStructure = IsGenericOrHasGenericParent(Container) ? SynthesizeOpenGenericBinding(Container, SymbolAllocator)->PGenericTypeBinding() : NULL; StructCycleNode *CycleCausingNode = NULL; DetectStructureMemberCycle( Container->PClass(), OpenBindingForStructure, OpenBindingForStructure, NULL, &CycleCausingNode, &SymbolAllocator); VSASSERT(Container->PClass()->IsStructCycleCheckingDone(), "Exiting struct layout cycle detection unexpectedly!!!"); VSASSERT(CycleCausingNode == NULL, "Inconsistency in struct cycle detection!!!"); } // It is imperative that the cycle info be cleared, else future compiles or cycle detection // for other structures during this compilation cycle could be very adversely affected. // VSASSERT(Container->PClass()->GetStructCycleInfo() == NULL, "Non-NULL struct info unexpected after cycle detection completed!!!"); // Mark the current container indicating that structure member cycle detection work is done SetStatusOfDetectStructMemberCycles(Done); } void Bindable::DetectStructureMemberCycle ( BCSYM_Class *Structure, BCSYM_GenericTypeBinding *StructureBindingContext, BCSYM_GenericTypeBinding *OpenBindingForStructure, StructCycleNode *PrevCycleNode, StructCycleNode **CycleCausingNode, Symbols *SymbolAllocator ) { StructCycleNode NewNode; bool CurrentBindingIsOpenBinding = false; if (StructureBindingContext == OpenBindingForStructure || // Need to match up null bindings for non-generic structs !StructureBindingContext || // Treat any open types in bad metadata as their equivalent // open bindings BCSYM::AreTypesEqual(StructureBindingContext, OpenBindingForStructure)) { if (Structure->GetStructCycleInfo()) { ReportStructureMemberCycleError(Structure->GetStructCycleInfo(), SymbolAllocator); *CycleCausingNode = Structure->GetStructCycleInfo(); return; } // Only set this when the type being checked is the open binding or a non-generic to // avoid walking the cycle nodes list in order to check for a cycle. // Structure->SetStructCycleInfo(&NewNode); CurrentBindingIsOpenBinding = true; } VSASSERT(*CycleCausingNode == NULL, "Inconsistency in struct cycle detection!!!"); NewNode.m_Struct = StructureBindingContext ? (BCSYM *)StructureBindingContext : Structure; NewNode.m_Field = NULL; NewNode.m_Next = NULL; if (PrevCycleNode) { PrevCycleNode->m_Next = &NewNode; } bool StructureDefinedInMetaData = DefinedInMetaData(Structure); BCITER_CHILD StructMembers(Structure); while (BCSYM_NamedRoot *Member = StructMembers.GetNext()) { VSASSERT(*CycleCausingNode == NULL, "Inconsistency in struct cycle detection!!!"); // Bug VSWhidbey 196029 // Ignore bad members only if they are in source. Need to consider bad // metadata members too because the metadata structure might actually // have a private field that could cause a cycle, but which is marked // bad for reasons like member clash. // // Ignore the synthetic withevents field - see bug VSWhidbey 208063 // if ((Member->IsBad() && // Bug VSWhidbey 196029 - see explanation above. // !StructureDefinedInMetaData) || !Member->IsVariable() || Member->PVariable()->IsShared() || Member->PVariable()->FieldCausesStructCycle() || Member->PVariable()->CreatedByWithEventsDecl()) { continue; } BCSYM *Type = Member->PVariable()->GetType(); VSASSERT(Type, "NULL type unexpected for member variable!!!"); VSASSERT(!Member->IsBad() || StructureDefinedInMetaData, "Member state changed to bad unexpectedly!!!"); BCSYM *TypeAfterReplacement = ReplaceGenericParametersWithArguments( Type, StructureBindingContext, *SymbolAllocator); VSASSERT(TypeAfterReplacement, "NULL substituted type unexpected for member variable!!!"); if (TypeAfterReplacement->IsBad() || !IsStructure(TypeAfterReplacement)) { continue; } BCSYM_Class *VariableType = TypeAfterReplacement->PClass(); BCSYM_GenericTypeBinding *VariableTypeBindingContext = TypeAfterReplacement->IsGenericTypeBinding() ? TypeAfterReplacement->PGenericTypeBinding() : NULL; // Optimization: Non-generic metadata structures cannot cause cycles involving source types. // if (DefinedInMetaData(VariableType) && !IsGenericOrHasGenericParent(VariableType)) { continue; } // Fill a new cycle info node // NewNode.m_Field = Member->PVariable(); BCSYM_GenericTypeBinding *OpenBindingForVariableType = IsGenericOrHasGenericParent(VariableType) ? OpenBindingForVariableType = SynthesizeOpenGenericBinding( VariableType, *SymbolAllocator)->PGenericTypeBinding() : NULL; // Use the open binding to detect any cycle on this variable's struct type // irrespective of any binding. This will also help catch infinite type // expansion issues. // if (!VariableType->IsStructCycleCheckingDone()) { DetectStructureMemberCycle( VariableType, OpenBindingForVariableType, OpenBindingForVariableType, &NewNode, CycleCausingNode, SymbolAllocator); // Cycle already reported on this field, so skip further checking. // So in order to skip further checking through that field, need to exit here. // If the rest of the cycle checking through this field is not skipped, this // could lead to infinite bindings and stack overflow. // if (*CycleCausingNode == &NewNode) { *CycleCausingNode = NULL; continue; } // A cycle error has already been reported on a field further down the stack. // So in order to skip further checking through that field, need to exit here. // If the rest of the cycle checking through this field is not skipped, this // could lead to infinite bindings and stack overflow. See Bug VSWhidbey 263032. // if (*CycleCausingNode != NULL) { break; } VSASSERT(Member->PVariable()->FieldCausesStructCycle() == false, "Should not continue further with struct cycle causing field!!!"); } // Now continue looking for any cycles that might result due to substitution, // but do so only for non-open bindings because open bindings have already // been handled above // if (VariableTypeBindingContext && !BCSYM::AreTypesEqual(VariableTypeBindingContext, OpenBindingForVariableType)) { DetectStructureMemberCycle( VariableType, VariableTypeBindingContext, OpenBindingForVariableType, &NewNode, CycleCausingNode, SymbolAllocator); // Cycle already reported on this field, so skip further checking. // So in order to skip further checking through that field, need to exit here. // If the rest of the cycle checking through this field is not skipped, this // could lead to infinite bindings and stack overflow. // if (*CycleCausingNode == &NewNode) { *CycleCausingNode = NULL; continue; } // A cycle error has already been reported on a field further down the stack. // So in order to skip further checking through that field, need to exit here. // If the rest of the cycle checking through this field is not skipped, this // could lead to infinite bindings and stack overflow. See Bug VSWhidbey 263032. // if (*CycleCausingNode != NULL) { break; } VSASSERT(Member->PVariable()->FieldCausesStructCycle() == false, "Should not continue further with struct cycle causing field!!!"); } } // Remove the current node from the list of cycle nodes // if (PrevCycleNode) { PrevCycleNode->m_Next = NULL; } if (CurrentBindingIsOpenBinding) { // A common way to indicate cycle checking completion for both metadata and source structures // and the only way to indicate this for metadata container. // Structure->SetIsStructCycleCheckingDone(true); // Clear out the cycle info in the structure that was used during cycle detection // Structure->SetStructCycleInfo(NULL); } return; } void Bindable::ReportStructureMemberCycleError ( StructCycleNode *CycleInitiatingNode, Symbols *SymbolAllocator ) { VSASSERT(CycleInitiatingNode, "Unexpected cycle reporting!!!"); VSASSERT(CycleInitiatingNode->m_Field, "NULL field unexpected in struct cycle!!!"); VSASSERT(CycleInitiatingNode->m_Struct, "NULL struct unexpected in struct cycle!!!"); BCSYM_Variable *CycleInitiatingField = CycleInitiatingNode->m_Field; VSASSERT(CycleInitiatingField->FieldCausesStructCycle() == false, "How can a field already reported in a struct cycle be involved in a cycle again ?"); BCSYM *CycleInitiatingStruct = CycleInitiatingNode->m_Struct; VSASSERT(IsStructure(CycleInitiatingStruct), "Non-structure unexpected in struct member cycle!!!"); if (DefinedInMetaData(CycleInitiatingStruct->PClass())) { // Ignore bad metadata // // Why no error ? Users will eventually get a typeload exception. // Treat it as a few other bad metadata error where the user // gets type load exception. // // Also Perf-wise would be bad to validate metadata structures before, // hand, we never did this before nor should we start now. // CycleInitiatingField->SetFieldCausesStructCycle(true); return; } Bindable *BindableInstanceForStructure = CycleInitiatingStruct->PClass()->GetBindableInstanceIfAlreadyExists(); if (!BindableInstanceForStructure) { VSFAIL("How can bindable not already be created for the structure with the cycle error ?"); return; } VSASSERT( !CycleInitiatingStruct->PClass()->IsBindingDone() && BindableInstanceForStructure->GetStatusOfDetectStructMemberCycles() != Done, "How can we have a cycle if the structure causing the cycle is beyond the process of cycle detection ?"); StringBuffer CycleDesc; BCSYM *ContainingStructure = CycleInitiatingNode->m_Struct; for(StructCycleNode *CurrentNode = CycleInitiatingNode; CurrentNode; CurrentNode = CurrentNode->m_Next) { BCSYM_Variable *MemberVar = CurrentNode->m_Field; VSASSERT(MemberVar, "NULL Member var unexpected in cycle!!!"); VSASSERT(MemberVar->GetContainer() == ContainingStructure->PClass(), "Inconsistency during struct member cycle error reporting!!!"); VSASSERT(MemberVar->FieldCausesStructCycle() == false, "How can a field already reported in a struct cycle be involved in a cycle again ?"); BCSYM *FieldType = MemberVar->GetType(); BCSYM *ContainedStructure = ContainingStructure->IsGenericBinding() ? ReplaceGenericParametersWithArguments( FieldType, ContainingStructure->PGenericBinding(), *SymbolAllocator) : FieldType; VSASSERT(ContainingStructure && ContainedStructure, "NULL structures unexpected in struct cycle!!!"); VSASSERT(IsStructure(ContainingStructure) && IsStructure(ContainedStructure), "How can a non-structure be involved in a structure embedded member cycle ?"); ResLoadStringRepl( ERRID_RecordEmbeds2, &CycleDesc, BindableInstanceForStructure->GetQualifiedErrorName(ContainingStructure), BindableInstanceForStructure->GetQualifiedErrorName(ContainedStructure), MemberVar->GetName()); ContainingStructure = ContainedStructure; } // Report the error specifying the error node at which the cycle was detected VSASSERT(CycleInitiatingField->GetRawType()->IsNamedType(), "Non-named type unexpected in structure cycle!!!"); BindableInstanceForStructure->ReportErrorOnSymbol( ERRID_RecordCycle2, BindableInstanceForStructure->CurrentErrorLog(CycleInitiatingField), CycleInitiatingField->GetRawType(), BindableInstanceForStructure->GetQualifiedErrorName(CycleInitiatingStruct), CycleDesc.GetString()); // Mark the structure Member on which the cycle error is detected as bad in order to // avoid reporting other spurious errors that would anyway go away once this is fixed. // CycleInitiatingField->SetIsBad(); CycleInitiatingField->SetFieldCausesStructCycle(true); return; } bool Bindable::IsStructure ( BCSYM_Container *Container ) { return Container->IsClass() && Container->PClass()->IsStruct() && !Container->PClass()->IsEnum() && !Container->PClass()->IsIntrinsicType(); } bool Bindable::IsStructure ( BCSYM *PossibleStructure ) { return PossibleStructure->IsContainer() && IsStructure(PossibleStructure->PContainer()); } // If underlying type of enum is detected only in bindable, // then we need to reType the enum members and expressions // used in it. // // So this begs the question: why not always do the typing // in Bindable. We don't do this to optimize the most common // case where the type is either not specified or specified // as primitive type. If this case is done in declared, then // we avoid having to redo the typing for this case during the // more frequent declared -> Bindable transitions. // void Bindable::ReTypeEnumMembersIfNecessary() { if (!CurrentContainer()->IsEnum()) { return; } BCSYM_Class *Enum = CurrentContainer()->PClass(); BCSYM *UnBoundUnderlyingType = Enum->GetUnderlyingTypeForEnum(); if (!UnBoundUnderlyingType || !UnBoundUnderlyingType->IsNamedType()) { // Bad non-named types for enums should have already been handled in declared // VSASSERT(!UnBoundUnderlyingType || UnBoundUnderlyingType->IsGenericBadNamedRoot() || (TypeHelpers::IsIntrinsicType(UnBoundUnderlyingType) && TypeHelpers::IsIntegralType(UnBoundUnderlyingType)), "Unexpected enum underlying type!!!"); return; } BCSYM *UnderlyingType = UnBoundUnderlyingType->PNamedType()->DigThroughNamedType(); if (UnderlyingType->IsGenericBadNamedRoot()) { return; } // IsIntegralType returns true for enums too, so need to check IsIntrinsic too additionally // if (!TypeHelpers::IsIntegralType(UnderlyingType) || !UnderlyingType->IsIntrinsicType()) { VSASSERT(UnBoundUnderlyingType->IsNamedType(), "Bad Non-named type unexpected as enum type in bindable!!!"); ReportErrorOnSymbol( ERRID_InvalidEnumBase, CurrentErrorLog(Enum), UnBoundUnderlyingType); // Change the bound type to a bad type so that when evaluating initializers of the enum // members, errors resulting from conversions to this type are avoided. // UnBoundUnderlyingType->PNamedType()->SetSymbol(Symbols::GetGenericBadNamedRoot()); return; } // Set the VType of the enum to the correct type // Enum->SetVtype(UnderlyingType->GetVtype()); return; } // This is a helper for and only for BCSYM_Class::GetVType() // to resolve an enum's underlying type if possible when // trying to determine theVType. // // This is needed because during bindable, some constant // expressions in declarations might need to be evaluated // for which we might need to know the VType of enums. // // Returns true if the underlying type was resolved, else // returns false. // bool Bindable::DetermineEnumUnderlyingTypeIfPossible ( BCSYM_Class *Enum, CompilationCaches *IDECompilationCaches ) { // NOTE: This is a helper for and only for BCSYM_Class::GetVType() VSASSERT(Enum->IsEnum(), "Non-enum unexpected!!!"); if (Enum->IsBindingDone() || DefinedInMetaData(Enum)) { return true; } BCSYM *UnderlyingType = Enum->PClass()->GetUnderlyingTypeForEnum(); if (!UnderlyingType || !UnderlyingType->IsNamedType() || UnderlyingType->PNamedType()->GetSymbol()) { return true; } #if IDE if (!IsInCompilationThread(Enum->GetCompiler())) { return false; } #endif IDE // UnderlyingType of enum is a NamedType that has not yet been resolved, // so resolve it if possible. return ResolveAllNamedTypesInContainerIfPossible( Enum, IDECompilationCaches, true); // true indicates - ensure that none of the previous steps are in progress } // This is a helper for and only for BCSYM::DigThroughNamedType // to resolve named types on demand when digging through // a named type. // // This is need because during bindable, some constant // expressions in declarations might need to be evaluated // for which we might need to dig through the named types // in containers which have not yet been through named type // resolution. // // Returns true if the NamedType was resolved, else returns false. // void Bindable::ResolveNamedTypeIfPossible ( BCSYM_NamedType *NamedType, CompilationCaches *IDECompilationCaches ) { // NOTE: This is a helper for and only for BCSYM::DigThroughNamedType BCSYM_NamedRoot *ContextOfNamedType = NamedType->GetContext(); VSASSERT( ContextOfNamedType, "Named Types with NULL context unexpected!!!"); BCSYM_Container *ContainerContextOfNamedType; if (ContextOfNamedType->IsContainer()) { ContainerContextOfNamedType = ContextOfNamedType->PContainer(); } else { ContainerContextOfNamedType = ContextOfNamedType->GetContainer(); } if (ContainerContextOfNamedType) { #if IDE if (!IsInCompilationThread(ContainerContextOfNamedType->GetCompiler())) { return; } #endif IDE Bindable::ResolveAllNamedTypesInContainerIfPossible( ContainerContextOfNamedType, IDECompilationCaches, false); // false indicates - don't bother to check whether any of the previous steps are in progress // // We don't bother to ensure here because the assertion is that this should never be invoked // when any of the previous steps are in progress. // // Assert in ResolveAllNamedTypesInContainerIfPossible to detect any rogue cases. } } // Returns true if resolved, else returns false. // bool Bindable::ResolveAllNamedTypesInContainerIfPossible ( BCSYM_Container *Container, CompilationCaches *IDECompilationCaches, bool EnsureNoPreviousStepsAreInProgress ) { VSASSERT( Container, "NULL container unexpected!!!"); if (Container->IsBindingDone()) { return true; } VSASSERT( !Container->GetSourceFile() || Container->GetSourceFile()->GetProject(), "How can a container in source not have a containing project ?"); SourceFile *ContainingSourceFile = Container->GetSourceFile(); // Nothing to do for metadata container // if (!ContainingSourceFile) { return true; } CompilerProject *ContainingProject = ContainingSourceFile->GetProject(); // If requested to resolve named types before completing declared, // then ignore this request. // if (!ContainingProject->IsDeclaredToBoundCompilationInProgress()) { return false; } if (EnsureNoPreviousStepsAreInProgress) { // If the previous steps i.e ResolveBases, etc. are in progress, // then this step i.e. ResolveAllNamedTypes cannot yet be started. // Bug VSWhidbey 176508 // if (!ContainingProject->HaveImportsBeenResolved() || ContainingSourceFile->AreImportsBeingResolved() || Container->GetBindableInstance()->GetStatusOfResolvePartialTypes() == Bindable::InProgress || Container->GetBindableInstance()->GetStatusOfResolveBases() == Bindable::InProgress) { return false; } } VSASSERT(!( !ContainingProject->HaveImportsBeenResolved() || ContainingSourceFile->AreImportsBeingResolved() || Container->GetBindableInstance()->GetStatusOfResolvePartialTypes() == Bindable::InProgress || Container->GetBindableInstance()->GetStatusOfResolveBases() == Bindable::InProgress ), "Unexpected call to ResolveAllNamedTypesForContainer - dependencies still in progress!!!"); ResolveAllNamedTypesForContainer(Container, IDECompilationCaches); return true; } WCHAR * Bindable::GetBasicRep ( BCSYM *Symbol, StringBuffer *BasicRep, BCSYM_Container *ContainerContext, BCSYM_GenericBinding *GenericBindingContext ) { if (!ContainerContext) { ContainerContext = CurrentContainer(); } Symbol->GetBasicRep( ContainerContext->GetCompiler(), ContainerContext, BasicRep, GenericBindingContext); return BasicRep->GetString(); } STRING * Bindable::GetQualifiedErrorName ( BCSYM *NamedRoot ) { VSASSERT( NamedRoot->IsNamedRoot(), "Non-NamedRoot unexpected!!!"); if (NamedRoot->IsGenericBinding()) { GenericBinding *Binding = NamedRoot->PGenericBinding(); return Binding->GetGeneric()->GetQualifiedName(true, CurrentContainer(), true, Binding); } else if (NamedRoot->IsContainer()) { BCSYM_Container *Container = NamedRoot->PContainer(); STRING *NameOfUnnamedNamespace = STRING_CONST(CurrentCompilerInstance(), EmptyString); if (StringPool::IsEqual(Container->GetName(), NameOfUnnamedNamespace)) { VSASSERT( Container->IsNamespace() && !Container->GetContainer(), "Root namespace expected!!!"); return STRING_CONST(CurrentCompilerInstance(), UnnamedNamespaceErrName); } return Container->GetQualifiedName(true, CurrentContainer(), true /* Append type parameters */); } else if (NamedRoot->IsNamedRoot()) { return NamedRoot->PNamedRoot()->GetQualifiedName(true, CurrentContainer()); } return NULL; } WCHAR * Bindable::GetErrorNameAndSig ( BCSYM *Symbol, BCSYM_GenericTypeBinding *GenericBindingContext, ErrorTable *ErrorLog, StringBuffer *TextBuffer ) { AssertIfNull(Symbol); AssertIfNull(TextBuffer); return ErrorLog->ExtractErrorName( Symbol, // Fully qualify the name for non-members // Symbol->IsMember() ? Symbol->PMember()->GetContainer() : NULL, *TextBuffer, GenericBindingContext); } WCHAR * Bindable::GetSigsForAmbiguousOverridingAndImplErrors ( DynamicArray<BCSYM_Proc *> &AmbiguousMembers, StringBuffer &Buffer ) { for(unsigned Index = 0; Index < AmbiguousMembers.Count(); Index++) { StringBuffer Signature; GetBasicRep( AmbiguousMembers.Element(Index), &Signature, AmbiguousMembers.Element(Index)->GetContainer(), NULL); // Display the unsubstituted signatures so that users can distinguish between the different members. ResLoadStringRepl( ERRID_OverriddenCandidate1, &Buffer, Signature.GetString()); } return Buffer.GetString(); } void Bindable::ReportErrorOnSymbol ( ERRID ErrID, ErrorTable *ErrorLog, BCSYM *SymbolToReportErrorOn, _In_opt_z_ const STRING *ErrorReplString1, _In_opt_z_ const STRING *ErrorReplString2, _In_opt_z_ const STRING *ErrorReplString3, _In_opt_z_ const STRING *ErrorReplString4, _In_opt_z_ const STRING *ErrorReplString5, _In_opt_z_ const STRING *ErrorReplString6, _In_opt_z_ const STRING *ErrorReplString7, _In_opt_z_ const STRING *ErrorReplString8, _In_opt_z_ const STRING *ErrorReplString9 ) { if (ErrorLog) { ErrorLog->CreateErrorWithSymbol( ErrID, SymbolToReportErrorOn, ErrorReplString1, ErrorReplString2, ErrorReplString3, ErrorReplString4, ErrorReplString5, ErrorReplString6, ErrorReplString7, ErrorReplString8, ErrorReplString9); } } void Bindable::ReportErrorOnSymbolWithBindingContexts ( ERRID ErrID, ErrorTable *ErrorLog, BCSYM *SymbolToReportErrorOn, BCSYM *Substitution1, BCSYM_GenericTypeBinding *GenericBindingContext1, BCSYM *Substitution2, BCSYM_GenericTypeBinding *GenericBindingContext2, BCSYM *Substitution3, BCSYM_GenericTypeBinding *GenericBindingContext3, BCSYM *Substitution4, BCSYM_GenericTypeBinding *GenericBindingContext4, BCSYM *Substitution5, BCSYM_GenericTypeBinding *GenericBindingContext5 ) { if (ErrorLog) { StringBuffer TextBuffer1; StringBuffer TextBuffer2; StringBuffer TextBuffer3; StringBuffer TextBuffer4; StringBuffer TextBuffer5; ErrorLog->CreateErrorWithSymbol( ErrID, SymbolToReportErrorOn, Substitution1==NULL ? NULL : GetErrorNameAndSig(Substitution1, GenericBindingContext1, ErrorLog, &TextBuffer1), Substitution2==NULL ? NULL : GetErrorNameAndSig(Substitution2, GenericBindingContext2, ErrorLog, &TextBuffer2), Substitution3==NULL ? NULL : GetErrorNameAndSig(Substitution3, GenericBindingContext3, ErrorLog, &TextBuffer3), Substitution4==NULL ? NULL : GetErrorNameAndSig(Substitution4, GenericBindingContext4, ErrorLog, &TextBuffer4), Substitution5==NULL ? NULL : GetErrorNameAndSig(Substitution5, GenericBindingContext5, ErrorLog, &TextBuffer5)); } } void Bindable::ReportErrorOnSymbol ( ERRID ErrID, ErrorTable *ErrorLog, BCSYM *SymbolToReportErrorOn, BCSYM *Substitution1, BCSYM *Substitution2, BCSYM *Substitution3, BCSYM *Substitution4, BCSYM *Substitution5 ) { ReportErrorOnSymbolWithBindingContexts( ErrID, ErrorLog, SymbolToReportErrorOn, Substitution1, NULL, Substitution2, NULL, Substitution3, NULL, Substitution4, NULL, Substitution5, NULL); } void Bindable::ReportErrorAtLocation ( ERRID ErrID, ErrorTable *ErrorLog, Location *Location, _In_opt_z_ STRING *ErrorReplString1, _In_opt_z_ STRING *ErrorReplString2, _In_opt_z_ STRING *ErrorReplString3, _In_opt_z_ STRING *ErrorReplString4, _In_opt_z_ STRING *ErrorReplString5, _In_opt_z_ STRING *ErrorReplString6, _In_opt_z_ STRING *ErrorReplString7, _In_opt_z_ STRING *ErrorReplString8, _In_opt_z_ STRING *ErrorReplString9 ) { if (ErrorLog) { VSASSERT( Location, "How can we report an error when we don't have a location ?"); ErrorLog->CreateError( ErrID, Location, ErrorReplString1, ErrorReplString2, ErrorReplString3, ErrorReplString4, ErrorReplString5, ErrorReplString6, ErrorReplString7, ErrorReplString8, ErrorReplString9); } } void Bindable::ReportErrorAtLocation ( ERRID ErrID, ErrorTable *ErrorLog, Location *Location, BCSYM *Substitution ) { if (ErrorLog) { StringBuffer TextBuffer; ErrorLog->CreateError( ErrID, Location, ErrorLog->ExtractErrorName( Substitution, Substitution->IsProc() ? Substitution->PProc()->GetContainer() : NULL, TextBuffer)); } } Location * Bindable::GetTypeUseErrorLocation ( BCSYM *RawType, Location *DefaultLocation ) { BCSYM *PossiblyNamedType = RawType->ChaseToNamedType(); if (PossiblyNamedType && PossiblyNamedType->IsNamedType() && PossiblyNamedType->HasLocation()) { return PossiblyNamedType->GetLocation(); } return DefaultLocation; } bool Bindable::CanOverload ( BCSYM_NamedRoot *Member, BCSYM_NamedRoot *OtherMember, unsigned &CompareFlags ) { // Overloading is possible only if the members being considered are // both Methods or both Properties. if (BothAreMethodsOrBothAreProperties(Member, OtherMember)) { CompareFlags = BCSYM::CompareProcs(Member->PProc(), (GenericBinding *)NULL, OtherMember->PProc(), (GenericBinding *)NULL, NULL); // EQ_Shape - Members that differ by parameter signature can overload each other. // // EQ_GenericMethodTypeParamCount - generic methods that differ only by the number of type // parameters can overload each other // // EQ_GenericTypeParams - Methods in generic types that can possibly unify for some type // arguments can overload each other // // Dev10 #792284 // EQ_OptionalTypes - this means that two corresponding optional parameter have different types. // Effectively the same thing as EQ_Shape or EQ_GenericTypeParams, see BCSYM::CompareParams(). if (CompareFlags & (EQ_Shape | EQ_GenericMethodTypeParamCount | EQ_GenericTypeParams | EQ_OptionalTypes)) { return true; } // Dev10 #792284 // EQ_Optional - this means that (see BCSYM::CompareParams()) // a) there is a mismatch in Optional modifier for corresponding parameters; // or // b) one proc has more arguments than the other and all extra arguments are optional. // // We should accept b) as a valid overloading case. if ( (CompareFlags & EQ_Optional) != 0 && Member->PProc()->GetParameterCount() != OtherMember->PProc()->GetParameterCount()) { return true; } if (IsConversionOperator(Member) && IsConversionOperator(OtherMember)) { // User defined conversion operators can additionally overload by return type. if (CompareFlags & EQ_Return) { return true; } // We allow possibly unifying methods to coexist when they are conversion operators if (CompareFlags & (EQ_GenericTypeParams | EQ_GenericTypeParamsForReturn)) { return true; } } return false; } else if (Member->IsType() && OtherMember->IsType() && Member->GetGenericParamCount() != OtherMember->GetGenericParamCount()) { CompareFlags = EQ_Shape; return true; } else { CompareFlags = EQ_Shape; return false; } } bool Bindable::IsMethod ( BCSYM *Member ) { if (Member->IsProc() && !Member->IsProperty() && !Member->IsEventDecl()) { return true; // Is a method } else { return false; } } bool Bindable::IsProperty ( BCSYM *Member ) { return Member->IsProperty(); } bool Bindable::IsSynthetic ( BCSYM_NamedRoot *Member, BCSYM_NamedRoot **SourceOfMember, BCSYM_NamedRoot **NamedContextOfMember, SyntheticContext *SyntheticContext ) { BCSYM_NamedRoot *SourceSymbol = NULL; BCSYM_NamedRoot *NamedContextOfSyntheticMember = NULL; Bindable::SyntheticContext Context = UnKnown; if (SourceSymbol = Member->CreatedByEventDecl()) { Context = EventDecl; } else if (SourceSymbol = Member->CreatedByWithEventsDecl()) { if (SourceSymbol->GetContainer()->IsSameContainer(Member->GetContainer())) { Context = WithEventsDecl; } else { VSASSERT( Member->IsProperty() || (Member->IsSyntheticMethod() && Member->PProc()->GetAssociatedPropertyDef()), "How can any other member be synthesized for a handles clause ?"); Context = HandlesOfBaseWithEvents; if (!Member->GetContainer() || !DefinedInMetaData(Member->GetContainer())) { if (Member->IsProperty()) { VSASSERT( Member->PProperty()->CreatedByHandlesClause(), "How can this member not be created due to a handles clause ?"); NamedContextOfSyntheticMember = Member->PProperty()->CreatedByHandlesClause()->GetHandlingMethod(); } else { BCSYM_Property *AssociatedProperty = Member->PProc()->GetAssociatedPropertyDef(); VSASSERT( AssociatedProperty->CreatedByHandlesClause(), "How can this member not be created due to a handles clause ?"); NamedContextOfSyntheticMember = AssociatedProperty->CreatedByHandlesClause()->GetHandlingMethod(); } } } } else if (SourceSymbol = Member->GetAutoPropertyThatCreatedSymbol()) { Context = AutoPropertyBackingField; } else if (Member->IsProc()) { BCSYM_Proc *Proc = Member->PProc(); if ((Proc->IsPropertyGet() || Proc->IsPropertySet()) && (SourceSymbol = Proc->GetAssociatedPropertyDef())) // Sometime imported getters and setters do not have // an associated property if the property is bad // in some way. So we will treat these a non-synthetic // symbols and will generate any name clash errors // against these symbols themselves { Context = PropertyGetOrSet; // Get/Set could be due to a withevents property. // So dig through the property to find the withevents variable // Bindable::SyntheticContext InnerContext; BCSYM_NamedRoot *InnerSourceSymbol; BCSYM_NamedRoot *InnerNamedContext; if (IsSynthetic(SourceSymbol, &InnerSourceSymbol, &InnerNamedContext, &InnerContext)) { SourceSymbol = InnerSourceSymbol; NamedContextOfSyntheticMember = InnerNamedContext; Context = InnerContext; } } else if (Proc->IsUserDefinedOperatorMethod()) { SourceSymbol = Proc->PMethodDecl()->GetAssociatedOperatorDef(); Context = OperatorMethod; } } if (SourceOfMember) { *SourceOfMember = SourceSymbol; } if (NamedContextOfMember) { if (NamedContextOfSyntheticMember) { *NamedContextOfMember = NamedContextOfSyntheticMember; } else { *NamedContextOfMember = SourceSymbol; } } if (SyntheticContext) { *SyntheticContext = Context; } if (SourceSymbol) { return true; } else { return false; } } /***************************************************************************** ;ResolveAllNamedTypes Resolve all of the named types in a list. This little function exists to expose this functionality outside of Bindable *****************************************************************************/ void Bindable::ResolveAllNamedTypes ( BCSYM_NamedType *NamedTypeList, // [in] The list of named type symbols to be resolved. NorlsAllocator *Allocator, // [in] allocator to use ErrorTable *ErrorLog, // [in] the error log to put our errors into - NULL if we are importing metadata Compiler *CompilerInstance, // [in] compiler context CompilerHost *CompilerHost, // [in] the compiler host SourceFile *OwningSourceFile, // [in] current file TypeResolutionFlags Flags, // [in] indicates how to resolve the type CompilationCaches *IDECompilationCaches ) { // Haul through all the named types in the list we were passed and resolve them for (BCSYM_NamedType *ThisNamedType = NamedTypeList; ThisNamedType; ThisNamedType = ThisNamedType->GetNext()) { ResolveNamedType( ThisNamedType, Allocator, ErrorLog, CompilerInstance, CompilerHost, OwningSourceFile, Flags, IDECompilationCaches, NameNoFlags, false /* don't disable name lookup caching */); } // haul through named types } /***************************************************************************** ;ResolveNamedType Resolve a single named type and do some semantics on it such as determing if it is IsNew and if so whether IsNew is legal; make sure they aren't using a private UDT illegally, Does obsolete checking, etc. *****************************************************************************/ void Bindable::ResolveNamedType ( BCSYM_NamedType *ThisNamedType, // [in] the named type to resolve NorlsAllocator *Allocator, // [in] for the Binder - may be NULL if no generic bindings occur in the type ErrorTable *ErrorLog, // [in] the error log to put our errors into - NULL if we are importing metadata Compiler *CompilerInstance, // [in] the current context CompilerHost *CompilerHost, // [in] the compilerhost SourceFile *CurrentSourceFile, // [in] the current file TypeResolutionFlags Flags, // [in] indicates how to resolve the type CompilationCaches *IDECompilationCaches, NameFlags NameInterpretFlags, // [in] indicates the name binding bool DisableNameLookupCaching // [in] indicates that name look up caching in semantics helpers // should be disabled ) { Location Loc; Loc.SetLocation(0,0); bool IsBadName = false; BCSYM_NamedRoot *BoundSymbol = NULL; // the symbol that semantics says represents this named type BCSYM_Hash *ContextHash = NULL; // the container where the named type was found. BCSYM_Hash *LookupHash = NULL; // the container where to start looking for the namedtype Symbols SymbolAllocator( CompilerInstance, Allocator, NULL, CurrentSourceFile->GetCurrentGenericBindingCache()); if (ThisNamedType->HasLocation()) { Loc = *ThisNamedType->GetLocation(); } VSASSERT( !ThisNamedType->IsTHISType() || ThisNamedType->GetNameCount() == 0, "Inconsistency in named type!!!"); if ( ThisNamedType->GetNameCount() == 0 ) { if (ThisNamedType->IsTHISType()) { BCSYM_NamedRoot *NamedContext = ThisNamedType->GetContext(); BCSYM_Container *ContainingType = NamedContext->IsContainer() ? NamedContext->PContainer() : NamedContext->GetContainer(); if (ContainingType->IsPartialTypeAndHasMainType()) { ContainingType = ContainingType->GetMainType(); } VSASSERT(ContainingType->IsClass(), "Class expected!!!"); if (IsGenericOrHasGenericParent(ContainingType)) { BoundSymbol = SynthesizeOpenGenericBinding( ContainingType, SymbolAllocator); } else { BoundSymbol = ContainingType; } } else { if (!CurrentSourceFile) { if (ThisNamedType->GetContext()) { if (IsUnnamedNamespace(ThisNamedType->GetContext(), CompilerInstance)) { BoundSymbol = ThisNamedType->GetContext()->PNamespace()->GetHash(); } else { VSFAIL("UnnamedNamespace not found!!!"); } } else { VSFAIL("UnnamedNamespace not found!!!"); } } else { // can happen when the type name is only "GlobalNameSpace". In prettylisting could show up BoundSymbol = CurrentSourceFile->GetUnnamedNamespace(); } VSASSERT( ThisNamedType->IsGlobalNameSpaceBased(), "Only GlobalNameSpace can have no qualified id" ); } } else { BCSYM_NamedRoot *Context = ThisNamedType->GetContext(); // Need to do this so that for statics within generic methods, we can bind the types // from the context of the generic method so that we can see the generic method's // type parameters too during binding. // // Need to do this although statics are not allowed inside generic methods in order to // report any type binding errors on the type of the variable. // if (Context->IsStaticLocalBackingField() && Context->PStaticLocalBackingField()->GetProcDefiningStatic() && Context->PStaticLocalBackingField()->GetProcDefiningStatic()->IsGeneric()) { Context = Context->PStaticLocalBackingField()->GetProcDefiningStatic(); } if (Context->IsContainer() && (Context->IsNamespace() || !ThisNamedType->IsUsedInAppliedAttributeContext())) // Attributes on a non-namespace container need to be bound in the // context of the container's parent { ContextHash = Context->PContainer()->GetHash(); } else if (Context->IsProc() && Context->PProc()->IsGeneric()) { ContextHash = Context->PProc()->GetGenericParamsHash(); } else { BCSYM_NamedRoot *ContainerOrMethod = Context->GetContainerOrContainingMethod(); if (ContainerOrMethod->IsContainer()) { ContextHash = ContainerOrMethod->PContainer()->GetHash(); } else if (ContainerOrMethod->IsProc() && ContainerOrMethod->PProc()->IsGeneric()) { ContextHash = ContainerOrMethod->PProc()->GetGenericParamsHash(); } else { ContextHash = ContainerOrMethod->GetContainer()->GetHash(); } } if (ThisNamedType->IsGlobalNameSpaceBased()) { if (!CurrentSourceFile) { if (ThisNamedType->GetContext()) { if (IsUnnamedNamespace(ThisNamedType->GetContext(), CompilerInstance)) { LookupHash = ThisNamedType->GetContext()->PNamespace()->GetHash(); } else { VSFAIL("UnnamedNamespace not found!!!"); } } else { VSFAIL("UnnamedNamespace not found!!!"); } } else { LookupHash = CurrentSourceFile->GetUnnamedNamespace()->GetHash(); } NameInterpretFlags |= NameSearchGlobalNameButLookIntoModule; } else { LookupHash = ContextHash; } // If this named type is from the context of an applied attribute, then determine // the applied attribute context. // BCSYM_NamedRoot *AppliedAttributeContext = ThisNamedType->IsUsedInAppliedAttributeContext() ? ThisNamedType->GetContext() : NULL; BoundSymbol = Semantics::EnsureNamedRoot ( Semantics::InterpretQualifiedName ( ThisNamedType->GetNameArray(), ThisNamedType->GetNameCount(), ThisNamedType->GetArgumentsArray(), Allocator, LookupHash, NameInterpretFlags | NameSearchTypeReferenceOnly | NameSearchIgnoreExtensionMethods | (ThisNamedType->IsAttributeName() ? NameSearchAttributeReference : NameNoFlags), Loc, ErrorLog, CompilerInstance, CompilerHost, IDECompilationCaches, CurrentSourceFile, Flags & TypeResolvePerformObsoleteChecks, IsBadName, DisableNameLookupCaching, ContextHash, AppliedAttributeContext ) ); } if ( IsBadName ) { //AssertIfFalse(!ErrorLog || ErrorLog->HasErrors()); BoundSymbol = Symbols::GetGenericBadNamedRoot(); } ERRID errid = 0; if (!BoundSymbol) { // The type is not defined. if (ThisNamedType->GetNameCount() == 1) { if (StringPool::IsEqual( ThisNamedType->GetNameArray()[0], CompilerInstance->TokenToString(tkCURRENCY))) { // Give a good error on currency errid = ERRID_ObsoleteDecimalNotCurrency; } else if (StringPool::IsEqual( ThisNamedType->GetNameArray()[0], CompilerInstance->TokenToString(tkANY)) && ThisNamedType->GetContext()->IsDllDeclare()) { // Give a good error on As Any errid = ERRID_ObsoleteAsAny; } else { errid = ERRID_UndefinedType1; } } else { errid = ERRID_UndefinedType1; } } else if (!BoundSymbol->IsType() && !BoundSymbol->IsBad()) { // if the type name is bad than the error generate for it will be sufficient - otherwise log the missing type error errid = ERRID_UnrecognizedType; } else if (ErrorLog && BoundSymbol->DigThroughAlias() != NULL && BoundSymbol->DigThroughAlias()->IsClass() && (BoundSymbol->DigThroughAlias()->PClass()->IsStdModule() || BoundSymbol == CompilerHost->GetFXSymbolProvider()->GetType(FX::VoidType)) && (!(Flags & TypeResolveAllowAllTypes) || ThisNamedType->IsTypeArgumentForGenericType())) { // A module or Void can't be used as a type in all cases except GetType() if (BoundSymbol->DigThroughAlias()->PClass()->IsStdModule()) errid = ERRID_ModuleAsType1; else errid = ERRID_BadUseOfVoid; } else if (ThisNamedType->IsAttributeName() && (BoundSymbol->IsGenericTypeBinding() || BoundSymbol->IsGenericParam())) { errid = ERRID_AttrCannotBeGenerics; } else if (ThisNamedType->GetContext()->IsVariable()) { BCSYM_Variable *Context = ThisNamedType->GetContext()->PVariable(); // We don't want to give errors for the type arguments to generic classes, // so skip the validation unless the type is the type of the variable // if (Context->GetRawType() == ThisNamedType) { // If the variable is marked As New, make sure the type can be created // (isn't abstract, has an appropriate constructor, etc) // if (Context->IsNew() && Context->IsLocal()) // Need to delay DimAsNewSemantics for member variables // because the constraint type for type params in the parent // will not yet be bound and cycle checking of constraints // will not yet be done. { // Need to do this here so bilgen won't throw an error about default needed. // We'll catch abstract creation errors in ResolveImplements() // DimAsNewSemantics( BoundSymbol, errid); } // Constant variables must be intrinsic // if (Context->IsConstant() && !ThisNamedType->IsAttributeName() && !IsTypeValidForConstantVariable(BoundSymbol)) { errid = ERRID_ConstAsNonConstant; } } } if (!errid) { ThisNamedType->SetSymbol(BoundSymbol->DigThroughAlias()); // We don't need to check for bad symbols with errid here because // semantics will already have done that in InterpretQualifiedName // if (!BoundSymbol->IsGenericBadNamedRoot()) { // Dev10 #735384 Check if we are improperly using embedded types if (ErrorLog != NULL && ThisNamedType->HasLocation()) { CompilerProject * pCurrentProject = NULL; if (CurrentSourceFile != NULL) { pCurrentProject = CurrentSourceFile->GetCompilerProject(); } else { BCSYM_NamedRoot * pNamedContext = ThisNamedType->GetContext(); if (pNamedContext != NULL) { pCurrentProject = pNamedContext->GetContainingProject(); } } if (pCurrentProject != NULL && pCurrentProject->NeedToCheckUseOfEmbeddedTypes()) { TypeHelpers::CheckClassesForUseOfEmbeddedTypes( ThisNamedType->GetSymbol(), pCurrentProject, ErrorLog, ThisNamedType->GetLocation()); } } return; } } else { // Log error discovered above // Build the qualified name. StringBuffer QualifiedName; unsigned CountOfNames = ThisNamedType->GetNameCount(); for(unsigned i = 0; i < CountOfNames; i++) { if (ThisNamedType->GetNameArray()[i]) { QualifiedName.AppendString( ThisNamedType->GetNameArray()[i]); if (i != CountOfNames - 1) { QualifiedName.AppendChar( L'.'); } } } if (ErrorLog) { if(!ErrorLog->HasThisErrorWithSymLocation(errid,ThisNamedType)) { ErrorLog->CreateErrorWithSymbol( errid, ThisNamedType, QualifiedName.GetString(), ThisNamedType->GetContext() ? // not used by all errids that come through here ThisNamedType->GetContext()->GetName() : L"", ThisNamedType->GetContext()->GetContainer() ? // not used by all errids that come through here ThisNamedType->GetContext()->GetContainer()->GetName() : L""); } } ThisNamedType->SetSymbol(Symbols::GetGenericBadNamedRoot()); // If one of the named types behind a parameter or a return type is bad, mark the procedure as bad // // Note that if the attribute applied to a procedure is bad, then that does not mean the procedure // is bad // } // [....]:2008.09.21. Consider handling the following code differently. // Notionally we're in "bindable", so if GetContext() is a proc then we're assumed to be binding a method // signature, and that's why we mark the method as BadParamTypeOrReturnType. It's UGLY for the // function ResolveNamedType to have an undocumented side effect on the context of the argument it was // given, but so it goes. // More problematically, we are also invoked when interpreting a lambda. // Notionally, we should likewise be marking the lambda as BadParamTypeOrReturnType. // But (1) lambdas don't even have such a field, and (2) even if they did, GetContext() points // to the proc that contained the lambda; not to the lambda itself. // As a workaround, lambda-interpretation passes the flag "TypeResolveDontMarkContainingProcAsBad" // to suppress any marking-as-bad. And the lambda-interpretation (in LambdaSemantics::InterpretLambdaParameters) // will mark the appropriate lambda paramers as bad after this function has returned. // Dev10#489103. if (ThisNamedType->GetContext()->IsProc() && !ThisNamedType->IsAttributeName() && !(Flags & TypeResolveDontMarkContainingProcAsBad)) { ThisNamedType->GetContext()->PProc()->SetIsBad(); // Also, indicate that the problem here is with a type associated with the proc, not the proc itself. ThisNamedType->GetContext()->PProc()->SetIsBadParamTypeOrReturnType(true); } } BCSYM_GenericBinding * Bindable::ResolveGenericType ( BCSYM_NamedRoot *GenericType, // [in] the generic NameTypeArguments *Arguments, // [in] the arguments BCSYM_GenericTypeBinding *ParentBinding, ErrorTable *ErrorLog, // [in] the error log to put our errors into - NULL if we are importing metadata Compiler *CompilerInstance, // [in] the current context Symbols *SymbolFactory ) { bool IsBad = false; Location ErrorLoc; ErrorLoc.Invalidate(); ValidateArity( GenericType->GetName(), GenericType, ParentBinding, Arguments->m_ArgumentCount, Arguments->GetAllArgumentsLocation(&ErrorLoc), ErrorLog, CompilerInstance, IsBad); if (IsBad) { } // For generic import alias A=Class1(Of Integer), reference to "A" can result in this condition. // else if (Arguments->m_ArgumentCount == 0 && ParentBinding && ParentBinding->GetGeneric() == GenericType) { return ParentBinding; } else if (ResolveGenericArguments( GenericType, GenericType->GetFirstGenericParam(), Arguments, ErrorLog, CompilerInstance)) { IsBad = true; } // Absence of the type for the type arguments implies the specification for an uninstantiated // generic type in a gettype expression. Eg: GetType(C1(Of ,)) // else if (Arguments->m_ArgumentCount > 0 && !Arguments->m_TypesForTypeArgumentsSpecified) { // Uninstantiated generic, so return NULL binding // return NULL; } BCSYM_GenericBinding *Binding = SymbolFactory->GetGenericBinding( IsBad, GenericType, Arguments->m_Arguments, Arguments->m_ArgumentCount, ParentBinding); // Store the generic binding to which the type arguments are associated // Arguments->m_BoundGenericBinding = Binding; return Binding; } void Bindable::ValidateArity ( _In_z_ STRING *Name, // [in] the name being searched for BCSYM_NamedRoot *Generic, // [in] the generic, can be NULL BCSYM_GenericTypeBinding *ParentBinding,// [in] the parent binding if any for this generic unsigned ArgumentCount, // [in] the number of type arguments for Generic Location *Loc, // [in] the location of the type arguments ErrorTable *ErrorLog, // [in] the error log to put our errors into - NULL in UI cases Compiler *CompilerInstance, // [in] the current compiler context bool &IsBad // [out] returns true if any arity mismatch issues found - caller needs to initialize ) { VSASSERT(IsBad || Generic, "Unexpected NULL argument!!!"); if (IsBad) { if (ErrorLog) { // No accessible '|1' accepts this number of type arguments. // // No accessible non-generic '|1' found. ErrorLog->CreateError( ArgumentCount == 0 ? ERRID_NoAccessibleNonGeneric1 : ERRID_NoAccessibleGeneric1, Loc, Name); } return; } if (Generic->IsBad()) { IsBad = true; } else if (ArgumentCount > 0 && (!Generic->IsGeneric() || // For generic import alias A=Class1(Of Integer), // A(Of Double) can result in this condition. // (ParentBinding && ParentBinding->GetGeneric() == Generic))) { if (ErrorLog) { StringBuffer ErrorStringForSymbol; ErrorLog->CreateError( ERRID_TypeOrMemberNotGeneric1, Loc, !Generic->IsGeneric() ? ErrorLog->ExtractErrorName(Generic, NULL, ErrorStringForSymbol) : ErrorLog->ExtractErrorName(ParentBinding, NULL, ErrorStringForSymbol)); } IsBad = true; } else if (ArgumentCount == 0 && ParentBinding && ParentBinding->GetGeneric() == Generic) { } else { ERRID ErrId = 0; unsigned ParameterCount = Generic->GetGenericParamCount(); if (ParameterCount == ArgumentCount) { } else if (ParameterCount == 0) { ErrId = ERRID_TypeOrMemberNotGeneric1; } else if (ParameterCount < ArgumentCount) { ErrId = ERRID_TooManyGenericArguments1; } else if (ParameterCount > ArgumentCount) { ErrId = ERRID_TooFewGenericArguments1; } if (ErrId) { if (ErrorLog) { StringBuffer ErrorStringForSymbol; ErrorLog->CreateError( ErrId, Loc, ErrorLog->ExtractErrorName(Generic, NULL, ErrorStringForSymbol)); } IsBad = true; } } return; } void Bindable::CheckAllGenericConstraints ( BCSYM_NamedType *NamedTypeList, ErrorTable *ErrorLog, CompilerHost *CompilerHostInstance, Compiler *CompilerInstance, Symbols *SymbolFactory, CompilationCaches *IDECompilationCaches ) { for (BCSYM_NamedType *ThisNamedType = NamedTypeList; ThisNamedType; ThisNamedType = ThisNamedType->GetNext()) { CheckGenericConstraints( ThisNamedType, ErrorLog, CompilerHostInstance, CompilerInstance, SymbolFactory, IDECompilationCaches); } } void Bindable::CheckGenericConstraints ( BCSYM_NamedType *NamedType, ErrorTable *ErrorLog, CompilerHost *CompilerHostInstance, Compiler *CompilerInstance, Symbols *SymbolFactory, CompilationCaches *IDECompilationCaches, bool CheckForArgumentBindingsToo ) { // Orcas behavior was to guard this loop with "!NamedType->IsBad()", but Orcas behavior // was also that NamedType->IsBad() always returned FALSE! // The idea behind the guard was correct, and for Dev10#489103 we changed // the behavior of IsBad() to return true for the case where it's a NamedType pointing // to a bad type. if (!NamedType->IsBad() && NamedType->GetArgumentsArray()) { for (unsigned Index = 0; Index < NamedType->GetNameCount(); Index++) { NameTypeArguments *TypeArguments = NamedType->GetArgumentsArray()[Index]; if (!TypeArguments) { continue; } BCSYM_GenericBinding *Binding = TypeArguments->m_BoundGenericBinding; CheckGenericConstraints( TypeArguments->m_BoundGenericBinding, NULL, TypeArguments, ErrorLog, CompilerHostInstance, CompilerInstance, SymbolFactory, IDECompilationCaches); // if requested, recursively check the constraints for the bindings among the type arguments // of the current binding too. // if (CheckForArgumentBindingsToo) { CheckGenericConstraintsForBindingsInTypeArguments( TypeArguments, ErrorLog, CompilerHostInstance, CompilerInstance, SymbolFactory, IDECompilationCaches); } } } } void Bindable::CheckGenericConstraintsForBindingsInTypeArguments ( NameTypeArguments *TypeArguments, ErrorTable *ErrorLog, CompilerHost *CompilerHostInstance, Compiler *CompilerInstance, Symbols *SymbolFactory, CompilationCaches *IDECompilationCaches ) { if (!TypeArguments || !TypeArguments->m_TypesForTypeArgumentsSpecified) { return; } for (unsigned ArgumentIndex = 0; ArgumentIndex < TypeArguments->m_ArgumentCount; ArgumentIndex++) { CheckGenericConstraints( TypeArguments->m_Arguments[ArgumentIndex], ErrorLog, CompilerHostInstance, CompilerInstance, SymbolFactory, IDECompilationCaches, true); // recursively check the constraints for the bindings among the type arguments of the // current binding too } } bool Bindable::CheckGenericConstraints ( BCSYM_GenericBinding *Binding, Location TypeArgumentLocations[], NameTypeArguments *TypeArgumentsLocationHolder, ErrorTable *ErrorLog, CompilerHost *CompilerHostInstance, Compiler *CompilerInstance, Symbols *SymbolFactory, CompilationCaches *IDECompilationCaches ) { // Only one of TypeArgumentLocations and TypeArgumentsLocationHolder can be passed in // VSASSERT( !(TypeArgumentLocations && TypeArgumentsLocationHolder), "Two sets of type argument locations unexpected!!!"); if (!Binding || Binding->IsBadGenericBinding()) { return false; } if (Binding->GetGeneric()->IsContainer()) { // The constraint types need to be resolved. ResolveAllNamedTypesForContainer(Binding->GetGeneric()->PContainer(), IDECompilationCaches); } bool paramsValid = true; for (BCSYM_GenericParam *Parameter = Binding->GetGeneric()->GetFirstGenericParam(); Parameter; Parameter = Parameter->GetNextParam()) { BCSYM *ArgumentType = Binding->GetArgument(Parameter->GetPosition()); if (ArgumentType->IsBad()) { continue; } if (ArgumentType->IsContainer()) { // Need to ensure that all bases and implements have been resolved before // this arguments can be validated against the constraints for the corres- // -ponding type parameter // ResolveAllNamedTypesForContainer(ArgumentType->PContainer(), IDECompilationCaches); } CheckRestrictedType( ERRID_RestrictedType1, ArgumentType->ChaseToType(), GetTypeArgumentLocation(Parameter, TypeArgumentsLocationHolder, TypeArgumentLocations), CompilerHostInstance, ErrorLog); // Validate the argument type against the type constraints of the parameter. if (! ValidateGenericConstraintsForType( ArgumentType, Parameter, Binding, TypeArgumentLocations, TypeArgumentsLocationHolder, ErrorLog, CompilerHostInstance, CompilerInstance, SymbolFactory ) ) { paramsValid = false; } } return paramsValid; } BCSYM_Proc * Bindable::GetPublicParameterlessConstructor ( BCSYM_Class *Class, Compiler *CompilerInstance ) { BCSYM_Proc *Constructor = NULL; for(Constructor = Class->GetFirstInstanceConstructor(CompilerInstance); Constructor; Constructor = Constructor->GetNextInstanceConstructor()) { if (Constructor->GetParameterCount() == 0 && Constructor->GetAccess() == ACCESS_Public) { break; } } return Constructor; } bool Bindable::ValidateTypeConstraintOnPartiallyBoundExtensionMethod ( Procedure * pProc, PartialGenericBinding * pPartialGenericBinding, GenericTypeConstraint * pConstraint, Type * pTypeParameterValue, Symbols * pSymbols, CompilerHost * pCompilerHost ) { ThrowIfNull(pConstraint); ThrowIfNull(pPartialGenericBinding); Type * pConstraintType = ReplaceGenericParametersWithArguments ( pConstraint->PGenericTypeConstraint()->GetType(), pPartialGenericBinding->m_pGenericBinding, *pSymbols ); return ! RefersToGenericParameter ( pConstraintType, pProc, NULL, NULL, 0, 0, false, pPartialGenericBinding->m_pFixedTypeArgumentBitVector ) && ValidateTypeConstraintForType ( pTypeParameterValue, pConstraintType, pCompilerHost, pSymbols ); } bool Bindable::ValidateConstraintOnPartiallyBoundExtensionMethod ( BCSYM_Proc * pProc, PartialGenericBinding * pPartialGenericBinding, GenericConstraint * pConstraint, GenericParameter * pParameter, Type * pTypeParameterValue, Symbols * pSymbols, CompilerHost * pCompilerHost ) { return ( ( pConstraint->IsGenericTypeConstraint() && ValidateTypeConstraintOnPartiallyBoundExtensionMethod ( pProc, pPartialGenericBinding, pConstraint->PGenericTypeConstraint(), pTypeParameterValue, pSymbols, pCompilerHost ) ) || ( pConstraint->IsReferenceConstraint() && TypeHelpers::IsReferenceType(pTypeParameterValue) ) || ( pConstraint->IsValueConstraint() && TypeHelpers::IsValueType(pTypeParameterValue) ) || ( pConstraint->IsNewConstraint() && ValidateNewConstraintForType(pTypeParameterValue, pParameter, NULL, NULL, NULL, pCompilerHost->GetCompiler()) ) ); } bool Bindable::ValidateGenericConstraintsOnPartiallyBoundExtensionMethod ( BCSYM_Proc * pProc, PartialGenericBinding * pPartialGenericBinding, Symbols * pSymbols, CompilerHost * pCompilerHost ) { ThrowIfNull(pProc); ThrowIfNull(pSymbols); ThrowIfNull(pCompilerHost); if (! pPartialGenericBinding) { return true; } GenericParameter * pParameter = pProc->GetFirstGenericParam(); while (pParameter) { if (pPartialGenericBinding->IsFixed(pParameter)) { Type * pTypeParameterValue = pPartialGenericBinding->m_pGenericBinding->GetCorrespondingArgument(pParameter); GenericConstraint * pConstraint = pParameter->GetConstraints(); while (pConstraint) { if ( ! ValidateConstraintOnPartiallyBoundExtensionMethod ( pProc, pPartialGenericBinding, pConstraint, pParameter, pTypeParameterValue, pSymbols, pCompilerHost ) ) { return false; } pConstraint = pConstraint->Next(); } } pParameter = pParameter->GetNextParam(); } return true; } bool Bindable::ValidateGenericConstraintsForType ( BCSYM *Type, BCSYM_GenericParam *Parameter, BCSYM_GenericBinding *Binding, Location TypeArgumentLocations[], NameTypeArguments *TypeArgumentsLocationHolder, ErrorTable *ErrorLog, CompilerHost *CompilerHostInstance, Compiler *CompilerInstance, Symbols *SymbolFactory, bool IgnoreProjectEquivalence, // Consider types as equivalent ignoring their projects' equivalence. CompilerProject **ProjectForType, // The project containing a component of type "Type" that was considered // for a successful match ignoring project equivalence. CompilerProject **ProjectForGenericParam // The project containing a component of type "Parameter" that was considered // for a successful match ignoring project equivalence. ) { // Validate the argument type against the type constraints of the parameter. // Only one of TypeArgumentLocations and TypeArgumentsLocationHolder can be passed in // VSASSERT( !(TypeArgumentLocations && TypeArgumentsLocationHolder), "Two sets of type argument locations unexpected!!!"); bool ConstraintsSatisfied = true; for (BCSYM_GenericConstraint *Constraint = Parameter->GetConstraints(); Constraint; Constraint = Constraint->Next()) { if (Constraint->IsBadConstraint()) { continue; } if (Constraint->IsGenericTypeConstraint()) { // Validate the argument type against the type constraint of the parameter. if (!ValidateTypeConstraintForType( Type, Parameter, Constraint->PGenericTypeConstraint(), Binding, TypeArgumentLocations, TypeArgumentsLocationHolder, ErrorLog, CompilerHostInstance, CompilerInstance, SymbolFactory, IgnoreProjectEquivalence, ProjectForType, ProjectForGenericParam)) { ConstraintsSatisfied = false; } } else if (Constraint->IsNewConstraint()) { // Validate the argument type against the "New" constraint of the parameter. if (!ValidateNewConstraintForType( Type, Parameter, TypeArgumentLocations, TypeArgumentsLocationHolder, ErrorLog, CompilerInstance)) { ConstraintsSatisfied = false; } } else if (Constraint->IsReferenceConstraint()) { // Validate the argument type against the "Class" constraint of the parameter. if (!ValidateReferenceConstraintForType( Type, Parameter, TypeArgumentLocations, TypeArgumentsLocationHolder, ErrorLog)) { ConstraintsSatisfied = false; } } else if (Constraint->IsValueConstraint()) { // Validate the argument type against the "Structure" constraint of the parameter. if (!ValidateValueConstraintForType( Type, Parameter, TypeArgumentLocations, TypeArgumentsLocationHolder, ErrorLog, CompilerHostInstance, CompilerInstance, TypeHelpers::IsNullableType(Binding,CompilerHostInstance))) { ConstraintsSatisfied = false; } } // Short circuit by returning as soon as validation fails when no error reporting is required // if (!ConstraintsSatisfied && !ErrorLog) { break; } } return ConstraintsSatisfied; } // Returns true if constraint is satisfied, else false // bool Bindable::ValidateTypeConstraintForType ( BCSYM *Type, BCSYM_GenericParam *Parameter, BCSYM_GenericTypeConstraint *Constraint, BCSYM_GenericBinding *Binding, Location TypeArgumentLocations[], NameTypeArguments *TypeArgumentsLocationHolder, ErrorTable *ErrorLog, CompilerHost *CompilerHostInstance, Compiler *CompilerInstance, Symbols *SymbolFactory, bool IgnoreProjectEquivalence, // Consider types as equivalent ignoring their projects' equivalence. CompilerProject **ProjectForType, // The project containing a component of type "Type" that was considered // for a successful match ignoring project equivalence. CompilerProject **ProjectForConstraint // The project containing a component of the "Constraint"'s type that was considered // for a successful match ignoring project equivalence. ) { BCSYM *ConstraintType = Constraint->GetType(); ConstraintType = ReplaceGenericParametersWithArguments( ConstraintType, Binding, *SymbolFactory); if (!ValidateTypeConstraintForType( Type, ConstraintType, CompilerHostInstance, SymbolFactory, IgnoreProjectEquivalence, ProjectForType, ProjectForConstraint)) { if (ErrorLog) { StringBuffer ArgumentBuffer; StringBuffer ConstraintBuffer; Location* ErrorLocation = GetTypeArgumentLocation(Parameter, TypeArgumentsLocationHolder, TypeArgumentLocations); WCHAR* ArgumentString = ErrorLog->ExtractErrorName(Type, NULL, ArgumentBuffer); WCHAR* ConstraintTypeString = ErrorLog->ExtractErrorName(ConstraintType, NULL, ConstraintBuffer); if (!ErrorLog->HasThisErrorWithLocationAndParameters( ERRID_GenericConstraintNotSatisfied2, ErrorLocation, ArgumentString, ConstraintTypeString)) { ErrorLog->CreateError( ERRID_GenericConstraintNotSatisfied2, ErrorLocation, ArgumentString, ConstraintTypeString); } } return false; } return true; } bool Bindable::ValidateTypeConstraintForType ( BCSYM *Type, BCSYM *ConstraintType, CompilerHost *CompilerHostInstance, Symbols *SymbolFactory, bool IgnoreProjectEquivalence, // Consider types as equivalent ignoring their projects' equivalence. CompilerProject **ProjectForType, // The project containing a component of type "Type" that was considered // for a successful match ignoring project equivalence. CompilerProject **ProjectForConstraintType // The project containing a component of type "ConstraintType" that was considered // for a successful match ignoring project equivalence. ) { if (ConstraintType->IsBad()) { return true; } ConversionClass Conversion = ClassifyPredefinedCLRConversion( ConstraintType, Type, *SymbolFactory, CompilerHostInstance, ConversionSemantics::ForConstraints, // for constraint-checks we don't allow value-conversions e.g. enum->underlying 0, // RecursionCount=0 because we're calling from outside IgnoreProjectEquivalence, ProjectForConstraintType, ProjectForType, NULL); if (Conversion == ConversionIdentity || Conversion == ConversionWidening) { return true; } return false; } // Returns true if constraint is satisfied, else false // bool Bindable::ValidateNewConstraintForType ( BCSYM *Type, BCSYM_GenericParam *Parameter, Location TypeArgumentLocations[], NameTypeArguments *TypeArgumentsLocationHolder, ErrorTable *ErrorLog, Compiler *CompilerInstance ) { VSASSERT(Parameter->HasNewConstraint(), "New constraint validation unexpected!!!"); if (Type->IsStruct() || Type->IsEnum()) { // All structs are assumed to have a default constructor // because they can always be constructed using initobj } else if (Type->IsGenericParam()) { BCSYM_GenericParam *GenericParamArgument = Type->PGenericParam(); // "Type parameter '|1' must have a 'New' constraint or 'Structure' constraint to satisfy the // 'New' constraint for type parameter '|2'.") if (!GenericParamArgument->CanBeInstantiated()) { if (ErrorLog) { StringBuffer ArgumentBuffer; StringBuffer ConstraintBuffer; ErrorLog->CreateError( ERRID_BadGenericParamForNewConstraint2, GetTypeArgumentLocation(Parameter, TypeArgumentsLocationHolder, TypeArgumentLocations), ErrorLog->ExtractErrorName(Type, NULL, ArgumentBuffer), ErrorLog->ExtractErrorName(Parameter, NULL, ConstraintBuffer)); } return false; } } else { BCSYM_Proc *SuitableConstructor = NULL; if (IsClass(Type)) { BCSYM_Class *Class = Type->PClass(); SuitableConstructor = GetPublicParameterlessConstructor(Class, CompilerInstance); // Report the MustInherit error only if no error is generated regarding a public parameterless // constructor. The reasons for this are: // - The public parameterless constructor missing is a more understandable error in this context // - Too much clutter to report both errors - Bug VSWhidbey 169091 // if (SuitableConstructor && Class->IsMustInherit()) { if (ErrorLog) { // Type argument '|1' is declared 'MustInherit' and so does not satisfy the 'New' constraint // for type parameter '|2'. StringBuffer ArgumentBuffer; StringBuffer ConstraintBuffer; ErrorLog->CreateError( ERRID_MustInheritForNewConstraint2, GetTypeArgumentLocation(Parameter, TypeArgumentsLocationHolder, TypeArgumentLocations), ErrorLog->ExtractErrorName(Type, NULL, ArgumentBuffer), ErrorLog->ExtractErrorName(Parameter, NULL, ConstraintBuffer)); } return false; } } if (!SuitableConstructor) { if (ErrorLog) { // // Type argument '|1' does not have a public parameterless instance constructor and so does not // satisfy the 'New' constraint for type parameter '|2' StringBuffer ArgumentBuffer; StringBuffer ConstraintBuffer; ErrorLog->CreateError( ERRID_NoSuitableNewForNewConstraint2, GetTypeArgumentLocation(Parameter, TypeArgumentsLocationHolder, TypeArgumentLocations), ErrorLog->ExtractErrorName(Type, NULL, ArgumentBuffer), ErrorLog->ExtractErrorName(Parameter, NULL, ConstraintBuffer)); } return false; } } return true; } // Returns true if constraint is satisfied, else false // bool Bindable::ValidateReferenceConstraintForType ( BCSYM *Type, BCSYM_GenericParam *Parameter, Location TypeArgumentLocations[], NameTypeArguments *TypeArgumentsLocationHolder, ErrorTable *ErrorLog ) { VSASSERT(!Parameter || Parameter->HasReferenceConstraint(), "Reference type constraint validation unexpected!!!"); if (!TypeHelpers::IsReferenceType(Type)) { if (ErrorLog) { // Type argument '|1' does not satisfy the 'Class' constraint for type parameter '|2' StringBuffer ArgumentBuffer; StringBuffer ConstraintBuffer; ErrorLog->CreateError( ERRID_BadTypeArgForRefConstraint2, GetTypeArgumentLocation(Parameter, TypeArgumentsLocationHolder, TypeArgumentLocations), ErrorLog->ExtractErrorName(Type, NULL, ArgumentBuffer), ErrorLog->ExtractErrorName(Parameter, NULL, ConstraintBuffer)); } return false; } return true; } // Returns true if constraint is satisfied, else false // bool Bindable::ValidateValueConstraintForType ( BCSYM *Type, BCSYM_GenericParam *Parameter, Location TypeArgumentLocations[], NameTypeArguments *TypeArgumentsLocationHolder, ErrorTable *ErrorLog, CompilerHost *CompilerHostInstance, Compiler *CompilerInstance, bool isNullableValue ) { VSASSERT(!Parameter || Parameter->HasValueConstraint(), "Value type constraint validation unexpected!!!"); if (!TypeHelpers::IsValueType(Type)) { if (ErrorLog) { Location* ErrorLocation = GetTypeArgumentLocation(Parameter, TypeArgumentsLocationHolder, TypeArgumentLocations); if (isNullableValue) { if (!ErrorLog->HasThisErrorWithLocation(ERRID_BadTypeArgForStructConstraintNull, *ErrorLocation)) { StringBuffer ArgumentBuffer; ErrorLog->CreateError( ERRID_BadTypeArgForStructConstraintNull, ErrorLocation, ErrorLog->ExtractErrorName(Type, NULL, ArgumentBuffer)); } } else { if (!ErrorLog->HasThisErrorWithLocation(ERRID_BadTypeArgForStructConstraint2, *ErrorLocation)) { // Type argument '|1' does not satisfy the 'Structure' constraint for type parameter '|2' StringBuffer ArgumentBuffer; StringBuffer ParameterBuffer; ErrorLog->CreateError( ERRID_BadTypeArgForStructConstraint2, ErrorLocation, ErrorLog->ExtractErrorName(Type, NULL, ArgumentBuffer), ErrorLog->ExtractErrorName(Parameter, NULL, ParameterBuffer)); } } } return false; } else if ( TypeHelpers::IsNullableType(Type, CompilerHostInstance) || TypeHelpers::IsConstrainedToNullable(Type, CompilerHostInstance) ) { if (ErrorLog) { Location* ErrorLocation = GetTypeArgumentLocation(Parameter, TypeArgumentsLocationHolder, TypeArgumentLocations); if (!ErrorLog->HasThisErrorWithLocation(ERRID_BadTypeArgForStructConstraint2, *ErrorLocation)) { // 'System.Nullable' does not satisfy the 'Structure' constraint for type parameter '|1'. Only non-nullable 'Structure' types are allowed. StringBuffer ParameterBuffer; ErrorLog->CreateError( ERRID_NullableDisallowedForStructConstr1, ErrorLocation, ErrorLog->ExtractErrorName(Parameter, NULL, ParameterBuffer)); } } return false; } return true; } Location* Bindable::GetTypeArgumentLocation ( BCSYM_GenericParam *Parameter, NameTypeArguments *TypeArgumentsLocationHolder, Location TypeArgumentLocations[] ) { return TypeArgumentsLocationHolder ? TypeArgumentsLocationHolder->GetArgumentLocation(Parameter->GetPosition()) : TypeArgumentLocations ? &TypeArgumentLocations[Parameter->GetPosition()] : NULL; } void Bindable::CheckGenericConstraints ( BCSYM *Type, ErrorTable *ErrorLog, CompilerHost *CompilerHostInstance, Compiler *CompilerInstance, Symbols *SymbolFactory, CompilationCaches *IDECompilationCaches, bool CheckForArgumentBindingsToo ) { if (Type->IsNamedType()) { CheckGenericConstraints( Type->PNamedType(), ErrorLog, CompilerHostInstance, CompilerInstance, SymbolFactory, IDECompilationCaches, CheckForArgumentBindingsToo); } } void Bindable::CheckGenericConstraintsForImportsTarget ( ImportedTarget *ImportsTarget, ErrorTable *ErrorLog, CompilerHost *CompilerHostInstance, Compiler *CompilerInstance, Symbols *SymbolFactory, CompilationCaches *IDECompilationCaches ) { if (ImportsTarget->m_hasError || !ImportsTarget->m_pTarget || ImportsTarget->m_pTarget->IsBad() || !ImportsTarget->m_pTarget->IsGenericTypeBinding()) { return; } VSASSERT(ImportsTarget->m_ppTypeArguments, "Type arguments expected for type binding!!!"); unsigned CurrentBindingIndex = ImportsTarget->m_NumDotDelimitedNames - 1; for(BCSYM_GenericBinding *Binding = ImportsTarget->m_pTarget->PGenericTypeBinding(); Binding; Binding = Binding->GetParentBinding()) { CheckGenericConstraints( Binding, NULL, ImportsTarget->m_ppTypeArguments[CurrentBindingIndex], ErrorLog, CompilerHostInstance, CompilerInstance, SymbolFactory, IDECompilationCaches); CheckGenericConstraintsForBindingsInTypeArguments( ImportsTarget->m_ppTypeArguments[CurrentBindingIndex], ErrorLog, CompilerHostInstance, CompilerInstance, SymbolFactory, IDECompilationCaches); CurrentBindingIndex--; } } bool Bindable::ResolveGenericArguments ( BCSYM *UnboundGeneric, BCSYM_GenericParam *Parameters, NameTypeArguments *ArgumentsInfo, ErrorTable *ErrorLog, // [in] the error log to put our errors into - NULL if we are importing metadata Compiler *CompilerInstance // [in] the current context ) { BCSYM **Arguments = ArgumentsInfo->m_Arguments; unsigned ArgumentCount = ArgumentsInfo->m_ArgumentCount; bool IsBad = false; unsigned ArgumentIndex = 0; while (Parameters != NULL && ArgumentIndex < ArgumentCount) { // Arguments[ArgumentIndex] can be NULL for unspecified type arguments // which is a valid scenario for types in getype expressions. // Eg: GetType(C(Of ,)) if (Arguments[ArgumentIndex]) { BCSYM *ArgumentType = Arguments[ArgumentIndex]->DigThroughNamedType(); if (ArgumentType->IsBad()) { IsBad = true; } } // Constraints cannot be checked yet because the constraint types have not necessarily been resolved. Parameters = Parameters->GetNextParam(); ArgumentIndex++; } if (Parameters != NULL) { // Error -- too few arguments. if (ErrorLog) { Location ErrorLoc; ErrorLog->CreateError( ERRID_TooFewGenericArguments1, ArgumentsInfo->GetAllArgumentsLocation(&ErrorLoc), UnboundGeneric->GetErrorName(CompilerInstance)); } IsBad = true; } if (ArgumentIndex != ArgumentCount) { // Error -- too many arguments. if (ErrorLog) { Location ErrorLoc; ErrorLog->CreateError( ERRID_TooManyGenericArguments1, ArgumentsInfo->GetAllArgumentsLocation(&ErrorLoc), UnboundGeneric->GetErrorName(CompilerInstance)); } IsBad = true; } return IsBad; } /***************************************************************************** ;ResolveImports Go through all the imports for the namespaces in this file and resolve them *****************************************************************************/ void Bindable::ResolveImports ( BCSYM_Namespace *NamespaceToCheck, // The namespace that owns the imports being resolved SourceFile *SourceFile, // [in] used to get the default namespace CompilerProject *Project, // [in] used by semantics when binding the name NorlsAllocator *Allocator, // [in] symbols will be allocated from this heap LineMarkerTable *LineMarkerTbl, // [in] ErrorTable *ErrorLog, // [in] the error log to put our errors into - NULL if we are importing metadata Compiler *CompilerInstance, // [in] the current context CompilationCaches *IDECompilationCaches ) { VSASSERT( NamespaceToCheck, "A file should have a namespace" ); BCITER_CHILD NamespaceIterator(NamespaceToCheck); ImportedTarget *ImportsToResolve = NamespaceToCheck->GetImports(); if (ImportsToResolve) { ResolveImportsList( ImportsToResolve, SourceFile, Project, Allocator, LineMarkerTbl, ErrorLog, CompilerInstance, IDECompilationCaches); } // for add imports validation: resolve the extra imports statement here if(SourceFile->GetExtraTrackedImport()) { ErrorTable dummyErrorLog(CompilerInstance, Project, NULL); ResolveImportsList( SourceFile->GetExtraTrackedImport(), SourceFile, Project, Allocator, NULL, &dummyErrorLog, CompilerInstance, IDECompilationCaches); } // Iterate through any nested namespaces while (BCSYM_NamedRoot *CurrentNamespaceSymbol = NamespaceIterator.GetNext()) { if (CurrentNamespaceSymbol->IsNamespace() && CurrentNamespaceSymbol->GetBindingSpace() != BINDSPACE_IgnoreSymbol ) { ResolveImports( CurrentNamespaceSymbol->PNamespace(), SourceFile, Project, Allocator, LineMarkerTbl, ErrorLog, CompilerInstance, IDECompilationCaches); } } } /************************************************************************************************** ;ResolveImportsList Resolves all of the imports clauses ***************************************************************************************************/ void Bindable::ResolveImportsList ( ImportedTarget *ImportsStatement, // List of imports to resolve SourceFile *SourceFile, // Used to get the unnamed namespace (may be null) CompilerProject *Project, // [in] the Project that Sourcefile belongs to NorlsAllocator *Allocator, // [in] the allocator to use for building aliases LineMarkerTable* LineMarkerTbl, // [in] the line marker table ErrorTable *ErrorLog, // [in] the error log to put our errors into - NULL if we are importing metadata Compiler *CompilerInstance, // [in] the current compilation context CompilationCaches *IDECompilationCaches ) { bool IsBadImportsName; // SourceFile might be NULL. Symbols SymbolFactory( CompilerInstance, Allocator, LineMarkerTbl, SourceFile == NULL ? NULL : ( Allocator == SourceFile->SymbolStorage() ? SourceFile->GetCurrentGenericBindingCache() : NULL)); // For project-level imports there is no source file. BCSYM_Namespace *UnnamedNamespace = SourceFile ? SourceFile->GetUnnamedNamespace() : CompilerInstance->GetUnnamedNamespace(Project); // If there is no unnamed namespace for this project, that means it contains // no files, so no need to do this. // if (!UnnamedNamespace) return; ResolvedImportsTree *pImportsCache = Project->GetImportsCache(); for(ImportedTarget *CurrentImport = ImportsStatement; CurrentImport; CurrentImport = CurrentImport->m_pNext) { // Make sure we null the target out first, that way, if we punt out because // of an error, we won't have a pointer that points to garbage. // // Clearing the following info is particularly important because for project // level imports we don't clear during decompilation and expect it to be cleared // before binding. // CurrentImport->m_pAlias = NULL; CurrentImport->m_hasError = false; if (CurrentImport->m_IsXml) { // Project-level imports need to have their XmlNamespaceDeclaration symbol rebound each Bound phase to the UnnamedNamespace, which can change // as files are removed and added to the project. File-level imports create the symbol in the Declared phase. if (CurrentImport->m_IsProjectLevelImport) CurrentImport->m_pTarget = SymbolFactory.GetXmlNamespaceDeclaration(CurrentImport->m_pstrQualifiedName, NULL, Project, NULL, true); } else { CurrentImport->m_pTarget = NULL; // If there are no names, then this import has an error. Punt this guy // if (!CurrentImport->m_NumDotDelimitedNames) { CurrentImport->m_hasError = true; continue; } bool HasGenericArguments = false; #if IDE VSASSERT( GetCompilerSharedState()->IsInBackgroundThread(), "Compilation cache is not being set for the FG thread, so the following call could cause performance problems"); #endif ResolveTypeArguments( CurrentImport->m_ppTypeArguments, CurrentImport->m_NumDotDelimitedNames, Allocator, ErrorLog, CompilerInstance, Project->GetCompilerHost(), SourceFile, TypeResolveNoFlags, IDECompilationCaches, // Compilation Caches NameSearchTypeReferenceOnly | NameSearchIgnoreImports | NameSearchImmediateOnly | NameSearchIgnoreBases, false, HasGenericArguments); ResolvedImportsNode *pResolvedImportsNode = NULL; BCSYM_NamedRoot *BoundImport = NULL; if (!HasGenericArguments && pImportsCache->Find(&CurrentImport->m_pstrQualifiedName, &pResolvedImportsNode)) { BoundImport = pResolvedImportsNode->BoundImport; IsBadImportsName = false; } else { #if IDE VSASSERT( GetCompilerSharedState()->IsInBackgroundThread(), "Compilation cache is not being set for the FG thread, so InterpretQualifiedName could cause performance problems"); #endif BoundImport = Semantics::EnsureNamedRoot ( Semantics::InterpretQualifiedName ( CurrentImport->m_DotDelimitedNames, CurrentImport->m_NumDotDelimitedNames, CurrentImport->m_ppTypeArguments, Allocator, UnnamedNamespace->GetHash(), // Restriction to not look at types in containers that are // visible through inheritance. Without this restriction, // file compile ordering will matter and will make binding // imports indeterminate in some cases. // ( NameSearchTypeReferenceOnly | NameSearchIgnoreImports | NameSearchImmediateOnly | NameSearchIgnoreBases | NameSearchIgnoreExtensionMethods ), CurrentImport->m_loc, ErrorLog, CompilerInstance, Project->GetCompilerHost(), IDECompilationCaches, //CompilationCaches SourceFile, // don't perform obsolete checks. This will be done later // in Obsolete checker after cracking attributes. // false, IsBadImportsName ) ); } // Handle errors that fell out of binding the import statement // if (IsBadImportsName) { CurrentImport->m_hasError = true; continue; } // Cache the import results. if (!HasGenericArguments && pResolvedImportsNode == NULL && BoundImport != NULL) { if (pImportsCache->Insert(&CurrentImport->m_pstrQualifiedName, &pResolvedImportsNode)) { pResolvedImportsNode->BoundImport = BoundImport; } } ERRID ErrId = 0; if (!BoundImport) { ErrId = SourceFile ? WRNID_UndefinedOrEmptyNamespaceOrClass2 : WRNID_UndefinedOrEmpyProjectNamespaceOrClass2; } else // is this an importable thing? { BCSYM *ImportType = BoundImport->DigThroughAlias(); if (!ImportType->IsNamespace() && (!ImportType->IsType() || // ImportType->IsDelegate() || // Non-aliased interface imports are disallowed // (ImportType->IsInterface() && !CurrentImport->m_pstrAliasName))) { ErrId = CurrentImport->m_pstrAliasName ? ERRID_InvalidTypeForAliasesImport2 : ERRID_NonNamespaceOrClassOnImport2; } } if (ErrId) { // don't log repeating errors // if (!CurrentImport->m_hasError) { STRING *ImportsString = CompilerInstance->ConcatStringsArray( CurrentImport->m_NumDotDelimitedNames, (const WCHAR **)CurrentImport->m_DotDelimitedNames, WIDE(".")); const WCHAR *LastName = CurrentImport->m_DotDelimitedNames[CurrentImport->m_NumDotDelimitedNames - 1] ? CurrentImport->m_DotDelimitedNames[CurrentImport->m_NumDotDelimitedNames - 1] : L""; if (ErrorLog) { ErrorLog->CreateError( ErrId, &CurrentImport->m_loc, ImportsString, LastName); } CurrentImport->m_hasError = true; } continue; } // The Import name is ok so far - CheckForDuplicates // CurrentImport->m_pTarget = BoundImport->DigThroughAlias(); } // All the imports for the namespace being processed in SourceFile are linked together // in the ImportsStatement List. There aren't very many - compare the guy just built // against everybody before him in the list looking for dupes // for(ImportedTarget *DupeIter = ImportsStatement; DupeIter != CurrentImport; DupeIter = DupeIter->m_pNext ) { // skip horked guys if (DupeIter->m_hasError) continue; // Duplicate alias names? if (CurrentImport->m_pstrAliasName && CurrentImport->m_IsXml == DupeIter->m_IsXml) { // Use case sensitive comparison if this is an Xml import if (CurrentImport->m_IsXml ? StringPool::IsEqualCaseSensitive(CurrentImport->m_pstrAliasName, DupeIter->m_pstrAliasName) : StringPool::IsEqual(CurrentImport->m_pstrAliasName, DupeIter->m_pstrAliasName)) { ErrorLog->CreateError( CurrentImport->m_IsXml ? ERRID_DuplicatePrefix : ERRID_DuplicateNamedImportAlias1, &DupeIter->m_loc, DupeIter->m_pstrAliasName); DupeIter->m_hasError = true; } } // Already imported this namespace? else if (!CurrentImport->m_pstrAliasName && !DupeIter->m_pstrAliasName && DupeIter->m_pTarget->PContainer()->IsSameContainer(CurrentImport->m_pTarget->PContainer())) { // When referring to the same container, either both should be bindings or both should be not // VSASSERT(!(DupeIter->m_pTarget->IsGenericTypeBinding() ^ CurrentImport->m_pTarget->IsGenericTypeBinding()), "Inconsistent type bindings in imports unexpected!!!"); VSASSERT(!(DupeIter->m_IsProjectLevelImport ^ CurrentImport->m_IsProjectLevelImport), "File level and project-level imports mix up unexpected!!!"); // Are imported entities equal ? // if (!DupeIter->m_pTarget->IsGenericBinding() || BCSYM::AreTypesEqual(DupeIter->m_pTarget, CurrentImport->m_pTarget)) { // Note no duplicate checking for project level imports. if (!DupeIter->m_IsProjectLevelImport) { StringBuffer ErrorSymbolNameBuffer; ErrorLog->CreateError( ERRID_DuplicateImport1, &DupeIter->m_loc, ErrorLog->ExtractErrorName(DupeIter->m_pTarget, NULL, ErrorSymbolNameBuffer)); DupeIter->m_hasError = true; } } else if (DupeIter->m_pTarget->IsGenericBinding()) { // Generic type '|1' has already been imported, although with different type arguments. StringBuffer ErrorSymbolNameBuffer; ErrorLog->CreateError( ERRID_DuplicateRawGenericTypeImport1, &DupeIter->m_loc, ErrorLog->ExtractErrorName(DupeIter->m_pTarget->PContainer(), NULL, ErrorSymbolNameBuffer)); DupeIter->m_hasError = true; } } } // Looking for duplicates // Make sure that the Import's alias doesn't have the same name as a type in the global namespace // if (!CurrentImport->m_IsXml) { if (!CurrentImport->m_hasError && CurrentImport->m_pstrAliasName != NULL && UnnamedNamespace) { BCSYM_Namespace *UnnamedNamespaceIter = UnnamedNamespace; do { // If this namespace is not available to the current project, ignore it if (!CompilerInstance->NamespaceIsAvailable(Project, UnnamedNamespaceIter)) { continue; } BCSYM_NamedRoot *TypeInGlobalNamespace = UnnamedNamespaceIter->SimpleBind(NULL, CurrentImport->m_pstrAliasName); if (TypeInGlobalNamespace) { StringBuffer TypeRep; TypeInGlobalNamespace->GetBasicRep( CompilerInstance, TypeInGlobalNamespace->GetContainer(), &TypeRep, NULL, NULL, TRUE /* full expansion */ ); ErrorLog->CreateError( ERRID_ImportAliasConflictsWithType2, &CurrentImport->m_loc, CurrentImport->m_pstrAliasName, TypeRep.GetString()); CurrentImport->m_hasError = true; break; } } while ((UnnamedNamespaceIter = UnnamedNamespaceIter->GetNextNamespace()) && // detect when we have looped around (Namespaces are on circularly linked lists UnnamedNamespaceIter != UnnamedNamespace); } } if (!CurrentImport->m_hasError) { CurrentImport->m_pAlias = SymbolFactory.GetAlias( CurrentImport->m_pstrAliasName, 0, CurrentImport->m_pTarget, NULL); } } // loop imports list } /***************************************************************************** ;BuildEvent Process an event declaration that is shaped by a delegate instead of the event declaration itself. Ok, this is ugly, but it's the simplest way to deal with it. Events that are declared "Event x as delegate" cannot be fully built until the delegate type that they are supposed to be is resolved. Once the delegate is known, we have to go back and set the parameters of the event. NOTE: this has to be kept in [....] with the associated decompilation logic in bindableDecompilation.cpp *****************************************************************************/ void Bindable::BuildEvent(BCSYM_EventDecl *Event) { BCSYM *RawDelegate = Event->GetRawDelegate(); // No delegate, no need to build anything. Someone else will report an error // if needed, or perhaps this is an implementing event which wouldn't have a // delegate yet (we hook it up later) // if (!RawDelegate || RawDelegate->IsGenericBadNamedRoot()) { return; } if (!RawDelegate->IsDelegate()) { // If we bind to anything but a delegate, give an error. if (!RawDelegate->DigThroughNamedType()->IsDelegate()) { if (!RawDelegate->DigThroughNamedType()->IsBad()) { ReportErrorOnSymbol( ERRID_EventTypeNotDelegate, CurrentErrorLog(Event), // intrinsics have no location so use event instead // RawDelegate->IsIntrinsicType() || RawDelegate->IsObject() ? Event : RawDelegate); Event->SetIsBad(); } return; } // Propagate the delegate shape to the event BCSYM *Delegate = Event->GetDelegate(); // Resolve the named types for the delegate so that the types // of the parameters of the invoke method are known. // ResolveAllNamedTypesForContainer(Delegate->PClass(), m_CompilationCaches); BCSYM_NamedRoot *InvokeMethod = Delegate->PClass()->SimpleBind( NULL, STRING_CONST(CurrentCompilerInstance(), DelegateInvoke)); if (InvokeMethod && InvokeMethod->IsBad()) { InvokeMethod->ReportError( CurrentCompilerInstance(), CurrentErrorLog(Event), RawDelegate->GetLocation()); Event->SetIsBad(); return; } if (InvokeMethod == NULL || !InvokeMethod->IsProc()) { ReportErrorOnSymbol( ERRID_UnsupportedType1, CurrentErrorLog(Event), RawDelegate, Delegate->PClass()->GetName()); Event->SetIsBad(); return; } // If the /target:winmdobj switch was specified then all events will take the WinRT shape unless // they implement a normal .NET shaped event. bool isWinRTShapedEventTheDefault = CurrentSourceFile(Event)->GetCompilerProject() && CurrentSourceFile(Event)->GetCompilerProject()->GetOutputType() == OUTPUT_WinMDObj; // If the delegate has a return type, that's not cool if (InvokeMethod->PProc()->GetType()) { ReportErrorOnSymbol( ERRID_EventDelegatesCantBeFunctions, CurrentErrorLog(Event), Event); Event->SetIsBad(); } else { // Validate the signatures of the event methods for a block event if (Event->IsBlockEvent()) { if (Event->GetProcAdd() && Event->GetProcAdd()->GetFirstParam()) { if (!BCSYM::AreTypesEqual( Event->GetProcAdd()->GetFirstParam()->GetType(), Delegate)) { // 'AddHandler' and 'RemoveHandler' method parameters must have the same delegate type as the containing event. // The type of the 'AddHandler' method's parameter must be the same as the type of the event. BCSYM *RawParamType = Event->GetProcAdd()->GetFirstParam()->GetRawType(); ReportErrorAtLocation( isWinRTShapedEventTheDefault ? ERRID_AddParamWrongForWinRT : ERRID_AddRemoveParamNotEventType, CurrentErrorLog(Event), RawParamType->IsNamedType() ? RawParamType->GetLocation() : Event->GetProcAdd()->GetFirstParam()->GetLocation()); Event->SetIsBad(); } } // If the event is implementing an interface member then we will do // parameter validation in ImplementsSemantics. if (Event->GetProcRemove() && Event->GetProcRemove()->GetFirstParam() && Event->GetImplementsList() == NULL) { BCSYM *RawParamType = Event->GetProcRemove()->GetFirstParam()->GetRawType(); if ((!isWinRTShapedEventTheDefault && !BCSYM::AreTypesEqual( Event->GetProcRemove()->GetFirstParam()->GetType(), Delegate)) || (isWinRTShapedEventTheDefault && CurrentCompilerHost()->GetFXSymbolProvider()->IsTypeAvailable(FX::EventRegistrationTokenType) && !BCSYM::AreTypesEqual( Event->GetProcRemove()->GetFirstParam()->GetType(), CurrentCompilerHost()->GetFXSymbolProvider()->GetType(FX::EventRegistrationTokenType)))) { // 'AddHandler' and 'RemoveHandler' method parameters must have the same delegate type as the containing event. // In a Windows Runtime event, the type of the 'RemoveHandler' method parameter must be 'EventRegistrationToken'. ReportErrorAtLocation( isWinRTShapedEventTheDefault ? ERRID_RemoveParamWrongForWinRT : ERRID_AddRemoveParamNotEventType, CurrentErrorLog(Event), RawParamType->IsNamedType() ? RawParamType->GetLocation() : Event->GetProcRemove()->GetFirstParam()->GetLocation()); Event->SetIsBad(); } } if (Event->GetProcFire()) { Symbols SymbolFactory( CurrentCompilerInstance(), CurrentAllocator(), NULL, CurrentGenericBindingCache()); MethodConversionClass MethodConversion = Semantics::ClassifyMethodConversion( Event->GetProcFire(), GenericBindingInfo(), InvokeMethod->PProc(), Delegate->IsGenericBinding() ? Delegate->PGenericBinding() : NULL, false, //IgnoreReturnValueErrorsForInference &SymbolFactory, CurrentCompilerHost()); if (!Semantics::IsSupportedMethodConversion( (CurrentSourceFile(Event)->GetOptionFlags() & OPTION_OptionStrict), MethodConversion)) { // 'RaiseEvent' method must have the same signature as the containing event's delegate type. StringBuffer DelegateSignature; Delegate->PContainer()->GetBasicRep( CurrentCompilerInstance(), CurrentContainer(), &DelegateSignature, Delegate->IsGenericBinding() ? Delegate->PGenericBinding() : NULL); ReportErrorOnSymbol( ERRID_RaiseEventShapeMismatch1, CurrentErrorLog(Event), Event->GetProcFire(), DelegateSignature.GetString()); Event->SetIsBad(); } } } } Symbols SymbolFactory( CurrentCompilerInstance(), CurrentAllocator(), NULL, CurrentGenericBindingCache()); // If the /target:winmdobj switch was specified then all events will take the WinRT shape unless // they implement a normal .NET shaped event. We will handle that case in ImplementsSemantics if (isWinRTShapedEventTheDefault && Event->GetImplementsList() == NULL) { Event->ConvertToWindowsRuntimeEvent(CurrentCompilerHost(), &SymbolFactory); } // We need to make a copy of the parameter list. Other people // may need to store symbol-specific information in it. // Make sure you copy the Location too!!!! CopyInvokeParamsToEvent( Event, Delegate, InvokeMethod->PProc(), CurrentAllocator(), &SymbolFactory); } } void Bindable::CopyInvokeParamsToEvent ( BCSYM_EventDecl *Event, BCSYM *Delegate, BCSYM_Proc *DelegateInvoke, NorlsAllocator *Allocator, Symbols *SymbolFactory ) { // We need to make a copy of the parameter list. Other people // may need to store symbol-specific information in it. // Make sure you copy the Location too!!!! BCSYM_Param *CurrentParameter = NULL; BCSYM_Param *FirstParameter = NULL; BCSYM_Param *LastParameter = NULL; for(CurrentParameter = DelegateInvoke->PProc()->GetFirstParam(); CurrentParameter != NULL; CurrentParameter = CurrentParameter->GetNext()) { size_t cbSize = CurrentParameter->IsParamWithValue() ? sizeof(BCSYM_ParamWithValue) : sizeof(BCSYM_Param); // [....] 9/13/2004: The numbers added together for the allocation are all values that we own, and are "small" // -- there is no danger of overflow, and so I have not altered the code at all. BCSYM_Param *BuiltParamSymbol = (BCSYM_Param*)Allocator->Alloc( cbSize + (CurrentParameter->HasLocation() ? sizeof(TrackedLocation) : 0)); if (CurrentParameter->HasLocation()) { // This is a little funky, but this is what we do in Symbols::AllocSymbol() to adjust the // base pointer for the symbol just created. // pTrackedLocation is of type TrackedLocation*, so adding 1 to that pointer adds // sizeof(TrackedLocation) bytes, not 1 byte. Tricky, but it works. // TrackedLocation* pTrackedLocation = (TrackedLocation*) BuiltParamSymbol; BuiltParamSymbol = (BCSYM_Param *)(pTrackedLocation + 1); } // First copy the Param symbol memcpy(BuiltParamSymbol, CurrentParameter, cbSize); // If the delegate is a generic binding, then the types of the event's parameters // need to use the bound argument types of the delegate (rather than the generic parameter types). // // Not needed if the delegate is implicitly created by this event, because then it is an // an open binding and replacing the types does not gain much. More importantly, this helps // the event parameters retain the namedtypes as their types which helps during error // reporting. See VSWhidbey 264180 // if (Delegate->IsGenericBinding() && Delegate->PNamedRoot()->CreatedByEventDecl() != Event) { BuiltParamSymbol->SetType( ReplaceGenericParametersWithArguments( BuiltParamSymbol->GetCompilerType(), Delegate->PGenericBinding(), *SymbolFactory)); } // The location does not get copied with the memcopy above (since it's actually outside the symbol) // so we need to copy it explicitly. if (CurrentParameter->HasLocation()) { BuiltParamSymbol->SetLocation(CurrentParameter->GetLocation()); } // Link them in the linked list of Parameters Symbols::SetNextParam(BuiltParamSymbol, NULL); if (LastParameter) { Symbols::SetNextParam(LastParameter, BuiltParamSymbol); } else { FirstParameter = BuiltParamSymbol; } LastParameter = BuiltParamSymbol; } Event->SetParamList(FirstParameter); // Clone the return type if required. Bug VSWhidbey 357546. BCSYM *ReturnType = Event->GetCompilerType(); if (ReturnType && !ReturnType->IsVoidType() && Delegate->IsGenericBinding() && Delegate->PNamedRoot()->CreatedByEventDecl() != Event) { Event->SetType( ReplaceGenericParametersWithArguments( ReturnType, Delegate->PGenericBinding(), *SymbolFactory)); } } void Bindable::EvaluateAllConstantDeclarationsInContainer() { NorlsAllocator norlsStorage(NORLSLOC); BCSYM_Container *Container = CurrentContainer(); do { for(BCSYM_Expression *ExpressionSymbol = Container->GetExpressionList(); ExpressionSymbol != NULL; ExpressionSymbol = ExpressionSymbol->GetNext()) { if (!ExpressionSymbol->IsEvaluated()) { EvaluateDeclaredExpression( ExpressionSymbol, &norlsStorage, CurrentAllocator(), CurrentErrorLog(ExpressionSymbol->GetReferringDeclaration()), CurrentCompilerInstance(), CurrentCompilerHost(), m_CompilationCaches); } } } while (Container = Container->GetNextPartialType()); } /***************************************************************************** ;EvaluateConstantDeclarations Evaluate all of the constant expressions in the given list. These are the constant expressions that couldn't be evaluated during Declared state because they referenced variables, etc. *****************************************************************************/ void Bindable::EvaluateConstantDeclarations ( BCSYM_Expression *ExpressionList, // [in] list of constant expressions to evaluate NorlsAllocator *Allocator, // [in] allocator for symbol storage ErrorTable *ErrorLog, // [in] the error log to put our errors into - NULL if we are importing metadata Compiler *CompilerInstance, // [in] the current compilation context CompilerHost *CompilerHost, // [in] the current compilerhost CompilationCaches *IDECompilationCaches ) { NorlsAllocator norlsStorage( NORLSLOC); for(BCSYM_Expression *ExpressionSymbol = ExpressionList; ExpressionSymbol != NULL; ExpressionSymbol = ExpressionSymbol->GetNext()) { if (!ExpressionSymbol->IsEvaluated()) { EvaluateDeclaredExpression( ExpressionSymbol, &norlsStorage, Allocator, ErrorLog, CompilerInstance, CompilerHost, IDECompilationCaches); } } } /***************************************************************************** ;EvaluateDeclaredExpression Step an expression from declared to evaluated. The text of the expression is obtained, parsed, and interpreted. *****************************************************************************/ void Bindable::EvaluateDeclaredExpression ( BCSYM_Expression * ExpressionSymbol, // [in] the expression we want to evaluate NorlsAllocator * TreeAllocator, // [in] allocator to use NorlsAllocator * SymbolAllocator, // [in] allocator to use ErrorTable *ErrorLog, // [in] the error log to put our errors into - NULL if we are importing metadata Compiler *CompilerInstance, // [in] the current compilation context CompilerHost *CompilerHost, // [in] the current compilerhost CompilationCaches *IDECompilationCaches ) { ParseTree::Expression *ExpressionTree = NULL; const Location *ExpressionLocation = ExpressionSymbol->GetLocation(); BCSYM_NamedRoot *ReferringDeclaration = ExpressionSymbol->GetReferringDeclaration(); BCSYM_Hash *ConstantsHash = NULL; // [in] hash table to use when resolving constants // a bad referring declaration can create havoc later (VSW 340844). Filter it out here. if (ReferringDeclaration->IsBad()) { return; } VSASSERT(ReferringDeclaration && (ReferringDeclaration->IsProc() || (ReferringDeclaration->IsVariable() && ReferringDeclaration->PVariable()->IsConstant())), "unexpected declaration with deferred expression : #10/29/2003#"); if (ExpressionSymbol->IsSyntheticExpressionForEnumMemberIncrement()) { VSASSERT( ExpressionLocation, "Synthetic expressions for Enums should have the location of the enum member for which they are defined!!!"); // This tree could have been built up during declared when synthesizing these // expressions, but they take up quite a bit of storage, so instead build up the // trees in bindable at the point of the evaluation, since building up these trees // is quick. // // So then the question, why not synthesize text ? This would result in the parse // trees having locations in non-user code, so any errors could end up squiggling // non-existing locations // There's a possibility to stack overflow if we evaluate this enum recursively 1 element at a time. // Instead, count to the first enum member that did not have a synthetic increment initializer value. // See Dev11 222108, 235772, 369336 int countFromPreviousEnumWithValue = 1; BCSYM_VariableWithValue *pFirstEnumVariableWithActualValue = ExpressionSymbol->GetPrevousEnumMember(); while (pFirstEnumVariableWithActualValue->GetExpression() && !pFirstEnumVariableWithActualValue->GetExpression()->IsEvaluated() && pFirstEnumVariableWithActualValue->GetExpression()->IsSyntheticExpressionForEnumMemberIncrement()) { pFirstEnumVariableWithActualValue = pFirstEnumVariableWithActualValue->GetExpression()->GetPrevousEnumMember(); countFromPreviousEnumWithValue++; } // Create the ParseTree Node representing the name of the previous enum member ParseTree::NameExpression *PrevEnumMember = new (TreeAllocator->Alloc(sizeof ParseTree::NameExpression)) ParseTree::NameExpression; PrevEnumMember->Opcode = ParseTree::Expression::Name; PrevEnumMember->Name.Name = CompilerInstance->AddString(pFirstEnumVariableWithActualValue->GetName()); PrevEnumMember->Name.TypeCharacter = chType_NONE; PrevEnumMember->Name.IsBracketed = false; PrevEnumMember->Name.IsBad = false; PrevEnumMember->Name.IsNullable = false; PrevEnumMember->Name.TextSpan = *ExpressionLocation; PrevEnumMember->TextSpan = *ExpressionLocation; ParseTree::IntegralLiteralExpression *IntegerLiteral = new (TreeAllocator->Alloc(sizeof ParseTree::IntegralLiteralExpression)) ParseTree::IntegralLiteralExpression; IntegerLiteral->Opcode = ParseTree::Expression::IntegralLiteral; IntegerLiteral->Value = countFromPreviousEnumWithValue; IntegerLiteral->Base = ParseTree::IntegralLiteralExpression::Decimal; IntegerLiteral->TextSpan = *ExpressionLocation; // For Ulong enums, force the constant increment value to be typed as an unsigned value to // avoid a decimal result. Bug VSWhidbey 285217. // IntegerLiteral->TypeCharacter = (ExpressionSymbol->GetForcedType() && ExpressionSymbol->GetForcedType()->GetVtype() == t_ui8) ? chType_U8 : chType_NONE; ParseTree::BinaryExpression *Increment = new (TreeAllocator->Alloc(sizeof ParseTree::BinaryExpression)) ParseTree::BinaryExpression; Increment->Opcode = ParseTree::Expression::Plus; Increment->Left = PrevEnumMember; Increment->Right = IntegerLiteral; Increment->TextSpan = *ExpressionLocation; // Note: No Punctuator needed for because this is a synthetic expression ExpressionTree = Increment; } else { // the text of the expression we are evaluating, // e.g. "test" given the expression: Const str As String * 5 = "Test" // WCHAR *ExpressionText = ExpressionSymbol->GetExpressionText(); CompilerFile *pFile = ReferringDeclaration->GetCompilerFile(); Parser ExpressionParser( TreeAllocator, CompilerInstance, CompilerHost, false, pFile ? pFile->GetProject()->GetCompilingLanguageVersion() : LANGUAGE_CURRENT); Scanner Scanner( CompilerInstance, ExpressionText, wcslen( ExpressionText ), 0, // get a scanner for tokenizing the expression in ExpressionText ExpressionLocation ? ExpressionLocation->m_lBegLine : 0, ExpressionLocation ? ExpressionLocation->m_lBegColumn : 0); // build a parse tree for the expression // IfFailThrow(ExpressionParser.ParseOneExpression( &Scanner, ErrorLog, &ExpressionTree, NULL, // ErrorInConstructRet pFile ? pFile->GetProject()->GetProjectLevelCondCompScope() : NULL, // Dev10 #789970 Use proper conditional complation scope. pFile && pFile->IsSourceFile() ? pFile->PSourceFile()->GetConditionalCompilationConstants() : NULL // Dev10 #789970 )); } // the location of the start of the text that makes up the expression we are evaluating // Location *TextLocation = ExpressionSymbol->GetLocation(); ExpressionSymbol->SetIsEvaluating(true); BCSYM *CastType; if (ExpressionSymbol->GetForcedType() == NULL) // are we supposed to cast the expression? { // no type to cast expression to CastType = NULL; } else // there is a cast for this expression - the type should already be bound { CastType = ExpressionSymbol->GetForcedType(); if (CastType->GetVtype() == t_ptr) { // byref parameter; get underlying type CastType = CastType->PPointerType()->GetCompilerRoot(); } } // If we're looking up constant expressions for a file, use the container as the lookup scope // // But for constant expressions in method declaration - say the optional parameter value, we need // to start off with the type params hash of the generic method. if (ReferringDeclaration->IsProc() && ReferringDeclaration->PProc()->IsGeneric()) { ConstantsHash = ReferringDeclaration->PProc()->GetGenericParamsHash(); } if (!ConstantsHash) { BCSYM_NamedRoot *ParentContext = ReferringDeclaration; while (ParentContext && !ParentContext->IsHash()) { ParentContext = ParentContext->GetImmediateParent(); } if (ParentContext) { ConstantsHash = ParentContext->PHash(); } } if (ConstantsHash) { // Make sure all bases and named types have been resolved for the container // before evaluating constant expressions in it. // How could this happen before the container's bases and named types have been // resolved ? Well, it could occur if this expression evaluation is triggered // when evaluating an expression in another container that is dependent on this // expression. // BCSYM_Container *ContainerOfConstantExpression = ConstantsHash->GetContainer(); VSASSERT( ContainerOfConstantExpression, "How can a hash be independent of a container ?"); ResolveAllNamedTypesInContainerIfPossible( ContainerOfConstantExpression, IDECompilationCaches, false); // false indicates - don't bother to check whether any of the previous steps are in progress // // We don't bother to ensure here because the assertion is that this should never be invoked // when any of the previous steps are in progress. // // Assert in ResolveAllNamedTypesInContainerIfPossible to detect any rogue cases. } // OPTIONAL: // Bindable sees many constant expressions, e.g. enums, attributes and parameter-defaults. // Of those expressions whose referring declaration is a Proc, they're all param-defaults. // Note: delegate declarations do not satisfy IsProc. It is "ByDesign" that you're not allowed // to specify optional parameters in a delegate declaration. bool ExprIsForAParameterDefault = ExpressionSymbol->GetReferringDeclaration()->IsProc(); // Parameter defaults work like this: // (1) Evaluate the default expression as a constant in a context where the target type is unknown // (2) If the resulting constant value is "Nothing" of type Object, then use default(T) // (3) Otherwise, attempt a constant-conversion of the value to the type of the parameter, // or to the underlying type of the parameter in case it's a nullable. // Note that "x as Integer? = CType(Nothing,Object) uses route 2, while "x as Integer? = CType(Nothing, Integer) // uses route 3. ConstantValue ValueOfConstant; ILTree::Expression *ExpressionOfConstant; bool ExpressionIsBad = false; BCSYM *ParameterType = CastType==NULL ? CastType : CastType->DigThroughAlias(); Semantics Analyzer(TreeAllocator, ErrorLog, CompilerInstance, CompilerHost, ConstantsHash->GetSourceFile(), NULL, false); // (1) Evaluate the rhs of the expression as a constant in a context where the target type is unknown ValueOfConstant = Analyzer.InterpretConstantExpression( ExpressionTree, ConstantsHash, NULL, // NULL target type, i.e. "in a context wher the target type is unknown" false, &ExpressionIsBad, //If this constant is used as parameter default, then the function needs to be passed to // InterpretConstantExpression, since this constant will be delayed to check obsolete and // the delayed obsolete check needs to know the context of this constant. //For example, class CC1 is obsolete. // //<Obsolete()> // Sub Foo(Optional ByVal x As Integer = CC1.val) // // If this constant is assigned to a constant field, then ReferringDeclaration refers to the // constant variable. // // Added for bug 482094. ReferringDeclaration, ExpressionSymbol->IsSyntheticExpression(), &ExpressionOfConstant); VSASSERT(ValueOfConstant.Integral==0 || ValueOfConstant.TypeCode!=t_ref, "unexpected: the only t_ref constant possible should have value 0"); if (ExpressionIsBad) { // If it's bad, we won't look any further... } else if (ValueOfConstant.TypeCode == t_ref && ValueOfConstant.Integral == 0) { // (2) If the resulting constant value is "Nothing" of type Object, then use default(T) // Note that ParameterType==NULL was used in optional parameters to mean "Object": see the comment // in Declare::MakeParames ZeroMemory(&ValueOfConstant, sizeof(ValueOfConstant)); // just to make sure there's no junk in it Vtypes pvtype = (ParameterType==NULL) ? t_ref : ParameterType->GetVtype(); ValueOfConstant.SetVType((pvtype==t_ref || pvtype==t_struct || pvtype==t_generic) ? t_ref : pvtype); } else { // (3) Otherwise, attempt a constant-conversion of the value to the parameter's type (or to its // underlying type if it was a nullable), reporting errors along the way if necessary. BCSYM *TargetType = ParameterType; if (TargetType!=NULL && TypeHelpers::IsNullableType(TargetType)) { TargetType = TypeHelpers::GetElementTypeOfNullable(TargetType); } // Incidentally, recall that we here in parameter-defaults use TargetType==NULL to indicate // a parameter type of "Object". In such a case, every parameter-default-expression is good // to go with no conversion needed. And indeed, if given a NULL TargetType, then // ConvertWithErrorChecking does indeed do no conversion. ValueOfConstant = Analyzer.ConvertConstantExpressionToConstantWithErrorChecking( ExpressionOfConstant, TargetType, ExpressionIsBad); // final parameter "ExpressionIsBad" is an _Out_ parameter } ExpressionSymbol->SetIsEvaluating(false); ExpressionSymbol->SetIsEvaluated(true); if (ExpressionIsBad && ErrorLog) { // check for ErrorLog so we only throw errors if we aren't importing meta-data // (which is happening when ErrorLog is NULL) // ReferringDeclaration->SetIsBad(); } else { if (ValueOfConstant.TypeCode == t_string) { // Copy the spelling so that it lives as long as the symbol. // [....] 9/13/2004: Since the string already exists, and we own the calculation of its length, there's no chance // that the number will overflow (or else it could not have been allocated in the first place). WCHAR *Spelling = (WCHAR *)SymbolAllocator->Alloc((ValueOfConstant.String.LengthInCharacters + 1) * sizeof(WCHAR)); if (ValueOfConstant.String.Spelling) { memcpy( Spelling, ValueOfConstant.String.Spelling, (ValueOfConstant.String.LengthInCharacters + 1) * sizeof(WCHAR)); } else { Spelling = NULL; } ValueOfConstant.String.Spelling = Spelling; } ExpressionSymbol->SetValue(ValueOfConstant); // Change an Object-typed constant to the type of its expression (VSW#177934). if (ValueOfConstant.TypeCode != t_ref && // Devdiv Bug[24272] ReferringDeclaration->IsVariable() && TypeHelpers::IsRootObjectType(ReferringDeclaration->PVariable()->GetType())) { ReferringDeclaration->PVariable()->SetType( CompilerHost->GetFXSymbolProvider()->GetType(ValueOfConstant.TypeCode)); } } } /**************************************************************************** ;ChaseThroughToType Chases through arrays, pointers, etc. to find the actual type of the symbol *****************************************************************************/ BCSYM * // the type of pType Bindable::ChaseThroughToType ( BCSYM * Type // [in] the type to chase through ) { for( ;; ) { switch( Type->GetKind()) // figure out the access of the type behind the member { case SYM_NamedType: Type = Type->DigThroughNamedType(); continue; case SYM_PointerType: Type = Type->PPointerType()->GetRoot(); continue; case SYM_ArrayLiteralType: case SYM_ArrayType: Type = Type->PArrayType()->GetRoot(); continue; default: return Type; } // switch } // endless loop } bool Bindable::FindBaseInMyGroupCollection(BCSYM_Class *Class, WellKnownAttrVals::MyGroupCollectionData* groupCollectionData, unsigned* foundIndex) { unsigned i = -1; bool found = false; if (groupCollectionData) { BCSYM_Class *Base = Class->GetCompilerBaseClass(); ULONG count = groupCollectionData->Count(); if (count) { WellKnownAttrVals::MyGroupCollectionBase* arrayBase = groupCollectionData->Array(); while (Base && !Base->IsObject()) { STRING* BaseQName = Base->GetQualifiedName(); for (i = 0 ; i < count; i++) { if (StringPool::IsEqual(BaseQName, arrayBase[i].m_GroupName)) { found = true; break; } } if(found) break; Base = Base->PClass()->GetCompilerBaseClass(); } } } if(foundIndex) *foundIndex = found ? i : -1; return found; } void Bindable::ScanAndLoadMyGroupCollectionMembers(BCSYM_Container *Container, CompilerProject *pProject) { // MetaData containers are not allowed here in order to keep the // loading of nested types "on demand". // VSASSERT( !DefinedInMetaData(Container), "Metadata containers not allowed here!!"); if (IsClass(Container)) { BCSYM_Class *Class = Container->PClass(); if (!CanBeMyGroupCollectionMember(Class, pProject->GetCompiler())) { // filter out partial types, generics and known to fail due to new constraint #if DEBUG // in debug mode and if MyGroupTrace, check if such class could be a member an debprintf why is rejected // partial types are ignored because their main part makes it anyhow. if (VBFTESTSWITCH(fMyGroupAndDefaultInst) && !Class->IsPartialType()) { MyGroupCollectionInfo* arrayOfMyGroupCollectionInfo = pProject->m_daMyGroupCollectionInfo.Array(); ULONG count = pProject->m_daMyGroupCollectionInfo.Count(); for (unsigned i = 0 ; i < count; i++) { BCSYM_Class *GroupClass = arrayOfMyGroupCollectionInfo[i].m_groupClass; WellKnownAttrVals::MyGroupCollectionData* groupCollectionData; GroupClass->GetPWellKnownAttrVals()->GetMyGroupCollectionData(&groupCollectionData); BCSYM_Class *Base = Class->GetCompilerBaseClass(); if (FindBaseInMyGroupCollection(Class, groupCollectionData, NULL)) { DebugPrintfCanBeMyGroupCollectionMember(Class, GroupClass, pProject->GetCompiler()); break; } } } #endif return; } MyGroupCollectionInfo* arrayOfMyGroupCollectionInfo = pProject->m_daMyGroupCollectionInfo.Array(); ULONG count = pProject->m_daMyGroupCollectionInfo.Count(); for (unsigned i = 0 ; i < count; i++) { BCSYM_Class *GroupClass = arrayOfMyGroupCollectionInfo[i].m_groupClass; WellKnownAttrVals::MyGroupCollectionData *groupCollectionData; GroupClass->GetPWellKnownAttrVals()->GetMyGroupCollectionData(&groupCollectionData); if (FindBaseInMyGroupCollection(Class, groupCollectionData, NULL)) { // check for duplicates in debug mode #ifdef DEBUG bool found = false; BCSYM_Class** arrayOfClassesInMyGroupMember = arrayOfMyGroupCollectionInfo[i].m_daMyGroupMembers.Array(); ULONG countMem = arrayOfMyGroupCollectionInfo[i].m_daMyGroupMembers.Count(); for (unsigned k = 0 ; k < countMem; k++) { if (BCSYM::AreTypesEqual(arrayOfClassesInMyGroupMember[k], Class)) { found = true; break; } } if (found) { VSDEBUGPRINTIF( VSFSWITCH(fMyGroupAndDefaultInst), "MyGroup: duplicate member: %S found in MyGroup class: %S\n", Class->GetName(), GroupClass->GetName()); } VSDEBUGPRINTIF( VSFSWITCH(fMyGroupAndDefaultInst), "MyGroup: adding class member '%S' to group '%S'\n", Class->GetName(), GroupClass->GetName()); #endif arrayOfMyGroupCollectionInfo[i].m_daMyGroupMembers.Add() = Class; // consider to break here. This would corespond to the case when a class can be member of only one group } } // do not itterate over the the nested types in a class. Nested classes cannot be members in // My* groups return; } // iterate Container for all nested types // else if (Container->IsNamespace()) { for(BCSYM_Container *NestedType = Container->GetNestedTypes(); NestedType; NestedType = NestedType->GetNextNestedType()) { ScanAndLoadMyGroupCollectionMembers(NestedType, pProject); } } } bool Bindable::CanBeMyGroupCollectionMember ( BCSYM_Class *pClass, Compiler *pCompiler ) { Type *pType = pClass; return !pClass->IsPartialType() && !pClass->IsGeneric() && GetPublicParameterlessConstructor(pClass, pCompiler) && CheckConstraintsOnNew(pType) == 0; } #if DEBUG // DebugPrintf co-function for the above CanBeMyGroupCollectionMember(). Keep in [....] void Bindable::DebugPrintfCanBeMyGroupCollectionMember ( BCSYM_Class *pClass, BCSYM_Class *pGroupClass, Compiler *pCompiler ) { Type *pType = pClass; char* ms = NULL; if ( pClass->IsGeneric()) ms = "MyGroup: class '%S' fails to qualify as a member in group '%S' because it is generic\n"; else if (!GetPublicParameterlessConstructor(pClass, pCompiler)) ms = "MyGroup: class '%S' fails to qualify as a member in group '%S' because it has no parameterless constructor\n"; else if (CheckConstraintsOnNew(pType) != 0) ms = "MyGroup: class '%S' fails to qualify as a member in group '%S' because it doesn't comply with the 'new constraint'\n"; else if ( pClass->IsPartialType()) { // nop - false positive partial classes are just skipped. Only the main part of a partial needs to qualify. //ms = "MyGroup: class '%S' fails to qualify as a member in group '%S' because it is partial\n"; } else { VSFAIL("DebugPrintfCanBeMyGroupCollectionMember out of [....]"); } if(ms) { VSDEBUGPRINTIF( VSFSWITCH(fMyGroupAndDefaultInst), ms, pClass->GetName(), pGroupClass->GetName()); } } #endif //DEBUG void Bindable::----AttributesOnAllSymbolsInContainer() { // For MetaData symbols, all attributes on symbols are ----ed when they are imported itself. // Also validation is not required for them because we only care about well known attributes. // VSASSERT( !DefinedInMetaData(CurrentContainer()), "MetaData container unexpected here!!!"); if (GetStatusOf----AttributesOnAllSymbolsInContainer() == InProgress || GetStatusOf----AttributesOnAllSymbolsInContainer() == Done) { return; } SetStatusOf----AttributesOnAllSymbolsInContainer(InProgress); // We need to ---- attributes for all bases because we need to check if a class // is a valid attribute and what kinds of symbols this can be applied to. // Also need these so that any inheritable attributes can be inherited. // ----AttributesForAllBases(); // Shadowing semantics needs to be done so that Properties, data members // shadowed by inaccessible members can be assigned to in the attribute // statement. // ResolveShadowingForAllAttributeClassesUsedInContainer(); // ---- Attributes for all symbols in current container. BCSYM_Container *Container = CurrentContainer(); Begin_ForAllSymbolsInContainerWithAttrs(SymbolHavingAttrs, Container, GetDeclaredAttrListHead) { VSASSERT( SymbolHavingAttrs->IsParam() || SymbolHavingAttrs->IsNamedRoot(), "Attributes can only be applied on parameters and named roots!!!"); BCSYM_NamedRoot *NamedContextOfSymbolHavingAttrs = GetNamedContextOfSymbolWithApplAttr(SymbolHavingAttrs); // Allocate space for well known attributes if not already allocated if (!SymbolHavingAttrs->GetPAttrVals()->GetPWellKnownAttrVals()) { WellKnownAttrVals* pWellKnownAttrVals = CurrentAllocator()->Alloc<WellKnownAttrVals>(); pWellKnownAttrVals = new (pWellKnownAttrVals) WellKnownAttrVals(CurrentAllocator()); SymbolHavingAttrs->GetPAttrVals()->SetPWellKnownAttrVals(pWellKnownAttrVals); } Attribute::----AllAttributesOnSymbol( SymbolHavingAttrs, CurrentAllocator(), CurrentCompilerInstance(), CurrentCompilerHost(), CurrentErrorLog(NamedContextOfSymbolHavingAttrs), CurrentSourceFile(NamedContextOfSymbolHavingAttrs)); } End_ForAllSymbolsInContainerWithAttrs if (IsClass(Container)) { InheritWellKnowAttributesFromBases(); DetermineIfAttribute(Container->PClass(), CurrentCompilerHost()); if (IsMyGroupCollection(Container)) { MyGroupCollectionInfo& ff = CurrentSourceFile(Container)->GetProject()->m_daMyGroupCollectionInfo.Add(); ff.m_groupClass = Container->PClass(); ff.m_daMyGroupMembers; CurrentSourceFile(Container)->SetDelayBindingCompletion(true); #if DEBUG VSDEBUGPRINTIF( VSFSWITCH(fMyGroupAndDefaultInst), "MyGroup: adding MyGroup '%S'\n", Container->PClass()->GetName()); #endif } #if DEBUG // in MyGroup trace mode tell why a generic class is ignored as group // make sure to update the condition here if "IsMyGroupCollection" changes else if ( Container->GetPWellKnownAttrVals()->HasMyGroupCollectionData() && !Container->IsPartialType() && IsGenericOrHasGenericParent(Container->PClass())) { VSDEBUGPRINTIF( VSFSWITCH(fMyGroupAndDefaultInst), "MyGroup: Class '%S' is ignored as a group because it is generic\n", Container->PClass()->GetName()); } #endif } SetStatusOf----AttributesOnAllSymbolsInContainer(Done); } bool Bindable::IsMyGroupCollection ( BCSYM_Container *Container ) { return (Container->GetPWellKnownAttrVals()->HasMyGroupCollectionData() && !Container->IsPartialType() && !IsGenericOrHasGenericParent(Container->PClass())); } BCSYM_NamedRoot * Bindable::GetNamedContextOfSymbolWithApplAttr ( BCSYM *SymbolWithApplAttr ) { VSASSERT( SymbolWithApplAttr->GetPAttrVals(), "Expected symbol with attributes!!!"); VSASSERT( SymbolWithApplAttr->IsParam() || SymbolWithApplAttr->IsNamedRoot(), "How can any other kind of symbol have attributes on it ?"); BCSYM_NamedRoot *NamedContextOfSymbolHavingAttrs; if (SymbolWithApplAttr->IsParam()) { // Note: // In the case of partial methods, we may not have a context for // the parameter; in this case, defer to the context of the associated // parameter. This happens if we had to create a fake PAttrVals. NamedContextOfSymbolHavingAttrs = SymbolWithApplAttr->GetPAttrVals()->GetPNon----edData()->m_psymParamContext; #if 0 if( NamedContextOfSymbolHavingAttrs == NULL && SymbolWithApplAttr->PParam()->GetCorrespondingParam() != NULL ) { NamedContextOfSymbolHavingAttrs = SymbolWithApplAttr->PParam()->GetCorrespondingParam()-> GetPAttrVals()->GetPNon----edData()->m_psymParamContext; } #endif } else { NamedContextOfSymbolHavingAttrs = SymbolWithApplAttr->PNamedRoot(); } return NamedContextOfSymbolHavingAttrs; } void Bindable::----AttributesForAllBases() { // We need to ---- attributes for all bases because we need to check if a class // is a valid attribute and what kinds of symbols this can be applied to. // Also need these so that any inheritable attributes can be inherited. // One level of bases is enough, because ----AttributesOnAllSymbolsInContainers recursively // invokes this on its bases. BCSYM_Container *Container = CurrentContainer(); if (!Container->IsClass() && !Container->IsInterface()) { return; } BasesIter Bases(Container); for(BCSYM_Container *Base = Bases.GetNextBase(); Base; Base = Bases.GetNextBase()) { if (Base->IsBad()) { continue; } ----AttributesOnAllSymbolsInContainer(Base, m_CompilationCaches); } } void Bindable::ResolveShadowingForAllAttributeClassesUsedInContainer() { // Shadowing semantics needs to be done so that Properties, data members // shadowed by inaccessible members can be assigned to in the attribute // statement. BCSYM_Container *Container = CurrentContainer(); Begin_ForAllSymbolsInContainerWithAttrs(SymbolHavingAttrs, Container, GetDeclaredAttrListHead) { BCITER_ApplAttrs ApplAttrsIter(SymbolHavingAttrs); while (BCSYM_ApplAttr *AppliedAttribute = ApplAttrsIter.GetNext()) { BCSYM *BoundAttribute = AppliedAttribute->GetAttributeSymbol(); if (BoundAttribute && BoundAttribute->IsContainer()) { ResolveShadowingOverloadingOverridingAndCheckGenericsForContainer(BoundAttribute->PContainer(), m_CompilationCaches); } } } End_ForAllSymbolsInContainerWithAttrs } void Bindable::InheritWellKnowAttributesFromBases() { BCSYM_Container *Container = CurrentContainer(); if (!Container->IsClass()) { return; } BCSYM_Container *Base = Container->PClass()->GetCompilerBaseClass(); if (Base) { InheritWellKnownAttributes(Base); } } /***************************************************************************** ;InheritWellKnownAttributes Recursively gathers all the well-known attributes from the base class and applies them to this class. *****************************************************************************/ void Bindable::InheritWellKnownAttributes ( BCSYM_Container *Base ) { BCSYM_Container *Derived = CurrentContainer(); // // Now update this class' attributes with those from the base class. // AttrVals *BaseAttributeValues; BaseAttributeValues = Base->GetPAttrVals(); // If the base class does not have any attributes, we have nothing to do. if (!BaseAttributeValues) { return; } // // if (!Derived->GetPAttrVals()) { const bool AllocForWellKnownAttributesToo = true; Derived->AllocAttrVals( CurrentAllocator(), CS_Bound, CurrentSourceFile(Derived), Derived, AllocForWellKnownAttributesToo); // } // // Inherit well-known attributes from the base class. // Derived->GetPAttrVals()->GetPWellKnownAttrVals()->InheritFromSymbol(Base); } /***************************************************************************** ;DetermineIfAttribute Run through this class and all its base classes and determine if the class is a custom attribute (i.e., inherits from System.Attribute) or a security attribute (inherits from System.Security.Permissions.SecurityAttribute). *****************************************************************************/ void Bindable::DetermineIfAttribute ( BCSYM_Class *Class, CompilerHost *CompilerHost ) { // start out at the root of the inheritance tree (the most base class) BCSYM_Class *Base = Class->GetCompilerBaseClass(); if (!Base) { return; } if (Base->IsSameContainer(CompilerHost->GetFXSymbolProvider()->GetType(FX::AttributeType)) || Base->IsAttribute()) { Class->SetIsAttribute(true); } // Certain platforms do not support security attributes. if (CompilerHost->GetFXSymbolProvider()->IsTypeAvailable(FX::SecurityAttributeType) && (Base->IsSameContainer(CompilerHost->GetFXSymbolProvider()->GetType(FX::SecurityAttributeType)) || Base->IsSecurityAttribute())) { Class->SetIsSecurityAttribute(true); } } bool IgnoreAttributesOnSymbol ( BCSYM *Symbol ) { // // Ignore all synthetic members except property accessors and user defined event methods (since they may have valid attributes). return Symbol->IsNamedRoot() && Bindable::IsSynthetic(Symbol->PNamedRoot()) && !(Symbol->IsProc() && (Symbol->PProc()->IsPropertyGet() || Symbol->PProc()->IsPropertySet() || (Symbol->PProc()->CreatedByEventDecl() && !Symbol->IsSyntheticMethod()))); } void Bindable::VerifyAttributesOnAllSymbolsInContainer() { VSASSERT( GetStatusOfVerifyAttributesOnAllSymbolsInContainer() != InProgress, "Should never have cyclic dependencies when verifying Attributes!!!"); if (GetStatusOfVerifyAttributesOnAllSymbolsInContainer() == Done) { return; } SetStatusOfVerifyAttributesOnAllSymbolsInContainer(InProgress); VerifyCustomAttributesOnAllSymbolsInContainer(); BCSYM_Container *Container = CurrentContainer(); // check for incorrect usage of well known attributes // Verify attributes applied on each symbol Begin_ForAllSymbolsInContainerWithAttrs(SymbolToCheck, Container, GetDeclaredAttrListHead) { VSASSERT( SymbolToCheck, "How can a symbol without any attributes be on this list?"); if (IgnoreAttributesOnSymbol(SymbolToCheck)) { continue; } // We want to skip any symbols that are partial declarations for methods or params. // This is because they share a common well-known table, and we don't want to // report errors twice. Today, Attribute::VerifyAttributeUsage // does not validate params, but tomorrow it may, so take care here. if( ( SymbolToCheck->IsMethodImpl() && SymbolToCheck->PMethodImpl()->IsPartialMethodDeclaration() && SymbolToCheck->PMethodImpl()->GetAssociatedMethod() != NULL ) || ( SymbolToCheck->IsParam() && SymbolToCheck->PParam()->IsPartialMethodParamDeclaration() && SymbolToCheck->PParam()->GetAssociatedParam() != NULL ) ) { continue; } Attribute::VerifyAttributeUsage ( SymbolToCheck, CurrentErrorLog(GetNamedContextOfSymbolWithApplAttr(SymbolToCheck)), m_CompilerHost ); } End_ForAllSymbolsInContainerWithAttrs // verify attributes obtained during bindable, usually through inheriting inheritable // attribute from the base class // Begin_ForAllSymbolsInContainerWithAttrs(SymbolToCheck, Container, GetBoundAttrListHead) { VSASSERT( SymbolToCheck, "How can a symbol without any attributes be on this list?"); if (IgnoreAttributesOnSymbol(SymbolToCheck)) { continue; } // We want to skip any symbols that are partial declarations for methods or params. // This is because they share a common well-known table, and we don't want to // report errors twice. Today, Attribute::VerifyAttributeUsage // does not validate params, but tomorrow it may, so take care here. if( ( SymbolToCheck->IsMethodImpl() && SymbolToCheck->PMethodImpl()->IsPartialMethodDeclaration() && SymbolToCheck->PMethodImpl()->GetAssociatedMethod() != NULL ) || ( SymbolToCheck->IsParam() && SymbolToCheck->PParam()->IsPartialMethodParamDeclaration() && SymbolToCheck->PParam()->GetAssociatedParam() != NULL ) ) { continue; } Attribute::VerifyAttributeUsage ( SymbolToCheck, CurrentErrorLog(GetNamedContextOfSymbolWithApplAttr(SymbolToCheck)), m_CompilerHost ); } End_ForAllSymbolsInContainerWithAttrs SetStatusOfVerifyAttributesOnAllSymbolsInContainer(Done); } void Bindable::VerifyCustomAttributesOnAllSymbolsInContainer() { BCSYM_Container *Container = CurrentContainer(); Begin_ForAllSymbolsInContainerWithAttrs(SymbolHavingAttrs, Container, GetDeclaredAttrListHead) { VSASSERT( SymbolHavingAttrs, "How can a symbol without any attributes be on this list?"); BCSYM_NamedRoot *NamedContext = GetNamedContextOfSymbolWithApplAttr(SymbolHavingAttrs); if (IgnoreAttributesOnSymbol(SymbolHavingAttrs)) { continue; } VerifyCustomAttributesOnSymbol( SymbolHavingAttrs, CurrentErrorLog(NamedContext), CurrentSourceFile(NamedContext)); } End_ForAllSymbolsInContainerWithAttrs } /***************************************************************************** ;VerifyCustomAttributes Verifies that the custom attributes on pSymbol are classes and are valid to be used as attributes and also that they can be applied to pSymbol. Assembly- and module-level attributes are stored on the SourceFile's UnnamedNamespace. This is the only time we need the pSourceFile param to be non-NULL. *****************************************************************************/ void Bindable::VerifyCustomAttributesOnSymbol ( BCSYM * pSymbol, ErrorTable *pErrorTable, SourceFile *pSourceFile ) { if (!pSymbol) { return; // Nothing to verify! } VSASSERT( pSymbol->IsNamedRoot() || pSymbol->IsParam(), "Bad symbol!"); if (!pSymbol->GetPAttrVals()) { return; } Compiler * pCompiler = pSourceFile->GetCompiler();; NorlsAllocator scratch(NORLSLOC); Declaration * pExtensionAttribute = Semantics::GetExtensionAttributeClass ( pCompiler, pSourceFile->GetCompilerHost(), pSourceFile, &scratch, NULL ); BCITER_ApplAttrs ApplAttrsIter(pSymbol); while (BCSYM_ApplAttr * pAttributeSymbol = ApplAttrsIter.GetNext()) { if ( pAttributeSymbol->GetAttributeSymbol() == pExtensionAttribute && pSymbol->IsProc() ) { continue; } // We need to ---- attributes for all classes used as attributes in this class // because we need to check if a class is a valid attribute and what kind // of symbols this can be applied to. Needed for validation purposes. // if (IsClass(pAttributeSymbol->GetAttributeSymbol())) { BCSYM_Class *pAppliedAttributeClass = pAttributeSymbol->GetAttributeSymbol()->PClass(); ----AttributesOnAllSymbolsInContainer(pAppliedAttributeClass, m_CompilationCaches); } if (pAttributeSymbol->GetAttrClass()->DigThroughNamedType()->IsBad()) { continue; } if (!pAttributeSymbol->GetAttrClass()->DigThroughNamedType()->IsClass() || pAttributeSymbol->GetAttrClass()->DigThroughNamedType()->PClass()->IsEnum()) { ReportErrorOnSymbol( ERRID_AttributeMustBeClassNotStruct1, CurrentErrorLog(pAttributeSymbol->GetAttrClass()), pAttributeSymbol, pAttributeSymbol->GetAttrClass()->GetErrorName(CurrentCompilerInstance())); continue; } BCSYM_Class * pAttributeClass = pAttributeSymbol->GetAttributeSymbol()->PClass(); // AnthonyL: Check if the attribute class can be applied to the symbol and if multiple applications are present and valid. // Note that error reporting is done in IsValidAttributeClass // if (!pAttributeClass->IsValidAttributeClass(pErrorTable, pAttributeSymbol)) { continue; } CorAttributeTargets Targets; bool AllowMultipleUse; bool IsInherited; bool IsOnAssemblyOrModule; // // See if we're dealing with an assembly- or module-level attribute // IsOnAssemblyOrModule = pSourceFile != NULL && pSymbol == pSourceFile->GetRootNamespace(); // // Check if the attribute class can be applied to the symbol. // pAttributeClass->GetPWellKnownAttrVals()->GetAttributeUsageData( &Targets, &AllowMultipleUse, &IsInherited); bool IsApplicationValid = false; if (( Targets & catClass) && (pSymbol->IsClass() && !pSymbol->IsDelegate() && !pSymbol->IsStruct())) { IsApplicationValid = true; } else if (( Targets & catStruct) && pSymbol->IsStruct()) { IsApplicationValid = true; } else if (( Targets & catEnum) && pSymbol->IsEnum()) { IsApplicationValid = true; } else if (( Targets & catConstructor) && ( pSymbol->IsProc() && pSymbol->PProc()->IsAnyConstructor())) { IsApplicationValid = true; } else if ((Targets & catMethod) && (pSymbol->IsProc() && !pSymbol->IsProperty() && !pSymbol->PProc()->IsAnyConstructor() && !pSymbol->IsEventDecl())) { IsApplicationValid = true; } else if ((Targets & catProperty) && pSymbol->IsProperty()) { IsApplicationValid = true; } else if ((Targets & catField) && (pSymbol->IsMember() && !pSymbol->IsProc())) { IsApplicationValid = true; } // The following condition allows NonSerialized attribute being applied on event. (Bug674331) else if (((Targets & catEvent) || (pAttributeSymbol->GetAttrIndex() && pAttributeSymbol->GetAttrIndex()->Attributes[0].m_attrkind == attrkindNonSerialized_Void)) && pSymbol->IsEventDecl()) { IsApplicationValid = true; } else if ((Targets & catInterface) && pSymbol->IsInterface()) { IsApplicationValid = true; } else if ((Targets & catParameter) && pSymbol->IsParam()&& !pSymbol->PParam()->IsReturnType()) { IsApplicationValid = true; } else if ((Targets & catReturnValue) && pSymbol->IsParam() && pSymbol->PParam()->IsReturnType()) { IsApplicationValid = true; } else if ((Targets & catDelegate) && pSymbol->IsDelegate()) { IsApplicationValid = true; } else if ((Targets & catAssembly) && pAttributeSymbol->IsAssembly()) { IsApplicationValid = true; } else if ((Targets & catModule) && pAttributeSymbol->IsModule()) { IsApplicationValid = true; } if ( !IsApplicationValid ) { if (IsOnAssemblyOrModule) { // Special case: Target was assembly or module, but the // symbol the attribute is attached to has no name. // Emit a special error in this case. if (pAttributeSymbol->IsAssembly()) { ReportErrorOnSymbol( ERRID_InvalidAssemblyAttribute1, CurrentErrorLog(pAttributeSymbol->GetAttrClass()), pAttributeSymbol, pAttributeClass->GetName()); } else if (pAttributeSymbol->IsModule()) { ReportErrorOnSymbol( ERRID_InvalidModuleAttribute1, CurrentErrorLog(pAttributeSymbol->GetAttrClass()), pAttributeSymbol, pAttributeClass->GetName()); } } else { // Normal case: Attribute can't be applied to this symbol ReportErrorOnSymbol( ERRID_InvalidAttributeUsage2, CurrentErrorLog(pAttributeSymbol->GetAttrClass()), pAttributeSymbol, pAttributeClass->GetName(), pSymbol->IsNamedRoot() ? pSymbol->GetErrorName(CurrentCompilerInstance()) : pSymbol->PParam()->GetName()); } } if (pAttributeClass == CurrentCompilerHost()->GetFXSymbolProvider()->GetType(FX::CLSCompliantAttributeType) && pSymbol->IsProc() && (pSymbol->PProc()->IsPropertyGet() || pSymbol->PProc()->IsPropertySet())) { // Warning and not error because this was permitted in RTM and Everett. // "System.CLSCompliantAttribute cannot be applied to property 'Get'/'Set'. ReportErrorOnSymbol( WRNID_CLSAttrInvalidOnGetSet, CurrentErrorLog(pAttributeSymbol->GetAttrClass()), pAttributeSymbol); } // Report error if an async method is annotated by SecurityCritical attribute or SecuritySafeCritical attribute, // CheckSecurityCriticalAttributeOnParentOfAysnc also reports error if an async method is in a container // which is annotated by SecurityCritical or SecuritySafeCritical attribute if (pSymbol->IsProc() && (pSymbol->PProc()->IsAsyncKeywordUsed() || pSymbol->PProc()->IsIteratorKeywordUsed())) { if (pAttributeClass == CurrentCompilerHost()->GetFXSymbolProvider()->GetType(FX::SecurityCriticalAttributeType)) { ReportErrorOnSymbol( ERRID_SecurityCriticalAsync, CurrentErrorLog(pAttributeSymbol->GetAttrClass()), pAttributeSymbol, L"SecurityCritical" ); } if (pAttributeClass == CurrentCompilerHost()->GetFXSymbolProvider()->GetType(FX::SecuritySafeCriticalAttributeType)) { ReportErrorOnSymbol( ERRID_SecurityCriticalAsync, CurrentErrorLog(pAttributeSymbol->GetAttrClass()), pAttributeSymbol, L"SecuritySafeCritical" ); } } // // Check if multiple applications are present and valid. // if (!AllowMultipleUse) { CheckForMultipleUsesOfAttribute( pSymbol, pAttributeSymbol, pAttributeClass); } } } void Bindable::CheckForMultipleUsesOfAttribute ( BCSYM *SymbolHavingAttrs, BCSYM_ApplAttr *AppliedAttributeSymbol, BCSYM_Class *AttributeClassToCheckFor ) { if (AppliedAttributeSymbol->IsBad()) { return; } BCSYM *SymbolWithAttributesToCheckAgainst = SymbolHavingAttrs->IsNamespace() ? SymbolHavingAttrs->PNamespace()->GetNextNamespaceInSameProject() : SymbolHavingAttrs; // For partial methods, the attribute walker invalidates the loop below, because we will // always find the same attribute first. Therefore, here, when validating attributes, // if we are the implementation, select the partial declaration as the location to start. This // will ensure that we don't start validating at the same attribute that we are checking. if( SymbolWithAttributesToCheckAgainst->IsMethodImpl() ) { if( SymbolWithAttributesToCheckAgainst->PMethodImpl()->IsPartialMethodImplementation() ) { SymbolWithAttributesToCheckAgainst = SymbolWithAttributesToCheckAgainst->PMethodImpl()->GetAssociatedMethod(); } } else if( SymbolWithAttributesToCheckAgainst->IsParam() ) { if( SymbolWithAttributesToCheckAgainst->PParam()->IsPartialMethodParamImplementation() ) { SymbolWithAttributesToCheckAgainst = SymbolWithAttributesToCheckAgainst->PParam()->GetAssociatedParam(); } } do { const bool LookOnlyInImmediatePartialContainer = true; BCITER_ApplAttrs ApplAttrsIter(SymbolWithAttributesToCheckAgainst, !LookOnlyInImmediatePartialContainer); while (BCSYM_ApplAttr *pAttributeSymbolTemp = ApplAttrsIter.GetNext()) { if (pAttributeSymbolTemp->IsBad()) { continue; } if (pAttributeSymbolTemp == AppliedAttributeSymbol) { // If reached here, then no error i.e. not applied multiple times // if (AttributeClassToCheckFor == CurrentCompilerHost()->GetFXSymbolProvider()->GetType(FX::CLSCompliantAttributeType) && SymbolHavingAttrs->IsNamespace()) { // Assembly level CLS Compliant attribute BCSYM_Namespace *Namespace = SymbolHavingAttrs->PNamespace(); VSASSERT( Namespace->GetSourceFile(), "Metadata symbol unexpected here!!!"); CompilerProject *CurrentProject = Namespace->GetSourceFile()->GetProject(); VSASSERT( CurrentProject, "How can a sourcefile not be in any project ?"); if ((AppliedAttributeSymbol->IsAssembly() && !CurrentProject->OutputIsModule()) || (AppliedAttributeSymbol->IsModule() && CurrentProject->OutputIsModule())) { bool IsCompliant; Namespace->GetPWellKnownAttrVals()->GetCLSCompliantData(&IsCompliant); // Propagate the Project level setting from the namespace to the Project CurrentProject->SetProjectClaimsCLSCompliance(IsCompliant); #if IDE // Needed for decompilation CurrentProject->SetFileThatCausedProjectsCLSComplianceClaim(Namespace->GetCompilerFile()); #endif } } return; } // Need to handle case where pAttributeCompare is not a class. In that // case, an error has already been reported, so just ignore it. BCSYM *pAttributeCompare = pAttributeSymbolTemp->GetAttrClass()->DigThroughNamedType(); BCSYM_Class *pAttributeClassCompare = pAttributeCompare->IsClass() ? pAttributeCompare->PClass() : NULL; if (AttributeClassToCheckFor == pAttributeClassCompare) { // // Need to handle the case where both module- and assembly-level // attributes end up on the same symbol. This is not an error // if one is on the assembly and the other is on the module. // // Note that a given symbol can hold either assembly/module // attributes or attributes with "real" targets, but no symbol // can hold a mixture of both. We use fAnyAssemblyOrModuleAttrs // to decide which case we're dealing with. // // This check will miss duplicate assembly- and // module-level attributes that are used in different files, // but ALink will catch those in MetaEmit::ALinkEmitAssemblyAttributes. // bool fAnyAssemblyOrModuleAttrs = AppliedAttributeSymbol->IsAssembly() | pAttributeSymbolTemp->IsAssembly() | AppliedAttributeSymbol->IsModule() | pAttributeSymbolTemp->IsModule(); if (!fAnyAssemblyOrModuleAttrs || (AppliedAttributeSymbol->IsModule() && pAttributeSymbolTemp->IsModule()) || (AppliedAttributeSymbol->IsAssembly() && pAttributeSymbolTemp->IsAssembly())) { ReportErrorOnSymbol( ERRID_InvalidMultipleAttributeUsage1, CurrentErrorLog(AppliedAttributeSymbol->GetAttrClass()), AppliedAttributeSymbol, AttributeClassToCheckFor->GetName()); AppliedAttributeSymbol->SetIsBad(); return; } } } VSASSERT( SymbolWithAttributesToCheckAgainst == SymbolHavingAttrs || SymbolWithAttributesToCheckAgainst->IsNamespace(), "No other symbol besides a namespace should be traversed in this way!!!"); } while (SymbolWithAttributesToCheckAgainst != SymbolHavingAttrs && (SymbolWithAttributesToCheckAgainst = SymbolWithAttributesToCheckAgainst->PNamespace()->GetNextNamespaceInSameProject())); } /***************************************************************************** ;GetSimilarKind Some symbols can be considered as generally equivalent for some situations - this 'normalizes' those symbols. *****************************************************************************/ BilKind // the 'normalized' symbol Bindable::GetSimilarKind ( BilKind SymbolKind // [in] the symbol to normalize ) { switch ( SymbolKind ) { case SYM_MethodDecl: // method decls and method impls will be 'equivalent' return SYM_MethodImpl; default: return SymbolKind; } } bool // true - PossiblyDerived derives from Base / false otherwise Bindable::DerivesFrom ( BCSYM_Container *PossiblyDerived, // [in] does this thing derive from Base? BCSYM_Container *Base // [in] the base class ) { VSASSERT( Base && PossiblyDerived, "Non-NULL base and derived expected!!!"); // clearly they aren't derived from each other // if (Base->IsSameContainer(PossiblyDerived)) { return false; } // classes can't derive from interfaces, etc. so these aren't related by inheritance if (Base->IsClass() != PossiblyDerived->IsClass()) { return false; } if (Base->IsClass()) { while (PossiblyDerived = PossiblyDerived->PClass()->GetCompilerBaseClass()) { if (Base->IsSameContainer(PossiblyDerived)) { return true; } } return false; } // Interface return PossiblyDerived->PInterface()->DerivesFrom( CurrentCompilerInstance(), Base->PInterface()); } /************************************************************************************************** ;IsGuyShadowed Determine whether a member was shadowed by another member ***************************************************************************************************/ bool Bindable::IsMemberShadowed ( BCSYM_NamedRoot *Member, // [in] is this Member shadowed MembersHashTable *ShadowingMembers // [in] hash of accessible members that shadow other members ) { BCSYM_NamedRoot *PossibleShadowingMember = ShadowingMembers->Find(Member->GetName()); BCSYM_Container *ContainerOfMember = Member->GetContainer(); while (PossibleShadowingMember) { if (DerivesFrom(PossibleShadowingMember->GetContainer(), ContainerOfMember)) { return true; } PossibleShadowingMember = ShadowingMembers->FindNextOfSameName(); } return false; } void Bindable::ScanContainerForObsoleteUsage(bool NeedToCheckObsolete) { VSASSERT( GetStatusOfScanContainerForObsoleteUsage() != InProgress, "Circular dependencies unexpected here!!!"); if (GetStatusOfScanContainerForObsoleteUsage() == Done) { return; } SetStatusOfScanContainerForObsoleteUsage(InProgress); for(BCSYM_Container *PartialContainer = CurrentContainer(); PartialContainer; PartialContainer = PartialContainer->GetNextPartialType()) { ObsoleteChecker checker(CurrentSourceFile(PartialContainer), CurrentErrorLog(PartialContainer)); checker.CheckForLongFullyQualifiedNames(PartialContainer); checker.ScanContainerForObsoleteUsage(PartialContainer, NeedToCheckObsolete); } // Complete any obsolete checks that semantics helpers triggered but could not // be completed because attribute cracking was not guaranteed to be completed // at that time. // if (NeedToCheckObsolete && m_DelayedCheckManager) { m_DelayedCheckManager->CompleteDelayedObsoleteChecks(); } SetStatusOfScanContainerForObsoleteUsage(Done); } // Complete result type accessibility checks that semantics helpers registered but // that we could not verify due to the fact that for that we need to dig through // named types which is not possible if we haven't resolved projectlevelimports // and application objects. void Bindable::ScanContainerForResultTypeChecks ( ) { if (m_DelayedCheckManager) { m_DelayedCheckManager->CompleteDelayedResultTypeChecks(); } } bool Bindable::SourceFilesOfContainerHaveErrorsInCurrentCompilerStep() { VSASSERT(!CurrentContainer()->IsPartialTypeAndHasMainType(), "Unexepected partial type!!!"); for(BCSYM_Container *Container = CurrentContainer(); Container; Container = Container->GetNextPartialType()) { ErrorTable *ErrorLog = CurrentErrorLog(Container); SourceFile *SourceFile = CurrentSourceFile(Container); if (!ErrorLog || !SourceFile) { continue; } if (ErrorLog->HasErrors() || SourceFile->HasActiveErrors()) { return true; } } return false; } // Use ResolveNamedTypeAndTypeArguments instead of ResolveNamedType in cases where the argument // types of generic bindings do not appear on a type list and so will not naturally be bound. void Bindable::ResolveNamedTypeAndTypeArguments ( BCSYM_NamedType *NamedType, // [in] the named type to resolve TypeResolutionFlags Flags, NameFlags NameInterpretFlags, bool DisableNameLookupCaching ) { // Resolve the type arguments // ResolveTypeArguments( NamedType->GetArgumentsArray(), NamedType->GetNameCount(), CurrentErrorLog(NamedType), CurrentSourceFile(NamedType->GetContext()), Flags, NameInterpretFlags, DisableNameLookupCaching); // Resolve the named type // ResolveNamedType( NamedType, Flags, NameInterpretFlags, DisableNameLookupCaching); } void Bindable::ResolveTypeArguments ( NameTypeArguments **ArgumentsArray, unsigned NumberOfArguments, ErrorTable *ErrorLog, SourceFile *CurrentSourceFile, TypeResolutionFlags Flags, NameFlags NameInterpretFlags, bool DisableNameLookupCaching ) { if (!ArgumentsArray) { return; } bool HasGenericArguments = false; ResolveTypeArguments( ArgumentsArray, NumberOfArguments, CurrentAllocator(), ErrorLog, CurrentCompilerInstance(), CurrentCompilerHost(), CurrentSourceFile, // Don't perform obsolete checks. Will do the // obsolete checking for the whole container later. Flags & ~TypeResolvePerformObsoleteChecks, m_CompilationCaches, NameInterpretFlags, DisableNameLookupCaching, HasGenericArguments); } void Bindable::ResolveTypeArguments ( NameTypeArguments **ArgumentsArray, unsigned NumberOfArguments, NorlsAllocator *Allocator, // [in] for the Binder - may be NULL if no generic bindings occur in the type ErrorTable *ErrorLog, // [in] the error log to put our errors into - NULL if we are importing metadata Compiler *CompilerInstance, // [in] the current context CompilerHost *CompilerHost, // [in] the compilerhost SourceFile *CurrentSourceFile, // [in] the current file TypeResolutionFlags Flags, // [in] indicates how to resolve the type CompilationCaches *IDECompilationCaches, NameFlags NameInterpretFlags, // [in] indicates the name binding bool DisableNameLookupCaching, // [in] indicates that name look up caching in semantics helpers should be disabled bool &HasGenericArgument ) { if (!ArgumentsArray) { return; } for (unsigned ArgumentsIndex = 0; ArgumentsIndex < NumberOfArguments; ArgumentsIndex++) { NameTypeArguments *Arguments = ArgumentsArray[ArgumentsIndex]; if (!Arguments) { continue; } for (unsigned ArgumentIndex = 0; ArgumentIndex < Arguments->m_ArgumentCount; ArgumentIndex++) { BCSYM *ArgumentType = Arguments->m_Arguments[ArgumentIndex]; HasGenericArgument = true; if (!ArgumentType) { continue; } ArgumentType = ArgumentType->ChaseToNamedType(); VSASSERT(ArgumentType, "Non-NULL result expected!!!"); if (ArgumentType->IsNamedType()) { // Resolve the type arguments // ResolveTypeArguments( ArgumentType->PNamedType()->GetArgumentsArray(), ArgumentType->PNamedType()->GetNameCount(), Allocator, ErrorLog, CompilerInstance, CompilerHost, CurrentSourceFile, Flags, IDECompilationCaches, NameInterpretFlags, DisableNameLookupCaching, HasGenericArgument); // Resolve the named type // ResolveNamedType( ArgumentType->PNamedType(), Allocator, ErrorLog, CompilerInstance, CompilerHost, CurrentSourceFile, Flags, IDECompilationCaches, NameInterpretFlags, DisableNameLookupCaching); } } } } void Bindable::ResolveBaseType ( BCSYM_NamedType *Type ) { // ResolveNamedTypeAndTypeArguments( Type, TypeResolveNoFlags, NameSearchIgnoreImmediateBases, // disable name look up caching because a base and a member type in the same context // might bind to different symbols. This could happen because the base is resolved before // any nested classes' bases are resolved whereas member types are resolved afterward. // true); } UserDefinedOperators MapToMatching ( UserDefinedOperators Input ) { // Given an operator that requires pair-wise declaration, return its matching operator. switch (Input) { case OperatorIsTrue: return OperatorIsFalse; case OperatorIsFalse: return OperatorIsTrue; case OperatorEqual: return OperatorNotEqual; case OperatorNotEqual: return OperatorEqual; case OperatorLess: return OperatorGreater; case OperatorLessEqual: return OperatorGreaterEqual; case OperatorGreaterEqual: return OperatorLessEqual; case OperatorGreater: return OperatorLess; default: VSFAIL("didn't expect this operator"); return Input; } } void Bindable::VerifyOperatorsInContainer() { VSASSERT(GetStatusOfVerifyOperatorsInContainer() != InProgress, "Circular dependencies unexpected here!!!"); VSASSERT(!CurrentContainer()->IsPartialTypeAndHasMainType(), "partial types aren't allowed in here"); if (GetStatusOfVerifyOperatorsInContainer() == Done) { return; } SetStatusOfVerifyOperatorsInContainer(InProgress); if (CurrentContainer()->HasUserDefinedOperators() && !IsStdModule(CurrentContainer())) { NorlsAllocator Scratch(NORLSLOC); RelationalOperatorPool Pool(Scratch); Symbols SymbolFactory( CurrentCompilerInstance(), CurrentAllocator(), NULL, CurrentGenericBindingCache()); BCSYM *InstanceTypeForMemberContainer = IsGenericOrHasGenericParent(CurrentContainer()) ? (BCSYM *)SynthesizeOpenGenericBinding( CurrentContainer(), SymbolFactory) : CurrentContainer(); // Walk over every member and perform semantic checks on the operators only. BCITER_CHILD Members(CurrentContainer()); while (BCSYM_NamedRoot *Member = Members.GetNext()) { if (Member->IsProc() && !Member->IsBad() && Member->PProc()->IsUserDefinedOperatorMethod() && !Member->PMethodDecl()->GetAssociatedOperatorDef()->IsBad()) { VerifyOperator( Member->PMethodDecl()->GetAssociatedOperatorDef(), InstanceTypeForMemberContainer, &Pool, &SymbolFactory); } } // Give errors for unmatched operators that require pair-wise declaration. CSingleListIter<OperatorInfo> Iter(Pool.CollateUnmatchedOperators()); while (OperatorInfo *Current = Iter.Next()) { StringBuffer ErrorReplString; GetBasicRep(Current->Symbol, &ErrorReplString); ReportErrorOnSymbol( ERRID_MatchingOperatorExpected2, CurrentErrorLog(Current->Symbol), Current->Symbol, CurrentCompilerInstance()->OperatorToString(MapToMatching(Current->Symbol->GetOperator())), ErrorReplString.GetString()); } } SetStatusOfVerifyOperatorsInContainer(Done); } void Bindable::VerifyOperator ( BCSYM_UserDefinedOperator *Member, BCSYM *InstanceTypeForMemberContainer, RelationalOperatorPool *Pool, Symbols *SymbolFactory ) { VSASSERT((OperatorUNDEF < Member->GetOperator()) && (Member->GetOperator() < OperatorMAXVALID), "invalid operator kind"); VSASSERT(Member->GetType() && Member->GetRawType(), "all operators must have a return type"); UserDefinedOperators Operator = Member->GetOperator(); bool HasContainingTypeParam = false; // Check if one of the parameter types is the defining container. unsigned int ParameterCount = 0; BCSYM_Param *Parameter = Member->GetFirstParam(); while (Parameter) { VSASSERT(!Parameter->IsBad() && !Parameter->IsBadParam(), "if we get this far, we shouldn't see bad params"); ParameterCount++; if (BCSYM::AreTypesEqual(Parameter->GetType(), InstanceTypeForMemberContainer) || (TypeHelpers::IsNullableType(Parameter->GetType(), CurrentCompilerHost()) && BCSYM::AreTypesEqual(TypeHelpers::GetElementTypeOfNullable(Parameter->GetType(),CurrentCompilerHost()), InstanceTypeForMemberContainer))) { HasContainingTypeParam = true; } Parameter = Parameter->GetNext(); } VSASSERT((IsUnaryOperator(Operator) && ParameterCount == 1) || (IsBinaryOperator(Operator) && ParameterCount == 2), "malformed operator - how did this survive Declared?"); // // The return type of conversion operators can also be the defining container. if (IsConversionOperator(Operator) && (BCSYM::AreTypesEqual(Member->GetType(), InstanceTypeForMemberContainer) || (TypeHelpers::IsNullableType(Member->GetType(), CurrentCompilerHost()) && BCSYM::AreTypesEqual(TypeHelpers::GetElementTypeOfNullable(Member->GetType(),CurrentCompilerHost()), InstanceTypeForMemberContainer)))) { HasContainingTypeParam = true; } if ((Operator == OperatorIsTrue || Operator == OperatorIsFalse) && !TypeHelpers::IsBooleanType(Member->GetType())) { // Named types for intrinsics don't occur, so we have no location info for them. Location *ErrorLocation = Member->GetRawType()->GetLocation() ? Member->GetRawType()->GetLocation() : Member->GetLocation(); ReportErrorAtLocation( ERRID_OperatorRequiresBoolReturnType1, CurrentErrorLog(Member), ErrorLocation, Member->GetName()); Member->SetIsBad(); if (HasContainingTypeParam) { // No more useful errors to display, so just exit. return; } } if (Operator == OperatorShiftLeft || Operator == OperatorShiftRight) { Type *SecondParamType = Member->GetFirstParam()->GetNext()->GetRawType(); // NULL??? Type * ActualSecondParamType = SecondParamType->DigThroughNamedType(); Type * NullableElementType = TypeHelpers::GetElementTypeOfNullable(ActualSecondParamType, m_CompilerHost); if ( !TypeHelpers::IsIntegerType(ActualSecondParamType) && ( !NullableElementType || !TypeHelpers::IsIntegerType(NullableElementType) ) ) { // Named types for intrinsics don't occur, so we have no location info for them. Location *ErrorLocation = SecondParamType->GetLocation() ? SecondParamType->GetLocation() : Member->GetLocation(); ReportErrorAtLocation( ERRID_OperatorRequiresIntegerParameter1, CurrentErrorLog(Member), ErrorLocation, Member->GetName()); Member->SetIsBad(); if (HasContainingTypeParam) { // No more useful errors to display, so just exit. return; } } } if (!HasContainingTypeParam) { // Named types for intrinsics don't occur, so we have no location info for them. Location *ErrorLocation = IsBinaryOperator(Operator) || IsConversionOperator(Operator) ? Member->GetLocation() : Member->GetFirstParam()->GetRawType()->GetLocation() ? Member->GetFirstParam()->GetRawType()->GetLocation() : Member->GetLocation(); ReportErrorAtLocation( IsBinaryOperator(Operator) ? ERRID_BinaryParamMustBeContainingType1 : IsConversionOperator(Operator) ? ERRID_ConvParamMustBeContainingType1 : ERRID_UnaryParamMustBeContainingType1, CurrentErrorLog(Member), ErrorLocation, InstanceTypeForMemberContainer); Member->SetIsBad(); return; } // Now we can perform conversion operator specific checks. if (IsConversionOperator(Operator)) { VSASSERT(IsConversionOperator(Member), "expected conversion operator"); Type *TargetType = Member->GetType(); Type *SourceType = Member->GetFirstParam()->GetType(); // Named types for intrinsics don't occur, so we have no location info for them. Location *TargetLocation = Member->GetRawType()->GetLocation() ? Member->GetRawType()->GetLocation() : Member->GetLocation(); Location *SourceLocation = Member->GetFirstParam()->GetRawType()->GetLocation() ? Member->GetFirstParam()->GetRawType()->GetLocation() : Member->GetLocation(); VSASSERT(BCSYM::AreTypesEqual(TargetType, InstanceTypeForMemberContainer) || (TypeHelpers::IsNullableType(TargetType, CurrentCompilerHost()) && BCSYM::AreTypesEqual(TypeHelpers::GetElementTypeOfNullable(TargetType,CurrentCompilerHost()), InstanceTypeForMemberContainer)) || BCSYM::AreTypesEqual(SourceType, InstanceTypeForMemberContainer) || (TypeHelpers::IsNullableType(SourceType, CurrentCompilerHost()) && BCSYM::AreTypesEqual(TypeHelpers::GetElementTypeOfNullable(SourceType,CurrentCompilerHost()), InstanceTypeForMemberContainer)), "expected containing type"); // if (TypeHelpers::IsRootObjectType(SourceType)) { ReportErrorAtLocation(ERRID_ConversionFromObject, CurrentErrorLog(Member), SourceLocation); Member->SetIsBad(); return; } if (TypeHelpers::IsRootObjectType(TargetType)) { ReportErrorAtLocation(ERRID_ConversionToObject, CurrentErrorLog(Member), TargetLocation); Member->SetIsBad(); return; } if (TypeHelpers::IsInterfaceType(SourceType)) { ReportErrorAtLocation(ERRID_ConversionFromInterfaceType, CurrentErrorLog(Member), SourceLocation); Member->SetIsBad(); return; } if (TypeHelpers::IsInterfaceType(TargetType)) { ReportErrorAtLocation(ERRID_ConversionToInterfaceType, CurrentErrorLog(Member), TargetLocation); Member->SetIsBad(); return; } if (TypeHelpers::EquivalentTypes(TypeHelpers::GetElementTypeOfNullable(TargetType,CurrentCompilerHost()), TypeHelpers::GetElementTypeOfNullable(SourceType,CurrentCompilerHost()))) { ReportErrorOnSymbol(ERRID_ConversionToSameType, CurrentErrorLog(Member), Member); Member->SetIsBad(); return; } if ((TypeHelpers::IsClassOrRecordType(SourceType) || SourceType->IsGenericParam()) && TypeHelpers::IsClassOrRecordType(TargetType) || TargetType->IsGenericParam()) { const bool ChaseThroughGenericBindings = true; if (TypeHelpers::IsOrInheritsFrom(TargetType, SourceType, *SymbolFactory, !ChaseThroughGenericBindings, NULL)) { ReportErrorOnSymbol( BCSYM::AreTypesEqual(TargetType, InstanceTypeForMemberContainer) ? ERRID_ConversionFromBaseType : ERRID_ConversionToDerivedType, CurrentErrorLog(Member), Member); Member->SetIsBad(); return; } if (TypeHelpers::IsOrInheritsFrom(SourceType, TargetType, *SymbolFactory, !ChaseThroughGenericBindings, NULL)) { ReportErrorOnSymbol( BCSYM::AreTypesEqual(TargetType, InstanceTypeForMemberContainer) ? ERRID_ConversionFromDerivedType : ERRID_ConversionToBaseType, CurrentErrorLog(Member), Member); Member->SetIsBad(); return; } } // Interestingly, by this point all predefined conversions have been ruled out. VSASSERT( Semantics::ClassifyPredefinedConversion(TargetType, SourceType, CurrentCompilerHost()) == ConversionError, "surprising conversion operator"); } Pool->Add(Operator, Member); return; } inline GenericBindingCache* Bindable::CurrentGenericBindingCache() { return m_CurrentContainerContext->GetCompilerFile() ? m_CurrentContainerContext->GetCompilerFile()->GetCurrentGenericBindingCache() : NULL; } ErrorTable * Bindable::CurrentErrorLog ( BCSYM *Symbol, BCSYM_NamedRoot *NamedRootContext ) { VSASSERT(Symbol, "Error table request for NULL symbol unexpected!!!"); if (Symbol->IsNamedRoot()) { return CurrentErrorLog(Symbol->PNamedRoot()); } if (Symbol->IsNamedType()) { return CurrentErrorLog(Symbol->PNamedType()); } if (Symbol->IsArrayType()) { return CurrentErrorLog(Symbol->PArrayType()->GetRawRoot(), NamedRootContext); } return CurrentErrorLog(NamedRootContext); }
35.654042
298
0.601083
csoap
ba7dfb91ad45e3637a3bbe86c2ca62a787ec2037
1,147
cpp
C++
app/src/main/jni/game/render/font_android.cpp
zork/tictactoe
0baa883e12c43e8d9bde2b54ec3265f5d65d444d
[ "MIT" ]
6
2018-05-08T22:28:29.000Z
2020-08-13T17:06:00.000Z
app/src/main/jni/game/render/font_android.cpp
zork/tictactoe
0baa883e12c43e8d9bde2b54ec3265f5d65d444d
[ "MIT" ]
null
null
null
app/src/main/jni/game/render/font_android.cpp
zork/tictactoe
0baa883e12c43e8d9bde2b54ec3265f5d65d444d
[ "MIT" ]
1
2020-08-13T17:06:38.000Z
2020-08-13T17:06:38.000Z
//// // font_android.cpp //// #include "game/render/font.h" #include "base/image/bitmap.h" #include "platform/android/android.h" namespace font { void DrawText(Bitmap* image, const std::string& text, int font_size, float color[], ui::View::HAlign halign, ui::View::VAlign valign) { JNIEnv* env = android::GetJNIEnv(); jclass text_draw_class = env->FindClass("com/zork/common/image/TextDraw"); jmethodID draw_text = env->GetStaticMethodID( text_draw_class, "DrawText", "(Ljava/lang/String;IFFFFIIIIJ)V"); env->CallStaticVoidMethod( text_draw_class, draw_text, env->NewStringUTF(text.c_str()), font_size, color[0], color[1], color[2], color[3], image->width(), image->height(), halign, valign, (jlong)image->image_data()); } } // namespace font extern "C" { void Java_com_zork_common_image_TextDraw_nativeOnTextDone( JNIEnv* env, jclass, jintArray image_data, jlong image_ptr) { jint* image = (jint*)image_ptr; jsize size = env->GetArrayLength(image_data); env->GetIntArrayRegion(image_data, 0, size, image); } }
27.97561
78
0.655623
zork
ba7efd6734b747a9b4b67cea18dad0bf5bbb324d
18,120
cxx
C++
weighters/weight_fsi_cai.cxx
MinervaExpt/MAT-MINERvA
a142702563260d8f21c1dbd7b739364823ad38e7
[ "MIT" ]
null
null
null
weighters/weight_fsi_cai.cxx
MinervaExpt/MAT-MINERvA
a142702563260d8f21c1dbd7b739364823ad38e7
[ "MIT" ]
4
2021-08-31T17:17:12.000Z
2021-10-29T19:41:39.000Z
weighters/weight_fsi_cai.cxx
MinervaExpt/MAT-MINERvA
a142702563260d8f21c1dbd7b739364823ad38e7
[ "MIT" ]
null
null
null
#include "weighters/weight_fsi_cai.h" using namespace PlotUtils; void weight_fsi_cai::read(const TString f) //Read in the params doubles from a file //argument: valid filename { if(f!="") { fFSIWeight = TFile::Open(f,"READONLY"); if (fFSIWeight){ hElaFSIWeight = (TH1D*) fFSIWeight->Get("weight_elastic_fsi"); hNoFSIWeight = (TH1D*) fFSIWeight->Get("weight_no_fsi"); std::cout << "have read in weights from file " << f <<std::endl; } else{ //File could not be read std::cout << "File could not be read" << std::endl; } } } double weight_fsi_cai::getGenieBE(const int A, const int Z) { if (A == 1) return 0; // hydrogen if (A == 6) return 17.0; // lithium if (A == 12) return 25.0; // carbon if (A == 16) return 27.0; // oxygen if (A == 24) return 32.0; // magnesium if (A == 56) return 36.0; // 56 iron if (A == 58) return 36.0; // 58 nickel if (A == 208) return 44.0; // 208 lead return 0; } double weight_fsi_cai::getWeightInternal(double Ti, int mode ) { if (mode == 1) { if( Ti > hNoFSIWeight->GetXaxis()->GetXmax() ) Ti = hNoFSIWeight->GetXaxis()->GetXmax(); else if( Ti < hNoFSIWeight->GetXaxis()->GetXmin() ) Ti = hNoFSIWeight->GetXaxis()->GetXmin(); return hNoFSIWeight->Interpolate(Ti); } if (mode == 3) { if( Ti > hElaFSIWeight->GetXaxis()->GetXmax() ) Ti = hElaFSIWeight->GetXaxis()->GetXmax(); if( Ti < hElaFSIWeight->GetXaxis()->GetXmin() ) Ti = hElaFSIWeight->GetXaxis()->GetXmin(); return hElaFSIWeight->Interpolate(Ti); } return 1; } int weight_fsi_cai::getQEFSIMode( int mc_intType, int mc_targetA, int mc_targetZ, int mc_er_nPart, const int* mc_er_ID, const int* mc_er_status, const int* mc_er_FD, const int* mc_er_LD, const int* mc_er_mother, const double* mc_er_Px, const double* mc_er_Py, const double* mc_er_Pz, const double* mc_er_E, double &Ti) { if (mc_intType != 1) return -999; //not QE if (mc_targetA == 1) return -999; // no FSI genie_particle fsi_part, prefsi_part; int fsi_npart = 0; int prefsi_npart = 0; for ( int i = 0; i< mc_er_nPart; ++ i ) { //cout<<"iPart = "<<i<<endl; const int pdg = mc_er_ID[i]; const int status = mc_er_status[i]; const int fd = mc_er_FD[i]; const int ld = mc_er_LD[i]; const int fm = mc_er_mother[i]; const double px = mc_er_Px[i]; const double py = mc_er_Py[i]; const double pz = mc_er_Pz[i]; const double E = mc_er_E[i]; TLorentzVector p4(px,py,pz,E); //double m = p4.M(); //double p = p4.P(); //cout<<"Defined m, p"<<endl; //if (abs(pdg) == 14 || pdg == 22) m = 0; genie_particle pobj(i,pdg,status,fd,ld,fm); pobj.SetMomentumEnergy( p4 ); //cout<<"pobj defined"<<endl; if ( pdg == m_FSPDG && status == 1) {fsi_part = pobj; ++fsi_npart;} if ( pdg == m_FSPDG && status == 14) {prefsi_part = pobj; ++prefsi_npart;} //cout<<"inserting "<<i<<"th part"<<endl; //particle_map.insert( std::make_pair( i, *pobj ) ); } //cout<<"end loop part"<<endl; //assert( !fsi_part.default_particle() ); Ti = prefsi_part.T(); if (prefsi_part.default_particle() ) return 11; // expected proton if (fsi_part.default_particle() ) return 12; // expected proton if (fsi_part.GetMother() != prefsi_part.GetId() ) return 13; if (prefsi_part.GetFD() != prefsi_part.GetLD() ) return 14; if (fsi_npart !=1 && prefsi_npart !=1) { return -1; //shouldn't exist } double Ei = prefsi_part.p4().E(); double Ep = Ei - getGenieBE( mc_targetA, mc_targetZ ); double pprime = sqrt( Ep*Ep - prefsi_part.p4().M2() ); double pold = prefsi_part.p4().P(); if (pold == 0 ) return 15; double scale = pprime/pold; double pxp = scale* prefsi_part.p4().Px(); double pyp = scale* prefsi_part.p4().Py(); double pzp = scale* prefsi_part.p4().Pz(); TLorentzVector p4p( pxp, pyp,pzp,Ep); genie_particle be_part = prefsi_part; be_part.SetMomentumEnergy( p4p ); //part = fsi_part.p4(); //bePart = be_part.p4(); bool noint = abs( be_part.p4().E() - fsi_part.p4().E() )< 0.0001 && fsi_part.p4().Angle( prefsi_part.p4().Vect() )<0.01; bool elastic = abs( be_part.p4().E() - fsi_part.p4().E() )< 5 ; if (noint) return 1; if (elastic) return 3; return 5; } int weight_fsi_cai::getResFSIMode( int mc_intType, int mc_targetA, int mc_targetZ, int mc_er_nPart, const int* mc_er_ID, const int* mc_er_status, const int* mc_er_FD, const int* mc_er_LD, const int* mc_er_mother, const double* mc_er_Px, const double* mc_er_Py, const double* mc_er_Pz, const double* mc_er_E, double &Ti) { if (mc_intType ==4 ) return 0; if (mc_targetA == 1) return 0; std::map<int, genie_particle> particle_map; genie_particle nofsi_pi; genie_particle fsi_pi; int fsi_npi = 0; for (int i = 0; i < mc_er_nPart; ++i) { const int pdg = mc_er_ID[i]; const int status = mc_er_status[i]; const int fd = mc_er_FD[i]; const int ld = mc_er_LD[i]; const int fm = mc_er_mother[i]; const double px = mc_er_Px[i]; const double py = mc_er_Py[i]; const double pz = mc_er_Pz[i]; const double e = mc_er_E[i]; //const double p = sqrt(px * px + py * py + pz * pz); //double m = sqrt(e * e - p * p); //if (pdg == -14 || pdg == 22) m = 0.0; genie_particle pobj(i,pdg,status,fd,ld,fm); TLorentzVector p4(px,py,pz,e); p4.RotateX(-theta_b); pobj.SetMomentumEnergy(p4); if (pdg == -211 && status == 1) { fsi_pi = pobj; ++fsi_npi; } if (pdg == -211 && status == 14) nofsi_pi = pobj; particle_map.insert(std::make_pair(i,pobj)); //bool __verbose = false; //if (__verbose) { // std::cout.setf(std::ios_base::fixed); // std::cout.precision(2); // std::cout << setw(8) << i << setw(15) << pdg << setw(8) << status // << setw(8) << fm << " (" // << setw(10) << px << setw(10) << py // << setw(10) << pz << setw(10) << e-m << " )" // << std::endl;; //} } if (fsi_npi < 1) { std::cout << "warning: no final state pi-" << std::endl; return 0; } assert(!fsi_pi.default_particle()); if (nofsi_pi.default_particle()) return 0; // pi- not come from pi- as in cex or pi prod std::vector<genie_particle> pim_ancestry; if (!fsi_pi.default_particle()) { genie_particle last_particle = fsi_pi; pim_ancestry.push_back(last_particle); for (;;) { int mother_id = last_particle.GetMother(); if (mother_id < 1) break; genie_particle mother = particle_map[mother_id]; pim_ancestry.push_back(mother); last_particle = mother; } } if (pim_ancestry[1] != nofsi_pi) return 0; const double delta_px = fsi_pi.p4().Px() - nofsi_pi.p4().Px(); const double delta_py = fsi_pi.p4().Px() - nofsi_pi.p4().Px(); const double delta_pz = fsi_pi.p4().Px() - nofsi_pi.p4().Px(); const double delta_k = fsi_pi.T() - nofsi_pi.T(); Ti = nofsi_pi.T(); bool noint = delta_px == 0.0 && delta_py == 0.0 && delta_pz == 0.0; bool elastic = (!noint) && abs(delta_k) < 10.0; bool inelastic = (!noint) && abs(delta_k) >= 10.0; if (noint) return 1; else if (elastic) return 3; else if (inelastic) return 4; else return 10; } double weight_fsi_cai::getWeight( int mc_intType, int mc_targetA, int mc_targetZ, int mc_er_nPart, const int* mc_er_ID, const int* mc_er_status, const int* mc_er_FD, const int* mc_er_LD, const int* mc_er_mother, const double* mc_er_Px, const double* mc_er_Py, const double* mc_er_Pz, const double* mc_er_E) { double Ti = 0; int Mode = (m_reweighQE)? getQEFSIMode( mc_intType, mc_targetA, mc_targetZ, mc_er_nPart, mc_er_ID, mc_er_status, mc_er_FD, mc_er_LD, mc_er_mother, mc_er_Px, mc_er_Py, mc_er_Pz, mc_er_E, Ti ): getResFSIMode( mc_intType, mc_targetA, mc_targetZ, mc_er_nPart, mc_er_ID, mc_er_status, mc_er_FD, mc_er_LD, mc_er_mother, mc_er_Px, mc_er_Py, mc_er_Pz, mc_er_E, Ti ); Ti/=1000; // convert to GeV return getWeightInternal( Ti, Mode ); } double weight_fsi_cai::getWeightPoly( int mc_intType, int mc_targetA, int mc_targetZ, int mc_er_nPart, int* mc_er_ID, int* mc_er_status, int* mc_er_FD, int* mc_er_LD, int* mc_er_mother, double* mc_er_Px, double* mc_er_Py, double* mc_er_Pz, double* mc_er_E) { if (mc_intType != 1 || mc_targetA==1 ) return 1.; double Ti = 0; int Mode = (m_reweighQE)? getQEFSIMode( mc_intType, mc_targetA, mc_targetZ, mc_er_nPart, mc_er_ID, mc_er_status, mc_er_FD, mc_er_LD, mc_er_mother, mc_er_Px, mc_er_Py, mc_er_Pz, mc_er_E, Ti ): getResFSIMode( mc_intType, mc_targetA, mc_targetZ, mc_er_nPart, mc_er_ID, mc_er_status, mc_er_FD, mc_er_LD, mc_er_mother, mc_er_Px, mc_er_Py, mc_er_Pz, mc_er_E, Ti ); Ti/=1000; // convert to GeV return getWeightInternalRik( Ti,mc_targetA, Mode, m_config ); } double weight_fsi_cai::getWeightInternalRik( double inputKEgev, int inputA, int mode, int config ) { //if (config == 0 or config == 3 or config>4) return 1.; if (config == 0) return 1; if (mode <= 0) return 1; if (config == 1 || config == 2) { if(inputKEgev < getGenieBE(inputA)/1000.+0.010 )return 1.0; if ( mode == 3 ) return 0.; //config == 2 //double lowEpolyC12[10] = {17.8228, 1551.6, -170931, 6.48098e6, -1.34102e8, 1.6961e9, -1.35026e10, 6.6204e10, -1.82973e11, 2.18416e11}; //double midEpolyC12[10] = {4.17489, -45.544, 345.733, -1485.0, 3875.45, -6356.52, 6588.9, -4194.6, 1499.09, -230.484}; //double highEpolyC12[10] = {1.23147, -0.0527092, 0.0081572, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; //double lowEpolyO16[10] = {-11.4283, 4987.76, -340194., 1.1199e7, -2.16573e8, 2.63567e9, -2.04893e10, 9.89449e10, -2.70812e11, 3.21319e11}; //double midEpolyO16[10] = {4.85878, -55.0283, 418.162, -1798.99, 4700.67, -7716.98, 8001.46, -5089.56, 1814.09, -277.456}; //double highEpolyO16[10] = {1.26765, -0.0583833, 0.00853185, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; //double lowEpolyAr40[10] = {-12.4288, 46744.8, -2.47696e6, 5.40691e7, -5.84637e8, 2.5746e9, 7.87892e9, -1.43636e11, 6.19253e11, -9.44823e11}; //double midEpolyAr40[10] = {31.0973, -517.199, 4089.58, -18404.7, 51320.3, -91701.5, 105134., -74779.8, 3032.9, -5203.64}; //double highEpolyAr40[10] = {1.47462, -0.111806, 0.0166705, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; //double lowEpolyFe56[10] = {2533.41, -140121., 3.27464e6, -4.09799e7, 2.88262e8, -1.07774e9, 1.67053e9, 0.0, 0.0, 0.0}; //double midEpolyFe56[10] = {31.9074, -525.4, 4131.33, -18520.4, 51485.8, -91755.4, 104940., -74465.9, 29837.6, -5157.84}; //double highEpolyFe56[10] = {1.52685, -0.127437, 0.0198632, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; //double lowEpolyPb208[10] = {6301.34, -347755., 8.07485e6, -1.00173e8, 6.97538e8, -2.57953e9, 3.95315e9, 0.0, 0.0, 0.0}; //double midEpolyPb208[10] = {61.6161, -1022.96, 7948.2, -35212.3, 96827.2, -170874., 193711., -136368., 54248.1, -9316.09}; //double highEpolyPb208[10] = {1.90105, -0.195386, 0.0286129, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; ////======================= antinu //double lowEpolyC12Anu[10] = {91.8662, -3841.37, 17803.8, 2.46643e6, -7.77780e7, 1.16001e9, -1.00604e10, 5.18932e10, -1.48160e11, 1.80790e11}; //double midEpolyC12Anu[10] = {6.87059, -87.0001, 658.091, -2865.93, 7713.87, -13257.9, 14592.2, -9963.09, 3845.83, -641.742}; //double highEpolyC12Anu[10] = {1.19153, -0.0273976, 0.00320112, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; ////config == 4 ////updated weights from Rik //double lowEpolyC12w4[10] = {-1.09786, 353.897, -14438.2, 249803.0, -961139.0, -3.30078e7, 5.9223e8, -4.42502e9, 1.62258e10, -2.39127e10}; //double midEpolyC12w4[10] = {1.40574, 0.580308, 33.3332, -323.69, 1330.14, -3060.15, 4217.66, -3458.10, 1555.36, -295.373}; //double highEpolyC12w4[10] = {1.16048, -0.00252581, 0.000616833, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; // //double lowEpolyO16w4[10] = { -1.60048, 435.953, -19971.4, 452149.0, -5.40787e6, 2.83386e7, 5.7011e7, -1.55825e9, 7.6214e9, -1.28315e10}; //double midEpolyO16w4[10] = { 1.44861, -0.40647, 42.8448, -374.366, 1495.64, -3402.08, 4662.46, -3809.16, 1708.30, -323.51}; //double highEpolyO16w4[10] = {1.15438, 0.00410489, -0.000841064, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; //double lowEpolyAr40w4[10] = {-15.9188, 2230.47, -116236.0, 3.35816e6, -5.99261e7, 6.88940e8, -5.12413e9, 2.38571e10, -6.32693e10, 7.29876e10}; //double midEpolyAr40w4[10] = {1.37013, 1.51099, 23.8883, -274.205, 1180.48, -2784.74, 3904.85, -3244.2, 1474.71, -282.505}; //double highEpolyAr40w4[10] = {1.15711, 0.00116488, -0.000304764, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; // //double lowEpolyFe56w4[10] = {-17.5586, 2416.34, -125628.0, 3.63612e6, -6.5208e7, 7.55278e8, -5.67114e9, 2.66995e10, -7.16941e10, 8.38294e10}; //double midEpolyFe56w4[10] = {1.36436, 1.61799, 22.7834, -266.814, 1149.24, -2702.28, 3770.63, -3114.18, 1406.30, -267.505}; //double highEpolyFe56w4[10] = {1.1583, -0.000677155, 0.000283527, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; //double lowEpolyPb208w4[10] = {-22.7764, 3056.80, -158958.0, 4.6053e6, -8.2631e7, 9.56844e8, -7.17712e9, 3.37296e10, -9.03555e10, 1.05349e11}; //double midEpolyPb208w4[10] = {1.38084, 1.34013, 24.5788, -272.457, 1158.25, -2708.59, 3770.54, -3112.01, 1405.81, -267.677}; //double highEpolyPb208w4[10] = {1.15639, 0.00157778, -0.000370309, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; // QE has a 25 MeV offset for this GENIE version // but the weights are really high, so move this forward by 10 MeV. //if(inputKEgev < 0.025)return 1.0; // For protons from Delta, same or 25 MeV offset? double *poly; double *low, *mid, *high; //Helium 4 if( inputA >3 && inputA<=10 ) { if(config==2){ // weight elasticFSI to otherFSI low = lowEpolyHe4w2; mid = midEpolyHe4w2; high = highEpolyHe4w2; } else { // weight elasticFSI to noFSI low = lowEpolyHe4; mid = midEpolyHe4; high = highEpolyHe4; if( ! m_neutrinoMode ) low = lowEpolyHe4Anu; mid = midEpolyHe4Anu; high = highEpolyHe4Anu; } } else if(inputA > 10 && inputA <= 15){ // For carbon, and maybe nitrogen if(config==2){ // weight elasticFSI to otherFSI low = lowEpolyC12w2; mid = midEpolyC12w2; high = highEpolyC12w2; } else { // weight elasticFSI to noFSI low = lowEpolyC12; mid = midEpolyC12; high = highEpolyC12; if( ! m_neutrinoMode ) low = lowEpolyC12Anu; mid = midEpolyC12Anu; high = highEpolyC12Anu; } } else if(inputA > 15 && inputA <= 23){ // mostly for oxygen if(config==2){ low = lowEpolyO16w2; mid = midEpolyO16w2; high = highEpolyO16w2; } else { low = lowEpolyO16; mid = midEpolyO16; high = highEpolyO16; if( ! m_neutrinoMode ) low = lowEpolyO16Anu; mid = midEpolyO16Anu; high = highEpolyO16Anu; //weight elasticFSI to noFSI } } else if (inputA > 23 && inputA < 32 ){ if(config==2){ // weight elasticFSI to otherFSI low = lowEpolySi28w2; mid = midEpolySi28w2; high = highEpolySi28w2; } else { //weight elasticFSI to noFSI low = lowEpolySi28; mid = midEpolySi28; high = highEpolySi28; if( ! m_neutrinoMode ) low = lowEpolySi28Anu; mid = midEpolySi28Anu; high = highEpolySi28Anu; } } else if(inputA > 32 && inputA <= 48){ if(config==2){ // weight elasticFSI to otherFSI low = lowEpolyAr40w2; mid = midEpolyAr40w2; high = highEpolyAr40w2; } else { //weight elasticFSI to noFSI low = lowEpolyAr40; mid = midEpolyAr40; high = highEpolyAr40; if( ! m_neutrinoMode ) low = lowEpolyAr40Anu; mid = midEpolyAr40Anu; high = highEpolyAr40Anu; } } else if(inputA > 48 && inputA <= 70){ // Use iron for nickel and such if(config==2){ // weight elasticFSI to otherFSI low = lowEpolyFe56w2; mid = midEpolyFe56w2; high = highEpolyFe56w2; } else { //weight elasticFSI to noFSI low = lowEpolyFe56; mid = midEpolyFe56; high = highEpolyFe56; if( ! m_neutrinoMode ) low = lowEpolyFe56Anu; mid = midEpolyFe56Anu; high = highEpolyFe56Anu; } } else if(inputA > 195 && inputA <= 240){ if(config==2){ // weight elasticFSI to otherFSI low = lowEpolyPb208w2; mid = midEpolyPb208w2; high = highEpolyPb208w2; } else { //weight elasticFSI to noFSI low = lowEpolyPb208; mid = midEpolyPb208; high = highEpolyPb208; if( ! m_neutrinoMode ) low = lowEpolyPb208Anu; mid = midEpolyPb208Anu; high = highEpolyPb208Anu; } } else { // some nuclei are not tested. return 1.0; } poly = polySwitcher( inputKEgev, low, mid, high ); // Finally calculate the weight. double powke = 1.0; double tempweight = 0.0; for(int i=0; i<10; i++){ tempweight += powke * poly[i]; powke *= inputKEgev; } // debug print statement //std::cout << "ElasticFSIWeight inputKEgev " << inputKEgev << " inputA " << inputA << " config " << config << " tempweight " << tempweight << std::endl; if (config == 4) { if (mode == 1) return 1; if (mode == 3) return 0; if (mode >= 4) return tempweight; } if (config == 2) { if (mode >= 4) return 1; if (mode == 3) return 0; if (mode == 1) return tempweight; } } return 1.; } double* weight_fsi_cai::polySwitcher(double inputKEgev, double *low, double *mid, double *high ) { if(inputKEgev > m_highcutoff)inputKEgev = m_highcutoff; double *poly; poly = high; if(inputKEgev < m_breakpointlow)poly = low; else if(inputKEgev < m_breakpointhigh)poly = mid; return poly; }
39.220779
319
0.611038
MinervaExpt
ba83f6018e7b70015dd43c5e9df4ad06d27180cc
285
hpp
C++
src/arch/arm/handlers.hpp
qookei/tart
e039f9c493560f306904793ac9143810aabbf68e
[ "Zlib" ]
11
2020-06-20T19:05:08.000Z
2021-04-07T17:49:18.000Z
src/arch/arm/handlers.hpp
qookei/tart
e039f9c493560f306904793ac9143810aabbf68e
[ "Zlib" ]
null
null
null
src/arch/arm/handlers.hpp
qookei/tart
e039f9c493560f306904793ac9143810aabbf68e
[ "Zlib" ]
null
null
null
#pragma once #include <stddef.h> namespace tart { void nmi(void *ctx); void hard_fault(void *ctx); void mm_fault(void *ctx); void bus_fault(void *ctx); void usage_fault(void *ctx); void sv_call(void *ctx); void pend_sv_call(void *ctx); void systick(void *ctx); } // namespace tart
16.764706
29
0.719298
qookei
ba8ab5c45c5e09f857e806ed423260c2c21c6318
6,761
cpp
C++
src/ossim/support_data/ossimQuickbirdRpcHeader.cpp
rkanavath/ossim18
d2e8204d11559a6a868755a490f2ec155407fa96
[ "MIT" ]
null
null
null
src/ossim/support_data/ossimQuickbirdRpcHeader.cpp
rkanavath/ossim18
d2e8204d11559a6a868755a490f2ec155407fa96
[ "MIT" ]
null
null
null
src/ossim/support_data/ossimQuickbirdRpcHeader.cpp
rkanavath/ossim18
d2e8204d11559a6a868755a490f2ec155407fa96
[ "MIT" ]
1
2019-09-25T00:43:35.000Z
2019-09-25T00:43:35.000Z
//---------------------------------------------------------------------------- // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // //---------------------------------------------------------------------------- // $Id: ossimQuickbirdRpcHeader.cpp 23664 2015-12-14 14:17:27Z dburken $ #include <ossim/support_data/ossimQuickbirdRpcHeader.h> #include <iostream> #include <fstream> #include <algorithm> #include <iterator> std::ostream& operator << (std::ostream& out, const ossimQuickbirdRpcHeader& data) { out << "theSatId = " << data.theSatId << std::endl << "theBandId = " << data.theBandId << std::endl << "theSpecId = " << data.theSpecId << std::endl << "theErrBias = " << data.theErrBias << std::endl << "theLineOffset = " << data.theLineOffset << std::endl << "theSampOffset = " << data.theSampOffset << std::endl << "theLatOffset = " << data.theLatOffset << std::endl << "theLonOffset = " << data.theLonOffset << std::endl << "theHeightOffset = " << data.theHeightOffset << std::endl << "theLineScale = " << data.theLineScale << std::endl << "theSampScale = " << data.theSampScale << std::endl << "theLatScale = " << data.theLatScale << std::endl << "theLonScale = " << data.theLonScale << std::endl << "theHeightScale = " << data.theHeightScale << std::endl; out << "lineNumCoef = " << std::endl; std::copy(data.theLineNumCoeff.begin(), data.theLineNumCoeff.end(), std::ostream_iterator<double>(out, "\n")); out << "lineDenCoef = " << std::endl; std::copy(data.theLineDenCoeff.begin(), data.theLineDenCoeff.end(), std::ostream_iterator<double>(out, "\n")); out << "sampNumCoef = " << std::endl; std::copy(data.theSampNumCoeff.begin(), data.theSampNumCoeff.end(), std::ostream_iterator<double>(out, "\n")); out << "sampDenCoef = " << std::endl; std::copy(data.theSampDenCoeff.begin(), data.theSampDenCoeff.end(), std::ostream_iterator<double>(out, "\n")); return out; } ossimQuickbirdRpcHeader::ossimQuickbirdRpcHeader() { } bool ossimQuickbirdRpcHeader::open(const ossimFilename& file) { theFilename = file; std::ifstream in(file.c_str(), std::ios::in|std::ios::binary); char test[64]; in.read((char*)test, 63); test[63] = '\0'; in.seekg(0); ossimString line = test; line = line.upcase(); if(parseNameValue(line)) { theErrorStatus = ossimErrorCodes::OSSIM_OK; getline(in, line); while((in)&&(theErrorStatus == ossimErrorCodes::OSSIM_OK)) { line = line.upcase(); if(line.contains("LINENUMCOEF")) { if(!readCoeff(in, theLineNumCoeff)) { setErrorStatus(); break; } } else if(line.contains("LINEDENCOEF")) { if(!readCoeff(in, theLineDenCoeff)) { setErrorStatus(); break; } } else if(line.contains("SAMPNUMCOEF")) { if(!readCoeff(in, theSampNumCoeff)) { setErrorStatus(); break; } } else if(line.contains("SAMPDENCOEF")) { if(!readCoeff(in, theSampDenCoeff)) { setErrorStatus(); break; } } else if(!parseNameValue(line)) { setErrorStatus(); break; } getline(in, line); } } else { setErrorStatus(); } return (theErrorStatus == ossimErrorCodes::OSSIM_OK); } bool ossimQuickbirdRpcHeader::readCoeff(std::istream& in, std::vector<double>& coeff) { coeff.clear(); bool done = false; ossimString line; while(!in.eof()&&!in.bad()&&!done) { getline(in, line); line.trim(); line.trim(','); if(line.contains(");")) { done = true; line.trim(';'); line.trim(')'); } coeff.push_back(line.toDouble()); } return done; } bool ossimQuickbirdRpcHeader::parseNameValue(const ossimString& line) { bool result = true; ossimString lineCopy = line; if(lineCopy.contains("SATID")) { theSatId = lineCopy.after("\""); theSatId = theSatId.before("\""); } else if(lineCopy.contains("BANDID")) { theBandId = lineCopy.after("\""); theBandId = theBandId.before("\""); } else if(lineCopy.contains("SPECID")) { theSpecId = lineCopy.after("\""); theSpecId = theSpecId.before("\""); } else if(lineCopy.contains("BEGIN_GROUP")) { } else if(lineCopy.contains("ERRBIAS")) { lineCopy = lineCopy.after("="); theErrBias = lineCopy.before(";").toDouble(); } else if(lineCopy.contains("ERRRAND")) { lineCopy = lineCopy.after("="); theErrRand = lineCopy.before(";").toDouble(); } else if(lineCopy.contains("LINEOFFSET")) { lineCopy = lineCopy.after("="); theLineOffset = lineCopy.before(";").toInt(); } else if(lineCopy.contains("SAMPOFFSET")) { lineCopy = lineCopy.after("="); theSampOffset = lineCopy.before(";").toInt(); } else if(lineCopy.contains("LATOFFSET")) { lineCopy = lineCopy.after("="); theLatOffset = lineCopy.before(";").toDouble(); } else if(lineCopy.contains("LONGOFFSET")) { lineCopy = lineCopy.after("="); theLonOffset = lineCopy.before(";").toDouble(); } else if(lineCopy.contains("HEIGHTOFFSET")) { lineCopy = lineCopy.after("="); theHeightOffset = lineCopy.before(";").toDouble(); } else if(lineCopy.contains("LINESCALE")) { lineCopy = lineCopy.after("="); theLineScale = lineCopy.before(";").toDouble(); } else if(lineCopy.contains("SAMPSCALE")) { lineCopy = lineCopy.after("="); theSampScale = lineCopy.before(";").toDouble(); } else if(lineCopy.contains("LATSCALE")) { lineCopy = lineCopy.after("="); theLatScale = lineCopy.before(";").toDouble(); } else if(lineCopy.contains("LONGSCALE")) { lineCopy = lineCopy.after("="); theLonScale = lineCopy.before(";").toDouble(); } else if(lineCopy.contains("HEIGHTSCALE")) { lineCopy = lineCopy.after("="); theHeightScale = lineCopy.before(";").toDouble(); } else if(lineCopy.contains("END_GROUP")) { } else if(lineCopy.contains("END")) { } else { result = false; } return result; }
27.262097
78
0.539861
rkanavath
ba8b042eec65c229f27f5fd441462370f5c51003
10,157
cpp
C++
projects/abuild/cache/test/tokens_test.cpp
agnesoft/adev-alt
3df0329939e3048bbf5db252efb5f74de9c0f061
[ "Apache-2.0" ]
null
null
null
projects/abuild/cache/test/tokens_test.cpp
agnesoft/adev-alt
3df0329939e3048bbf5db252efb5f74de9c0f061
[ "Apache-2.0" ]
null
null
null
projects/abuild/cache/test/tokens_test.cpp
agnesoft/adev-alt
3df0329939e3048bbf5db252efb5f74de9c0f061
[ "Apache-2.0" ]
null
null
null
import atest; import abuild.cache; import abuild.test_utilities; using ::atest::assert_; using ::atest::expect; using ::atest::suite; using ::atest::test; static const auto S = suite("Tokens", [] { // NOLINT(cert-err58-cpp) test("Token - IfToken", [] { const ::abuild::TestFile testFile{"./abuild.cache_test.yaml"}; const ::abuild::Token token{::abuild::IfToken{ .elements = { ::abuild::DefinedToken{.name = "MY_MACRO"}, ::abuild::AndToken{}, ::abuild::LeftBracketToken{}, ::abuild::EqualsToken{.left = "10", .right = "SOME_VALUE"}, ::abuild::OrToken{}, ::abuild::GreaterThanOrEqualsToken{.left = "10", .right = "SOME_VALUE"}, ::abuild::OrToken{}, ::abuild::GreaterThanToken{.left = "10", .right = "SOME_VALUE"}, ::abuild::OrToken{}, ::abuild::LessThanOrEqualsToken{.left = "10", .right = "SOME_VALUE"}, ::abuild::OrToken{}, ::abuild::LessThanToken{.left = "10", .right = "SOME_VALUE"}, ::abuild::RightBracketToken{}, ::abuild::AndToken{}, ::abuild::NotToken{}, ::abuild::HasIncludeExternalToken{.name = "my_header.hpp"}, ::abuild::OrToken{}, ::abuild::HasIncludeLocalToken{.name = "include/some_header.h"}}}}; { ::abuild::Cache cache{testFile.path()}; ::abuild::SourceFile *source = cache.add_source_file("main.cpp"); source->tokens.push_back(token); } ::abuild::Cache cache{testFile.path()}; ::abuild::SourceFile *source = cache.exact_source_file("main.cpp"); assert_(source).not_to_be(nullptr); assert_(source->tokens.size()).to_be(1U); expect(source->tokens[0]).to_be(token); }); test("Token - ElseToken", [] { const ::abuild::TestFile testFile{"./abuild.cache_test.yaml"}; const ::abuild::Token token = ::abuild::ElseToken{}; { ::abuild::Cache cache{testFile.path()}; ::abuild::SourceFile *source = cache.add_source_file("main.cpp"); source->tokens.push_back(token); } ::abuild::Cache cache{testFile.path()}; ::abuild::SourceFile *source = cache.exact_source_file("main.cpp"); assert_(source).not_to_be(nullptr); assert_(source->tokens.size()).to_be(1U); expect(source->tokens[0]).to_be(token); }); test("Token - EndIfToken", [] { const ::abuild::TestFile testFile{"./abuild.cache_test.yaml"}; const ::abuild::Token token = ::abuild::EndIfToken{}; { ::abuild::Cache cache{testFile.path()}; ::abuild::SourceFile *source = cache.add_source_file("main.cpp"); source->tokens.push_back(token); } ::abuild::Cache cache{testFile.path()}; ::abuild::SourceFile *source = cache.exact_source_file("main.cpp"); assert_(source).not_to_be(nullptr); assert_(source->tokens.size()).to_be(1U); expect(source->tokens[0]).to_be(token); }); test("Token - DefineToken", [] { const ::abuild::TestFile testFile{"./abuild.cache_test.yaml"}; const ::abuild::Token token = ::abuild::DefineToken{.name = "MY_MACRO", .value = "1"}; { ::abuild::Cache cache{testFile.path()}; ::abuild::SourceFile *source = cache.add_source_file("main.cpp"); source->tokens.push_back(token); } ::abuild::Cache cache{testFile.path()}; ::abuild::SourceFile *source = cache.exact_source_file("main.cpp"); assert_(source).not_to_be(nullptr); assert_(source->tokens.size()).to_be(1U); expect(source->tokens[0]).to_be(token); }); test("Token - ImportIncludeExternalToken", [] { const ::abuild::TestFile testFile{"./abuild.cache_test.yaml"}; const ::abuild::Token token = ::abuild::ImportIncludeExternalToken{.name = "include/my_header.hpp", .exported = true}; { ::abuild::Cache cache{testFile.path()}; ::abuild::SourceFile *source = cache.add_source_file("main.cpp"); source->tokens.push_back(token); } ::abuild::Cache cache{testFile.path()}; ::abuild::SourceFile *source = cache.exact_source_file("main.cpp"); assert_(source).not_to_be(nullptr); assert_(source->tokens.size()).to_be(1U); expect(source->tokens[0]).to_be(token); }); test("Token - ImportIncludeLocalToken", [] { const ::abuild::TestFile testFile{"./abuild.cache_test.yaml"}; const ::abuild::Token token = ::abuild::ImportIncludeLocalToken{.name = "include/my_header.hpp", .exported = true}; { ::abuild::Cache cache{testFile.path()}; ::abuild::SourceFile *source = cache.add_source_file("main.cpp"); source->tokens.push_back(token); } ::abuild::Cache cache{testFile.path()}; ::abuild::SourceFile *source = cache.exact_source_file("main.cpp"); assert_(source).not_to_be(nullptr); assert_(source->tokens.size()).to_be(1U); expect(source->tokens[0]).to_be(token); }); test("Token - ImportModulePartitionToken", [] { const ::abuild::TestFile testFile{"./abuild.cache_test.yaml"}; const ::abuild::Token token = ::abuild::ImportModulePartitionToken{.name = "my_partition", .exported = true}; { ::abuild::Cache cache{testFile.path()}; ::abuild::SourceFile *source = cache.add_source_file("main.cpp"); source->tokens.push_back(token); } ::abuild::Cache cache{testFile.path()}; ::abuild::SourceFile *source = cache.exact_source_file("main.cpp"); assert_(source).not_to_be(nullptr); assert_(source->tokens.size()).to_be(1U); expect(source->tokens[0]).to_be(token); }); test("Token - ImportModuleToken", [] { const ::abuild::TestFile testFile{"./abuild.cache_test.yaml"}; const ::abuild::Token token = ::abuild::ImportModuleToken{.name = "my_module", .exported = true}; { ::abuild::Cache cache{testFile.path()}; ::abuild::SourceFile *source = cache.add_source_file("main.cpp"); source->tokens.push_back(token); } ::abuild::Cache cache{testFile.path()}; ::abuild::SourceFile *source = cache.exact_source_file("main.cpp"); assert_(source).not_to_be(nullptr); assert_(source->tokens.size()).to_be(1U); expect(source->tokens[0]).to_be(token); }); test("Token - IncludeExternalToken", [] { const ::abuild::TestFile testFile{"./abuild.cache_test.yaml"}; const ::abuild::Token token = ::abuild::IncludeExternalToken{.name = "include/my_header.hpp"}; { ::abuild::Cache cache{testFile.path()}; ::abuild::SourceFile *source = cache.add_source_file("main.cpp"); source->tokens.push_back(token); } ::abuild::Cache cache{testFile.path()}; ::abuild::SourceFile *source = cache.exact_source_file("main.cpp"); assert_(source).not_to_be(nullptr); assert_(source->tokens.size()).to_be(1U); expect(source->tokens[0]).to_be(token); }); test("Token - IncludeLocalToken", [] { const ::abuild::TestFile testFile{"./abuild.cache_test.yaml"}; const ::abuild::Token token = ::abuild::IncludeLocalToken{.name = "include/my_header.hpp"}; { ::abuild::Cache cache{testFile.path()}; ::abuild::SourceFile *source = cache.add_source_file("main.cpp"); source->tokens.push_back(token); } ::abuild::Cache cache{testFile.path()}; ::abuild::SourceFile *source = cache.exact_source_file("main.cpp"); assert_(source).not_to_be(nullptr); assert_(source->tokens.size()).to_be(1U); expect(source->tokens[0]).to_be(token); }); test("Token - ModulePartitionToken", [] { const ::abuild::TestFile testFile{"./abuild.cache_test.yaml"}; const ::abuild::Token token = ::abuild::ModulePartitionToken{.mod = "my_module", .name = "my_partition", .exported = true}; { ::abuild::Cache cache{testFile.path()}; ::abuild::SourceFile *source = cache.add_source_file("main.cpp"); source->tokens.push_back(token); } ::abuild::Cache cache{testFile.path()}; ::abuild::SourceFile *source = cache.exact_source_file("main.cpp"); assert_(source).not_to_be(nullptr); assert_(source->tokens.size()).to_be(1U); expect(source->tokens[0]).to_be(token); }); test("Token - ModuleToken", [] { const ::abuild::TestFile testFile{"./abuild.cache_test.yaml"}; const ::abuild::Token token = ::abuild::ModuleToken{.name = "my_module", .exported = true}; { ::abuild::Cache cache{testFile.path()}; ::abuild::SourceFile *source = cache.add_source_file("main.cpp"); source->tokens.push_back(token); } ::abuild::Cache cache{testFile.path()}; ::abuild::SourceFile *source = cache.exact_source_file("main.cpp"); assert_(source).not_to_be(nullptr); assert_(source->tokens.size()).to_be(1U); expect(source->tokens[0]).to_be(token); }); test("Token - UndefToken", [] { const ::abuild::TestFile testFile{"./abuild.cache_test.yaml"}; const ::abuild::Token token = ::abuild::UndefToken{.name = "MY_MACRO"}; { ::abuild::Cache cache{testFile.path()}; ::abuild::SourceFile *source = cache.add_source_file("main.cpp"); source->tokens.push_back(token); } ::abuild::Cache cache{testFile.path()}; ::abuild::SourceFile *source = cache.exact_source_file("main.cpp"); assert_(source).not_to_be(nullptr); assert_(source->tokens.size()).to_be(1U); expect(source->tokens[0]).to_be(token); }); });
38.473485
131
0.584031
agnesoft
ba8b111c79d9f0b99e0ee093dfc07cef63f3d493
163
cpp
C++
CodeFights/leapYear.cpp
AREA44/competitive-programming
00cede478685bf337193bce4804f13c4ff170903
[ "MIT" ]
null
null
null
CodeFights/leapYear.cpp
AREA44/competitive-programming
00cede478685bf337193bce4804f13c4ff170903
[ "MIT" ]
null
null
null
CodeFights/leapYear.cpp
AREA44/competitive-programming
00cede478685bf337193bce4804f13c4ff170903
[ "MIT" ]
null
null
null
// Determine if a given year is leap or not. bool leapYear(int year) { if ( year%4==0 && year%100!=0 || year%400==0 ) { return true; } return false; }
16.3
50
0.588957
AREA44
ba8b5f3beba54b180a0fb01e68eda13eb958243a
3,156
hpp
C++
include/termox/widget/widgets/detail/textbox_base.hpp
a-n-t-h-o-n-y/MCurses
c9184a0fefbdc4eb9a044f815ee2270e6b8f202c
[ "MIT" ]
284
2017-11-07T10:06:48.000Z
2021-01-12T15:32:51.000Z
include/termox/widget/widgets/detail/textbox_base.hpp
a-n-t-h-o-n-y/MCurses
c9184a0fefbdc4eb9a044f815ee2270e6b8f202c
[ "MIT" ]
38
2018-01-14T12:34:54.000Z
2020-09-26T15:32:43.000Z
include/termox/widget/widgets/detail/textbox_base.hpp
a-n-t-h-o-n-y/MCurses
c9184a0fefbdc4eb9a044f815ee2270e6b8f202c
[ "MIT" ]
31
2017-11-30T11:22:21.000Z
2020-11-03T05:27:47.000Z
#ifndef TERMOX_WIDGET_WIDGETS_DETAIL_TEXTBOX_BASE_HPP #define TERMOX_WIDGET_WIDGETS_DETAIL_TEXTBOX_BASE_HPP #include <cstddef> #include <signals_light/signal.hpp> #include <termox/painter/glyph_string.hpp> #include <termox/widget/point.hpp> #include <termox/widget/widgets/text_view.hpp> namespace ox::detail { /// Implements cursor movement on top of a Text_view, for use by Textbox. class Textbox_base : public Text_view { private: using Text_view::Parameters; protected: /// Construct with initial \p text, enable cursor. explicit Textbox_base(Glyph_string text = U"", Align alignment = Align::Left, Wrap wrap = Wrap::Word, Brush insert_brush = Brush{}); explicit Textbox_base(Parameters p); public: /// Emitted when the cursor moves left, passes along \n positions moved. sl::Signal<void(std::size_t n)> cursor_moved_left; /// Emitted when the cursor moves right, passes along \n positions moved. sl::Signal<void(std::size_t n)> cursor_moved_right; /// Emitted when the cursor moves up, passes along \n positions moved. sl::Signal<void(std::size_t n)> cursor_moved_up; /// Emitted when the cursor moves down, passes along \n positions moved. sl::Signal<void(std::size_t n)> cursor_moved_down; public: /// Set the cursor to \p position, or the nearest Glyph if no glyph there. void set_cursor(Point position); /// Set the cursor to the Glyph at \p index into contents. void set_cursor(std::size_t index); /// Add cursor movement to Text_view::scroll_up. void scroll_up(int n = 1) override; /// Add cursor movement to Text_view::scroll_down. void scroll_down(int n = 1) override; /// Move the cursor up \p n lines, scroll if at the top line. /** Cursor is moved to the right-most Glyph if the moved to line does not * extend as far as the current cursor column position. */ void cursor_up(int n = 1); /// Move the cursor down \p n lines, scroll if at the bottom line. /** Cursor is moved to the right-most Glyph if the moved to line does not * extend as far as the current cursor column position. */ void cursor_down(int n = 1); /// Move the cursor \p n indices towards the beginning of contents. /** Scroll up if moving past the top-left position. */ void cursor_left(int n = 1); /// Move the cursor \p n indices towards the end of contents. /** Scroll down if moving past the bottom-right position. */ void cursor_right(int n = 1); protected: /// Return the index into contents that the cursor is located at. [[nodiscard]] auto cursor_index() const -> int; /// Scroll to make the cursor visible if no longer on screen after resize. auto resize_event(Area new_size, Area old_size) -> bool override; private: /// Move the cursor one position to the right. void increment_cursor_right(); /// Move the cursor one position to the left. void increment_cursor_left(); }; } // namespace ox::detail #endif // TERMOX_WIDGET_WIDGETS_DETAIL_TEXTBOX_BASE_HPP
35.863636
78
0.683777
a-n-t-h-o-n-y
ba8c2ebe7c5f453879acf5d7480d0d5bff5fe401
5,397
hpp
C++
openstudiocore/src/model/ZoneHVACUnitHeater.hpp
hongyuanjia/OpenStudio
6cc52f1b66c069cf13f2b6ca2a0cc3c137c37cf0
[ "MIT" ]
1
2019-04-21T15:38:54.000Z
2019-04-21T15:38:54.000Z
openstudiocore/src/model/ZoneHVACUnitHeater.hpp
hongyuanjia/OpenStudio
6cc52f1b66c069cf13f2b6ca2a0cc3c137c37cf0
[ "MIT" ]
null
null
null
openstudiocore/src/model/ZoneHVACUnitHeater.hpp
hongyuanjia/OpenStudio
6cc52f1b66c069cf13f2b6ca2a0cc3c137c37cf0
[ "MIT" ]
1
2019-07-18T06:52:29.000Z
2019-07-18T06:52:29.000Z
/*********************************************************************************************************************** * OpenStudio(R), Copyright (c) 2008-2018, Alliance for Sustainable Energy, LLC. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following * disclaimer. * * (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other materials provided with the distribution. * * (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote * products derived from this software without specific prior written permission from the respective party. * * (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative * works may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without * specific prior written permission from Alliance for Sustainable Energy, LLC. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER, THE UNITED STATES GOVERNMENT, OR ANY CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **********************************************************************************************************************/ #ifndef MODEL_ZONEHVACUNITHEATER_HPP #define MODEL_ZONEHVACUNITHEATER_HPP #include "ModelAPI.hpp" #include "ZoneHVACComponent.hpp" namespace openstudio { class Quantity; class OSOptionalQuantity; namespace model { class Schedule; class HVACComponent; namespace detail { class ZoneHVACUnitHeater_Impl; } // detail /** ZoneHVACUnitHeater is a ZoneHVACComponent that wraps the OpenStudio IDD object 'OS:ZoneHVAC:UnitHeater'. */ class MODEL_API ZoneHVACUnitHeater : public ZoneHVACComponent { public: /** @name Constructors and Destructors */ ZoneHVACUnitHeater(const Model& model, Schedule & availabilitySchedule, HVACComponent & supplyAirFan, HVACComponent & heatingCoil); virtual ~ZoneHVACUnitHeater() {} static IddObjectType iddObjectType(); static std::vector<std::string> fanControlTypeValues(); /** @name Getters */ Schedule availabilitySchedule() const; HVACComponent supplyAirFan() const; boost::optional<double> maximumSupplyAirFlowRate() const; bool isMaximumSupplyAirFlowRateAutosized() const; /** In EnergyPlus 8.2.0 and above this property maps to the EnergyPlus field "Supply Air Fan Operation During No Heating" **/ std::string fanControlType() const; HVACComponent heatingCoil() const; boost::optional<double> maximumHotWaterFlowRate() const; bool isMaximumHotWaterFlowRateAutosized() const; double minimumHotWaterFlowRate() const; bool isMinimumHotWaterFlowRateDefaulted() const; double heatingConvergenceTolerance() const; bool isHeatingConvergenceToleranceDefaulted() const; /** @name Setters */ bool setAvailabilitySchedule(Schedule& schedule); bool setSupplyAirFan(const HVACComponent & fan ); bool setMaximumSupplyAirFlowRate(double maximumSupplyAirFlowRate); void autosizeMaximumSupplyAirFlowRate(); bool setFanControlType(std::string fanControlType); bool setHeatingCoil(const HVACComponent & heatingCoil ); bool setMaximumHotWaterFlowRate(double maximumHotWaterFlowRate); void resetMaximumHotWaterFlowRate(); void autosizeMaximumHotWaterFlowRate(); bool setMinimumHotWaterFlowRate(double minimumHotWaterFlowRate); void resetMinimumHotWaterFlowRate(); bool setHeatingConvergenceTolerance(double heatingConvergenceTolerance); void resetHeatingConvergenceTolerance(); /** @name Other */ boost::optional<double> autosizedMaximumSupplyAirFlowRate() const ; boost::optional<double> autosizedMaximumHotWaterFlowRate() const ; protected: /// @cond typedef detail::ZoneHVACUnitHeater_Impl ImplType; explicit ZoneHVACUnitHeater(std::shared_ptr<detail::ZoneHVACUnitHeater_Impl> impl); friend class detail::ZoneHVACUnitHeater_Impl; friend class Model; friend class IdfObject; friend class openstudio::detail::IdfObject_Impl; /// @endcond private: REGISTER_LOGGER("openstudio.model.ZoneHVACUnitHeater"); }; /** \relates ZoneHVACUnitHeater*/ typedef boost::optional<ZoneHVACUnitHeater> OptionalZoneHVACUnitHeater; /** \relates ZoneHVACUnitHeater*/ typedef std::vector<ZoneHVACUnitHeater> ZoneHVACUnitHeaterVector; } // model } // openstudio #endif // MODEL_ZONEHVACUNITHEATER_HPP
33.521739
127
0.743191
hongyuanjia
ba92c975def3746fdae34b3de708f2ecfa990d60
2,361
cpp
C++
src/pbrt/gpu/samples.cpp
meistdan/pbrt-v4
376c58ee77be6cc38790671b18bba239a68a5fe8
[ "Apache-2.0" ]
4
2020-08-24T19:35:00.000Z
2020-10-28T02:16:21.000Z
src/pbrt/gpu/samples.cpp
meistdan/pbrt-v4
376c58ee77be6cc38790671b18bba239a68a5fe8
[ "Apache-2.0" ]
null
null
null
src/pbrt/gpu/samples.cpp
meistdan/pbrt-v4
376c58ee77be6cc38790671b18bba239a68a5fe8
[ "Apache-2.0" ]
1
2020-08-30T14:23:07.000Z
2020-08-30T14:23:07.000Z
// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. // The pbrt source code is licensed under the Apache License, Version 2.0. // SPDX: Apache-2.0 #include <pbrt/pbrt.h> #include <pbrt/gpu/pathintegrator.h> #include <pbrt/samplers.h> #include <type_traits> namespace pbrt { template <typename Sampler> void GPUPathIntegrator::GenerateRaySamples(int depth, int sampleIndex) { std::string desc = std::string("Generate ray samples - ") + Sampler::Name(); RayQueue *rayQueue = CurrentRayQueue(depth); ForAllQueued(desc.c_str(), rayQueue, maxQueueSize, PBRT_GPU_LAMBDA(const RayWorkItem w, int index) { // Figure out how many dimensions have been consumed so far: 5 // are used for the initial camera sample and then either 7 or // 10 per ray, depending on whether there's subsurface // scattering. int dimension = 5 + 7 * depth; if (haveSubsurface) dimension += 3 * depth; // Initialize a Sampler Sampler pixelSampler = *sampler.Cast<Sampler>(); Point2i pPixel = pixelSampleState.pPixel[w.pixelIndex]; pixelSampler.StartPixelSample(pPixel, sampleIndex, dimension); // Generate the samples for the ray and store them with it in // the ray queue. RaySamples rs; rs.direct.u = pixelSampler.Get2D(); rs.direct.uc = pixelSampler.Get1D(); rs.indirect.u = pixelSampler.Get2D(); rs.indirect.uc = pixelSampler.Get1D(); rs.indirect.rr = pixelSampler.Get1D(); rs.haveSubsurface = haveSubsurface; if (haveSubsurface) { rs.subsurface.uc = pixelSampler.Get1D(); rs.subsurface.u = pixelSampler.Get2D(); } pixelSampleState.samples[w.pixelIndex] = rs; }); } void GPUPathIntegrator::GenerateRaySamples(int depth, int sampleIndex) { auto generateSamples = [=](auto sampler) { using Sampler = std::remove_reference_t<decltype(*sampler)>; if constexpr (!std::is_same_v<Sampler, MLTSampler> && !std::is_same_v<Sampler, DebugMLTSampler>) GenerateRaySamples<Sampler>(depth, sampleIndex); }; // Call the appropriate GenerateRaySamples specialization based on the // Sampler's actual type. sampler.DispatchCPU(generateSamples); } } // namespace pbrt
36.323077
80
0.660737
meistdan
ba935dd94be3bfb1e1830f1c93e205c59439be71
10,088
cpp
C++
src/TriangMesh.cpp
NikitaMatckevich/SWE_FVM
bffdcea6292a263514b97fa4f6f93679a7452714
[ "MIT" ]
null
null
null
src/TriangMesh.cpp
NikitaMatckevich/SWE_FVM
bffdcea6292a263514b97fa4f6f93679a7452714
[ "MIT" ]
null
null
null
src/TriangMesh.cpp
NikitaMatckevich/SWE_FVM
bffdcea6292a263514b97fa4f6f93679a7452714
[ "MIT" ]
null
null
null
#include <TriangMesh.h> #include <iostream> #include <fstream> #include <functional> #include <string> using namespace std; struct EdgeHash { std::size_t operator()(const EdgeTag& e) const { return std::hash<Idx>()(e[0]) ^ (std::hash<Idx>()(e[1]) << 1); } }; struct EdgeEqual { bool operator()(const EdgeTag& lhs, const EdgeTag& rhs) const { return lhs[0] == rhs[0] && lhs[1] == rhs[1]; } }; // PARSING OF MSH FILE TriangMesh::TriangMesh(const string& filename) { ifstream msh(filename); if (!msh.is_open()) { throw MeshError("cannot open mesh file " + filename); } string line; auto FindSection = bind([&filename](ifstream& msh, string& line, const string& sectname) { while (getline(msh, line) && line.find(sectname) != 0); if (msh.eof()) throw MeshError("EOF while looking for " + sectname + " section in " + filename); }, std::ref(msh), std::ref(line), std::placeholders::_1); constexpr auto msh_size = numeric_limits<streamsize>::max(); FindSection("$MeshFormat"); double version; Idx is_binary; msh >> version >> is_binary; if (version < 4.1) { throw MeshError("mesh format in " + filename + " is not >= 4.1 version, the current version is: " + to_string(version)); } if (is_binary == 1) { throw MeshError("mesh format in " + filename + " is binary, not supported"); } FindSection("$Entities"); Idx num_entity_points, num_entity_curves, num_entity_blocks; msh >> num_entity_points >> num_entity_curves; msh.ignore(msh_size, '\n'); vector<Idx> physical_groups(num_entity_curves); while (getline(msh, line) && (--num_entity_points > 0)); for (Idx curve = 1; curve <= num_entity_curves; curve++) { Idx curve_tag, num_physical_tags, physical_tag; double min_x, min_y, min_z, max_x, max_y, max_z; msh >> curve_tag; if (curve != curve_tag) { throw MeshError("curve tags in " + filename + " are not consequent"); } msh >> min_x >> min_y >> min_z; msh >> max_x >> max_y >> max_z; msh >> num_physical_tags; if (num_physical_tags != 1) { throw MeshError("ambiguous definition of boundary condition at file " + filename); } msh >> physical_tag; physical_groups[curve-1] = physical_tag; msh.ignore(msh_size, '\n'); } FindSection("$Nodes"); Idx num_nodes; msh >> num_entity_blocks >> num_nodes; msh.ignore(msh_size, '\n'); m_p.resize(Eigen::NoChange, num_nodes); for (Idx block = 1, current_node = 0; block <= num_entity_blocks; block++) { Idx entity_dim, entity_tag, parametric, nodes_in_block; msh >> entity_dim >> entity_tag >> parametric >> nodes_in_block; Idx cnt = nodes_in_block; while (getline(msh, line) && (cnt-- > 0)); for (Idx node = 1; node <= nodes_in_block; node++) { double x, y; msh >> x >> y; m_p(0, current_node) = x; m_p(1, current_node) = y; current_node++; msh.ignore(msh_size, '\n'); } } FindSection("$Elements"); Idx num_elements; msh >> num_entity_blocks >> num_elements; msh.ignore(msh_size, '\n'); unordered_map<EdgeTag, Idx, EdgeHash, EdgeEqual> edge_ids; m_edge_triangs.resize(2 * num_nodes - 1, Eigen::NoChange); for (Idx block = 1; block < num_entity_blocks; block++) { Idx entity_dim, entity_tag, elem_type, elems_in_block; msh >> entity_dim >> entity_tag >> elem_type >> elems_in_block; if (elem_type != 1) { throw MeshError("unknown elements before triangles in " + filename + ", expected only boundary edges"); } for (Idx elem = 1; elem <= elems_in_block; elem++) { Idx id, beg, end; msh >> id >> beg >> end; if (--beg > --end) std::swap(beg, end); edge_ids.emplace(make_pair(EdgeTag{beg, end}, edge_ids.size())); m_edge_triangs(edge_ids.size() - 1, 1) = -physical_groups[entity_tag-1]; msh.ignore(msh_size, '\n'); } } Idx entity_dim, entity_tag, elem_type, num_triangs; msh >> entity_dim >> entity_tag >> elem_type >> num_triangs; if (elem_type != 2) { throw MeshError("last element block of " + filename + " should be a block of triangles"); } m_edge_triangs.conservativeResize(num_nodes + num_triangs - 1, Eigen::NoChange); m_triang_points.resize(num_triangs, Eigen::NoChange); m_triang_edges.resize(num_triangs, Eigen::NoChange); m_triang_triangs.resize(num_triangs, Eigen::NoChange); for (Idx it = 0; it < num_triangs; it++) { Idx elem_id, pts[3]; msh >> elem_id >> pts[0] >> pts[1] >> pts[2]; for (short int k = 0; k < 3; k++) { Idx pa = pts[k] - 1; Idx pb = pts[(k + 1) % 3] - 1; m_triang_points(it, k) = pa; if (pa > pb) std::swap(pa, pb); auto insertion = edge_ids.emplace(EdgeTag{pa, pb}, edge_ids.size()); Idx edge_id = (*insertion.first).second; m_triang_edges(it, k) = edge_id; if (insertion.second) { m_edge_triangs(edge_id, 1) = it; } else { m_edge_triangs(edge_id, 0) = it; Idx itk = m_edge_triangs(edge_id, 1); m_triang_triangs(it, k) = itk; if (itk >= 0) { Idx l; (m_triang_edges.row(itk) == edge_id).maxCoeff(&l); m_triang_triangs(itk, l) = it; } } } } m_edge_points.resize(edge_ids.size(), Eigen::NoChange); for (const auto& edge : edge_ids) { m_edge_points(edge.second, 0) = edge.first[0]; m_edge_points(edge.second, 1) = edge.first[1]; } } using namespace Eigen; #include "PointOperations.h" using NodeTag = TriangMesh::NodeTag; EdgeTag TriangMesh::EdgePoints(NodeTag i) const { return m_edge_points.row(i); } EdgeTag TriangMesh::EdgeTriangs(NodeTag i) const { return m_edge_triangs.row(i); } bool TriangMesh::IsEdgeBoundary(NodeTag i) const { return m_edge_triangs(i, 1) < 0; } TriangTag TriangMesh::TriangPoints(NodeTag i) const { return m_triang_points.row(i); } TriangTag TriangMesh::TriangEdges(NodeTag i) const { return m_triang_edges.row(i); } TriangTag TriangMesh::TriangTriangs(NodeTag i) const { return m_triang_triangs.row(i); } bool TriangMesh::IsTriangleBoundary(NodeTag i) const { auto ie = m_triang_edges.row(i); return ie.unaryExpr([this](NodeTag i) { return this->IsEdgeBoundary(i); }).any(); } Point TriangMesh::P(NodeTag i) const { return m_p.col(i); } Point TriangMesh::T(NodeTag i) const { const auto& ip = m_triang_points.row(i); return 1. / 3. * (m_p.col(ip[0]) + m_p.col(ip[1]) + m_p.col(ip[2])); } Point TriangMesh::E(NodeTag i) const { const auto& ip = m_edge_points.row(i); return 0.5 * (m_p.col(ip[0]) + m_p.col(ip[1])); } Point TriangMesh::C(NodeTag i) const { const auto& ip = m_edge_points.row(i); if (IsEdgeBoundary(i)) return 0.5 * (P(ip[0]) + P(ip[1])); const auto& it = m_edge_triangs.row(i); return Intersection(P(ip[0]), P(ip[1]), T(it[0]), T(it[1])); } PointArray TriangMesh::P(NodeTagArray const& i) const { return m_p(all, i); } PointArray TriangMesh::T(NodeTagArray const& i) const { PointArray res(2, i.rows()); for (NodeTag k = 0; k < i.size(); k++) res.col(k) = T(i[k]); return res; } PointArray TriangMesh::E(NodeTagArray const& i) const { PointArray res(i.rows(), 1); for (NodeTag k = 0; k < i.size(); k++) res.col(k) = E(i[k]); return res; } PointArray TriangMesh::C(NodeTagArray const& i) const { PointArray res(i.rows(), 1); for (NodeTag k = 0; k < i.size(); k++) res.col(k) = C(i[k]); return res; } Vector2d TriangMesh::Tang(NodeTag ie, NodeTag it) const { NodeTag a = m_edge_points(ie, 0); NodeTag b = m_edge_points(ie, 1); Vector2d tan = (P(b) - P(a)).matrix() / L(ie); if (Det(T(it) - P(a), tan) > 0.) { tan = -tan; } return tan; } Vector2d TriangMesh::Norm(NodeTag ie, NodeTag it) const { return (Matrix2d() << 0, 1, -1, 0).finished() * Tang(ie, it); } double TriangMesh::L(NodeTag ie) const { const auto& ip = m_edge_points.row(ie); return Len(P(ip[0]), P(ip[1])); } double TriangMesh::Area(NodeTag it) const { const auto& ip = m_triang_points.row(it); return TriangArea(P(ip[0]), P(ip[1]), P(ip[2])); } double MaxTriangArea(TriangMesh const& m) { double max_s = 0.; for (size_t i = 0; i < m.NumTriangles(); i++) { double s = m.Area(i); if (s > max_s) max_s = s; } return max_s; } // SIMPLE I/O #include <iostream> void Info(ostream& out, const TriangMesh& m) { out.setf(ios::left, ios::adjustfield); auto WriteComment = bind( [&](ostream& out, Idx wid, string_view c) { out.width(wid); out << c << ' '; }, ref(out), std::placeholders::_1, std::placeholders::_2); auto WriteLine = [&](auto n, string_view c1, auto v1, string_view c2, auto v2, string_view c3, auto v3, string_view c4, auto v4) { out.width(4); out << n << ' '; WriteComment(7, c1); out.width(3); out << v1 << ' '; WriteComment(10, c2); out.width(3); out << v2 << ' '; WriteComment(11, c3); out.width(3); out << v3 << ' '; WriteComment(14, c4); out.width(3); out << v4 << ' '; out << '\n'; }; out << "TRIANGULAR MESH :\n"; out << "nodes: total = " << m.NumNodes() << '\n'; for (size_t i = 0; i < m.NumNodes(); ++i) { WriteLine(i, "points:", m.P(i).transpose(), "" , "", "" , "", "" , ""); } out << "edges: total = " << m.NumEdges() << '\n'; for (size_t i = 0; i < m.NumEdges(); ++i) { WriteLine(i, "points:" , m.EdgePoints(i), "triangles:", m.EdgeTriangs(i), "center at:", m.E(i).transpose(), "" , ""); } out << "triangles: total = " << m.NumTriangles() << ";\tmax area = " << MaxTriangArea(m) << '\n'; for (size_t i = 0; i < m.NumTriangles(); ++i) { WriteLine(i, "points:" , m.TriangPoints(i), "edges:" , m.TriangEdges(i), "neighbours:" , m.TriangTriangs(i), "barycenter at:", m.E(i).transpose()); } }
30.477341
92
0.598632
NikitaMatckevich
ba967e44ca2effe2e766a08b7240a470b224d4dc
2,561
cpp
C++
lesson04/src/disjoint_set.cpp
Usdjy/CPPExercises2021
a4ab46a8726f57c08171e1236566d48779332bbf
[ "MIT" ]
1
2021-12-14T19:28:32.000Z
2021-12-14T19:28:32.000Z
lesson04/src/disjoint_set.cpp
Usdjy/CPPExercises2021
a4ab46a8726f57c08171e1236566d48779332bbf
[ "MIT" ]
null
null
null
lesson04/src/disjoint_set.cpp
Usdjy/CPPExercises2021
a4ab46a8726f57c08171e1236566d48779332bbf
[ "MIT" ]
null
null
null
#include "disjoint_set.h" #define ROOT -1 // объявили макрос (считайте константу) равный минус единице - чтобы не было "волшебной переменной", а была именованная константа "корень дерева" using namespace std; DisjointSet::DisjointSet(int size) { parent = std::vector<int>(size); ranks = std::vector<int>(size); sizes = std::vector<int>(size); // - заполните вектора так чтобы на этапе конструирования эта система непересекающихся множеств состояла из: // size элементов, каждый из которых состоит в своем множестве (а значит ссылка на родителя у него - на корень, т.е. на ROOT, а какой тогда ранк и размер у множества каждого элемента?) for(int i=0;i<size;++i) {parent[i]=ROOT;ranks[i]=0;sizes[i]=1;} // заполнить parents // заполнить ranks // заполнить sizes } int DisjointSet::get_set(int element) { // по номеру элемента нужно переходя по ссылкам на родителя дойти до самого верхнего элемента, // номер этого корневого элемента - номер множества на данный момент (кто вверху тот и главный, множество названо в его честь) vector <int> v; while(parent[element]!=(-1)) {v.push_back(element);element=parent[element];} for(auto h:v) parent[h]=element; return element; } int DisjointSet::count_differents() const { // сколько разных множеств (подсказка: в каждом множестве ровно один корень, а корень - это тот у кого родитель = ROOT) int count = 0; for (size_t i = 0; i < this->parent.size(); i++) { if(parent[i]==(-1)) ++count; } return count; } int DisjointSet::get_set_size(int element) { // сообщить сколько элементов в множестве, которому принадлежит данный элемент (да, это очень просто) return sizes[get_set(element)]; } int DisjointSet::union_sets(int element0, int element1) { // узнать корневые элементы этих двух элементов и посмотрев на них - решить, // кого из них подвесить к другому (тем самым объединить два множества) // при этом стоит подвешивать менее высокое дерево к более высокому (т.е. учитывая ранк), // а так же важно не забыть после переподвешивания у корневого элемента обновить ранк и размер множества element0=get_set(element0);element1=get_set(element1); if(ranks[element0]<ranks[element1]) {parent[element0]=element1;sizes[element1]+=sizes[element0];return element1;} else if(ranks[element0]==ranks[element1]) {parent[element0]=element1;++ranks[element0];sizes[element1]+=sizes[element0];return element1;} else {parent[element1]=element0;sizes[element0]+=sizes[element1];return element0;} }
46.563636
188
0.717688
Usdjy
ba9699bbe1b1102ad971f284ca2343ee5db0175f
2,834
cxx
C++
src/python/lib/graph/agglo/merge_rules.cxx
DerThorsten/n3p
c4bd4cd90f20e68f0dbd62587aba28e4752a0ac1
[ "MIT" ]
38
2016-06-29T07:42:50.000Z
2021-12-09T09:25:25.000Z
src/python/lib/graph/agglo/merge_rules.cxx
tbullmann/nifty
00119fd4753817b931272d6d3120b6ebd334882a
[ "MIT" ]
62
2016-07-27T16:07:53.000Z
2022-03-30T17:24:36.000Z
src/python/lib/graph/agglo/merge_rules.cxx
tbullmann/nifty
00119fd4753817b931272d6d3120b6ebd334882a
[ "MIT" ]
20
2016-01-25T21:21:52.000Z
2021-12-09T09:25:16.000Z
#include <pybind11/pybind11.h> #include <pybind11/numpy.h> #include "nifty/graph/agglo/cluster_policies/detail/merge_rules.hxx" namespace py = pybind11; PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>); namespace nifty{ namespace graph{ namespace agglo{ void exportMergeRules(py::module & aggloModule) { py::class_<merge_rules::ArithmeticMeanSettings>(aggloModule, "ArithmeticMeanSettings") .def(py::init<>()) .def("__str__",[](const merge_rules::ArithmeticMeanSettings & self){ return self.name(); }) ; py::class_<merge_rules::SumSettings>(aggloModule, "SumSettings") .def(py::init<>()) .def("__str__",[](const merge_rules::SumSettings & self){ return self.name(); }) ; py::class_<merge_rules::GeneralizedMeanSettings>(aggloModule, "GeneralizedMeanSettings") // .def( // py::init([](double val) { return new merge_rules::GeneralizedMeanSettings(val); }) // ) .def(py::init<double>(), py::arg("p")=1.0 ) .def("__str__",[](const merge_rules::GeneralizedMeanSettings & self){ return self.name(); }) ; py::class_<merge_rules::SmoothMaxSettings>(aggloModule, "SmoothMaxSettings") .def(py::init<double>(), py::arg("p")=1.0 ) .def("__str__",[](const merge_rules::SmoothMaxSettings & self){ return self.name(); }) ; py::class_<merge_rules::RankOrderSettings>(aggloModule, "RankOrderSettings") .def(py::init<double, uint16_t>(), py::arg("q")=0.5, py::arg("numberOfBins")=50 ) .def("__str__",[](const merge_rules::RankOrderSettings & self){ return self.name(); }) ; py::class_<merge_rules::MaxSettings>(aggloModule, "MaxSettings") .def(py::init<>()) .def("__str__",[](const merge_rules::MaxSettings & self){ return self.name(); }) ; py::class_<merge_rules::MutexWatershedSettings>(aggloModule, "MutexWatershedSettings") .def(py::init<>()) .def("__str__",[](const merge_rules::MutexWatershedSettings & self){ return self.name(); }) ; py::class_<merge_rules::MinSettings>(aggloModule, "MinSettings") .def(py::init<>()) .def("__str__",[](const merge_rules::MinSettings & self){ return self.name(); }) ; } } // end namespace agglo } // end namespace graph } // end namespace nifty
29.520833
101
0.527876
DerThorsten
ba99973fc95c863217b27689d40b7be4a1daf6fc
26,654
cpp
C++
3rd_party/gslib/ogs/src/ogsKernels.cpp
roystgnr/nekRS
280acd21c3088d7658a8a113e544fce05853d7b4
[ "BSD-3-Clause" ]
null
null
null
3rd_party/gslib/ogs/src/ogsKernels.cpp
roystgnr/nekRS
280acd21c3088d7658a8a113e544fce05853d7b4
[ "BSD-3-Clause" ]
null
null
null
3rd_party/gslib/ogs/src/ogsKernels.cpp
roystgnr/nekRS
280acd21c3088d7658a8a113e544fce05853d7b4
[ "BSD-3-Clause" ]
null
null
null
/* The MIT License (MIT) Copyright (c) 2017 Tim Warburton, Noel Chalmers, Jesse Chan, Ali Karakus Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "ogstypes.h" #include "ogs.hpp" #include "ogsKernels.hpp" namespace ogs { int Nrefs = 0; void* hostBuf; size_t hostBufSize=0; void* haloBuf; occa::memory o_haloBuf; occa::memory h_haloBuf; occa::stream defaultStream; occa::stream dataStream; occa::properties kernelInfo; occa::kernel gatherScatterKernel_floatAdd; occa::kernel gatherScatterKernel_floatMul; occa::kernel gatherScatterKernel_floatMin; occa::kernel gatherScatterKernel_floatMax; occa::kernel gatherScatterKernel_doubleAdd; occa::kernel gatherScatterKernel_doubleMul; occa::kernel gatherScatterKernel_doubleMin; occa::kernel gatherScatterKernel_doubleMax; occa::kernel gatherScatterKernel_intAdd; occa::kernel gatherScatterKernel_intMul; occa::kernel gatherScatterKernel_intMin; occa::kernel gatherScatterKernel_intMax; occa::kernel gatherScatterKernel_longAdd; occa::kernel gatherScatterKernel_longMul; occa::kernel gatherScatterKernel_longMin; occa::kernel gatherScatterKernel_longMax; occa::kernel gatherScatterVecKernel_floatAdd; occa::kernel gatherScatterVecKernel_floatMul; occa::kernel gatherScatterVecKernel_floatMin; occa::kernel gatherScatterVecKernel_floatMax; occa::kernel gatherScatterVecKernel_doubleAdd; occa::kernel gatherScatterVecKernel_doubleMul; occa::kernel gatherScatterVecKernel_doubleMin; occa::kernel gatherScatterVecKernel_doubleMax; occa::kernel gatherScatterVecKernel_intAdd; occa::kernel gatherScatterVecKernel_intMul; occa::kernel gatherScatterVecKernel_intMin; occa::kernel gatherScatterVecKernel_intMax; occa::kernel gatherScatterVecKernel_longAdd; occa::kernel gatherScatterVecKernel_longMul; occa::kernel gatherScatterVecKernel_longMin; occa::kernel gatherScatterVecKernel_longMax; occa::kernel gatherScatterManyKernel_floatAdd; occa::kernel gatherScatterManyKernel_floatMul; occa::kernel gatherScatterManyKernel_floatMin; occa::kernel gatherScatterManyKernel_floatMax; occa::kernel gatherScatterManyKernel_doubleAdd; occa::kernel gatherScatterManyKernel_doubleMul; occa::kernel gatherScatterManyKernel_doubleMin; occa::kernel gatherScatterManyKernel_doubleMax; occa::kernel gatherScatterManyKernel_intAdd; occa::kernel gatherScatterManyKernel_intMul; occa::kernel gatherScatterManyKernel_intMin; occa::kernel gatherScatterManyKernel_intMax; occa::kernel gatherScatterManyKernel_longAdd; occa::kernel gatherScatterManyKernel_longMul; occa::kernel gatherScatterManyKernel_longMin; occa::kernel gatherScatterManyKernel_longMax; occa::kernel gatherKernel_floatAdd; occa::kernel gatherKernel_floatMul; occa::kernel gatherKernel_floatMin; occa::kernel gatherKernel_floatMax; occa::kernel gatherKernel_doubleAdd; occa::kernel gatherKernel_doubleMul; occa::kernel gatherKernel_doubleMin; occa::kernel gatherKernel_doubleMax; occa::kernel gatherKernel_intAdd; occa::kernel gatherKernel_intMul; occa::kernel gatherKernel_intMin; occa::kernel gatherKernel_intMax; occa::kernel gatherKernel_longAdd; occa::kernel gatherKernel_longMul; occa::kernel gatherKernel_longMin; occa::kernel gatherKernel_longMax; occa::kernel gatherVecKernel_floatAdd; occa::kernel gatherVecKernel_floatMul; occa::kernel gatherVecKernel_floatMin; occa::kernel gatherVecKernel_floatMax; occa::kernel gatherVecKernel_doubleAdd; occa::kernel gatherVecKernel_doubleMul; occa::kernel gatherVecKernel_doubleMin; occa::kernel gatherVecKernel_doubleMax; occa::kernel gatherVecKernel_intAdd; occa::kernel gatherVecKernel_intMul; occa::kernel gatherVecKernel_intMin; occa::kernel gatherVecKernel_intMax; occa::kernel gatherVecKernel_longAdd; occa::kernel gatherVecKernel_longMul; occa::kernel gatherVecKernel_longMin; occa::kernel gatherVecKernel_longMax; occa::kernel gatherManyKernel_floatAdd; occa::kernel gatherManyKernel_floatMul; occa::kernel gatherManyKernel_floatMin; occa::kernel gatherManyKernel_floatMax; occa::kernel gatherManyKernel_doubleAdd; occa::kernel gatherManyKernel_doubleMul; occa::kernel gatherManyKernel_doubleMin; occa::kernel gatherManyKernel_doubleMax; occa::kernel gatherManyKernel_intAdd; occa::kernel gatherManyKernel_intMul; occa::kernel gatherManyKernel_intMin; occa::kernel gatherManyKernel_intMax; occa::kernel gatherManyKernel_longAdd; occa::kernel gatherManyKernel_longMul; occa::kernel gatherManyKernel_longMin; occa::kernel gatherManyKernel_longMax; occa::kernel scatterKernel_float; occa::kernel scatterKernel_double; occa::kernel scatterKernel_int; occa::kernel scatterKernel_long; occa::kernel scatterVecKernel_float; occa::kernel scatterVecKernel_double; occa::kernel scatterVecKernel_int; occa::kernel scatterVecKernel_long; occa::kernel scatterManyKernel_float; occa::kernel scatterManyKernel_double; occa::kernel scatterManyKernel_int; occa::kernel scatterManyKernel_long; } void ogs::initKernels(MPI_Comm comm, occa::device device) { int rank, size; MPI_Comm_rank(comm, &rank); MPI_Comm_size(comm, &size); ogs::defaultStream = device.getStream(); ogs::dataStream = device.createStream(); ogs::kernelInfo["defines"].asObject(); ogs::kernelInfo["includes"].asArray(); ogs::kernelInfo["header"].asArray(); ogs::kernelInfo["flags"].asObject(); if(sizeof(dlong)==4){ ogs::kernelInfo["defines/" "dlong"]="int"; } if(sizeof(hlong)==8){ ogs::kernelInfo["defines/" "hlong"]="long long int"; } if(sizeof(dfloat) == sizeof(double)){ ogs::kernelInfo["defines/" "dfloat"]= "double"; ogs::kernelInfo["defines/" "dfloat4"]= "double4"; } else if(sizeof(dfloat) == sizeof(float)){ ogs::kernelInfo["defines/" "dfloat"]= "float"; ogs::kernelInfo["defines/" "dfloat4"]= "float4"; } if(device.mode()=="OpenCL"){ //ogs::kernelInfo["compiler_flags"] += "-cl-opt-disable"; ogs::kernelInfo["compiler_flags"] += " -cl-std=CL2.0 "; ogs::kernelInfo["compiler_flags"] += " -cl-strict-aliasing "; ogs::kernelInfo["compiler_flags"] += " -cl-mad-enable "; ogs::kernelInfo["defines/" "hlong"]="long"; } if(device.mode()=="CUDA"){ // add backend compiler optimization for CUDA ogs::kernelInfo["compiler_flags"] += " --ftz=true "; ogs::kernelInfo["compiler_flags"] += " --prec-div=false "; ogs::kernelInfo["compiler_flags"] += " --prec-sqrt=false "; ogs::kernelInfo["compiler_flags"] += " --use_fast_math "; ogs::kernelInfo["compiler_flags"] += " --fmad=true "; // compiler option for cuda } MPI_Barrier(comm); double tStartLoadKernel = MPI_Wtime(); if(rank == 0) printf("loading gs kernels ... "); fflush(stdout); for (int r=0;r<2;r++){ if ((r==0 && rank==0) || (r==1 && rank>0)) { ogs::gatherScatterKernel_floatAdd = device.buildKernel(DOGS "/okl/gatherScatter.okl", "gatherScatter_floatAdd", ogs::kernelInfo); ogs::gatherScatterKernel_floatMul = device.buildKernel(DOGS "/okl/gatherScatter.okl", "gatherScatter_floatMul", ogs::kernelInfo); ogs::gatherScatterKernel_floatMin = device.buildKernel(DOGS "/okl/gatherScatter.okl", "gatherScatter_floatMin", ogs::kernelInfo); ogs::gatherScatterKernel_floatMax = device.buildKernel(DOGS "/okl/gatherScatter.okl", "gatherScatter_floatMax", ogs::kernelInfo); ogs::gatherScatterKernel_doubleAdd = device.buildKernel(DOGS "/okl/gatherScatter.okl", "gatherScatter_doubleAdd", ogs::kernelInfo); ogs::gatherScatterKernel_doubleMul = device.buildKernel(DOGS "/okl/gatherScatter.okl", "gatherScatter_doubleMul", ogs::kernelInfo); ogs::gatherScatterKernel_doubleMin = device.buildKernel(DOGS "/okl/gatherScatter.okl", "gatherScatter_doubleMin", ogs::kernelInfo); ogs::gatherScatterKernel_doubleMax = device.buildKernel(DOGS "/okl/gatherScatter.okl", "gatherScatter_doubleMax", ogs::kernelInfo); ogs::gatherScatterKernel_intAdd = device.buildKernel(DOGS "/okl/gatherScatter.okl", "gatherScatter_intAdd", ogs::kernelInfo); ogs::gatherScatterKernel_intMul = device.buildKernel(DOGS "/okl/gatherScatter.okl", "gatherScatter_intMul", ogs::kernelInfo); ogs::gatherScatterKernel_intMin = device.buildKernel(DOGS "/okl/gatherScatter.okl", "gatherScatter_intMin", ogs::kernelInfo); ogs::gatherScatterKernel_intMax = device.buildKernel(DOGS "/okl/gatherScatter.okl", "gatherScatter_intMax", ogs::kernelInfo); ogs::gatherScatterKernel_longAdd = device.buildKernel(DOGS "/okl/gatherScatter.okl", "gatherScatter_longAdd", ogs::kernelInfo); ogs::gatherScatterKernel_longMul = device.buildKernel(DOGS "/okl/gatherScatter.okl", "gatherScatter_longMul", ogs::kernelInfo); ogs::gatherScatterKernel_longMin = device.buildKernel(DOGS "/okl/gatherScatter.okl", "gatherScatter_longMin", ogs::kernelInfo); ogs::gatherScatterKernel_longMax = device.buildKernel(DOGS "/okl/gatherScatter.okl", "gatherScatter_longMax", ogs::kernelInfo); ogs::gatherScatterVecKernel_floatAdd = device.buildKernel(DOGS "/okl/gatherScatterVec.okl", "gatherScatterVec_floatAdd", ogs::kernelInfo); ogs::gatherScatterVecKernel_floatMul = device.buildKernel(DOGS "/okl/gatherScatterVec.okl", "gatherScatterVec_floatMul", ogs::kernelInfo); ogs::gatherScatterVecKernel_floatMin = device.buildKernel(DOGS "/okl/gatherScatterVec.okl", "gatherScatterVec_floatMin", ogs::kernelInfo); ogs::gatherScatterVecKernel_floatMax = device.buildKernel(DOGS "/okl/gatherScatterVec.okl", "gatherScatterVec_floatMax", ogs::kernelInfo); ogs::gatherScatterVecKernel_doubleAdd = device.buildKernel(DOGS "/okl/gatherScatterVec.okl", "gatherScatterVec_doubleAdd", ogs::kernelInfo); ogs::gatherScatterVecKernel_doubleMul = device.buildKernel(DOGS "/okl/gatherScatterVec.okl", "gatherScatterVec_doubleMul", ogs::kernelInfo); ogs::gatherScatterVecKernel_doubleMin = device.buildKernel(DOGS "/okl/gatherScatterVec.okl", "gatherScatterVec_doubleMin", ogs::kernelInfo); ogs::gatherScatterVecKernel_doubleMax = device.buildKernel(DOGS "/okl/gatherScatterVec.okl", "gatherScatterVec_doubleMax", ogs::kernelInfo); ogs::gatherScatterVecKernel_intAdd = device.buildKernel(DOGS "/okl/gatherScatterVec.okl", "gatherScatterVec_intAdd", ogs::kernelInfo); ogs::gatherScatterVecKernel_intMul = device.buildKernel(DOGS "/okl/gatherScatterVec.okl", "gatherScatterVec_intMul", ogs::kernelInfo); ogs::gatherScatterVecKernel_intMin = device.buildKernel(DOGS "/okl/gatherScatterVec.okl", "gatherScatterVec_intMin", ogs::kernelInfo); ogs::gatherScatterVecKernel_intMax = device.buildKernel(DOGS "/okl/gatherScatterVec.okl", "gatherScatterVec_intMax", ogs::kernelInfo); ogs::gatherScatterVecKernel_longAdd = device.buildKernel(DOGS "/okl/gatherScatterVec.okl", "gatherScatterVec_longAdd", ogs::kernelInfo); ogs::gatherScatterVecKernel_longMul = device.buildKernel(DOGS "/okl/gatherScatterVec.okl", "gatherScatterVec_longMul", ogs::kernelInfo); ogs::gatherScatterVecKernel_longMin = device.buildKernel(DOGS "/okl/gatherScatterVec.okl", "gatherScatterVec_longMin", ogs::kernelInfo); ogs::gatherScatterVecKernel_longMax = device.buildKernel(DOGS "/okl/gatherScatterVec.okl", "gatherScatterVec_longMax", ogs::kernelInfo); ogs::gatherScatterManyKernel_floatAdd = device.buildKernel(DOGS "/okl/gatherScatterMany.okl", "gatherScatterMany_floatAdd", ogs::kernelInfo); ogs::gatherScatterManyKernel_floatMul = device.buildKernel(DOGS "/okl/gatherScatterMany.okl", "gatherScatterMany_floatMul", ogs::kernelInfo); ogs::gatherScatterManyKernel_floatMin = device.buildKernel(DOGS "/okl/gatherScatterMany.okl", "gatherScatterMany_floatMin", ogs::kernelInfo); ogs::gatherScatterManyKernel_floatMax = device.buildKernel(DOGS "/okl/gatherScatterMany.okl", "gatherScatterMany_floatMax", ogs::kernelInfo); ogs::gatherScatterManyKernel_doubleAdd = device.buildKernel(DOGS "/okl/gatherScatterMany.okl", "gatherScatterMany_doubleAdd", ogs::kernelInfo); ogs::gatherScatterManyKernel_doubleMul = device.buildKernel(DOGS "/okl/gatherScatterMany.okl", "gatherScatterMany_doubleMul", ogs::kernelInfo); ogs::gatherScatterManyKernel_doubleMin = device.buildKernel(DOGS "/okl/gatherScatterMany.okl", "gatherScatterMany_doubleMin", ogs::kernelInfo); ogs::gatherScatterManyKernel_doubleMax = device.buildKernel(DOGS "/okl/gatherScatterMany.okl", "gatherScatterMany_doubleMax", ogs::kernelInfo); ogs::gatherScatterManyKernel_intAdd = device.buildKernel(DOGS "/okl/gatherScatterMany.okl", "gatherScatterMany_intAdd", ogs::kernelInfo); ogs::gatherScatterManyKernel_intMul = device.buildKernel(DOGS "/okl/gatherScatterMany.okl", "gatherScatterMany_intMul", ogs::kernelInfo); ogs::gatherScatterManyKernel_intMin = device.buildKernel(DOGS "/okl/gatherScatterMany.okl", "gatherScatterMany_intMin", ogs::kernelInfo); ogs::gatherScatterManyKernel_intMax = device.buildKernel(DOGS "/okl/gatherScatterMany.okl", "gatherScatterMany_intMax", ogs::kernelInfo); ogs::gatherScatterManyKernel_longAdd = device.buildKernel(DOGS "/okl/gatherScatterMany.okl", "gatherScatterMany_longAdd", ogs::kernelInfo); ogs::gatherScatterManyKernel_longMul = device.buildKernel(DOGS "/okl/gatherScatterMany.okl", "gatherScatterMany_longMul", ogs::kernelInfo); ogs::gatherScatterManyKernel_longMin = device.buildKernel(DOGS "/okl/gatherScatterMany.okl", "gatherScatterMany_longMin", ogs::kernelInfo); ogs::gatherScatterManyKernel_longMax = device.buildKernel(DOGS "/okl/gatherScatterMany.okl", "gatherScatterMany_longMax", ogs::kernelInfo); ogs::gatherKernel_floatAdd = device.buildKernel(DOGS "/okl/gather.okl", "gather_floatAdd", ogs::kernelInfo); ogs::gatherKernel_floatMul = device.buildKernel(DOGS "/okl/gather.okl", "gather_floatMul", ogs::kernelInfo); ogs::gatherKernel_floatMin = device.buildKernel(DOGS "/okl/gather.okl", "gather_floatMin", ogs::kernelInfo); ogs::gatherKernel_floatMax = device.buildKernel(DOGS "/okl/gather.okl", "gather_floatMax", ogs::kernelInfo); ogs::gatherKernel_doubleAdd = device.buildKernel(DOGS "/okl/gather.okl", "gather_doubleAdd", ogs::kernelInfo); ogs::gatherKernel_doubleMul = device.buildKernel(DOGS "/okl/gather.okl", "gather_doubleMul", ogs::kernelInfo); ogs::gatherKernel_doubleMin = device.buildKernel(DOGS "/okl/gather.okl", "gather_doubleMin", ogs::kernelInfo); ogs::gatherKernel_doubleMax = device.buildKernel(DOGS "/okl/gather.okl", "gather_doubleMax", ogs::kernelInfo); ogs::gatherKernel_intAdd = device.buildKernel(DOGS "/okl/gather.okl", "gather_intAdd", ogs::kernelInfo); ogs::gatherKernel_intMul = device.buildKernel(DOGS "/okl/gather.okl", "gather_intMul", ogs::kernelInfo); ogs::gatherKernel_intMin = device.buildKernel(DOGS "/okl/gather.okl", "gather_intMin", ogs::kernelInfo); ogs::gatherKernel_intMax = device.buildKernel(DOGS "/okl/gather.okl", "gather_intMax", ogs::kernelInfo); ogs::gatherKernel_longAdd = device.buildKernel(DOGS "/okl/gather.okl", "gather_longAdd", ogs::kernelInfo); ogs::gatherKernel_longMul = device.buildKernel(DOGS "/okl/gather.okl", "gather_longMul", ogs::kernelInfo); ogs::gatherKernel_longMin = device.buildKernel(DOGS "/okl/gather.okl", "gather_longMin", ogs::kernelInfo); ogs::gatherKernel_longMax = device.buildKernel(DOGS "/okl/gather.okl", "gather_longMax", ogs::kernelInfo); ogs::gatherVecKernel_floatAdd = device.buildKernel(DOGS "/okl/gatherVec.okl", "gatherVec_floatAdd", ogs::kernelInfo); ogs::gatherVecKernel_floatMul = device.buildKernel(DOGS "/okl/gatherVec.okl", "gatherVec_floatMul", ogs::kernelInfo); ogs::gatherVecKernel_floatMin = device.buildKernel(DOGS "/okl/gatherVec.okl", "gatherVec_floatMin", ogs::kernelInfo); ogs::gatherVecKernel_floatMax = device.buildKernel(DOGS "/okl/gatherVec.okl", "gatherVec_floatMax", ogs::kernelInfo); ogs::gatherVecKernel_doubleAdd = device.buildKernel(DOGS "/okl/gatherVec.okl", "gatherVec_doubleAdd", ogs::kernelInfo); ogs::gatherVecKernel_doubleMul = device.buildKernel(DOGS "/okl/gatherVec.okl", "gatherVec_doubleMul", ogs::kernelInfo); ogs::gatherVecKernel_doubleMin = device.buildKernel(DOGS "/okl/gatherVec.okl", "gatherVec_doubleMin", ogs::kernelInfo); ogs::gatherVecKernel_doubleMax = device.buildKernel(DOGS "/okl/gatherVec.okl", "gatherVec_doubleMax", ogs::kernelInfo); ogs::gatherVecKernel_intAdd = device.buildKernel(DOGS "/okl/gatherVec.okl", "gatherVec_intAdd", ogs::kernelInfo); ogs::gatherVecKernel_intMul = device.buildKernel(DOGS "/okl/gatherVec.okl", "gatherVec_intMul", ogs::kernelInfo); ogs::gatherVecKernel_intMin = device.buildKernel(DOGS "/okl/gatherVec.okl", "gatherVec_intMin", ogs::kernelInfo); ogs::gatherVecKernel_intMax = device.buildKernel(DOGS "/okl/gatherVec.okl", "gatherVec_intMax", ogs::kernelInfo); ogs::gatherVecKernel_longAdd = device.buildKernel(DOGS "/okl/gatherVec.okl", "gatherVec_longAdd", ogs::kernelInfo); ogs::gatherVecKernel_longMul = device.buildKernel(DOGS "/okl/gatherVec.okl", "gatherVec_longMul", ogs::kernelInfo); ogs::gatherVecKernel_longMin = device.buildKernel(DOGS "/okl/gatherVec.okl", "gatherVec_longMin", ogs::kernelInfo); ogs::gatherVecKernel_longMax = device.buildKernel(DOGS "/okl/gatherVec.okl", "gatherVec_longMax", ogs::kernelInfo); ogs::gatherManyKernel_floatAdd = device.buildKernel(DOGS "/okl/gatherMany.okl", "gatherMany_floatAdd", ogs::kernelInfo); ogs::gatherManyKernel_floatMul = device.buildKernel(DOGS "/okl/gatherMany.okl", "gatherMany_floatMul", ogs::kernelInfo); ogs::gatherManyKernel_floatMin = device.buildKernel(DOGS "/okl/gatherMany.okl", "gatherMany_floatMin", ogs::kernelInfo); ogs::gatherManyKernel_floatMax = device.buildKernel(DOGS "/okl/gatherMany.okl", "gatherMany_floatMax", ogs::kernelInfo); ogs::gatherManyKernel_doubleAdd = device.buildKernel(DOGS "/okl/gatherMany.okl", "gatherMany_doubleAdd", ogs::kernelInfo); ogs::gatherManyKernel_doubleMul = device.buildKernel(DOGS "/okl/gatherMany.okl", "gatherMany_doubleMul", ogs::kernelInfo); ogs::gatherManyKernel_doubleMin = device.buildKernel(DOGS "/okl/gatherMany.okl", "gatherMany_doubleMin", ogs::kernelInfo); ogs::gatherManyKernel_doubleMax = device.buildKernel(DOGS "/okl/gatherMany.okl", "gatherMany_doubleMax", ogs::kernelInfo); ogs::gatherManyKernel_intAdd = device.buildKernel(DOGS "/okl/gatherMany.okl", "gatherMany_intAdd", ogs::kernelInfo); ogs::gatherManyKernel_intMul = device.buildKernel(DOGS "/okl/gatherMany.okl", "gatherMany_intMul", ogs::kernelInfo); ogs::gatherManyKernel_intMin = device.buildKernel(DOGS "/okl/gatherMany.okl", "gatherMany_intMin", ogs::kernelInfo); ogs::gatherManyKernel_intMax = device.buildKernel(DOGS "/okl/gatherMany.okl", "gatherMany_intMax", ogs::kernelInfo); ogs::gatherManyKernel_longAdd = device.buildKernel(DOGS "/okl/gatherMany.okl", "gatherMany_longAdd", ogs::kernelInfo); ogs::gatherManyKernel_longMul = device.buildKernel(DOGS "/okl/gatherMany.okl", "gatherMany_longMul", ogs::kernelInfo); ogs::gatherManyKernel_longMin = device.buildKernel(DOGS "/okl/gatherMany.okl", "gatherMany_longMin", ogs::kernelInfo); ogs::gatherManyKernel_longMax = device.buildKernel(DOGS "/okl/gatherMany.okl", "gatherMany_longMax", ogs::kernelInfo); ogs::scatterKernel_float = device.buildKernel(DOGS "/okl/scatter.okl", "scatter_float", ogs::kernelInfo); ogs::scatterKernel_double = device.buildKernel(DOGS "/okl/scatter.okl", "scatter_double", ogs::kernelInfo); ogs::scatterKernel_int = device.buildKernel(DOGS "/okl/scatter.okl", "scatter_int", ogs::kernelInfo); ogs::scatterKernel_long = device.buildKernel(DOGS "/okl/scatter.okl", "scatter_long", ogs::kernelInfo); ogs::scatterVecKernel_float = device.buildKernel(DOGS "/okl/scatterVec.okl", "scatterVec_float", ogs::kernelInfo); ogs::scatterVecKernel_double = device.buildKernel(DOGS "/okl/scatterVec.okl", "scatterVec_double", ogs::kernelInfo); ogs::scatterVecKernel_int = device.buildKernel(DOGS "/okl/scatterVec.okl", "scatterVec_int", ogs::kernelInfo); ogs::scatterVecKernel_long = device.buildKernel(DOGS "/okl/scatterVec.okl", "scatterVec_long", ogs::kernelInfo); ogs::scatterManyKernel_float = device.buildKernel(DOGS "/okl/scatterMany.okl", "scatterMany_float", ogs::kernelInfo); ogs::scatterManyKernel_double = device.buildKernel(DOGS "/okl/scatterMany.okl", "scatterMany_double", ogs::kernelInfo); ogs::scatterManyKernel_int = device.buildKernel(DOGS "/okl/scatterMany.okl", "scatterMany_int", ogs::kernelInfo); ogs::scatterManyKernel_long = device.buildKernel(DOGS "/okl/scatterMany.okl", "scatterMany_long", ogs::kernelInfo); } MPI_Barrier(comm); } MPI_Barrier(comm); if(rank == 0) printf("done (%gs)\n", MPI_Wtime() - tStartLoadKernel); fflush(stdout); } void ogs::freeKernels() { ogs::gatherScatterKernel_floatAdd.free(); ogs::gatherScatterKernel_floatMul.free(); ogs::gatherScatterKernel_floatMin.free(); ogs::gatherScatterKernel_floatMax.free(); ogs::gatherScatterKernel_doubleAdd.free(); ogs::gatherScatterKernel_doubleMul.free(); ogs::gatherScatterKernel_doubleMin.free(); ogs::gatherScatterKernel_doubleMax.free(); ogs::gatherScatterKernel_intAdd.free(); ogs::gatherScatterKernel_intMul.free(); ogs::gatherScatterKernel_intMin.free(); ogs::gatherScatterKernel_intMax.free(); ogs::gatherScatterKernel_longAdd.free(); ogs::gatherScatterKernel_longMul.free(); ogs::gatherScatterKernel_longMin.free(); ogs::gatherScatterKernel_longMax.free(); ogs::gatherScatterVecKernel_floatAdd.free(); ogs::gatherScatterVecKernel_floatMul.free(); ogs::gatherScatterVecKernel_floatMin.free(); ogs::gatherScatterVecKernel_floatMax.free(); ogs::gatherScatterVecKernel_doubleAdd.free(); ogs::gatherScatterVecKernel_doubleMul.free(); ogs::gatherScatterVecKernel_doubleMin.free(); ogs::gatherScatterVecKernel_doubleMax.free(); ogs::gatherScatterVecKernel_intAdd.free(); ogs::gatherScatterVecKernel_intMul.free(); ogs::gatherScatterVecKernel_intMin.free(); ogs::gatherScatterVecKernel_intMax.free(); ogs::gatherScatterVecKernel_longAdd.free(); ogs::gatherScatterVecKernel_longMul.free(); ogs::gatherScatterVecKernel_longMin.free(); ogs::gatherScatterVecKernel_longMax.free(); ogs::gatherScatterManyKernel_floatAdd.free(); ogs::gatherScatterManyKernel_floatMul.free(); ogs::gatherScatterManyKernel_floatMin.free(); ogs::gatherScatterManyKernel_floatMax.free(); ogs::gatherScatterManyKernel_doubleAdd.free(); ogs::gatherScatterManyKernel_doubleMul.free(); ogs::gatherScatterManyKernel_doubleMin.free(); ogs::gatherScatterManyKernel_doubleMax.free(); ogs::gatherScatterManyKernel_intAdd.free(); ogs::gatherScatterManyKernel_intMul.free(); ogs::gatherScatterManyKernel_intMin.free(); ogs::gatherScatterManyKernel_intMax.free(); ogs::gatherScatterManyKernel_longAdd.free(); ogs::gatherScatterManyKernel_longMul.free(); ogs::gatherScatterManyKernel_longMin.free(); ogs::gatherScatterManyKernel_longMax.free(); ogs::gatherKernel_floatAdd.free(); ogs::gatherKernel_floatMul.free(); ogs::gatherKernel_floatMin.free(); ogs::gatherKernel_floatMax.free(); ogs::gatherKernel_doubleAdd.free(); ogs::gatherKernel_doubleMul.free(); ogs::gatherKernel_doubleMin.free(); ogs::gatherKernel_doubleMax.free(); ogs::gatherKernel_intAdd.free(); ogs::gatherKernel_intMul.free(); ogs::gatherKernel_intMin.free(); ogs::gatherKernel_intMax.free(); ogs::gatherKernel_longAdd.free(); ogs::gatherKernel_longMul.free(); ogs::gatherKernel_longMin.free(); ogs::gatherKernel_longMax.free(); ogs::gatherVecKernel_floatAdd.free(); ogs::gatherVecKernel_floatMul.free(); ogs::gatherVecKernel_floatMin.free(); ogs::gatherVecKernel_floatMax.free(); ogs::gatherVecKernel_doubleAdd.free(); ogs::gatherVecKernel_doubleMul.free(); ogs::gatherVecKernel_doubleMin.free(); ogs::gatherVecKernel_doubleMax.free(); ogs::gatherVecKernel_intAdd.free(); ogs::gatherVecKernel_intMul.free(); ogs::gatherVecKernel_intMin.free(); ogs::gatherVecKernel_intMax.free(); ogs::gatherVecKernel_longAdd.free(); ogs::gatherVecKernel_longMul.free(); ogs::gatherVecKernel_longMin.free(); ogs::gatherVecKernel_longMax.free(); ogs::gatherManyKernel_floatAdd.free(); ogs::gatherManyKernel_floatMul.free(); ogs::gatherManyKernel_floatMin.free(); ogs::gatherManyKernel_floatMax.free(); ogs::gatherManyKernel_doubleAdd.free(); ogs::gatherManyKernel_doubleMul.free(); ogs::gatherManyKernel_doubleMin.free(); ogs::gatherManyKernel_doubleMax.free(); ogs::gatherManyKernel_intAdd.free(); ogs::gatherManyKernel_intMul.free(); ogs::gatherManyKernel_intMin.free(); ogs::gatherManyKernel_intMax.free(); ogs::gatherManyKernel_longAdd.free(); ogs::gatherManyKernel_longMul.free(); ogs::gatherManyKernel_longMin.free(); ogs::gatherManyKernel_longMax.free(); ogs::scatterKernel_float.free(); ogs::scatterKernel_double.free(); ogs::scatterKernel_int.free(); ogs::scatterKernel_long.free(); ogs::scatterVecKernel_float.free(); ogs::scatterVecKernel_double.free(); ogs::scatterVecKernel_int.free(); ogs::scatterVecKernel_long.free(); ogs::scatterManyKernel_float.free(); ogs::scatterManyKernel_double.free(); ogs::scatterManyKernel_int.free(); ogs::scatterManyKernel_long.free(); ogs::o_haloBuf.free(); ogs::haloBuf = NULL; }
55.995798
149
0.771592
roystgnr
ba99c46ab2b4cc8ffed797b81c30dfbac8dfa060
693
cc
C++
src/Attributes/DrillToleranceAttribute.cc
aaronbamberger/gerber_rs274x_parser
d2bbd6c66d322ab47715771642255f8302521300
[ "BSD-2-Clause" ]
6
2016-09-28T18:26:42.000Z
2021-04-10T13:19:05.000Z
src/Attributes/DrillToleranceAttribute.cc
aaronbamberger/gerber_rs274x_parser
d2bbd6c66d322ab47715771642255f8302521300
[ "BSD-2-Clause" ]
1
2021-02-09T00:24:04.000Z
2021-02-27T22:08:05.000Z
src/Attributes/DrillToleranceAttribute.cc
aaronbamberger/gerber_rs274x_parser
d2bbd6c66d322ab47715771642255f8302521300
[ "BSD-2-Clause" ]
5
2017-09-14T09:48:17.000Z
2021-07-19T07:58:34.000Z
/* * Copyright 2021 Aaron Bamberger * Licensed under BSD 2-clause license * See LICENSE file at root of source tree, * or https://opensource.org/licenses/BSD-2-Clause */ #include "Attributes/DrillToleranceAttribute.hh" DrillToleranceAttribute::DrillToleranceAttribute(ValueWithLocation<double> plus_tolerance, ValueWithLocation<double> minus_tolerance, yy::location name_location) : StandardAttribute(ValueWithLocation<std::string>(".DrillTolerance", name_location), StandardAttributeType::STANDARD_ATTRIBUTE_DRILL_TOLERANCE), m_plus_tolerance(plus_tolerance), m_minus_tolerance(minus_tolerance) {} DrillToleranceAttribute::~DrillToleranceAttribute() {}
33
90
0.787879
aaronbamberger
ba9c80654c3a1d3bb952a8156ad1a44f6799857c
1,139
hpp
C++
include/detectball.hpp
ssudake21/spm
fb6d62674831acb2ddac4c5dddce24b2d2c89caa
[ "Apache-2.0" ]
1
2019-06-20T01:54:37.000Z
2019-06-20T01:54:37.000Z
include/detectball.hpp
ssudake21/spm
fb6d62674831acb2ddac4c5dddce24b2d2c89caa
[ "Apache-2.0" ]
null
null
null
include/detectball.hpp
ssudake21/spm
fb6d62674831acb2ddac4c5dddce24b2d2c89caa
[ "Apache-2.0" ]
null
null
null
/*! * \file detectball.hpp * \brief */ #ifndef __DETECTBALL_H_INCLUDED__ #define __DETECTBALL_H_INCLUDED__ #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/core/core.hpp> #include <opencv2/video/video.hpp> #include <iostream> using namespace cv; /*! * \class DetectBall * \brief */ class DetectBall { private: //! max number of objects to be detected in frame static const int MAX_NUM_OBJECTS = 50; //! minimum and maximum object area static const int MIN_OBJECT_AREA = 11 * 11; static const int MAX_OBJECT_AREA = 20 * 20; Scalar *white_minval, *white_maxval; long long int frameCount; public: DetectBall(); ~DetectBall(); void morphOps(Mat &frame); Point trackFilteredObject(Mat &frame); Point detectWhite(Mat &frame); void mapPosition(Mat &frame, Point position, int status); // int showFrameNo(Mat &frame); int showFrameNo(); }; class SnKalman { private: KalmanFilter kalmanfilter; Mat_<float> *state; Mat *processNoise; Mat_<float> *measurement; int flaginit; public: SnKalman(); ~SnKalman(); Point correctPoisition(Point position); }; #endif
19.637931
58
0.729587
ssudake21
baa05568757004610ac574afbfc34d778f404368
2,260
cpp
C++
android-31/java/sql/SQLWarning.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-31/java/sql/SQLWarning.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-29/java/sql/SQLWarning.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#include "../../JString.hpp" #include "../../JThrowable.hpp" #include "./SQLWarning.hpp" namespace java::sql { // Fields // QJniObject forward SQLWarning::SQLWarning(QJniObject obj) : java::sql::SQLException(obj) {} // Constructors SQLWarning::SQLWarning() : java::sql::SQLException( "java.sql.SQLWarning", "()V" ) {} SQLWarning::SQLWarning(JString arg0) : java::sql::SQLException( "java.sql.SQLWarning", "(Ljava/lang/String;)V", arg0.object<jstring>() ) {} SQLWarning::SQLWarning(JThrowable arg0) : java::sql::SQLException( "java.sql.SQLWarning", "(Ljava/lang/Throwable;)V", arg0.object<jthrowable>() ) {} SQLWarning::SQLWarning(JString arg0, JString arg1) : java::sql::SQLException( "java.sql.SQLWarning", "(Ljava/lang/String;Ljava/lang/String;)V", arg0.object<jstring>(), arg1.object<jstring>() ) {} SQLWarning::SQLWarning(JString arg0, JThrowable arg1) : java::sql::SQLException( "java.sql.SQLWarning", "(Ljava/lang/String;Ljava/lang/Throwable;)V", arg0.object<jstring>(), arg1.object<jthrowable>() ) {} SQLWarning::SQLWarning(JString arg0, JString arg1, jint arg2) : java::sql::SQLException( "java.sql.SQLWarning", "(Ljava/lang/String;Ljava/lang/String;I)V", arg0.object<jstring>(), arg1.object<jstring>(), arg2 ) {} SQLWarning::SQLWarning(JString arg0, JString arg1, JThrowable arg2) : java::sql::SQLException( "java.sql.SQLWarning", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)V", arg0.object<jstring>(), arg1.object<jstring>(), arg2.object<jthrowable>() ) {} SQLWarning::SQLWarning(JString arg0, JString arg1, jint arg2, JThrowable arg3) : java::sql::SQLException( "java.sql.SQLWarning", "(Ljava/lang/String;Ljava/lang/String;ILjava/lang/Throwable;)V", arg0.object<jstring>(), arg1.object<jstring>(), arg2, arg3.object<jthrowable>() ) {} // Methods java::sql::SQLWarning SQLWarning::getNextWarning() const { return callObjectMethod( "getNextWarning", "()Ljava/sql/SQLWarning;" ); } void SQLWarning::setNextWarning(java::sql::SQLWarning arg0) const { callMethod<void>( "setNextWarning", "(Ljava/sql/SQLWarning;)V", arg0.object() ); } } // namespace java::sql
25.681818
79
0.671239
YJBeetle
baa35e7aa30971136885604b162f97fb6a6c4046
5,966
cc
C++
src/outlinerboundingboxer.cc
jariarkko/cave-outliner
2077a24627881f45a27aec3eb4e5b4855f6b7fec
[ "BSD-3-Clause" ]
4
2021-09-02T16:52:23.000Z
2022-02-07T16:39:50.000Z
src/outlinerboundingboxer.cc
jariarkko/cave-outliner
2077a24627881f45a27aec3eb4e5b4855f6b7fec
[ "BSD-3-Clause" ]
87
2021-09-12T06:09:57.000Z
2022-02-15T00:05:43.000Z
src/outlinerboundingboxer.cc
jariarkko/cave-outliner
2077a24627881f45a27aec3eb4e5b4855f6b7fec
[ "BSD-3-Clause" ]
1
2021-09-28T21:38:30.000Z
2021-09-28T21:38:30.000Z
/////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// // // CCC AAA V V EEEEE OOO UU UU TTTTTT LL II NN NN EEEEE RRRRR // CC CC AA AA V V EE OO OO UU UU TT LL II NNN NN EE RR RR // CC AA AA V V EEE OO OO UU UU TT LL II NN N NN EEE RRRRR // CC CC AAAAAA V V EE OO OO UU UU TT LL II NN NNN EE RR R // CCc AA AA V EEEEE OOO UUUUU TT LLLLL II NN NN EEEEE RR R // // CAVE OUTLINER -- Cave 3D model processing software // // Copyright (C) 2021 by Jari Arkko -- See LICENSE.txt for license information. // /////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// // Includes /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// #include <cassert> #include <stdlib.h> #include <assimp/Importer.hpp> #include <assimp/scene.h> #include <assimp/postprocess.h> #include "outlinerdebug.hh" #include "outlinermath.hh" #include "outlinerboundingboxer.hh" /////////////////////////////////////////////////////////////////////////////////////////////// // Functions ////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// BoundingBoxer::BoundingBoxer(const aiScene* scene, outlinerreal xIncrease, outlinerreal yIncrease, outlinerreal zIncrease) { infof("Calculating bounding box..."); boundingBoxSet = 0; boundingScene(scene); if (!boundingBoxSet) { errf("Cannot determine bounding box (empty model?)"); } increasedBoundingBox = boundingBox; increasedBoundingBox.start.x -= xIncrease; increasedBoundingBox.end.x += xIncrease; increasedBoundingBox.start.y -= yIncrease; increasedBoundingBox.end.y += yIncrease; increasedBoundingBox.start.z -= zIncrease; increasedBoundingBox.end.z += zIncrease; infof(" Discovered bounding box (%.2f,%.2f,%.2f) to (%.2f,%.2f,%.2f)", boundingBox.start.x, boundingBox.start.y, boundingBox.start.z, boundingBox.end.x, boundingBox.end.y, boundingBox.end.z); } void BoundingBoxer::getOriginalBoundingBox(OutlinerBox3D& boundingBoxOut) { assert(boundingBoxSet); boundingBoxOut = boundingBox; } void BoundingBoxer::getIncreasedBoundingBox(OutlinerBox3D& boundingBoxOut) { assert(boundingBoxSet); boundingBoxOut = increasedBoundingBox; } BoundingBoxer::~BoundingBoxer() { debugf("BoundingBoxer::~BoundingBoxer"); } void BoundingBoxer::boundingScene(const aiScene* scene) { boundingNode(scene,scene->mRootNode); } void BoundingBoxer::boundingNode(const aiScene* scene, const aiNode* node) { for (unsigned int j = 0; j < node->mNumMeshes; j++) { boundingMesh(scene->mMeshes[node->mMeshes[j]]); } for (unsigned int i = 0; i < node->mNumChildren; i++) { boundingNode(scene,node->mChildren[i]); } } void BoundingBoxer::boundingMesh(const aiMesh* mesh) { assert(mesh != 0); boundingFaces(mesh); } void BoundingBoxer::boundingFaces(const aiMesh* mesh) { assert(mesh != 0); for (unsigned int f = 0; f < mesh->mNumFaces; f++) { boundingFace(mesh,&mesh->mFaces[f]); } } void BoundingBoxer::boundingFace(const aiMesh* mesh, const aiFace* face) { // Sanity checks assert(mesh != 0); assert(face != 0); if (face->mNumIndices != 3) { errf("Cannot handle a face with %u indices", face->mNumIndices); return; } if (face->mIndices[0] >= mesh->mNumVertices) { errf("Face points to a vertex %u that does not exist", face->mIndices[0]); return; } if (face->mIndices[1] >= mesh->mNumVertices) { errf("Face points to a vertex %u that does not exist", face->mIndices[1]); return; } if (face->mIndices[2] >= mesh->mNumVertices) { errf("Face points to a vertex %u that does not exist", face->mIndices[2]); return; } // Calculate bounding box const aiVector3D& vertexA = mesh->mVertices[face->mIndices[0]]; const aiVector3D& vertexB = mesh->mVertices[face->mIndices[1]]; const aiVector3D& vertexC = mesh->mVertices[face->mIndices[2]]; OutlinerBox3D elementBoundingBox; OutlinerTriangle3D triangle3(vertexA,vertexB,vertexC); OutlinerMath::triangleBoundingBox3D(triangle3,elementBoundingBox); // See if this is the first bounding box we see if (!boundingBoxSet) { boundingBox = elementBoundingBox; boundingBoxSet = 1; return; } // See if the new element should extend the existing bounding somehow if (elementBoundingBox.start.x < boundingBox.start.x) { boundingBox.start.x = elementBoundingBox.start.x; } if (elementBoundingBox.end.x > boundingBox.end.x) { boundingBox.end.x = elementBoundingBox.end.x; } if (elementBoundingBox.start.y < boundingBox.start.y) { boundingBox.start.y = elementBoundingBox.start.y; } if (elementBoundingBox.end.y > boundingBox.end.y) { boundingBox.end.y = elementBoundingBox.end.y; } if (elementBoundingBox.start.z < boundingBox.start.z) { boundingBox.start.z = elementBoundingBox.start.z; } if (elementBoundingBox.end.z > boundingBox.end.z) { boundingBox.end.z = elementBoundingBox.end.z; } }
36.157576
95
0.53654
jariarkko
baa3e10c85ae181b42e8d2914b10a257929b4dd4
2,775
cpp
C++
video/device/linux_list_devices.cpp
fgenolini/frank
0581c503f0a724cb29dc1901df9da5893947190f
[ "MIT" ]
1
2020-10-12T03:08:22.000Z
2020-10-12T03:08:22.000Z
video/device/linux_list_devices.cpp
fgenolini/frank
0581c503f0a724cb29dc1901df9da5893947190f
[ "MIT" ]
17
2020-04-23T08:32:59.000Z
2020-08-20T16:58:26.000Z
video/device/linux_list_devices.cpp
fgenolini/frank
0581c503f0a724cb29dc1901df9da5893947190f
[ "MIT" ]
1
2020-10-12T03:33:27.000Z
2020-10-12T03:33:27.000Z
#include "config.h" #if defined(UNIX) && !defined(APPLE) && !defined(MINGW) && !defined(MSYS) && \ !defined(CYGWIN) && !defined(WIN32) WARNINGS_OFF #include <cstdlib> #include <filesystem> #include <fstream> #include <iostream> #include <string> #include <vector> #include <gsl/gsl_util> WARNINGS_ON using namespace gsl; #include "device/linux_list_devices.h" // Implementation of video/audio device enumeration on Linux namespace fs = std::filesystem; namespace frank::video { // Linux listing of video input devices using video4linux std::vector<std::string> linux_list_device_names(standard_io *) { // On Linux: list all files called // /sys/class/video4linux/video0/name // /sys/class/video4linux/video1/name // ... const fs::path video4linux{"/sys/class/video4linux"}; if (!fs::exists(video4linux)) return std::vector<std::string>(); std::vector<std::string> new_devices{}; for (const auto &entry : fs::directory_iterator(video4linux)) { const auto video_device = entry.path().filename().string(); if (!entry.is_directory()) continue; std::cout << "file: " << video_device << '\n'; fs::path index; index += entry.path(); index /= "index"; if (!fs::exists(index)) continue; std::ifstream index_file(index, std::ifstream::in); if (index_file.is_open()) { auto _ = finally([&index_file] { index_file.close(); }); auto file_contents = index_file.rdbuf(); auto contents_size = file_contents->pubseekoff(0, index_file.end, index_file.in); file_contents->pubseekpos(0, index_file.in); auto contents = new char[contents_size]; file_contents->sgetn(contents, contents_size); std::string video_device_index{contents}; if (video_device_index.compare(0, 1, "0") != 0) continue; } fs::path name; name += entry.path(); name /= "name"; if (!fs::exists(name)) continue; std::ifstream name_file(name, std::ifstream::in); if (!name_file.is_open()) continue; auto _ = finally([&name_file] { name_file.close(); }); auto file_contents = name_file.rdbuf(); auto contents_size = file_contents->pubseekoff(0, name_file.end, name_file.in); file_contents->pubseekpos(0, name_file.in); auto contents = new char[contents_size]; file_contents->sgetn(contents, contents_size); std::cout << "name: " << contents << '\n'; std::string video_device_name{contents}; std::string new_device{video_device_name}; new_devices.push_back(new_device); } return new_devices; } std::vector<std::string> linux_list_devices(standard_io *stdio) { auto device_names = linux_list_device_names(stdio); return device_names; } } // namespace frank::video #endif
28.316327
80
0.668468
fgenolini
baa4baf4b9f1015bd23654247a7777416b47e977
760
cpp
C++
tools/animator/src/gui/gui.cpp
anteins/Blunted2
284a1fb59805914af1ee0dc763ff022fb088a922
[ "Unlicense" ]
null
null
null
tools/animator/src/gui/gui.cpp
anteins/Blunted2
284a1fb59805914af1ee0dc763ff022fb088a922
[ "Unlicense" ]
null
null
null
tools/animator/src/gui/gui.cpp
anteins/Blunted2
284a1fb59805914af1ee0dc763ff022fb088a922
[ "Unlicense" ]
null
null
null
// written by bastiaan konings schuiling 2008 - 2014 // this work is public domain. the code is undocumented, scruffy, untested, and should generally not be used for anything important. // i do not offer support, so don't ask. to be used for inspiration :) #include "gui.hpp" namespace blunted { GuiTask::GuiTask(boost::shared_ptr<Scene2D> scene2D, float ratio, int margin) : scene2D(scene2D), ratio(ratio), margin(margin) { guiInterface = new GuiInterface(scene2D, ratio, margin); } GuiTask::~GuiTask() { scene2D.reset(); delete guiInterface; } void GuiTask::GetPhase() { } void GuiTask::ProcessPhase() { guiInterface->Process(); } void GuiTask::PutPhase() { } GuiInterface *GuiTask::GetInterface() { return guiInterface; } }
21.714286
132
0.710526
anteins
baa59545e2670825a48de371db5cdc5e0c003234
3,381
cc
C++
test/cpp/end2end/admin_services_end2end_test.cc
lishengze/grpc
70fa55155beade94670661f033e91b55f43c9dee
[ "Apache-2.0" ]
1
2021-12-01T03:10:14.000Z
2021-12-01T03:10:14.000Z
test/cpp/end2end/admin_services_end2end_test.cc
lishengze/grpc
70fa55155beade94670661f033e91b55f43c9dee
[ "Apache-2.0" ]
null
null
null
test/cpp/end2end/admin_services_end2end_test.cc
lishengze/grpc
70fa55155beade94670661f033e91b55f43c9dee
[ "Apache-2.0" ]
null
null
null
// // // Copyright 2021 gRPC authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/strings/str_cat.h" #include <grpcpp/ext/admin_services.h> #include <grpcpp/ext/proto_server_reflection_plugin.h> #include <grpcpp/grpcpp.h> #include "src/proto/grpc/reflection/v1alpha/reflection.grpc.pb.h" #include "test/core/util/port.h" #include "test/core/util/test_config.h" namespace grpc { namespace testing { class AdminServicesTest : public ::testing::Test { public: void SetUp() override { std::string address = absl::StrCat("localhost:", grpc_pick_unused_port_or_die()); // Create admin server grpc::reflection::InitProtoReflectionServerBuilderPlugin(); ServerBuilder builder; builder.AddListeningPort(address, InsecureServerCredentials()); grpc::AddAdminServices(&builder); server_ = builder.BuildAndStart(); // Create channel auto reflection_stub = reflection::v1alpha::ServerReflection::NewStub( CreateChannel(address, InsecureChannelCredentials())); stream_ = reflection_stub->ServerReflectionInfo(&reflection_ctx_); } std::vector<std::string> GetServiceList() { std::vector<std::string> services; reflection::v1alpha::ServerReflectionRequest request; reflection::v1alpha::ServerReflectionResponse response; request.set_list_services(""); stream_->Write(request); stream_->Read(&response); for (auto& service : response.list_services_response().service()) { services.push_back(service.name()); } return services; } private: std::unique_ptr<Server> server_; ClientContext reflection_ctx_; std::shared_ptr< ClientReaderWriter<reflection::v1alpha::ServerReflectionRequest, reflection::v1alpha::ServerReflectionResponse>> stream_; }; TEST_F(AdminServicesTest, ValidateRegisteredServices) { // Using Contains here, because the server builder might register other // services in certain environments. EXPECT_THAT( GetServiceList(), ::testing::AllOf( ::testing::Contains("grpc.channelz.v1.Channelz"), ::testing::Contains("grpc.reflection.v1alpha.ServerReflection"))); #if defined(GRPC_NO_XDS) || defined(DISABLED_XDS_PROTO_IN_CC) EXPECT_THAT(GetServiceList(), ::testing::Not(::testing::Contains( "envoy.service.status.v3.ClientStatusDiscoveryService"))); #else EXPECT_THAT(GetServiceList(), ::testing::Contains( "envoy.service.status.v3.ClientStatusDiscoveryService")); #endif // GRPC_NO_XDS or DISABLED_XDS_PROTO_IN_CC } } // namespace testing } // namespace grpc int main(int argc, char** argv) { grpc::testing::TestEnvironment env(argc, argv); ::testing::InitGoogleTest(&argc, argv); int ret = RUN_ALL_TESTS(); return ret; }
33.147059
76
0.71399
lishengze
baa7792f26a9085dfe05ca8ecf2100cfcae2912d
5,665
cpp
C++
DriverlessCar/Main.cpp
phuctm97/driverless-car-2
ce9c8b0bf83da20a9b2d856d257b0ddfd10e8531
[ "MIT" ]
null
null
null
DriverlessCar/Main.cpp
phuctm97/driverless-car-2
ce9c8b0bf83da20a9b2d856d257b0ddfd10e8531
[ "MIT" ]
null
null
null
DriverlessCar/Main.cpp
phuctm97/driverless-car-2
ce9c8b0bf83da20a9b2d856d257b0ddfd10e8531
[ "MIT" ]
3
2020-03-04T16:00:05.000Z
2022-02-24T11:29:52.000Z
#include "Collector/ICollector.h" #include "Collector/CollectorWithVideo/CollectorWithVideo.h" // [on Car] replace with CollectorWithCamera #include "Calculator/ICalculator.h" #include "Calculator/CalculatorBlobsBased/CalculatorBlobsBased.h" #include "Calculator/CropTool.h" #include "Calculator/FlipTool.h" #include "Calculator/BinarizeTool.h" #include "Calculator/BlobTool.h" #include "Analyzer/IAnalyzer.h" #include "Analyzer/AnalyzerCasesBased/AnalyzerCasesBased.h" #include "Driver/IDriver.h" #include "Driver/DriverStupid/DriverStupid.h" // [on Car] replace with DriverPid #include "Application/Keyboard/WindowsKeyboard.h" // [on Car] replace with LinuxKeyboard #include "Application/IApplication.h" #include "Application/ApplicationTestCollector/ApplicationTestCollector.h" #include "Application/ApplicationTestCalculator/ApplicationTestCalculator.h" #include "Application/ApplicationTestAnalyzer/ApplicationTestAnalyzer.h" #include "Application/ApplicationFinal/ApplicationFinal.h" sb::IApplication* application = nullptr; void composeApplicationTestCollector(); void composeApplicationTestCalculator(); void composeApplicationTestAnalyzer(); void composeApplicationFinal(); void releaseApplication(); void onKeyPressed( int key ); int main( const int argc, const char** argv ) { composeApplicationTestAnalyzer(); if ( application == nullptr ) return -1; application->addKeyboardCallback( &onKeyPressed ); application->run(); releaseApplication(); system( "pause" ); return 0; } void composeApplicationTestCollector() { sb::ICollector* collector = nullptr; collector = new sb::CollectorWithVideo( "..\\Debug\\sample-5.avi" ); // [on Car] replace with CollectorWithCamera application = new sb::ApplicationTestCollector( collector, new sb::WindowsKeyboard( 33 ) ); // [on Car] replace with LinuxKeyboard } void composeApplicationTestCalculator() { sb::ICollector* collector = nullptr; sb::ICalculator* calculator = nullptr; collector = new sb::CollectorWithVideo( "..\\Debug\\sample-9.avi" ); // [on Car] replace with CollectorWithCamera calculator = new sb::CalculatorBlobsBased( new sb::CropTool( cv::Rect( 0, 332, 640, 100 ) ), new sb::FlipTool(), new sb::BinarizeTool( 170 ), new sb::BlobTool( { 0.2,0.25,0.25,0.3 }, cv::Size( 640, 100 ) ) ); application = new sb::ApplicationTestCalculator( collector, calculator, new sb::WindowsKeyboard( 33 ) ); // [on Car] replace with LinuxKeyboard } void composeApplicationTestAnalyzer() { sb::ICollector* collector = nullptr; sb::ICalculator* calculator = nullptr; sb::IAnalyzer* analyzer = nullptr; collector = new sb::CollectorWithVideo( "..\\Debug\\sample-13.avi" ); // [on Car] replace with CollectorWithCamera calculator = new sb::CalculatorBlobsBased( new sb::CropTool( cv::Rect( 0, 332, 640, 100 ) ), new sb::FlipTool(), new sb::BinarizeTool( 190 ), new sb::BlobTool( { 0.2,0.25,0.25,0.3 }, cv::Size( 640, 100 ) ) ); sb::AnalyzeParams* analyzeParams = new sb::AnalyzeParams(); { analyzeParams->MIN_LANE_BLOB_SIZE = 1200; analyzeParams->MIN_LANE_BLOB_HEIGHT = 50; analyzeParams->MIN_LANE_BLOB_HEIGHT_TO_CHECK_OBSTACLE = 70; analyzeParams->MIN_LANE_WIDTH_1 = 30; analyzeParams->MAX_LANE_WIDTH_1 = 70; analyzeParams->MIN_LANE_WIDTH_2 = 20; analyzeParams->MAX_LANE_WIDTH_2 = 50; analyzeParams->MAX_ROW_WIDTH_DIFF = 7; analyzeParams->SECTION_HOPS_TO_LIVE = 4; analyzeParams->MAX_LANE_POSITION_DIFF = 100; analyzeParams->MAX_LANE_SIZE_DIFF = 2500; analyzeParams->MAX_LANE_HEIGHT_DIFF = 30; analyzeParams->CROP_OFFSET = cv::Point( 0, 332 ); } analyzer = new sb::AnalyzerCasesBased( analyzeParams ); application = new sb::ApplicationTestAnalyzer( collector, calculator, analyzer, new sb::WindowsKeyboard( 33 ) ); // [on Car] replace with LinuxKeyboard } void composeApplicationFinal() { sb::ICollector* collector = nullptr; sb::ICalculator* calculator = nullptr; sb::IAnalyzer* analyzer = nullptr; sb::IDriver* driver = nullptr; collector = new sb::CollectorWithVideo( "..\\Debug\\sample-1.avi" ); // [on Car] replace with CameraWithCamera calculator = new sb::CalculatorBlobsBased( new sb::CropTool( cv::Rect( 0, 332, 640, 100 ) ), new sb::FlipTool(), new sb::BinarizeTool( 200 ), new sb::BlobTool( { 0.2,0.25,0.25,0.3 }, cv::Size( 640, 100 ) ) ); sb::AnalyzeParams* analyzeParams = new sb::AnalyzeParams(); { analyzeParams->MIN_LANE_BLOB_SIZE = 1500; analyzeParams->MIN_LANE_BLOB_HEIGHT = 75; analyzeParams->MIN_LANE_WIDTH_1 = 30; analyzeParams->MAX_LANE_WIDTH_1 = 70; analyzeParams->MIN_LANE_WIDTH_2 = 50; analyzeParams->MAX_LANE_WIDTH_2 = 20; analyzeParams->MAX_ROW_WIDTH_DIFF = 7; analyzeParams->SECTION_HOPS_TO_LIVE = 4; analyzeParams->MAX_LANE_POSITION_DIFF = 100; analyzeParams->MAX_LANE_SIZE_DIFF = 1000; analyzeParams->MAX_LANE_HEIGHT_DIFF = 30; } analyzer = new sb::AnalyzerCasesBased( analyzeParams ); driver = new sb::DriverStupid(); // [on Car] replace with DriverPid application = new sb::ApplicationFinal( collector, calculator, analyzer, driver, new sb::WindowsKeyboard( 33 ), "D:\\test", cv::Point( 0, 332 ) ); // [on Car] replace with LinuxKeyboard } void releaseApplication() { application->release(); } void onKeyPressed( int key ) { if ( key == 27 ) application->exit(); }
36.082803
186
0.695499
phuctm97
baa7e9366c3862f120e8e7e549d27f999c53ca1c
1,047
hpp
C++
include/RED4ext/Types/generated/anim/AnimNode_BlendSpace.hpp
Cyberpunk-Extended-Development-Team/RED4ext.SDK
2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae
[ "MIT" ]
1
2021-02-01T23:07:50.000Z
2021-02-01T23:07:50.000Z
include/RED4ext/Types/generated/anim/AnimNode_BlendSpace.hpp
Cyberpunk-Extended-Development-Team/RED4ext.SDK
2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae
[ "MIT" ]
null
null
null
include/RED4ext/Types/generated/anim/AnimNode_BlendSpace.hpp
Cyberpunk-Extended-Development-Team/RED4ext.SDK
2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae
[ "MIT" ]
null
null
null
#pragma once // This file is generated from the Game's Reflection data #include <cstdint> #include <RED4ext/Common.hpp> #include <RED4ext/REDhash.hpp> #include <RED4ext/CName.hpp> #include <RED4ext/DynArray.hpp> #include <RED4ext/Types/generated/anim/AnimNode_Base.hpp> #include <RED4ext/Types/generated/anim/AnimNode_BlendSpace_InternalsBlendSpace.hpp> #include <RED4ext/Types/generated/anim/FloatLink.hpp> namespace RED4ext { namespace anim { struct AnimNode_BlendSpace : anim::AnimNode_Base { static constexpr const char* NAME = "animAnimNode_BlendSpace"; static constexpr const char* ALIAS = NAME; anim::AnimNode_BlendSpace_InternalsBlendSpace blendSpace; // 48 DynArray<anim::FloatLink> inputLinks; // 210 anim::FloatLink progressLink; // 220 bool fireAnimEndEvent; // 240 uint8_t unk241[0x248 - 0x241]; // 241 CName animEndEventName; // 248 bool isLooped; // 250 uint8_t unk251[0x258 - 0x251]; // 251 }; RED4EXT_ASSERT_SIZE(AnimNode_BlendSpace, 0x258); } // namespace anim } // namespace RED4ext
30.794118
83
0.751671
Cyberpunk-Extended-Development-Team
bab1a30276d99dfb58df19ba73952bdecc2be15a
26,438
cpp
C++
src/utilities/bcl/BCLXML.cpp
muehleisen/OpenStudio
3bfe89f6c441d1e61e50b8e94e92e7218b4555a0
[ "blessing" ]
3
2020-09-05T18:13:23.000Z
2022-01-15T14:47:57.000Z
src/utilities/bcl/BCLXML.cpp
muehleisen/OpenStudio
3bfe89f6c441d1e61e50b8e94e92e7218b4555a0
[ "blessing" ]
4
2016-06-27T21:25:59.000Z
2020-04-28T14:00:21.000Z
src/utilities/bcl/BCLXML.cpp
jmarrec/OpenStudio
5276feff0d8dbd6c8ef4e87eed626bc270a19b14
[ "blessing" ]
1
2020-06-19T14:54:05.000Z
2020-06-19T14:54:05.000Z
/*********************************************************************************************************************** * OpenStudio(R), Copyright (c) 2008-2021, Alliance for Sustainable Energy, LLC, and other contributors. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following * disclaimer. * * (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the distribution. * * (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products * derived from this software without specific prior written permission from the respective party. * * (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works * may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior * written permission from Alliance for Sustainable Energy, LLC. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED * STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***********************************************************************************************************************/ #include "BCLXML.hpp" #include "../units/Quantity.hpp" #include "../core/Checksum.hpp" #include "../core/FilesystemHelpers.hpp" #include "../time/DateTime.hpp" #include <sstream> #include <pugixml.hpp> namespace openstudio { BCLXML::BCLXML(const BCLXMLType& bclXMLType) : m_bclXMLType(bclXMLType), m_uid{removeBraces(openstudio::createUUID())}, m_versionId{removeBraces(openstudio::createUUID())}, m_versionModified{DateTime::nowUTC().toISO8601()} {} BCLXML::BCLXML(const openstudio::path& xmlPath) : m_path(openstudio::filesystem::system_complete(xmlPath)) { if (!openstudio::filesystem::exists(xmlPath)) { LOG_AND_THROW("'" << toString(xmlPath) << "' does not exist"); } else if (!openstudio::filesystem::is_regular_file(xmlPath)) { LOG_AND_THROW("'" << toString(xmlPath) << "' cannot be opened for reading BCL XML data"); } pugi::xml_document bclXML; openstudio::filesystem::ifstream file(m_path); if (file.is_open()) { auto result = bclXML.load(file); if (!result) { LOG_AND_THROW("'" << toString(xmlPath) << "' could not be read as XML data"); } file.close(); } else { file.close(); LOG_AND_THROW("'" << toString(xmlPath) << "' could not be opened"); } auto element = bclXML.child("component"); if (element) { m_bclXMLType = BCLXMLType::ComponentXML; } else { element = bclXML.child("measure"); if (element) { m_bclXMLType = BCLXMLType::MeasureXML; } else { LOG_AND_THROW("'" << toString(xmlPath) << "' is not a correct BCL XML"); } } // get schema version to see if we need to upgrade anything // added in schema version 3 VersionString startingVersion("2.0"); auto subelement = element.child("schema_version"); if (subelement) { try { startingVersion = VersionString(subelement.text().as_string()); } catch (const std::exception&) { // Yuck } } m_name = decodeString(element.child("name").text().as_string()); m_uid = element.child("uid").text().as_string(); m_versionId = element.child("version_id").text().as_string(); if (m_name.empty() || m_uid.empty() || m_versionId.empty()) { LOG_AND_THROW("'" << toString(xmlPath) << "' is not a correct BCL XML"); } // added in schema version 3 // error is only present if something went wrong, so we check if it exists first // to avoid always initializing m_error to a string (even if empty) // note: decodeString(element.child("error").text().as_string()) would always return a string even if 'error' key didn't exist pugi::xml_node errorElement = element.child("error"); if (errorElement) { m_error = errorElement.text().as_string(); } subelement = element.child("version_modified"); if (subelement) { m_versionModified = subelement.text().as_string(); if (!DateTime::fromISO8601(m_versionModified)) { // not an allowable date time m_versionModified = ""; } } if (m_bclXMLType == BCLXMLType::MeasureXML) { // added in schema version 3 m_className = decodeString(element.child("class_name").text().as_string()); } // added in schema version 3 m_displayName = decodeString(element.child("display_name").text().as_string()); if (m_displayName.empty()) { // use name m_displayName = m_name; } m_description = decodeString(element.child("description").text().as_string()); if (m_bclXMLType == BCLXMLType::MeasureXML) { m_modelerDescription = decodeString(element.child("modeler_description").text().as_string()); subelement = element.child("arguments"); if (subelement) { for (auto& arg : subelement.children("argument")) { try { m_arguments.push_back(BCLMeasureArgument(arg)); } catch (const std::exception&) { LOG(Error, "Bad argument in BCL XML"); } } } subelement = element.child("outputs"); if (subelement) { for (auto& outputElement : subelement.children("output")) { if (outputElement.first_child()) { try { m_outputs.push_back(BCLMeasureOutput(outputElement)); } catch (const std::exception&) { LOG(Error, "Bad output in BCL XML"); } } } } } subelement = element.child("files"); if (subelement) { for (auto& fileElement : subelement.children("file")) { if (fileElement.first_child()) { std::string softwareProgram; std::string softwareProgramVersion; boost::optional<VersionString> minCompatibleVersion; boost::optional<VersionString> maxCompatibleVersion; auto versionElement = fileElement.child("version"); if (versionElement) { softwareProgram = versionElement.child("software_program").text().as_string(); softwareProgramVersion = versionElement.child("identifier").text().as_string(); // added in schema version 3 auto minCompatibleVersionElement = versionElement.child("min_compatible"); if (!minCompatibleVersionElement) { try { // if minCompatibleVersion not explicitly set, assume softwareProgramVersion is min minCompatibleVersion = VersionString(softwareProgramVersion); } catch (const std::exception&) { } } else { try { minCompatibleVersion = VersionString(minCompatibleVersionElement.text().as_string()); } catch (const std::exception&) { } } // added in schema version 3 auto maxCompatibleVersionElement = versionElement.child("max_compatible"); if (maxCompatibleVersionElement) { try { maxCompatibleVersion = VersionString(maxCompatibleVersionElement.text().as_string()); } catch (const std::exception&) { } } } std::string fileName = fileElement.child("filename").text().as_string(); //std::string fileType = fileElement.firstChildElement("filetype").firstChild().nodeValue().toStdString(); std::string usageType = fileElement.child("usage_type").text().as_string(); std::string checkSum = fileElement.child("checksum").text().as_string(); openstudio::path path; ; if (usageType == "script") { path = m_path.parent_path() / toPath(fileName); } else if (usageType == "doc") { path = m_path.parent_path() / toPath("docs") / toPath(fileName); } else if (usageType == "test") { path = m_path.parent_path() / toPath("tests") / toPath(fileName); } else if (usageType == "resource") { path = m_path.parent_path() / toPath("resources") / toPath(fileName); } else { path = m_path.parent_path() / toPath(fileName); } BCLFileReference fileref(path); fileref.setSoftwareProgram(softwareProgram); fileref.setSoftwareProgramVersion(softwareProgramVersion); if (minCompatibleVersion) { fileref.setMinCompatibleVersion(*minCompatibleVersion); } if (maxCompatibleVersion) { fileref.setMaxCompatibleVersion(*maxCompatibleVersion); } fileref.setUsageType(usageType); fileref.setChecksum(checkSum); m_files.push_back(fileref); } else { break; } } } subelement = element.child("attributes"); if (subelement) { for (auto& attributeElement : subelement.children("attribute")) { if (attributeElement.first_child()) { std::string name = attributeElement.child("name").text().as_string(); std::string value = attributeElement.child("value").text().as_string(); std::string datatype = attributeElement.child("datatype").text().as_string(); // Units are optional std::string units = attributeElement.child("units").text().as_string(); if (datatype == "float") { if (units.empty()) { Attribute attr(name, boost::lexical_cast<double>(value)); m_attributes.push_back(attr); } else { Attribute attr(name, boost::lexical_cast<double>(value), units); m_attributes.push_back(attr); } } else if (datatype == "int") { if (units.empty()) { Attribute attr(name, boost::lexical_cast<int>(value)); m_attributes.push_back(attr); } else { Attribute attr(name, boost::lexical_cast<int>(value), units); m_attributes.push_back(attr); } } else if (datatype == "boolean") { bool temp; if (value == "true") { temp = true; } else { temp = false; } if (units.empty()) { Attribute attr(name, temp); m_attributes.push_back(attr); } else { Attribute attr(name, temp, units); m_attributes.push_back(attr); } } else { // Assume string if (units.empty()) { Attribute attr(name, value); m_attributes.push_back(attr); } else { Attribute attr(name, value, units); m_attributes.push_back(attr); } } } else { break; } } } subelement = element.child("tags"); if (subelement) { for (auto& tagElement : subelement.children("tag")) { auto text = tagElement.text(); if (!text.empty()) { m_tags.push_back(text.as_string()); } } } // added in schema version 3 m_xmlChecksum = element.child("xml_checksum").text().as_string(); } boost::optional<BCLXML> BCLXML::load(const openstudio::path& xmlPath) { boost::optional<BCLXML> result; try { result = BCLXML(xmlPath); } catch (const std::exception&) { } return result; } std::string BCLXML::escapeString(const std::string& txt) { // seems that we don't need to do this anymore return txt; // http://stackoverflow.com/questions/2083754/why-shouldnt-apos-be-used-to-escape-single-quotes // This code was dead already, with the return above. // Commented out, but should likely be removed // QString result = toQString(txt);//.replace("'", "#x27;"); // return result.toStdString(); } std::string BCLXML::decodeString(const std::string& txt) { // seems that we don't need to do this anymore // only thing that can't be in the text node on disk are '<' (should be '&lt;') and '&' (should be '&amp;') return txt; // This code was dead already, with the return above. // Commented out, but should likely be removed // QString result = toQString(txt);//.replace("#x27;", "'"); // return result.toStdString(); } std::string BCLXML::uid() const { return m_uid; } std::string BCLXML::versionId() const { return m_versionId; } boost::optional<DateTime> BCLXML::versionModified() const { boost::optional<DateTime> result; if (!m_versionModified.empty()) { result = DateTime::fromISO8601(m_versionModified); } return result; } std::string BCLXML::xmlChecksum() const { return m_xmlChecksum; } std::string BCLXML::name() const { return m_name; } std::string BCLXML::displayName() const { return m_displayName; } std::string BCLXML::className() const { return m_className; } std::string BCLXML::description() const { return m_description; } std::string BCLXML::modelerDescription() const { return m_modelerDescription; } std::vector<BCLMeasureArgument> BCLXML::arguments() const { return m_arguments; } std::vector<BCLMeasureOutput> BCLXML::outputs() const { return m_outputs; } std::vector<BCLFileReference> BCLXML::files() const { return m_files; } std::vector<BCLFileReference> BCLXML::files(const std::string& filetype) const { std::vector<BCLFileReference> matches; for (const BCLFileReference& file : m_files) { if (file.fileType() == filetype) { matches.push_back(file); } } return matches; } std::vector<Attribute> BCLXML::attributes() const { return m_attributes; } std::vector<Attribute> BCLXML::getAttributes(const std::string& name) const { std::vector<Attribute> result; for (const Attribute& attribute : m_attributes) { if (attribute.name() == name) { result.push_back(attribute); } } return result; } std::vector<std::string> BCLXML::tags() const { return m_tags; } openstudio::path BCLXML::path() const { return m_path; } openstudio::path BCLXML::directory() const { return m_path.parent_path(); } boost::optional<std::string> BCLXML::error() const { return m_error; } void BCLXML::resetXMLChecksum() { incrementVersionId(); m_xmlChecksum = "00000000"; } void BCLXML::setError(const std::string& error) { incrementVersionId(); m_error = escapeString(error); } void BCLXML::resetError() { incrementVersionId(); m_error.reset(); } void BCLXML::setName(const std::string& name) { incrementVersionId(); m_name = escapeString(name); } void BCLXML::setDisplayName(const std::string& displayName) { incrementVersionId(); m_displayName = escapeString(displayName); } void BCLXML::setClassName(const std::string& className) { incrementVersionId(); m_className = escapeString(className); } void BCLXML::setDescription(const std::string& description) { incrementVersionId(); m_description = escapeString(description); } void BCLXML::setModelerDescription(const std::string& modelerDescription) { incrementVersionId(); m_modelerDescription = escapeString(modelerDescription); } void BCLXML::setArguments(const std::vector<BCLMeasureArgument>& arguments) { incrementVersionId(); m_arguments = arguments; } void BCLXML::setOutputs(const std::vector<BCLMeasureOutput>& outputs) { incrementVersionId(); m_outputs = outputs; } void BCLXML::addFile(const BCLFileReference& file) { removeFile(file.path()); incrementVersionId(); m_files.push_back(file); } bool BCLXML::hasFile(const openstudio::path& path) const { bool result = false; openstudio::path test = openstudio::filesystem::system_complete(path); for (const BCLFileReference& file : m_files) { if (file.path() == test) { result = true; break; } } return result; } bool BCLXML::removeFile(const openstudio::path& path) { bool result = false; openstudio::path test = openstudio::filesystem::system_complete(path); std::vector<BCLFileReference> newFiles; for (const BCLFileReference& file : m_files) { if (file.path() == test) { result = true; } else { newFiles.push_back(file); } } if (result == true) { incrementVersionId(); m_files = newFiles; } return result; } void BCLXML::clearFiles() { incrementVersionId(); m_files.clear(); } void BCLXML::addAttribute(const Attribute& attribute) { incrementVersionId(); m_attributes.push_back(attribute); } bool BCLXML::removeAttributes(const std::string& name) { bool result = false; std::vector<Attribute> newAttributes; for (const Attribute& attribute : m_attributes) { if (attribute.name() == name) { result = true; } else { newAttributes.push_back(attribute); } } if (result == true) { incrementVersionId(); m_attributes = newAttributes; } return result; } void BCLXML::clearAttributes() { incrementVersionId(); m_attributes.clear(); } void BCLXML::addTag(const std::string& tagName) { removeTag(tagName); incrementVersionId(); m_tags.push_back(tagName); } bool BCLXML::removeTag(const std::string& tagName) { auto it = std::find(m_tags.begin(), m_tags.end(), tagName); if (it != m_tags.end()) { incrementVersionId(); m_tags.erase(it); return true; } return false; } void BCLXML::clearTags() { incrementVersionId(); m_tags.clear(); } bool BCLXML::save() const { if (m_path.empty()) { return false; } pugi::xml_document doc; //doc.createProcessingInstruction("xml", "version=\"1.0\" encoding=\"utf-8\""); pugi::xml_node docElement; if (m_bclXMLType == BCLXMLType::ComponentXML) { docElement = doc.append_child("component"); } else if (m_bclXMLType == BCLXMLType::MeasureXML) { docElement = doc.append_child("measure"); } else { return false; } auto element = docElement.append_child("schema_version"); auto text = element.text(); text.set("3.0"); if (m_error) { element = docElement.append_child("error"); text = element.text(); text.set(escapeString(*m_error).c_str()); } element = docElement.append_child("name"); text = element.text(); text.set(escapeString(m_name).c_str()); element = docElement.append_child("uid"); text = element.text(); text.set(m_uid.c_str()); element = docElement.append_child("version_id"); text = element.text(); text.set(m_versionId.c_str()); if (!m_versionModified.empty()) { element = docElement.append_child("version_modified"); text = element.text(); text.set(m_versionModified.c_str()); } element = docElement.append_child("xml_checksum"); text = element.text(); text.set(m_xmlChecksum.c_str()); if (m_bclXMLType == BCLXMLType::MeasureXML) { element = docElement.append_child("class_name"); text = element.text(); text.set(m_className.c_str()); } element = docElement.append_child("display_name"); text = element.text(); text.set(m_displayName.c_str()); element = docElement.append_child("description"); text = element.text(); text.set(escapeString(m_description).c_str()); if (m_bclXMLType == BCLXMLType::MeasureXML) { element = docElement.append_child("modeler_description"); text = element.text(); text.set(escapeString(m_modelerDescription).c_str()); element = docElement.append_child("arguments"); for (const BCLMeasureArgument& argument : m_arguments) { auto argumentElement = element.append_child("argument"); argument.writeValues(argumentElement); } element = docElement.append_child("outputs"); for (const BCLMeasureOutput& output : m_outputs) { auto outputElement = element.append_child("output"); output.writeValues(outputElement); } } // TODO: write provenances element = docElement.append_child("provenances"); // write tags // provenances isn't written so element above is not used... so ignore it here // cppcheck-suppress redundantAssignment element = docElement.append_child("tags"); for (const std::string& tag : m_tags) { auto tagElement = element.append_child("tag"); text = tagElement.text(); text.set(tag.c_str()); } // write attributes element = docElement.append_child("attributes"); for (const Attribute& attribute : m_attributes) { std::string value; std::string dataType; switch (attribute.valueType().value()) { case AttributeValueType::Boolean: if (attribute.valueAsBoolean()) { value = "true"; } else { value = "false"; } dataType = "boolean"; break; case AttributeValueType::Double: value = attribute.toString(); dataType = "float"; break; case AttributeValueType::Integer: value = attribute.toString(); dataType = "integer"; break; case AttributeValueType::Unsigned: value = attribute.toString(); dataType = "unsigned"; break; case AttributeValueType::String: value = attribute.toString(); dataType = "string"; break; case AttributeValueType::AttributeVector: // can't handle this yet continue; break; default: // can't handle this yet continue; } auto attributeElement = element.append_child("attribute"); auto subelement = attributeElement.append_child("name"); text = subelement.text(); text.set(attribute.name().c_str()); subelement = attributeElement.append_child("value"); text = subelement.text(); text.set(value.c_str()); subelement = attributeElement.append_child("datatype"); text = subelement.text(); text.set(dataType.c_str()); boost::optional<std::string> units = attribute.units(); if (units) { subelement = attributeElement.append_child("units"); text = subelement.text(); text.set((*units).c_str()); } } // write files element = docElement.append_child("files"); for (const BCLFileReference& file : m_files) { auto subelement = element.append_child("file"); file.writeValues(subelement); } // write to disk openstudio::filesystem::ofstream file(m_path); if (!file.is_open()) { return false; } doc.save(file, " "); file.close(); return true; } bool BCLXML::saveAs(const openstudio::path& xmlPath) { incrementVersionId(); m_path = openstudio::filesystem::system_complete(xmlPath); return save(); } void BCLXML::changeUID() { m_uid = removeBraces(openstudio::createUUID()); // DLM: should this call incrementVersionId() ? } void BCLXML::incrementVersionId() { m_versionId = removeBraces(openstudio::createUUID()); m_versionModified = DateTime::nowUTC().toISO8601(); } bool BCLXML::checkForUpdatesXML() { std::string newChecksum = computeXMLChecksum(); if (m_xmlChecksum.empty()) { // we are unsure if this is a real change or update from version 2 // set this here and return false m_xmlChecksum = newChecksum; return false; } if (m_xmlChecksum != newChecksum) { incrementVersionId(); m_xmlChecksum = newChecksum; return true; } return false; } void printAttributeForChecksum(std::ostream& os, const Attribute& attribute, const std::string& tabs) { if (attribute.valueType() == AttributeValueType::AttributeVector) { for (const Attribute& child : attribute.valueAsAttributeVector()) { printAttributeForChecksum(os, child, tabs + " "); } } else { os << tabs << "Name: " << attribute.name() << '\n'; if (attribute.displayName()) { os << tabs << "Display Name: " << attribute.displayName().get() << '\n'; } os << tabs << "Value Type: " << attribute.valueType().valueName() << '\n'; os << tabs << "Value: " << attribute.toString() << '\n'; if (attribute.units()) { os << tabs << "Units: " << attribute.units().get() << '\n'; } os << '\n'; } } std::string BCLXML::computeXMLChecksum() const { // DLM: CHANGING THE IMPLEMENTATION OF THIS FUNCTION WILL CAUSE // CHECKSUMS TO BE COMPUTED DIFFERENTLY // WE WANT TO AVOID FIGHTING WHERE DIFFERENT VERSIONS OF OPENSTUDIO // COMPUTE THE CHECKSUM IN DIFFERENT WAYS std::stringstream ss; // will be picked up when Ruby file changes //ss << "Name: " << m_name << '\n'; // will be picked up when Ruby file changes //ss << "Display Name: " << m_displayName << '\n'; // will be picked up when Ruby file changes //ss << "Class Name: " << m_className << '\n'; // not managed manually //ss << m_uid; //ss << m_versionId; //ss << m_xmlChecksum; // will be picked up when Ruby file changes //ss << "Description: " << m_description << '\n'; // will be picked up when Ruby file changes //ss << "Modeler Description: " << m_modelerDescription << '\n'; // will be picked up when Ruby file changes //ss << "Arguments: " << '\n'; //for (const BCLMeasureArgument& argument : m_arguments){ // ss << argument << '\n'; //} // will be picked up when checkForUpdatesFiles //ss << "Files: " << '\n'; //for (const BCLFileReference& file : m_files){ // ss << file << '\n'; //} // attributes are edited in the xml ss << "Attributes: " << '\n'; for (const Attribute& attribute : m_attributes) { //ss << attribute; // can't use this because attributes uuid are regenerated on each load // DLM: in the end just create a new method that won't change printAttributeForChecksum(ss, attribute, " "); } // tags are edited in the xml ss << "Tags: " << '\n'; for (const std::string& tag : m_tags) { ss << " " << tag << '\n'; } //std::cout << "Checksum computed on:" << '\n'; //std::cout << ss.str() << '\n'; return checksum(ss); } } // namespace openstudio
30.180365
128
0.64778
muehleisen
bab42054517ff7ed1c53bd02a4889cecd91c01ac
33,810
cpp
C++
library/src/rocblas_auxiliary.cpp
malcolmroberts/rocBLAS
019833e177c362d8def819c8026560a323bac959
[ "MIT" ]
null
null
null
library/src/rocblas_auxiliary.cpp
malcolmroberts/rocBLAS
019833e177c362d8def819c8026560a323bac959
[ "MIT" ]
null
null
null
library/src/rocblas_auxiliary.cpp
malcolmroberts/rocBLAS
019833e177c362d8def819c8026560a323bac959
[ "MIT" ]
null
null
null
/* ************************************************************************ * Copyright 2016-2019 Advanced Micro Devices, Inc. * * ************************************************************************ */ #include <hip/hip_runtime.h> #include <stdio.h> #include "definitions.h" #include "rocblas-types.h" #include "handle.h" #include "logging.h" #include "utility.h" #include "rocblas-auxiliary.h" #include "rocblas_unique_ptr.hpp" #include "Tensile.h" /* ============================================================================================ */ /******************************************************************************* * ! \brief indicates whether the pointer is on the host or device. * currently HIP API can only recoginize the input ptr on deive or not * can not recoginize it is on host or not ******************************************************************************/ rocblas_pointer_mode rocblas_pointer_to_mode(void* ptr) { hipPointerAttribute_t attribute; hipPointerGetAttributes(&attribute, ptr); if(ptr == attribute.devicePointer) return rocblas_pointer_mode_device; else return rocblas_pointer_mode_host; } /******************************************************************************* * ! \brief get pointer mode, can be host or device ******************************************************************************/ extern "C" rocblas_status rocblas_get_pointer_mode(rocblas_handle handle, rocblas_pointer_mode* mode) { // if handle not valid if(!handle) return rocblas_status_invalid_pointer; *mode = handle->pointer_mode; if(handle->layer_mode & rocblas_layer_mode_log_trace) log_trace(handle, "rocblas_get_pointer_mode", *mode); return rocblas_status_success; } /******************************************************************************* * ! \brief set pointer mode to host or device ******************************************************************************/ extern "C" rocblas_status rocblas_set_pointer_mode(rocblas_handle handle, rocblas_pointer_mode mode) { // if handle not valid if(!handle) return rocblas_status_invalid_pointer; if(handle->layer_mode & rocblas_layer_mode_log_trace) log_trace(handle, "rocblas_set_pointer_mode", mode); handle->pointer_mode = mode; return rocblas_status_success; } /******************************************************************************* * ! \brief create rocblas handle called before any rocblas library routines ******************************************************************************/ extern "C" rocblas_status rocblas_create_handle(rocblas_handle* handle) { // if handle not valid if(!handle) return rocblas_status_invalid_pointer; // allocate on heap try { static int dummy = (tensileInitialize(), 0); *handle = new _rocblas_handle(); if((*handle)->layer_mode & rocblas_layer_mode_log_trace) log_trace(*handle, "rocblas_create_handle"); } catch(rocblas_status status) { return status; } return rocblas_status_success; } /******************************************************************************* *! \brief release rocblas handle, will implicitly synchronize host and device ******************************************************************************/ extern "C" rocblas_status rocblas_destroy_handle(rocblas_handle handle) { if(handle->layer_mode & rocblas_layer_mode_log_trace) log_trace(handle, "rocblas_destroy_handle"); // call destructor try { delete handle; } catch(rocblas_status status) { return status; } return rocblas_status_success; } /******************************************************************************* *! \brief set rocblas stream used for all subsequent library function calls. * If not set, all hip kernels will take the default NULL stream. * stream_id must be created before this call ******************************************************************************/ extern "C" rocblas_status rocblas_set_stream(rocblas_handle handle, hipStream_t stream_id) { if(handle->layer_mode & rocblas_layer_mode_log_trace) log_trace(handle, "rocblas_set_stream", stream_id); return handle->set_stream(stream_id); } /******************************************************************************* *! \brief get rocblas stream used for all subsequent library function calls. * If not set, all hip kernels will take the default NULL stream. ******************************************************************************/ extern "C" rocblas_status rocblas_get_stream(rocblas_handle handle, hipStream_t* stream_id) { if(handle->layer_mode & rocblas_layer_mode_log_trace) log_trace(handle, "rocblas_get_stream", *stream_id); return handle->get_stream(stream_id); } /******************************************************************************* *! \brief Non-unit stride vector copy on device. Vectors are void pointers with element size elem_size ******************************************************************************/ // arbitrarily assign max buffer size to 1Mb constexpr size_t VEC_BUFF_MAX_BYTES = 1048576; constexpr rocblas_int NB_X = 256; __global__ void copy_void_ptr_vector_kernel(rocblas_int n, rocblas_int elem_size, const void* x, rocblas_int incx, void* y, rocblas_int incy) { size_t tid = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x; if(tid < n) { memcpy( (char*)y + tid * incy * elem_size, (const char*)x + tid * incx * elem_size, elem_size); } } /******************************************************************************* *! \brief copies void* vector x with stride incx on host to void* vector y with stride incy on device. Vectors have n elements of size elem_size. ******************************************************************************/ extern "C" rocblas_status rocblas_set_vector(rocblas_int n, rocblas_int elem_size, const void* x_h, rocblas_int incx, void* y_d, rocblas_int incy) try { if(n == 0) // quick return return rocblas_status_success; if(n < 0 || incx <= 0 || incy <= 0 || elem_size <= 0) return rocblas_status_invalid_size; if(!x_h || !y_d) return rocblas_status_invalid_pointer; if(incx == 1 && incy == 1) // contiguous host vector -> contiguous device vector { PRINT_IF_HIP_ERROR(hipMemcpy(y_d, x_h, elem_size * n, hipMemcpyHostToDevice)); } else // either non-contiguous host vector or non-contiguous device vector { size_t bytes_to_copy = static_cast<size_t>(elem_size) * static_cast<size_t>(n); size_t temp_byte_size = bytes_to_copy < VEC_BUFF_MAX_BYTES ? bytes_to_copy : VEC_BUFF_MAX_BYTES; int n_elem = temp_byte_size / elem_size; // number of elements in buffer int n_copy = ((n - 1) / n_elem) + 1; // number of times buffer is copied int blocks = (n_elem - 1) / NB_X + 1; // parameters for device kernel dim3 grid(blocks); dim3 threads(NB_X); size_t x_h_byte_stride = (size_t)elem_size * incx; size_t y_d_byte_stride = (size_t)elem_size * incy; size_t t_h_byte_stride = (size_t)elem_size; for(int i_copy = 0; i_copy < n_copy; i_copy++) { int i_start = i_copy * n_elem; int n_elem_max = n - i_start < n_elem ? n - i_start : n_elem; int contig_size = n_elem_max * elem_size; void* y_d_start = (char*)y_d + i_start * y_d_byte_stride; const void* x_h_start = (const char*)x_h + i_start * x_h_byte_stride; if((incx != 1) && (incy != 1)) { // used unique_ptr to avoid memory leak auto t_h_managed = rocblas_unique_ptr{malloc(temp_byte_size), free}; void* t_h = t_h_managed.get(); if(!t_h) return rocblas_status_memory_error; auto t_d_managed = rocblas_unique_ptr{rocblas::device_malloc(temp_byte_size), rocblas::device_free}; void* t_d = t_d_managed.get(); if(!t_d) return rocblas_status_memory_error; // non-contiguous host vector -> host buffer for(size_t i_b = 0, i_x = i_start; i_b < n_elem_max; i_b++, i_x++) { memcpy((char*)t_h + i_b * t_h_byte_stride, (const char*)x_h + i_x * x_h_byte_stride, elem_size); } // host buffer -> device buffer PRINT_IF_HIP_ERROR(hipMemcpy(t_d, t_h, contig_size, hipMemcpyHostToDevice)); // device buffer -> non-contiguous device vector hipLaunchKernelGGL(copy_void_ptr_vector_kernel, grid, threads, 0, 0, n_elem_max, elem_size, t_d, 1, y_d_start, incy); } else if(incx == 1 && incy != 1) { // used unique_ptr to avoid memory leak auto t_d_managed = rocblas_unique_ptr{rocblas::device_malloc(temp_byte_size), rocblas::device_free}; void* t_d = t_d_managed.get(); if(!t_d) return rocblas_status_memory_error; // contiguous host vector -> device buffer PRINT_IF_HIP_ERROR(hipMemcpy(t_d, x_h_start, contig_size, hipMemcpyHostToDevice)); // device buffer -> non-contiguous device vector hipLaunchKernelGGL(copy_void_ptr_vector_kernel, grid, threads, 0, 0, n_elem_max, elem_size, t_d, 1, y_d_start, incy); } else if(incx != 1 && incy == 1) { // used unique_ptr to avoid memory leak auto t_h_managed = rocblas_unique_ptr{malloc(temp_byte_size), free}; void* t_h = t_h_managed.get(); if(!t_h) return rocblas_status_memory_error; // non-contiguous host vector -> host buffer for(size_t i_b = 0, i_x = i_start; i_b < n_elem_max; i_b++, i_x++) { memcpy((char*)t_h + i_b * t_h_byte_stride, (const char*)x_h + i_x * x_h_byte_stride, elem_size); } // host buffer -> contiguous device vector PRINT_IF_HIP_ERROR(hipMemcpy(y_d_start, t_h, contig_size, hipMemcpyHostToDevice)); } } } return rocblas_status_success; } catch(...) // catch all exceptions { return rocblas_status_internal_error; } /******************************************************************************* *! \brief copies void* vector x with stride incx on device to void* vector y with stride incy on host. Vectors have n elements of size elem_size. ******************************************************************************/ extern "C" rocblas_status rocblas_get_vector(rocblas_int n, rocblas_int elem_size, const void* x_d, rocblas_int incx, void* y_h, rocblas_int incy) try { if(n == 0) // quick return return rocblas_status_success; if(n < 0 || incx <= 0 || incy <= 0 || elem_size <= 0) return rocblas_status_invalid_size; if(!x_d || !y_h) return rocblas_status_invalid_pointer; if(incx == 1 && incy == 1) // congiguous device vector -> congiguous host vector { PRINT_IF_HIP_ERROR(hipMemcpy(y_h, x_d, elem_size * n, hipMemcpyDeviceToHost)); } else // either device or host vector is non-contiguous { size_t bytes_to_copy = static_cast<size_t>(elem_size) * static_cast<size_t>(n); size_t temp_byte_size = bytes_to_copy < VEC_BUFF_MAX_BYTES ? bytes_to_copy : VEC_BUFF_MAX_BYTES; int n_elem = temp_byte_size / elem_size; // number elements in buffer int n_copy = ((n - 1) / n_elem) + 1; // number of times buffer is copied int blocks = (n_elem - 1) / NB_X + 1; // parameters for device kernel dim3 grid(blocks); dim3 threads(NB_X); size_t x_d_byte_stride = (size_t)elem_size * incx; size_t y_h_byte_stride = (size_t)elem_size * incy; size_t t_h_byte_stride = (size_t)elem_size; for(int i_copy = 0; i_copy < n_copy; i_copy++) { int i_start = i_copy * n_elem; int n_elem_max = n - (n_elem * i_copy) < n_elem ? n - (n_elem * i_copy) : n_elem; int contig_size = elem_size * n_elem_max; const void* x_d_start = (const char*)x_d + i_start * x_d_byte_stride; void* y_h_start = (char*)y_h + i_start * y_h_byte_stride; if(incx != 1 && incy != 1) { // used unique_ptr to avoid memory leak auto t_h_managed = rocblas_unique_ptr{malloc(temp_byte_size), free}; void* t_h = t_h_managed.get(); if(!t_h) return rocblas_status_memory_error; auto t_d_managed = rocblas_unique_ptr{rocblas::device_malloc(temp_byte_size), rocblas::device_free}; void* t_d = t_d_managed.get(); if(!t_d) return rocblas_status_memory_error; // non-contiguous device vector -> device buffer hipLaunchKernelGGL(copy_void_ptr_vector_kernel, grid, threads, 0, 0, n_elem_max, elem_size, x_d_start, incx, t_d, 1); // device buffer -> host buffer PRINT_IF_HIP_ERROR(hipMemcpy(t_h, t_d, contig_size, hipMemcpyDeviceToHost)); // host buffer -> non-contiguous host vector for(size_t i_b = 0, i_y = i_start; i_b < n_elem_max; i_b++, i_y++) { memcpy((char*)y_h + i_y * y_h_byte_stride, (const char*)t_h + i_b * t_h_byte_stride, elem_size); } } else if(incx == 1 && incy != 1) { // used unique_ptr to avoid memory leak auto t_h_managed = rocblas_unique_ptr{malloc(temp_byte_size), free}; void* t_h = t_h_managed.get(); if(!t_h) return rocblas_status_memory_error; // congiguous device vector -> host buffer PRINT_IF_HIP_ERROR(hipMemcpy(t_h, x_d_start, contig_size, hipMemcpyDeviceToHost)); // host buffer -> non-contiguous host vector for(size_t i_b = 0, i_y = i_start; i_b < n_elem_max; i_b++, i_y++) { memcpy((char*)y_h + i_y * y_h_byte_stride, (const char*)t_h + i_b * t_h_byte_stride, elem_size); } } else if(incx != 1 && incy == 1) { // used unique_ptr to avoid memory leak auto t_d_managed = rocblas_unique_ptr{rocblas::device_malloc(temp_byte_size), rocblas::device_free}; void* t_d = t_d_managed.get(); if(!t_d) return rocblas_status_memory_error; // non-contiguous device vector -> device buffer hipLaunchKernelGGL(copy_void_ptr_vector_kernel, grid, threads, 0, 0, n_elem_max, elem_size, x_d_start, incx, t_d, 1); // device buffer -> contiguous host vector PRINT_IF_HIP_ERROR(hipMemcpy(y_h_start, t_d, contig_size, hipMemcpyDeviceToHost)); } } } return rocblas_status_success; } catch(...) // catch all exceptions { return rocblas_status_internal_error; } /******************************************************************************* *! \brief Matrix copy on device. Matrices are void pointers with element size elem_size ******************************************************************************/ constexpr size_t MAT_BUFF_MAX_BYTES = 1048576; constexpr rocblas_int MATRIX_DIM_X = 128; constexpr rocblas_int MATRIX_DIM_Y = 8; __global__ void copy_void_ptr_matrix_kernel(rocblas_int rows, rocblas_int cols, size_t elem_size, const void* a, rocblas_int lda, void* b, rocblas_int ldb) { rocblas_int tx = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x; rocblas_int ty = hipBlockIdx_y * hipBlockDim_y + hipThreadIdx_y; if(tx < rows && ty < cols) memcpy((char*)b + (tx + ldb * ty) * elem_size, (const char*)a + (tx + lda * ty) * elem_size, elem_size); } /******************************************************************************* *! \brief copies void* matrix a_h with leading dimentsion lda on host to void* matrix b_d with leading dimension ldb on device. Matrices have size rows * cols with element size elem_size. ******************************************************************************/ extern "C" rocblas_status rocblas_set_matrix(rocblas_int rows, rocblas_int cols, rocblas_int elem_size, const void* a_h, rocblas_int lda, void* b_d, rocblas_int ldb) try { if(rows == 0 || cols == 0) // quick return return rocblas_status_success; if(rows < 0 || cols < 0 || lda <= 0 || ldb <= 0 || rows > lda || rows > ldb || elem_size <= 0) return rocblas_status_invalid_size; if(!a_h || !b_d) return rocblas_status_invalid_pointer; // contiguous host matrix -> contiguous device matrix if(lda == rows && ldb == rows) { size_t bytes_to_copy = static_cast<size_t>(elem_size) * static_cast<size_t>(rows) * static_cast<size_t>(cols); PRINT_IF_HIP_ERROR(hipMemcpy(b_d, a_h, bytes_to_copy, hipMemcpyHostToDevice)); } // matrix colums too large to fit in temp buffer, copy matrix col by col else if(rows * elem_size > MAT_BUFF_MAX_BYTES) { for(size_t i = 0; i < cols; i++) { PRINT_IF_HIP_ERROR(hipMemcpy((char*)b_d + ldb * i * elem_size, (const char*)a_h + lda * i * elem_size, (size_t)elem_size * rows, hipMemcpyHostToDevice)); } } // columns fit in temp buffer, pack columns in buffer, hipMemcpy host->device, unpack // columns else { size_t bytes_to_copy = static_cast<size_t>(elem_size) * static_cast<size_t>(rows) * static_cast<size_t>(cols); size_t temp_byte_size = bytes_to_copy < MAT_BUFF_MAX_BYTES ? bytes_to_copy : MAT_BUFF_MAX_BYTES; int n_cols = temp_byte_size / (elem_size * rows); // number of columns in buffer int n_copy = ((cols - 1) / n_cols) + 1; // number of times buffer is copied rocblas_int blocksX = ((rows - 1) / MATRIX_DIM_X) + 1; // parameters for device kernel rocblas_int blocksY = ((n_cols - 1) / MATRIX_DIM_Y) + 1; dim3 grid(blocksX, blocksY); dim3 threads(MATRIX_DIM_X, MATRIX_DIM_Y); size_t lda_h_byte = (size_t)elem_size * lda; size_t ldb_d_byte = (size_t)elem_size * ldb; size_t ldt_h_byte = (size_t)elem_size * rows; for(int i_copy = 0; i_copy < n_copy; i_copy++) { size_t i_start = i_copy * n_cols; int n_cols_max = cols - i_start < n_cols ? cols - i_start : n_cols; int contig_size = elem_size * rows * n_cols_max; void* b_d_start = (char*)b_d + i_start * ldb_d_byte; const void* a_h_start = (const char*)a_h + i_start * lda_h_byte; if((lda != rows) && (ldb != rows)) { // used unique_ptr to avoid memory leak auto t_h_managed = rocblas_unique_ptr{malloc(temp_byte_size), free}; void* t_h = t_h_managed.get(); if(!t_h) return rocblas_status_memory_error; auto t_d_managed = rocblas_unique_ptr{rocblas::device_malloc(temp_byte_size), rocblas::device_free}; void* t_d = t_d_managed.get(); if(!t_d) return rocblas_status_memory_error; // non-contiguous host matrix -> host buffer for(size_t i_t = 0, i_a = i_start; i_t < n_cols_max; i_t++, i_a++) { memcpy((char*)t_h + i_t * ldt_h_byte, (const char*)a_h + i_a * lda_h_byte, ldt_h_byte); } // host buffer -> device buffer PRINT_IF_HIP_ERROR(hipMemcpy(t_d, t_h, contig_size, hipMemcpyHostToDevice)); // device buffer -> non-contiguous device matrix hipLaunchKernelGGL(copy_void_ptr_matrix_kernel, grid, threads, 0, 0, rows, n_cols_max, elem_size, t_d, rows, b_d_start, ldb); } else if(lda == rows && ldb != rows) { // used unique_ptr to avoid memory leak auto t_d_managed = rocblas_unique_ptr{rocblas::device_malloc(temp_byte_size), rocblas::device_free}; void* t_d = t_d_managed.get(); if(!t_d) return rocblas_status_memory_error; // contiguous host matrix -> device buffer PRINT_IF_HIP_ERROR(hipMemcpy(t_d, a_h_start, contig_size, hipMemcpyHostToDevice)); // device buffer -> non-contiguous device matrix hipLaunchKernelGGL(copy_void_ptr_matrix_kernel, grid, threads, 0, 0, rows, n_cols_max, elem_size, t_d, rows, b_d_start, ldb); } else if(lda != rows && ldb == rows) { // used unique_ptr to avoid memory leak auto t_h_managed = rocblas_unique_ptr{malloc(temp_byte_size), free}; void* t_h = t_h_managed.get(); if(!t_h) return rocblas_status_memory_error; // non-contiguous host matrix -> host buffer for(size_t i_t = 0, i_a = i_start; i_t < n_cols_max; i_t++, i_a++) { memcpy((char*)t_h + i_t * ldt_h_byte, (const char*)a_h + i_a * lda_h_byte, ldt_h_byte); } // host buffer -> contiguous device matrix PRINT_IF_HIP_ERROR(hipMemcpy(b_d_start, t_h, contig_size, hipMemcpyHostToDevice)); } } } return rocblas_status_success; } catch(...) // catch all exceptions { return rocblas_status_internal_error; } /******************************************************************************* *! \brief copies void* matrix a_h with leading dimentsion lda on host to void* matrix b_d with leading dimension ldb on device. Matrices have size rows * cols with element size elem_size. ******************************************************************************/ extern "C" rocblas_status rocblas_get_matrix(rocblas_int rows, rocblas_int cols, rocblas_int elem_size, const void* a_d, rocblas_int lda, void* b_h, rocblas_int ldb) try { if(rows == 0 || cols == 0) // quick return return rocblas_status_success; if(rows < 0 || cols < 0 || lda <= 0 || ldb <= 0 || rows > lda || rows > ldb || elem_size <= 0) return rocblas_status_invalid_size; if(!a_d || !b_h) return rocblas_status_invalid_pointer; // congiguous device matrix -> congiguous host matrix if(lda == rows && ldb == rows) { size_t bytes_to_copy = elem_size * static_cast<size_t>(rows) * cols; PRINT_IF_HIP_ERROR(hipMemcpy(b_h, a_d, bytes_to_copy, hipMemcpyDeviceToHost)); } // columns too large for temp buffer, hipMemcpy column by column else if(rows * elem_size > MAT_BUFF_MAX_BYTES) { for(size_t i = 0; i < cols; i++) { PRINT_IF_HIP_ERROR(hipMemcpy((char*)b_h + i * ldb * elem_size, (const char*)a_d + i * lda * elem_size, elem_size * rows, hipMemcpyDeviceToHost)); } } // columns fit in temp buffer, pack columns in buffer, hipMemcpy device->host, unpack // columns else { size_t bytes_to_copy = elem_size * static_cast<size_t>(rows) * cols; size_t temp_byte_size = bytes_to_copy < MAT_BUFF_MAX_BYTES ? bytes_to_copy : MAT_BUFF_MAX_BYTES; int n_cols = temp_byte_size / (elem_size * rows); // number of columns in buffer int n_copy = ((cols - 1) / n_cols) + 1; // number times buffer copied rocblas_int blocksX = ((rows - 1) / MATRIX_DIM_X) + 1; // parameters for device kernel rocblas_int blocksY = ((n_cols - 1) / MATRIX_DIM_Y) + 1; dim3 grid(blocksX, blocksY); dim3 threads(MATRIX_DIM_X, MATRIX_DIM_Y); size_t lda_d_byte = (size_t)elem_size * lda; size_t ldb_h_byte = (size_t)elem_size * ldb; size_t ldt_h_byte = (size_t)elem_size * rows; for(int i_copy = 0; i_copy < n_copy; i_copy++) { int i_start = i_copy * n_cols; int n_cols_max = cols - i_start < n_cols ? cols - i_start : n_cols; size_t contig_size = elem_size * (size_t)rows * n_cols_max; const void* a_d_start = (const char*)a_d + i_start * lda_d_byte; void* b_h_start = (char*)b_h + i_start * ldb_h_byte; if(lda != rows && ldb != rows) { // used unique_ptr to avoid memory leak auto t_h_managed = rocblas_unique_ptr{malloc(temp_byte_size), free}; void* t_h = t_h_managed.get(); if(!t_h) return rocblas_status_memory_error; auto t_d_managed = rocblas_unique_ptr{rocblas::device_malloc(temp_byte_size), rocblas::device_free}; void* t_d = t_d_managed.get(); if(!t_d) return rocblas_status_memory_error; // non-contiguous device matrix -> device buffer hipLaunchKernelGGL(copy_void_ptr_matrix_kernel, grid, threads, 0, 0, rows, n_cols_max, elem_size, a_d_start, lda, t_d, rows); // device buffer -> host buffer PRINT_IF_HIP_ERROR(hipMemcpy(t_h, t_d, contig_size, hipMemcpyDeviceToHost)); // host buffer -> non-contiguous host matrix for(size_t i_t = 0, i_b = i_start; i_t < n_cols_max; i_t++, i_b++) { memcpy((char*)b_h + i_b * ldb_h_byte, (const char*)t_h + i_t * ldt_h_byte, ldt_h_byte); } } else if(lda == rows && ldb != rows) { // used unique_ptr to avoid memory leak auto t_h_managed = rocblas_unique_ptr{malloc(temp_byte_size), free}; void* t_h = t_h_managed.get(); if(!t_h) return rocblas_status_memory_error; // congiguous device matrix -> host buffer PRINT_IF_HIP_ERROR(hipMemcpy(t_h, a_d_start, contig_size, hipMemcpyDeviceToHost)); // host buffer -> non-contiguous host matrix for(size_t i_t = 0, i_b = i_start; i_t < n_cols_max; i_t++, i_b++) { memcpy((char*)b_h + i_b * ldb_h_byte, (const char*)t_h + i_t * ldt_h_byte, ldt_h_byte); } } else if(lda != rows && ldb == rows) { // used unique_ptr to avoid memory leak auto t_d_managed = rocblas_unique_ptr{rocblas::device_malloc(temp_byte_size), rocblas::device_free}; void* t_d = t_d_managed.get(); if(!t_d) return rocblas_status_memory_error; // non-contiguous device matrix -> device buffer hipLaunchKernelGGL(copy_void_ptr_matrix_kernel, grid, threads, 0, 0, rows, n_cols_max, elem_size, a_d_start, lda, t_d, rows); // device temp buffer -> contiguous host matrix PRINT_IF_HIP_ERROR(hipMemcpy(b_h_start, t_d, contig_size, hipMemcpyDeviceToHost)); } } } return rocblas_status_success; } catch(...) // catch all exceptions { return rocblas_status_internal_error; }
45.443548
100
0.46291
malcolmroberts
3bf7f88d08b080cec2043bca0c043c74e6604a4b
88,065
cpp
C++
Game/Points.cpp
sjohal21/Floating-Sandbox
0170e3696ed4f012f5f17fdbbdaef1af4117f495
[ "CC-BY-4.0" ]
44
2018-07-08T16:44:53.000Z
2022-02-06T14:07:30.000Z
Game/Points.cpp
sjohal21/Floating-Sandbox
0170e3696ed4f012f5f17fdbbdaef1af4117f495
[ "CC-BY-4.0" ]
31
2019-03-24T16:00:38.000Z
2022-02-24T20:23:18.000Z
Game/Points.cpp
sjohal21/Floating-Sandbox
0170e3696ed4f012f5f17fdbbdaef1af4117f495
[ "CC-BY-4.0" ]
24
2018-11-08T21:58:53.000Z
2022-01-12T12:04:42.000Z
/*************************************************************************************** * Original Author: Gabriele Giuseppini * Created: 2018-05-06 * Copyright: Gabriele Giuseppini (https://github.com/GabrieleGiuseppini) ***************************************************************************************/ #include "Physics.h" #include <GameCore/GameMath.h> #include <GameCore/Log.h> #include <GameCore/PrecalculatedFunction.h> #include <cmath> #include <limits> namespace Physics { void Points::Add( vec2f const & position, float water, float internalPressure, StructuralMaterial const & structuralMaterial, ElectricalMaterial const * electricalMaterial, bool isRope, float strength, ElementIndex electricalElementIndex, bool isStructurallyLeaking, vec4f const & color, vec2f const & textureCoordinates, float randomNormalizedUniformFloat) { ElementIndex const pointIndex = static_cast<ElementIndex>(mIsDamagedBuffer.GetCurrentPopulatedSize()); mIsDamagedBuffer.emplace_back(false); mMaterialsBuffer.emplace_back(&structuralMaterial, electricalMaterial); mIsRopeBuffer.emplace_back(isRope); mPositionBuffer.emplace_back(position); mFactoryPositionBuffer.emplace_back(position); mVelocityBuffer.emplace_back(vec2f::zero()); mDynamicForceBuffer.emplace_back(vec2f::zero()); mStaticForceBuffer.emplace_back(vec2f::zero()); mAugmentedMaterialMassBuffer.emplace_back(structuralMaterial.GetMass()); mMassBuffer.emplace_back(structuralMaterial.GetMass()); mMaterialBuoyancyVolumeFillBuffer.emplace_back(structuralMaterial.BuoyancyVolumeFill); mStrengthBuffer.emplace_back(strength); mDecayBuffer.emplace_back(1.0f); mFrozenCoefficientBuffer.emplace_back(1.0f); mIntegrationFactorTimeCoefficientBuffer.emplace_back(CalculateIntegrationFactorTimeCoefficient(mCurrentNumMechanicalDynamicsIterations, 1.0f)); mBuoyancyCoefficientsBuffer.emplace_back(CalculateBuoyancyCoefficients( structuralMaterial.BuoyancyVolumeFill, structuralMaterial.ThermalExpansionCoefficient)); mCachedDepthBuffer.emplace_back(mParentWorld.GetOceanSurface().GetDepth(position)); mIntegrationFactorBuffer.emplace_back(vec2f::zero()); mInternalPressureBuffer.emplace_back(internalPressure); mIsHullBuffer.emplace_back(structuralMaterial.IsHull); // Default is from material mMaterialWaterIntakeBuffer.emplace_back(structuralMaterial.WaterIntake); mMaterialWaterRestitutionBuffer.emplace_back(1.0f - structuralMaterial.WaterRetention); mMaterialWaterDiffusionSpeedBuffer.emplace_back(structuralMaterial.WaterDiffusionSpeed); mWaterBuffer.emplace_back(water); mWaterVelocityBuffer.emplace_back(vec2f::zero()); mWaterMomentumBuffer.emplace_back(vec2f::zero()); mCumulatedIntakenWater.emplace_back(0.0f); mLeakingCompositeBuffer.emplace_back(LeakingComposite(isStructurallyLeaking)); if (isStructurallyLeaking) SetStructurallyLeaking(pointIndex); mFactoryIsStructurallyLeakingBuffer.emplace_back(isStructurallyLeaking); mTotalFactoryWetPoints += (water > 0.0f ? 1 : 0); // Heat dynamics mTemperatureBuffer.emplace_back(GameParameters::Temperature0); assert(structuralMaterial.GetHeatCapacity() > 0.0f); mMaterialHeatCapacityReciprocalBuffer.emplace_back(1.0f / structuralMaterial.GetHeatCapacity()); mMaterialThermalExpansionCoefficientBuffer.emplace_back(structuralMaterial.ThermalExpansionCoefficient); mMaterialIgnitionTemperatureBuffer.emplace_back(structuralMaterial.IgnitionTemperature); mMaterialCombustionTypeBuffer.emplace_back(structuralMaterial.CombustionType); mCombustionStateBuffer.emplace_back(CombustionState()); // Electrical dynamics mElectricalElementBuffer.emplace_back(electricalElementIndex); mLightBuffer.emplace_back(0.0f); // Wind dynamics mMaterialWindReceptivityBuffer.emplace_back(structuralMaterial.WindReceptivity); // Rust dynamics mMaterialRustReceptivityBuffer.emplace_back(structuralMaterial.RustReceptivity); // Ephemeral particles mEphemeralParticleAttributes1Buffer.emplace_back(); mEphemeralParticleAttributes2Buffer.emplace_back(); // Structure mConnectedSpringsBuffer.emplace_back(); mFactoryConnectedSpringsBuffer.emplace_back(); mConnectedTrianglesBuffer.emplace_back(); mFactoryConnectedTrianglesBuffer.emplace_back(); // Connectivity mConnectedComponentIdBuffer.emplace_back(NoneConnectedComponentId); mPlaneIdBuffer.emplace_back(NonePlaneId); mPlaneIdFloatBuffer.emplace_back(0.0f); mCurrentConnectivityVisitSequenceNumberBuffer.emplace_back(); // Repair state mRepairStateBuffer.emplace_back(); // Gadgets mIsGadgetAttachedBuffer.emplace_back(false); // Randomness mRandomNormalizedUniformFloatBuffer.emplace_back(randomNormalizedUniformFloat); // Immutable render attributes mColorBuffer.emplace_back(color); mTextureCoordinatesBuffer.emplace_back(textureCoordinates); } void Points::CreateEphemeralParticleAirBubble( vec2f const & position, float depth, float temperature, float vortexAmplitude, float vortexPeriod, float currentSimulationTime, PlaneId planeId) { // Get a free slot (but don't steal one) auto pointIndex = FindFreeEphemeralParticle(currentSimulationTime, false); if (NoneElementIndex == pointIndex) return; // No luck // // Store attributes // StructuralMaterial const & airStructuralMaterial = mMaterialDatabase.GetUniqueStructuralMaterial(StructuralMaterial::MaterialUniqueType::Air); // We want to limit the buoyancy applied to air - using 1.0 makes an air particle boost up too quickly float constexpr AirBuoyancyVolumeFill = 0.003f; assert(mIsDamagedBuffer[pointIndex] == false); // Ephemeral points are never damaged mMaterialsBuffer[pointIndex] = Materials(&airStructuralMaterial, nullptr); mPositionBuffer[pointIndex] = position; mVelocityBuffer[pointIndex] = vec2f::zero(); assert(mDynamicForceBuffer[pointIndex] == vec2f::zero()); // Ephemeral points never participate in dynamic forces (springs + surface pressure) mStaticForceBuffer[pointIndex] = vec2f::zero(); mAugmentedMaterialMassBuffer[pointIndex] = airStructuralMaterial.GetMass(); mMassBuffer[pointIndex] = airStructuralMaterial.GetMass(); mMaterialBuoyancyVolumeFillBuffer[pointIndex] = AirBuoyancyVolumeFill; assert(mDecayBuffer[pointIndex] == 1.0f); //mDecayBuffer[pointIndex] = 1.0f; mFrozenCoefficientBuffer[pointIndex] = 1.0f; mIntegrationFactorTimeCoefficientBuffer[pointIndex] = CalculateIntegrationFactorTimeCoefficient(mCurrentNumMechanicalDynamicsIterations, 1.0f); mBuoyancyCoefficientsBuffer[pointIndex] = CalculateBuoyancyCoefficients( AirBuoyancyVolumeFill, airStructuralMaterial.ThermalExpansionCoefficient); mCachedDepthBuffer[pointIndex] = depth; //mInternalPressureBuffer[pointIndex] = 0.0f; // There's no hull hence we won't need it //mMaterialWaterIntakeBuffer[pointIndex] = airStructuralMaterial.WaterIntake; //mMaterialWaterRestitutionBuffer[pointIndex] = 1.0f - airStructuralMaterial.WaterRetention; //mMaterialWaterDiffusionSpeedBuffer[pointIndex] = airStructuralMaterial.WaterDiffusionSpeed; mWaterBuffer[pointIndex] = 0.0f; assert(!mLeakingCompositeBuffer[pointIndex].IsCumulativelyLeaking); //mLeakingCompositeBuffer[pointIndex] = LeakingComposite(false); mTemperatureBuffer[pointIndex] = temperature; assert(airStructuralMaterial.GetHeatCapacity() > 0.0f); mMaterialHeatCapacityReciprocalBuffer[pointIndex] = 1.0f / airStructuralMaterial.GetHeatCapacity(); mMaterialThermalExpansionCoefficientBuffer[pointIndex] = airStructuralMaterial.ThermalExpansionCoefficient; //mMaterialIgnitionTemperatureBuffer[pointIndex] = airStructuralMaterial.IgnitionTemperature; //mMaterialCombustionTypeBuffer[pointIndex] = airStructuralMaterial.CombustionType; //mCombustionStateBuffer[pointIndex] = CombustionState(); assert(mLightBuffer[pointIndex] == 0.0f); //mLightBuffer[pointIndex] = 0.0f; mMaterialWindReceptivityBuffer[pointIndex] = 0.0f; // Air bubbles (underwater) do not care about wind assert(mMaterialRustReceptivityBuffer[pointIndex] == 0.0f); //mMaterialRustReceptivityBuffer[pointIndex] = 0.0f; mEphemeralParticleAttributes1Buffer[pointIndex].Type = EphemeralType::AirBubble; mEphemeralParticleAttributes1Buffer[pointIndex].StartSimulationTime = currentSimulationTime; mEphemeralParticleAttributes2Buffer[pointIndex].MaxSimulationLifetime = std::numeric_limits<float>::max(); mEphemeralParticleAttributes2Buffer[pointIndex].State = EphemeralState::AirBubbleState( vortexAmplitude, vortexPeriod); assert(mConnectedComponentIdBuffer[pointIndex] == NoneConnectedComponentId); //mConnectedComponentIdBuffer[pointIndex] = NoneConnectedComponentId; mPlaneIdBuffer[pointIndex] = planeId; mPlaneIdFloatBuffer[pointIndex] = static_cast<float>(planeId); mIsPlaneIdBufferEphemeralDirty = true; mColorBuffer[pointIndex] = airStructuralMaterial.RenderColor; mIsEphemeralColorBufferDirty = true; } void Points::CreateEphemeralParticleDebris( vec2f const & position, vec2f const & velocity, float depth, float water, StructuralMaterial const & structuralMaterial, float currentSimulationTime, float maxSimulationLifetime, PlaneId planeId) { // Get a free slot (or steal one) auto pointIndex = FindFreeEphemeralParticle(currentSimulationTime, true); assert(NoneElementIndex != pointIndex); // // Store attributes // assert(mIsDamagedBuffer[pointIndex] == false); // Ephemeral points are never damaged mMaterialsBuffer[pointIndex] = Materials(&structuralMaterial, nullptr); mPositionBuffer[pointIndex] = position; mVelocityBuffer[pointIndex] = velocity; assert(mDynamicForceBuffer[pointIndex] == vec2f::zero()); // Ephemeral points never participate in springs + surface pressure mStaticForceBuffer[pointIndex] = vec2f::zero(); mAugmentedMaterialMassBuffer[pointIndex] = structuralMaterial.GetMass(); mMassBuffer[pointIndex] = structuralMaterial.GetMass(); mMaterialBuoyancyVolumeFillBuffer[pointIndex] = 0.0f; // No buoyancy assert(mDecayBuffer[pointIndex] == 1.0f); //mDecayBuffer[pointIndex] = 1.0f; mFrozenCoefficientBuffer[pointIndex] = 1.0f; mIntegrationFactorTimeCoefficientBuffer[pointIndex] = CalculateIntegrationFactorTimeCoefficient(mCurrentNumMechanicalDynamicsIterations, 1.0f); mBuoyancyCoefficientsBuffer[pointIndex] = BuoyancyCoefficients(0.0f, 0.0f); // No buoyancy mCachedDepthBuffer[pointIndex] = depth; //mInternalPressureBuffer[pointIndex] = 0.0f; // There's no hull hence we won't need it //mMaterialWaterIntakeBuffer[pointIndex] = structuralMaterial.WaterIntake; //mMaterialWaterRestitutionBuffer[pointIndex] = 1.0f - structuralMaterial.WaterRetention; //mMaterialWaterDiffusionSpeedBuffer[pointIndex] = structuralMaterial.WaterDiffusionSpeed; mWaterBuffer[pointIndex] = water; assert(!mLeakingCompositeBuffer[pointIndex].IsCumulativelyLeaking); //mLeakingCompositeBuffer[pointIndex] = LeakingComposite(false); mTemperatureBuffer[pointIndex] = GameParameters::Temperature0; assert(structuralMaterial.GetHeatCapacity() > 0.0f); mMaterialHeatCapacityReciprocalBuffer[pointIndex] = 1.0f / structuralMaterial.GetHeatCapacity(); //mMaterialThermalExpansionCoefficientBuffer[pointIndex] = structuralMaterial.ThermalExpansionCoefficient; //mMaterialIgnitionTemperatureBuffer[pointIndex] = structuralMaterial.IgnitionTemperature; //mMaterialCombustionTypeBuffer[pointIndex] = structuralMaterial.CombustionType; //mCombustionStateBuffer[pointIndex] = CombustionState(); assert(mLightBuffer[pointIndex] == 0.0f); //mLightBuffer[pointIndex] = 0.0f; mMaterialWindReceptivityBuffer[pointIndex] = 3.0f; // Debris are susceptible to wind assert(mMaterialRustReceptivityBuffer[pointIndex] == 0.0f); //mMaterialRustReceptivityBuffer[pointIndex] = 0.0f; mEphemeralParticleAttributes1Buffer[pointIndex].Type = EphemeralType::Debris; mEphemeralParticleAttributes1Buffer[pointIndex].StartSimulationTime = currentSimulationTime; mEphemeralParticleAttributes2Buffer[pointIndex].MaxSimulationLifetime = maxSimulationLifetime; mEphemeralParticleAttributes2Buffer[pointIndex].State = EphemeralState::DebrisState(); assert(mConnectedComponentIdBuffer[pointIndex] == NoneConnectedComponentId); //mConnectedComponentIdBuffer[pointIndex] = NoneConnectedComponentId; mPlaneIdBuffer[pointIndex] = planeId; mPlaneIdFloatBuffer[pointIndex] = static_cast<float>(planeId); mIsPlaneIdBufferEphemeralDirty = true; mColorBuffer[pointIndex] = structuralMaterial.RenderColor; mIsEphemeralColorBufferDirty = true; // Remember that ephemeral points are dirty now mAreEphemeralPointsDirtyForRendering = true; } void Points::CreateEphemeralParticleSmoke( Render::GenericMipMappedTextureGroups textureGroup, EphemeralState::SmokeState::GrowthType growth, vec2f const & position, float depth, float temperature, float currentSimulationTime, PlaneId planeId, GameParameters const & gameParameters) { // Get a free slot (or steal one) auto pointIndex = FindFreeEphemeralParticle(currentSimulationTime, true); assert(NoneElementIndex != pointIndex); // Choose a lifetime float const maxSimulationLifetime = gameParameters.SmokeParticleLifetimeAdjustment * GameRandomEngine::GetInstance().GenerateUniformReal( GameParameters::MinSmokeParticlesLifetime, GameParameters::MaxSmokeParticlesLifetime); // // Store attributes // StructuralMaterial const & airStructuralMaterial = mMaterialDatabase.GetUniqueStructuralMaterial(StructuralMaterial::MaterialUniqueType::Air); float constexpr SmokeBuoyancyVolumeFill = 1.0f; assert(mIsDamagedBuffer[pointIndex] == false); // Ephemeral points are never damaged mMaterialsBuffer[pointIndex] = Materials(&airStructuralMaterial, nullptr); mPositionBuffer[pointIndex] = position; mVelocityBuffer[pointIndex] = vec2f::zero(); assert(mDynamicForceBuffer[pointIndex] == vec2f::zero()); // Ephemeral points never participate in springs nor surface pressure mStaticForceBuffer[pointIndex] = vec2f::zero(); mAugmentedMaterialMassBuffer[pointIndex] = airStructuralMaterial.GetMass(); mMassBuffer[pointIndex] = airStructuralMaterial.GetMass(); mMaterialBuoyancyVolumeFillBuffer[pointIndex] = SmokeBuoyancyVolumeFill; assert(mDecayBuffer[pointIndex] == 1.0f); //mDecayBuffer[pointIndex] = 1.0f; mFrozenCoefficientBuffer[pointIndex] = 1.0f; mIntegrationFactorTimeCoefficientBuffer[pointIndex] = CalculateIntegrationFactorTimeCoefficient(mCurrentNumMechanicalDynamicsIterations, 1.0f); mBuoyancyCoefficientsBuffer[pointIndex] = CalculateBuoyancyCoefficients( SmokeBuoyancyVolumeFill, airStructuralMaterial.ThermalExpansionCoefficient); mCachedDepthBuffer[pointIndex] = depth; //mInternalPressureBuffer[pointIndex] = 0.0f; // There's no hull hence we won't need it //mMaterialWaterIntakeBuffer[pointIndex] = airStructuralMaterial.WaterIntake; //mMaterialWaterRestitutionBuffer[pointIndex] = 1.0f - airStructuralMaterial.WaterRetention; //mMaterialWaterDiffusionSpeedBuffer[pointIndex] = airStructuralMaterial.WaterDiffusionSpeed; mWaterBuffer[pointIndex] = 0.0f; assert(!mLeakingCompositeBuffer[pointIndex].IsCumulativelyLeaking); //mLeakingCompositeBuffer[pointIndex] = LeakingComposite(false); mTemperatureBuffer[pointIndex] = temperature; assert(airStructuralMaterial.GetHeatCapacity() > 0.0f); mMaterialHeatCapacityReciprocalBuffer[pointIndex] = 1.0f / airStructuralMaterial.GetHeatCapacity(); mMaterialThermalExpansionCoefficientBuffer[pointIndex] = airStructuralMaterial.ThermalExpansionCoefficient; //mMaterialIgnitionTemperatureBuffer[pointIndex] = airStructuralMaterial.IgnitionTemperature; //mMaterialCombustionTypeBuffer[pointIndex] = airStructuralMaterial.CombustionType; //mCombustionStateBuffer[pointIndex] = CombustionState(); assert(mLightBuffer[pointIndex] == 0.0f); //mLightBuffer[pointIndex] = 0.0f; mMaterialWindReceptivityBuffer[pointIndex] = 0.2f; // Smoke cares about wind assert(mMaterialRustReceptivityBuffer[pointIndex] == 0.0f); //mMaterialRustReceptivityBuffer[pointIndex] = 0.0f; mEphemeralParticleAttributes1Buffer[pointIndex].Type = EphemeralType::Smoke; mEphemeralParticleAttributes1Buffer[pointIndex].StartSimulationTime = currentSimulationTime; mEphemeralParticleAttributes2Buffer[pointIndex].MaxSimulationLifetime = maxSimulationLifetime; mEphemeralParticleAttributes2Buffer[pointIndex].State = EphemeralState::SmokeState( textureGroup, growth, GameRandomEngine::GetInstance().GenerateNormalizedUniformReal()); assert(mConnectedComponentIdBuffer[pointIndex] == NoneConnectedComponentId); //mConnectedComponentIdBuffer[pointIndex] = NoneConnectedComponentId; mPlaneIdBuffer[pointIndex] = planeId; mPlaneIdFloatBuffer[pointIndex] = static_cast<float>(planeId); mIsPlaneIdBufferEphemeralDirty = true; mColorBuffer[pointIndex] = airStructuralMaterial.RenderColor; mIsEphemeralColorBufferDirty = true; } void Points::CreateEphemeralParticleSparkle( vec2f const & position, vec2f const & velocity, StructuralMaterial const & structuralMaterial, float depth, float currentSimulationTime, float maxSimulationLifetime, PlaneId planeId) { // Get a free slot (or steal one) auto pointIndex = FindFreeEphemeralParticle(currentSimulationTime, true); assert(NoneElementIndex != pointIndex); // // Store attributes // assert(mIsDamagedBuffer[pointIndex] == false); // Ephemeral points are never damaged mMaterialsBuffer[pointIndex] = Materials(&structuralMaterial, nullptr); mPositionBuffer[pointIndex] = position; mVelocityBuffer[pointIndex] = velocity; assert(mDynamicForceBuffer[pointIndex] == vec2f::zero()); // Ephemeral points never participate in springs + surface pressure mStaticForceBuffer[pointIndex] = vec2f::zero(); mAugmentedMaterialMassBuffer[pointIndex] = structuralMaterial.GetMass(); mMassBuffer[pointIndex] = structuralMaterial.GetMass(); mMaterialBuoyancyVolumeFillBuffer[pointIndex] = 0.0f; // No buoyancy assert(mDecayBuffer[pointIndex] == 1.0f); //mDecayBuffer[pointIndex] = 1.0f; mFrozenCoefficientBuffer[pointIndex] = 1.0f; mIntegrationFactorTimeCoefficientBuffer[pointIndex] = CalculateIntegrationFactorTimeCoefficient(mCurrentNumMechanicalDynamicsIterations, 1.0f); mBuoyancyCoefficientsBuffer[pointIndex] = BuoyancyCoefficients(0.0f, 0.0f); // No buoyancy mCachedDepthBuffer[pointIndex] = depth; //mInternalPressureBuffer[pointIndex] = 0.0f; // There's no hull hence we won't need it //mMaterialWaterIntakeBuffer[pointIndex] = structuralMaterial.WaterIntake; //mMaterialWaterRestitutionBuffer[pointIndex] = 1.0f - structuralMaterial.WaterRetention; //mMaterialWaterDiffusionSpeedBuffer[pointIndex] = structuralMaterial.WaterDiffusionSpeed; mWaterBuffer[pointIndex] = 0.0f; assert(!mLeakingCompositeBuffer[pointIndex].IsCumulativelyLeaking); //mLeakingCompositeBuffer[pointIndex] = LeakingComposite(false); mTemperatureBuffer[pointIndex] = GameParameters::Temperature0; assert(structuralMaterial.GetHeatCapacity() > 0.0f); mMaterialHeatCapacityReciprocalBuffer[pointIndex] = 1.0f / structuralMaterial.GetHeatCapacity(); //mMaterialThermalExpansionCoefficientBuffer[pointIndex] = structuralMaterial.ThermalExpansionCoefficient; //mMaterialIgnitionTemperatureBuffer[pointIndex] = structuralMaterial.IgnitionTemperature; //mMaterialCombustionTypeBuffer[pointIndex] = structuralMaterial.CombustionType; //mCombustionStateBuffer[pointIndex] = CombustionState(); assert(mLightBuffer[pointIndex] == 0.0f); //mLightBuffer[pointIndex] = 0.0f; mMaterialWindReceptivityBuffer[pointIndex] = 20.0f; // Sparkles are susceptible to wind assert(mMaterialRustReceptivityBuffer[pointIndex] == 0.0f); //mMaterialRustReceptivityBuffer[pointIndex] = 0.0f; mEphemeralParticleAttributes1Buffer[pointIndex].Type = EphemeralType::Sparkle; mEphemeralParticleAttributes1Buffer[pointIndex].StartSimulationTime = currentSimulationTime; mEphemeralParticleAttributes2Buffer[pointIndex].MaxSimulationLifetime = maxSimulationLifetime; mEphemeralParticleAttributes2Buffer[pointIndex].State = EphemeralState::SparkleState(); assert(mConnectedComponentIdBuffer[pointIndex] == NoneConnectedComponentId); //mConnectedComponentIdBuffer[pointIndex] = NoneConnectedComponentId; mPlaneIdBuffer[pointIndex] = planeId; mPlaneIdFloatBuffer[pointIndex] = static_cast<float>(planeId); mIsPlaneIdBufferEphemeralDirty = true; } void Points::CreateEphemeralParticleWakeBubble( vec2f const & position, vec2f const & velocity, float depth, float currentSimulationTime, PlaneId planeId, GameParameters const & gameParameters) { // Get a free slot (but don't steal one) auto pointIndex = FindFreeEphemeralParticle(currentSimulationTime, false); if (NoneElementIndex == pointIndex) return; // No luck // // Store attributes // StructuralMaterial const & waterStructuralMaterial = mMaterialDatabase.GetUniqueStructuralMaterial(StructuralMaterial::MaterialUniqueType::Water); assert(mIsDamagedBuffer[pointIndex] == false); // Ephemeral points are never damaged mMaterialsBuffer[pointIndex] = Materials(&waterStructuralMaterial, nullptr); mPositionBuffer[pointIndex] = position; mVelocityBuffer[pointIndex] = velocity; assert(mDynamicForceBuffer[pointIndex] == vec2f::zero()); // Ephemeral points never participate in springs + surface pressure mStaticForceBuffer[pointIndex] = vec2f::zero(); mAugmentedMaterialMassBuffer[pointIndex] = waterStructuralMaterial.GetMass(); mMassBuffer[pointIndex] = waterStructuralMaterial.GetMass(); mMaterialBuoyancyVolumeFillBuffer[pointIndex] = waterStructuralMaterial.BuoyancyVolumeFill; assert(mDecayBuffer[pointIndex] == 1.0f); //mDecayBuffer[pointIndex] = 1.0f; mFrozenCoefficientBuffer[pointIndex] = 1.0f; mIntegrationFactorTimeCoefficientBuffer[pointIndex] = CalculateIntegrationFactorTimeCoefficient(mCurrentNumMechanicalDynamicsIterations, 1.0f); mBuoyancyCoefficientsBuffer[pointIndex] = CalculateBuoyancyCoefficients( waterStructuralMaterial.BuoyancyVolumeFill, waterStructuralMaterial.ThermalExpansionCoefficient); mCachedDepthBuffer[pointIndex] = depth; //mInternalPressureBuffer[pointIndex] = 0.0f; // There's no hull hence we won't need it //mMaterialWaterIntakeBuffer[pointIndex] = waterStructuralMaterial.WaterIntake; //mMaterialWaterRestitutionBuffer[pointIndex] = 1.0f - waterStructuralMaterial.WaterRetention; //mMaterialWaterDiffusionSpeedBuffer[pointIndex] = waterStructuralMaterial.WaterDiffusionSpeed; mWaterBuffer[pointIndex] = 0.0f; assert(!mLeakingCompositeBuffer[pointIndex].IsCumulativelyLeaking); //mLeakingCompositeBuffer[pointIndex] = LeakingComposite(false); mTemperatureBuffer[pointIndex] = gameParameters.WaterTemperature; assert(waterStructuralMaterial.GetHeatCapacity() > 0.0f); mMaterialHeatCapacityReciprocalBuffer[pointIndex] = 1.0f / waterStructuralMaterial.GetHeatCapacity(); mMaterialThermalExpansionCoefficientBuffer[pointIndex] = waterStructuralMaterial.ThermalExpansionCoefficient; //mMaterialIgnitionTemperatureBuffer[pointIndex] = waterStructuralMaterial.IgnitionTemperature; //mMaterialCombustionTypeBuffer[pointIndex] = waterStructuralMaterial.CombustionType; //mCombustionStateBuffer[pointIndex] = CombustionState(); assert(mLightBuffer[pointIndex] == 0.0f); //mLightBuffer[pointIndex] = 0.0f; mMaterialWindReceptivityBuffer[pointIndex] = 0.0f; // Wake bubbles (underwater) do not care about wind assert(mMaterialRustReceptivityBuffer[pointIndex] == 0.0f); //mMaterialRustReceptivityBuffer[pointIndex] = 0.0f; mEphemeralParticleAttributes1Buffer[pointIndex].Type = EphemeralType::WakeBubble; mEphemeralParticleAttributes1Buffer[pointIndex].StartSimulationTime = currentSimulationTime; mEphemeralParticleAttributes2Buffer[pointIndex].MaxSimulationLifetime = 0.4f; // Magic number mEphemeralParticleAttributes2Buffer[pointIndex].State = EphemeralState::WakeBubbleState(); assert(mConnectedComponentIdBuffer[pointIndex] == NoneConnectedComponentId); //mConnectedComponentIdBuffer[pointIndex] = NoneConnectedComponentId; mPlaneIdBuffer[pointIndex] = planeId; mPlaneIdFloatBuffer[pointIndex] = static_cast<float>(planeId); mIsPlaneIdBufferEphemeralDirty = true; mColorBuffer[pointIndex] = waterStructuralMaterial.RenderColor; mIsEphemeralColorBufferDirty = true; } void Points::Detach( ElementIndex pointElementIndex, vec2f const & velocity, DetachOptions detachOptions, float currentSimulationTime, GameParameters const & gameParameters) { // We don't detach ephemeral points assert(pointElementIndex < mAlignedShipPointCount); // Invoke ship detach handler assert(nullptr != mShipPhysicsHandler); mShipPhysicsHandler->HandlePointDetach( pointElementIndex, !!(detachOptions & Points::DetachOptions::GenerateDebris), !!(detachOptions & Points::DetachOptions::FireDestroyEvent), currentSimulationTime, gameParameters); // Imprint velocity, unless the point is pinned if (!IsPinned(pointElementIndex)) { mVelocityBuffer[pointElementIndex] = velocity; } // Check if it's the first time we get damaged if (!mIsDamagedBuffer[pointElementIndex]) { // Invoke handler mShipPhysicsHandler->HandlePointDamaged(pointElementIndex); // Flag ourselves as damaged mIsDamagedBuffer[pointElementIndex] = true; } } void Points::Restore(ElementIndex pointElementIndex) { assert(IsDamaged(pointElementIndex)); // Clear the damaged flag mIsDamagedBuffer[pointElementIndex] = false; // Restore factory-time structural IsLeaking mLeakingCompositeBuffer[pointElementIndex].LeakingSources.StructuralLeak = mFactoryIsStructurallyLeakingBuffer[pointElementIndex] ? 1.0f : 0.0f; // Remove point from set of burning points, in case it was burning if (mCombustionStateBuffer[pointElementIndex].State != CombustionState::StateType::NotBurning) { auto pointIt = std::find( mBurningPoints.cbegin(), mBurningPoints.cend(), pointElementIndex); assert(pointIt != mBurningPoints.cend()); mBurningPoints.erase(pointIt); // Restore combustion state mCombustionStateBuffer[pointElementIndex].Reset(); } // Invoke ship handler assert(nullptr != mShipPhysicsHandler); mShipPhysicsHandler->HandlePointRestore(pointElementIndex); } void Points::OnOrphaned(ElementIndex pointElementIndex) { // // If we're in flames, make the flame tiny // if (mCombustionStateBuffer[pointElementIndex].State == CombustionState::StateType::Burning) { // New target: fraction of current size plus something mCombustionStateBuffer[pointElementIndex].MaxFlameDevelopment = mCombustionStateBuffer[pointElementIndex].FlameDevelopment / 3.0f + 0.04f * mRandomNormalizedUniformFloatBuffer[pointElementIndex]; mCombustionStateBuffer[pointElementIndex].State = CombustionState::StateType::Developing_2; } } void Points::DestroyEphemeralParticle( ElementIndex pointElementIndex) { // Invoke ship handler assert(nullptr != mShipPhysicsHandler); mShipPhysicsHandler->HandleEphemeralParticleDestroy(pointElementIndex); // Fire destroy event mGameEventHandler->OnDestroy( GetStructuralMaterial(pointElementIndex), mParentWorld.GetOceanSurface().IsUnderwater(GetPosition(pointElementIndex)), 1u); // Expire particle ExpireEphemeralParticle(pointElementIndex); } void Points::UpdateForGameParameters(GameParameters const & gameParameters) { // // Check parameter changes // float const numMechanicalDynamicsIterations = gameParameters.NumMechanicalDynamicsIterations<float>(); if (numMechanicalDynamicsIterations != mCurrentNumMechanicalDynamicsIterations) { // Recalc integration factor time coefficients for (ElementIndex i : *this) { mIntegrationFactorTimeCoefficientBuffer[i] = CalculateIntegrationFactorTimeCoefficient( numMechanicalDynamicsIterations, mFrozenCoefficientBuffer[i]); } // Remember the new value mCurrentNumMechanicalDynamicsIterations = numMechanicalDynamicsIterations; } float const cumulatedIntakenWaterThresholdForAirBubbles = GameParameters::AirBubblesDensityToCumulatedIntakenWater(gameParameters.AirBubblesDensity); if (cumulatedIntakenWaterThresholdForAirBubbles != mCurrentCumulatedIntakenWaterThresholdForAirBubbles) { // Randomize cumulated water intaken for each leaking point for (ElementIndex i : RawShipPoints()) { if (GetLeakingComposite(i).IsCumulativelyLeaking) { mCumulatedIntakenWater[i] = RandomizeCumulatedIntakenWater(cumulatedIntakenWaterThresholdForAirBubbles); } } // Remember the new value mCurrentCumulatedIntakenWaterThresholdForAirBubbles = cumulatedIntakenWaterThresholdForAirBubbles; } float const combustionSpeedAdjustment = gameParameters.CombustionSpeedAdjustment; if (combustionSpeedAdjustment != mCurrentCombustionSpeedAdjustment) { // Recalc combustion decay parameters CalculateCombustionDecayParameters(combustionSpeedAdjustment, GameParameters::GameParameters::ParticleUpdateLowFrequencyStepTimeDuration<float>); // Remember the new value mCurrentCombustionSpeedAdjustment = combustionSpeedAdjustment; } } void Points::UpdateCombustionLowFrequency( ElementIndex pointOffset, ElementIndex pointStride, float currentSimulationTime, Storm::Parameters const & stormParameters, GameParameters const & gameParameters) { ///////////////////////////////////////////////////////////////////////////// // Take care of following: // - NotBurning->Developing transition (Ignition) // - Burning->Decay, Extinguishing transition ///////////////////////////////////////////////////////////////////////////// // Prepare candidates for ignition and explosion; we'll pick the top N ones // based on the ignition temperature delta mCombustionIgnitionCandidates.clear(); mCombustionExplosionCandidates.clear(); // The cdf for rain: we stop burning with a probability equal to this float const rainExtinguishCdf = FastPow(stormParameters.RainDensity, 0.5f); // // Visit all points // // No real reason not to do ephemeral points as well, other than they're // currently not expected to burn // for (ElementIndex pointIndex = pointOffset; pointIndex < mRawShipPointCount; pointIndex += pointStride) { auto const currentState = mCombustionStateBuffer[pointIndex].State; if (currentState == CombustionState::StateType::NotBurning) { // // See if this point should start burning // float const effectiveIgnitionTemperature = mMaterialIgnitionTemperatureBuffer[pointIndex] * gameParameters.IgnitionTemperatureAdjustment; // Note: we don't check for rain on purpose: we allow flames to develop even if it rains, // we'll eventually smother them later if (GetTemperature(pointIndex) >= effectiveIgnitionTemperature + GameParameters::IgnitionTemperatureHighWatermark && GetWater(pointIndex) < GameParameters::SmotheringWaterLowWatermark && GetDecay(pointIndex) > GameParameters::SmotheringDecayHighWatermark) { auto const combustionType = mMaterialCombustionTypeBuffer[pointIndex]; if (combustionType == StructuralMaterial::MaterialCombustionType::Combustion && !IsCachedUnderwater(pointIndex)) { // Store point as ignition candidate mCombustionIgnitionCandidates.emplace_back( pointIndex, (GetTemperature(pointIndex) - effectiveIgnitionTemperature) / effectiveIgnitionTemperature); } else if (combustionType == StructuralMaterial::MaterialCombustionType::Explosion) { // Store point as explosion candidate mCombustionExplosionCandidates.emplace_back( pointIndex, (GetTemperature(pointIndex) - effectiveIgnitionTemperature) / effectiveIgnitionTemperature); } } } else if (currentState == CombustionState::StateType::Burning) { // // See if this point should start extinguishing... // // ...for water or sea: we do this check at high frequency // ...for temperature or decay or rain: we check it here float const effectiveIgnitionTemperature = mMaterialIgnitionTemperatureBuffer[pointIndex] * gameParameters.IgnitionTemperatureAdjustment; if (GetTemperature(pointIndex) <= (effectiveIgnitionTemperature + GameParameters::IgnitionTemperatureLowWatermark) || GetDecay(pointIndex) < GameParameters::SmotheringDecayLowWatermark) { // // Transition to Extinguishing - by consumption // mCombustionStateBuffer[pointIndex].State = CombustionState::StateType::Extinguishing_Consumed; // Notify combustion end mGameEventHandler->OnPointCombustionEnd(); } else if (GameRandomEngine::GetInstance().GenerateUniformBoolean(rainExtinguishCdf)) { // // Transition to Extinguishing - by smothering for rain // SmotherCombustion(pointIndex, false); } else { // Apply effects of burning // // 1. Decay burning point // auto const pointMass = mMaterialsBuffer[pointIndex].Structural->GetMass(); float const decayAlpha = (mCombustionDecayAlphaFunctionA * pointMass + mCombustionDecayAlphaFunctionB) * pointMass + mCombustionDecayAlphaFunctionC; assert(decayAlpha <= 1.0f); // We can't allow decay to grow // Decay point mDecayBuffer[pointIndex] *= decayAlpha; // // 2. Decay neighbors // for (auto const s : GetConnectedSprings(pointIndex).ConnectedSprings) { mDecayBuffer[s.OtherEndpointIndex] *= decayAlpha; } } } } // // Pick candidates for ignition // if (!mCombustionIgnitionCandidates.empty()) { // Randomly choose the max number of points we want to ignite now, // honoring MaxBurningParticles at the same time size_t const maxIgnitionPoints = std::min( std::min( size_t(4) + GameRandomEngine::GetInstance().Choose(size_t(6)), // 4->9 mBurningPoints.size() < gameParameters.MaxBurningParticles ? static_cast<size_t>(gameParameters.MaxBurningParticles) - mBurningPoints.size() : size_t(0)), mCombustionIgnitionCandidates.size()); // Sort top N candidates by ignition temperature delta std::nth_element( mCombustionIgnitionCandidates.data(), mCombustionIgnitionCandidates.data() + maxIgnitionPoints, mCombustionIgnitionCandidates.data() + mCombustionIgnitionCandidates.size(), [](auto const & t1, auto const & t2) { return std::get<1>(t1) > std::get<1>(t2); }); // Ignite these points for (size_t i = 0; i < maxIgnitionPoints; ++i) { assert(i < mCombustionIgnitionCandidates.size()); auto const pointIndex = std::get<0>(mCombustionIgnitionCandidates[i]); // // Ignite! // mCombustionStateBuffer[pointIndex].State = CombustionState::StateType::Developing_1; // Initial development depends on how deep this particle is in its burning zone mCombustionStateBuffer[pointIndex].FlameDevelopment = 0.1f + 0.5f * SmoothStep(0.0f, 2.0f, std::get<1>(mCombustionIgnitionCandidates[i])); // Max development: random and depending on number of springs connected to this point // (so chains have smaller flames) float const deltaSizeDueToConnectedSprings = static_cast<float>(mConnectedSpringsBuffer[pointIndex].ConnectedSprings.size()) * 0.0625f; // 0.0625 -> 0.50 (@8) mCombustionStateBuffer[pointIndex].MaxFlameDevelopment = std::max( 0.25f + deltaSizeDueToConnectedSprings + 0.5f * mRandomNormalizedUniformFloatBuffer[pointIndex], // 0.25 + dsdtcs -> 0.75 + dsdtcs mCombustionStateBuffer[pointIndex].FlameDevelopment); // Reset flame vector mCombustionStateBuffer[pointIndex].FlameVector = CalculateIdealFlameVector( GetVelocity(pointIndex), 200.0f); // For an initial flame, we want the particle's current velocity to have a smaller impact on the flame vector // Add point to vector of burning points, sorted by plane ID assert(mBurningPoints.cend() == std::find(mBurningPoints.cbegin(), mBurningPoints.cend(), pointIndex)); mBurningPoints.insert( std::lower_bound( // Earlier than others at same plane ID, so it's drawn behind them mBurningPoints.cbegin(), mBurningPoints.cend(), pointIndex, [this](auto p1, auto p2) { // Sort by plane and then by vertical position, so bottommost flames cover uppermost ones return mPlaneIdBuffer[p1] < mPlaneIdBuffer[p2] || (mPlaneIdBuffer[p1] == mPlaneIdBuffer[p2] && mPositionBuffer[p1].y > mPositionBuffer[p2].y); }), pointIndex); // Notify mGameEventHandler->OnPointCombustionBegin(); } } // // Pick candidates for explosion // if (!mCombustionExplosionCandidates.empty()) { size_t const maxExplosionPoints = std::min( size_t(10), // Magic number mCombustionExplosionCandidates.size()); // Sort top N candidates by ignition temperature delta std::nth_element( mCombustionExplosionCandidates.data(), mCombustionExplosionCandidates.data() + maxExplosionPoints, mCombustionExplosionCandidates.data() + mCombustionExplosionCandidates.size(), [](auto const & t1, auto const & t2) { return std::get<1>(t1) > std::get<1>(t2); }); // Calculate blast heat float const blastHeat = GameParameters::CombustionHeat * 1.5f // Arbitrary multiplier * GameParameters::ParticleUpdateLowFrequencyStepTimeDuration<float> * gameParameters.CombustionHeatAdjustment * (gameParameters.IsUltraViolentMode ? 10.0f : 1.0f); // Explode these points for (size_t i = 0; i < maxExplosionPoints; ++i) { assert(i < mCombustionExplosionCandidates.size()); auto const pointIndex = std::get<0>(mCombustionExplosionCandidates[i]); auto const pointPosition = GetPosition(pointIndex); // // Explode! // float const blastRadius = mMaterialsBuffer[pointIndex].Structural->ExplosiveCombustionRadius * (gameParameters.IsUltraViolentMode ? 4.0f : 1.0f); float const blastForce = 40000.0f // Magic number * mMaterialsBuffer[pointIndex].Structural->ExplosiveCombustionStrength; // Start explosion mShipPhysicsHandler->StartExplosion( currentSimulationTime, GetPlaneId(pointIndex), pointPosition, blastRadius, blastForce, blastHeat, ExplosionType::Combustion, gameParameters); // Notify explosion mGameEventHandler->OnCombustionExplosion( IsCachedUnderwater(pointIndex), 1); // Transition state mCombustionStateBuffer[pointIndex].State = CombustionState::StateType::Exploded; } } } void Points::UpdateCombustionHighFrequency( float /*currentSimulationTime*/, float dt, GameParameters const & gameParameters) { // // For all burning points, take care of following: // - Developing points: development up // - Burning points: heat generation // - Extinguishing points: development down // // Heat generated by combustion in this step float const effectiveCombustionHeat = GameParameters::CombustionHeat * dt * gameParameters.CombustionHeatAdjustment; // Points that are not burning anymore after this step assert(mStoppedBurningPoints.empty()); for (auto const pointIndex : mBurningPoints) { CombustionState & pointCombustionState = mCombustionStateBuffer[pointIndex]; assert(pointCombustionState.State != CombustionState::StateType::NotBurning); // Otherwise it wouldn't be in this set // // Check if this point should stop developing/burning or start extinguishing faster // auto const currentState = pointCombustionState.State; if ((currentState == CombustionState::StateType::Developing_1 || currentState == CombustionState::StateType::Developing_2 || currentState == CombustionState::StateType::Burning || currentState == CombustionState::StateType::Extinguishing_Consumed) && (IsCachedUnderwater(pointIndex) || GetWater(pointIndex) > GameParameters::SmotheringWaterHighWatermark)) { // // Transition to Extinguishing - by smothering for water // SmotherCombustion(pointIndex, true); } else if (currentState == CombustionState::StateType::Burning) { // // Generate heat at: // - point itself: fix to constant temperature = ignition temperature + 10% // - neighbors: 100Kw * C, scaled by directional alpha // // This point mTemperatureBuffer[pointIndex] = mMaterialIgnitionTemperatureBuffer[pointIndex] * gameParameters.IgnitionTemperatureAdjustment * 1.1f; // Neighbors for (auto const s : GetConnectedSprings(pointIndex).ConnectedSprings) { auto const otherEndpointIndex = s.OtherEndpointIndex; // Calculate direction coefficient so to prefer upwards direction: // 0.9 + 1.0*(1 - cos(theta)): 2.9 N, 0.9 S, 1.9 W and E vec2f const springDir = (GetPosition(otherEndpointIndex) - GetPosition(pointIndex)).normalise(); float const dirAlpha = (0.9f + 1.0f * (1.0f - springDir.dot(GameParameters::GravityNormalized))); // No normalization: when using normalization flame does not propagate along rope // Add heat to the neighbor, diminishing with the neighbor's decay mTemperatureBuffer[otherEndpointIndex] += effectiveCombustionHeat * dirAlpha * mMaterialHeatCapacityReciprocalBuffer[otherEndpointIndex] * mDecayBuffer[otherEndpointIndex]; } } /* FUTUREWORK The following code emits smoke for burning particles, but there are rendering problems: Smoke should be drawn behind flames, hence GenericTexture's should be drawn in a layer that is earlier than flames. However, generic textures (smoke) have internal transparency, while flames have none; the Z test makes it so then that smoke at plane ID P shows the ship behind it, even though there are flames at plane IDs < P. The only way out that I may think of, at this moment, is to draw flames and generic textures alternatively, for each plane ID (!), or to make smoke fully opaque. // // Check if this point should emit smoke // if (pointCombustionState.State != CombustionState::StateType::NotBurning) { // See if we need to calculate the next emission timestamp if (pointCombustionState.NextSmokeEmissionSimulationTimestamp == 0.0f) { pointCombustionState.NextSmokeEmissionSimulationTimestamp = currentSimulationTime + GameRandomEngine::GetInstance().GenerateExponentialReal( gameParameters.SmokeEmissionDensityAdjustment * pointCombustionState.FlameDevelopment / 1.5f); // TODOHERE: replace with Material's properties, precalc'd with gameParameters.SmokeEmissionDensityAdjustment } // See if it's time to emit smoke if (currentSimulationTime >= pointCombustionState.NextSmokeEmissionSimulationTimestamp) { // // Emit smoke // // Generate particle CreateEphemeralParticleHeavySmoke( GetPosition(pointIndex), GetTemperature(pointIndex), currentSimulationTime, GetPlaneId(pointIndex), gameParameters); // Make sure we re-calculate the next emission timestamp pointCombustionState.NextSmokeEmissionSimulationTimestamp = 0.0f; } } */ // // Run development/extinguishing state machine now // switch (pointCombustionState.State) { case CombustionState::StateType::Developing_1: { // // Develop up // // f(n-1) + 0.04*f(n-1): when starting from 0.1, after 61 steps (~1s) it's 1.1 // http://www.calcul.com/show/calculator/recursive?values=[{%22n%22:0,%22value%22:0.1,%22valid%22:true}]&expression=f(n-1)%20+%200.105*f(n-1)&target=0&endTarget=25&range=true // pointCombustionState.FlameDevelopment += 0.04f * pointCombustionState.FlameDevelopment; // Check whether it's time to transition to the next development phase if (pointCombustionState.FlameDevelopment > pointCombustionState.MaxFlameDevelopment + 0.1f) { pointCombustionState.State = CombustionState::StateType::Developing_2; } break; } case CombustionState::StateType::Developing_2: { // // Develop down // // FlameDevelopment is now in the (MFD + epsilon, MFD) range auto const extraFlameDevelopment = pointCombustionState.FlameDevelopment - pointCombustionState.MaxFlameDevelopment; // Check whether it's time to transition to burning if (extraFlameDevelopment < 0.02f) { pointCombustionState.State = CombustionState::StateType::Burning; pointCombustionState.FlameDevelopment = pointCombustionState.MaxFlameDevelopment; } else { // Keep converging to goal pointCombustionState.FlameDevelopment -= 0.35f * extraFlameDevelopment; } break; } case CombustionState::StateType::Extinguishing_Consumed: case CombustionState::StateType::Extinguishing_SmotheredRain: case CombustionState::StateType::Extinguishing_SmotheredWater: { // // Un-develop // if (pointCombustionState.State == CombustionState::StateType::Extinguishing_Consumed) { // // f(n-1) - 0.0625*(1.01 - f(n-1)): when starting from 1, after 75 steps (1.5s) it's under 0.02 // http://www.calcul.com/show/calculator/recursive?values=[{%22n%22:0,%22value%22:1,%22valid%22:true}]&expression=f(n-1)%20-%200.0625*(1.01%20-%20f(n-1))&target=0&endTarget=80&range=true // pointCombustionState.FlameDevelopment -= 0.0625f * (pointCombustionState.MaxFlameDevelopment - pointCombustionState.FlameDevelopment + 0.01f); } else if (pointCombustionState.State == CombustionState::StateType::Extinguishing_SmotheredRain) { // // f(n-1) - 0.075*f(n-1): when starting from 1, after 50 steps (1.0s) it's under 0.02 // http://www.calcul.com/show/calculator/recursive?values=[{%22n%22:0,%22value%22:1,%22valid%22:true}]&expression=f(n-1)%20-%200.075*f(n-1)&target=0&endTarget=75&range=true // pointCombustionState.FlameDevelopment -= 0.075f * pointCombustionState.FlameDevelopment; } else { assert(pointCombustionState.State == CombustionState::StateType::Extinguishing_SmotheredWater); // // f(n-1) - 0.3*f(n-1): when starting from 1, after 10 steps (0.2s) it's under 0.02 // http://www.calcul.com/show/calculator/recursive?values=[{%22n%22:0,%22value%22:1,%22valid%22:true}]&expression=f(n-1)%20-%200.3*f(n-1)&target=0&endTarget=25&range=true // pointCombustionState.FlameDevelopment -= 0.3f * pointCombustionState.FlameDevelopment; } // Check whether we are done now if (pointCombustionState.FlameDevelopment <= 0.02f) { // // Stop burning // pointCombustionState.State = CombustionState::StateType::NotBurning; // Remove point from set of burning points mStoppedBurningPoints.emplace_back(pointIndex); } break; } case CombustionState::StateType::Burning: case CombustionState::StateType::Exploded: case CombustionState::StateType::NotBurning: { // Nothing to do here break; } } // // Calculate flame vector // // Note: the point might not be burning anymore, in case we've just extinguished it // // Vector Q is the vector describing the ideal, final flame's // direction and length vec2f const Q = CalculateIdealFlameVector( GetVelocity(pointIndex), 100.0f); // Particle's velocity has a larger impact on the final vector // // Converge current flame vector towards target vector Q // // fv(n) = rate * Q + (1 - rate) * fv(n-1) // http://www.calcul.com/show/calculator/recursive?values=[{%22n%22:0,%22value%22:1,%22valid%22:true}]&expression=0.2%20*%205%20+%20(1%20-%200.2)*f(n-1)&target=0&endTarget=80&range=true // // Rate inversely depends on the magnitude of change: // - A big change: little rate (lots of inertia) // - A small change: big rate (immediately responsive) float constexpr MinConvergenceRate = 0.02f; float constexpr MaxConvergenceRate = 0.05f; float const changeMagnitude = std::abs(Q.angleCw(pointCombustionState.FlameVector)); float const convergenceRate = MinConvergenceRate + (MaxConvergenceRate - MinConvergenceRate) * (1.0f - LinearStep(0.0f, Pi<float>, changeMagnitude)); pointCombustionState.FlameVector += (Q - pointCombustionState.FlameVector) * convergenceRate; } // // Remove points that have stopped burning // if (!mStoppedBurningPoints.empty()) { for (auto stoppedBurningPoint : mStoppedBurningPoints) { auto burningPointIt = std::find( mBurningPoints.cbegin(), mBurningPoints.cend(), stoppedBurningPoint); assert(burningPointIt != mBurningPoints.cend()); mBurningPoints.erase(burningPointIt); } mStoppedBurningPoints.clear(); } } void Points::ReorderBurningPointsForDepth() { std::sort( mBurningPoints.begin(), mBurningPoints.end(), [this](auto p1, auto p2) { // Sort by plane and then by vertical position, so bottommost flames cover uppermost ones return mPlaneIdBuffer[p1] < mPlaneIdBuffer[p2] || (mPlaneIdBuffer[p1] == mPlaneIdBuffer[p2] && mPositionBuffer[p1].y > mPositionBuffer[p2].y); }); } void Points::UpdateEphemeralParticles( float currentSimulationTime, GameParameters const & gameParameters) { // Transformation from desired velocity impulse to force float const randomWalkVelocityImpulseToForceCoefficient = GameParameters::AirMass / gameParameters.SimulationStepTimeDuration<float>; // Ocean surface displacement at bubbles surfacing float const oceanFloorDisplacementAtAirBubbleSurfacingSurfaceOffset = (gameParameters.DoDisplaceWater ? 1.0f : 0.0f) * 1.0f; // Visit all ephemeral particles for (ElementIndex pointIndex : this->EphemeralPoints()) { auto const ephemeralType = GetEphemeralType(pointIndex); if (EphemeralType::None != ephemeralType) { // // Run this particle's state machine // switch (ephemeralType) { case EphemeralType::AirBubble: { // Do not advance air bubble if it's pinned if (!IsPinned(pointIndex)) { float const depth = GetCachedDepth(pointIndex); if (depth <= 0.0f) { // Got to the surface, expire ExpireEphemeralParticle(pointIndex); } else { // // Update state // auto & state = mEphemeralParticleAttributes2Buffer[pointIndex].State.AirBubble; // DeltaY state.CurrentDeltaY = depth; // Simulation lifetime auto const simulationLifetime = currentSimulationTime - mEphemeralParticleAttributes1Buffer[pointIndex].StartSimulationTime; state.SimulationLifetime = simulationLifetime; // // Update vortex // float const vortexValue = state.VortexAmplitude * PrecalcLoFreqSin.GetNearestPeriodic( state.NormalizedVortexAngularVelocity * simulationLifetime); // Apply vortex to bubble AddStaticForce( pointIndex, vec2f( vortexValue, 0.0f)); // // Displace ocean surface, if surfacing // if (depth < oceanFloorDisplacementAtAirBubbleSurfacingSurfaceOffset) { mParentWorld.DisplaceOceanSurfaceAt( GetPosition(pointIndex).x, (oceanFloorDisplacementAtAirBubbleSurfacingSurfaceOffset - depth) / 2.0f); // Magic number mGameEventHandler->OnAirBubbleSurfaced(1); } } } break; } case EphemeralType::Debris: { // Check if expired auto const elapsedSimulationLifetime = currentSimulationTime - mEphemeralParticleAttributes1Buffer[pointIndex].StartSimulationTime; auto const maxSimulationLifetime = mEphemeralParticleAttributes2Buffer[pointIndex].MaxSimulationLifetime; if (elapsedSimulationLifetime >= maxSimulationLifetime) { ExpireEphemeralParticle(pointIndex); // Remember that ephemeral points are now dirty mAreEphemeralPointsDirtyForRendering = true; } else { // Update alpha based off remaining time float alpha = std::max( 1.0f - elapsedSimulationLifetime / maxSimulationLifetime, 0.0f); mColorBuffer[pointIndex].w = alpha; mIsEphemeralColorBufferDirty = true; } break; } case EphemeralType::Smoke: { // Calculate progress auto const elapsedSimulationLifetime = currentSimulationTime - mEphemeralParticleAttributes1Buffer[pointIndex].StartSimulationTime; assert(mEphemeralParticleAttributes2Buffer[pointIndex].MaxSimulationLifetime > 0.0f); float const lifetimeProgress = elapsedSimulationLifetime / mEphemeralParticleAttributes2Buffer[pointIndex].MaxSimulationLifetime; // Check if expired if (lifetimeProgress >= 1.0f || IsCachedUnderwater(pointIndex)) { // /// Expired // ExpireEphemeralParticle(pointIndex); } else { // // Still alive // // Update progress mEphemeralParticleAttributes2Buffer[pointIndex].State.Smoke.LifetimeProgress = lifetimeProgress; if (EphemeralState::SmokeState::GrowthType::Slow == mEphemeralParticleAttributes2Buffer[pointIndex].State.Smoke.Growth) { mEphemeralParticleAttributes2Buffer[pointIndex].State.Smoke.ScaleProgress = std::min(1.0f, elapsedSimulationLifetime / 5.0f); } else { assert(EphemeralState::SmokeState::GrowthType::Fast == mEphemeralParticleAttributes2Buffer[pointIndex].State.Smoke.Growth); mEphemeralParticleAttributes2Buffer[pointIndex].State.Smoke.ScaleProgress = 1.07f * (1.0f - exp(-3.0f * lifetimeProgress)); } // Inject random walk in direction orthogonal to current velocity float const randomWalkMagnitude = 0.3f * (static_cast<float>(GameRandomEngine::GetInstance().Choose<int>(2)) - 0.5f); vec2f const deviationDirection = GetVelocity(pointIndex).normalise().to_perpendicular(); AddStaticForce( pointIndex, deviationDirection * randomWalkMagnitude * randomWalkVelocityImpulseToForceCoefficient); } break; } case EphemeralType::Sparkle: { // Check if expired auto const elapsedSimulationLifetime = currentSimulationTime - mEphemeralParticleAttributes1Buffer[pointIndex].StartSimulationTime; auto const maxSimulationLifetime = mEphemeralParticleAttributes2Buffer[pointIndex].MaxSimulationLifetime; if (elapsedSimulationLifetime >= maxSimulationLifetime || IsCachedUnderwater(pointIndex)) { ExpireEphemeralParticle(pointIndex); } else { // Update progress based off remaining time assert(maxSimulationLifetime > 0.0f); mEphemeralParticleAttributes2Buffer[pointIndex].State.Sparkle.Progress = elapsedSimulationLifetime / maxSimulationLifetime; } break; } case EphemeralType::WakeBubble: { // Check if expired auto const elapsedSimulationLifetime = currentSimulationTime - mEphemeralParticleAttributes1Buffer[pointIndex].StartSimulationTime; auto const maxSimulationLifetime = mEphemeralParticleAttributes2Buffer[pointIndex].MaxSimulationLifetime; if (elapsedSimulationLifetime >= maxSimulationLifetime || !IsCachedUnderwater(pointIndex)) { ExpireEphemeralParticle(pointIndex); } else { // Update progress based off remaining time assert(maxSimulationLifetime > 0.0f); mEphemeralParticleAttributes2Buffer[pointIndex].State.WakeBubble.Progress = elapsedSimulationLifetime / maxSimulationLifetime; } break; } default: { // Do nothing } } } } } void Points::UpdateHighlights(GameWallClock::float_time currentWallClockTime) { // // ElectricalElement highlights // auto constexpr ElectricalElementHighlightLifetime = 1s; for (auto it = mElectricalElementHighlightedPoints.begin(); it != mElectricalElementHighlightedPoints.end(); /* incremented in loop */) { // Calculate progress float const progress = GameWallClock::Progress( currentWallClockTime, it->StartTime, ElectricalElementHighlightLifetime); if (progress > 1.0f) { // Expire it = mElectricalElementHighlightedPoints.erase(it); } else { // Update it->Progress = progress; ++it; } } // // Circle // for (auto it = mCircleHighlightedPoints.begin(); it != mCircleHighlightedPoints.end(); /* incremented in loop */) { // Expected sequence when not renewed: // - Highlight created: SimulationStepsExperienced = 0 // - Points::Update: SimulationStepsExperienced = 1 // - Render // - Points::Update: SimulationStepsExperienced = 2 => removed // - Render (none) ++(it->SimulationStepsExperienced); if (it->SimulationStepsExperienced > 1) { // Expire it = mCircleHighlightedPoints.erase(it); } else { ++it; } } } void Points::Query(ElementIndex pointElementIndex) const { LogMessage("PointIndex: ", pointElementIndex, (nullptr != mMaterialsBuffer[pointElementIndex].Structural) ? (" (" + mMaterialsBuffer[pointElementIndex].Structural->Name) + ")" : ""); LogMessage("P=", mPositionBuffer[pointElementIndex].toString(), " V=", mVelocityBuffer[pointElementIndex].toString()); LogMessage("M=", mMassBuffer[pointElementIndex], " IP=", mInternalPressureBuffer[pointElementIndex], " W=", mWaterBuffer[pointElementIndex], " L=", mLightBuffer[pointElementIndex], " T=", mTemperatureBuffer[pointElementIndex], " Decay=", mDecayBuffer[pointElementIndex]); LogMessage("PlaneID: ", mPlaneIdBuffer[pointElementIndex], " ConnectedComponentID: ", mConnectedComponentIdBuffer[pointElementIndex]); } void Points::ColorPoint( ElementIndex pointIndex, rgbaColor const & color) { mColorBuffer[pointIndex] = color.toVec4f(); mIsWholeColorBufferDirty = true; } void Points::UploadAttributes( ShipId shipId, Render::RenderContext & renderContext) const { auto & shipRenderContext = renderContext.GetShipRenderContext(shipId); // Upload immutable attributes, if we haven't uploaded them yet if (mIsTextureCoordinatesBufferDirty) { shipRenderContext.UploadPointImmutableAttributes(mTextureCoordinatesBuffer.data()); mIsTextureCoordinatesBufferDirty = false; } // Upload colors, if dirty if (mIsWholeColorBufferDirty) { renderContext.UploadShipPointColorsAsync( shipId, mColorBuffer.data(), 0, mAllPointCount); mIsWholeColorBufferDirty = false; mIsEphemeralColorBufferDirty = false; } else if (mIsEphemeralColorBufferDirty) { // Only upload ephemeral particle portion renderContext.UploadShipPointColorsAsync( shipId, &(mColorBuffer.data()[mAlignedShipPointCount]), mAlignedShipPointCount, mEphemeralPointCount); mIsEphemeralColorBufferDirty = false; } // // Upload mutable attributes // shipRenderContext.UploadPointMutableAttributesStart(); shipRenderContext.UploadPointMutableAttributes( mPositionBuffer.data(), mLightBuffer.data(), mWaterBuffer.data()); if (mIsPlaneIdBufferNonEphemeralDirty) { if (mIsPlaneIdBufferEphemeralDirty) { // Whole shipRenderContext.UploadPointMutableAttributesPlaneId( mPlaneIdFloatBuffer.data(), 0, mAllPointCount); mIsPlaneIdBufferEphemeralDirty = false; } else { // Just non-ephemeral portion shipRenderContext.UploadPointMutableAttributesPlaneId( mPlaneIdFloatBuffer.data(), 0, mRawShipPointCount); } mIsPlaneIdBufferNonEphemeralDirty = false; } else if (mIsPlaneIdBufferEphemeralDirty) { // Just ephemeral portion shipRenderContext.UploadPointMutableAttributesPlaneId( &(mPlaneIdFloatBuffer.data()[mAlignedShipPointCount]), mAlignedShipPointCount, mEphemeralPointCount); mIsPlaneIdBufferEphemeralDirty = false; } // The following attributes never change for ephemeral particles, // hence after the first upload for reasonable defaults, we only // need to upload them for the ship's (structural = raw) points, // not for the ephemeral ones size_t const partialPointCount = mHaveWholeBuffersBeenUploadedOnce ? mRawShipPointCount : mAllPointCount; if (mIsDecayBufferDirty) { shipRenderContext.UploadPointMutableAttributesDecay( mDecayBuffer.data(), 0, partialPointCount); mIsDecayBufferDirty = false; } if (renderContext.GetHeatRenderMode() != HeatRenderModeType::None) { renderContext.UploadShipPointTemperatureAsync( shipId, mTemperatureBuffer.data(), 0, partialPointCount); } if (renderContext.GetDebugShipRenderMode() == DebugShipRenderModeType::InternalPressure) { renderContext.UploadShipPointAuxiliaryDataAsync( shipId, mInternalPressureBuffer.data(), 0, partialPointCount); } else if (renderContext.GetDebugShipRenderMode() == DebugShipRenderModeType::Strength) { renderContext.UploadShipPointAuxiliaryDataAsync( shipId, mStrengthBuffer.data(), 0, partialPointCount); } shipRenderContext.UploadPointMutableAttributesEnd(); mHaveWholeBuffersBeenUploadedOnce = true; } void Points::UploadNonEphemeralPointElements( ShipId shipId, Render::RenderContext & renderContext) const { bool const doUploadAllPoints = (DebugShipRenderModeType::Points == renderContext.GetDebugShipRenderMode()); auto & shipRenderContext = renderContext.GetShipRenderContext(shipId); for (ElementIndex pointIndex : RawShipPoints()) { if (doUploadAllPoints || mConnectedSpringsBuffer[pointIndex].ConnectedSprings.empty()) // orphaned { shipRenderContext.UploadElementPoint(pointIndex); } } } void Points::UploadFlames( ShipId shipId, Render::RenderContext & renderContext) const { // // Flames are uploaded in this order: // - Z order (guaranteed by internal sorting of mBurningPoints) // - Background flames first (i.e. flames on ropes/springs) followed // by foreground flames // // We use # of triangles as a heuristic for the point being on a chain, // and we use the *factory* ones to avoid sudden depth jumps when triangles are destroyed by fire // auto & shipRenderContext = renderContext.GetShipRenderContext(shipId); shipRenderContext.UploadFlamesStart(mBurningPoints.size()); // Background for (auto const pointIndex : mBurningPoints) { if (mFactoryConnectedTrianglesBuffer[pointIndex].ConnectedTriangles.empty()) { shipRenderContext.UploadBackgroundFlame( GetPlaneId(pointIndex), GetPosition(pointIndex), mCombustionStateBuffer[pointIndex].FlameVector, mCombustionStateBuffer[pointIndex].FlameDevelopment, // scale mRandomNormalizedUniformFloatBuffer[pointIndex]); } } // Foreground for (auto const pointIndex : mBurningPoints) { if (!mFactoryConnectedTrianglesBuffer[pointIndex].ConnectedTriangles.empty()) { shipRenderContext.UploadForegroundFlame( GetPlaneId(pointIndex), GetPosition(pointIndex), mCombustionStateBuffer[pointIndex].FlameVector, mCombustionStateBuffer[pointIndex].FlameDevelopment, // scale mRandomNormalizedUniformFloatBuffer[pointIndex]); } } shipRenderContext.UploadFlamesEnd(); } void Points::UploadVectors( ShipId shipId, Render::RenderContext & renderContext) const { auto & shipRenderContext = renderContext.GetShipRenderContext(shipId); vec4f color; vec2f const * vectorBuffer = nullptr; float lengthAdjustment = 0.0f; switch (renderContext.GetVectorFieldRenderMode()) { case VectorFieldRenderModeType::PointStaticForce: { color = vec4f(0.5f, 0.1f, 0.f, 1.0f); vectorBuffer = mStaticForceBuffer.data(); lengthAdjustment = 0.00075f; break; } case VectorFieldRenderModeType::PointDynamicForce: { color = vec4f(1.0f, 0.266f, 0.16f, 1.0f); vectorBuffer = mDynamicForceBuffer.data(); lengthAdjustment = 0.000001f; break; } case VectorFieldRenderModeType::PointVelocity: { color = vec4f(0.203f, 0.552f, 0.219f, 1.0f); vectorBuffer = mVelocityBuffer.data(); lengthAdjustment = 0.25f; break; } case VectorFieldRenderModeType::PointWaterMomentum: { color = vec4f(0.054f, 0.066f, 0.443f, 1.0f); vectorBuffer = mWaterMomentumBuffer.data(); lengthAdjustment = 0.4f; break; } case VectorFieldRenderModeType::PointWaterVelocity: { color = vec4f(0.094f, 0.509f, 0.925f, 1.0f); vectorBuffer = mWaterVelocityBuffer.data(); lengthAdjustment = 1.0f; break; } case VectorFieldRenderModeType::None: { return; } } shipRenderContext.UploadVectorsStart(mElementCount, color); for (auto const p : this->RawShipPoints()) { shipRenderContext.UploadVector( GetPosition(p), mPlaneIdFloatBuffer[p], vectorBuffer[p], lengthAdjustment); } for (auto const p : this->EphemeralPoints()) { if (GetEphemeralType(p) != EphemeralType::None) { shipRenderContext.UploadVector( GetPosition(p), mPlaneIdFloatBuffer[p], vectorBuffer[p], lengthAdjustment); } } shipRenderContext.UploadVectorsEnd(); } void Points::UploadEphemeralParticles( ShipId shipId, Render::RenderContext & renderContext) const { // // Upload points and/or textures // auto & shipRenderContext = renderContext.GetShipRenderContext(shipId); if (mAreEphemeralPointsDirtyForRendering) { shipRenderContext.UploadElementEphemeralPointsStart(); } for (ElementIndex pointIndex : this->EphemeralPoints()) { switch (GetEphemeralType(pointIndex)) { case EphemeralType::AirBubble: { auto const & state = mEphemeralParticleAttributes2Buffer[pointIndex].State.AirBubble; // Calculate scale based on lifetime float constexpr ScaleMax = 0.275f; float constexpr ScaleMin = 0.04f; float const scale = ScaleMin + (ScaleMax - ScaleMin) * LinearStep(0.0f, 2.0f, state.SimulationLifetime); shipRenderContext.UploadAirBubble( GetPlaneId(pointIndex), GetPosition(pointIndex), scale, std::min(0.6f, state.CurrentDeltaY)); // Alpha break; } case EphemeralType::Debris: { // Don't upload point unless there's been a change if (mAreEphemeralPointsDirtyForRendering) { shipRenderContext.UploadElementEphemeralPoint(pointIndex); } break; } case EphemeralType::Smoke: { auto const & state = mEphemeralParticleAttributes2Buffer[pointIndex].State.Smoke; // Calculate scale float const scale = state.ScaleProgress; // Calculate alpha float const lifetimeProgress = state.LifetimeProgress; float const alpha = SmoothStep(0.0f, 0.05f, lifetimeProgress) - SmoothStep(0.7f, 1.0f, lifetimeProgress); // Upload smoke shipRenderContext.UploadGenericMipMappedTextureRenderSpecification( GetPlaneId(pointIndex), state.PersonalitySeed, state.TextureGroup, GetPosition(pointIndex), scale, alpha); break; } case EphemeralType::Sparkle: { vec2f const velocityVector = -GetVelocity(pointIndex) / GameParameters::MaxSparkleParticlesForCutVelocity; // We use the cut sparkles arbitrarily shipRenderContext.UploadSparkle( GetPlaneId(pointIndex), GetPosition(pointIndex), velocityVector, mEphemeralParticleAttributes2Buffer[pointIndex].State.Sparkle.Progress); break; } case EphemeralType::WakeBubble: { auto const & state = mEphemeralParticleAttributes2Buffer[pointIndex].State.WakeBubble; shipRenderContext.UploadGenericMipMappedTextureRenderSpecification( GetPlaneId(pointIndex), TextureFrameId(Render::GenericMipMappedTextureGroups::EngineWake, 0), GetPosition(pointIndex), 0.10f + 1.22f * state.Progress, // Scale, magic formula mRandomNormalizedUniformFloatBuffer[pointIndex] * 2.0f * Pi<float>, // Angle 1.0f - state.Progress); // Alpha break; } case EphemeralType::None: default: { // Ignore break; } } } if (mAreEphemeralPointsDirtyForRendering) { shipRenderContext.UploadElementEphemeralPointsEnd(); // Not dirty anymore mAreEphemeralPointsDirtyForRendering = false; } } void Points::UploadHighlights( ShipId shipId, Render::RenderContext & renderContext) const { auto & shipRenderContext = renderContext.GetShipRenderContext(shipId); for (auto const & h : mElectricalElementHighlightedPoints) { shipRenderContext.UploadHighlight( HighlightModeType::ElectricalElement, GetPlaneId(h.PointIndex), GetPosition(h.PointIndex), 5.0f, // HalfQuadSize, magic number h.HighlightColor, h.Progress); } for (auto const & h : mCircleHighlightedPoints) { shipRenderContext.UploadHighlight( HighlightModeType::Circle, GetPlaneId(h.PointIndex), GetPosition(h.PointIndex), 4.0f, // HalfQuadSize, magic number h.HighlightColor, 1.0f); } } void Points::AugmentMaterialMass( ElementIndex pointElementIndex, float offset, Springs & springs) { assert(pointElementIndex < mElementCount); mAugmentedMaterialMassBuffer[pointElementIndex] = GetStructuralMaterial(pointElementIndex).GetMass() + offset; // Notify all connected springs for (auto connectedSpring : mConnectedSpringsBuffer[pointElementIndex].ConnectedSprings) { springs.UpdateForMass(connectedSpring.SpringIndex, *this); } } void Points::UpdateMasses(GameParameters const & gameParameters) { // // Update: // - Current mass: augmented material mass + point's water mass, slowly converging to avoid discontinuities // - Integration factor: integration factor time coefficient / current mass // float const densityAdjustedWaterMass = Formulae::CalculateWaterDensity(gameParameters.WaterTemperature, gameParameters); float const * restrict const augmentedMaterialMassBuffer = mAugmentedMaterialMassBuffer.data(); float const * restrict const waterBuffer = mWaterBuffer.data(); float const * restrict const materialBuoyancyVolumeFillBuffer = mMaterialBuoyancyVolumeFillBuffer.data(); float * restrict const massBuffer = mMassBuffer.data(); float const * restrict const integrationFactorTimeCoefficientBuffer = mIntegrationFactorTimeCoefficientBuffer.data(); float * restrict const integrationFactorBuffer = reinterpret_cast<float *>(mIntegrationFactorBuffer.data()); size_t const count = GetBufferElementCount(); for (size_t i = 0; i < count; ++i) { // The mass we want float const targetMass = augmentedMaterialMassBuffer[i] + std::min(waterBuffer[i], materialBuoyancyVolumeFillBuffer[i]) * densityAdjustedWaterMass; // The mass we get: current mass slowly converging towards the mass we want // (nature abhors discontinuities) float const newMass = massBuffer[i] + (targetMass - massBuffer[i]) * 0.12f; assert(newMass > 0.0f); massBuffer[i] = newMass; integrationFactorBuffer[i * 2] = integrationFactorTimeCoefficientBuffer[i] / newMass; integrationFactorBuffer[i * 2 + 1] = integrationFactorTimeCoefficientBuffer[i] / newMass; } } ////////////////////////////////////////////////////////////////////////////////////////////////// void Points::CalculateCombustionDecayParameters( float combustionSpeedAdjustment, float dt) { // // Combustion decay - we want it proportional to mass. // // We want to model the decay alpha as a quadratic law on the burning // particle's mass m: alpha = a * m^2 + b * m + c // // (Ideal) constraints: // // * A cloth mass (0.6Kg) decays (reaches 0.5) in t=12 (simulation) seconds // * An ~iron mass (800Kg) decays (reaches 0.5) in > 60 (simulation) seconds => alpha = 0.980194129 // * The largest mass (2400Kg) decays (reaches 0.5) in a ton of (simulation) seconds => alpha = 0.9998 // // The constraints above are expressed with the following formulas: // n = t / (gameParameters.CombustionSpeedAdjustment * dt) // alpha_i ^ n_i = 0.5 // assert(mMaterialDatabase.GetLargestMass() == 2400.0f); float constexpr m1 = 0.6f; float constexpr t1 = 12.0f; float const n1 = t1 / (combustionSpeedAdjustment * dt); float const alpha1 = std::pow(0.5f, 1.0f / n1); // 0.956739426 float constexpr m2 = 800.0f; float constexpr t2 = 26.5284f; float const n2 = t2 / (combustionSpeedAdjustment * dt); float const alpha2 = std::pow(0.5f, 1.0f / n2); // 0.980194151 float constexpr m3 = 2400.0f; float constexpr t3 = 2653.19f; float const n3 = t3 / (combustionSpeedAdjustment * dt); float const alpha3 = std::pow(0.5f, 1.0f / n3); // 0.9998 // den = (x1−x2)(x1−x3)(x2−x3) // a = x3(y2−y1)+x2(y1−y3)+x1(y3−y2) / den // b = x^21(y2−y3)+x^23(y1−y2)+x^22(y3−y1) / den // c = x^22(x3y1−x1y3)+x2(x^21y3−x^23y1)+x1x3(x3−x1)y2 float const den = (m1 - m2) * (m1 - m3) * (m2 - m3); float const a_num = m3 * (alpha2 - alpha1) + m2 * (alpha1 - alpha3) + m1 * (alpha3 - alpha2); float const b_num = m1 * m1 * (alpha2 - alpha3) + m3 * m3 * (alpha1 - alpha2) + m2 * m2 * (alpha3 - alpha1); float const c_num = m2 * m2 * (m3 * alpha1 - m1 * alpha3) + m2 * (m1 * m1 * alpha3 - m3 * m3 * alpha1) + m1 * m3 * (m3 - m1) * alpha2; mCombustionDecayAlphaFunctionA = a_num / den; mCombustionDecayAlphaFunctionB = b_num / den; mCombustionDecayAlphaFunctionC = c_num / den; } vec2f Points::CalculateIdealFlameVector( vec2f const & pointVelocity, float pointVelocityMagnitudeThreshold) { // Vector Q is the vector describing the ideal, final flame's // direction and (unscaled) length. // // At rest it's (0, 1) - simply, the flame pointing upwards. // When the particle has velocity V, it is the interpolation of the rest upward // vector (B) with the opposite of the particle's velocity: // Q = (1-a) * B - a * V // Where 'a' depends on the magnitude of the particle's velocity. // The interpolation factor depends on the magnitude of the particle's velocity, // via a magic formula; the more the particle's velocity, the more the resultant // vector is aligned with the particle's velocity float const interpolationFactor = SmoothStep(0.0f, pointVelocityMagnitudeThreshold, pointVelocity.length()); vec2f constexpr B = vec2f(0.0f, 1.0f); vec2f Q = B * (1.0f - interpolationFactor) - pointVelocity * interpolationFactor; float const Ql = Q.length(); // Qn = normalized Q vec2f const Qn = Q.normalise(Ql); // Limit length of Q: no more than Qlmax float constexpr Qlmax = 1.8f; // Magic number Q = Qn * std::min(Ql, Qlmax); return Q; } ElementIndex Points::FindFreeEphemeralParticle( float currentSimulationTime, bool doForce) { // // Search for the firt free ephemeral particle; if a free one is not found, reuse the // oldest particle // ElementIndex oldestParticle = NoneElementIndex; float oldestParticleLifetime = 0.0f; assert(mFreeEphemeralParticleSearchStartIndex >= mAlignedShipPointCount && mFreeEphemeralParticleSearchStartIndex < mAllPointCount); for (ElementIndex p = mFreeEphemeralParticleSearchStartIndex; ; /*incremented in loop*/) { if (EphemeralType::None == mEphemeralParticleAttributes1Buffer[p].Type) { // Found! // Remember to start after this one next time mFreeEphemeralParticleSearchStartIndex = p + 1; if (mFreeEphemeralParticleSearchStartIndex >= mAllPointCount) mFreeEphemeralParticleSearchStartIndex = mAlignedShipPointCount; return p; } // Check whether it's the oldest auto const lifetime = currentSimulationTime - mEphemeralParticleAttributes1Buffer[p].StartSimulationTime; if (lifetime >= oldestParticleLifetime) { oldestParticle = p; oldestParticleLifetime = lifetime; } // Advance ++p; if (p >= mAllPointCount) p = mAlignedShipPointCount; if (p == mFreeEphemeralParticleSearchStartIndex) { // Went around break; } } // // No luck // if (!doForce) return NoneElementIndex; // // Steal the oldest // assert(NoneElementIndex != oldestParticle); // Remember to start after this one next time mFreeEphemeralParticleSearchStartIndex = oldestParticle + 1; if (mFreeEphemeralParticleSearchStartIndex >= mAllPointCount) mFreeEphemeralParticleSearchStartIndex = mAlignedShipPointCount; return oldestParticle; } }
40.102459
275
0.645773
sjohal21
3bf870973f94c3fad3df77ce7d23776eaec2a753
101,021
hpp
C++
storage/HashTable.hpp
Hacker0912/quickstep-datalog
1de22e7ab787b5efa619861a167a097ff6a4f549
[ "Apache-2.0" ]
82
2016-04-18T03:59:06.000Z
2019-02-04T11:46:08.000Z
storage/HashTable.hpp
Hacker0912/quickstep-datalog
1de22e7ab787b5efa619861a167a097ff6a4f549
[ "Apache-2.0" ]
265
2016-04-19T17:52:43.000Z
2018-10-11T17:55:08.000Z
storage/HashTable.hpp
Hacker0912/quickstep-datalog
1de22e7ab787b5efa619861a167a097ff6a4f549
[ "Apache-2.0" ]
68
2016-04-18T05:00:34.000Z
2018-10-30T12:41:02.000Z
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. **/ #ifndef QUICKSTEP_STORAGE_HASH_TABLE_HPP_ #define QUICKSTEP_STORAGE_HASH_TABLE_HPP_ #include <atomic> #include <cstddef> #include <cstdlib> #include <type_traits> #include <vector> #include "catalog/CatalogTypedefs.hpp" #include "storage/HashTableBase.hpp" #include "storage/StorageBlob.hpp" #include "storage/StorageBlockInfo.hpp" #include "storage/StorageConstants.hpp" #include "storage/StorageManager.hpp" #include "storage/TupleReference.hpp" #include "storage/ValueAccessor.hpp" #include "storage/ValueAccessorUtil.hpp" #include "threading/SpinSharedMutex.hpp" #include "types/Type.hpp" #include "types/TypedValue.hpp" #include "utility/BloomFilter.hpp" #include "utility/HashPair.hpp" #include "utility/Macros.hpp" namespace quickstep { /** \addtogroup Storage * @{ */ /** * @brief Base class for hash table. * * This class is templated so that the core hash-table logic can be reused in * different contexts requiring different value types and semantics (e.g. * hash-joins vs. hash-based grouping for aggregates vs. hash-based indices). * The base template defines the interface that HashTables provide to clients * and implements some common functionality for all HashTables. There a few * different (also templated) implementation classes that inherit from this * base class and have different physical layouts with different performance * characteristics. As of this writing, they are: * 1. LinearOpenAddressingHashTable - All keys/values are stored directly * in a single array of buckets. Collisions are handled by simply * advancing to the "next" adjacent bucket until an empty bucket is * found. This implementation is vulnerable to performance degradation * due to the formation of bucket chains when there are many duplicate * and/or consecutive keys. * 2. SeparateChainingHashTable - Keys/values are stored in a separate * region of memory from the base hash table slot array. Every bucket * has a "next" pointer so that entries that collide (i.e. map to the * same base slot) form chains of pointers with each other. Although * this implementation has some extra indirection compared to * LinearOpenAddressingHashTable, it does not have the same * vulnerabilities to key skew, and it additionally supports a very * efficient bucket-preallocation mechanism that minimizes cache * coherency overhead when multiple threads are building a HashTable * as part of a hash-join. * 3. SimpleScalarSeparateChainingHashTable - A simplified version of * SeparateChainingHashTable that is only usable for single, scalar * keys with a reversible hash function. This implementation exploits * the reversible hash to avoid storing separate copies of keys at all, * and to skip an extra key comparison when hash codes collide. * * @note If you need to create a HashTable and not just use it as a client, see * HashTableFactory, which simplifies the process of creating a * HashTable. * * @param ValueT The mapped value in this hash table. Must be * copy-constructible. For a serializable hash table, ValueT must also * be trivially copyable and trivially destructible (and beware of * pointers to external memory). * @param resizable Whether this hash table is resizable (using memory from a * StorageManager) or not (using a private, fixed memory allocation). * @param serializable If true, this hash table can safely be saved to and * loaded from disk. If false, some out of band memory may be used (e.g. * to store variable length keys). * @param force_key_copy If true, inserted keys are always copied into this * HashTable's memory. If false, pointers to external values may be * stored instead. force_key_copy should be true if the hash table will * outlive the external key values which are inserted into it. Note that * if serializable is true and force_key_copy is false, then relative * offsets will be used instead of absolute pointers to keys, meaning * that the pointed-to keys must be serialized and deserialized in * exactly the same relative byte order (e.g. as part of the same * StorageBlock), and keys must not change position relative to this * HashTable (beware TupleStorageSubBlocks that may self-reorganize when * modified). If serializable and resizable are both true, then * force_key_copy must also be true. * @param allow_duplicate_keys If true, multiple values can be mapped to the * same key. If false, one and only one value may be mapped. **/ template <typename ValueT, bool resizable, bool serializable, bool force_key_copy, bool allow_duplicate_keys> class HashTable : public HashTableBase<resizable, serializable, force_key_copy, allow_duplicate_keys> { static_assert(std::is_copy_constructible<ValueT>::value, "A HashTable can not be used with a Value type which is not " "copy-constructible."); static_assert((!serializable) || std::is_trivially_destructible<ValueT>::value, "A serializable HashTable can not be used with a Value type " "which is not trivially destructible."); static_assert(!(serializable && resizable && !force_key_copy), "A HashTable must have force_key_copy=true when serializable " "and resizable are both true."); // TODO(chasseur): GCC 4.8.3 doesn't yet implement // std::is_trivially_copyable. In the future, we should include a // static_assert that prevents a serializable HashTable from being used with // a ValueT which is not trivially copyable. public: // Shadow template parameters. This is useful for shared test harnesses. typedef ValueT value_type; static constexpr bool template_resizable = resizable; static constexpr bool template_serializable = serializable; static constexpr bool template_force_key_copy = force_key_copy; static constexpr bool template_allow_duplicate_keys = allow_duplicate_keys; // Some HashTable implementations (notably LinearOpenAddressingHashTable) // use a special hash code to represent an empty bucket, and another special // code to indicate that a bucket is currently being inserted into. For those // HashTables, this is a surrogate hash value for empty buckets. Keys which // actually hash to this value should have their hashes mutated (e.g. by // adding 1). We use zero, since we will often be using memory which is // already zeroed-out and this saves us the trouble of a memset. This has // some downside, as the hash function we use is the identity hash for // integers, and the integer 0 is common in many data sets and must be // adjusted (and will then spuriously collide with 1). Nevertheless, this // expense is outweighed by no longer having to memset large regions of // memory when initializing a HashTable. static constexpr unsigned char kEmptyHashByte = 0x0; static constexpr std::size_t kEmptyHash = 0x0; // A surrogate hash value for a bucket which is currently being inserted // into. As with kEmptyHash, keys which actually hash to this value should // have their hashes adjusted. static constexpr std::size_t kPendingHash = ~kEmptyHash; /** * @brief Virtual destructor. **/ virtual ~HashTable() { if (resizable) { if (blob_.valid()) { if (serializable) { DEV_WARNING("Destroying a resizable serializable HashTable's underlying " "StorageBlob."); } const block_id blob_id = blob_->getID(); blob_.release(); storage_manager_->deleteBlockOrBlobFile(blob_id); } } } /** * @brief Get the ID of the StorageBlob used to store a resizable HashTable. * * @warning This method must not be used for a non-resizable HashTable. * * @return The ID of the StorageBlob used to store this HashTable. **/ inline block_id getBlobId() const { DEBUG_ASSERT(resizable); return blob_->getID(); } /** * @brief Erase all entries in this hash table. * * @warning This method is not guaranteed to be threadsafe. **/ virtual void clear() = 0; /** * @brief Add a new entry into the hash table. * * @warning The key must not be null. * @warning This method is threadsafe with regard to other calls to put(), * putCompositeKey(), putValueAccessor(), and * putValueAccessorCompositeKey(), but should not be used * simultaneously with upsert(), upsertCompositeKey(), * upsertValueAccessor(), or upsertValueAccessorCompositeKey(). * @note This version is for single scalar keys, see also putCompositeKey(). * @note If the hash table is (close to) full and resizable is true, this * routine might result in rebuilding the entire hash table. * * @param key The key. * @param value The value payload. * @return HashTablePutResult::kOK if an entry was successfully inserted, * HashTablePutResult::kDuplicateKey if allow_duplicate_keys is false * and key was a duplicate, or HashTablePutResult::kOutOfSpace if * resizable is false and storage space for the hash table has been * exhausted. **/ HashTablePutResult put(const TypedValue &key, const ValueT &value); /** * @brief Add a new entry into the hash table (composite key version). * * @warning No component of the key may be null. * @warning This method is threadsafe with regard to other calls to put(), * putCompositeKey(), putValueAccessor(), and * putValueAccessorCompositeKey(), but should not be used * simultaneously with upsert(), upsertCompositeKey(), * upsertValueAccessor(), or upsertValueAccessorCompositeKey(). * @note This version is for composite keys, see also put(). * @note If the hash table is (close to) full and resizable is true, this * routine might result in rebuilding the entire hash table. * * @param key The components of the key. * @param value The value payload. * @return HashTablePutResult::kOK if an entry was successfully inserted, * HashTablePutResult::kDuplicateKey if allow_duplicate_keys is false * and key was a duplicate, or HashTablePutResult::kOutOfSpace if * resizable is false and storage space for the hash table has been * exhausted. **/ HashTablePutResult putCompositeKey(const std::vector<TypedValue> &key, const ValueT &value); /** * @brief Add (multiple) new entries into the hash table from a * ValueAccessor. * * @warning This method is threadsafe with regard to other calls to put(), * putCompositeKey(), putValueAccessor(), and * putValueAccessorCompositeKey(), but should not be used * simultaneously with upsert(), upsertCompositeKey(), * upsertValueAccessor(), or upsertValueAccessorCompositeKey(). * @note This version is for scalar keys, see also * putValueAccessorCompositeKey(). * @note If the hash table fills up while this call is in progress and * resizable is true, this might result in rebuilding the entire hash * table. * * @param accessor A ValueAccessor which will be used to access keys. * beginIteration() should be called on accessor before calling this * method. * @param key_attr_id The attribute ID of the keys to be read from accessor. * @param check_for_null_keys If true, each key will be checked to see if it * is null before inserting it (null keys are skipped). This must be * set to true if some of the keys that will be read from accessor may * be null. * @param functor A pointer to a functor, which should provide a call * operator that takes const ValueAccessor& as an argument (or better * yet, a templated call operator which takes a const reference to * some subclass of ValueAccessor as an argument) and returns either * a ValueT or a reference to a ValueT. The functor should generate * the appropriate mapped value for the current tuple the accessor is * iterating on. * @return HashTablePutResult::kOK if all keys and generated values from * accessor were successfully inserted. * HashTablePutResult::kOutOfSpace is returned if this hash-table is * non-resizable and ran out of space (note that some entries may * still have been inserted, and accessor's iteration will be left on * the first tuple which could not be inserted). * HashTablePutResult::kDuplicateKey is returned if * allow_duplicate_keys is false and a duplicate key is encountered * (as with HashTablePutResult::kOutOfSpace, some entries may have * been inserted, and accessor will be left on the tuple with a * duplicate key). **/ template <typename FunctorT> HashTablePutResult putValueAccessor(ValueAccessor *accessor, const attribute_id key_attr_id, const bool check_for_null_keys, FunctorT *functor); /** * @brief Add (multiple) new entries into the hash table from a * ValueAccessor (composite key version). * * @warning This method is threadsafe with regard to other calls to put(), * putCompositeKey(), putValueAccessor(), and * putValueAccessorCompositeKey(), but should not be used * simultaneously with upsert(), upsertCompositeKey(), * upsertValueAccessor(), or upsertValueAccessorCompositeKey(). * @note This version is for composite keys, see also putValueAccessor(). * @note If the hash table fills up while this call is in progress and * resizable is true, this might result in rebuilding the entire hash * table. * * @param accessor A ValueAccessor which will be used to access keys. * beginIteration() should be called on accessor before calling this * method. * @param key_attr_ids The attribute IDs of each key component to be read * from accessor. * @param check_for_null_keys If true, each key will be checked to see if it * has a null component before inserting it (null keys are skipped). * This must be set to true if some of the keys that will be read from * accessor may be null. * @param functor A pointer to a functor, which should provide a call * operator that takes const ValueAccessor& as an argument (or better * yet, a templated call operator which takes a const reference to * some subclass of ValueAccessor as an argument) and returns either * a ValueT or a reference to a ValueT. The functor should generate * the appropriate mapped value for the current tuple the accessor is * iterating on. * @return HashTablePutResult::kOK if all keys and generated values from * accessor were successfully inserted. * HashTablePutResult::kOutOfSpace is returned if this hash-table is * non-resizable and ran out of space (note that some entries may * still have been inserted, and accessor's iteration will be left on * the first tuple which could not be inserted). * HashTablePutResult::kDuplicateKey is returned if * allow_duplicate_keys is false and a duplicate key is encountered * (as with HashTablePutResult::kOutOfSpace, some entries may have * been inserted, and accessor will be left on the tuple with a * duplicate key). **/ template <typename FunctorT> HashTablePutResult putValueAccessorCompositeKey( ValueAccessor *accessor, const std::vector<attribute_id> &key_attr_ids, const bool check_for_null_keys, FunctorT *functor); /** * @brief Apply a functor to the value mapped to a key, first inserting a new * value if one is not already present. * * @warning The key must not be null. * @warning This method is only usable if allow_duplicate_keys is false. * @warning This method is threadsafe with regard to other calls to upsert(), * upsertCompositeKey(), upsertValueAccessor(), and * upsertValueAccessorCompositeKey(), but should not be used * simultaneously with put(), putCompositeKey(), putValueAccessor(), * or putValueAccessorCompositeKey(). * @warning The ValueT* pointer passed to functor's call operator is only * guaranteed to be valid for the duration of the call. The functor * should not store a copy of the pointer and assume that it remains * valid. * @warning Although this method itself is threadsafe, the ValueT object * accessed by functor is not guaranteed to be (although it is * guaranteed that its initial insertion will be atomic). If it is * possible for multiple threads to call upsert() with the same key * at the same time, then their access to ValueT should be made * threadsafe (e.g. with the use of atomic types, mutexes, or some * other external synchronization). * @note This version is for single scalar keys, see also * upsertCompositeKey(). * @note If the hash table is (close to) full and resizable is true, this * routine might result in rebuilding the entire hash table. * * @param key The key. * @param initial_value If there was not already a preexisting entry in this * HashTable for the specified key, then the value will be initialized * with a copy of initial_value. This parameter is ignored if a value * is already present for key. * @param functor A pointer to a functor, which should provide a call * operator which takes ValueT* as an argument. The call operator will * be invoked once on the value corresponding to key (which may be * newly inserted and default-constructed). * @return True on success, false if upsert failed because there was not * enough space to insert a new entry in this HashTable. **/ template <typename FunctorT> bool upsert(const TypedValue &key, const ValueT &initial_value, FunctorT *functor); /** * @brief Apply a functor to the value mapped to a key, first inserting a new * value if one is not already present. * * @warning The key must not be null. * @warning This method is only usable if allow_duplicate_keys is false. * @warning This method is threadsafe with regard to other calls to upsert(), * upsertCompositeKey(), upsertValueAccessor(), and * upsertValueAccessorCompositeKey(), but should not be used * simultaneously with put(), putCompositeKey(), putValueAccessor(), * or putValueAccessorCompositeKey(). * @warning The ValueT* pointer passed to functor's call operator is only * guaranteed to be valid for the duration of the call. The functor * should not store a copy of the pointer and assume that it remains * valid. * @warning Although this method itself is threadsafe, the ValueT object * accessed by functor is not guaranteed to be (although it is * guaranteed that its initial insertion will be atomic). If it is * possible for multiple threads to call upsertCompositeKey() with * the same key at the same time, then their access to ValueT should * be made threadsafe (e.g. with the use of atomic types, mutexes, * or some other external synchronization). * @note This version is for composite keys, see also upsert(). * @note If the hash table is (close to) full and resizable is true, this * routine might result in rebuilding the entire hash table. * * @param key The key. * @param initial_value If there was not already a preexisting entry in this * HashTable for the specified key, then the value will be initialized * with a copy of initial_value. This parameter is ignored if a value * is already present for key. * @param functor A pointer to a functor, which should provide a call * operator which takes ValueT* as an argument. The call operator will * be invoked once on the value corresponding to key (which may be * newly inserted and default-constructed). * @return True on success, false if upsert failed because there was not * enough space to insert a new entry in this HashTable. **/ template <typename FunctorT> bool upsertCompositeKey(const std::vector<TypedValue> &key, const ValueT &initial_value, FunctorT *functor); /** * @brief Apply a functor to (multiple) entries in this hash table, with keys * drawn from a ValueAccessor. New values are first inserted if not * already present. * * @warning This method is only usable if allow_duplicate_keys is false. * @warning This method is threadsafe with regard to other calls to upsert(), * upsertCompositeKey(), upsertValueAccessor(), and * upsertValueAccessorCompositeKey(), but should not be used * simultaneously with put(), putCompositeKey(), putValueAccessor(), * or putValueAccessorCompositeKey(). * @warning The ValueAccessor reference and ValueT* pointer passed to * functor's call operator are only guaranteed to be valid for the * duration of the call. The functor should not store a copy of * these pointers and assume that they remain valid. * @warning Although this method itself is threadsafe, the ValueT object * accessed by functor is not guaranteed to be (although it is * guaranteed that its initial insertion will be atomic). If it is * possible for multiple threads to call upsertValueAccessor() with * the same key at the same time, then their access to ValueT should * be made threadsafe (e.g. with the use of atomic types, mutexes, * or some other external synchronization). * @note This version is for single scalar keys, see also * upsertValueAccessorCompositeKey(). * @note If the hash table is (close to) full and resizable is true, this * routine might result in rebuilding the entire hash table. * * @param accessor A ValueAccessor which will be used to access keys. * beginIteration() should be called on accessor before calling this * method. * @param key_attr_id The attribute ID of the keys to be read from accessor. * @param check_for_null_keys If true, each key will be checked to see if it * is null before upserting it (null keys are skipped). This must be * set to true if some of the keys that will be read from accessor may * be null. * @param functor A pointer to a functor, which should provide a call * operator that takes two arguments: const ValueAccessor& (or better * yet, a templated call operator which takes a const reference to * some subclass of ValueAccessor as its first argument) and ValueT*. * The call operator will be invoked once for every tuple with a * non-null key in accessor. * @return True on success, false if upsert failed because there was not * enough space to insert new entries for all the keys in accessor * (note that some entries may still have been upserted, and * accessor's iteration will be left on the first tuple which could * not be inserted). **/ template <typename FunctorT> bool upsertValueAccessor(ValueAccessor *accessor, const attribute_id key_attr_id, const bool check_for_null_keys, const ValueT &initial_value, FunctorT *functor); /** * @brief Apply a functor to (multiple) entries in this hash table, with keys * drawn from a ValueAccessor. New values are first inserted if not * already present. Composite key version. * * @warning This method is only usable if allow_duplicate_keys is false. * @warning This method is threadsafe with regard to other calls to upsert(), * upsertCompositeKey(), upsertValueAccessor(), and * upsertValueAccessorCompositeKey(), but should not be used * simultaneously with put(), putCompositeKey(), putValueAccessor(), * or putValueAccessorCompositeKey(). * @warning The ValueAccessor reference and ValueT* pointer passed to * functor's call operator are only guaranteed to be valid for the * duration of the call. The functor should not store a copy of * these pointers and assume that they remain valid. * @warning Although this method itself is threadsafe, the ValueT object * accessed by functor is not guaranteed to be (although it is * guaranteed that its initial insertion will be atomic). If it is * possible for multiple threads to call upsertValueAccessor() with * the same key at the same time, then their access to ValueT should * be made threadsafe (e.g. with the use of atomic types, mutexes, * or some other external synchronization). * @note This version is for composite keys, see also upsertValueAccessor(). * @note If the hash table is (close to) full and resizable is true, this * routine might result in rebuilding the entire hash table. * * @param accessor A ValueAccessor which will be used to access keys. * beginIteration() should be called on accessor before calling this * method. * @param key_attr_ids The attribute IDs of each key component to be read * from accessor. * @param check_for_null_keys If true, each key will be checked to see if it * is null before upserting it (null keys are skipped). This must be * set to true if some of the keys that will be read from accessor may * be null. * @param functor A pointer to a functor, which should provide a call * operator that takes two arguments: const ValueAccessor& (or better * yet, a templated call operator which takes a const reference to * some subclass of ValueAccessor as its first argument) and ValueT*. * The call operator will be invoked once for every tuple with a * non-null key in accessor. * @return True on success, false if upsert failed because there was not * enough space to insert new entries for all the keys in accessor * (note that some entries may still have been upserted, and * accessor's iteration will be left on the first tuple which could * not be inserted). **/ template <typename FunctorT> bool upsertValueAccessorCompositeKey( ValueAccessor *accessor, const std::vector<attribute_id> &key_attr_ids, const bool check_for_null_keys, const ValueT &initial_value, FunctorT *functor); /** * @brief Get the size of the hash table at the time this function is called. **/ virtual std::size_t getHashTableMemorySizeBytes() const = 0; /** * @brief Determine the number of entries (key-value pairs) contained in this * HashTable. * @note For some HashTable implementations, this is O(1), but for others it * may be O(n) where n is the number of buckets. * * @warning This method assumes that no concurrent calls to put(), * putCompositeKey(), putValueAccessor(), * putValueAccessorCompositeKey(), upsert(), upsertCompositeKey(), * upsertValueAccessor(), or upsertValueAccessorCompositeKey() are * taking place (i.e. that this HashTable is immutable for the * duration of the call). Concurrent calls to getSingle(), * getSingleCompositeKey(), getAll(), getAllCompositeKey(), * getAllFromValueAccessor(), getAllFromValueAccessorCompositeKey(), * forEach(), and forEachCompositeKey() are safe. * * @return The number of entries in this HashTable. **/ virtual std::size_t numEntries() const = 0; /** * @brief Lookup a key against this hash table to find a matching entry. * * @warning Only usable with the hash table that does not allow duplicate * keys. * @warning The key must not be null. * @warning This method assumes that no concurrent calls to put(), * putCompositeKey(), putValueAccessor(), * putValueAccessorCompositeKey(), upsert(), upsertCompositeKey(), * upsertValueAccessor(), or upsertValueAccessorCompositeKey() are * taking place (i.e. that this HashTable is immutable for the * duration of the call and as long as the returned pointer may be * dereferenced). Concurrent calls to getSingle(), * getSingleCompositeKey(), getAll(), getAllCompositeKey(), * getAllFromValueAccessor(), getAllFromValueAccessorCompositeKey(), * forEach(), and forEachCompositeKey() are safe. * @note This version is for single scalar keys. See also * getSingleCompositeKey(). * * @param key The key to look up. * @return The value of a matched entry if a matching key is found. * Otherwise, return NULL. **/ virtual const ValueT* getSingle(const TypedValue &key) const = 0; /** * @brief Lookup a composite key against this hash table to find a matching * entry. * * @warning Only usable with the hash table that does not allow duplicate * keys. * @warning The key must not be null. * @warning This method assumes that no concurrent calls to put(), * putCompositeKey(), putValueAccessor(), * putValueAccessorCompositeKey(), upsert(), upsertCompositeKey(), * upsertValueAccessor(), or upsertValueAccessorCompositeKey() are * taking place (i.e. that this HashTable is immutable for the * duration of the call and as long as the returned pointer may be * dereferenced). Concurrent calls to getSingle(), * getSingleCompositeKey(), getAll(), getAllCompositeKey(), * getAllFromValueAccessor(), getAllFromValueAccessorCompositeKey(), * forEach(), and forEachCompositeKey() are safe. * @note This version is for composite keys. See also getSingle(). * * @param key The key to look up. * @return The value of a matched entry if a matching key is found. * Otherwise, return NULL. **/ virtual const ValueT* getSingleCompositeKey(const std::vector<TypedValue> &key) const = 0; /** * @brief Lookup a key against this hash table to find matching entries. * * @warning The key must not be null. * @warning This method assumes that no concurrent calls to put(), * putCompositeKey(), putValueAccessor(), * putValueAccessorCompositeKey(), upsert(), upsertCompositeKey(), * upsertValueAccessor(), or upsertValueAccessorCompositeKey() are * taking place (i.e. that this HashTable is immutable for the * duration of the call and as long as the returned pointer may be * dereferenced). Concurrent calls to getSingle(), * getSingleCompositeKey(), getAll(), getAllCompositeKey(), * getAllFromValueAccessor(), getAllFromValueAccessorCompositeKey(), * forEach(), and forEachCompositeKey() are safe. * @note It is more efficient to call getSingle() if the hash table does not * allow duplicate keys. * @note This version is for single scalar keys. See also * getAllCompositeKey(). * * @param key The key to look up. * @param values A vector to hold values of all matching entries. Matches * will be appended to the vector. **/ virtual void getAll(const TypedValue &key, std::vector<const ValueT*> *values) const = 0; /** * @brief Lookup a composite key against this hash table to find matching * entries. * * @warning The key must not be null. * @warning This method assumes that no concurrent calls to put(), * putCompositeKey(), putValueAccessor(), * putValueAccessorCompositeKey(), upsert(), upsertCompositeKey(), * upsertValueAccessor(), or upsertValueAccessorCompositeKey() are * taking place (i.e. that this HashTable is immutable for the * duration of the call and as long as the returned pointer may be * dereferenced). Concurrent calls to getSingle(), * getSingleCompositeKey(), getAll(), getAllCompositeKey(), * getAllFromValueAccessor(), getAllFromValueAccessorCompositeKey(), * forEach(), and forEachCompositeKey() are safe. * @note It is more efficient to call getSingleCompositeKey() if the hash * table does not allow duplicate keys. * @note This version is for composite keys. See also getAll(). * * @param key The key to look up. * @param values A vector to hold values of all matching entries. Matches * will be appended to the vector. **/ virtual void getAllCompositeKey(const std::vector<TypedValue> &key, std::vector<const ValueT*> *values) const = 0; /** * @brief Lookup (multiple) keys from a ValueAccessor and apply a functor to * the matching values. * * @warning This method assumes that no concurrent calls to put(), * putCompositeKey(), putValueAccessor(), * putValueAccessorCompositeKey(), upsert(), upsertCompositeKey(), * upsertValueAccessor(), or upsertValueAccessorCompositeKey() are * taking place (i.e. that this HashTable is immutable for the * duration of the call and as long as the returned pointer may be * dereferenced). Concurrent calls to getSingle(), * getSingleCompositeKey(), getAll(), getAllCompositeKey(), * getAllFromValueAccessor(), getAllFromValueAccessorCompositeKey(), * forEach(), and forEachCompositeKey() are safe. * @note This version is for single scalar keys. See also * getAllFromValueAccessorCompositeKey(). * * @param accessor A ValueAccessor which will be used to access keys. * beginIteration() should be called on accessor before calling this * method. * @param key_attr_id The attribute ID of the keys to be read from accessor. * @param check_for_null_keys If true, each key will be checked to see if it * is null before looking it up (null keys are skipped). This must be * set to true if some of the keys that will be read from accessor may * be null. * @param functor A pointer to a functor, which should provide a call * operator that takes 2 arguments: const ValueAccessor& (or better * yet, a templated call operator which takes a const reference to * some subclass of ValueAccessor as its first argument) and * const ValueT&. The functor will be invoked once for each pair of a * key taken from accessor and matching value. **/ template <typename FunctorT> void getAllFromValueAccessor(ValueAccessor *accessor, const attribute_id key_attr_id, const bool check_for_null_keys, FunctorT *functor) const; /** * @brief Lookup (multiple) keys from a ValueAccessor, apply a functor to the * matching values and additionally call a recordMatch() function of * the functor when the first match for a key is found. * @warning This method assumes that no concurrent calls to put(), * putCompositeKey(), putValueAccessor(), * putValueAccessorCompositeKey(), upsert(), upsertCompositeKey(), * upsertValueAccessor(), or upsertValueAccessorCompositeKey() are * taking place (i.e. that this HashTable is immutable for the * duration of the call and as long as the returned pointer may be * dereferenced). Concurrent calls to getSingle(), * getSingleCompositeKey(), getAll(), getAllCompositeKey(), * getAllFromValueAccessor(), getAllFromValueAccessorCompositeKey(), * forEach(), and forEachCompositeKey() are safe. * @note This version is for single scalar keys. See also * getAllFromValueAccessorCompositeKeyWithExtraWorkForFirstMatch(). * * @param accessor A ValueAccessor which will be used to access keys. * beginIteration() should be called on accessor before calling this * method. * @param key_attr_id The attribute ID of the keys to be read from accessor. * @param check_for_null_keys If true, each key will be checked to see if it * is null before looking it up (null keys are skipped). This must be * set to true if some of the keys that will be read from accessor may * be null. * @param functor A pointer to a functor, which should provide two functions: * 1) An operator that takes 2 arguments: const ValueAccessor& (or better * yet, a templated call operator which takes a const reference to * some subclass of ValueAccessor as its first argument) and * const ValueT&. The operator will be invoked once for each pair of a * key taken from accessor and matching value. * 2) A function hasMatch that takes 1 argument: const ValueAccessor&. * The function will be called only once for a key from accessor when * the first match is found. */ template <typename FunctorT> void getAllFromValueAccessorWithExtraWorkForFirstMatch( ValueAccessor *accessor, const attribute_id key_attr_id, const bool check_for_null_keys, FunctorT *functor) const; /** * @brief Lookup (multiple) keys from a ValueAccessor, apply a functor to the * matching values and additionally call a recordMatch() function of * the functor when the first match for a key is found. Composite key * version. * @warning This method assumes that no concurrent calls to put(), * putCompositeKey(), putValueAccessor(), * putValueAccessorCompositeKey(), upsert(), upsertCompositeKey(), * upsertValueAccessor(), or upsertValueAccessorCompositeKey() are * taking place (i.e. that this HashTable is immutable for the * duration of the call and as long as the returned pointer may be * dereferenced). Concurrent calls to getSingle(), * getSingleCompositeKey(), getAll(), getAllCompositeKey(), * getAllFromValueAccessor(), getAllFromValueAccessorCompositeKey(), * forEach(), and forEachCompositeKey() are safe. * * @param accessor A ValueAccessor which will be used to access keys. * beginIteration() should be called on accessor before calling this * method. * @param key_attr_id The attribute ID of the keys to be read from accessor. * @param check_for_null_keys If true, each key will be checked to see if it * is null before looking it up (null keys are skipped). This must be * set to true if some of the keys that will be read from accessor may * be null. * @param functor A pointer to a functor, which should provide two functions: * 1) An operator that takes 2 arguments: const ValueAccessor& (or better * yet, a templated call operator which takes a const reference to * some subclass of ValueAccessor as its first argument) and * const ValueT&. The operator will be invoked once for each pair of a * key taken from accessor and matching value. * 2) A function hasMatch that takes 1 argument: const ValueAccessor&. * The function will be called only once for a key from accessor when * the first match is found. */ template <typename FunctorT> void getAllFromValueAccessorCompositeKeyWithExtraWorkForFirstMatch( ValueAccessor *accessor, const std::vector<attribute_id> &key_attr_ids, const bool check_for_null_keys, FunctorT *functor) const; /** * @brief Lookup (multiple) keys from a ValueAccessor and apply a functor to * the matching values. Composite key version. * * @warning This method assumes that no concurrent calls to put(), * putCompositeKey(), putValueAccessor(), * putValueAccessorCompositeKey(), upsert(), upsertCompositeKey(), * upsertValueAccessor(), or upsertValueAccessorCompositeKey() are * taking place (i.e. that this HashTable is immutable for the * duration of the call and as long as the returned pointer may be * dereferenced). Concurrent calls to getSingle(), * getSingleCompositeKey(), getAll(), getAllCompositeKey(), * getAllFromValueAccessor(), getAllFromValueAccessorCompositeKey(), * forEach(), and forEachCompositeKey() are safe. * @note This version is for composite keys. See also * getAllFromValueAccessor(). * * @param accessor A ValueAccessor which will be used to access keys. * beginIteration() should be called on accessor before calling this * method. * @param key_attr_ids The attribute IDs of each key component to be read * from accessor. * @param check_for_null_keys If true, each key will be checked to see if it * has a null component before inserting it (null keys are skipped). * This must be set to true if some of the keys that will be read from * accessor may be null. * @param functor A pointer to a functor, which should provide a call * operator that takes 2 arguments: const ValueAccessor& (or better * yet, a templated call operator which takes a const reference to * some subclass of ValueAccessor as its first argument) and * const ValueT&. The functor will be invoked once for each pair of a * key taken from accessor and matching value. **/ template <typename FunctorT> void getAllFromValueAccessorCompositeKey(ValueAccessor *accessor, const std::vector<attribute_id> &key_attr_ids, const bool check_for_null_keys, FunctorT *functor) const; /** * @brief Apply the functor to each key with a match in the hash table. * * @param accessor A ValueAccessor which will be used to access keys. * beginIteration() should be called on accessor before calling this * method. * @param key_attr_id The attribute ID of the keys to be read from accessor. * @param check_for_null_keys If true, each key will be checked to see if it * is null before looking it up (null keys are skipped). This must be * set to true if some of the keys that will be read from accessor may * be null. * @param functor A pointer to a functor which should provide an operator that * takes 1 argument: const ValueAccessor&. The operator will be called * only once for a key from accessor if there is a match. */ template <typename FunctorT> void runOverKeysFromValueAccessorIfMatchFound(ValueAccessor *accessor, const attribute_id key_attr_id, const bool check_for_null_keys, FunctorT *functor) const { return runOverKeysFromValueAccessor<true>(accessor, key_attr_id, check_for_null_keys, functor); } /** * @brief Apply the functor to each key with a match in the hash table. * * @param accessor A ValueAccessor which will be used to access keys. * beginIteration() should be called on accessor before calling this * method. * @param key_attr_id The attribute ID of the keys to be read from accessor. * @param check_for_null_keys If true, each key will be checked to see if it * is null before looking it up (null keys are skipped). This must be * set to true if some of the keys that will be read from accessor may * be null. * @param functor A pointer to a functor which should provide an operator that * takes 1 argument: const ValueAccessor&. The operator will be called * only once for a key from accessor if there is a match. */ template <typename FunctorT> void runOverKeysFromValueAccessorIfMatchFoundCompositeKey( ValueAccessor *accessor, const std::vector<attribute_id> &key_attr_ids, const bool check_for_null_keys, FunctorT *functor) const { return runOverKeysFromValueAccessorCompositeKey<true>(accessor, key_attr_ids, check_for_null_keys, functor); } /** * @brief Apply the functor to each key without a match in the hash table. * * @param accessor A ValueAccessor which will be used to access keys. * beginIteration() should be called on accessor before calling this * method. * @param key_attr_id The attribute ID of the keys to be read from accessor. * @param check_for_null_keys If true, each key will be checked to see if it * is null before looking it up (null keys are skipped). This must be * set to true if some of the keys that will be read from accessor may * be null. * @param functor A pointer to a functor which should provide an operator that * takes 1 argument: const ValueAccessor&. The operator will be called * only once for a key from accessor if there is no match. */ template <typename FunctorT> void runOverKeysFromValueAccessorIfMatchNotFound( ValueAccessor *accessor, const attribute_id key_attr_id, const bool check_for_null_keys, FunctorT *functor) const { return runOverKeysFromValueAccessor<false>(accessor, key_attr_id, check_for_null_keys, functor); } /** * @brief Apply the functor to each key without a match in the hash table. * * @param accessor A ValueAccessor which will be used to access keys. * beginIteration() should be called on accessor before calling this * method. * @param key_attr_id The attribute ID of the keys to be read from accessor. * @param check_for_null_keys If true, each key will be checked to see if it * is null before looking it up (null keys are skipped). This must be * set to true if some of the keys that will be read from accessor may * be null. * @param functor A pointer to a functor which should provide an operator that * takes 1 argument: const ValueAccessor&. The operator will be called * only once for a key from accessor if there is no match. */ template <typename FunctorT> void runOverKeysFromValueAccessorIfMatchNotFoundCompositeKey( ValueAccessor *accessor, const std::vector<attribute_id> &key_attr_ids, const bool check_for_null_keys, FunctorT *functor) const { return runOverKeysFromValueAccessorCompositeKey<false>(accessor, key_attr_ids, check_for_null_keys, functor); } /** * @brief Apply a functor to each key, value pair in this hash table. * * @warning This method assumes that no concurrent calls to put(), * putCompositeKey(), putValueAccessor(), * putValueAccessorCompositeKey(), upsert(), upsertCompositeKey(), * upsertValueAccessor(), or upsertValueAccessorCompositeKey() are * taking place (i.e. that this HashTable is immutable for the * duration of the call and as long as the returned pointer may be * dereferenced). Concurrent calls to getSingle(), * getSingleCompositeKey(), getAll(), getAllCompositeKey(), * getAllFromValueAccessor(), getAllFromValueAccessorCompositeKey(), * forEach(), and forEachCompositeKey() are safe. * @note This version is for single scalar keys. See also * forEachCompositeKey(). * * @param functor A pointer to a functor, which should provide a call * operator which takes 2 arguments: const TypedValue&, const ValueT&. * The call operator will be invoked once on each key, value pair in * this hash table (note that if allow_duplicate_keys is true, * the call may occur multiple times for the same key with different * values). * @return The number of key-value pairs visited. **/ template <typename FunctorT> std::size_t forEach(FunctorT *functor) const; /** * @brief Apply a functor to each key, value pair in this hash table. * * @warning This method assumes that no concurrent calls to put(), * putCompositeKey(), putValueAccessor(), * putValueAccessorCompositeKey(), upsert(), upsertCompositeKey(), * upsertValueAccessor(), or upsertValueAccessorCompositeKey() are * taking place (i.e. that this HashTable is immutable for the * duration of the call and as long as the returned pointer may be * dereferenced). Concurrent calls to getSingle(), * getSingleCompositeKey(), getAll(), getAllCompositeKey(), * getAllFromValueAccessor(), getAllFromValueAccessorCompositeKey(), * forEach(), and forEachCompositeKey() are safe. * @note This version is for composite keys. See also forEach(). * * @param functor A pointer to a functor, which should provide a call * operator which takes 2 arguments: const std::vector<TypedValue>&, * const ValueT&. The call operator will be invoked once on each key, * value pair in this hash table (note that if allow_duplicate_keys is * true, the call may occur multiple times for the same key with * different values). * @return The number of key-value pairs visited. **/ template <typename FunctorT> std::size_t forEachCompositeKey(FunctorT *functor) const; protected: /** * @brief Constructor for new resizable hash table. * * @param key_types A vector of one or more types (>1 indicates a composite * key). * @param num_entries The estimated number of entries this hash table will * hold. * @param storage_manager The StorageManager to use (a StorageBlob will be * allocated to hold this hash table's contents). * @param adjust_hashes If true, the hash of a key should be modified by * applying AdjustHash() so that it does not collide with one of the * special values kEmptyHash or kPendingHash. If false, the hash is * used as-is. * @param use_scalar_literal_hash If true, the key is a single scalar literal * (non-composite) that it is safe to use the simplified hash function * TypedValue::getHashScalarLiteral() on. If false, the generic * TypedValue::getHash() method will be used. * @param preallocate_supported If true, this HashTable overrides * preallocateForBulkInsert() to allow bulk-allocation of resources * (i.e. buckets and variable-length key storage) in a single up-front * pass when bulk-inserting entries. If false, resources are allocated * on the fly for each entry. **/ HashTable(const std::vector<const Type*> &key_types, const std::size_t num_entries, StorageManager *storage_manager, const bool adjust_hashes, const bool use_scalar_literal_hash, const bool preallocate_supported) : key_types_(key_types), scalar_key_inline_(true), key_inline_(nullptr), adjust_hashes_(adjust_hashes), use_scalar_literal_hash_(use_scalar_literal_hash), preallocate_supported_(preallocate_supported), storage_manager_(storage_manager), hash_table_memory_(nullptr), hash_table_memory_size_(0) { DEBUG_ASSERT(resizable); } /** * @brief Constructor for non-resizable hash table. * * @param key_types A vector of one or more types (>1 indicates a composite * key). * @param hash_table_memory A pointer to memory to use for this hash table. * @param hash_table_memory_size The size of hash_table_memory in bytes. * @param new_hash_table If true, this hash table is being constructed for * the first time and hash_table_memory will be cleared. If false, * reload a pre-existing hash table. * @param hash_table_memory_zeroed If new_hash_table is true, setting this to * true means that this HashTable will assume that hash_table_memory * has already been zeroed-out (any newly-allocated block or blob * memory from StorageManager is zeroed-out). If false, this HashTable * will explicitly zero-fill its memory as neccessary. This parameter * has no effect when new_hash_table is false. * @param adjust_hashes If true, the hash of a key should be modified by * applying AdjustHash() so that it does not collide with one of the * special values kEmptyHash or kPendingHash. If false, the hash is * used as-is. * @param use_scalar_literal_hash If true, the key is a single scalar literal * (non-composite) that it is safe to use the simplified hash function * TypedValue::getHashScalarLiteral() on. If false, the generic * TypedValue::getHash() method will be used. * @param preallocate_supported If true, this HashTable overrides * preallocateForBulkInsert() to allow bulk-allocation of resources * (i.e. buckets and variable-length key storage) in a single up-front * pass when bulk-inserting entries. If false, resources are allocated * on the fly for each entry. **/ HashTable(const std::vector<const Type*> &key_types, void *hash_table_memory, const std::size_t hash_table_memory_size, const bool new_hash_table, const bool hash_table_memory_zeroed, const bool adjust_hashes, const bool use_scalar_literal_hash, const bool preallocate_supported) : key_types_(key_types), scalar_key_inline_(true), key_inline_(nullptr), adjust_hashes_(adjust_hashes), use_scalar_literal_hash_(use_scalar_literal_hash), preallocate_supported_(preallocate_supported), storage_manager_(nullptr), hash_table_memory_(hash_table_memory), hash_table_memory_size_(hash_table_memory_size) { DEBUG_ASSERT(!resizable); } // Adjust 'hash' so that it is not exactly equal to either of the special // values kEmptyHash or kPendingHash. inline constexpr static std::size_t AdjustHash(const std::size_t hash) { return hash + (hash == kEmptyHash) - (hash == kPendingHash); } // Set information about which key components are stored inline. This usually // comes from a HashTableKeyManager, and is set by the constructor of a // subclass of HashTable. inline void setKeyInline(const std::vector<bool> *key_inline) { scalar_key_inline_ = key_inline->front(); key_inline_ = key_inline; } // Generate a hash for a composite key by hashing each component of 'key' and // mixing their bits with CombineHashes(). inline std::size_t hashCompositeKey(const std::vector<TypedValue> &key) const; // If 'force_key_copy' is true and some part of a composite key is // variable-length, calculate the total number of bytes for variable-length // key components that need to be copied. Otherwise, return 0 to indicate // that no variable-length copy is required. inline std::size_t calculateVariableLengthCompositeKeyCopySize( const std::vector<TypedValue> &key) const; // Helpers for put. If this HashTable is resizable, 'resize_shared_mutex_' // should be locked in shared mode before calling either of these methods. virtual HashTablePutResult putInternal(const TypedValue &key, const std::size_t variable_key_size, const ValueT &value, HashTablePreallocationState *prealloc_state) = 0; virtual HashTablePutResult putCompositeKeyInternal(const std::vector<TypedValue> &key, const std::size_t variable_key_size, const ValueT &value, HashTablePreallocationState *prealloc_state) = 0; // Helpers for upsert. Both return a pointer to the value corresponding to // 'key'. If this HashTable is resizable, 'resize_shared_mutex_' should be // locked in shared mode while calling and using the returned pointer. May // return NULL if there is not enough space to insert a new key, in which // case a resizable HashTable should release the 'resize_shared_mutex_' and // call resize(), then try again. virtual ValueT* upsertInternal(const TypedValue &key, const std::size_t variable_key_size, const ValueT &initial_value) = 0; virtual ValueT* upsertCompositeKeyInternal(const std::vector<TypedValue> &key, const std::size_t variable_key_size, const ValueT &initial_value) = 0; // Helpers for forEach. Each return true on success, false if no more entries // exist to iterate over. After a successful call, '*key' is overwritten with // the key of the next entry, '*value' points to the associated value, and // '*entry_num' is incremented to the next (implementation defined) entry to // check ('*entry_num' should initially be set to zero). virtual bool getNextEntry(TypedValue *key, const ValueT **value, std::size_t *entry_num) const = 0; virtual bool getNextEntryCompositeKey(std::vector<TypedValue> *key, const ValueT **value, std::size_t *entry_num) const = 0; // Helpers for getAllFromValueAccessor. Each return true on success, false if // no more entries exist for the specified key. After a successful call, // '*value' points to the associated value, and '*entry_num' is incremented // to the next (implementation defined) entry to check ('*entry_num' should // initially be set to zero). virtual bool getNextEntryForKey(const TypedValue &key, const std::size_t hash_code, const ValueT **value, std::size_t *entry_num) const = 0; virtual bool getNextEntryForCompositeKey(const std::vector<TypedValue> &key, const std::size_t hash_code, const ValueT **value, std::size_t *entry_num) const = 0; // Return true if key exists in the hash table. virtual bool hasKey(const TypedValue &key) const = 0; virtual bool hasCompositeKey(const std::vector<TypedValue> &key) const = 0; // For a resizable HashTable, grow to accomodate more entries. If // 'extra_buckets' is not zero, it may serve as a "hint" to implementations // that at least the requested number of extra buckets are required when // resizing (mainly used in putValueAccessor() and // putValueAccessorCompositeKey() when 'preallocate_supported_' is true). // Implementations are free to ignore 'extra_buckets'. If // 'extra_variable_storage' is not zero, implementations will attempt to // allocate at least enough additional variable-key storage space to // accomodate the number of bytes specified. 'retry_num' is intended ONLY for // when resize() recursively calls itself and should not be set to nonzero by // any other caller. virtual void resize(const std::size_t extra_buckets, const std::size_t extra_variable_storage, const std::size_t retry_num = 0) = 0; // In the case where 'allow_duplicate_keys' is true, it is possible to // pre-calculate the number of key-value entries and the amount of // variable-length key storage that will be needed to insert all the // entries from a ValueAccessor in putValueAccessor() or // putValueAccessorCompositeKey() before actually inserting anything. Some // HashTable implemetations (notably SeparateChainingHashTable) can achieve // better performance by ammortizing the cost of allocating certain resources // (buckets and variable-length key storage) in one up-front allocation. This // method is intended to support that. Returns true and fills in // '*prealloc_state' if pre-allocation was successful. Returns false if a // resize() is needed. virtual bool preallocateForBulkInsert(const std::size_t total_entries, const std::size_t total_variable_key_size, HashTablePreallocationState *prealloc_state) { FATAL_ERROR("Called HashTable::preallocateForBulkInsert() on a HashTable " "implementation that does not support preallocation."); } // Type(s) of keys. const std::vector<const Type*> key_types_; // Information about whether key components are stored inline or in a // separate variable-length storage region. This is usually determined by a // HashTableKeyManager and set by calling setKeyInline(). bool scalar_key_inline_; const std::vector<bool> *key_inline_; // Whether hashes should be adjusted by AdjustHash() before being used. const bool adjust_hashes_; // Whether it is safe to use the simplified TypedValue::getHashScalarLiteral() // method instead of the generic TypedValue::getHash() method. const bool use_scalar_literal_hash_; // Whether preallocateForBulkInsert() is supported by this HashTable. const bool preallocate_supported_; // Used only when resizable is true: StorageManager *storage_manager_; MutableBlobReference blob_; // Locked in shared mode for most operations, exclusive mode during resize. // Not locked at all for non-resizable HashTables. alignas(kCacheLineBytes) SpinSharedMutex<true> resize_shared_mutex_; // Used only when resizable is false: void *hash_table_memory_; const std::size_t hash_table_memory_size_; private: // Assign '*key_vector' with the attribute values specified by 'key_attr_ids' // at the current position of 'accessor'. If 'check_for_null_keys' is true, // stops and returns true if any of the values is null, otherwise returns // false. template <typename ValueAccessorT> inline static bool GetCompositeKeyFromValueAccessor( const ValueAccessorT &accessor, const std::vector<attribute_id> &key_attr_ids, const bool check_for_null_keys, std::vector<TypedValue> *key_vector) { for (std::vector<attribute_id>::size_type key_idx = 0; key_idx < key_attr_ids.size(); ++key_idx) { (*key_vector)[key_idx] = accessor.getTypedValue(key_attr_ids[key_idx]); if (check_for_null_keys && (*key_vector)[key_idx].isNull()) { return true; } } return false; } // If run_if_match_found is true, apply the functor to each key if a match is // found; otherwise, apply the functor if no match is found. template <bool run_if_match_found, typename FunctorT> void runOverKeysFromValueAccessor(ValueAccessor *accessor, const attribute_id key_attr_id, const bool check_for_null_keys, FunctorT *functor) const; template <bool run_if_match_found, typename FunctorT> void runOverKeysFromValueAccessorCompositeKey( ValueAccessor *accessor, const std::vector<attribute_id> &key_attr_ids, const bool check_for_null_keys, FunctorT *functor) const; // Method containing the actual logic implementing getAllFromValueAccessor(). // Has extra template parameters that control behavior to avoid some // inner-loop branching. template <typename FunctorT, bool check_for_null_keys, bool adjust_hashes_template, bool use_scalar_literal_hash_template> void getAllFromValueAccessorImpl(ValueAccessor *accessor, const attribute_id key_attr_id, FunctorT *functor) const; DISALLOW_COPY_AND_ASSIGN(HashTable); }; /** * @brief An instantiation of the HashTable template for use in hash joins. * @note This assumes that duplicate keys are allowed. If it is known a priori * that there are no duplicate keys (e.g. because of primary key or * unique constraints on a table), then using a version of HashTable with * allow_duplicate_keys = false can be more efficient. * @warning This has force_key_copy = false. Therefore, any blocks which keys * are inserted from should remain memory-resident and not be * reorganized or rebuilt for the lifetime of this JoinHashTable. If * that is not possible, then a HashTable with force_key_copy = true * must be used instead. **/ typedef HashTable<TupleReference, true, false, false, true> JoinHashTable; template <template <typename, bool, bool, bool, bool> class HashTableImpl> using JoinHashTableImpl = HashTableImpl<TupleReference, true, false, false, true>; /** * @brief An instantiation of the HashTable template for use in aggregations. * @note This has force_key_copy = true, so that we don't have dangling pointers * to blocks that are evicted. **/ template <typename ValueT> using AggregationStateHashTable = HashTable<ValueT, true, false, true, false>; template <template <typename, bool, bool, bool, bool> class HashTableImpl, typename ValueT> using AggregationStateHashTableImpl = HashTableImpl<ValueT, true, false, true, false>; /** @} */ // ---------------------------------------------------------------------------- // Implementations of template class methods follow. template <typename ValueT, bool resizable, bool serializable, bool force_key_copy, bool allow_duplicate_keys> HashTablePutResult HashTable<ValueT, resizable, serializable, force_key_copy, allow_duplicate_keys> ::put(const TypedValue &key, const ValueT &value) { const std::size_t variable_size = (force_key_copy && !scalar_key_inline_) ? key.getDataSize() : 0; if (resizable) { HashTablePutResult result = HashTablePutResult::kOutOfSpace; while (result == HashTablePutResult::kOutOfSpace) { { SpinSharedMutexSharedLock<true> lock(resize_shared_mutex_); result = putInternal(key, variable_size, value, nullptr); } if (result == HashTablePutResult::kOutOfSpace) { resize(0, variable_size); } } return result; } else { return putInternal(key, variable_size, value, nullptr); } } template <typename ValueT, bool resizable, bool serializable, bool force_key_copy, bool allow_duplicate_keys> HashTablePutResult HashTable<ValueT, resizable, serializable, force_key_copy, allow_duplicate_keys> ::putCompositeKey(const std::vector<TypedValue> &key, const ValueT &value) { const std::size_t variable_size = calculateVariableLengthCompositeKeyCopySize(key); if (resizable) { HashTablePutResult result = HashTablePutResult::kOutOfSpace; while (result == HashTablePutResult::kOutOfSpace) { { SpinSharedMutexSharedLock<true> lock(resize_shared_mutex_); result = putCompositeKeyInternal(key, variable_size, value, nullptr); } if (result == HashTablePutResult::kOutOfSpace) { resize(0, variable_size); } } return result; } else { return putCompositeKeyInternal(key, variable_size, value, nullptr); } } template <typename ValueT, bool resizable, bool serializable, bool force_key_copy, bool allow_duplicate_keys> template <typename FunctorT> HashTablePutResult HashTable<ValueT, resizable, serializable, force_key_copy, allow_duplicate_keys> ::putValueAccessor(ValueAccessor *accessor, const attribute_id key_attr_id, const bool check_for_null_keys, FunctorT *functor) { HashTablePutResult result = HashTablePutResult::kOutOfSpace; std::size_t variable_size; HashTablePreallocationState prealloc_state; bool using_prealloc = allow_duplicate_keys && preallocate_supported_; return InvokeOnAnyValueAccessor( accessor, [&](auto *accessor) -> HashTablePutResult { // NOLINT(build/c++11) if (using_prealloc) { std::size_t total_entries = 0; std::size_t total_variable_key_size = 0; if (check_for_null_keys || (force_key_copy && !scalar_key_inline_)) { // If we need to filter out nulls OR make variable copies, make a // prepass over the ValueAccessor. while (accessor->next()) { TypedValue key = accessor->getTypedValue(key_attr_id); if (check_for_null_keys && key.isNull()) { continue; } ++total_entries; total_variable_key_size += (force_key_copy && !scalar_key_inline_) ? key.getDataSize() : 0; } accessor->beginIteration(); } else { total_entries = accessor->getNumTuples(); } if (resizable) { bool prealloc_succeeded = false; while (!prealloc_succeeded) { { SpinSharedMutexSharedLock<true> lock(resize_shared_mutex_); prealloc_succeeded = this->preallocateForBulkInsert(total_entries, total_variable_key_size, &prealloc_state); } if (!prealloc_succeeded) { this->resize(total_entries, total_variable_key_size); } } } else { using_prealloc = this->preallocateForBulkInsert(total_entries, total_variable_key_size, &prealloc_state); } } if (resizable) { while (result == HashTablePutResult::kOutOfSpace) { { result = HashTablePutResult::kOK; SpinSharedMutexSharedLock<true> lock(resize_shared_mutex_); while (accessor->next()) { TypedValue key = accessor->getTypedValue(key_attr_id); if (check_for_null_keys && key.isNull()) { continue; } variable_size = (force_key_copy && !scalar_key_inline_) ? key.getDataSize() : 0; result = this->putInternal(key, variable_size, (*functor)(*accessor), using_prealloc ? &prealloc_state : nullptr); if (result == HashTablePutResult::kDuplicateKey) { DEBUG_ASSERT(!using_prealloc); return result; } else if (result == HashTablePutResult::kOutOfSpace) { DEBUG_ASSERT(!using_prealloc); break; } } } if (result == HashTablePutResult::kOutOfSpace) { this->resize(0, variable_size); accessor->previous(); } } } else { while (accessor->next()) { TypedValue key = accessor->getTypedValue(key_attr_id); if (check_for_null_keys && key.isNull()) { continue; } variable_size = (force_key_copy && !scalar_key_inline_) ? key.getDataSize() : 0; result = this->putInternal(key, variable_size, (*functor)(*accessor), using_prealloc ? &prealloc_state : nullptr); if (result != HashTablePutResult::kOK) { return result; } } } return HashTablePutResult::kOK; }); } template <typename ValueT, bool resizable, bool serializable, bool force_key_copy, bool allow_duplicate_keys> template <typename FunctorT> HashTablePutResult HashTable<ValueT, resizable, serializable, force_key_copy, allow_duplicate_keys> ::putValueAccessorCompositeKey(ValueAccessor *accessor, const std::vector<attribute_id> &key_attr_ids, const bool check_for_null_keys, FunctorT *functor) { DEBUG_ASSERT(key_types_.size() == key_attr_ids.size()); HashTablePutResult result = HashTablePutResult::kOutOfSpace; std::size_t variable_size; HashTablePreallocationState prealloc_state; bool using_prealloc = allow_duplicate_keys && preallocate_supported_; std::vector<TypedValue> key_vector; key_vector.resize(key_attr_ids.size()); return InvokeOnAnyValueAccessor( accessor, [&](auto *accessor) -> HashTablePutResult { // NOLINT(build/c++11) if (using_prealloc) { std::size_t total_entries = 0; std::size_t total_variable_key_size = 0; if (check_for_null_keys || force_key_copy) { // If we need to filter out nulls OR make variable copies, make a // prepass over the ValueAccessor. while (accessor->next()) { if (this->GetCompositeKeyFromValueAccessor(*accessor, key_attr_ids, check_for_null_keys, &key_vector)) { continue; } ++total_entries; total_variable_key_size += this->calculateVariableLengthCompositeKeyCopySize(key_vector); } accessor->beginIteration(); } else { total_entries = accessor->getNumTuples(); } if (resizable) { bool prealloc_succeeded = false; while (!prealloc_succeeded) { { SpinSharedMutexSharedLock<true> lock(resize_shared_mutex_); prealloc_succeeded = this->preallocateForBulkInsert(total_entries, total_variable_key_size, &prealloc_state); } if (!prealloc_succeeded) { this->resize(total_entries, total_variable_key_size); } } } else { using_prealloc = this->preallocateForBulkInsert(total_entries, total_variable_key_size, &prealloc_state); } } if (resizable) { while (result == HashTablePutResult::kOutOfSpace) { { result = HashTablePutResult::kOK; SpinSharedMutexSharedLock<true> lock(resize_shared_mutex_); while (accessor->next()) { if (this->GetCompositeKeyFromValueAccessor(*accessor, key_attr_ids, check_for_null_keys, &key_vector)) { continue; } variable_size = this->calculateVariableLengthCompositeKeyCopySize(key_vector); result = this->putCompositeKeyInternal(key_vector, variable_size, (*functor)(*accessor), using_prealloc ? &prealloc_state : nullptr); if (result == HashTablePutResult::kDuplicateKey) { DEBUG_ASSERT(!using_prealloc); return result; } else if (result == HashTablePutResult::kOutOfSpace) { DEBUG_ASSERT(!using_prealloc); break; } } } if (result == HashTablePutResult::kOutOfSpace) { this->resize(0, variable_size); accessor->previous(); } } } else { while (accessor->next()) { if (this->GetCompositeKeyFromValueAccessor(*accessor, key_attr_ids, check_for_null_keys, &key_vector)) { continue; } variable_size = this->calculateVariableLengthCompositeKeyCopySize(key_vector); result = this->putCompositeKeyInternal(key_vector, variable_size, (*functor)(*accessor), using_prealloc ? &prealloc_state : nullptr); if (result != HashTablePutResult::kOK) { return result; } } } return HashTablePutResult::kOK; }); } template <typename ValueT, bool resizable, bool serializable, bool force_key_copy, bool allow_duplicate_keys> template <typename FunctorT> bool HashTable<ValueT, resizable, serializable, force_key_copy, allow_duplicate_keys> ::upsert(const TypedValue &key, const ValueT &initial_value, FunctorT *functor) { DEBUG_ASSERT(!allow_duplicate_keys); const std::size_t variable_size = (force_key_copy && !scalar_key_inline_) ? key.getDataSize() : 0; if (resizable) { for (;;) { { SpinSharedMutexSharedLock<true> resize_lock(resize_shared_mutex_); ValueT *value = upsertInternal(key, variable_size, initial_value); if (value != nullptr) { (*functor)(value); return true; } } resize(0, force_key_copy && !scalar_key_inline_ ? key.getDataSize() : 0); } } else { ValueT *value = upsertInternal(key, variable_size, initial_value); if (value == nullptr) { return false; } else { (*functor)(value); return true; } } } template <typename ValueT, bool resizable, bool serializable, bool force_key_copy, bool allow_duplicate_keys> template <typename FunctorT> bool HashTable<ValueT, resizable, serializable, force_key_copy, allow_duplicate_keys> ::upsertCompositeKey(const std::vector<TypedValue> &key, const ValueT &initial_value, FunctorT *functor) { DEBUG_ASSERT(!allow_duplicate_keys); const std::size_t variable_size = calculateVariableLengthCompositeKeyCopySize(key); if (resizable) { for (;;) { { SpinSharedMutexSharedLock<true> resize_lock(resize_shared_mutex_); ValueT *value = upsertCompositeKeyInternal(key, variable_size, initial_value); if (value != nullptr) { (*functor)(value); return true; } } resize(0, variable_size); } } else { ValueT *value = upsertCompositeKeyInternal(key, variable_size, initial_value); if (value == nullptr) { return false; } else { (*functor)(value); return true; } } } template <typename ValueT, bool resizable, bool serializable, bool force_key_copy, bool allow_duplicate_keys> template <typename FunctorT> bool HashTable<ValueT, resizable, serializable, force_key_copy, allow_duplicate_keys> ::upsertValueAccessor(ValueAccessor *accessor, const attribute_id key_attr_id, const bool check_for_null_keys, const ValueT &initial_value, FunctorT *functor) { DEBUG_ASSERT(!allow_duplicate_keys); std::size_t variable_size; return InvokeOnAnyValueAccessor( accessor, [&](auto *accessor) -> bool { // NOLINT(build/c++11) if (resizable) { bool continuing = true; while (continuing) { { continuing = false; SpinSharedMutexSharedLock<true> lock(resize_shared_mutex_); while (accessor->next()) { TypedValue key = accessor->getTypedValue(key_attr_id); if (check_for_null_keys && key.isNull()) { continue; } variable_size = (force_key_copy && !scalar_key_inline_) ? key.getDataSize() : 0; ValueT *value = this->upsertInternal(key, variable_size, initial_value); if (value == nullptr) { continuing = true; break; } else { (*functor)(*accessor, value); } } } if (continuing) { this->resize(0, variable_size); accessor->previous(); } } } else { while (accessor->next()) { TypedValue key = accessor->getTypedValue(key_attr_id); if (check_for_null_keys && key.isNull()) { continue; } variable_size = (force_key_copy && !scalar_key_inline_) ? key.getDataSize() : 0; ValueT *value = this->upsertInternal(key, variable_size, initial_value); if (value == nullptr) { return false; } else { (*functor)(*accessor, value); } } } return true; }); } template <typename ValueT, bool resizable, bool serializable, bool force_key_copy, bool allow_duplicate_keys> template <typename FunctorT> bool HashTable<ValueT, resizable, serializable, force_key_copy, allow_duplicate_keys> ::upsertValueAccessorCompositeKey(ValueAccessor *accessor, const std::vector<attribute_id> &key_attr_ids, const bool check_for_null_keys, const ValueT &initial_value, FunctorT *functor) { DEBUG_ASSERT(!allow_duplicate_keys); std::size_t variable_size; std::vector<TypedValue> key_vector; key_vector.resize(key_attr_ids.size()); return InvokeOnAnyValueAccessor( accessor, [&](auto *accessor) -> bool { // NOLINT(build/c++11) if (resizable) { bool continuing = true; while (continuing) { { continuing = false; SpinSharedMutexSharedLock<true> lock(resize_shared_mutex_); while (accessor->next()) { if (this->GetCompositeKeyFromValueAccessor(*accessor, key_attr_ids, check_for_null_keys, &key_vector)) { continue; } variable_size = this->calculateVariableLengthCompositeKeyCopySize(key_vector); ValueT *value = this->upsertCompositeKeyInternal(key_vector, variable_size, initial_value); if (value == nullptr) { continuing = true; break; } else { (*functor)(*accessor, value); } } } if (continuing) { this->resize(0, variable_size); accessor->previous(); } } } else { while (accessor->next()) { if (this->GetCompositeKeyFromValueAccessor(*accessor, key_attr_ids, check_for_null_keys, &key_vector)) { continue; } variable_size = this->calculateVariableLengthCompositeKeyCopySize(key_vector); ValueT *value = this->upsertCompositeKeyInternal(key_vector, variable_size, initial_value); if (value == nullptr) { return false; } else { (*functor)(*accessor, value); } } } return true; }); } template <typename ValueT, bool resizable, bool serializable, bool force_key_copy, bool allow_duplicate_keys> template <typename FunctorT> void HashTable<ValueT, resizable, serializable, force_key_copy, allow_duplicate_keys> ::getAllFromValueAccessor(ValueAccessor *accessor, const attribute_id key_attr_id, const bool check_for_null_keys, FunctorT *functor) const { // Pass through to method with additional template parameters for less // branching in inner loop. if (check_for_null_keys) { if (adjust_hashes_) { if (use_scalar_literal_hash_) { getAllFromValueAccessorImpl<FunctorT, true, true, true>( accessor, key_attr_id, functor); } else { getAllFromValueAccessorImpl<FunctorT, true, true, false>( accessor, key_attr_id, functor); } } else { if (use_scalar_literal_hash_) { getAllFromValueAccessorImpl<FunctorT, true, false, true>( accessor, key_attr_id, functor); } else { getAllFromValueAccessorImpl<FunctorT, true, false, false>( accessor, key_attr_id, functor); } } } else { if (adjust_hashes_) { if (use_scalar_literal_hash_) { getAllFromValueAccessorImpl<FunctorT, false, true, true>( accessor, key_attr_id, functor); } else { getAllFromValueAccessorImpl<FunctorT, false, true, false>( accessor, key_attr_id, functor); } } else { if (use_scalar_literal_hash_) { getAllFromValueAccessorImpl<FunctorT, false, false, true>( accessor, key_attr_id, functor); } else { getAllFromValueAccessorImpl<FunctorT, false, false, false>( accessor, key_attr_id, functor); } } } } template <typename ValueT, bool resizable, bool serializable, bool force_key_copy, bool allow_duplicate_keys> template <typename FunctorT> void HashTable<ValueT, resizable, serializable, force_key_copy, allow_duplicate_keys> ::getAllFromValueAccessorCompositeKey(ValueAccessor *accessor, const std::vector<attribute_id> &key_attr_ids, const bool check_for_null_keys, FunctorT *functor) const { DEBUG_ASSERT(key_types_.size() == key_attr_ids.size()); std::vector<TypedValue> key_vector; key_vector.resize(key_attr_ids.size()); InvokeOnAnyValueAccessor( accessor, [&](auto *accessor) -> void { // NOLINT(build/c++11) while (accessor->next()) { bool null_key = false; for (std::vector<attribute_id>::size_type key_idx = 0; key_idx < key_types_.size(); ++key_idx) { key_vector[key_idx] = accessor->getTypedValue(key_attr_ids[key_idx]); if (check_for_null_keys && key_vector[key_idx].isNull()) { null_key = true; break; } } if (null_key) { continue; } const std::size_t hash_code = adjust_hashes_ ? this->AdjustHash(this->hashCompositeKey(key_vector)) : this->hashCompositeKey(key_vector); std::size_t entry_num = 0; const ValueT *value; while (this->getNextEntryForCompositeKey(key_vector, hash_code, &value, &entry_num)) { (*functor)(*accessor, *value); if (!allow_duplicate_keys) { break; } } } }); } template <typename ValueT, bool resizable, bool serializable, bool force_key_copy, bool allow_duplicate_keys> template <typename FunctorT> void HashTable<ValueT, resizable, serializable, force_key_copy, allow_duplicate_keys>:: getAllFromValueAccessorWithExtraWorkForFirstMatch( ValueAccessor *accessor, const attribute_id key_attr_id, const bool check_for_null_keys, FunctorT *functor) const { InvokeOnAnyValueAccessor( accessor, [&](auto *accessor) -> void { // NOLINT(build/c++11) while (accessor->next()) { TypedValue key = accessor->getTypedValue(key_attr_id); if (check_for_null_keys && key.isNull()) { continue; } const std::size_t hash_code = adjust_hashes_ ? HashTable<ValueT, resizable, serializable, force_key_copy, allow_duplicate_keys> ::AdjustHash(key.getHash()) : key.getHash(); std::size_t entry_num = 0; const ValueT *value; if (this->getNextEntryForKey(key, hash_code, &value, &entry_num)) { functor->recordMatch(*accessor); (*functor)(*accessor, *value); if (!allow_duplicate_keys) { continue; } while (this->getNextEntryForKey(key, hash_code, &value, &entry_num)) { (*functor)(*accessor, *value); } } } }); // NOLINT(whitespace/parens) } template <typename ValueT, bool resizable, bool serializable, bool force_key_copy, bool allow_duplicate_keys> template <typename FunctorT> void HashTable<ValueT, resizable, serializable, force_key_copy, allow_duplicate_keys> ::getAllFromValueAccessorCompositeKeyWithExtraWorkForFirstMatch( ValueAccessor *accessor, const std::vector<attribute_id> &key_attr_ids, const bool check_for_null_keys, FunctorT *functor) const { DEBUG_ASSERT(key_types_.size() == key_attr_ids.size()); std::vector<TypedValue> key_vector; key_vector.resize(key_attr_ids.size()); InvokeOnAnyValueAccessor( accessor, [&](auto *accessor) -> void { // NOLINT(build/c++11) while (accessor->next()) { bool null_key = false; for (std::vector<attribute_id>::size_type key_idx = 0; key_idx < key_types_.size(); ++key_idx) { key_vector[key_idx] = accessor->getTypedValue(key_attr_ids[key_idx]); if (check_for_null_keys && key_vector[key_idx].isNull()) { null_key = true; break; } } if (null_key) { continue; } const std::size_t hash_code = adjust_hashes_ ? HashTable<ValueT, resizable, serializable, force_key_copy, allow_duplicate_keys> ::AdjustHash(this->hashCompositeKey(key_vector)) : this->hashCompositeKey(key_vector); std::size_t entry_num = 0; const ValueT *value; if (this->getNextEntryForCompositeKey(key_vector, hash_code, &value, &entry_num)) { functor->recordMatch(*accessor); (*functor)(*accessor, *value); if (!allow_duplicate_keys) { continue; } while (this->getNextEntryForCompositeKey(key_vector, hash_code, &value, &entry_num)) { (*functor)(*accessor, *value); } } } }); // NOLINT(whitespace/parens) } template <typename ValueT, bool resizable, bool serializable, bool force_key_copy, bool allow_duplicate_keys> template <bool run_if_match_found, typename FunctorT> void HashTable<ValueT, resizable, serializable, force_key_copy, allow_duplicate_keys>:: runOverKeysFromValueAccessor(ValueAccessor *accessor, const attribute_id key_attr_id, const bool check_for_null_keys, FunctorT *functor) const { InvokeOnAnyValueAccessor( accessor, [&](auto *accessor) -> void { // NOLINT(build/c++11) while (accessor->next()) { TypedValue key = accessor->getTypedValue(key_attr_id); if (check_for_null_keys && key.isNull()) { if (!run_if_match_found) { (*functor)(*accessor); continue; } } if (run_if_match_found) { if (this->hasKey(key)) { (*functor)(*accessor); } } else { if (!this->hasKey(key)) { (*functor)(*accessor); } } } }); // NOLINT(whitespace/parens) } template <typename ValueT, bool resizable, bool serializable, bool force_key_copy, bool allow_duplicate_keys> template <bool run_if_match_found, typename FunctorT> void HashTable<ValueT, resizable, serializable, force_key_copy, allow_duplicate_keys> ::runOverKeysFromValueAccessorCompositeKey(ValueAccessor *accessor, const std::vector<attribute_id> &key_attr_ids, const bool check_for_null_keys, FunctorT *functor) const { DEBUG_ASSERT(key_types_.size() == key_attr_ids.size()); std::vector<TypedValue> key_vector; key_vector.resize(key_attr_ids.size()); InvokeOnAnyValueAccessor( accessor, [&](auto *accessor) -> void { // NOLINT(build/c++11) while (accessor->next()) { bool null_key = false; for (std::vector<attribute_id>::size_type key_idx = 0; key_idx < key_types_.size(); ++key_idx) { key_vector[key_idx] = accessor->getTypedValue(key_attr_ids[key_idx]); if (check_for_null_keys && key_vector[key_idx].isNull()) { null_key = true; break; } } if (null_key) { if (!run_if_match_found) { (*functor)(*accessor); continue; } } if (run_if_match_found) { if (this->hasCompositeKey(key_vector)) { (*functor)(*accessor); } } else if (!this->hasCompositeKey(key_vector)) { (*functor)(*accessor); } } }); // NOLINT(whitespace/parens) } template <typename ValueT, bool resizable, bool serializable, bool force_key_copy, bool allow_duplicate_keys> template <typename FunctorT> std::size_t HashTable<ValueT, resizable, serializable, force_key_copy, allow_duplicate_keys> ::forEach(FunctorT *functor) const { std::size_t entries_visited = 0; std::size_t entry_num = 0; TypedValue key; const ValueT *value_ptr; while (getNextEntry(&key, &value_ptr, &entry_num)) { ++entries_visited; (*functor)(key, *value_ptr); } return entries_visited; } template <typename ValueT, bool resizable, bool serializable, bool force_key_copy, bool allow_duplicate_keys> template <typename FunctorT> std::size_t HashTable<ValueT, resizable, serializable, force_key_copy, allow_duplicate_keys> ::forEachCompositeKey(FunctorT *functor) const { std::size_t entries_visited = 0; std::size_t entry_num = 0; std::vector<TypedValue> key; const ValueT *value_ptr; while (getNextEntryCompositeKey(&key, &value_ptr, &entry_num)) { ++entries_visited; (*functor)(key, *value_ptr); key.clear(); } return entries_visited; } template <typename ValueT, bool resizable, bool serializable, bool force_key_copy, bool allow_duplicate_keys> inline std::size_t HashTable<ValueT, resizable, serializable, force_key_copy, allow_duplicate_keys> ::hashCompositeKey(const std::vector<TypedValue> &key) const { DEBUG_ASSERT(!key.empty()); DEBUG_ASSERT(key.size() == key_types_.size()); std::size_t hash = key.front().getHash(); for (std::vector<TypedValue>::const_iterator key_it = key.begin() + 1; key_it != key.end(); ++key_it) { hash = CombineHashes(hash, key_it->getHash()); } return hash; } template <typename ValueT, bool resizable, bool serializable, bool force_key_copy, bool allow_duplicate_keys> inline std::size_t HashTable<ValueT, resizable, serializable, force_key_copy, allow_duplicate_keys> ::calculateVariableLengthCompositeKeyCopySize(const std::vector<TypedValue> &key) const { DEBUG_ASSERT(!key.empty()); DEBUG_ASSERT(key.size() == key_types_.size()); if (force_key_copy) { std::size_t total = 0; for (std::vector<TypedValue>::size_type idx = 0; idx < key.size(); ++idx) { if (!(*key_inline_)[idx]) { total += key[idx].getDataSize(); } } return total; } else { return 0; } } template <typename ValueT, bool resizable, bool serializable, bool force_key_copy, bool allow_duplicate_keys> template <typename FunctorT, bool check_for_null_keys, bool adjust_hashes_template, bool use_scalar_literal_hash_template> void HashTable<ValueT, resizable, serializable, force_key_copy, allow_duplicate_keys> ::getAllFromValueAccessorImpl( ValueAccessor *accessor, const attribute_id key_attr_id, FunctorT *functor) const { InvokeOnAnyValueAccessor( accessor, [&](auto *accessor) -> void { // NOLINT(build/c++11) while (accessor->next()) { TypedValue key = accessor->getTypedValue(key_attr_id); if (check_for_null_keys && key.isNull()) { continue; } const std::size_t true_hash = use_scalar_literal_hash_template ? key.getHashScalarLiteral() : key.getHash(); const std::size_t adjusted_hash = adjust_hashes_template ? this->AdjustHash(true_hash) : true_hash; std::size_t entry_num = 0; const ValueT *value; while (this->getNextEntryForKey(key, adjusted_hash, &value, &entry_num)) { (*functor)(*accessor, *value); if (!allow_duplicate_keys) { break; } } } }); } } // namespace quickstep #endif // QUICKSTEP_STORAGE_HASH_TABLE_HPP_
46.212717
107
0.637046
Hacker0912
3bfb6b7ec394f0ef0dc85b8e9a756bb99ffaa161
417
hpp
C++
src/IComponent.hpp
bullno1/xveearr
4690cde72b7ec747d944daa919c3275744d75e25
[ "BSD-2-Clause" ]
null
null
null
src/IComponent.hpp
bullno1/xveearr
4690cde72b7ec747d944daa919c3275744d75e25
[ "BSD-2-Clause" ]
null
null
null
src/IComponent.hpp
bullno1/xveearr
4690cde72b7ec747d944daa919c3275744d75e25
[ "BSD-2-Clause" ]
null
null
null
#ifndef XVEEEARR_COMPONENT_HPP #define XVEEEARR_COMPONENT_HPP namespace xveearr { class IComponentBase { public: virtual void shutdown() = 0; virtual const char* getName() const = 0; }; template<typename T> class IComponent: public IComponentBase { public: virtual bool init(const T& initParam) = 0; }; template<> class IComponent<void>: public IComponentBase { public: virtual bool init() = 0; }; } #endif
13.451613
45
0.741007
bullno1
3bfdb4c4122bd1a2553ffe89582015c146b50fd0
17,759
cpp
C++
code/utils/ETools/encode.cpp
InNoHurryToCode/xray-162
fff9feb9ffb681b3c6ba1dc7c4534fe80006f87e
[ "Apache-2.0" ]
58
2016-11-20T19:14:35.000Z
2021-12-27T21:03:35.000Z
code/utils/ETools/encode.cpp
InNoHurryToCode/xray-162
fff9feb9ffb681b3c6ba1dc7c4534fe80006f87e
[ "Apache-2.0" ]
59
2016-09-10T10:44:20.000Z
2018-09-03T19:07:30.000Z
code/utils/ETools/encode.cpp
InNoHurryToCode/xray-162
fff9feb9ffb681b3c6ba1dc7c4534fe80006f87e
[ "Apache-2.0" ]
39
2017-02-05T13:35:37.000Z
2022-03-14T11:00:12.000Z
/* OggEnc ** ** This program is distributed under the GNU General Public License, version 2. ** A copy of this license is included with this source. ** ** Copyright 2000-2002, Michael Smith <msmith@xiph.org> ** ** Portions from Vorbize, (c) Kenneth Arnold <kcarnold-xiph@arnoldnet.net> ** and libvorbis examples, (c) Monty <monty@xiph.org> **/ #include "stdafx.h" #include <stdlib.h> #include <stdio.h> #include <math.h> #include <string.h> #include "platform.h" #include <vorbis/vorbisenc.h> #include "encode.h" //#include "i18n.h" #define READSIZE 1024 #define _(a) a int oe_write_page(ogg_page* page, FILE* fp); #define SETD(toset) \ do { \ if (sscanf(opts[i].val, "%lf", &dval) != 1) \ fprintf(stderr, "For option %s, couldn't read value %s as double\n", opts[i].arg, \ opts[i].val); \ else \ toset = dval; \ } while (0) #define SETL(toset) \ do { \ if (sscanf(opts[i].val, "%ld", &lval) != 1) \ fprintf(stderr, "For option %s, couldn't read value %s as integer\n", opts[i].arg, \ opts[i].val); \ else \ toset = lval; \ } while (0) static void set_advanced_encoder_options(adv_opt* opts, int count, vorbis_info* vi) { int manage = 0; struct ovectl_ratemanage2_arg ai; int i; double dval; long lval; vorbis_encode_ctl(vi, OV_ECTL_RATEMANAGE2_GET, &ai); for (i = 0; i < count; i++) { fprintf(stderr, _("Setting advanced encoder option \"%s\" to %s\n"), opts[i].arg, opts[i].val); if (!xr_strcmp(opts[i].arg, "bitrate_average_damping")) { SETD(ai.bitrate_average_damping); manage = 1; } else if (!xr_strcmp(opts[i].arg, "bitrate_average")) { SETL(ai.bitrate_average_kbps); manage = 1; } else if (!xr_strcmp(opts[i].arg, "bit_reservoir_bias")) { SETD(ai.bitrate_limit_reservoir_bias); manage = 1; } else if (!xr_strcmp(opts[i].arg, "bit_reservoir_bits")) { SETL(ai.bitrate_limit_reservoir_bits); manage = 1; } else if (!xr_strcmp(opts[i].arg, "bitrate_hard_min")) { SETL(ai.bitrate_limit_min_kbps); manage = 1; } else if (!xr_strcmp(opts[i].arg, "bitrate_hard_max")) { SETL(ai.bitrate_limit_max_kbps); manage = 1; } else if (!xr_strcmp(opts[i].arg, "impulse_noisetune")) { double val; SETD(val); vorbis_encode_ctl(vi, OV_ECTL_IBLOCK_SET, &val); } else if (!xr_strcmp(opts[i].arg, "lowpass_frequency")) { double _prev, _new; SETD(_new); vorbis_encode_ctl(vi, OV_ECTL_LOWPASS_GET, &_prev); vorbis_encode_ctl(vi, OV_ECTL_LOWPASS_SET, &_new); fprintf(stderr, _("Changed lowpass frequency from %f kHz to %f kHz\n"), _prev, _new); } else { fprintf(stderr, _("Unrecognised advanced option \"%s\"\n"), opts[i].arg); } } if (manage) { if (vorbis_encode_ctl(vi, OV_ECTL_RATEMANAGE2_SET, &ai)) { fprintf(stderr, "Failed to set advanced rate management parameters\n"); } } } int oe_encode(oe_enc_opt* opt) { ogg_stream_state os; ogg_page og; ogg_packet op; vorbis_dsp_state vd; vorbis_block vb; vorbis_info vi; long bitrate; long samplesdone = 0; int eos; long bytes_written = 0, packetsdone = 0; double time_elapsed; int ret = 0; TIMER* timer; if (opt->channels > 255) { fprintf( stderr, _("255 channels should be enough for anyone. (Sorry, vorbis doesn't support more)\n")); return 1; } /* get start time. */ timer = timer_start(); if (!opt->managed && (opt->min_bitrate >= 0 || opt->max_bitrate >= 0)) { fprintf(stderr, _("Requesting a minimum or maximum bitrate requires --managed\n")); return 1; } /* if we had no quality or bitrate spec at all from the user, use the default quality with no management --Monty 20020711 */ if (opt->bitrate < 0 && opt->min_bitrate < 0 && opt->max_bitrate < 0) { opt->quality_set = 1; } opt->start_encode(opt->infilename, opt->filename, opt->bitrate, opt->quality, opt->quality_set, opt->managed, opt->min_bitrate, opt->max_bitrate); /* Have vorbisenc choose a mode for us */ vorbis_info_init(&vi); if (opt->quality_set > 0) { if (vorbis_encode_setup_vbr(&vi, opt->channels, opt->rate, opt->quality)) { fprintf(stderr, _("Mode initialisation failed: invalid parameters for quality\n")); vorbis_info_clear(&vi); return 1; } /* do we have optional hard bitrate restrictions? */ if (opt->max_bitrate > 0 || opt->min_bitrate > 0) { struct ovectl_ratemanage2_arg ai; vorbis_encode_ctl(&vi, OV_ECTL_RATEMANAGE2_GET, &ai); /* libvorbis 1.1 (and current svn) doesn't actually fill this in, which looks like a bug. It'll then reject it when we call the SET version below. So, fill it in with the values that libvorbis would have used to fill in this structure if we were using the bitrate-oriented setup functions. Unfortunately, some of those values are dependent on the bitrate, and libvorbis has no way to get a nominal bitrate from a quality value. Well, except by doing a full setup... So, we do that. Also, note that this won't work correctly unless you have a very recent (2005/03/04 or later) version of libvorbis from svn). */ { vorbis_info vi2; vorbis_info_init(&vi2); vorbis_encode_setup_vbr(&vi2, opt->channels, opt->rate, opt->quality); vorbis_encode_setup_init(&vi2); bitrate = vi2.bitrate_nominal; vorbis_info_clear(&vi2); } ai.bitrate_average_kbps = bitrate / 1000; ai.bitrate_average_damping = 1.5; ai.bitrate_limit_reservoir_bits = bitrate * 2; ai.bitrate_limit_reservoir_bias = .1; /* And now the ones we actually wanted to set */ ai.bitrate_limit_min_kbps = opt->min_bitrate; ai.bitrate_limit_max_kbps = opt->max_bitrate; ai.management_active = 1; if (vorbis_encode_ctl(&vi, OV_ECTL_RATEMANAGE2_SET, &ai) == 0) fprintf(stderr, _("Set optional hard quality restrictions\n")); else { fprintf(stderr, _("Failed to set bitrate min/max in quality mode\n")); vorbis_info_clear(&vi); return 1; } } } else { if (vorbis_encode_setup_managed( &vi, opt->channels, opt->rate, opt->max_bitrate > 0 ? opt->max_bitrate * 1000 : -1, opt->bitrate * 1000, opt->min_bitrate > 0 ? opt->min_bitrate * 1000 : -1)) { fprintf(stderr, _("Mode initialisation failed: invalid parameters for bitrate\n")); vorbis_info_clear(&vi); return 1; } } if (opt->managed && opt->bitrate < 0) { struct ovectl_ratemanage2_arg ai; vorbis_encode_ctl(&vi, OV_ECTL_RATEMANAGE2_GET, &ai); ai.bitrate_average_kbps = -1; vorbis_encode_ctl(&vi, OV_ECTL_RATEMANAGE2_SET, &ai); } else if (!opt->managed) { /* Turn off management entirely (if it was turned on). */ vorbis_encode_ctl(&vi, OV_ECTL_RATEMANAGE2_SET, NULL); } set_advanced_encoder_options(opt->advopt, opt->advopt_count, &vi); vorbis_encode_setup_init(&vi); /* Now, set up the analysis engine, stream encoder, and other preparation before the encoding begins. */ vorbis_analysis_init(&vd, &vi); vorbis_block_init(&vd, &vb); ogg_stream_init(&os, opt->serialno); /* Now, build the three header packets and send through to the stream output stage (but defer actual file output until the main encode loop) */ { ogg_packet header_main; ogg_packet header_comments; ogg_packet header_codebooks; int result; /* Build the packets */ vorbis_analysis_headerout(&vd, opt->comments, &header_main, &header_comments, &header_codebooks); /* And stream them out */ ogg_stream_packetin(&os, &header_main); ogg_stream_packetin(&os, &header_comments); ogg_stream_packetin(&os, &header_codebooks); while ((result = ogg_stream_flush(&os, &og)) != 0) { if (!result) break; ret = oe_write_page(&og, opt->out); if (ret != og.header_len + og.body_len) { opt->error(_("Failed writing header to output stream\n")); ret = 1; goto cleanup; /* Bail and try to clean up stuff */ } } } eos = 0; /* Main encode loop - continue until end of file */ while (!eos) { float** buffer = vorbis_analysis_buffer(&vd, READSIZE); long samples_read = opt->read_samples(opt->readdata, buffer, READSIZE); if (samples_read == 0) /* Tell the library that we wrote 0 bytes - signalling the end */ vorbis_analysis_wrote(&vd, 0); else { samplesdone += samples_read; /* Call progress update every 40 pages */ if (packetsdone >= 40) { double time; packetsdone = 0; time = timer_time(timer); opt->progress_update(opt->filename, opt->total_samples_per_channel, samplesdone, time); } /* Tell the library how many samples (per channel) we wrote into the supplied buffer */ vorbis_analysis_wrote(&vd, samples_read); } /* While we can get enough data from the library to analyse, one block at a time... */ while (vorbis_analysis_blockout(&vd, &vb) == 1) { /* Do the main analysis, creating a packet */ vorbis_analysis(&vb, NULL); vorbis_bitrate_addblock(&vb); while (vorbis_bitrate_flushpacket(&vd, &op)) { /* Add packet to bitstream */ ogg_stream_packetin(&os, &op); packetsdone++; /* If we've gone over a page boundary, we can do actual output, so do so (for however many pages are available) */ while (!eos) { int result = ogg_stream_pageout(&os, &og); if (!result) break; ret = oe_write_page(&og, opt->out); if (ret != og.header_len + og.body_len) { opt->error(_("Failed writing data to output stream\n")); ret = 1; goto cleanup; /* Bail */ } else bytes_written += ret; if (ogg_page_eos(&og)) eos = 1; } } } } ret = 0; /* Success, set return value to 0 since other things reuse it * for nefarious purposes. */ /* Cleanup time */ cleanup: ogg_stream_clear(&os); vorbis_block_clear(&vb); vorbis_dsp_clear(&vd); vorbis_info_clear(&vi); time_elapsed = timer_time(timer); opt->end_encode(opt->filename, time_elapsed, opt->rate, samplesdone, bytes_written); timer_clear(timer); return ret; } void update_statistics_full(char* fn, long total, long done, double time) { static const char* spinner = "|/-\\"; static int spinpoint = 0; double remain_time; int minutes = 0, seconds = 0; remain_time = time / ((double)done / (double)total) - time; minutes = ((int)remain_time) / 60; seconds = (int)(remain_time - (double)((int)remain_time / 60) * 60); fprintf(stderr, "\r"); fprintf(stderr, _("\t[%5.1f%%] [%2dm%.2ds remaining] %c "), done * 100.0 / total, minutes, seconds, spinner[spinpoint++ % 4]); } void update_statistics_notime(char* fn, long total, long done, double time) { static const char* spinner = "|/-\\"; static int spinpoint = 0; fprintf(stderr, "\r"); fprintf(stderr, _("\tEncoding [%2dm%.2ds so far] %c "), ((int)time) / 60, (int)(time - (double)((int)time / 60) * 60), spinner[spinpoint++ % 4]); } int oe_write_page(ogg_page* page, FILE* fp) { int written; written = (int)fwrite(page->header, 1, page->header_len, fp); written += (int)fwrite(page->body, 1, page->body_len, fp); return written; } void final_statistics(char* fn, double time, int rate, long samples, long bytes) { double speed_ratio; if (fn) fprintf(stderr, _("\n\nDone encoding file \"%s\"\n"), fn); else fprintf(stderr, _("\n\nDone encoding.\n")); speed_ratio = (double)samples / (double)rate / time; fprintf(stderr, _("\n\tFile length: %dm %04.1fs\n"), (int)(samples / rate / 60), samples / rate - samples / rate / 60 * 60); fprintf(stderr, _("\tElapsed time: %dm %04.1fs\n"), (int)(time / 60), time - iFloor((float)time / 60) * 60); fprintf(stderr, _("\tRate: %.4f\n"), speed_ratio); fprintf(stderr, _("\tAverage bitrate: %.1f kb/s\n\n"), 8. / 1000. * ((double)bytes / ((double)samples / (double)rate))); } void final_statistics_null(char* fn, double time, int rate, long samples, long bytes) { /* Don't do anything, this is just a placeholder function for quiet mode */ } void update_statistics_null(char* fn, long total, long done, double time) { /* So is this */ } void encode_error(const char* errmsg) { fprintf(stderr, "\n%s\n", errmsg); } static void print_brconstraints(int min, int max) { if (min > 0 && max > 0) fprintf(stderr, "(min %d kbps, max %d kbps)", min, max); else if (min > 0) fprintf(stderr, "(min %d kbps, no max)", min); else if (max > 0) fprintf(stderr, "(no min, max %d kbps)", max); else fprintf(stderr, "(no min or max)"); } void start_encode_full(char* fn, char* outfn, int bitrate, float quality, int qset, int managed, int min, int max) { if (bitrate > 0) { if (managed > 0) { fprintf(stderr, _("Encoding %s%s%s to \n " "%s%s%s \nat average bitrate %d kbps "), fn ? "\"" : "", fn ? fn : _("standard input"), fn ? "\"" : "", outfn ? "\"" : "", outfn ? outfn : _("standard output"), outfn ? "\"" : "", bitrate); print_brconstraints(min, max); fprintf(stderr, ", \nusing full bitrate management engine\n"); } else { fprintf(stderr, _("Encoding %s%s%s to \n %s%s%s \nat approximate bitrate %d kbps (VBR " "encoding enabled)\n"), fn ? "\"" : "", fn ? fn : _("standard input"), fn ? "\"" : "", outfn ? "\"" : "", outfn ? outfn : _("standard output"), outfn ? "\"" : "", bitrate); } } else { if (qset > 0) { if (managed > 0) { fprintf(stderr, _("Encoding %s%s%s to \n %s%s%s \nat quality level %2.2f using " "constrained VBR "), fn ? "\"" : "", fn ? fn : _("standard input"), fn ? "\"" : "", outfn ? "\"" : "", outfn ? outfn : _("standard output"), outfn ? "\"" : "", quality * 10); print_brconstraints(min, max); fprintf(stderr, "\n"); } else { fprintf(stderr, _("Encoding %s%s%s to \n %s%s%s \nat quality %2.2f\n"), fn ? "\"" : "", fn ? fn : _("standard input"), fn ? "\"" : "", outfn ? "\"" : "", outfn ? outfn : _("standard output"), outfn ? "\"" : "", quality * 10); } } else { fprintf(stderr, _("Encoding %s%s%s to \n %s%s%s \nusing bitrate management "), fn ? "\"" : "", fn ? fn : _("standard input"), fn ? "\"" : "", outfn ? "\"" : "", outfn ? outfn : _("standard output"), outfn ? "\"" : ""); print_brconstraints(min, max); fprintf(stderr, "\n"); } } } void start_encode_null(char* fn, char* outfn, int bitrate, float quality, int qset, int managed, int min, int max) {}
38.439394
99
0.51861
InNoHurryToCode
3bfea285d3aeee7f16c804c2402afec08b75b330
2,740
hpp
C++
libs/fnd/variant/include/bksge/fnd/variant/detail/move_assign.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
4
2018-06-10T13:35:32.000Z
2021-06-03T14:27:41.000Z
libs/fnd/variant/include/bksge/fnd/variant/detail/move_assign.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
566
2017-01-31T05:36:09.000Z
2022-02-09T05:04:37.000Z
libs/fnd/variant/include/bksge/fnd/variant/detail/move_assign.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
1
2018-07-05T04:40:53.000Z
2018-07-05T04:40:53.000Z
/** * @file move_assign.hpp * * @brief MoveAssign の定義 * * @author myoukaku */ #ifndef BKSGE_FND_VARIANT_DETAIL_MOVE_ASSIGN_HPP #define BKSGE_FND_VARIANT_DETAIL_MOVE_ASSIGN_HPP #include <bksge/fnd/variant/variant_npos.hpp> #include <bksge/fnd/variant/detail/copy_assign.hpp> #include <bksge/fnd/variant/detail/raw_idx_visit.hpp> #include <bksge/fnd/variant/detail/variant_access.hpp> #include <bksge/fnd/variant/detail/variant_traits.hpp> #include <bksge/fnd/type_traits/bool_constant.hpp> #include <utility> namespace bksge { namespace variant_detail { template <bool, typename... Types> struct MoveAssignBase; template <bool B, typename... Types> struct MoveAssignVisitor { MoveAssignBase<B, Types...>* m_this; template <typename RhsMem, typename RhsIndex> BKSGE_CXX14_CONSTEXPR void impl(RhsMem&& rhs_mem, RhsIndex rhs_index, bksge::true_type) { if (m_this->m_index == rhs_index) { variant_detail::variant_access::get_impl<rhs_index>(*m_this) = std::move(rhs_mem); } else { variant_detail::variant_access::variant_cast<Types...>(*m_this).template emplace<rhs_index>(std::move(rhs_mem)); } } template <typename RhsMem, typename RhsIndex> BKSGE_CXX14_CONSTEXPR void impl(RhsMem&& /*rhs_mem*/, RhsIndex /*rhs_index*/, bksge::false_type) { m_this->reset(); } template <typename RhsMem, typename RhsIndex> BKSGE_CXX14_CONSTEXPR void operator()(RhsMem&& rhs_mem, RhsIndex rhs_index) { impl(std::forward<RhsMem>(rhs_mem), rhs_index, bksge::bool_constant<rhs_index != bksge::variant_npos>{}); } }; template <typename... Types> struct MoveAssignBase<false, Types...> : public variant_detail::CopyAssignAlias<Types...> { using Base = variant_detail::CopyAssignAlias<Types...>; using Base::Base; MoveAssignBase& operator=(MoveAssignBase&& rhs) noexcept(variant_detail::VariantTraits<Types...>::s_nothrow_move_assign) { variant_detail::raw_idx_visit( MoveAssignVisitor<false, Types...>{this}, variant_detail::variant_access::variant_cast<Types...>(rhs)); return *this; } MoveAssignBase(MoveAssignBase const&) = default; MoveAssignBase(MoveAssignBase&&) = default; MoveAssignBase& operator=(MoveAssignBase const&) = default; }; template <typename... Types> struct MoveAssignBase<true, Types...> : public variant_detail::CopyAssignAlias<Types...> { using Base = variant_detail::CopyAssignAlias<Types...>; using Base::Base; }; template <typename... Types> using MoveAssignAlias = MoveAssignBase<variant_detail::VariantTraits<Types...>::s_trivial_move_assign, Types...>; } // namespace variant_detail } // namespace bksge #endif // BKSGE_FND_VARIANT_DETAIL_MOVE_ASSIGN_HPP
28.247423
116
0.727007
myoukaku
3bffdce14200efbcb0ef7f702221417bfd5f16ee
170,645
hh
C++
libclingo/clingo.hh
tsahyt/clingo
5c5a61dc0ac5f54d8245e6c4ec28f6040882b151
[ "MIT" ]
1
2018-11-20T10:29:50.000Z
2018-11-20T10:29:50.000Z
libclingo/clingo.hh
tsahyt/clingo
5c5a61dc0ac5f54d8245e6c4ec28f6040882b151
[ "MIT" ]
null
null
null
libclingo/clingo.hh
tsahyt/clingo
5c5a61dc0ac5f54d8245e6c4ec28f6040882b151
[ "MIT" ]
null
null
null
// {{{ MIT License // Copyright 2017 Roland Kaminski // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // }}} #ifndef CLINGO_HH #define CLINGO_HH #include <clingo.h> #include <string> #include <cstring> #include <functional> #include <ostream> #include <algorithm> #include <vector> #include <cassert> #include <type_traits> #include <memory> #include <tuple> #include <forward_list> #include <atomic> #include <iostream> namespace Clingo { // {{{1 basic types // consider using upper case using literal_t = clingo_literal_t; using id_t = clingo_id_t; using weight_t = clingo_weight_t; using atom_t = clingo_atom_t; enum class TruthValue { Free = clingo_truth_value_free, True = clingo_truth_value_true, False = clingo_truth_value_false }; inline std::ostream &operator<<(std::ostream &out, TruthValue tv) { switch (tv) { case TruthValue::Free: { out << "Free"; break; } case TruthValue::True: { out << "True"; break; } case TruthValue::False: { out << "False"; break; } } return out; } // {{{1 variant namespace Detail { template <class T, class... U> struct TypeInList : std::false_type { }; template <class T, class... U> struct TypeInList<T, T, U...> : std::true_type { }; template <class T, class V, class... U> struct TypeInList<T, V, U...> : TypeInList<T, U...> { }; template <unsigned, class... U> struct VariantHolder; template <unsigned n> struct VariantHolder<n> { bool check_type() const { return type_ == 0; } void emplace() { } void emplace2() { } void copy(VariantHolder const &) { } void destroy() { type_ = 0; data_ = nullptr; } void print(std::ostream &) const { } void swap(VariantHolder &other) { std::swap(type_, other.type_); std::swap(data_, other.data_); } unsigned type_ = 0; void *data_ = nullptr; }; template <unsigned n, class T, class... U> struct VariantHolder<n, T, U...> : VariantHolder<n+1, U...>{ using Helper = VariantHolder<n+1, U...>; using Helper::check_type; using Helper::emplace; using Helper::emplace2; using Helper::data_; using Helper::type_; bool check_type(T *) const { return type_ == n; } template <class... Args> void emplace(T *, Args&& ...x) { data_ = new T{std::forward<Args>(x)...}; type_ = n; } // NOTE: http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1467 template <class... Args> void emplace2(T *, Args&& ...x) { data_ = new T(std::forward<Args>(x)...); type_ = n; } void copy(VariantHolder const &src) { if (src.type_ == n) { data_ = new T(*static_cast<T const*>(src.data_)); type_ = src.type_; } Helper::copy(src); } // NOTE: workaround for visual studio (C++14 can also simply use auto) # define CLINGO_VARIANT_RETURN(Type) decltype(std::declval<V>().visit(std::declval<Type&>(), std::declval<Args>()...)) template <class V, class... Args> using Ret_ = CLINGO_VARIANT_RETURN(T); template <class V, class... Args> using ConstRet_ = CLINGO_VARIANT_RETURN(T const); // non-const template <class V, class U1, class... U2, class... Args> auto accept_(V &&visitor, Args &&... args) -> CLINGO_VARIANT_RETURN(T) { static_assert(std::is_same<Ret_<V, Args...>, typename Helper::template Ret_<V, Args...>>::value, ""); return n == type_ ? visitor.visit(*static_cast<T*>(data_), std::forward<Args>(args)...) : Helper::template accept<V>(std::forward<V>(visitor), std::forward<Args>(args)...); } template <class V, class... Args> auto accept_(V &&visitor, Args &&... args) -> CLINGO_VARIANT_RETURN(T) { assert(n == type_); return visitor.visit(*static_cast<T*>(data_), std::forward<Args>(args)...); } template <class V, class... Args> auto accept(V &&visitor, Args &&... args) -> CLINGO_VARIANT_RETURN(T) { return accept_<V, U...>(std::forward<V>(visitor), std::forward<Args>(args)...); } // const template <class V, class U1, class... U2, class... Args> auto accept_(V &&visitor, Args &&... args) const -> CLINGO_VARIANT_RETURN(T const) { static_assert(std::is_same<ConstRet_<V, Args...>, typename Helper::template ConstRet_<V, Args...>>::value, ""); return n == type_ ? visitor.visit(*static_cast<T const *>(data_), std::forward<Args>(args)...) : Helper::template accept<V>(std::forward<V>(visitor), std::forward<Args>(args)...); } template <class V, class... Args> auto accept_(V &&visitor, Args &&... args) const -> CLINGO_VARIANT_RETURN(T const) { assert(n == type_); return visitor.visit(*static_cast<T const *>(data_), std::forward<Args>(args)...); } template <class V, class... Args> auto accept(V &&visitor, Args &&... args) const -> CLINGO_VARIANT_RETURN(T const) { return accept_<V, U...>(std::forward<V>(visitor), std::forward<Args>(args)...); } # undef CLINGO_VARIANT_RETURN void destroy() { if (n == type_) { delete static_cast<T*>(data_); } Helper::destroy(); } void print(std::ostream &out) const { if (n == type_) { out << *static_cast<T const*>(data_); } Helper::print(out); } }; } // Detail template <class T> class Optional { public: Optional() { } Optional(T const &x) : data_(new T(x)) { } Optional(T &x) : data_(new T(x)) { } Optional(T &&x) : data_(new T(std::move(x))) { } template <class... Args> Optional(Args&&... x) : data_(new T{std::forward<Args>(x)...}) { } Optional(Optional &&opt) noexcept : data_(opt.data_.release()) { } Optional(Optional const &opt) : data_(opt ? new T(*opt.get()) : nullptr) { } Optional &operator=(T const &x) { clear(); data_.reset(new T(x)); } Optional &operator=(T &x) { clear(); data_.reset(new T(x)); } Optional &operator=(T &&x) { clear(); data_.reset(new T(std::move(x))); } Optional &operator=(Optional &&opt) noexcept { data_ = std::move(opt.data_); } Optional &operator=(Optional const &opt) { clear(); data_.reset(opt ? new T(*opt.get()) : nullptr); } T *get() { return data_.get(); } T const *get() const { return data_.get(); } T *operator->() { return get(); } T const *operator->() const { return get(); } T &operator*() & { return *get(); } T const &operator*() const & { return *get(); } T &&operator*() && { return std::move(*get()); } T const &&operator*() const && { return std::move(*get()); } template <class... Args> void emplace(Args&&... x) { clear(); data_(new T{std::forward<Args>(x)...}); } void clear() { data_.reset(nullptr); } explicit operator bool() const { return data_.get() != nullptr; } private: std::unique_ptr<T> data_; }; template <class... T> class Variant { using Holder = Detail::VariantHolder<1, T...>; public: Variant(Variant const &other) : Variant(other.data_) { } Variant(Variant &&other) noexcept { data_.swap(other.data_); } template <class U> Variant(U &&u, typename std::enable_if<Detail::TypeInList<U, T...>::value>::type * = nullptr) { emplace2<U>(std::forward<U>(u)); } template <class U> Variant(U &u, typename std::enable_if<Detail::TypeInList<U, T...>::value>::type * = nullptr) { emplace2<U>(u); } template <class U> Variant(U const &u, typename std::enable_if<Detail::TypeInList<U, T...>::value>::type * = nullptr) { emplace2<U>(u); } template <class U, class... Args> static Variant make(Args&& ...args) { Variant<T...> x; x.data_.emplace(static_cast<U*>(nullptr), std::forward<Args>(args)...); return std::move(x); } ~Variant() { data_.destroy(); } Variant &operator=(Variant const &other) { return *this = other.data_; } Variant &operator=(Variant &&other) noexcept { return *this = std::move(other.data_); } template <class U> typename std::enable_if<Detail::TypeInList<U, T...>::value, Variant>::type &operator=(U &&u) { emplace2<U>(std::forward<U>(u)); return *this; } template <class U> typename std::enable_if<Detail::TypeInList<U, T...>::value, Variant>::type &operator=(U &u) { emplace2<U>(u); return *this; } template <class U> typename std::enable_if<Detail::TypeInList<U, T...>::value, Variant>::type &operator=(U const &u) { emplace2<U>(u); return *this; } template <class U> U &get() { if (!data_.check_type(static_cast<U*>(nullptr))) { throw std::bad_cast(); } return *static_cast<U*>(data_.data_); } template <class U> U const &get() const { if (!data_.check_type(static_cast<U*>(nullptr))) { throw std::bad_cast(); } return *static_cast<U*>(data_.data_); } template <class U, class... Args> void emplace(Args&& ...args) { Variant<T...> x; x.data_.emplace(static_cast<U*>(nullptr), std::forward<Args>(args)...); data_.swap(x.data_); } template <class U> bool is() const { return data_.check_type(static_cast<U*>(nullptr)); } void swap(Variant &other) { data_.swap(other.data_); } template <class V, class... Args> typename Holder::template Ret_<V, Args...> accept(V &&visitor, Args &&... args) { return data_.accept(std::forward<V>(visitor), std::forward<Args>(args)...); } template <class V, class... Args> typename Holder::template ConstRet_<V, Args...> accept(V &&visitor, Args &&... args) const { return data_.accept(std::forward<V>(visitor), std::forward<Args>(args)...); } friend std::ostream &operator<<(std::ostream &out, Variant const &x) { x.data_.print(out); return out; } private: Variant() { } Variant(Holder const &data) { data_.copy(data); } Variant &operator=(Holder const &data) { Variant x(data); data_.swap(x.data_); return *this; } Variant &operator=(Holder &&data) noexcept { Holder x; x.swap(data); // Destroy the old data_ only after securing the new data // Otherwise, data would be destroyed together with data_ if it was a descendant of data_ data_.destroy(); x.swap(data_); return *this; } template <class U, class... Args> void emplace2(Args&& ...args) { Variant<T...> x; x.data_.emplace2(static_cast<U*>(nullptr), std::forward<Args>(args)...); data_.swap(x.data_); } private: Holder data_; }; // {{{1 span template <class Iterator> class IteratorRange { public: using reference = typename Iterator::reference; using difference_type = typename Iterator::difference_type; IteratorRange(Iterator begin, Iterator end) : begin_(begin) , end_(end) { } reference operator[](difference_type n) { auto it = begin_; std::advance(it, n); return *it; } difference_type size() { return std::distance(begin_, end_); } bool empty() { return begin_ == end_; } Iterator begin() { return begin_; } Iterator end() { return end_; } private: Iterator begin_; Iterator end_; }; template <class Iterator> IteratorRange<Iterator> make_range(Iterator ib, Iterator ie) { return {ib, ie}; } template <class T> class ValuePointer { public: ValuePointer(T value) : value_(value) { } T &operator*() { return value_; } T *operator->() { return &value_; } private: T value_; }; template <class T> struct ToIterator { T const *operator()(T const *x) const { return x; } }; template <class T, class I = ToIterator<T>> class Span : private I { public: using IteratorType = typename std::result_of<I(T const *)>::type; using ReferenceType = decltype(*std::declval<IteratorType>()); Span(I to_it = I()) : Span(nullptr, size_t(0), to_it) { } template <class U> Span(U const *begin, size_t size) : Span(static_cast<T const *>(begin), size) { } Span(T const *begin, size_t size, I to_it = I()) : Span(begin, begin + size, to_it) { } Span(std::initializer_list<T> c, I to_it = I()) : Span(c.size() > 0 ? &*c.begin() : nullptr, c.size(), to_it) { } template <class U> Span(U const &c, I to_it = I()) : Span(c.size() > 0 ? &*c.begin() : nullptr, c.size(), to_it) { } Span(T const *begin, T const *end, I to_it = I()) : I(to_it) , begin_(begin) , end_(end) { } IteratorType begin() const { return I::operator()(begin_); } IteratorType end() const { return I::operator()(end_); } ReferenceType operator[](size_t offset) const { return *(begin() + offset); } ReferenceType front() const { return *begin(); } ReferenceType back() const { return *I::operator()(end_-1); } size_t size() const { return end_ - begin_; } bool empty() const { return begin_ == end_; } private: T const *begin_; T const *end_; }; template <class T, class U> bool equal_range(T const &a, U const &b) { using namespace std; return a.size() == b.size() && std::equal(begin(a), end(a), begin(b)); } template <class T, class I, class V> bool operator==(Span<T, I> span, V const &v) { return equal_range(span, v); } template <class T, class I, class V> bool operator==(V const &v, Span<T, I> span) { return equal_range(span, v); } template <class T, class I> std::ostream &operator<<(std::ostream &out, Span<T, I> span) { out << "{"; bool comma = false; for (auto &x : span) { if (comma) { out << ", "; } else { out << " "; } out << x; comma = true; } out << " }"; return out; } // {{{1 signature class Signature { public: explicit Signature(clingo_signature_t sig) : sig_(sig) { } Signature(char const *name, uint32_t arity, bool positive = true); char const *name() const; uint32_t arity() const; bool positive() const; bool negative() const; size_t hash() const; clingo_signature_t const &to_c() const { return sig_; } clingo_signature_t &to_c() { return sig_; } private: clingo_signature_t sig_; }; inline std::ostream &operator<<(std::ostream &out, Signature sig) { out << (sig.negative() ? "-" : "") << sig.name() << "/" << sig.arity(); return out; } bool operator==(Signature a, Signature b); bool operator!=(Signature a, Signature b); bool operator< (Signature a, Signature b); bool operator<=(Signature a, Signature b); bool operator> (Signature a, Signature b); bool operator>=(Signature a, Signature b); } namespace std { template<> struct hash<Clingo::Signature> { size_t operator()(Clingo::Signature sig) const { return sig.hash(); } }; } namespace Clingo { // {{{1 symbol enum class SymbolType : clingo_symbol_type_t { Infimum = clingo_symbol_type_infimum, Number = clingo_symbol_type_number, String = clingo_symbol_type_string, Function = clingo_symbol_type_function, Supremum = clingo_symbol_type_supremum }; class Symbol; using SymbolSpan = Span<Symbol>; using SymbolVector = std::vector<Symbol>; class Symbol { public: Symbol(); explicit Symbol(clingo_symbol_t); int number() const; char const *name() const; char const *string() const; bool is_positive() const; bool is_negative() const; SymbolSpan arguments() const; SymbolType type() const; std::string to_string() const; size_t hash() const; clingo_symbol_t &to_c() { return sym_; } clingo_symbol_t const &to_c() const { return sym_; } private: clingo_symbol_t sym_; }; Symbol Number(int num); Symbol Supremum(); Symbol Infimum(); Symbol String(char const *str); Symbol Id(char const *str, bool positive = true); Symbol Function(char const *name, SymbolSpan args, bool positive = true); std::ostream &operator<<(std::ostream &out, Symbol sym); bool operator==(Symbol a, Symbol b); bool operator!=(Symbol a, Symbol b); bool operator< (Symbol a, Symbol b); bool operator<=(Symbol a, Symbol b); bool operator> (Symbol a, Symbol b); bool operator>=(Symbol a, Symbol b); } namespace std { template<> struct hash<Clingo::Symbol> { size_t operator()(Clingo::Symbol sym) const { return sym.hash(); } }; } namespace Clingo { // {{{1 symbolic atoms class SymbolicAtom { friend class SymbolicAtomIterator; public: explicit SymbolicAtom(clingo_symbolic_atoms_t *atoms, clingo_symbolic_atom_iterator_t range) : atoms_(atoms) , range_(range) { } Symbol symbol() const; literal_t literal() const; bool is_fact() const; bool is_external() const; clingo_symbolic_atom_iterator_t to_c() const { return range_; } private: clingo_symbolic_atoms_t *atoms_; clingo_symbolic_atom_iterator_t range_; }; class SymbolicAtomIterator : private SymbolicAtom, public std::iterator<std::input_iterator_tag, SymbolicAtom> { public: explicit SymbolicAtomIterator(clingo_symbolic_atoms_t *atoms, clingo_symbolic_atom_iterator_t range) : SymbolicAtom{atoms, range} { } SymbolicAtom &operator*() { return *this; } SymbolicAtom *operator->() { return this; } SymbolicAtomIterator &operator++(); SymbolicAtomIterator operator++ (int) { auto range = range_; ++(*this); return SymbolicAtomIterator{atoms_, range}; } bool operator==(SymbolicAtomIterator it) const; bool operator!=(SymbolicAtomIterator it) const { return !(*this == it); } explicit operator bool() const; clingo_symbolic_atom_iterator_t to_c() const { return range_; } }; class SymbolicAtoms { public: explicit SymbolicAtoms(clingo_symbolic_atoms_t *atoms) : atoms_(atoms) { } SymbolicAtomIterator begin() const; SymbolicAtomIterator begin(Signature sig) const; SymbolicAtomIterator end() const; SymbolicAtomIterator find(Symbol atom) const; std::vector<Signature> signatures() const; size_t length() const; clingo_symbolic_atoms_t* to_c() const { return atoms_; } SymbolicAtom operator[](Symbol atom) { return *find(atom); } private: clingo_symbolic_atoms_t *atoms_; }; // {{{1 theory atoms enum class TheoryTermType : clingo_theory_term_type_t { Tuple = clingo_theory_term_type_tuple, List = clingo_theory_term_type_list, Set = clingo_theory_term_type_set, Function = clingo_theory_term_type_function, Number = clingo_theory_term_type_number, Symbol = clingo_theory_term_type_symbol }; template <class T> class TheoryIterator : public std::iterator<std::random_access_iterator_tag, const T, ptrdiff_t, T*, T> { public: using base = std::iterator<std::random_access_iterator_tag, const T>; using difference_type = typename base::difference_type; explicit TheoryIterator(clingo_theory_atoms_t *atoms, clingo_id_t const* id) : elem_(atoms) , id_(id) { } TheoryIterator& operator++() { ++id_; return *this; } TheoryIterator operator++(int) { TheoryIterator t(*this); ++*this; return t; } TheoryIterator& operator--() { --id_; return *this; } TheoryIterator operator--(int) { TheoryIterator t(*this); --*this; return t; } TheoryIterator& operator+=(difference_type n) { id_ += n; return *this; } TheoryIterator& operator-=(difference_type n) { id_ -= n; return *this; } friend TheoryIterator operator+(TheoryIterator it, difference_type n) { return TheoryIterator{it.atoms(), it.id_ + n}; } friend TheoryIterator operator+(difference_type n, TheoryIterator it) { return TheoryIterator{it.atoms(), it.id_ + n}; } friend TheoryIterator operator-(TheoryIterator it, difference_type n) { return TheoryIterator{it.atoms(), it.id_ - n}; } friend difference_type operator-(TheoryIterator a, TheoryIterator b) { return a.id_ - b.id_; } T operator*() { return elem_ = *id_; } T *operator->() { return &(elem_ = *id_); } friend void swap(TheoryIterator& lhs, TheoryIterator& rhs) { std::swap(lhs.id_, rhs.id_); std::swap(lhs.elem_, rhs.elem_); } friend bool operator==(const TheoryIterator& lhs, const TheoryIterator& rhs) { return lhs.id_ == rhs.id_; } friend bool operator!=(const TheoryIterator& lhs, const TheoryIterator& rhs) { return !(lhs == rhs); } friend bool operator< (TheoryIterator lhs, TheoryIterator rhs) { return lhs.id_ < rhs.id_; } friend bool operator> (TheoryIterator lhs, TheoryIterator rhs) { return rhs < lhs; } friend bool operator<=(TheoryIterator lhs, TheoryIterator rhs) { return !(lhs > rhs); } friend bool operator>=(TheoryIterator lhs, TheoryIterator rhs) { return !(lhs < rhs); } private: clingo_theory_atoms_t *&atoms() { return elem_.atoms_; } private: T elem_; clingo_id_t const *id_; }; template <class T> class ToTheoryIterator { public: explicit ToTheoryIterator(clingo_theory_atoms_t *atoms) : atoms_(atoms) { } T operator ()(clingo_id_t const *id) const { return T{atoms_, id}; } private: clingo_theory_atoms_t *atoms_; }; class TheoryTerm; using TheoryTermIterator = TheoryIterator<TheoryTerm>; using TheoryTermSpan = Span<clingo_id_t, ToTheoryIterator<TheoryTermIterator>>; class TheoryTerm { friend class TheoryIterator<TheoryTerm>; public: explicit TheoryTerm(clingo_theory_atoms_t *atoms, clingo_id_t id) : atoms_(atoms) , id_(id) { } TheoryTermType type() const; int number() const; char const *name() const; TheoryTermSpan arguments() const; clingo_id_t to_c() const { return id_; } std::string to_string() const; private: TheoryTerm(clingo_theory_atoms_t *atoms) : TheoryTerm(atoms, 0) { } TheoryTerm &operator=(clingo_id_t id) { id_ = id; return *this; } private: clingo_theory_atoms_t *atoms_; clingo_id_t id_; }; std::ostream &operator<<(std::ostream &out, TheoryTerm term); class TheoryElement; using TheoryElementIterator = TheoryIterator<TheoryElement>; using TheoryElementSpan = Span<clingo_id_t, ToTheoryIterator<TheoryElementIterator>>; using LiteralSpan = Span<literal_t>; class TheoryElement { friend class TheoryIterator<TheoryElement>; public: explicit TheoryElement(clingo_theory_atoms_t *atoms, clingo_id_t id) : atoms_(atoms) , id_(id) { } TheoryTermSpan tuple() const; LiteralSpan condition() const; literal_t condition_id() const; std::string to_string() const; clingo_id_t to_c() const { return id_; } private: TheoryElement(clingo_theory_atoms_t *atoms) : TheoryElement(atoms, 0) { } TheoryElement &operator=(clingo_id_t id) { id_ = id; return *this; } private: clingo_theory_atoms_t *atoms_; clingo_id_t id_; }; std::ostream &operator<<(std::ostream &out, TheoryElement term); class TheoryAtom { friend class TheoryAtomIterator; public: explicit TheoryAtom(clingo_theory_atoms_t *atoms, clingo_id_t id) : atoms_(atoms) , id_(id) { } TheoryElementSpan elements() const; TheoryTerm term() const; bool has_guard() const; literal_t literal() const; std::pair<char const *, TheoryTerm> guard() const; std::string to_string() const; clingo_id_t to_c() const { return id_; } private: TheoryAtom(clingo_theory_atoms_t *atoms) : TheoryAtom(atoms, 0) { } TheoryAtom &operator=(clingo_id_t id) { id_ = id; return *this; } private: clingo_theory_atoms_t *atoms_; clingo_id_t id_; }; std::ostream &operator<<(std::ostream &out, TheoryAtom term); class TheoryAtomIterator : private TheoryAtom, public std::iterator<TheoryAtom, std::random_access_iterator_tag, ptrdiff_t, TheoryAtom*, TheoryAtom> { public: explicit TheoryAtomIterator(clingo_theory_atoms_t *atoms, clingo_id_t id) : TheoryAtom{atoms, id} { } TheoryAtomIterator& operator++() { ++id_; return *this; } TheoryAtomIterator operator++(int) { auto t = *this; ++*this; return t; } TheoryAtomIterator& operator--() { --id_; return *this; } TheoryAtomIterator operator--(int) { auto t = *this; --*this; return t; } TheoryAtomIterator& operator+=(difference_type n) { id_ += static_cast<clingo_id_t>(n); return *this; } TheoryAtomIterator& operator-=(difference_type n) { id_ -= static_cast<clingo_id_t>(n); return *this; } friend TheoryAtomIterator operator+(TheoryAtomIterator it, difference_type n) { return TheoryAtomIterator{it.atoms(), clingo_id_t(it.id() + n)}; } friend TheoryAtomIterator operator+(difference_type n, TheoryAtomIterator it) { return TheoryAtomIterator{it.atoms(), clingo_id_t(it.id() + n)}; } friend TheoryAtomIterator operator-(TheoryAtomIterator it, difference_type n) { return TheoryAtomIterator{it.atoms(), clingo_id_t(it.id() - n)}; } friend difference_type operator-(TheoryAtomIterator a, TheoryAtomIterator b) { return a.id() - b.id(); } TheoryAtom operator*() { return *this; } TheoryAtom *operator->() { return this; } friend void swap(TheoryAtomIterator& lhs, TheoryAtomIterator& rhs) { std::swap(lhs.atoms(), rhs.atoms()); std::swap(lhs.id(), rhs.id()); } friend bool operator==(TheoryAtomIterator lhs, TheoryAtomIterator rhs) { return lhs.atoms() == rhs.atoms() && lhs.id() == rhs.id(); } friend bool operator!=(TheoryAtomIterator lhs, TheoryAtomIterator rhs) { return !(lhs == rhs); } friend bool operator< (TheoryAtomIterator lhs, TheoryAtomIterator rhs) { assert(lhs.atoms() == rhs.atoms()); return (lhs.id() + 1) < (rhs.id() + 1); } friend bool operator> (TheoryAtomIterator lhs, TheoryAtomIterator rhs) { return rhs < lhs; } friend bool operator<=(TheoryAtomIterator lhs, TheoryAtomIterator rhs) { return !(lhs > rhs); } friend bool operator>=(TheoryAtomIterator lhs, TheoryAtomIterator rhs) { return !(lhs < rhs); } private: clingo_theory_atoms_t *&atoms() { return atoms_; } clingo_id_t &id() { return id_; } }; class TheoryAtoms { public: explicit TheoryAtoms(clingo_theory_atoms_t *atoms) : atoms_(atoms) { } TheoryAtomIterator begin() const; TheoryAtomIterator end() const; size_t size() const; clingo_theory_atoms_t *to_c() const { return atoms_; } private: clingo_theory_atoms_t *atoms_; }; // {{{1 propagate init enum PropagatorCheckMode : clingo_propagator_check_mode_t { None = clingo_propagator_check_mode_none, Total = clingo_propagator_check_mode_total, Partial = clingo_propagator_check_mode_fixpoint, }; class PropagateInit { public: explicit PropagateInit(clingo_propagate_init_t *init) : init_(init) { } literal_t solver_literal(literal_t lit) const; void add_watch(literal_t lit); int number_of_threads() const; SymbolicAtoms symbolic_atoms() const; TheoryAtoms theory_atoms() const; PropagatorCheckMode get_check_mode() const; void set_check_mode(PropagatorCheckMode mode); clingo_propagate_init_t *to_c() const { return init_; } private: clingo_propagate_init_t *init_; }; // {{{1 assignment class Assignment { public: explicit Assignment(clingo_assignment_t *ass) : ass_(ass) { } bool has_conflict() const; uint32_t decision_level() const; bool has_literal(literal_t lit) const; TruthValue truth_value(literal_t lit) const; uint32_t level(literal_t lit) const; literal_t decision(uint32_t level) const; bool is_fixed(literal_t lit) const; bool is_true(literal_t lit) const; bool is_false(literal_t lit) const; size_t size() const; size_t max_size() const; bool is_total() const; clingo_assignment_t *to_c() const { return ass_; } private: clingo_assignment_t *ass_; }; // {{{1 propagate control enum class ClauseType : clingo_clause_type_t { Learnt = clingo_clause_type_learnt, Static = clingo_clause_type_static, Volatile = clingo_clause_type_volatile, VolatileStatic = clingo_clause_type_volatile_static }; inline std::ostream &operator<<(std::ostream &out, ClauseType t) { switch (t) { case ClauseType::Learnt: { out << "Learnt"; break; } case ClauseType::Static: { out << "Static"; break; } case ClauseType::Volatile: { out << "Volatile"; break; } case ClauseType::VolatileStatic: { out << "VolatileStatic"; break; } } return out; } class PropagateControl { public: explicit PropagateControl(clingo_propagate_control_t *ctl) : ctl_(ctl) { } id_t thread_id() const; Assignment assignment() const; literal_t add_literal(); void add_watch(literal_t literal); bool has_watch(literal_t literal) const; void remove_watch(literal_t literal); bool add_clause(LiteralSpan clause, ClauseType type = ClauseType::Learnt); bool propagate(); clingo_propagate_control_t *to_c() const { return ctl_; } private: clingo_propagate_control_t *ctl_; }; // {{{1 propagator class Propagator { public: virtual void init(PropagateInit &init); virtual void propagate(PropagateControl &ctl, LiteralSpan changes); virtual void undo(PropagateControl const &ctl, LiteralSpan changes); virtual void check(PropagateControl &ctl); virtual ~Propagator() noexcept = default; }; // {{{1 ground program observer using IdSpan = Span<id_t>; using AtomSpan = Span<atom_t>; class WeightedLiteral { public: WeightedLiteral(clingo_literal_t lit, clingo_weight_t weight) : wlit_{lit, weight} { } explicit WeightedLiteral(clingo_weighted_literal_t wlit) : wlit_(wlit) { } literal_t literal() const { return wlit_.literal; } weight_t weight() const { return wlit_.weight; } clingo_weighted_literal_t const &to_c() const { return wlit_; } clingo_weighted_literal_t &to_c() { return wlit_; } private: clingo_weighted_literal_t wlit_; }; using WeightedLiteralSpan = Span<WeightedLiteral>; enum class HeuristicType : clingo_heuristic_type_t { Level = clingo_heuristic_type_level, Sign = clingo_heuristic_type_sign, Factor = clingo_heuristic_type_factor, Init = clingo_heuristic_type_init, True = clingo_heuristic_type_true, False = clingo_heuristic_type_false }; inline std::ostream &operator<<(std::ostream &out, HeuristicType t) { switch (t) { case HeuristicType::Level: { out << "Level"; break; } case HeuristicType::Sign: { out << "Sign"; break; } case HeuristicType::Factor: { out << "Factor"; break; } case HeuristicType::Init: { out << "Init"; break; } case HeuristicType::True: { out << "True"; break; } case HeuristicType::False: { out << "False"; break; } } return out; } enum class ExternalType { Free = clingo_external_type_free, True = clingo_external_type_true, False = clingo_external_type_false, Release = clingo_external_type_release }; inline std::ostream &operator<<(std::ostream &out, ExternalType t) { switch (t) { case ExternalType::Free: { out << "Free"; break; } case ExternalType::True: { out << "True"; break; } case ExternalType::False: { out << "False"; break; } case ExternalType::Release: { out << "Release"; break; } } return out; } class GroundProgramObserver { public: virtual void init_program(bool incremental); virtual void begin_step(); virtual void end_step(); virtual void rule(bool choice, AtomSpan head, LiteralSpan body); virtual void weight_rule(bool choice, AtomSpan head, weight_t lower_bound, WeightedLiteralSpan body); virtual void minimize(weight_t priority, WeightedLiteralSpan literals); virtual void project(AtomSpan atoms); virtual void output_atom(Symbol symbol, atom_t atom); virtual void output_term(Symbol symbol, LiteralSpan condition); virtual void output_csp(Symbol symbol, int value, LiteralSpan condition); virtual void external(atom_t atom, ExternalType type); virtual void assume(LiteralSpan literals); virtual void heuristic(atom_t atom, HeuristicType type, int bias, unsigned priority, LiteralSpan condition); virtual void acyc_edge(int node_u, int node_v, LiteralSpan condition); virtual void theory_term_number(id_t term_id, int number); virtual void theory_term_string(id_t term_id, char const *name); virtual void theory_term_compound(id_t term_id, int name_id_or_type, IdSpan arguments); virtual void theory_element(id_t element_id, IdSpan terms, LiteralSpan condition); virtual void theory_atom(id_t atom_id_or_zero, id_t term_id, IdSpan elements); virtual void theory_atom_with_guard(id_t atom_id_or_zero, id_t term_id, IdSpan elements, id_t operator_id, id_t right_hand_side_id); virtual ~GroundProgramObserver() noexcept = default; }; inline void GroundProgramObserver::init_program(bool) { } inline void GroundProgramObserver::begin_step() { } inline void GroundProgramObserver::end_step() { } inline void GroundProgramObserver::rule(bool, AtomSpan, LiteralSpan) { } inline void GroundProgramObserver::weight_rule(bool, AtomSpan, weight_t, WeightedLiteralSpan) { } inline void GroundProgramObserver::minimize(weight_t, WeightedLiteralSpan) { } inline void GroundProgramObserver::project(AtomSpan) { } inline void GroundProgramObserver::output_atom(Symbol, atom_t) { } inline void GroundProgramObserver::output_term(Symbol, LiteralSpan) { } inline void GroundProgramObserver::output_csp(Symbol, int, LiteralSpan) { } inline void GroundProgramObserver::external(atom_t, ExternalType) { } inline void GroundProgramObserver::assume(LiteralSpan) { } inline void GroundProgramObserver::heuristic(atom_t, HeuristicType, int, unsigned, LiteralSpan) { } inline void GroundProgramObserver::acyc_edge(int, int, LiteralSpan) { } inline void GroundProgramObserver::theory_term_number(id_t, int) { } inline void GroundProgramObserver::theory_term_string(id_t, char const *) { } inline void GroundProgramObserver::theory_term_compound(id_t, int, IdSpan) { } inline void GroundProgramObserver::theory_element(id_t, IdSpan, LiteralSpan) { } inline void GroundProgramObserver::theory_atom(id_t, id_t, IdSpan) { } inline void GroundProgramObserver::theory_atom_with_guard(id_t, id_t, IdSpan, id_t, id_t) { } // {{{1 symbolic literal class SymbolicLiteral { public: SymbolicLiteral(Symbol sym, bool sign) : sym_{sym.to_c(), sign} { } explicit SymbolicLiteral(clingo_symbolic_literal_t sym) : sym_(sym) { } Symbol symbol() const { return Symbol(sym_.symbol); } bool is_positive() const { return sym_.positive; } bool is_negative() const { return !sym_.positive; } clingo_symbolic_literal_t &to_c() { return sym_; } clingo_symbolic_literal_t const &to_c() const { return sym_; } private: clingo_symbolic_literal_t sym_; }; using SymbolicLiteralSpan = Span<SymbolicLiteral>; inline std::ostream &operator<<(std::ostream &out, SymbolicLiteral sym) { if (sym.is_negative()) { out << "~"; } out << sym.symbol(); return out; } inline bool operator==(SymbolicLiteral a, SymbolicLiteral b) { return a.is_negative() == b.is_negative() && a.symbol() == b.symbol(); } inline bool operator!=(SymbolicLiteral a, SymbolicLiteral b) { return !(a == b); } inline bool operator< (SymbolicLiteral a, SymbolicLiteral b) { if (a.is_negative() != b.is_negative()) { return a.is_negative() < b.is_negative(); } return a.symbol() < b.symbol(); } inline bool operator<=(SymbolicLiteral a, SymbolicLiteral b) { return !(b < a); } inline bool operator> (SymbolicLiteral a, SymbolicLiteral b) { return (b < a); } inline bool operator>=(SymbolicLiteral a, SymbolicLiteral b) { return !(a < b); } // {{{1 solve control class SolveControl { public: explicit SolveControl(clingo_solve_control_t *ctl) : ctl_(ctl) { } void add_clause(SymbolicLiteralSpan clause); void add_clause(LiteralSpan clause); SymbolicAtoms symbolic_atoms(); clingo_solve_control_t *to_c() const { return ctl_; } private: clingo_solve_control_t *ctl_; }; // {{{1 model enum class ModelType : clingo_model_type_t { StableModel = clingo_model_type_stable_model, BraveConsequences = clingo_model_type_brave_consequences, CautiousConsequences = clingo_model_type_cautious_consequences }; class ShowType { public: enum Type : clingo_show_type_bitset_t { CSP = clingo_show_type_csp, Shown = clingo_show_type_shown, Atoms = clingo_show_type_atoms, Terms = clingo_show_type_terms, Theory = clingo_show_type_extra, All = clingo_show_type_all, Complement = clingo_show_type_complement }; ShowType(clingo_show_type_bitset_t type) : type_(type) { } operator clingo_show_type_bitset_t() const { return type_; } private: clingo_show_type_bitset_t type_; }; using CostVector = std::vector<int64_t>; class Model { public: explicit Model(clingo_model_t *model); bool contains(Symbol atom) const; bool optimality_proven() const; CostVector cost() const; SymbolVector symbols(ShowType show = ShowType::Shown) const; SolveControl context() const; ModelType type() const; id_t thread_id() const; uint64_t number() const; explicit operator bool() const { return model_ != nullptr; } clingo_model_t *to_c() const { return model_; } private: clingo_model_t *model_; }; inline std::ostream &operator<<(std::ostream &out, Model m) { out << SymbolSpan(m.symbols(ShowType::Shown)); return out; } // {{{1 solve result class SolveResult { public: SolveResult() : res_(0) { } explicit SolveResult(clingo_solve_result_bitset_t res) : res_(res) { } bool is_satisfiable() const { return res_ & clingo_solve_result_satisfiable; } bool is_unsatisfiable() const { return (res_ & clingo_solve_result_unsatisfiable) != 0; } bool is_unknown() const { return (res_ & 3) == 0; } bool is_exhausted() const { return (res_ & clingo_solve_result_exhausted) != 0; } bool is_interrupted() const { return (res_ & clingo_solve_result_interrupted) != 0; } clingo_solve_result_bitset_t &to_c() { return res_; } clingo_solve_result_bitset_t const &to_c() const { return res_; } friend bool operator==(SolveResult a, SolveResult b) { return a.res_ == b.res_; } friend bool operator!=(SolveResult a, SolveResult b) { return a.res_ != b.res_; } private: clingo_solve_result_bitset_t res_; }; inline std::ostream &operator<<(std::ostream &out, SolveResult res) { if (res.is_satisfiable()) { out << "SATISFIABLE"; if (!res.is_exhausted()) { out << "+"; } } else if (res.is_unsatisfiable()) { out << "UNSATISFIABLE"; } else { out << "UNKNOWN"; } if (res.is_interrupted()) { out << "/INTERRUPTED"; } return out; } // {{{1 solve handle class SolveEventHandler { public: virtual bool on_model(Model const &model); virtual void on_finish(SolveResult result); virtual ~SolveEventHandler() = default; }; inline bool SolveEventHandler::on_model(Model const &) { return true; } inline void SolveEventHandler::on_finish(SolveResult) { } namespace Detail { class AssignOnce; } // namespace Detail class SolveHandle { public: SolveHandle(); explicit SolveHandle(clingo_solve_handle_t *it, Detail::AssignOnce &ptr); SolveHandle(SolveHandle &&it); SolveHandle(SolveHandle const &) = delete; SolveHandle &operator=(SolveHandle &&it); SolveHandle &operator=(SolveHandle const &) = delete; clingo_solve_handle_t *to_c() const { return iter_; } void resume(); void wait(); bool wait(double timeout); Model model(); Model next(); SolveResult get(); void cancel(); ~SolveHandle(); private: clingo_solve_handle_t *iter_; Detail::AssignOnce *exception_; }; class ModelIterator : public std::iterator<Model, std::input_iterator_tag> { public: explicit ModelIterator(SolveHandle &iter) : iter_(&iter) , model_(nullptr) { model_ = iter_->next(); } ModelIterator() : iter_(nullptr) , model_(nullptr) { } ModelIterator &operator++() { model_ = iter_->next(); return *this; } // Warning: the resulting iterator should not be used // because its model is no longer valid ModelIterator operator++(int) { ModelIterator t = *this; ++*this; return t; } Model &operator*() { return model_; } Model *operator->() { return &**this; } friend bool operator==(ModelIterator a, ModelIterator b) { return a.model_.to_c() == b.model_.to_c(); } friend bool operator!=(ModelIterator a, ModelIterator b) { return !(a == b); } private: SolveHandle *iter_; Model model_; }; inline ModelIterator begin(SolveHandle &it) { return ModelIterator(it); } inline ModelIterator end(SolveHandle &) { return ModelIterator(); } // {{{1 location class Location : public clingo_location_t { public: explicit Location(clingo_location_t loc) : clingo_location_t(loc) { } Location(char const *begin_file, char const *end_file, size_t begin_line, size_t end_line, size_t begin_column, size_t end_column) : clingo_location_t{begin_file, end_file, begin_line, end_line, begin_column, end_column} { } char const *begin_file() const { return clingo_location_t::begin_file; } char const *end_file() const { return clingo_location_t::end_file; } size_t begin_line() const { return clingo_location_t::begin_line; } size_t end_line() const { return clingo_location_t::end_line; } size_t begin_column() const { return clingo_location_t::begin_column; } size_t end_column() const { return clingo_location_t::end_column; } }; inline std::ostream &operator<<(std::ostream &out, Location loc) { out << loc.begin_file() << ":" << loc.begin_line() << ":" << loc.begin_column(); bool dash = true; bool eq = std::strcmp(loc.begin_file(), loc.end_file()) == 0; if (!eq) { out << (dash ? "-" : ":") << loc.end_file(); dash = false; } eq = eq && (loc.begin_line() == loc.end_line()); if (!eq) { out << (dash ? "-" : ":") << loc.end_line(); dash = false; } eq = eq && (loc.begin_column() == loc.end_column()); if (!eq) { out << (dash ? "-" : ":") << loc.end_column(); dash = false; } return out; } // {{{1 ast namespace AST { enum class ComparisonOperator : clingo_ast_comparison_operator_t { GreaterThan = clingo_ast_comparison_operator_greater_than, LessThan = clingo_ast_comparison_operator_less_than, LessEqual = clingo_ast_comparison_operator_less_equal, GreaterEqual = clingo_ast_comparison_operator_greater_equal, NotEqual = clingo_ast_comparison_operator_not_equal, Equal = clingo_ast_comparison_operator_equal }; inline std::ostream &operator<<(std::ostream &out, ComparisonOperator op) { switch (op) { case ComparisonOperator::GreaterThan: { out << ">"; break; } case ComparisonOperator::LessThan: { out << "<"; break; } case ComparisonOperator::LessEqual: { out << "<="; break; } case ComparisonOperator::GreaterEqual: { out << ">="; break; } case ComparisonOperator::NotEqual: { out << "!="; break; } case ComparisonOperator::Equal: { out << "="; break; } } return out; } enum class Sign : clingo_ast_sign_t { None = clingo_ast_sign_none, Negation = clingo_ast_sign_negation, DoubleNegation = clingo_ast_sign_double_negation }; inline std::ostream &operator<<(std::ostream &out, Sign op) { switch (op) { case Sign::None: { out << ""; break; } case Sign::Negation: { out << "not "; break; } case Sign::DoubleNegation: { out << "not not "; break; } } return out; } // {{{2 terms // variable struct Variable; struct UnaryOperation; struct BinaryOperation; struct Interval; struct Function; struct Pool; struct Term { Location location; Variant<Symbol, Variable, UnaryOperation, BinaryOperation, Interval, Function, Pool> data; }; std::ostream &operator<<(std::ostream &out, Term const &term); // Variable struct Variable { char const *name; }; std::ostream &operator<<(std::ostream &out, Variable const &x); // unary operation enum UnaryOperator : clingo_ast_unary_operator_t { Absolute = clingo_ast_unary_operator_absolute, Minus = clingo_ast_unary_operator_minus, Negation = clingo_ast_unary_operator_negation }; inline char const *left_hand_side(UnaryOperator op) { switch (op) { case UnaryOperator::Absolute: { return "|"; } case UnaryOperator::Minus: { return "-"; } case UnaryOperator::Negation: { return "~"; } } return ""; } inline char const *right_hand_side(UnaryOperator op) { switch (op) { case UnaryOperator::Absolute: { return "|"; } case UnaryOperator::Minus: { return ""; } case UnaryOperator::Negation: { return ""; } } return ""; } struct UnaryOperation { UnaryOperator unary_operator; Term argument; }; std::ostream &operator<<(std::ostream &out, UnaryOperation const &x); // binary operation enum class BinaryOperator : clingo_ast_binary_operator_t { XOr = clingo_ast_binary_operator_xor, Or = clingo_ast_binary_operator_or, And = clingo_ast_binary_operator_and, Plus = clingo_ast_binary_operator_plus, Minus = clingo_ast_binary_operator_minus, Multiplication = clingo_ast_binary_operator_multiplication, Division = clingo_ast_binary_operator_division, Modulo = clingo_ast_binary_operator_modulo, Power = clingo_ast_binary_operator_power }; inline std::ostream &operator<<(std::ostream &out, BinaryOperator op) { switch (op) { case BinaryOperator::XOr: { out << "^"; break; } case BinaryOperator::Or: { out << "?"; break; } case BinaryOperator::And: { out << "&"; break; } case BinaryOperator::Plus: { out << "+"; break; } case BinaryOperator::Minus: { out << "-"; break; } case BinaryOperator::Multiplication: { out << "*"; break; } case BinaryOperator::Division: { out << "/"; break; } case BinaryOperator::Modulo: { out << "\\"; break; } case BinaryOperator::Power: { out << "**"; break; } } return out; } struct BinaryOperation { BinaryOperator binary_operator; Term left; Term right; }; std::ostream &operator<<(std::ostream &out, BinaryOperation const &x); // interval struct Interval { Term left; Term right; }; std::ostream &operator<<(std::ostream &out, Interval const &x); // function struct Function { char const *name; std::vector<Term> arguments; bool external; }; std::ostream &operator<<(std::ostream &out, Function const &x); // pool struct Pool { std::vector<Term> arguments; }; std::ostream &operator<<(std::ostream &out, Pool const &x); // {{{2 csp struct CSPProduct { Location location; Term coefficient; Optional<Term> variable; }; std::ostream &operator<<(std::ostream &out, CSPProduct const &x); struct CSPSum { Location location; std::vector<CSPProduct> terms; }; std::ostream &operator<<(std::ostream &out, CSPSum const &x); struct CSPGuard { ComparisonOperator comparison; CSPSum term; }; std::ostream &operator<<(std::ostream &out, CSPGuard const &x); struct CSPLiteral { CSPSum term; std::vector<CSPGuard> guards; }; std::ostream &operator<<(std::ostream &out, CSPLiteral const &x); // {{{2 ids struct Id { Location location; char const *id; }; std::ostream &operator<<(std::ostream &out, Id const &x); // {{{2 literals struct Comparison { ComparisonOperator comparison; Term left; Term right; }; std::ostream &operator<<(std::ostream &out, Comparison const &x); struct Boolean { bool value; }; std::ostream &operator<<(std::ostream &out, Boolean const &x); struct Literal { Location location; Sign sign; Variant<Boolean, Term, Comparison, CSPLiteral> data; }; std::ostream &operator<<(std::ostream &out, Literal const &x); // {{{2 aggregates enum class AggregateFunction : clingo_ast_aggregate_function_t { Count = clingo_ast_aggregate_function_count, Sum = clingo_ast_aggregate_function_sum, SumPlus = clingo_ast_aggregate_function_sump, Min = clingo_ast_aggregate_function_min, Max = clingo_ast_aggregate_function_max }; inline std::ostream &operator<<(std::ostream &out, AggregateFunction op) { switch (op) { case AggregateFunction::Count: { out << "#count"; break; } case AggregateFunction::Sum: { out << "#sum"; break; } case AggregateFunction::SumPlus: { out << "#sum+"; break; } case AggregateFunction::Min: { out << "#min"; break; } case AggregateFunction::Max: { out << "#max"; break; } } return out; } struct AggregateGuard { ComparisonOperator comparison; Term term; }; struct ConditionalLiteral { Literal literal; std::vector<Literal> condition; }; std::ostream &operator<<(std::ostream &out, ConditionalLiteral const &x); // lparse-style aggregate struct Aggregate { std::vector<ConditionalLiteral> elements; Optional<AggregateGuard> left_guard; Optional<AggregateGuard> right_guard; }; std::ostream &operator<<(std::ostream &out, Aggregate const &x); // body aggregate struct BodyAggregateElement { std::vector<Term> tuple; std::vector<Literal> condition; }; std::ostream &operator<<(std::ostream &out, BodyAggregateElement const &x); struct BodyAggregate { AggregateFunction function; std::vector<BodyAggregateElement> elements; Optional<AggregateGuard> left_guard; Optional<AggregateGuard> right_guard; }; std::ostream &operator<<(std::ostream &out, BodyAggregate const &x); // head aggregate struct HeadAggregateElement { std::vector<Term> tuple; ConditionalLiteral condition; }; std::ostream &operator<<(std::ostream &out, HeadAggregateElement const &x); struct HeadAggregate { AggregateFunction function; std::vector<HeadAggregateElement> elements; Optional<AggregateGuard> left_guard; Optional<AggregateGuard> right_guard; }; std::ostream &operator<<(std::ostream &out, HeadAggregate const &x); // disjunction struct Disjunction { std::vector<ConditionalLiteral> elements; }; std::ostream &operator<<(std::ostream &out, Disjunction const &x); // disjoint struct DisjointElement { Location location; std::vector<Term> tuple; CSPSum term; std::vector<Literal> condition; }; std::ostream &operator<<(std::ostream &out, DisjointElement const &x); struct Disjoint { std::vector<DisjointElement> elements; }; std::ostream &operator<<(std::ostream &out, Disjoint const &x); // {{{2 theory atom enum class TheoryTermSequenceType : int { Tuple = 0, List = 1, Set = 2 }; inline char const *left_hand_side(TheoryTermSequenceType x) { switch (x) { case TheoryTermSequenceType::Tuple: { return "("; } case TheoryTermSequenceType::List: { return "["; } case TheoryTermSequenceType::Set: { return "{"; } } return ""; } inline char const *right_hand_side(TheoryTermSequenceType x) { switch (x) { case TheoryTermSequenceType::Tuple: { return ")"; } case TheoryTermSequenceType::List: { return "]"; } case TheoryTermSequenceType::Set: { return "}"; } } return ""; } struct TheoryFunction; struct TheoryTermSequence; struct TheoryUnparsedTerm; struct TheoryTerm { Location location; Variant<Symbol, Variable, TheoryTermSequence, TheoryFunction, TheoryUnparsedTerm> data; }; std::ostream &operator<<(std::ostream &out, TheoryTerm const &x); struct TheoryTermSequence { TheoryTermSequenceType type; std::vector<TheoryTerm> terms; }; std::ostream &operator<<(std::ostream &out, TheoryTermSequence const &x); struct TheoryFunction { char const *name; std::vector<TheoryTerm> arguments; }; std::ostream &operator<<(std::ostream &out, TheoryFunction const &x); struct TheoryUnparsedTermElement { std::vector<char const *> operators; TheoryTerm term; }; std::ostream &operator<<(std::ostream &out, TheoryUnparsedTermElement const &x); struct TheoryUnparsedTerm { std::vector<TheoryUnparsedTermElement> elements; }; std::ostream &operator<<(std::ostream &out, TheoryUnparsedTerm const &x); struct TheoryAtomElement { std::vector<TheoryTerm> tuple; std::vector<Literal> condition; }; std::ostream &operator<<(std::ostream &out, TheoryAtomElement const &x); struct TheoryGuard { char const *operator_name; TheoryTerm term; }; std::ostream &operator<<(std::ostream &out, TheoryGuard const &x); struct TheoryAtom { Term term; std::vector<TheoryAtomElement> elements; Optional<TheoryGuard> guard; }; std::ostream &operator<<(std::ostream &out, TheoryAtom const &x); // {{{2 head literals struct HeadLiteral { Location location; Variant<Literal, Disjunction, Aggregate, HeadAggregate, TheoryAtom> data; }; std::ostream &operator<<(std::ostream &out, HeadLiteral const &x); // {{{2 body literals struct BodyLiteral { Location location; Sign sign; Variant<Literal, ConditionalLiteral, Aggregate, BodyAggregate, TheoryAtom, Disjoint> data; }; std::ostream &operator<<(std::ostream &out, BodyLiteral const &x); // {{{2 theory definitions enum class TheoryOperatorType : clingo_ast_theory_operator_type_t { Unary = clingo_ast_theory_operator_type_unary, BinaryLeft = clingo_ast_theory_operator_type_binary_left, BinaryRight = clingo_ast_theory_operator_type_binary_right }; inline std::ostream &operator<<(std::ostream &out, TheoryOperatorType op) { switch (op) { case TheoryOperatorType::Unary: { out << "unary"; break; } case TheoryOperatorType::BinaryLeft: { out << "binary, left"; break; } case TheoryOperatorType::BinaryRight: { out << "binary, right"; break; } } return out; } struct TheoryOperatorDefinition { Location location; char const *name; unsigned priority; TheoryOperatorType type; }; std::ostream &operator<<(std::ostream &out, TheoryOperatorDefinition const &x); struct TheoryTermDefinition { Location location; char const *name; std::vector<TheoryOperatorDefinition> operators; }; std::ostream &operator<<(std::ostream &out, TheoryTermDefinition const &x); struct TheoryGuardDefinition { char const *term; std::vector<char const *> operators; }; std::ostream &operator<<(std::ostream &out, TheoryGuardDefinition const &x); enum class TheoryAtomDefinitionType : clingo_ast_theory_atom_definition_type_t { Head = clingo_ast_theory_atom_definition_type_head, Body = clingo_ast_theory_atom_definition_type_body, Any = clingo_ast_theory_atom_definition_type_any, Directive = clingo_ast_theory_atom_definition_type_directive }; inline std::ostream &operator<<(std::ostream &out, TheoryAtomDefinitionType op) { switch (op) { case TheoryAtomDefinitionType::Head: { out << "head"; break; } case TheoryAtomDefinitionType::Body: { out << "body"; break; } case TheoryAtomDefinitionType::Any: { out << "any"; break; } case TheoryAtomDefinitionType::Directive: { out << "directive"; break; } } return out; } struct TheoryAtomDefinition { Location location; TheoryAtomDefinitionType type; char const *name; unsigned arity; char const *elements; Optional<TheoryGuardDefinition> guard; }; std::ostream &operator<<(std::ostream &out, TheoryAtomDefinition const &x); struct TheoryDefinition { char const *name; std::vector<TheoryTermDefinition> terms; std::vector<TheoryAtomDefinition> atoms; }; std::ostream &operator<<(std::ostream &out, TheoryDefinition const &x); // {{{2 statements // rule struct Rule { HeadLiteral head; std::vector<BodyLiteral> body; }; std::ostream &operator<<(std::ostream &out, Rule const &x); // definition struct Definition { char const *name; Term value; bool is_default; }; std::ostream &operator<<(std::ostream &out, Definition const &x); // show struct ShowSignature { Signature signature; bool csp; }; std::ostream &operator<<(std::ostream &out, ShowSignature const &x); struct ShowTerm { Term term; std::vector<BodyLiteral> body; bool csp; }; std::ostream &operator<<(std::ostream &out, ShowTerm const &x); // minimize struct Minimize { Term weight; Term priority; std::vector<Term> tuple; std::vector<BodyLiteral> body; }; std::ostream &operator<<(std::ostream &out, Minimize const &x); // script enum class ScriptType : clingo_ast_script_type_t { Lua = clingo_ast_script_type_lua, Python = clingo_ast_script_type_python }; inline std::ostream &operator<<(std::ostream &out, ScriptType op) { switch (op) { case ScriptType::Lua: { out << "lua"; break; } case ScriptType::Python: { out << "python"; break; } } return out; } struct Script { ScriptType type; char const *code; }; std::ostream &operator<<(std::ostream &out, Script const &x); // program struct Program { char const *name; std::vector<Id> parameters; }; std::ostream &operator<<(std::ostream &out, Program const &x); // external struct External { Term atom; std::vector<BodyLiteral> body; }; std::ostream &operator<<(std::ostream &out, External const &x); // edge struct Edge { Term u; Term v; std::vector<BodyLiteral> body; }; std::ostream &operator<<(std::ostream &out, Edge const &x); // heuristic struct Heuristic { Term atom; std::vector<BodyLiteral> body; Term bias; Term priority; Term modifier; }; std::ostream &operator<<(std::ostream &out, Heuristic const &x); // project struct ProjectAtom { Term atom; std::vector<BodyLiteral> body; }; std::ostream &operator<<(std::ostream &out, ProjectAtom const &x); struct ProjectSignature { Signature signature; }; std::ostream &operator<<(std::ostream &out, ProjectSignature const &x); // statement struct Statement { Location location; Variant<Rule, Definition, ShowSignature, ShowTerm, Minimize, Script, Program, External, Edge, Heuristic, ProjectAtom, ProjectSignature, TheoryDefinition> data; }; std::ostream &operator<<(std::ostream &out, Statement const &x); } // namespace AST // {{{1 backend class Backend { public: explicit Backend(clingo_backend_t *backend) : backend_(backend) { } void rule(bool choice, AtomSpan head, LiteralSpan body); void weight_rule(bool choice, AtomSpan head, weight_t lower, WeightedLiteralSpan body); void minimize(weight_t prio, WeightedLiteralSpan body); void project(AtomSpan atoms); void external(atom_t atom, ExternalType type); void assume(LiteralSpan lits); void heuristic(atom_t atom, HeuristicType type, int bias, unsigned priority, LiteralSpan condition); void acyc_edge(int node_u, int node_v, LiteralSpan condition); atom_t add_atom(); clingo_backend_t *to_c() const { return backend_; } private: clingo_backend_t *backend_; }; // {{{1 statistics template <class T> class KeyIterator : public std::iterator<std::random_access_iterator_tag, char const *, ptrdiff_t, ValuePointer<char const *>, char const *> { public: explicit KeyIterator(T const *map, size_t index = 0) : map_(map) , index_(index) { } KeyIterator& operator++() { ++index_; return *this; } KeyIterator operator++(int) { KeyIterator t(*this); ++*this; return t; } KeyIterator& operator--() { --index_; return *this; } KeyIterator operator--(int) { KeyIterator t(*this); --*this; return t; } KeyIterator& operator+=(difference_type n) { index_ += n; return *this; } KeyIterator& operator-=(difference_type n) { index_ -= n; return *this; } friend KeyIterator operator+(KeyIterator it, difference_type n) { return KeyIterator{it.map_, it.index_ + n}; } friend KeyIterator operator+(difference_type n, KeyIterator it) { return KeyIterator{it.map_, it.index_ + n}; } friend KeyIterator operator-(KeyIterator it, difference_type n) { return KeyIterator{it.map_, it.index_ - n}; } friend difference_type operator-(KeyIterator a, KeyIterator b) { return a.index_ - b.index_; } reference operator*() { return map_->key_name(index_); } pointer operator->() { return pointer(**this); } friend void swap(KeyIterator& lhs, KeyIterator& rhs) { std::swap(lhs.map_, rhs.map_); std::swap(lhs.index_, rhs.index_); } friend bool operator==(const KeyIterator& lhs, const KeyIterator& rhs) { return lhs.index_ == rhs.index_; } friend bool operator!=(const KeyIterator& lhs, const KeyIterator& rhs) { return !(lhs == rhs); } friend bool operator< (KeyIterator lhs, KeyIterator rhs) { return (lhs.index_ + 1) < (rhs.index_ + 1); } friend bool operator> (KeyIterator lhs, KeyIterator rhs) { return rhs < lhs; } friend bool operator<=(KeyIterator lhs, KeyIterator rhs) { return !(lhs > rhs); } friend bool operator>=(KeyIterator lhs, KeyIterator rhs) { return !(lhs < rhs); } private: T const *map_; size_t index_; }; template <class T, class P=T*> class ArrayIterator : public std::iterator<std::random_access_iterator_tag, T, ptrdiff_t, ValuePointer<T>, T> { public: using base = std::iterator<std::random_access_iterator_tag, T, ptrdiff_t, ValuePointer<T>, T>; using difference_type = typename base::difference_type; using reference = typename base::reference; using pointer = typename base::pointer; explicit ArrayIterator(P arr, size_t index = 0) : arr_(arr) , index_(index) { } ArrayIterator& operator++() { ++index_; return *this; } ArrayIterator operator++(int) { ArrayIterator t(*this); ++*this; return t; } ArrayIterator& operator--() { --index_; return *this; } ArrayIterator operator--(int) { ArrayIterator t(*this); --*this; return t; } ArrayIterator& operator+=(difference_type n) { index_ += n; return *this; } ArrayIterator& operator-=(difference_type n) { index_ -= n; return *this; } friend ArrayIterator operator+(ArrayIterator it, difference_type n) { return ArrayIterator{it.arr_, it.index_ + n}; } friend ArrayIterator operator+(difference_type n, ArrayIterator it) { return ArrayIterator{it.arr_, it.index_ + n}; } friend ArrayIterator operator-(ArrayIterator it, difference_type n) { return ArrayIterator{it.arr_, it.index_ - n}; } friend difference_type operator-(ArrayIterator a, ArrayIterator b) { return a.index_ - b.index_; } reference operator*() { return (*arr_)[index_]; } pointer operator->() { return pointer(**this); } friend void swap(ArrayIterator& lhs, ArrayIterator& rhs) { std::swap(lhs.arr_, rhs.arr_); std::swap(lhs.index_, rhs.index_); } friend bool operator==(const ArrayIterator& lhs, const ArrayIterator& rhs) { return lhs.index_ == rhs.index_; } friend bool operator!=(const ArrayIterator& lhs, const ArrayIterator& rhs) { return !(lhs == rhs); } friend bool operator< (ArrayIterator lhs, ArrayIterator rhs) { return (lhs.index_ + 1) < (rhs.index_ + 1); } friend bool operator> (ArrayIterator lhs, ArrayIterator rhs) { return rhs < lhs; } friend bool operator<=(ArrayIterator lhs, ArrayIterator rhs) { return !(lhs > rhs); } friend bool operator>=(ArrayIterator lhs, ArrayIterator rhs) { return !(lhs < rhs); } private: P arr_; size_t index_; }; enum class StatisticsType : clingo_statistics_type_t { Value = clingo_statistics_type_value, Array = clingo_statistics_type_array, Map = clingo_statistics_type_map }; class Statistics; using StatisticsKeyIterator = KeyIterator<Statistics>; using StatisticsArrayIterator = ArrayIterator<Statistics, Statistics const *>; using StatisticsKeyRange = IteratorRange<StatisticsKeyIterator>; class Statistics { friend class KeyIterator<Statistics>; public: explicit Statistics(clingo_statistics_t *stats, uint64_t key) : stats_(stats) , key_(key) { } // generic StatisticsType type() const; // arrays size_t size() const; Statistics operator[](size_t index) const; Statistics at(size_t index) const { return operator[](index); } StatisticsArrayIterator begin() const; StatisticsArrayIterator end() const; // maps Statistics operator[](char const *name) const; Statistics get(char const *name) { return operator[](name); } StatisticsKeyRange keys() const; // leafs double value() const; operator double() const { return value(); } clingo_statistics_t *to_c() const { return stats_; } private: char const *key_name(size_t index) const; clingo_statistics_t *stats_; uint64_t key_; }; // {{{1 configuration class Configuration; using ConfigurationArrayIterator = ArrayIterator<Configuration>; using ConfigurationKeyIterator = KeyIterator<Configuration>; using ConfigurationKeyRange = IteratorRange<ConfigurationKeyIterator>; class Configuration { friend class KeyIterator<Configuration>; public: explicit Configuration(clingo_configuration_t *conf, clingo_id_t key) : conf_(conf) , key_(key) { } // arrays bool is_array() const; Configuration operator[](size_t index); Configuration at(size_t index) { return operator[](index); } ConfigurationArrayIterator begin(); ConfigurationArrayIterator end(); size_t size() const; bool empty() const; // maps bool is_map() const; Configuration operator[](char const *name); Configuration get(char const *name) { return operator[](name); } ConfigurationKeyRange keys() const; // values bool is_value() const; bool is_assigned() const; std::string value() const; operator std::string() const { return value(); } Configuration &operator=(char const *value); // generic char const *decription() const; clingo_configuration_t *to_c() const { return conf_; } private: char const *key_name(size_t index) const; clingo_configuration_t *conf_; unsigned key_; }; // {{{1 program builder class ProgramBuilder { public: explicit ProgramBuilder(clingo_program_builder_t *builder) : builder_(builder) { } void begin(); void add(AST::Statement const &stm); void end(); clingo_program_builder_t *to_c() const { return builder_; } private: clingo_program_builder_t *builder_; }; // {{{1 control class Part { public: Part(char const *name, SymbolSpan params) : part_{name, reinterpret_cast<clingo_symbol_t const*>(params.begin()), params.size()} { } explicit Part(clingo_part_t part) : part_(part) { } char const *name() const { return part_.name; } SymbolSpan params() const { return {reinterpret_cast<Symbol const*>(part_.params), part_.size}; } clingo_part_t const &to_c() const { return part_; } clingo_part_t &to_c() { return part_; } private: clingo_part_t part_; }; using SymbolSpanCallback = std::function<void (SymbolSpan)>; using PartSpan = Span<Part>; using GroundCallback = std::function<void (Location loc, char const *, SymbolSpan, SymbolSpanCallback)>; using StringSpan = Span<char const *>; enum class ErrorCode : clingo_error_t { Runtime = clingo_error_runtime, Logic = clingo_error_logic, BadAlloc = clingo_error_bad_alloc, Unknown = clingo_error_unknown, }; inline std::ostream &operator<<(std::ostream &out, ErrorCode code) { out << clingo_error_string(static_cast<clingo_error_t>(code)); return out; } enum class WarningCode : clingo_warning_t { OperationUndefined = clingo_warning_operation_undefined, RuntimeError = clingo_warning_runtime_error, AtomUndefined = clingo_warning_atom_undefined, FileIncluded = clingo_warning_file_included, VariableUnbounded = clingo_warning_variable_unbounded, GlobalVariable = clingo_warning_global_variable, Other = clingo_warning_other, }; using Logger = std::function<void (WarningCode, char const *)>; inline std::ostream &operator<<(std::ostream &out, WarningCode code) { out << clingo_warning_string(static_cast<clingo_warning_t>(code)); return out; } class Control { struct Impl; public: Control(StringSpan args = {}, Logger logger = nullptr, unsigned message_limit = 20); explicit Control(clingo_control_t *ctl); Control(Control &&c); Control(Control const &) = delete; Control &operator=(Control &&c); Control &operator=(Control const &c) = delete; ~Control() noexcept; void add(char const *name, StringSpan params, char const *part); void ground(PartSpan parts, GroundCallback cb = nullptr); SolveHandle solve(SymbolicLiteralSpan assumptions = {}, SolveEventHandler *handler = nullptr, bool asynchronous = false, bool yield = true); void assign_external(Symbol atom, TruthValue value); void release_external(Symbol atom); SymbolicAtoms symbolic_atoms() const; TheoryAtoms theory_atoms() const; void register_propagator(Propagator &propagator, bool sequential = false); void register_observer(GroundProgramObserver &observer, bool replace = false); void cleanup(); bool has_const(char const *name) const; Symbol get_const(char const *name) const; void interrupt() noexcept; void *claspFacade(); void load(char const *file); void use_enumeration_assumption(bool value); Backend backend(); ProgramBuilder builder(); template <class F> void with_builder(F f) { ProgramBuilder b = builder(); b.begin(); f(b); b.end(); } Configuration configuration(); Statistics statistics() const; clingo_control_t *to_c() const; private: Impl *impl_; }; // {{{1 global functions using StatementCallback = std::function<void (AST::Statement &&)>; void parse_program(char const *program, StatementCallback cb, Logger logger = nullptr, unsigned message_limit = 20); Symbol parse_term(char const *str, Logger logger = nullptr, unsigned message_limit = 20); char const *add_string(char const *str); std::tuple<int, int, int> version(); // }}}1 } // namespace Clingo //{{{1 implementation #define CLINGO_CALLBACK_TRY try #define CLINGO_CALLBACK_CATCH(ref) catch (...){ (ref) = std::current_exception(); return false; } return true #define CLINGO_TRY try #define CLINGO_CATCH catch (...){ Detail::handle_cxx_error(); return false; } return true namespace Clingo { // {{{2 details namespace Detail { inline void handle_error(bool ret) { if (!ret) { char const *msg = clingo_error_message(); if (!msg) { msg = "no message"; } switch (static_cast<clingo_error>(clingo_error_code())) { case clingo_error_runtime: { throw std::runtime_error(msg); } case clingo_error_logic: { throw std::logic_error(msg); } case clingo_error_bad_alloc: { throw std::bad_alloc(); } case clingo_error_unknown: { throw std::runtime_error(msg); } case clingo_error_success: { throw std::runtime_error(msg); } } } } inline void handle_error(bool ret, std::exception_ptr &exc) { if (!ret) { if (exc) { std::exception_ptr ptr = exc; exc = nullptr; std::rethrow_exception(ptr); } handle_error(false); } } enum class AssignState { Unassigned=0, Writing=1, Assigned=2 }; class AssignOnce { public: AssignOnce &operator=(std::exception_ptr x) { auto ua = AssignState::Unassigned; if (state_.compare_exchange_strong(ua, AssignState::Writing)) { val_ = x; state_ = AssignState::Assigned; } return *this; } std::exception_ptr &operator*() { static std::exception_ptr null = nullptr; // NOTE: this is not necessarily the exception that caused the search to stop // but just the first that has been set return state_ == AssignState::Assigned ? val_ : null; } void reset() { state_ = AssignState::Unassigned; val_ = nullptr; } private: std::atomic<AssignState> state_; std::exception_ptr val_ = nullptr; }; inline void handle_error(bool ret, AssignOnce &exc) { if (!ret) { handle_error(ret, *exc); } } inline void handle_cxx_error() { try { throw; } catch (std::bad_alloc const &e) { clingo_set_error(clingo_error_bad_alloc, e.what()); return; } catch (std::runtime_error const &e) { clingo_set_error(clingo_error_runtime, e.what()); return; } catch (std::logic_error const &e) { clingo_set_error(clingo_error_logic, e.what()); return; } catch (...) { } clingo_set_error(clingo_error_unknown, "unknown error"); } template <class S, class P, class ...Args> std::string to_string(S size, P print, Args ...args) { std::vector<char> ret; size_t n; Detail::handle_error(size(std::forward<Args>(args)..., &n)); ret.resize(n); Detail::handle_error(print(std::forward<Args>(args)..., ret.data(), n)); return std::string(ret.begin(), ret.end()-1); } } // namespace Detail // {{{2 signature inline Signature::Signature(char const *name, uint32_t arity, bool positive) { Detail::handle_error(clingo_signature_create(name, arity, positive, &sig_)); } inline char const *Signature::name() const { return clingo_signature_name(sig_); } inline uint32_t Signature::arity() const { return clingo_signature_arity(sig_); } inline bool Signature::positive() const { return clingo_signature_is_positive(sig_); } inline bool Signature::negative() const { return clingo_signature_is_negative(sig_); } inline size_t Signature::hash() const { return clingo_signature_hash(sig_); } inline bool operator==(Signature a, Signature b) { return clingo_signature_is_equal_to(a.to_c(), b.to_c()); } inline bool operator!=(Signature a, Signature b) { return !clingo_signature_is_equal_to(a.to_c(), b.to_c()); } inline bool operator< (Signature a, Signature b) { return clingo_signature_is_less_than(a.to_c(), b.to_c()); } inline bool operator<=(Signature a, Signature b) { return !clingo_signature_is_less_than(b.to_c(), a.to_c()); } inline bool operator> (Signature a, Signature b) { return clingo_signature_is_less_than(b.to_c(), a.to_c()); } inline bool operator>=(Signature a, Signature b) { return !clingo_signature_is_less_than(a.to_c(), b.to_c()); } // {{{2 symbol inline Symbol::Symbol() { clingo_symbol_create_number(0, &sym_); } inline Symbol::Symbol(clingo_symbol_t sym) : sym_(sym) { } inline Symbol Number(int num) { clingo_symbol_t sym; clingo_symbol_create_number(num, &sym); return Symbol(sym); } inline Symbol Supremum() { clingo_symbol_t sym; clingo_symbol_create_supremum(&sym); return Symbol(sym); } inline Symbol Infimum() { clingo_symbol_t sym; clingo_symbol_create_infimum(&sym); return Symbol(sym); } inline Symbol String(char const *str) { clingo_symbol_t sym; Detail::handle_error(clingo_symbol_create_string(str, &sym)); return Symbol(sym); } inline Symbol Id(char const *id, bool positive) { clingo_symbol_t sym; Detail::handle_error(clingo_symbol_create_id(id, positive, &sym)); return Symbol(sym); } inline Symbol Function(char const *name, SymbolSpan args, bool positive) { clingo_symbol_t sym; Detail::handle_error(clingo_symbol_create_function(name, reinterpret_cast<clingo_symbol_t const *>(args.begin()), args.size(), positive, &sym)); return Symbol(sym); } inline int Symbol::number() const { int ret; Detail::handle_error(clingo_symbol_number(sym_, &ret)); return ret; } inline char const *Symbol::name() const { char const *ret; Detail::handle_error(clingo_symbol_name(sym_, &ret)); return ret; } inline char const *Symbol::string() const { char const *ret; Detail::handle_error(clingo_symbol_string(sym_, &ret)); return ret; } inline bool Symbol::is_positive() const { bool ret; Detail::handle_error(clingo_symbol_is_positive(sym_, &ret)); return ret; } inline bool Symbol::is_negative() const { bool ret; Detail::handle_error(clingo_symbol_is_negative(sym_, &ret)); return ret; } inline SymbolSpan Symbol::arguments() const { clingo_symbol_t const *ret; size_t n; Detail::handle_error(clingo_symbol_arguments(sym_, &ret, &n)); return {reinterpret_cast<Symbol const *>(ret), n}; } inline SymbolType Symbol::type() const { return static_cast<SymbolType>(clingo_symbol_type(sym_)); } inline std::string Symbol::to_string() const { return Detail::to_string(clingo_symbol_to_string_size, clingo_symbol_to_string, sym_); } inline size_t Symbol::hash() const { return clingo_symbol_hash(sym_); } inline std::ostream &operator<<(std::ostream &out, Symbol sym) { out << sym.to_string(); return out; } inline bool operator==(Symbol a, Symbol b) { return clingo_symbol_is_equal_to(a.to_c(), b.to_c()); } inline bool operator!=(Symbol a, Symbol b) { return !clingo_symbol_is_equal_to(a.to_c(), b.to_c()); } inline bool operator< (Symbol a, Symbol b) { return clingo_symbol_is_less_than(a.to_c(), b.to_c()); } inline bool operator<=(Symbol a, Symbol b) { return !clingo_symbol_is_less_than(b.to_c(), a.to_c()); } inline bool operator> (Symbol a, Symbol b) { return clingo_symbol_is_less_than(b.to_c(), a.to_c()); } inline bool operator>=(Symbol a, Symbol b) { return !clingo_symbol_is_less_than(a.to_c(), b.to_c()); } // {{{2 symbolic atoms inline Symbol SymbolicAtom::symbol() const { clingo_symbol_t ret; clingo_symbolic_atoms_symbol(atoms_, range_, &ret); return Symbol(ret); } inline clingo_literal_t SymbolicAtom::literal() const { clingo_literal_t ret; clingo_symbolic_atoms_literal(atoms_, range_, &ret); return ret; } inline bool SymbolicAtom::is_fact() const { bool ret; clingo_symbolic_atoms_is_fact(atoms_, range_, &ret); return ret; } inline bool SymbolicAtom::is_external() const { bool ret; clingo_symbolic_atoms_is_external(atoms_, range_, &ret); return ret; } inline SymbolicAtomIterator &SymbolicAtomIterator::operator++() { clingo_symbolic_atom_iterator_t range; Detail::handle_error(clingo_symbolic_atoms_next(atoms_, range_, &range)); range_ = range; return *this; } inline SymbolicAtomIterator::operator bool() const { bool ret; Detail::handle_error(clingo_symbolic_atoms_is_valid(atoms_, range_, &ret)); return ret; } inline bool SymbolicAtomIterator::operator==(SymbolicAtomIterator it) const { bool ret = atoms_ == it.atoms_; if (ret) { Detail::handle_error(clingo_symbolic_atoms_iterator_is_equal_to(atoms_, range_, it.range_, &ret)); } return ret; } inline SymbolicAtomIterator SymbolicAtoms::begin() const { clingo_symbolic_atom_iterator_t it; Detail::handle_error(clingo_symbolic_atoms_begin(atoms_, nullptr, &it)); return SymbolicAtomIterator{atoms_, it}; } inline SymbolicAtomIterator SymbolicAtoms::begin(Signature sig) const { clingo_symbolic_atom_iterator_t it; Detail::handle_error(clingo_symbolic_atoms_begin(atoms_, &sig.to_c(), &it)); return SymbolicAtomIterator{atoms_, it}; } inline SymbolicAtomIterator SymbolicAtoms::end() const { clingo_symbolic_atom_iterator_t it; Detail::handle_error(clingo_symbolic_atoms_end(atoms_, &it)); return SymbolicAtomIterator{atoms_, it}; } inline SymbolicAtomIterator SymbolicAtoms::find(Symbol atom) const { clingo_symbolic_atom_iterator_t it; Detail::handle_error(clingo_symbolic_atoms_find(atoms_, atom.to_c(), &it)); return SymbolicAtomIterator{atoms_, it}; } inline std::vector<Signature> SymbolicAtoms::signatures() const { size_t n; clingo_symbolic_atoms_signatures_size(atoms_, &n); Signature sig("", 0); std::vector<Signature> ret; ret.resize(n, sig); Detail::handle_error(clingo_symbolic_atoms_signatures(atoms_, reinterpret_cast<clingo_signature_t *>(ret.data()), n)); return ret; } inline size_t SymbolicAtoms::length() const { size_t ret; Detail::handle_error(clingo_symbolic_atoms_size(atoms_, &ret)); return ret; } // {{{2 theory atoms inline TheoryTermType TheoryTerm::type() const { clingo_theory_term_type_t ret; Detail::handle_error(clingo_theory_atoms_term_type(atoms_, id_, &ret)); return static_cast<TheoryTermType>(ret); } inline int TheoryTerm::number() const { int ret; Detail::handle_error(clingo_theory_atoms_term_number(atoms_, id_, &ret)); return ret; } inline char const *TheoryTerm::name() const { char const *ret; Detail::handle_error(clingo_theory_atoms_term_name(atoms_, id_, &ret)); return ret; } inline TheoryTermSpan TheoryTerm::arguments() const { clingo_id_t const *ret; size_t n; Detail::handle_error(clingo_theory_atoms_term_arguments(atoms_, id_, &ret, &n)); return {ret, n, ToTheoryIterator<TheoryTermIterator>{atoms_}}; } inline std::ostream &operator<<(std::ostream &out, TheoryTerm term) { out << term.to_string(); return out; } inline std::string TheoryTerm::to_string() const { return Detail::to_string(clingo_theory_atoms_term_to_string_size, clingo_theory_atoms_term_to_string, atoms_, id_); } inline TheoryTermSpan TheoryElement::tuple() const { clingo_id_t const *ret; size_t n; Detail::handle_error(clingo_theory_atoms_element_tuple(atoms_, id_, &ret, &n)); return {ret, n, ToTheoryIterator<TheoryTermIterator>{atoms_}}; } inline LiteralSpan TheoryElement::condition() const { clingo_literal_t const *ret; size_t n; Detail::handle_error(clingo_theory_atoms_element_condition(atoms_, id_, &ret, &n)); return {ret, n}; } inline literal_t TheoryElement::condition_id() const { clingo_literal_t ret; Detail::handle_error(clingo_theory_atoms_element_condition_id(atoms_, id_, &ret)); return ret; } inline std::string TheoryElement::to_string() const { return Detail::to_string(clingo_theory_atoms_element_to_string_size, clingo_theory_atoms_element_to_string, atoms_, id_); } inline std::ostream &operator<<(std::ostream &out, TheoryElement term) { out << term.to_string(); return out; } inline TheoryElementSpan TheoryAtom::elements() const { clingo_id_t const *ret; size_t n; Detail::handle_error(clingo_theory_atoms_atom_elements(atoms_, id_, &ret, &n)); return {ret, n, ToTheoryIterator<TheoryElementIterator>{atoms_}}; } inline TheoryTerm TheoryAtom::term() const { clingo_id_t ret; Detail::handle_error(clingo_theory_atoms_atom_term(atoms_, id_, &ret)); return TheoryTerm{atoms_, ret}; } inline bool TheoryAtom::has_guard() const { bool ret; Detail::handle_error(clingo_theory_atoms_atom_has_guard(atoms_, id_, &ret)); return ret; } inline literal_t TheoryAtom::literal() const { clingo_literal_t ret; Detail::handle_error(clingo_theory_atoms_atom_literal(atoms_, id_, &ret)); return ret; } inline std::pair<char const *, TheoryTerm> TheoryAtom::guard() const { char const *name; clingo_id_t term; Detail::handle_error(clingo_theory_atoms_atom_guard(atoms_, id_, &name, &term)); return {name, TheoryTerm{atoms_, term}}; } inline std::string TheoryAtom::to_string() const { return Detail::to_string(clingo_theory_atoms_atom_to_string_size, clingo_theory_atoms_atom_to_string, atoms_, id_); } inline std::ostream &operator<<(std::ostream &out, TheoryAtom term) { out << term.to_string(); return out; } inline TheoryAtomIterator TheoryAtoms::begin() const { return TheoryAtomIterator{atoms_, 0}; } inline TheoryAtomIterator TheoryAtoms::end() const { return TheoryAtomIterator{atoms_, clingo_id_t(size())}; } inline size_t TheoryAtoms::size() const { size_t ret; Detail::handle_error(clingo_theory_atoms_size(atoms_, &ret)); return ret; } // {{{2 assignment inline bool Assignment::has_conflict() const { return clingo_assignment_has_conflict(ass_); } inline uint32_t Assignment::decision_level() const { return clingo_assignment_decision_level(ass_); } inline bool Assignment::has_literal(literal_t lit) const { return clingo_assignment_has_literal(ass_, lit); } inline TruthValue Assignment::truth_value(literal_t lit) const { clingo_truth_value_t ret; Detail::handle_error(clingo_assignment_truth_value(ass_, lit, &ret)); return static_cast<TruthValue>(ret); } inline uint32_t Assignment::level(literal_t lit) const { uint32_t ret; Detail::handle_error(clingo_assignment_level(ass_, lit, &ret)); return ret; } inline literal_t Assignment::decision(uint32_t level) const { literal_t ret; Detail::handle_error(clingo_assignment_decision(ass_, level, &ret)); return ret; } inline bool Assignment::is_fixed(literal_t lit) const { bool ret; Detail::handle_error(clingo_assignment_is_fixed(ass_, lit, &ret)); return ret; } inline bool Assignment::is_true(literal_t lit) const { bool ret; Detail::handle_error(clingo_assignment_is_true(ass_, lit, &ret)); return ret; } inline bool Assignment::is_false(literal_t lit) const { bool ret; Detail::handle_error(clingo_assignment_is_false(ass_, lit, &ret)); return ret; } inline size_t Assignment::size() const { return clingo_assignment_size(ass_); } inline size_t Assignment::max_size() const { return clingo_assignment_max_size(ass_); } inline bool Assignment::is_total() const { return clingo_assignment_is_total(ass_); } // {{{2 propagate init inline literal_t PropagateInit::solver_literal(literal_t lit) const { literal_t ret; Detail::handle_error(clingo_propagate_init_solver_literal(init_, lit, &ret)); return ret; } inline void PropagateInit::add_watch(literal_t lit) { Detail::handle_error(clingo_propagate_init_add_watch(init_, lit)); } inline int PropagateInit::number_of_threads() const { return clingo_propagate_init_number_of_threads(init_); } inline SymbolicAtoms PropagateInit::symbolic_atoms() const { clingo_symbolic_atoms_t *ret; Detail::handle_error(clingo_propagate_init_symbolic_atoms(init_, &ret)); return SymbolicAtoms{ret}; } inline TheoryAtoms PropagateInit::theory_atoms() const { clingo_theory_atoms_t *ret; Detail::handle_error(clingo_propagate_init_theory_atoms(init_, &ret)); return TheoryAtoms{ret}; } inline PropagatorCheckMode PropagateInit::get_check_mode() const { return static_cast<PropagatorCheckMode>(clingo_propagate_init_get_check_mode(init_)); } inline void PropagateInit::set_check_mode(PropagatorCheckMode mode) { clingo_propagate_init_set_check_mode(init_, mode); } // {{{2 propagate control inline id_t PropagateControl::thread_id() const { return clingo_propagate_control_thread_id(ctl_); } inline Assignment PropagateControl::assignment() const { return Assignment{clingo_propagate_control_assignment(ctl_)}; } inline literal_t PropagateControl::add_literal() { clingo_literal_t ret; Detail::handle_error(clingo_propagate_control_add_literal(ctl_, &ret)); return ret; } inline void PropagateControl::add_watch(literal_t literal) { Detail::handle_error(clingo_propagate_control_add_watch(ctl_, literal)); } inline bool PropagateControl::has_watch(literal_t literal) const { return clingo_propagate_control_has_watch(ctl_, literal); } inline void PropagateControl::remove_watch(literal_t literal) { clingo_propagate_control_remove_watch(ctl_, literal); } inline bool PropagateControl::add_clause(LiteralSpan clause, ClauseType type) { bool ret; Detail::handle_error(clingo_propagate_control_add_clause(ctl_, clause.begin(), clause.size(), static_cast<clingo_clause_type_t>(type), &ret)); return ret; } inline bool PropagateControl::propagate() { bool ret; Detail::handle_error(clingo_propagate_control_propagate(ctl_, &ret)); return ret; } // {{{2 propagator inline void Propagator::init(PropagateInit &) { } inline void Propagator::propagate(PropagateControl &, LiteralSpan) { } inline void Propagator::undo(PropagateControl const &, LiteralSpan) { } inline void Propagator::check(PropagateControl &) { } // {{{2 solve control inline SymbolicAtoms SolveControl::symbolic_atoms() { clingo_symbolic_atoms_t *atoms; Detail::handle_error(clingo_solve_control_symbolic_atoms(ctl_, &atoms)); return SymbolicAtoms{atoms}; } inline void SolveControl::add_clause(SymbolicLiteralSpan clause) { std::vector<literal_t> lits; auto atoms = symbolic_atoms(); for (auto &x : clause) { auto it = atoms.find(x.symbol()); if (it != atoms.end()) { auto lit = it->literal(); lits.emplace_back(x.is_positive() ? lit : -lit); } else if (x.is_negative()) { return; } } add_clause(LiteralSpan{lits}); } inline void SolveControl::add_clause(LiteralSpan clause) { Detail::handle_error(clingo_solve_control_add_clause(ctl_, reinterpret_cast<clingo_literal_t const *>(clause.begin()), clause.size())); } // {{{2 model inline Model::Model(clingo_model_t *model) : model_(model) { } inline bool Model::contains(Symbol atom) const { bool ret; Detail::handle_error(clingo_model_contains(model_, atom.to_c(), &ret)); return ret; } inline CostVector Model::cost() const { CostVector ret; size_t n; Detail::handle_error(clingo_model_cost_size(model_, &n)); ret.resize(n); Detail::handle_error(clingo_model_cost(model_, ret.data(), n)); return ret; } inline SymbolVector Model::symbols(ShowType show) const { SymbolVector ret; size_t n; Detail::handle_error(clingo_model_symbols_size(model_, show, &n)); ret.resize(n); Detail::handle_error(clingo_model_symbols(model_, show, reinterpret_cast<clingo_symbol_t *>(ret.data()), n)); return ret; } inline uint64_t Model::number() const { uint64_t ret; Detail::handle_error(clingo_model_number(model_, &ret)); return ret; } inline bool Model::optimality_proven() const { bool ret; Detail::handle_error(clingo_model_optimality_proven(model_, &ret)); return ret; } inline SolveControl Model::context() const { clingo_solve_control_t *ret; Detail::handle_error(clingo_model_context(model_, &ret)); return SolveControl{ret}; } inline ModelType Model::type() const { clingo_model_type_t ret; Detail::handle_error(clingo_model_type(model_, &ret)); return static_cast<ModelType>(ret); } inline id_t Model::thread_id() const { id_t ret; Detail::handle_error(clingo_model_thread_id(model_, &ret)); return ret; } // {{{2 solve handle namespace Detail { } // namespace Detail inline SolveHandle::SolveHandle() : iter_(nullptr) , exception_(nullptr) { } inline SolveHandle::SolveHandle(clingo_solve_handle_t *it, Detail::AssignOnce &ptr) : iter_(it) , exception_(&ptr) { } inline SolveHandle::SolveHandle(SolveHandle &&it) : SolveHandle() { *this = std::move(it); } inline SolveHandle &SolveHandle::operator=(SolveHandle &&it) { iter_ = it.iter_; it.iter_ = nullptr; exception_ = it.exception_; it.exception_ = nullptr; return *this; } inline void SolveHandle::resume() { Detail::handle_error(clingo_solve_handle_resume(iter_), *exception_); } inline void SolveHandle::wait() { (void)wait(-1); } inline bool SolveHandle::wait(double timeout) { bool res = true; clingo_solve_handle_wait(iter_, timeout, &res); return res; } inline Model SolveHandle::model() { clingo_model_t *m = nullptr; Detail::handle_error(clingo_solve_handle_model(iter_, &m), *exception_); return Model{m}; } inline Model SolveHandle::next() { resume(); return model(); } inline SolveResult SolveHandle::get() { clingo_solve_result_bitset_t ret = 0; Detail::handle_error(clingo_solve_handle_get(iter_, &ret), *exception_); return SolveResult{ret}; } inline void SolveHandle::cancel() { Detail::handle_error(clingo_solve_handle_close(iter_), *exception_); } inline SolveHandle::~SolveHandle() { if (iter_) { Detail::handle_error(clingo_solve_handle_close(iter_), *exception_); } } // {{{2 backend inline void Backend::rule(bool choice, AtomSpan head, LiteralSpan body) { Detail::handle_error(clingo_backend_rule(backend_, choice, head.begin(), head.size(), body.begin(), body.size())); } inline void Backend::weight_rule(bool choice, AtomSpan head, weight_t lower, WeightedLiteralSpan body) { Detail::handle_error(clingo_backend_weight_rule(backend_, choice, head.begin(), head.size(), lower, reinterpret_cast<clingo_weighted_literal_t const *>(body.begin()), body.size())); } inline void Backend::minimize(weight_t prio, WeightedLiteralSpan body) { Detail::handle_error(clingo_backend_minimize(backend_, prio, reinterpret_cast<clingo_weighted_literal_t const *>(body.begin()), body.size())); } inline void Backend::project(AtomSpan atoms) { Detail::handle_error(clingo_backend_project(backend_, atoms.begin(), atoms.size())); } inline void Backend::external(atom_t atom, ExternalType type) { Detail::handle_error(clingo_backend_external(backend_, atom, static_cast<clingo_external_type_t>(type))); } inline void Backend::assume(LiteralSpan lits) { Detail::handle_error(clingo_backend_assume(backend_, lits.begin(), lits.size())); } inline void Backend::heuristic(atom_t atom, HeuristicType type, int bias, unsigned priority, LiteralSpan condition) { Detail::handle_error(clingo_backend_heuristic(backend_, atom, static_cast<clingo_heuristic_type_t>(type), bias, priority, condition.begin(), condition.size())); } inline void Backend::acyc_edge(int node_u, int node_v, LiteralSpan condition) { Detail::handle_error(clingo_backend_acyc_edge(backend_, node_u, node_v, condition.begin(), condition.size())); } inline atom_t Backend::add_atom() { clingo_atom_t ret; Detail::handle_error(clingo_backend_add_atom(backend_, &ret)); return ret; } // {{{2 statistics inline StatisticsType Statistics::type() const { clingo_statistics_type_t ret; Detail::handle_error(clingo_statistics_type(stats_, key_, &ret)); return StatisticsType(ret); } inline size_t Statistics::size() const { size_t ret; Detail::handle_error(clingo_statistics_array_size(stats_, key_, &ret)); return ret; } inline Statistics Statistics::operator[](size_t index) const { uint64_t ret; Detail::handle_error(clingo_statistics_array_at(stats_, key_, index, &ret)); return Statistics{stats_, ret}; } inline StatisticsArrayIterator Statistics::begin() const { return StatisticsArrayIterator{this, 0}; } inline StatisticsArrayIterator Statistics::end() const { return StatisticsArrayIterator{this, size()}; } inline Statistics Statistics::operator[](char const *name) const { uint64_t ret; Detail::handle_error(clingo_statistics_map_at(stats_, key_, name, &ret)); return Statistics{stats_, ret}; } inline StatisticsKeyRange Statistics::keys() const { size_t ret; Detail::handle_error(clingo_statistics_map_size(stats_, key_, &ret)); return StatisticsKeyRange{ StatisticsKeyIterator{this, 0}, StatisticsKeyIterator{this, ret} }; } inline double Statistics::value() const { double ret; Detail::handle_error(clingo_statistics_value_get(stats_, key_, &ret)); return ret; } inline char const *Statistics::key_name(size_t index) const { char const *ret; Detail::handle_error(clingo_statistics_map_subkey_name(stats_, key_, index, &ret)); return ret; } // {{{2 configuration inline Configuration Configuration::operator[](size_t index) { unsigned ret; Detail::handle_error(clingo_configuration_array_at(conf_, key_, index, &ret)); return Configuration{conf_, ret}; } inline ConfigurationArrayIterator Configuration::begin() { return ConfigurationArrayIterator{this, 0}; } inline ConfigurationArrayIterator Configuration::end() { return ConfigurationArrayIterator{this, size()}; } inline size_t Configuration::size() const { size_t n; Detail::handle_error(clingo_configuration_array_size(conf_, key_, &n)); return n; } inline bool Configuration::empty() const { return size() == 0; } inline Configuration Configuration::operator[](char const *name) { clingo_id_t ret; Detail::handle_error(clingo_configuration_map_at(conf_, key_, name, &ret)); return Configuration{conf_, ret}; } inline ConfigurationKeyRange Configuration::keys() const { size_t n; Detail::handle_error(clingo_configuration_map_size(conf_, key_, &n)); return ConfigurationKeyRange{ ConfigurationKeyIterator{this, size_t(0)}, ConfigurationKeyIterator{this, size_t(n)} }; } inline bool Configuration::is_value() const { clingo_configuration_type_bitset_t type; Detail::handle_error(clingo_configuration_type(conf_, key_, &type)); return type & clingo_configuration_type_value; } inline bool Configuration::is_array() const { clingo_configuration_type_bitset_t type; Detail::handle_error(clingo_configuration_type(conf_, key_, &type)); return (type & clingo_configuration_type_array) != 0; } inline bool Configuration::is_map() const { clingo_configuration_type_bitset_t type; Detail::handle_error(clingo_configuration_type(conf_, key_, &type)); return (type & clingo_configuration_type_map) != 0; } inline bool Configuration::is_assigned() const { bool ret; Detail::handle_error(clingo_configuration_value_is_assigned(conf_, key_, &ret)); return ret; } inline std::string Configuration::value() const { size_t n; Detail::handle_error(clingo_configuration_value_get_size(conf_, key_, &n)); std::vector<char> ret(n); Detail::handle_error(clingo_configuration_value_get(conf_, key_, ret.data(), n)); return std::string(ret.begin(), ret.end() - 1); } inline Configuration &Configuration::operator=(char const *value) { Detail::handle_error(clingo_configuration_value_set(conf_, key_, value)); return *this; } inline char const *Configuration::decription() const { char const *ret; Detail::handle_error(clingo_configuration_description(conf_, key_, &ret)); return ret; } inline char const *Configuration::key_name(size_t index) const { char const *ret; Detail::handle_error(clingo_configuration_map_subkey_name(conf_, key_, index, &ret)); return ret; } // {{{2 program builder namespace AST { namespace Detail { struct ASTToC { // {{{3 term clingo_ast_id_t convId(Id const &id) { return {id.location, id.id}; } struct TermTag {}; clingo_ast_term_t visit(Symbol const &x, TermTag) { clingo_ast_term_t ret; ret.type = clingo_ast_term_type_symbol; ret.symbol = x.to_c(); return ret; } clingo_ast_term_t visit(Variable const &x, TermTag) { clingo_ast_term_t ret; ret.type = clingo_ast_term_type_variable; ret.variable = x.name; return ret; } clingo_ast_term_t visit(UnaryOperation const &x, TermTag) { auto unary_operation = create_<clingo_ast_unary_operation_t>(); unary_operation->unary_operator = static_cast<clingo_ast_unary_operator_t>(x.unary_operator); unary_operation->argument = convTerm(x.argument); clingo_ast_term_t ret; ret.type = clingo_ast_term_type_unary_operation; ret.unary_operation = unary_operation; return ret; } clingo_ast_term_t visit(BinaryOperation const &x, TermTag) { auto binary_operation = create_<clingo_ast_binary_operation_t>(); binary_operation->binary_operator = static_cast<clingo_ast_binary_operator_t>(x.binary_operator); binary_operation->left = convTerm(x.left); binary_operation->right = convTerm(x.right); clingo_ast_term_t ret; ret.type = clingo_ast_term_type_binary_operation; ret.binary_operation = binary_operation; return ret; } clingo_ast_term_t visit(Interval const &x, TermTag) { auto interval = create_<clingo_ast_interval_t>(); interval->left = convTerm(x.left); interval->right = convTerm(x.right); clingo_ast_term_t ret; ret.type = clingo_ast_term_type_interval; ret.interval = interval; return ret; } clingo_ast_term_t visit(Function const &x, TermTag) { auto function = create_<clingo_ast_function_t>(); function->name = x.name; function->arguments = convTermVec(x.arguments); function->size = x.arguments.size(); clingo_ast_term_t ret; ret.type = x.external ? clingo_ast_term_type_external_function : clingo_ast_term_type_function; ret.function = function; return ret; } clingo_ast_term_t visit(Pool const &x, TermTag) { auto pool = create_<clingo_ast_pool_t>(); pool->arguments = convTermVec(x.arguments); pool->size = x.arguments.size(); clingo_ast_term_t ret; ret.type = clingo_ast_term_type_pool; ret.pool = pool; return ret; } clingo_ast_term_t convTerm(Term const &x) { auto ret = x.data.accept(*this, TermTag{}); ret.location = x.location; return ret; } clingo_ast_term_t *convTerm(Optional<Term> const &x) { return x ? create_(convTerm(*x.get())) : nullptr; } clingo_ast_term_t *convTermVec(std::vector<Term> const &x) { return createArray_(x, static_cast<clingo_ast_term_t (ASTToC::*)(Term const &)>(&ASTToC::convTerm)); } clingo_ast_csp_product_term_t convCSPProduct(CSPProduct const &x) { clingo_ast_csp_product_term_t ret; ret.location = x.location; ret.variable = convTerm(x.variable); ret.coefficient = convTerm(x.coefficient); return ret; } clingo_ast_csp_sum_term_t convCSPAdd(CSPSum const &x) { clingo_ast_csp_sum_term_t ret; ret.location = x.location; ret.terms = createArray_(x.terms, &ASTToC::convCSPProduct); ret.size = x.terms.size(); return ret; } clingo_ast_theory_unparsed_term_element_t convTheoryUnparsedTermElement(TheoryUnparsedTermElement const &x) { clingo_ast_theory_unparsed_term_element_t ret; ret.term = convTheoryTerm(x.term); ret.operators = createArray_(x.operators, &ASTToC::identity<char const *>); ret.size = x.operators.size(); return ret; } struct TheoryTermTag { }; clingo_ast_theory_term_t visit(Symbol const &term, TheoryTermTag) { clingo_ast_theory_term_t ret; ret.type = clingo_ast_theory_term_type_symbol; ret.symbol = term.to_c(); return ret; } clingo_ast_theory_term_t visit(Variable const &term, TheoryTermTag) { clingo_ast_theory_term_t ret; ret.type = clingo_ast_theory_term_type_variable; ret.variable = term.name; return ret; } clingo_ast_theory_term_t visit(TheoryTermSequence const &term, TheoryTermTag) { auto sequence = create_<clingo_ast_theory_term_array_t>(); sequence->terms = convTheoryTermVec(term.terms); sequence->size = term.terms.size(); clingo_ast_theory_term_t ret; switch (term.type) { case TheoryTermSequenceType::Set: { ret.type = clingo_ast_theory_term_type_set; break; } case TheoryTermSequenceType::List: { ret.type = clingo_ast_theory_term_type_list; break; } case TheoryTermSequenceType::Tuple: { ret.type = clingo_ast_theory_term_type_tuple; break; } } ret.set = sequence; return ret; } clingo_ast_theory_term_t visit(TheoryFunction const &term, TheoryTermTag) { auto function = create_<clingo_ast_theory_function_t>(); function->name = term.name; function->arguments = convTheoryTermVec(term.arguments); function->size = term.arguments.size(); clingo_ast_theory_term_t ret; ret.type = clingo_ast_theory_term_type_function; ret.function = function; return ret; } clingo_ast_theory_term_t visit(TheoryUnparsedTerm const &term, TheoryTermTag) { auto unparsed_term = create_<clingo_ast_theory_unparsed_term>(); unparsed_term->elements = createArray_(term.elements, &ASTToC::convTheoryUnparsedTermElement); unparsed_term->size = term.elements.size(); clingo_ast_theory_term_t ret; ret.type = clingo_ast_theory_term_type_unparsed_term; ret.unparsed_term = unparsed_term; return ret; } clingo_ast_theory_term_t convTheoryTerm(TheoryTerm const &x) { auto ret = x.data.accept(*this, TheoryTermTag{}); ret.location = x.location; return ret; } clingo_ast_theory_term_t *convTheoryTermVec(std::vector<TheoryTerm> const &x) { return createArray_(x, &ASTToC::convTheoryTerm); } // {{{3 literal clingo_ast_csp_guard_t convCSPGuard(CSPGuard const &x) { clingo_ast_csp_guard_t ret; ret.comparison = static_cast<clingo_ast_comparison_operator_t>(x.comparison); ret.term = convCSPAdd(x.term); return ret; } clingo_ast_literal_t visit(Boolean const &x) { clingo_ast_literal_t ret; ret.type = clingo_ast_literal_type_boolean; ret.boolean = x.value; return ret; } clingo_ast_literal_t visit(Term const &x) { clingo_ast_literal_t ret; ret.type = clingo_ast_literal_type_symbolic; ret.symbol = create_<clingo_ast_term_t>(convTerm(x)); return ret; } clingo_ast_literal_t visit(Comparison const &x) { auto comparison = create_<clingo_ast_comparison_t>(); comparison->comparison = static_cast<clingo_ast_comparison_operator_t>(x.comparison); comparison->left = convTerm(x.left); comparison->right = convTerm(x.right); clingo_ast_literal_t ret; ret.type = clingo_ast_literal_type_comparison; ret.comparison = comparison; return ret; } clingo_ast_literal_t visit(CSPLiteral const &x) { auto csp = create_<clingo_ast_csp_literal_t>(); csp->term = convCSPAdd(x.term); csp->guards = createArray_(x.guards, &ASTToC::convCSPGuard); csp->size = x.guards.size(); clingo_ast_literal_t ret; ret.type = clingo_ast_literal_type_csp; ret.csp_literal = csp; return ret; } clingo_ast_literal_t convLiteral(Literal const &x) { auto ret = x.data.accept(*this); ret.sign = static_cast<clingo_ast_sign_t>(x.sign); ret.location = x.location; return ret; } clingo_ast_literal_t *convLiteralVec(std::vector<Literal> const &x) { return createArray_(x, &ASTToC::convLiteral); } // {{{3 aggregates clingo_ast_aggregate_guard_t *convAggregateGuard(Optional<AggregateGuard> const &guard) { return guard ? create_<clingo_ast_aggregate_guard_t>({static_cast<clingo_ast_comparison_operator_t>(guard->comparison), convTerm(guard->term)}) : nullptr; } clingo_ast_conditional_literal_t convConditionalLiteral(ConditionalLiteral const &x) { clingo_ast_conditional_literal_t ret; ret.literal = convLiteral(x.literal); ret.condition = convLiteralVec(x.condition); ret.size = x.condition.size(); return ret; } clingo_ast_theory_guard_t *convTheoryGuard(Optional<TheoryGuard> const &x) { return x ? create_<clingo_ast_theory_guard_t>({x->operator_name, convTheoryTerm(x->term)}) : nullptr; } clingo_ast_theory_atom_element_t convTheoryAtomElement(TheoryAtomElement const &x) { clingo_ast_theory_atom_element_t ret; ret.tuple = convTheoryTermVec(x.tuple); ret.tuple_size = x.tuple.size(); ret.condition = convLiteralVec(x.condition); ret.condition_size = x.condition.size(); return ret; } clingo_ast_body_aggregate_element_t convBodyAggregateElement(BodyAggregateElement const &x) { clingo_ast_body_aggregate_element_t ret; ret.tuple = convTermVec(x.tuple); ret.tuple_size = x.tuple.size(); ret.condition = convLiteralVec(x.condition); ret.condition_size = x.condition.size(); return ret; } clingo_ast_head_aggregate_element_t convHeadAggregateElement(HeadAggregateElement const &x) { clingo_ast_head_aggregate_element_t ret; ret.tuple = convTermVec(x.tuple); ret.tuple_size = x.tuple.size(); ret.conditional_literal = convConditionalLiteral(x.condition); return ret; } clingo_ast_aggregate_t convAggregate(Aggregate const &x) { clingo_ast_aggregate_t ret; ret.left_guard = convAggregateGuard(x.left_guard); ret.right_guard = convAggregateGuard(x.right_guard); ret.size = x.elements.size(); ret.elements = createArray_(x.elements, &ASTToC::convConditionalLiteral); return ret; } clingo_ast_theory_atom_t convTheoryAtom(TheoryAtom const &x) { clingo_ast_theory_atom_t ret; ret.term = convTerm(x.term); ret.guard = convTheoryGuard(x.guard); ret.elements = createArray_(x.elements, &ASTToC::convTheoryAtomElement); ret.size = x.elements.size(); return ret; } clingo_ast_disjoint_element_t convDisjointElement(DisjointElement const &x) { clingo_ast_disjoint_element_t ret; ret.location = x.location; ret.tuple = convTermVec(x.tuple); ret.tuple_size = x.tuple.size(); ret.term = convCSPAdd(x.term); ret.condition = convLiteralVec(x.condition); ret.condition_size = x.condition.size(); return ret; } // {{{3 head literal struct HeadLiteralTag { }; clingo_ast_head_literal_t visit(Literal const &x, HeadLiteralTag) { clingo_ast_head_literal_t ret; ret.type = clingo_ast_head_literal_type_literal; ret.literal = create_<clingo_ast_literal_t>(convLiteral(x)); return ret; } clingo_ast_head_literal_t visit(Disjunction const &x, HeadLiteralTag) { auto disjunction = create_<clingo_ast_disjunction_t>(); disjunction->size = x.elements.size(); disjunction->elements = createArray_(x.elements, &ASTToC::convConditionalLiteral); clingo_ast_head_literal_t ret; ret.type = clingo_ast_head_literal_type_disjunction; ret.disjunction = disjunction; return ret; } clingo_ast_head_literal_t visit(Aggregate const &x, HeadLiteralTag) { clingo_ast_head_literal_t ret; ret.type = clingo_ast_head_literal_type_aggregate; ret.aggregate = create_<clingo_ast_aggregate_t>(convAggregate(x)); return ret; } clingo_ast_head_literal_t visit(HeadAggregate const &x, HeadLiteralTag) { auto head_aggregate = create_<clingo_ast_head_aggregate_t>(); head_aggregate->left_guard = convAggregateGuard(x.left_guard); head_aggregate->right_guard = convAggregateGuard(x.right_guard); head_aggregate->function = static_cast<clingo_ast_aggregate_function_t>(x.function); head_aggregate->size = x.elements.size(); head_aggregate->elements = createArray_(x.elements, &ASTToC::convHeadAggregateElement); clingo_ast_head_literal_t ret; ret.type = clingo_ast_head_literal_type_head_aggregate; ret.head_aggregate = head_aggregate; return ret; } clingo_ast_head_literal_t visit(TheoryAtom const &x, HeadLiteralTag) { clingo_ast_head_literal_t ret; ret.type = clingo_ast_head_literal_type_theory_atom; ret.theory_atom = create_<clingo_ast_theory_atom_t>(convTheoryAtom(x)); return ret; } clingo_ast_head_literal_t convHeadLiteral(HeadLiteral const &lit) { auto ret = lit.data.accept(*this, HeadLiteralTag{}); ret.location = lit.location; return ret; } // {{{3 body literal struct BodyLiteralTag { }; clingo_ast_body_literal_t visit(Literal const &x, BodyLiteralTag) { clingo_ast_body_literal_t ret; ret.type = clingo_ast_body_literal_type_literal; ret.literal = create_<clingo_ast_literal_t>(convLiteral(x)); return ret; } clingo_ast_body_literal_t visit(ConditionalLiteral const &x, BodyLiteralTag) { clingo_ast_body_literal_t ret; ret.type = clingo_ast_body_literal_type_conditional; ret.conditional = create_<clingo_ast_conditional_literal_t>(convConditionalLiteral(x)); return ret; } clingo_ast_body_literal_t visit(Aggregate const &x, BodyLiteralTag) { clingo_ast_body_literal_t ret; ret.type = clingo_ast_body_literal_type_aggregate; ret.aggregate = create_<clingo_ast_aggregate_t>(convAggregate(x)); return ret; } clingo_ast_body_literal_t visit(BodyAggregate const &x, BodyLiteralTag) { auto body_aggregate = create_<clingo_ast_body_aggregate_t>(); body_aggregate->left_guard = convAggregateGuard(x.left_guard); body_aggregate->right_guard = convAggregateGuard(x.right_guard); body_aggregate->function = static_cast<clingo_ast_aggregate_function_t>(x.function); body_aggregate->size = x.elements.size(); body_aggregate->elements = createArray_(x.elements, &ASTToC::convBodyAggregateElement); clingo_ast_body_literal_t ret; ret.type = clingo_ast_body_literal_type_body_aggregate; ret.body_aggregate = body_aggregate; return ret; } clingo_ast_body_literal_t visit(TheoryAtom const &x, BodyLiteralTag) { clingo_ast_body_literal_t ret; ret.type = clingo_ast_body_literal_type_theory_atom; ret.theory_atom = create_<clingo_ast_theory_atom_t>(convTheoryAtom(x)); return ret; } clingo_ast_body_literal_t visit(Disjoint const &x, BodyLiteralTag) { auto disjoint = create_<clingo_ast_disjoint_t>(); disjoint->size = x.elements.size(); disjoint->elements = createArray_(x.elements, &ASTToC::convDisjointElement); clingo_ast_body_literal_t ret; ret.type = clingo_ast_body_literal_type_disjoint; ret.disjoint = disjoint; return ret; } clingo_ast_body_literal_t convBodyLiteral(BodyLiteral const &x) { auto ret = x.data.accept(*this, BodyLiteralTag{}); ret.sign = static_cast<clingo_ast_sign_t>(x.sign); ret.location = x.location; return ret; } clingo_ast_body_literal_t* convBodyLiteralVec(std::vector<BodyLiteral> const &x) { return createArray_(x, &ASTToC::convBodyLiteral); } // {{{3 theory definitions clingo_ast_theory_operator_definition_t convTheoryOperatorDefinition(TheoryOperatorDefinition const &x) { clingo_ast_theory_operator_definition_t ret; ret.type = static_cast<clingo_ast_theory_operator_type_t>(x.type); ret.priority = x.priority; ret.location = x.location; ret.name = x.name; return ret; } clingo_ast_theory_term_definition_t convTheoryTermDefinition(TheoryTermDefinition const &x) { clingo_ast_theory_term_definition_t ret; ret.name = x.name; ret.location = x.location; ret.operators = createArray_(x.operators, &ASTToC::convTheoryOperatorDefinition); ret.size = x.operators.size(); return ret; } clingo_ast_theory_guard_definition_t convTheoryGuardDefinition(TheoryGuardDefinition const &x) { clingo_ast_theory_guard_definition_t ret; ret.term = x.term; ret.operators = createArray_(x.operators, &ASTToC::identity<char const *>); ret.size = x.operators.size(); return ret; } clingo_ast_theory_atom_definition_t convTheoryAtomDefinition(TheoryAtomDefinition const &x) { clingo_ast_theory_atom_definition_t ret; ret.name = x.name; ret.arity = x.arity; ret.location = x.location; ret.type = static_cast<clingo_ast_theory_atom_definition_type_t>(x.type); ret.elements = x.elements; ret.guard = x.guard ? create_<clingo_ast_theory_guard_definition_t>(convTheoryGuardDefinition(*x.guard.get())) : nullptr; return ret; } // {{{3 statement clingo_ast_statement_t visit(Rule const &x) { auto *rule = create_<clingo_ast_rule_t>(); rule->head = convHeadLiteral(x.head); rule->size = x.body.size(); rule->body = convBodyLiteralVec(x.body); clingo_ast_statement_t ret; ret.type = clingo_ast_statement_type_rule; ret.rule = rule; return ret; } clingo_ast_statement_t visit(Definition const &x) { auto *definition = create_<clingo_ast_definition_t>(); definition->is_default = x.is_default; definition->name = x.name; definition->value = convTerm(x.value); clingo_ast_statement_t ret; ret.type = clingo_ast_statement_type_const; ret.definition = definition; return ret; } clingo_ast_statement_t visit(ShowSignature const &x) { auto *show_signature = create_<clingo_ast_show_signature_t>(); show_signature->csp = x.csp; show_signature->signature = x.signature.to_c(); clingo_ast_statement_t ret; ret.type = clingo_ast_statement_type_show_signature; ret.show_signature = show_signature; return ret; } clingo_ast_statement_t visit(ShowTerm const &x) { auto *show_term = create_<clingo_ast_show_term_t>(); show_term->csp = x.csp; show_term->term = convTerm(x.term); show_term->body = convBodyLiteralVec(x.body); show_term->size = x.body.size(); clingo_ast_statement_t ret; ret.type = clingo_ast_statement_type_show_term; ret.show_term = show_term; return ret; } clingo_ast_statement_t visit(Minimize const &x) { auto *minimize = create_<clingo_ast_minimize_t>(); minimize->weight = convTerm(x.weight); minimize->priority = convTerm(x.priority); minimize->tuple = convTermVec(x.tuple); minimize->tuple_size = x.tuple.size(); minimize->body = convBodyLiteralVec(x.body); minimize->body_size = x.body.size(); clingo_ast_statement_t ret; ret.type = clingo_ast_statement_type_minimize; ret.minimize = minimize; return ret; } clingo_ast_statement_t visit(Script const &x) { auto *script = create_<clingo_ast_script_t>(); script->type = static_cast<clingo_ast_script_type_t>(x.type); script->code = x.code; clingo_ast_statement_t ret; ret.type = clingo_ast_statement_type_script; ret.script = script; return ret; } clingo_ast_statement_t visit(Program const &x) { auto *program = create_<clingo_ast_program_t>(); program->name = x.name; program->parameters = createArray_(x.parameters, &ASTToC::convId); program->size = x.parameters.size(); clingo_ast_statement_t ret; ret.type = clingo_ast_statement_type_program; ret.program = program; return ret; } clingo_ast_statement_t visit(External const &x) { auto *external = create_<clingo_ast_external_t>(); external->atom = convTerm(x.atom); external->body = convBodyLiteralVec(x.body); external->size = x.body.size(); clingo_ast_statement_t ret; ret.type = clingo_ast_statement_type_external; ret.external = external; return ret; } clingo_ast_statement_t visit(Edge const &x) { auto *edge = create_<clingo_ast_edge_t>(); edge->u = convTerm(x.u); edge->v = convTerm(x.v); edge->body = convBodyLiteralVec(x.body); edge->size = x.body.size(); clingo_ast_statement_t ret; ret.type = clingo_ast_statement_type_edge; ret.edge = edge; return ret; } clingo_ast_statement_t visit(Heuristic const &x) { auto *heuristic = create_<clingo_ast_heuristic_t>(); heuristic->atom = convTerm(x.atom); heuristic->bias = convTerm(x.bias); heuristic->priority = convTerm(x.priority); heuristic->modifier = convTerm(x.modifier); heuristic->body = convBodyLiteralVec(x.body); heuristic->size = x.body.size(); clingo_ast_statement_t ret; ret.type = clingo_ast_statement_type_heuristic; ret.heuristic = heuristic; return ret; } clingo_ast_statement_t visit(ProjectAtom const &x) { auto *project = create_<clingo_ast_project_t>(); project->atom = convTerm(x.atom); project->body = convBodyLiteralVec(x.body); project->size = x.body.size(); clingo_ast_statement_t ret; ret.type = clingo_ast_statement_type_project_atom; ret.project_atom = project; return ret; } clingo_ast_statement_t visit(ProjectSignature const &x) { clingo_ast_statement_t ret; ret.type = clingo_ast_statement_type_project_atom_signature; ret.project_signature = x.signature.to_c(); return ret; } clingo_ast_statement_t visit(TheoryDefinition const &x) { auto *theory_definition = create_<clingo_ast_theory_definition_t>(); theory_definition->name = x.name; theory_definition->terms = createArray_(x.terms, &ASTToC::convTheoryTermDefinition); theory_definition->terms_size = x.terms.size(); theory_definition->atoms = createArray_(x.atoms, &ASTToC::convTheoryAtomDefinition); theory_definition->atoms_size = x.atoms.size(); clingo_ast_statement_t ret; ret.type = clingo_ast_statement_type_theory_definition; ret.theory_definition = theory_definition; return ret; } // {{{3 aux template <class T> T identity(T t) { return t; } template <class T> T *create_() { data_.emplace_back(operator new(sizeof(T))); return reinterpret_cast<T*>(data_.back()); } template <class T> T *create_(T x) { auto *r = create_<T>(); *r = x; return r; } template <class T> T *createArray_(size_t size) { arrdata_.emplace_back(operator new[](sizeof(T) * size)); return reinterpret_cast<T*>(arrdata_.back()); } template <class T, class F> auto createArray_(std::vector<T> const &vec, F f) -> decltype((this->*f)(std::declval<T>()))* { using U = decltype((this->*f)(std::declval<T>())); auto r = createArray_<U>(vec.size()), jt = r; for (auto it = vec.begin(), ie = vec.end(); it != ie; ++it, ++jt) { *jt = (this->*f)(*it); } return r; } ~ASTToC() noexcept { for (auto &x : data_) { operator delete(x); } for (auto &x : arrdata_) { operator delete[](x); } data_.clear(); arrdata_.clear(); } std::vector<void *> data_; std::vector<void *> arrdata_; // }}}3 }; } } // namespace AST Detail inline void ProgramBuilder::begin() { Detail::handle_error(clingo_program_builder_begin(builder_)); } inline void ProgramBuilder::add(AST::Statement const &stm) { AST::Detail::ASTToC a; auto x = stm.data.accept(a); x.location = stm.location; Detail::handle_error(clingo_program_builder_add(builder_, &x)); } inline void ProgramBuilder::end() { Detail::handle_error(clingo_program_builder_end(builder_)); } // {{{2 control struct Control::Impl { Impl(Logger logger) : ctl(nullptr) , handler(nullptr) , logger(logger) { } Impl(clingo_control_t *ctl) : ctl(ctl) , handler(nullptr) { } ~Impl() noexcept { if (ctl) { clingo_control_free(ctl); } } operator clingo_control_t *() { return ctl; } clingo_control_t *ctl; SolveEventHandler *handler; Detail::AssignOnce ptr; Logger logger; std::forward_list<std::pair<Propagator&, Detail::AssignOnce&>> propagators_; std::forward_list<std::pair<GroundProgramObserver&, Detail::AssignOnce&>> observers_; }; inline Clingo::Control::Control(StringSpan args, Logger logger, unsigned message_limit) : impl_(new Clingo::Control::Impl(logger)) { clingo_logger_t f = [](clingo_warning_t code, char const *msg, void *data) { try { (*static_cast<Logger*>(data))(static_cast<WarningCode>(code), msg); } catch (...) { } }; Detail::handle_error(clingo_control_new(args.begin(), args.size(), logger ? f : nullptr, logger ? &impl_->logger : nullptr, message_limit, &impl_->ctl)); } inline Control::Control(clingo_control_t *ctl) : impl_(new Impl(ctl)) { } inline Control::Control(Control &&c) : impl_(nullptr) { std::swap(impl_, c.impl_); } inline Control &Control::operator=(Control &&c) { delete impl_; impl_ = nullptr; std::swap(impl_, c.impl_); return *this; } inline Control::~Control() noexcept { delete impl_; } inline void Control::add(char const *name, StringSpan params, char const *part) { Detail::handle_error(clingo_control_add(*impl_, name, params.begin(), params.size(), part)); } inline void Control::ground(PartSpan parts, GroundCallback cb) { using Data = std::pair<GroundCallback&, Detail::AssignOnce&>; Data data(cb, impl_->ptr); impl_->ptr.reset(); Detail::handle_error(clingo_control_ground(*impl_, reinterpret_cast<clingo_part_t const *>(parts.begin()), parts.size(), [](clingo_location_t const *loc, char const *name, clingo_symbol_t const *args, size_t n, void *data, clingo_symbol_callback_t cb, void *cbdata) -> bool { auto &d = *static_cast<Data*>(data); CLINGO_CALLBACK_TRY { if (d.first) { struct Ret : std::exception { }; try { d.first(Location(*loc), name, {reinterpret_cast<Symbol const *>(args), n}, [cb, cbdata](SymbolSpan symret) { if (!cb(reinterpret_cast<clingo_symbol_t const *>(symret.begin()), symret.size(), cbdata)) { throw Ret(); } }); } catch (Ret e) { return false; } } } CLINGO_CALLBACK_CATCH(d.second); }, &data), data.second); } inline clingo_control_t *Control::to_c() const { return *impl_; } inline SolveHandle Control::solve(SymbolicLiteralSpan assumptions, SolveEventHandler *handler, bool asynchronous, bool yield) { clingo_solve_handle_t *it; clingo_solve_mode_bitset_t mode = 0; if (asynchronous) { mode |= clingo_solve_mode_async; } if (yield) { mode |= clingo_solve_mode_yield; } impl_->handler = handler; impl_->ptr.reset(); clingo_solve_event_callback_t on_event = [](clingo_solve_event_type_t type, void *event, void *pdata, bool *goon) { Impl &data = *static_cast<Impl*>(pdata); switch (type) { case clingo_solve_event_type_model: { CLINGO_CALLBACK_TRY { Model m{static_cast<clingo_model_t*>(event)}; *goon = data.handler->on_model(m); } CLINGO_CALLBACK_CATCH(data.ptr); } case clingo_solve_event_type_finish: { try { data.handler->on_finish(SolveResult{*static_cast<clingo_solve_result_bitset_t*>(event)}); *goon = true; return true; } catch (std::exception const &e) { fprintf(stderr, "error in SolveEventHandler::on_finish going to terminate:\n%s\n", e.what()); } catch (...) { fprintf(stderr, "error in SolveEventHandler::on_finish going to terminate\n"); } fflush(stderr); std::terminate(); } } return false; }; Detail::handle_error(clingo_control_solve(*impl_, mode, reinterpret_cast<clingo_symbolic_literal_t const *>(assumptions.begin()), assumptions.size(), handler ? on_event : nullptr, impl_, &it), impl_->ptr); return SolveHandle{it, impl_->ptr}; } inline void Control::assign_external(Symbol atom, TruthValue value) { Detail::handle_error(clingo_control_assign_external(*impl_, atom.to_c(), static_cast<clingo_truth_value_t>(value))); } inline void Control::release_external(Symbol atom) { Detail::handle_error(clingo_control_release_external(*impl_, atom.to_c())); } inline SymbolicAtoms Control::symbolic_atoms() const { clingo_symbolic_atoms_t *ret; Detail::handle_error(clingo_control_symbolic_atoms(*impl_, &ret)); return SymbolicAtoms{ret}; } inline TheoryAtoms Control::theory_atoms() const { clingo_theory_atoms_t *ret; clingo_control_theory_atoms(*impl_, &ret); return TheoryAtoms{ret}; } namespace Detail { using PropagatorData = std::pair<Propagator&, AssignOnce&>; inline static bool g_init(clingo_propagate_init_t *ctl, void *pdata) { PropagatorData &data = *static_cast<PropagatorData*>(pdata); CLINGO_CALLBACK_TRY { PropagateInit pi(ctl); data.first.init(pi); } CLINGO_CALLBACK_CATCH(data.second); } inline static bool g_propagate(clingo_propagate_control_t *ctl, clingo_literal_t const *changes, size_t n, void *pdata) { PropagatorData &data = *static_cast<PropagatorData*>(pdata); CLINGO_CALLBACK_TRY { PropagateControl pc(ctl); data.first.propagate(pc, {changes, n}); } CLINGO_CALLBACK_CATCH(data.second); } inline static bool g_undo(clingo_propagate_control_t *ctl, clingo_literal_t const *changes, size_t n, void *pdata) { PropagatorData &data = *static_cast<PropagatorData*>(pdata); CLINGO_CALLBACK_TRY { PropagateControl pc(ctl); data.first.undo(pc, {changes, n}); } CLINGO_CALLBACK_CATCH(data.second); } inline static bool g_check(clingo_propagate_control_t *ctl, void *pdata) { PropagatorData &data = *static_cast<PropagatorData*>(pdata); CLINGO_CALLBACK_TRY { PropagateControl pc(ctl); data.first.check(pc); } CLINGO_CALLBACK_CATCH(data.second); } } // namespace Detail inline void Control::register_propagator(Propagator &propagator, bool sequential) { impl_->propagators_.emplace_front(propagator, impl_->ptr); static clingo_propagator_t g_propagator = { Detail::g_init, Detail::g_propagate, Detail::g_undo, Detail::g_check }; Detail::handle_error(clingo_control_register_propagator(*impl_, &g_propagator, &impl_->propagators_.front(), sequential)); } namespace Detail { using ObserverData = std::pair<GroundProgramObserver&, AssignOnce&>; inline bool g_init_program(bool incremental, void *pdata) { ObserverData &data = *static_cast<ObserverData*>(pdata); CLINGO_CALLBACK_TRY { data.first.init_program(incremental); } CLINGO_CALLBACK_CATCH(data.second); } inline bool g_begin_step(void *pdata) { ObserverData &data = *static_cast<ObserverData*>(pdata); CLINGO_CALLBACK_TRY { data.first.begin_step(); } CLINGO_CALLBACK_CATCH(data.second); } inline bool g_end_step(void *pdata) { ObserverData &data = *static_cast<ObserverData*>(pdata); CLINGO_CALLBACK_TRY { data.first.end_step(); } CLINGO_CALLBACK_CATCH(data.second); } inline bool g_rule(bool choice, clingo_atom_t const *head, size_t head_size, clingo_literal_t const *body, size_t body_size, void *pdata) { ObserverData &data = *static_cast<ObserverData*>(pdata); CLINGO_CALLBACK_TRY { data.first.rule(choice, AtomSpan(head, head_size), LiteralSpan(body, body_size)); } CLINGO_CALLBACK_CATCH(data.second); } inline bool g_weight_rule(bool choice, clingo_atom_t const *head, size_t head_size, clingo_weight_t lower_bound, clingo_weighted_literal_t const *body, size_t body_size, void *pdata) { ObserverData &data = *static_cast<ObserverData*>(pdata); CLINGO_CALLBACK_TRY { data.first.weight_rule(choice, AtomSpan(head, head_size), lower_bound, WeightedLiteralSpan(reinterpret_cast<WeightedLiteral const*>(body), body_size)); } CLINGO_CALLBACK_CATCH(data.second); } inline bool g_minimize(clingo_weight_t priority, clingo_weighted_literal_t const* literals, size_t size, void *pdata) { ObserverData &data = *static_cast<ObserverData*>(pdata); CLINGO_CALLBACK_TRY { data.first.minimize(priority, WeightedLiteralSpan(reinterpret_cast<WeightedLiteral const*>(literals), size)); } CLINGO_CALLBACK_CATCH(data.second); } inline bool g_project(clingo_atom_t const *atoms, size_t size, void *pdata) { ObserverData &data = *static_cast<ObserverData*>(pdata); CLINGO_CALLBACK_TRY { data.first.project(AtomSpan(atoms, size)); } CLINGO_CALLBACK_CATCH(data.second); } inline bool g_output_atom(clingo_symbol_t symbol, clingo_atom_t atom, void *pdata) { ObserverData &data = *static_cast<ObserverData*>(pdata); CLINGO_CALLBACK_TRY { data.first.output_atom(Symbol{symbol}, atom); } CLINGO_CALLBACK_CATCH(data.second); } inline bool g_output_term(clingo_symbol_t symbol, clingo_literal_t const *condition, size_t size, void *pdata) { ObserverData &data = *static_cast<ObserverData*>(pdata); CLINGO_CALLBACK_TRY { data.first.output_term(Symbol{symbol}, LiteralSpan{condition, size}); } CLINGO_CALLBACK_CATCH(data.second); } inline bool g_output_csp(clingo_symbol_t symbol, int value, clingo_literal_t const *condition, size_t size, void *pdata) { ObserverData &data = *static_cast<ObserverData*>(pdata); CLINGO_CALLBACK_TRY { data.first.output_csp(Symbol{symbol}, value, LiteralSpan{condition, size}); } CLINGO_CALLBACK_CATCH(data.second); } inline bool g_external(clingo_atom_t atom, clingo_external_type_t type, void *pdata) { ObserverData &data = *static_cast<ObserverData*>(pdata); CLINGO_CALLBACK_TRY { data.first.external(atom, static_cast<ExternalType>(type)); } CLINGO_CALLBACK_CATCH(data.second); } inline bool g_assume(clingo_literal_t const *literals, size_t size, void *pdata) { ObserverData &data = *static_cast<ObserverData*>(pdata); CLINGO_CALLBACK_TRY { data.first.assume(LiteralSpan(literals, size)); } CLINGO_CALLBACK_CATCH(data.second); } inline bool g_heuristic(clingo_atom_t atom, clingo_heuristic_type_t type, int bias, unsigned priority, clingo_literal_t const *condition, size_t size, void *pdata) { ObserverData &data = *static_cast<ObserverData*>(pdata); CLINGO_CALLBACK_TRY { data.first.heuristic(atom, static_cast<HeuristicType>(type), bias, priority, LiteralSpan(condition, size)); } CLINGO_CALLBACK_CATCH(data.second); } inline bool g_acyc_edge(int node_u, int node_v, clingo_literal_t const *condition, size_t size, void *pdata) { ObserverData &data = *static_cast<ObserverData*>(pdata); CLINGO_CALLBACK_TRY { data.first.acyc_edge(node_u, node_v, LiteralSpan(condition, size)); } CLINGO_CALLBACK_CATCH(data.second); } inline bool g_theory_term_number(clingo_id_t term_id, int number, void *pdata) { ObserverData &data = *static_cast<ObserverData*>(pdata); CLINGO_CALLBACK_TRY { data.first.theory_term_number(term_id, number); } CLINGO_CALLBACK_CATCH(data.second); } inline bool g_theory_term_string(clingo_id_t term_id, char const *name, void *pdata) { ObserverData &data = *static_cast<ObserverData*>(pdata); CLINGO_CALLBACK_TRY { data.first.theory_term_string(term_id, name); } CLINGO_CALLBACK_CATCH(data.second); } inline bool g_theory_term_compound(clingo_id_t term_id, int name_id_or_type, clingo_id_t const *arguments, size_t size, void *pdata) { ObserverData &data = *static_cast<ObserverData*>(pdata); CLINGO_CALLBACK_TRY { data.first.theory_term_compound(term_id, name_id_or_type, IdSpan(arguments, size)); } CLINGO_CALLBACK_CATCH(data.second); } inline bool g_theory_element(clingo_id_t element_id, clingo_id_t const *terms, size_t terms_size, clingo_literal_t const *condition, size_t condition_size, void *pdata) { ObserverData &data = *static_cast<ObserverData*>(pdata); CLINGO_CALLBACK_TRY { data.first.theory_element(element_id, IdSpan(terms, terms_size), LiteralSpan(condition, condition_size)); } CLINGO_CALLBACK_CATCH(data.second); } inline bool g_theory_atom(clingo_id_t atom_id_or_zero, clingo_id_t term_id, clingo_id_t const *elements, size_t size, void *pdata) { ObserverData &data = *static_cast<ObserverData*>(pdata); CLINGO_CALLBACK_TRY { data.first.theory_atom(atom_id_or_zero, term_id, IdSpan(elements, size)); } CLINGO_CALLBACK_CATCH(data.second); } inline bool g_theory_atom_with_guard(clingo_id_t atom_id_or_zero, clingo_id_t term_id, clingo_id_t const *elements, size_t size, clingo_id_t operator_id, clingo_id_t right_hand_side_id, void *pdata) { ObserverData &data = *static_cast<ObserverData*>(pdata); CLINGO_CALLBACK_TRY { data.first.theory_atom_with_guard(atom_id_or_zero, term_id, IdSpan(elements, size), operator_id, right_hand_side_id); } CLINGO_CALLBACK_CATCH(data.second); } } // namespace Detail inline void Control::register_observer(GroundProgramObserver &observer, bool replace) { impl_->observers_.emplace_front(observer, impl_->ptr); static clingo_ground_program_observer_t g_observer = { Detail::g_init_program, Detail::g_begin_step, Detail::g_end_step, Detail::g_rule, Detail::g_weight_rule, Detail::g_minimize, Detail::g_project, Detail::g_output_atom, Detail::g_output_term, Detail::g_output_csp, Detail::g_external, Detail::g_assume, Detail::g_heuristic, Detail::g_acyc_edge, Detail::g_theory_term_number, Detail::g_theory_term_string, Detail::g_theory_term_compound, Detail::g_theory_element, Detail::g_theory_atom, Detail::g_theory_atom_with_guard }; Detail::handle_error(clingo_control_register_observer(*impl_, &g_observer, replace, &impl_->observers_.front())); } inline void Control::cleanup() { Detail::handle_error(clingo_control_cleanup(*impl_)); } inline bool Control::has_const(char const *name) const { bool ret; Detail::handle_error(clingo_control_has_const(*impl_, name, &ret)); return ret; } inline Symbol Control::get_const(char const *name) const { clingo_symbol_t ret; Detail::handle_error(clingo_control_get_const(*impl_, name, &ret)); return Symbol(ret); } inline void Control::interrupt() noexcept { clingo_control_interrupt(*impl_); } inline void *Control::claspFacade() { void *ret; Detail::handle_error(clingo_control_clasp_facade(impl_->ctl, &ret)); return ret; } inline void Control::load(char const *file) { Detail::handle_error(clingo_control_load(*impl_, file)); } inline void Control::use_enumeration_assumption(bool value) { Detail::handle_error(clingo_control_use_enumeration_assumption(*impl_, value)); } inline Backend Control::backend() { clingo_backend_t *ret; Detail::handle_error(clingo_control_backend(*impl_, &ret)); return Backend{ret}; } inline Configuration Control::configuration() { clingo_configuration_t *conf; Detail::handle_error(clingo_control_configuration(*impl_, &conf)); unsigned key; Detail::handle_error(clingo_configuration_root(conf, &key)); return Configuration{conf, key}; } inline Statistics Control::statistics() const { clingo_statistics_t *stats; Detail::handle_error(clingo_control_statistics(const_cast<clingo_control_t*>(impl_->ctl), &stats)); uint64_t key; Detail::handle_error(clingo_statistics_root(stats, &key)); return Statistics{stats, key}; } inline ProgramBuilder Control::builder() { clingo_program_builder_t *ret; Detail::handle_error(clingo_control_program_builder(impl_->ctl, &ret)); return ProgramBuilder{ret}; } // {{{2 global functions inline Symbol parse_term(char const *str, Logger logger, unsigned message_limit) { clingo_symbol_t ret; Detail::handle_error(clingo_parse_term(str, [](clingo_warning_t code, char const *msg, void *data) { try { (*static_cast<Logger*>(data))(static_cast<WarningCode>(code), msg); } catch (...) { } }, &logger, message_limit, &ret)); return Symbol(ret); } inline char const *add_string(char const *str) { char const *ret; Detail::handle_error(clingo_add_string(str, &ret)); return ret; } inline std::tuple<int, int, int> version() { std::tuple<int, int, int> ret; clingo_version(&std::get<0>(ret), &std::get<1>(ret), &std::get<2>(ret)); return ret; } namespace AST { namespace Detail { template <class T> struct PrintWrapper { T const &vec; char const *pre; char const *sep; char const *post; bool empty; friend std::ostream &operator<<(std::ostream &out, PrintWrapper x) { using namespace std; auto it = std::begin(x.vec), ie = std::end(x.vec); if (it != ie) { out << x.pre; out << *it; for (++it; it != ie; ++it) { out << x.sep << *it; } out << x.post; } else if (x.empty) { out << x.pre; out << x.post; } return out; } }; template <class T> PrintWrapper<T> print(T const &vec, char const *pre, char const *sep, char const *post, bool empty) { return {vec, pre, sep, post, empty}; } inline PrintWrapper<std::vector<BodyLiteral>> print_body(std::vector<BodyLiteral> const &vec, char const *pre = " : ") { return print(vec, vec.empty() ? "" : pre, "; ", ".", true); } // {{{3 C -> C++ #define CLINGO_ARRAY(in, out) \ inline std::vector<out> conv ## out ## Vec(in const *arr, size_t size) { \ std::vector<out> ret; \ for (auto it = arr, ie = arr + size; it != ie; ++it) { \ ret.emplace_back(conv ## out(*it)); \ } \ return ret; \ } // {{{4 terms inline Id convId(clingo_ast_id_t const &id) { return {Location(id.location), id.id}; } CLINGO_ARRAY(clingo_ast_id_t, Id) inline Term convTerm(clingo_ast_term_t const &term); CLINGO_ARRAY(clingo_ast_term_t, Term) inline Term convTerm(clingo_ast_term_t const &term) { switch (static_cast<enum clingo_ast_term_type>(term.type)) { case clingo_ast_term_type_symbol: { return {Location{term.location}, Symbol{term.symbol}}; } case clingo_ast_term_type_variable: { return {Location{term.location}, Variable{term.variable}}; } case clingo_ast_term_type_unary_operation: { auto &op = *term.unary_operation; return {Location{term.location}, UnaryOperation{static_cast<UnaryOperator>(op.unary_operator), convTerm(op.argument)}}; } case clingo_ast_term_type_binary_operation: { auto &op = *term.binary_operation; return {Location{term.location}, BinaryOperation{static_cast<BinaryOperator>(op.binary_operator), convTerm(op.left), convTerm(op.right)}}; } case clingo_ast_term_type_interval: { auto &x = *term.interval; return {Location{term.location}, Interval{convTerm(x.left), convTerm(x.right)}}; } case clingo_ast_term_type_function: { auto &x = *term.function; return {Location{term.location}, Function{x.name, convTermVec(x.arguments, x.size), false}}; } case clingo_ast_term_type_external_function: { auto &x = *term.external_function; return {Location{term.location}, Function{x.name, convTermVec(x.arguments, x.size), true}}; } case clingo_ast_term_type_pool: { auto &x = *term.pool; return {Location{term.location}, Pool{convTermVec(x.arguments, x.size)}}; } } throw std::logic_error("cannot happen"); } inline Optional<Term> convTerm(clingo_ast_term_t const *term) { return term ? Optional<Term>{convTerm(*term)} : Optional<Term>{}; } // csp inline CSPProduct convCSPProduct(clingo_ast_csp_product_term const &term) { return {Location{term.location}, convTerm(term.coefficient), convTerm(term.variable)}; } CLINGO_ARRAY(clingo_ast_csp_product_term, CSPProduct) inline CSPSum convCSPAdd(clingo_ast_csp_sum_term_t const &term) { return {Location{term.location}, convCSPProductVec(term.terms, term.size)}; } // theory inline TheoryTerm convTheoryTerm(clingo_ast_theory_term_t const &term); CLINGO_ARRAY(clingo_ast_theory_term_t, TheoryTerm) inline TheoryUnparsedTermElement convTheoryUnparsedTermElement(clingo_ast_theory_unparsed_term_element_t const &term) { return {std::vector<char const *>{term.operators, term.operators + term.size}, convTheoryTerm(term.term)}; } CLINGO_ARRAY(clingo_ast_theory_unparsed_term_element_t, TheoryUnparsedTermElement) inline TheoryTerm convTheoryTerm(clingo_ast_theory_term_t const &term) { switch (static_cast<enum clingo_ast_theory_term_type>(term.type)) { case clingo_ast_theory_term_type_symbol: { return {Location{term.location}, Symbol{term.symbol}}; } case clingo_ast_theory_term_type_variable: { return {Location{term.location}, Variable{term.variable}}; } case clingo_ast_theory_term_type_list: { auto &x = *term.list; return {Location{term.location}, TheoryTermSequence{TheoryTermSequenceType::List, convTheoryTermVec(x.terms, x.size)}}; } case clingo_ast_theory_term_type_set: { auto &x = *term.list; return {Location{term.location}, TheoryTermSequence{TheoryTermSequenceType::Set, convTheoryTermVec(x.terms, x.size)}}; } case clingo_ast_theory_term_type_tuple: { auto &x = *term.list; return {Location{term.location}, TheoryTermSequence{TheoryTermSequenceType::Tuple, convTheoryTermVec(x.terms, x.size)}}; } case clingo_ast_theory_term_type_function: { auto &x = *term.function; return {Location{term.location}, TheoryFunction{x.name, convTheoryTermVec(x.arguments, x.size)}}; } case clingo_ast_theory_term_type_unparsed_term: { auto &x = *term.unparsed_term; return {Location{term.location}, TheoryUnparsedTerm{convTheoryUnparsedTermElementVec(x.elements, x.size)}}; } } throw std::logic_error("cannot happen"); } // {{{4 literal inline CSPGuard convCSPGuard(clingo_ast_csp_guard_t const &guard) { return {static_cast<ComparisonOperator>(guard.comparison), convCSPAdd(guard.term)}; } CLINGO_ARRAY(clingo_ast_csp_guard_t, CSPGuard) inline Literal convLiteral(clingo_ast_literal_t const &lit) { switch (static_cast<enum clingo_ast_literal_type>(lit.type)) { case clingo_ast_literal_type_boolean: { return {Location(lit.location), static_cast<Sign>(lit.sign), Boolean{lit.boolean}}; } case clingo_ast_literal_type_symbolic: { return {Location(lit.location), static_cast<Sign>(lit.sign), convTerm(*lit.symbol)}; } case clingo_ast_literal_type_comparison: { auto &c = *lit.comparison; return {Location(lit.location), static_cast<Sign>(lit.sign), Comparison{static_cast<ComparisonOperator>(c.comparison), convTerm(c.left), convTerm(c.right)}}; } case clingo_ast_literal_type_csp: { auto &c = *lit.csp_literal; return {Location(lit.location), static_cast<Sign>(lit.sign), CSPLiteral{convCSPAdd(c.term), convCSPGuardVec(c.guards, c.size)}}; } } throw std::logic_error("cannot happen"); } CLINGO_ARRAY(clingo_ast_literal_t, Literal) // {{{4 aggregates inline Optional<AggregateGuard> convAggregateGuard(clingo_ast_aggregate_guard_t const *guard) { return guard ? Optional<AggregateGuard>{AggregateGuard{static_cast<ComparisonOperator>(guard->comparison), convTerm(guard->term)}} : Optional<AggregateGuard>{}; } inline ConditionalLiteral convConditionalLiteral(clingo_ast_conditional_literal_t const &lit) { return {convLiteral(lit.literal), convLiteralVec(lit.condition, lit.size)}; } CLINGO_ARRAY(clingo_ast_conditional_literal_t, ConditionalLiteral) inline Aggregate convAggregate(clingo_ast_aggregate_t const &aggr) { return {convConditionalLiteralVec(aggr.elements, aggr.size), convAggregateGuard(aggr.left_guard), convAggregateGuard(aggr.right_guard)}; } // theory atom inline Optional<TheoryGuard> convTheoryGuard(clingo_ast_theory_guard_t const *guard) { return guard ? Optional<TheoryGuard>{TheoryGuard{guard->operator_name, convTheoryTerm(guard->term)}} : Optional<TheoryGuard>{}; } inline TheoryAtomElement convTheoryAtomElement(clingo_ast_theory_atom_element_t const &elem) { return {convTheoryTermVec(elem.tuple, elem.tuple_size), convLiteralVec(elem.condition, elem.condition_size)}; } CLINGO_ARRAY(clingo_ast_theory_atom_element_t, TheoryAtomElement) inline TheoryAtom convTheoryAtom(clingo_ast_theory_atom_t const &atom) { return {convTerm(atom.term), convTheoryAtomElementVec(atom.elements, atom.size), convTheoryGuard(atom.guard)}; } // disjoint inline DisjointElement convDisjointElement(clingo_ast_disjoint_element_t const &elem) { return {Location{elem.location}, convTermVec(elem.tuple, elem.tuple_size), convCSPAdd(elem.term), convLiteralVec(elem.condition, elem.condition_size)}; } CLINGO_ARRAY(clingo_ast_disjoint_element_t, DisjointElement) // head aggregates inline HeadAggregateElement convHeadAggregateElement(clingo_ast_head_aggregate_element_t const &elem) { return {convTermVec(elem.tuple, elem.tuple_size), convConditionalLiteral(elem.conditional_literal)}; } CLINGO_ARRAY(clingo_ast_head_aggregate_element_t, HeadAggregateElement) // body aggregates inline BodyAggregateElement convBodyAggregateElement(clingo_ast_body_aggregate_element_t const &elem) { return {convTermVec(elem.tuple, elem.tuple_size), convLiteralVec(elem.condition, elem.condition_size)}; } CLINGO_ARRAY(clingo_ast_body_aggregate_element_t, BodyAggregateElement) // {{{4 head literal inline HeadLiteral convHeadLiteral(clingo_ast_head_literal_t const &head) { switch (static_cast<enum clingo_ast_head_literal_type>(head.type)) { case clingo_ast_head_literal_type_literal: { return {Location{head.location}, convLiteral(*head.literal)}; } case clingo_ast_head_literal_type_disjunction: { auto &d = *head.disjunction; return {Location{head.location}, Disjunction{convConditionalLiteralVec(d.elements, d.size)}}; } case clingo_ast_head_literal_type_aggregate: { return {Location{head.location}, convAggregate(*head.aggregate)}; } case clingo_ast_head_literal_type_head_aggregate: { auto &a = *head.head_aggregate; return {Location{head.location}, HeadAggregate{static_cast<AggregateFunction>(a.function), convHeadAggregateElementVec(a.elements, a.size), convAggregateGuard(a.left_guard), convAggregateGuard(a.right_guard)}}; } case clingo_ast_head_literal_type_theory_atom: { return {Location{head.location}, convTheoryAtom(*head.theory_atom)}; } } throw std::logic_error("cannot happen"); } // {{{4 body literal inline BodyLiteral convBodyLiteral(clingo_ast_body_literal_t const &body) { switch (static_cast<enum clingo_ast_body_literal_type>(body.type)) { case clingo_ast_body_literal_type_literal: { return {Location{body.location}, static_cast<Sign>(body.sign), convLiteral(*body.literal)}; } case clingo_ast_body_literal_type_conditional: { return {Location{body.location}, static_cast<Sign>(body.sign), convConditionalLiteral(*body.conditional)}; } case clingo_ast_body_literal_type_aggregate: { return {Location{body.location}, static_cast<Sign>(body.sign), convAggregate(*body.aggregate)}; } case clingo_ast_body_literal_type_body_aggregate: { auto &a = *body.body_aggregate; return {Location{body.location}, static_cast<Sign>(body.sign), BodyAggregate{static_cast<AggregateFunction>(a.function), convBodyAggregateElementVec(a.elements, a.size), convAggregateGuard(a.left_guard), convAggregateGuard(a.right_guard)}}; } case clingo_ast_body_literal_type_theory_atom: { return {Location{body.location}, static_cast<Sign>(body.sign), convTheoryAtom(*body.theory_atom)}; } case clingo_ast_body_literal_type_disjoint: { auto &d = *body.disjoint; return {Location{body.location}, static_cast<Sign>(body.sign), Disjoint{convDisjointElementVec(d.elements, d.size)}}; } } throw std::logic_error("cannot happen"); } CLINGO_ARRAY(clingo_ast_body_literal_t, BodyLiteral) // {{{4 statement inline TheoryOperatorDefinition convTheoryOperatorDefinition(clingo_ast_theory_operator_definition_t const &def) { return {Location{def.location}, def.name, def.priority, static_cast<TheoryOperatorType>(def.type)}; } CLINGO_ARRAY(clingo_ast_theory_operator_definition_t, TheoryOperatorDefinition) inline Optional<TheoryGuardDefinition> convTheoryGuardDefinition(clingo_ast_theory_guard_definition_t const *def) { return def ? Optional<TheoryGuardDefinition>{def->term, std::vector<char const *>{def->operators, def->operators + def->size}} : Optional<TheoryGuardDefinition>{}; } inline TheoryTermDefinition convTheoryTermDefinition(clingo_ast_theory_term_definition_t const &def) { return {Location{def.location}, def.name, convTheoryOperatorDefinitionVec(def.operators, def.size)}; std::vector<TheoryOperatorDefinition> operators; } CLINGO_ARRAY(clingo_ast_theory_term_definition_t, TheoryTermDefinition) inline TheoryAtomDefinition convTheoryAtomDefinition(clingo_ast_theory_atom_definition_t const &def) { return {Location{def.location}, static_cast<TheoryAtomDefinitionType>(def.type), def.name, def.arity, def.elements, convTheoryGuardDefinition(def.guard)}; } CLINGO_ARRAY(clingo_ast_theory_atom_definition_t, TheoryAtomDefinition) inline void convStatement(clingo_ast_statement_t const *stm, StatementCallback &cb) { switch (static_cast<enum clingo_ast_statement_type>(stm->type)) { case clingo_ast_statement_type_rule: { cb({Location(stm->location), Rule{convHeadLiteral(stm->rule->head), convBodyLiteralVec(stm->rule->body, stm->rule->size)}}); break; } case clingo_ast_statement_type_const: { cb({Location(stm->location), Definition{stm->definition->name, convTerm(stm->definition->value), stm->definition->is_default}}); break; } case clingo_ast_statement_type_show_signature: { cb({Location(stm->location), ShowSignature{Signature(stm->show_signature->signature), stm->show_signature->csp}}); break; } case clingo_ast_statement_type_show_term: { cb({Location(stm->location), ShowTerm{convTerm(stm->show_term->term), convBodyLiteralVec(stm->show_term->body, stm->show_term->size), stm->show_term->csp}}); break; } case clingo_ast_statement_type_minimize: { auto &min = *stm->minimize; cb({Location(stm->location), Minimize{convTerm(min.weight), convTerm(min.priority), convTermVec(min.tuple, min.tuple_size), convBodyLiteralVec(min.body, min.body_size)}}); break; } case clingo_ast_statement_type_script: { cb({Location(stm->location), Script{static_cast<ScriptType>(stm->script->type), stm->script->code}}); break; } case clingo_ast_statement_type_program: { cb({Location(stm->location), Program{stm->program->name, convIdVec(stm->program->parameters, stm->program->size)}}); break; } case clingo_ast_statement_type_external: { cb({Location(stm->location), External{convTerm(stm->external->atom), convBodyLiteralVec(stm->external->body, stm->external->size)}}); break; } case clingo_ast_statement_type_edge: { cb({Location(stm->location), Edge{convTerm(stm->edge->u), convTerm(stm->edge->v), convBodyLiteralVec(stm->edge->body, stm->edge->size)}}); break; } case clingo_ast_statement_type_heuristic: { auto &heu = *stm->heuristic; cb({Location(stm->location), Heuristic{convTerm(heu.atom), convBodyLiteralVec(heu.body, heu.size), convTerm(heu.bias), convTerm(heu.priority), convTerm(heu.modifier)}}); break; } case clingo_ast_statement_type_project_atom: { cb({Location(stm->location), ProjectAtom{convTerm(stm->project_atom->atom), convBodyLiteralVec(stm->project_atom->body, stm->project_atom->size)}}); break; } case clingo_ast_statement_type_project_atom_signature: { cb({Location(stm->location), ProjectSignature{Signature(stm->project_signature)}}); break; } case clingo_ast_statement_type_theory_definition: { auto &def = *stm->theory_definition; cb({Location(stm->location), TheoryDefinition{def.name, convTheoryTermDefinitionVec(def.terms, def.terms_size), convTheoryAtomDefinitionVec(def.atoms, def.atoms_size)}}); break; } } } // }}}4 #undef CLINGO_ARRAY // }}}3 } // namespace Detail // {{{3 printing // {{{4 statement inline std::ostream &operator<<(std::ostream &out, TheoryDefinition const &x) { out << "#theory " << x.name << " {\n"; bool comma = false; for (auto &y : x.terms) { if (comma) { out << ";\n"; } else { comma = true; } out << " " << y.name << " {\n" << Detail::print(y.operators, " ", ";\n", "\n", true) << " }"; } for (auto &y : x.atoms) { if (comma) { out << ";\n"; } else { comma = true; } out << " " << y; } if (comma) { out << "\n"; } out << "}."; return out; } inline std::ostream &operator<<(std::ostream &out, TheoryAtomDefinition const &x) { out << "&" << x.name << "/" << x.arity << " : " << x.elements; if (x.guard) { out << ", " << *x.guard.get(); } out << ", " << x.type; return out; } inline std::ostream &operator<<(std::ostream &out, TheoryGuardDefinition const &x) { out << "{ " << Detail::print(x.operators, "", ", ", "", false) << " }, " << x.term; return out; } inline std::ostream &operator<<(std::ostream &out, TheoryTermDefinition const &x) { out << x.name << " {\n" << Detail::print(x.operators, " ", ";\n", "\n", true) << "}"; return out; } inline std::ostream &operator<<(std::ostream &out, TheoryOperatorDefinition const &x) { out << x.name << " : " << x.priority << ", " << x.type; return out; } inline std::ostream &operator<<(std::ostream &out, BodyLiteral const &x) { out << x.sign << x.data; return out; } inline std::ostream &operator<<(std::ostream &out, HeadLiteral const &x) { out << x.data; return out; } inline std::ostream &operator<<(std::ostream &out, TheoryAtom const &x) { out << "&" << x.term << " { " << Detail::print(x.elements, "", "; ", "", false) << " }"; if (x.guard) { out << " " << *x.guard.get(); } return out; } inline std::ostream &operator<<(std::ostream &out, TheoryGuard const &x) { out << x.operator_name << " " << x.term; return out; } inline std::ostream &operator<<(std::ostream &out, TheoryAtomElement const &x) { out << Detail::print(x.tuple, "", ",", "", false) << " : " << Detail::print(x.condition, "", ",", "", false); return out; } inline std::ostream &operator<<(std::ostream &out, TheoryUnparsedTermElement const &x) { out << Detail::print(x.operators, " ", " ", " ", false) << x.term; return out; } inline std::ostream &operator<<(std::ostream &out, TheoryFunction const &x) { out << x.name << Detail::print(x.arguments, "(", ",", ")", !x.arguments.empty()); return out; } inline std::ostream &operator<<(std::ostream &out, TheoryTermSequence const &x) { bool tc = x.terms.size() == 1 && x.type == TheoryTermSequenceType::Tuple; out << Detail::print(x.terms, left_hand_side(x.type), ",", "", true); if (tc) { out << ",)"; } else { out << right_hand_side(x.type); } return out; } inline std::ostream &operator<<(std::ostream &out, TheoryTerm const &x) { out << x.data; return out; } inline std::ostream &operator<<(std::ostream &out, TheoryUnparsedTerm const &x) { if (x.elements.size() > 1) { out << "("; } out << Detail::print(x.elements, "", "", "", false); if (x.elements.size() > 1) { out << ")"; } return out; } inline std::ostream &operator<<(std::ostream &out, Disjoint const &x) { out << "#disjoint { " << Detail::print(x.elements, "", "; ", "", false) << " }"; return out; } inline std::ostream &operator<<(std::ostream &out, DisjointElement const &x) { out << Detail::print(x.tuple, "", ",", "", false) << " : " << x.term << " : " << Detail::print(x.condition, "", ",", "", false); return out; } inline std::ostream &operator<<(std::ostream &out, Disjunction const &x) { out << Detail::print(x.elements, "", "; ", "", false); return out; } inline std::ostream &operator<<(std::ostream &out, HeadAggregate const &x) { if (x.left_guard) { out << x.left_guard->term << " " << x.left_guard->comparison << " "; } out << x.function << " { " << Detail::print(x.elements, "", "; ", "", false) << " }"; if (x.right_guard) { out << " " << x.right_guard->comparison << " " << x.right_guard->term; } return out; } inline std::ostream &operator<<(std::ostream &out, HeadAggregateElement const &x) { out << Detail::print(x.tuple, "", ",", "", false) << " : " << x.condition; return out; } inline std::ostream &operator<<(std::ostream &out, BodyAggregate const &x) { if (x.left_guard) { out << x.left_guard->term << " " << x.left_guard->comparison << " "; } out << x.function << " { " << Detail::print(x.elements, "", "; ", "", false) << " }"; if (x.right_guard) { out << " " << x.right_guard->comparison << " " << x.right_guard->term; } return out; } inline std::ostream &operator<<(std::ostream &out, BodyAggregateElement const &x) { out << Detail::print(x.tuple, "", ",", "", false) << " : " << Detail::print(x.condition, "", ", ", "", false); return out; } inline std::ostream &operator<<(std::ostream &out, Aggregate const &x) { if (x.left_guard) { out << x.left_guard->term << " " << x.left_guard->comparison << " "; } out << "{ " << Detail::print(x.elements, "", "; ", "", false) << " }"; if (x.right_guard) { out << " " << x.right_guard->comparison << " " << x.right_guard->term; } return out; } inline std::ostream &operator<<(std::ostream &out, ConditionalLiteral const &x) { out << x.literal << Detail::print(x.condition, " : ", ", ", "", true); return out; } inline std::ostream &operator<<(std::ostream &out, Literal const &x) { out << x.sign << x.data; return out; } inline std::ostream &operator<<(std::ostream &out, Boolean const &x) { out << (x.value ? "#true" : "#false"); return out; } inline std::ostream &operator<<(std::ostream &out, Comparison const &x) { out << x.left << x.comparison << x.right; return out; } inline std::ostream &operator<<(std::ostream &out, Id const &x) { out << x.id; return out; } inline std::ostream &operator<<(std::ostream &out, CSPLiteral const &x) { out << x.term; for (auto &y : x.guards) { out << y; } return out; } inline std::ostream &operator<<(std::ostream &out, CSPGuard const &x) { out << "$" << x.comparison << x.term; return out; } inline std::ostream &operator<<(std::ostream &out, CSPSum const &x) { if (x.terms.empty()) { out << "0"; } else { out << Detail::print(x.terms, "", "$+", "", false); } return out; } inline std::ostream &operator<<(std::ostream &out, CSPProduct const &x) { if (x.variable) { out << x.coefficient << "$*$" << *x.variable.get(); } else { out << x.coefficient; } return out; } inline std::ostream &operator<<(std::ostream &out, Pool const &x) { // NOTE: there is no representation for an empty pool if (x.arguments.empty()) { out << "(1/0)"; } else { out << Detail::print(x.arguments, "(", ";", ")", true); } return out; } inline std::ostream &operator<<(std::ostream &out, Function const &x) { bool tc = x.name[0] == '\0' && x.arguments.size() == 1; bool ey = x.name[0] == '\0' || !x.arguments.empty(); out << (x.external ? "@" : "") << x.name << Detail::print(x.arguments, "(", ",", tc ? ",)" : ")", ey); return out; } inline std::ostream &operator<<(std::ostream &out, Interval const &x) { out << "(" << x.left << ".." << x.right << ")"; return out; } inline std::ostream &operator<<(std::ostream &out, BinaryOperation const &x) { out << "(" << x.left << x.binary_operator << x.right << ")"; return out; } inline std::ostream &operator<<(std::ostream &out, UnaryOperation const &x) { out << left_hand_side(x.unary_operator) << x.argument << right_hand_side(x.unary_operator); return out; } inline std::ostream &operator<<(std::ostream &out, Variable const &x) { out << x.name; return out; } inline std::ostream &operator<<(std::ostream &out, Term const &x) { out << x.data; return out; } inline std::ostream &operator<<(std::ostream &out, Rule const &x) { out << x.head << Detail::print_body(x.body, " :- "); return out; } inline std::ostream &operator<<(std::ostream &out, Definition const &x) { out << "#const " << x.name << " = " << x.value << "."; if (x.is_default) { out << " [default]"; } return out; } inline std::ostream &operator<<(std::ostream &out, ShowSignature const &x) { out << "#show " << (x.csp ? "$" : "") << x.signature << "."; return out; } inline std::ostream &operator<<(std::ostream &out, ShowTerm const &x) { out << "#show " << (x.csp ? "$" : "") << x.term << Detail::print_body(x.body); return out; } inline std::ostream &operator<<(std::ostream &out, Minimize const &x) { out << Detail::print_body(x.body, ":~ ") << " [" << x.weight << "@" << x.priority << Detail::print(x.tuple, ",", ",", "", false) << "]"; return out; } inline std::ostream &operator<<(std::ostream &out, Script const &x) { std::string s = x.code; if (!s.empty() && s.back() == '\n') { s.back() = '.'; } out << s; return out; } inline std::ostream &operator<<(std::ostream &out, Program const &x) { out << "#program " << x.name << Detail::print(x.parameters, "(", ",", ")", false) << "."; return out; } inline std::ostream &operator<<(std::ostream &out, External const &x) { out << "#external " << x.atom << Detail::print_body(x.body); return out; } inline std::ostream &operator<<(std::ostream &out, Edge const &x) { out << "#edge (" << x.u << "," << x.v << ")" << Detail::print_body(x.body); return out; } inline std::ostream &operator<<(std::ostream &out, Heuristic const &x) { out << "#heuristic " << x.atom << Detail::print_body(x.body) << " [" << x.bias<< "@" << x.priority << "," << x.modifier << "]"; return out; } inline std::ostream &operator<<(std::ostream &out, ProjectAtom const &x) { out << "#project " << x.atom << Detail::print_body(x.body); return out; } inline std::ostream &operator<<(std::ostream &out, ProjectSignature const &x) { out << "#project " << x.signature << "."; return out; } inline std::ostream &operator<<(std::ostream &out, Statement const &x) { out << x.data; return out; } // }}}4 // }}}3 } // namespace AST inline void parse_program(char const *program, StatementCallback cb, Logger logger, unsigned message_limit) { using Data = std::pair<StatementCallback &, std::exception_ptr>; Data data(cb, nullptr); Detail::handle_error(clingo_parse_program(program, [](clingo_ast_statement_t const *stm, void *data) -> bool { auto &d = *static_cast<Data*>(data); CLINGO_CALLBACK_TRY { AST::Detail::convStatement(stm, d.first); } CLINGO_CALLBACK_CATCH(d.second); }, &data, [](clingo_warning_t code, char const *msg, void *data) { try { (*static_cast<Logger*>(data))(static_cast<WarningCode>(code), msg); } catch (...) { } }, &logger, message_limit), data.second); } // }}}2 } // namespace Clingo #undef CLINGO_CALLBACK_TRY #undef CLINGO_CALLBACK_CATCH #undef CLINGO_TRY #undef CLINGO_CATCH // }}}1 #endif
35.514048
252
0.677283
tsahyt
ce043e2bd502aab9a92620d06e38ea52824e84a1
3,871
cpp
C++
Menu.cpp
KoheXR/Warzone_Esp_-_aimbot
152754bba7fea464382df5f75844273f94629c9e
[ "MIT" ]
113
2020-03-26T17:56:01.000Z
2022-03-30T02:55:37.000Z
Menu.cpp
KoheXR/Warzone_Esp_-_aimbot
152754bba7fea464382df5f75844273f94629c9e
[ "MIT" ]
21
2020-03-24T09:02:24.000Z
2021-07-21T15:44:28.000Z
Menu.cpp
KoheXR/Warzone_Esp_-_aimbot
152754bba7fea464382df5f75844273f94629c9e
[ "MIT" ]
66
2020-03-25T19:07:51.000Z
2022-03-23T20:08:29.000Z
#pragma once #include <Windows.h> #include "imgui.h" #include "Render.h" #include "Global.h" #include <Settings.h> namespace Menu { bool bIsOpen = true; ImVec4 Red = { 255, 0, 0, 255 }; ImVec4 Green = { 0, 255, 0, 255 }; void MenuInit() { ImGuiStyle& style = ImGui::GetStyle(); style.Alpha = 1.f; style.WindowPadding = ImVec2(28, 14); style.WindowMinSize = ImVec2(32, 32); style.WindowRounding = 0.0f; //4.0 for slight curve style.WindowTitleAlign = ImVec2(0.5f, 0.5f); style.ChildRounding = 0.0f; style.FramePadding = ImVec2(4, 3); style.FrameRounding = 0.0f; //2.0 style.ItemSpacing = ImVec2(8, 4); style.ItemInnerSpacing = ImVec2(4, 4); style.TouchExtraPadding = ImVec2(0, 0); style.IndentSpacing = 21.0f; style.ColumnsMinSpacing = 3.0f; style.ScrollbarSize = 6.0f; style.ScrollbarRounding = 16.0f; //16.0 style.GrabMinSize = 0.1f; style.GrabRounding = 16.0f; //16.00 style.ButtonTextAlign = ImVec2(0.5f, 0.5f); style.DisplayWindowPadding = ImVec2(22, 22); style.DisplaySafeAreaPadding = ImVec2(4, 4); style.AntiAliasedLines = true; style.CurveTessellationTol = 1.25f; } void DrawMenu() { Menu::MenuInit(); ImGuiWindowFlags window_flags = 0; ImGui::SetNextWindowSize(ImVec2(130, 140)); ImGui::SetNextWindowPos(ImVec2(1775, 15)); ImGui::PushFont(m_pTahomaFont); ImGui::Begin("Overflow", NULL, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse); { if (Settings::bEspToggle) { ImGui::PushStyleColor(ImGuiCol_Text, Green); //ImGui::Checkbox("ESP", &Globals::bEspToggle); ImGui::Text("ESP - ON"); } else { ImGui::PushStyleColor(ImGuiCol_Text, Red); ImGui::Text("ESP - OFF"); } ImGui::PopStyleColor(); ImGui::Spacing(); if (Settings::bTextToggle) { ImGui::PushStyleColor(ImGuiCol_Text, Green); ImGui::Text("Text - ON"); } else { ImGui::PushStyleColor(ImGuiCol_Text, Red); ImGui::Text("Text - OFF"); } ImGui::PopStyleColor(); ImGui::Spacing(); if (Settings::bSnapLinesToggle) { ImGui::PushStyleColor(ImGuiCol_Text, Green); ImGui::Text("Snap - ON"); } else { ImGui::PushStyleColor(ImGuiCol_Text, Red); ImGui::Text("Snap - OFF"); } ImGui::PopStyleColor(); ImGui::Spacing(); } ImGui::End(); ImGui::PopFont(); } WNDPROC oWndProc; LRESULT APIENTRY WndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_LBUTTONDOWN: ImGui::GetIO().MouseDown[0] = true; return DefWindowProc(hwnd, uMsg, wParam, lParam); break; case WM_LBUTTONUP: ImGui::GetIO().MouseDown[0] = false; return DefWindowProc(hwnd, uMsg, wParam, lParam); break; case WM_RBUTTONDOWN: ImGui::GetIO().MouseDown[1] = true; return DefWindowProc(hwnd, uMsg, wParam, lParam); break; case WM_RBUTTONUP: ImGui::GetIO().MouseDown[1] = false; return DefWindowProc(hwnd, uMsg, wParam, lParam); break; case WM_MBUTTONDOWN: ImGui::GetIO().MouseDown[2] = true; return DefWindowProc(hwnd, uMsg, wParam, lParam); break; case WM_MBUTTONUP: ImGui::GetIO().MouseDown[2] = false; return DefWindowProc(hwnd, uMsg, wParam, lParam); break; case WM_MOUSEWHEEL: ImGui::GetIO().MouseWheel += GET_WHEEL_DELTA_WPARAM(wParam) > 0 ? +1.0f : -1.0f; return DefWindowProc(hwnd, uMsg, wParam, lParam); break; case WM_MOUSEMOVE: ImGui::GetIO().MousePos.x = (signed short)(lParam); ImGui::GetIO().MousePos.y = (signed short)(lParam >> 16); return DefWindowProc(hwnd, uMsg, wParam, lParam); break; } return CallWindowProc(oWndProc, hwnd, uMsg, wParam, lParam); } void InputInit(HWND hWindow) { oWndProc = (WNDPROC)SetWindowLongPtr(hWindow, GWLP_WNDPROC, (__int3264)(LONG_PTR)WndProc); } void InputRemove(HWND hWindow) { SetWindowLongPtr(hWindow, GWLP_WNDPROC, (LONG_PTR)oWndProc); } }
26.333333
162
0.676569
KoheXR
ce068ce2d0beb8f62fbbba04a379e3db078b0027
10,411
cpp
C++
UISim_C++/src/Graph.cpp
UISim2020/UISim2020
a216898a707079c86807d61e7a157c9fc34d0f59
[ "MIT" ]
1
2021-02-28T10:11:54.000Z
2021-02-28T10:11:54.000Z
UISim_C++/src/Graph.cpp
UISim2020/UISim2020
a216898a707079c86807d61e7a157c9fc34d0f59
[ "MIT" ]
null
null
null
UISim_C++/src/Graph.cpp
UISim2020/UISim2020
a216898a707079c86807d61e7a157c9fc34d0f59
[ "MIT" ]
null
null
null
/* * Graph.cpp * * Created on: 2019��3��13�� * Author: yichen_shen */ #include "Graph.h" #include "TextWriter.h" #include "TextReader.h" #include "Trim.h" #include <math.h> #include "IndexManager.h" #include <time.h> #include <iostream> #include <algorithm> Graph::Graph() { // TODO Auto-generated constructor stub // rnd.seed(time(NULL)); } Graph::~Graph() { // TODO Auto-generated destructor stub } void Graph::preprocess() { unordered_set<Node *, hash_node1> remove; for (auto &n : nodes) { // if (n.in.size() < minNumEdges || n.out.size() < minNumEdges) { if (n.second.in.empty() || n.second.out.empty()) remove.insert(&(n.second)); } if (remove.empty()) return; // finished cout << remove.size() << " nodes to be removed..." << endl; for (auto &n : remove) { // remove from out neighbors' in for (auto &m : n->out) m->in.erase(find(m->in.begin(), m->in.end(), n)); // remove from in neighbors' out for (auto &m : n->in) m->out.erase(find(m->out.begin(), m->out.end(), n)); nodes.erase(n->id); } preprocess(); } void Graph::saveToFile(string nodeFile, string edgeFile) { TextWriter out(nodeFile); for (auto &n : nodes) out.writeln(n.second.id); out.close(); TextWriter newout(edgeFile); int count = 0; for (auto &n : nodes) for (auto &m : n.second.out) { newout.writeln(n.second.id + "\t" + m->id); count++; } newout.close(); cout << "# Nodes: " << nodes.size() << endl; cout << "# Edges: " << count << endl; } void Graph::clear() { nodes.clear(); } void Graph::loadGraphFromFile(string nodeFile, string edgeFile) { clear(); TextReader inN(nodeFile); TextReader inE(edgeFile); string line; cout << "Loading graph" << endl; int count = 0; while ((line = inN.readln()).size() != 0) { int id = atoi(line.c_str()); addNode(Node(id, count)); // for exact //this.nodesIndex[count]=id; // System.out.println("Test node index----Graph:Line103-----Node id: "+ id+" index: "+count); count++; if (count % 100000 == 0) cout << "."; } while ((line = inE.readln()).size() != 0) { vector<string> ssplit; split(line, "\t", ssplit); int from = atoi(ssplit[0].c_str()); // System.out.println(from); int to = atoi(ssplit[1].c_str()); addEdge(from, to); // count++; // if (count % 1000000 == 0) // System.out.print("."); } cout << "Loading end" << endl; inN.close(); inE.close(); init(); } void Graph::loadFromFile(string nodeFile, string edgeFile, bool identifyHubs) { loadGraphFromFile(nodeFile, edgeFile); if (identifyHubs) { string hubNodeFile = IndexManager::getHubNodeFile(); loadHubs(hubNodeFile); } } void Graph::loadFromFile(string nodeFile, string edgeFile, string hubFile) { loadGraphFromFile(nodeFile, edgeFile); loadHubs(hubFile); } void Graph::loadHubs(string hubNodeFile) { TextReader in(hubNodeFile); string line; unordered_set<Node *, hash_node1> hubs; while ((line = in.readln()).length() != 0) { if (hubs.size() == Config::numHubs) break; int id = atoi(line.c_str()); Node *n = &getNode(id); // if (n == null) // n = new Node(id); n->isHub = true; hubs.insert(n); } in.close(); } unordered_set<Node *, hash_node1> Graph::getHubs() { return hubs; } void Graph::addNode(const Node &n) { nodes[n.id] = n; } void Graph::addEdge(int from, int to) { Node *nFrom = &getNode(from); Node *nTo = &getNode(to); nFrom->out.push_back(nTo); nTo->in.push_back(nFrom); } void Graph::resetPrimeG() { // auto n = nodes.begin(); // while(n!=nodes.end()) // { // n->second.isVisited = false; // n++; // } unordered_set<int> tmp; is_visited.swap(tmp); } void Graph::computeOutPrimeSim(Node &q, double maxhubScore, PrimeSim &outSim) { auto &simmap = outSim.getMap(); unordered_map<int, unordered_map<int, double>>::iterator simit; vector<Node *> expNodes; unordered_map<int, double> valInLastLevel; vector<Node *> newExpNodes; unordered_map<int, double> valInThisLevel; double rea; expNodes.push_back(&q); is_visited.insert(q.id); //q.isVisited = true; //don't save query node as hub or meeting node outSim.addNewNode(q, false, is_visited); outSim.set(0, q, 1.0); valInLastLevel[q.id] = 1.0; int length = 1; while (length <= DEPTH) { if (expNodes.size() == 0) break; newExpNodes.resize(0); valInThisLevel.clear(); for (auto &cur : expNodes) { //System.out.println("current node: " + cur.id); for (auto &n : cur->out) { // an edge cur-->n, where cur is meeting node, so for n, should store the Reversed reachability: R(n->cur)=1*1/In(n) //System.out.println("out:" + n.id); if (is_visited.find(n->id) == is_visited.end()) outSim.addNewNode(*n, false, is_visited); rea = (double)valInLastLevel[cur->id] / (double)n->in.size() * (double)sqrt(Config::alpha); //*(Config.alpha)2.26: ensure the prime subgraphs are not too large //know the reachability when expanding hubs // double rea = valInLastLevel.get(cur.id)/n.in.size();//modified 8.27, don't multiply alpha at this time, otherwise will double multiply alpha^length as another tour also has this alpha, so leave it for online merging. if (rea * maxhubScore > ITER_STOP) { if (valInThisLevel.find(n->id) == valInThisLevel.end()) { //System.out.println("value:" + rea); valInThisLevel[n->id] = rea; if (n->out.size() > 0 && !n->isHub) newExpNodes.push_back(n); } else valInThisLevel[n->id] = valInThisLevel[n->id] + rea; } } } outSim.set(length, valInThisLevel); // System.out.println(length); // for(Integer i:valInThisLevel.keySet()) { // System.out.println("node:" + i + " rea:" + valInThisLevel.get(i)); // } expNodes = newExpNodes; //newExpNodes.clear(); valInLastLevel = valInThisLevel; //valInThisLevel.clear(); length++; } /* for(Integer m:outSim.map.keySet()) { System.out.println("length:" + m); //System.out.println(outSim.map.get(m).size()); for(Integer n:outSim.map.get(m).keySet()) { System.out.println("node:" + n + " rea:" + outSim.map.get(m).get(n)); } }*/ // System.out.println("Remove empty length (Out) for node " + q.id); for (simit = simmap.begin(); simit != simmap.end();) { if (simit->second.size() == 0) { // System.out.println("No such length in Insim " + l); simit = simmap.erase(simit); } else { simit++; } } } void Graph::computeInPrimeSim(Node &q, double maxhubScore, PrimeSim &inSim) { auto &simmap = inSim.getMap(); unordered_map<int, unordered_map<int, double>>::iterator simit; vector<Node *> expNodes; //List<Node> newExpNodes = new ArrayList <Node>(); unordered_map<int, double> valInLastLevel; //Map<Integer,Double> valInThisLevel = new HashMap<Integer,Double>(); expNodes.push_back(&q); // Nodes to be expanded, initially only q //add 2/23/2015 inSim.addNewNode(q, true, is_visited); //q.isVisited = true; inSim.set(0, q, 1.0); valInLastLevel[q.id] = 1.0; int length = 1; vector<Node *> newExpNodes; unordered_map<int, double> valInThisLevel; double rea; while (length <= DEPTH) { if (expNodes.size() == 0) break; newExpNodes.resize(0); valInThisLevel.clear(); for (auto cur : expNodes) { for (auto n : cur->in) { //a edge n-->cur, if R(cur)==a, then R(n)==1/In(cur)*a, because of the reversed walk from cur to n. if (is_visited.find(n->id) == is_visited.end()) inSim.addNewNode(*n, true, is_visited); // mark n as visited and add n to meetingNodes in PrimeSim rea = valInLastLevel[cur->id] / (double)cur->in.size() * sqrt(Config::alpha); // // cout<<cur->id<<endl; // System.out.println(n+": "+ rea); // double rea = valInLastLevel.get(cur.id)/cur.in.size(); // modified 8.27, mutiply alpha later when merge two tours if (rea * maxhubScore > ITER_STOP) { if (valInThisLevel.find(n->id) == valInThisLevel.end()) { valInThisLevel[n->id] = rea; if (n->in.size() > 0 && !n->isHub) newExpNodes.push_back(n); } else valInThisLevel[n->id] = valInThisLevel[n->id] + rea; } } } inSim.set(length, valInThisLevel); expNodes = newExpNodes; //newExpNodes.clear(); valInLastLevel = valInThisLevel; //valInThisLevel.clear(); length++; } // System.out.println("Remove empty length for node " + q.id); for (simit = simmap.begin(); simit != simmap.end();) { if (simit->second.size() == 0) { // System.out.println("No such length in Insim " + l); simit = simmap.erase(simit); } else { simit++; } } } int Graph::numNodes() { return nodes.size(); } Node &Graph::getNode(int id) { if (nodes.find(id) == nodes.end()) nodes[id] = Node(id); return nodes[id]; } vector<Node *> Graph::getNodes() { vector<Node *> no; for (auto &it : nodes) no.push_back(&(it.second)); return no; } bool Graph::containsNode(int id) { return nodes.find(id) != nodes.end(); } Graph::Graph(const Graph &Graph) { this->nodes = Graph.nodes; this->hubs = Graph.hubs; } int Graph::findNode(int index) { for (auto &n : nodes){ if (n.second.index == index) return n.second.id; } return -1; } void Graph::init() { for (auto &n : nodes) n.second.initOutEdgeWeight(); }
26.356962
320
0.556143
UISim2020
ce0a5572f40aed049ddc9a6c35be6f68446c9dd4
333
cpp
C++
monisai_2/problem_5.cpp
Leon-Francis/AlgorithmPractice
bfff066da64ebbb00ecd33d94ebbe5bcc382867c
[ "MIT" ]
1
2020-10-07T12:03:12.000Z
2020-10-07T12:03:12.000Z
monisai_2/problem_5.cpp
Leon-Francis/AlgorithmPractice
bfff066da64ebbb00ecd33d94ebbe5bcc382867c
[ "MIT" ]
null
null
null
monisai_2/problem_5.cpp
Leon-Francis/AlgorithmPractice
bfff066da64ebbb00ecd33d94ebbe5bcc382867c
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main(int argc, char const *argv[]) { int n; int a, b, c; cin >> n >> a >> b >> c; int res = 0; for (int i = 1; i <= n; i++) { if (i % a != 0 && i % b != 0 && i % c != 0) { res++; } } cout << res << endl; return 0; }
17.526316
51
0.378378
Leon-Francis
ce0d17629d550b1c8cb95fb03596ccd2750caaec
6,716
cc
C++
mesh/mesh.cc
rafgitdz/bimodal-scheduler-rstm
7d6f795e6a2820a4c59cdc195bcea4d13c5d20c8
[ "BSD-3-Clause" ]
null
null
null
mesh/mesh.cc
rafgitdz/bimodal-scheduler-rstm
7d6f795e6a2820a4c59cdc195bcea4d13c5d20c8
[ "BSD-3-Clause" ]
null
null
null
mesh/mesh.cc
rafgitdz/bimodal-scheduler-rstm
7d6f795e6a2820a4c59cdc195bcea4d13c5d20c8
[ "BSD-3-Clause" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2006, 2007 // University of Rochester // Department of Computer Science // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of the University of Rochester nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. /* mesh.cc * * Delaunay triangularization. * * Michael L. Scott, 2006-2007. */ #include <unistd.h> // for getopt() #include <iostream> using std::cout; using std::cerr; #include "config.h" #include "lock.h" #include "point.h" #include "edge.h" #include "edge_set.h" #include "my_thread.h" #include "dwyer.h" #include "worker.h" d_lock io_lock; unsigned long long start_time; unsigned long long last_time; edge_set *edges; int num_points = 100; // number of points int num_workers = 4; // threads static int seed = 1; // for random # gen bool output_incremental = false; // dump edges as we go along bool output_end = false; // dump edges at end bool verbose = false; // print stats // verbose <- (output_incremental || output_end) static bool read_points = false; // read points from stdin static void usage() { cerr << "usage: mesh [-p] [-oi] [-oe] [-v] [-n points] [-w workers] [-s seed]\n"; cerr << "\t-p: read points from stdin\n" << "\t-oi: output edges incrementally\n" << "\t-oe: output edges at end\n" << "\t-v: print timings, etc., even if not -oi or -oe\n"; exit(1); } static void parse_args(int argc, char* argv[]) { int c; while ((c = getopt(argc, argv, "o:vpn:w:s:")) != -1) { switch (c) { case 'o': verbose = true; switch (optarg[0]) { case 'i': output_incremental = true; break; case 'e': output_end = true; break; default: usage(); // does not return } break; case 'p': read_points = true; case 'v': verbose = true; break; case 'n': num_points = atoi(optarg); break; case 'w': num_workers = atoi(optarg); if (num_workers < 1 || num_workers > MAX_WORKERS) { cerr << "numWorkers must be between 1 and " << MAX_WORKERS << "\n"; exit(1); } break; case 's': seed = atoi(optarg); assert (seed != 0); break; case '?': default: usage(); // does not return } } if (optind != argc) usage(); // does not return } int main(int argc, char* argv[]) { parse_args(argc, argv); stm::init("Polka", "invis-eager", true /*use_static_cm*/); if (verbose) { // Print args, X and Y ranges for benefit of optional display tool: for (int i = 0; i < argc; i++) { cout << argv[i] << " "; } cout << "\n"; } create_points(read_points ? 0 : seed); start_time = last_time = getElapsedTime(); edges = new edge_set; // has to be done _after_ initializing num_workers // But note: initialization will not be complete until every // thread calls help_initialize() if (num_workers == 1) { int min_coord = -(2 << (MAX_COORD_BITS-1)); // close enough int max_coord = (2 << (MAX_COORD_BITS-1)) - 1; // close enough edges->help_initialize(0); unsigned long long now; if (verbose) { now = getElapsedTime(); cout << "time: " << (now - start_time)/1e9 << " " << (now - last_time)/1e9 << " (point partitioning)\n"; last_time = now; } dwyer_solve(all_points, 0, num_points - 1, min_coord, max_coord, min_coord, max_coord, 0); now = getElapsedTime(); if (verbose) { cout << "time: " << (now - start_time)/1e9 << " " << (now - last_time)/1e9 << " (Dwyer triangulation)\n"; } cout << "time: " << (now - start_time)/1e9 << " " << (now - last_time)/1e9 << " (join)\n"; last_time = now; } else { region_info **regions = new region_info*[num_workers]; barrier *bar = new barrier(num_workers); thread **workers = new thread*[num_workers]; for (int i = 0; i < num_workers; i++) { workers[i] = new thread(new worker(i, regions, bar)); } for (int i = 0; i < num_workers; i++) { delete workers[i]; // join } unsigned long long now = getElapsedTime(); cout << "time: " << (now - start_time)/1e9 << " " << (now - last_time)/1e9 << " (join)\n"; last_time = now; } if (output_end) edges->print_all(); }
35.162304
85
0.532609
rafgitdz
ce0e1e0faadcaf6c25efd0bc96d178b7ddadeeb8
576
hpp
C++
metaforce-gui/ArgumentEditor.hpp
Jcw87/urde
fb9ea9092ad00facfe957ece282a86c194e9cbda
[ "MIT" ]
267
2016-03-10T21:59:16.000Z
2021-03-28T18:21:03.000Z
metaforce-gui/ArgumentEditor.hpp
cobalt2727/metaforce
3bb05c0ee5dd9b1b8eaa861fc49713aef62c844a
[ "MIT" ]
129
2016-03-12T10:17:32.000Z
2021-04-05T20:45:19.000Z
metaforce-gui/ArgumentEditor.hpp
cobalt2727/metaforce
3bb05c0ee5dd9b1b8eaa861fc49713aef62c844a
[ "MIT" ]
31
2016-03-20T00:20:11.000Z
2021-03-10T21:14:11.000Z
#pragma once #include <memory> #include <QDialog> #include <QStringListModel> class QAbstractButton; namespace Ui { class ArgumentEditor; } // namespace Ui class ArgumentEditor : public QDialog { Q_OBJECT std::unique_ptr<Ui::ArgumentEditor> m_ui; QStringListModel m_model; public: explicit ArgumentEditor(QWidget* parent = nullptr); ~ArgumentEditor() override; private slots: void on_addButton_clicked(); void on_addCvarButton_clicked(); void on_editButton_clicked(); void on_deleteButton_clicked(); void on_buttonBox_clicked(QAbstractButton*); };
18.580645
53
0.767361
Jcw87
ce167cd9fce344ee1e0ad491f4320d99794eb0f2
7,110
cpp
C++
ODFAEG/src/odfaeg/Physics/boundingEllipsoid.cpp
Ornito/ODFAEG-1
f563975ae4bdd2e178d1ed7267e1920425aa2c4d
[ "Zlib" ]
5
2015-06-13T13:11:59.000Z
2020-04-17T23:10:23.000Z
ODFAEG/src/odfaeg/Physics/boundingEllipsoid.cpp
Ornito/ODFAEG-1
f563975ae4bdd2e178d1ed7267e1920425aa2c4d
[ "Zlib" ]
4
2019-01-07T11:46:21.000Z
2020-02-14T15:04:15.000Z
ODFAEG/src/odfaeg/Physics/boundingEllipsoid.cpp
Ornito/ODFAEG-1
f563975ae4bdd2e178d1ed7267e1920425aa2c4d
[ "Zlib" ]
4
2016-01-05T09:54:57.000Z
2021-01-06T18:52:26.000Z
#include "../../../include/odfaeg/Physics/boundingEllipsoid.h" #include "../../../include/odfaeg/Physics/boundingSphere.h" #include "../../../include/odfaeg/Physics/boundingBox.h" #include "../../../include/odfaeg/Physics/orientedBoundingBox.h" #include "../../../include/odfaeg/Physics/boundingPolyhedron.h" #include "../../../include/odfaeg/Graphics/transformMatrix.h" namespace odfaeg { namespace physic { BoundingEllipsoid::BoundingEllipsoid(math::Vec3f center, int a, int b, int c) { this->center = center; radius = math::Vec3f(a, b, c); graphic::TransformMatrix tm; tm.setOrigin(center); tm.setTranslation(center); tm.update(); translation = tm.getMatrix(); tm.reset3D(); tm.setOrigin(center); tm.setScale(radius); tm.update(); scale = tm.getMatrix(); } bool BoundingEllipsoid::intersects(BoundingSphere &bs, CollisionResultSet::Info& info) { //We do the same for check the collision with a circle, except taht the circle have only 1 ray. //The equation for the circle is then a bit different. math::Ray r(bs.getCenter(), center); math::Vec3f near, far; if (!intersectsWhere(r, near, far, info)) return false; math::Vec3f d = far - center; return (center.computeDistSquared(bs.getCenter()) - bs.getRadius() * bs.getRadius() - d.magnSquared()) <= 0; } bool BoundingEllipsoid::intersects(BoundingEllipsoid &be, CollisionResultSet::Info& info) { //The distance between the 2 centers. math::Ray r1(center, be.getCenter()); math::Ray r2(be.getCenter(), center); math::Vec3f near1, near2, far1, far2; if (!intersectsWhere(r1, near1, far1, info)) return false; if (!be.intersectsWhere(r2, near2, far2, info)) return false; math::Vec3f d1 = far1 - center; math::Vec3f d2 = far2 - be.getCenter(); return (center.computeDistSquared(be.getCenter()) - d1.magnSquared() - d2.magnSquared()) <= 0; } bool BoundingEllipsoid::intersects(BoundingBox &bx, CollisionResultSet::Info& info) { math::Ray r1(center, bx.getCenter()); math::Ray r2(bx.getCenter(), center); math::Vec3f near1, near2, far1, far2; if (!intersectsWhere(r1, near1, far1, info)) return false; if (!bx.intersectsWhere(r2, near2, far2, info)) return false; math::Vec3f d1 = far1 - center; math::Vec3f d2 = far2 - bx.getCenter(); return (center.computeDistSquared(bx.getCenter()) - d1.magnSquared() - d2.magnSquared()) <= 0; } bool BoundingEllipsoid::intersects(OrientedBoundingBox &obx, CollisionResultSet::Info& info) { //The line between the two centers. math::Ray r1(center, obx.getCenter()); math::Ray r2(obx.getCenter(), center); math::Vec3f near1, near2, far1, far2; if (!intersectsWhere(r1, near1, far1, info)) return false; if (!obx.intersectsWhere(r2, near2, far2, info)) return false; math::Vec3f d1 = far1 - center; math::Vec3f d2 = far2 - obx.getCenter(); return (center.computeDistSquared(obx.getCenter()) - d1.magnSquared() - d2.magnSquared()) <= 0; } bool BoundingEllipsoid::intersects(BoundingPolyhedron &bp, CollisionResultSet::Info& info) { math::Ray r1(center, bp.getCenter()); math::Ray r2(bp.getCenter(), center); math::Vec3f near1, near2, far1, far2; if (!intersectsWhere(r1, near1, far1, info)) return false; if (!bp.intersectsWhere(r2, near2, far2, info)) return false; math::Vec3f d1 = far1 - center; math::Vec3f d2 = far2 - bp.getCenter(); return (center.computeDistSquared(bp.getCenter()) - d1.magnSquared() -d2.magnSquared()) <= 0; } bool BoundingEllipsoid::intersects (math::Ray &r, bool segment, CollisionResultSet::Info& info) { math::Matrix4f transform = scale * rotation * translation; math::Matrix4f invTransform = transform.inverse(); math::Vec3f orig = invTransform * r.getOrig(); math::Vec3f ext = invTransform * r.getExt(); math::Ray tRay (orig, ext); math::Vec3f mtu; BoundingSphere bs(math::Vec3f(0, 0, 0), 1); if (!bs.intersects(tRay, segment, info)) return false; return false; } bool BoundingEllipsoid::intersectsWhere(math::Ray& r, math::Vec3f& near, math::Vec3f& far, CollisionResultSet::Info& info) { math::Matrix4f transform = scale * rotation * translation; math::Matrix4f invTransform = transform.inverse(); math::Vec3f orig = invTransform * r.getOrig(); math::Vec3f ext = invTransform * r.getExt(); math::Ray tRay (orig, ext); math::Vec3f i1, i2; BoundingSphere bs(math::Vec3f(0, 0, 0), 1); if (!bs.intersectsWhere(tRay, i1, i2, info)) return false; near = transform * i1; far = transform * i2; return true; } bool BoundingEllipsoid::isPointInside (math::Vec3f point) { math::Ray r (center, point); CollisionResultSet::Info info; if (!intersects(r, false, info)) return false; return true; } math::Vec3f BoundingEllipsoid::getPosition() { return math::Vec3f (center.x - radius.x, center.y - radius.y, center.z - radius.z); } math::Vec3f BoundingEllipsoid::getCenter() { return center; } math::Vec3f BoundingEllipsoid::getRadius() { return radius; } math::Vec3f BoundingEllipsoid::getSize() { return math::Vec3f(radius.x * 2, radius.y * 2, radius.z * 2); } void BoundingEllipsoid::move(math::Vec3f t) { center += t; graphic::TransformMatrix tm; tm.setOrigin(center); tm.setTranslation(center); tm.update(); translation = tm.getMatrix(); } void BoundingEllipsoid::setScale(math::Vec3f s) { graphic::TransformMatrix tm; tm.setOrigin(center); tm.setScale(s); tm.update(); scale = tm.getMatrix(); } void BoundingEllipsoid::rotate(float angle, math::Vec3f axis) { graphic::TransformMatrix tm; tm.setOrigin(center); tm.setRotation(axis, angle); tm.update(); rotation = tm.getMatrix(); } } }
46.776316
133
0.549648
Ornito
ce18a18695db87268aba899ee8cdc2707ca00df5
6,990
cpp
C++
MaterialLib/MPL/CreateProperty.cpp
yezhigangzju/ogs
074c5129680e87516477708b081afe79facabe87
[ "BSD-3-Clause" ]
1
2019-10-24T02:38:44.000Z
2019-10-24T02:38:44.000Z
MaterialLib/MPL/CreateProperty.cpp
yezhigangzju/ogs
074c5129680e87516477708b081afe79facabe87
[ "BSD-3-Clause" ]
null
null
null
MaterialLib/MPL/CreateProperty.cpp
yezhigangzju/ogs
074c5129680e87516477708b081afe79facabe87
[ "BSD-3-Clause" ]
null
null
null
/** * \file * \author Norbert Grunwald * \date Sep 7, 2017 * * \copyright * Copyright (c) 2012-2020, OpenGeoSys Community (http://www.opengeosys.org) * Distributed under a Modified BSD License. * See accompanying file LICENSE.txt or * http://www.opengeosys.org/project/license */ #include "CreateProperty.h" #include <string> #include <vector> #include "BaseLib/ConfigTree.h" #include "Component.h" #include "Medium.h" #include "Phase.h" #include "Properties/CreateProperties.h" #include "Properties/Properties.h" namespace { std::unique_ptr<MaterialPropertyLib::Property> createProperty( int const geometry_dimension, BaseLib::ConfigTree const& config, std::vector<std::unique_ptr<ParameterLib::ParameterBase>> const& parameters, ParameterLib::CoordinateSystem const* const local_coordinate_system, std::map<std::string, std::unique_ptr<MathLib::PiecewiseLinearInterpolation>> const& curves) { using namespace MaterialPropertyLib; // Parsing the property type: //! \ogs_file_param{properties__property__type} auto const property_type = config.peekConfigParameter<std::string>("type"); if (property_type == "Constant") { return createConstant(config); } if (property_type == "Curve") { return createCurve(config, curves); } if (property_type == "Linear") { return createLinear(config); } if (property_type == "Exponential") { return createExponential(config); } if (property_type == "Parameter") { return createParameterProperty(config, parameters); } if (boost::iequals(property_type, "AverageMolarMass")) { return createAverageMolarMass(config); } if (boost::iequals(property_type, "ClausiusClapeyron")) { return createClausiusClapeyron(config); } if (boost::iequals(property_type, "Dupuit")) { return createDupuitPermeability(config, parameters); } if (boost::iequals(property_type, "IdealGasLaw")) { return createIdealGasLaw(config); } if (boost::iequals(property_type, "StrainDependentPermeability")) { return createStrainDependentPermeability( geometry_dimension, config, parameters, local_coordinate_system); } if (boost::iequals(property_type, "PermeabilityMohrCoulombFailureIndexModel")) { return createPermeabilityMohrCoulombFailureIndexModel( geometry_dimension, config, parameters, local_coordinate_system); } if (boost::iequals(property_type, "KozenyCarman")) { return createKozenyCarmanModel(config, parameters); } if (boost::iequals(property_type, "PermeabilityOrthotropicPowerLaw")) { return createPermeabilityOrthotropicPowerLaw(config, local_coordinate_system); } if (boost::iequals(property_type, "PorosityFromMassBalance")) { return createPorosityFromMassBalance(config, parameters); } if (boost::iequals(property_type, "TransportPorosityFromMassBalance")) { return createTransportPorosityFromMassBalance(config, parameters); } if (boost::iequals(property_type, "SaturationBrooksCorey")) { return createSaturationBrooksCorey(config); } if (boost::iequals(property_type, "RelPermBrooksCorey")) { return createRelPermBrooksCorey(config); } if (boost::iequals(property_type, "SaturationLiakopoulos")) { return createSaturationLiakopoulos(config); } if (boost::iequals(property_type, "RelPermLiakopoulos")) { return createRelPermLiakopoulos(config); } if (boost::iequals(property_type, "SaturationVanGenuchten")) { return createSaturationVanGenuchten(config); } if (boost::iequals(property_type, "CapillaryPressureVanGenuchten")) { return createCapillaryPressureVanGenuchten(config); } if (boost::iequals(property_type, "CapillaryPressureRegularizedVanGenuchten")) { return createCapillaryPressureRegularizedVanGenuchten(config); } if (boost::iequals(property_type, "RelativePermeabilityVanGenuchten")) { return createRelPermVanGenuchten(config); } if (boost::iequals(property_type, "RelativePermeabilityUdell")) { return createRelPermUdell(config); } if (boost::iequals(property_type, "SaturationDependentHeatConduction")) { return createSaturationDependentHeatConduction(config); } if (boost::iequals(property_type, "SaturationDependentSwelling")) { return createSaturationDependentSwelling(config, local_coordinate_system); } if (boost::iequals(property_type, "BishopsPowerLaw")) { return createBishopsPowerLaw(config); } if (boost::iequals(property_type, "BishopsSaturationCutoff")) { return createBishopsSaturationCutoff(config); } if (boost::iequals(property_type, "LinearSaturationSwellingStress")) { return createLinearSaturationSwellingStress(config); } // If none of the above property types are found, OGS throws an error. OGS_FATAL("The specified component property type '{:s}' was not recognized", property_type); } } // namespace namespace MaterialPropertyLib { std::unique_ptr<PropertyArray> createProperties( int const geometry_dimension, boost::optional<BaseLib::ConfigTree> const& config, std::vector<std::unique_ptr<ParameterLib::ParameterBase>> const& parameters, ParameterLib::CoordinateSystem const* const local_coordinate_system, std::map<std::string, std::unique_ptr<MathLib::PiecewiseLinearInterpolation>> const& curves) { if (!config) { return nullptr; } //! \ogs_file_param{properties__property} auto const& property_configs = config->getConfigSubtreeList("property"); if (property_configs.empty()) { return nullptr; } auto properties = std::make_unique<PropertyArray>(); for (auto property_config : property_configs) { // Parsing the property name: auto const property_name = //! \ogs_file_param{properties__property__name} property_config.getConfigParameter<std::string>("name"); // Create a new property based on the configuration subtree: auto property = createProperty(geometry_dimension, property_config, parameters, local_coordinate_system, curves); // Insert the new property at the right position into the components // private PropertyArray: (*properties)[convertStringToProperty(property_name)] = std::move(property); } return properties; } } // namespace MaterialPropertyLib
29.004149
80
0.667811
yezhigangzju
ce1bade86ec6eb36605e8ec4c5319b5e49b1378b
2,738
cpp
C++
Level/GameLevel.cpp
sagbonkh/Sokoban_Solver
96290f4d85d36ff2591eca96c7d4d694e0763b8d
[ "Unlicense" ]
null
null
null
Level/GameLevel.cpp
sagbonkh/Sokoban_Solver
96290f4d85d36ff2591eca96c7d4d694e0763b8d
[ "Unlicense" ]
null
null
null
Level/GameLevel.cpp
sagbonkh/Sokoban_Solver
96290f4d85d36ff2591eca96c7d4d694e0763b8d
[ "Unlicense" ]
null
null
null
// Copyright Tobias Faller 2016 #include <Level/GameLevel.h> #include <Level/MapGrid.h> #include <Level/Parser.h> #include <numeric> #include <fstream> #include <string> namespace Sokoban { using std::ifstream; using std::istream; using std::to_string; using std::string; using std::endl; using std::cout; using std::cerr; using std::plus; using std::accumulate; using namespace std::string_literals; GameLevel::GameLevel(const std::string &path, pos_type pos) : _path(path), _pos(pos) { } GameLevel::GameLevel(const std::string &path, ifstream &in) : _path(path), _pos(in.tellg()) { // loop until next level string line = " "; while (!line.empty() && !in.eof()) { getline(in, line); } } GameLevel::GameLevel(istream &in) { load(in); } vector<shared_ptr<const GameLevel>> GameLevel::loadAllFromFile(const string &filename) { vector<shared_ptr<const GameLevel>> result; ifstream in(filename); if (!in.is_open()) throw "File not found"; shared_ptr<const GameLevel> nextLevel = nullptr; do { nextLevel = nullptr; if (in.eof()) break; try { nextLevel = make_shared<GameLevel>(filename, in); if (!*nextLevel) continue; result.push_back(nextLevel); // cout << static_cast<string>(*nextLevel) << endl; } catch (std::exception &e) { cerr << "Level could not be parsed." << endl; } } while (nextLevel); in.close(); return result; } void GameLevel::load(istream &in) const { if (_loaded) return; Parser parser(in); if (!parser.success()) throw "Parsing failed"; _name = parser.getName(); _map = parser.getMap(); if (_map->empty()) { _map = nullptr; } _loaded = true; } void GameLevel::load() const { if (_loaded) return; ifstream in(_path); try { if (!in.is_open()) throw "File not found"; in.seekg(_pos); load(in); in.close(); } catch (const std::exception &e) { throw "Level could not be read from path "s + _path + " at position "s + to_string(_pos); } } const std::string& GameLevel::getName() const { if (!_loaded) load(); return _name; } const shared_ptr<const MapGrid::initial_map_t>& GameLevel::getMap() const { if (!_loaded) load(); return _map; } std::shared_ptr<const GameLevel> GameLevel::getptr() const { return shared_from_this(); } bool GameLevel::isEmpty() const { if (!_loaded) load(); return !_map || _map->empty(); } GameLevel::operator bool() const { return !isEmpty(); } GameLevel::operator string() const { if (isEmpty()) return "<EMPTY GAME LEVEL>"; string result; const MapGrid::initial_map_t &map = *getMap(); result += "; " + getName() + "\n"; for (const auto &row : map) { result += accumulate(row.begin(), row.end(), string(), plus<string> {}) + "\n"; } return result; } } // namespace Sokoban
19.985401
88
0.663988
sagbonkh
ce1c085e4aca19e94177342faceaba2a95979e28
22,232
cpp
C++
test/interpolation-test.cpp
12ff54e/BSplineInterpolation
b0f04414807bea999c5102f1274ea2ad9c2a6b6f
[ "MIT" ]
5
2022-03-21T08:50:42.000Z
2022-03-31T05:31:41.000Z
test/interpolation-test.cpp
12ff54e/BSplineInterpolation
b0f04414807bea999c5102f1274ea2ad9c2a6b6f
[ "MIT" ]
null
null
null
test/interpolation-test.cpp
12ff54e/BSplineInterpolation
b0f04414807bea999c5102f1274ea2ad9c2a6b6f
[ "MIT" ]
1
2022-03-31T11:12:24.000Z
2022-03-31T11:12:24.000Z
#include "../src/include/Interpolation.hpp" #include "./Assertion.hpp" #include "./rel_err.hpp" #include <algorithm> #include <iostream> int main() { using namespace std; using namespace intp; // These tests are done by comparing interpolation results with that from // MMA. Assertion assertion; constexpr double tol = 1e-14; // 1D interpolation test array<double, 13> f{{0.905515, 0.894638, -0.433134, 0.43131, -0.131052, 0.262974, 0.423888, -0.562671, -0.915567, -0.261017, -0.47915, -0.00939326, -0.445962}}; InterpolationFunction1D<double> interp{std::make_pair(0, .5 * (f.size() - 1)), std::make_pair(f.begin(), f.end())}; auto coords_1d_half = {1.968791374707961, 0.23397112295047862, 4.183162505803409, 5.744438451300649, 0.322817339924379, 5.431730686042901, 1.2745684388796121, 0.21339197545741406, 1.5321444095845136, 0.64165470553346}; // some random points auto coords_1d = {3.937582749415922, 0.46794224590095723, 8.366325011606818, 11.488876902601298, 0.645634679848758, 10.863461372085801, 2.5491368777592243, 0.4267839509148281, 3.064288819169027, 1.28330941106692}; // Values pre-computed by MMA auto vals_1d = {-0.10342680140577024, 1.4404772594187227, -0.6740383362867217, 0.059044924309338276, 1.3546807267401677, -0.08084215107000194, 0.01725408002459637, 1.4414547842595904, 0.444175804071652, 0.39522879177749654}; std::cout << "\n1D Interpolation Test:\n"; double d = rel_err( interp, std::make_pair(coords_1d_half.begin(), coords_1d_half.end()), std::make_pair(vals_1d.begin(), vals_1d.end())); assertion(d < tol); std::cout << "\n1D test " << (assertion.last_status() == 0 ? "succeed" : "failed") << '\n'; std::cout << "Relative Error = " << d << '\n'; assertion(std::abs(interp(-.5) - (-6.3167718907512755)) < tol, "Out of left boundary extrapolation did not work as expected.\n"); assertion( std::abs(interp(6.5) - (-4.508470210464194)) < tol, "Out of right boundary extrapolation did not work as expected.\n"); // 2D interpolation test // random 5x5 mesh grid constexpr array<array<double, 5>, 5> f2{ {{0.1149376591802711, 0.366986491879822, 0.8706293477610783, 0.35545268902617266, 0.5618622985788111}, {0.20103081669915168, -0.35136997700640915, 0.3459158000280991, -0.6411854570589961, -0.924275445068762}, {0.0609591391461084, -0.9863975752412686, 0.6961713590119816, 0.8400181479240318, 0.3758703506622121}, {-0.849674573235994, 0.7037626673100483, 0.5167482535099701, -0.961602882417603, 0.9016008505150341}, {-0.7763245335851283, 0.729592963642911, -0.5861424925445622, -0.3508132480272552, 0.7075736670162986}}}; Mesh<double, 2> f2d{f2.size(), f2[0].size()}; for (unsigned i = 0; i < f2d.dim_size(0); ++i) { for (unsigned j = 0; j < f2d.dim_size(1); ++j) { f2d(i, j) = f2[i][j]; } } InterpolationFunction<double, 2> interp2{ 3, f2d, make_pair(0., f2d.dim_size(0) - 1.), make_pair(0., f2d.dim_size(1) - 1.)}; // some random points constexpr array<array<double, 2>, 10> coords_2d{ {{2.7956403386992656, 0.16702594760696154}, {0.14620918612600242, 1.80574833501798}, {0.912690726300375, 1.617752882497217}, {3.4743760585635837, 3.235474073888084}, {3.2819951814307826, 1.2227470066832273}, {2.6455842429367955, 2.5079261616463135}, {2.4398083528195187, 2.6353068861468163}, {0.3906420637429102, 0.4383471604184015}, {3.702137078579508, 3.366239031714958}, {1.0831817822035914, 1.7656688800854026}}}; // and their spline value, pre-computed by MMA constexpr array<double, 10> vals_2d{ {-0.5407817111102959, 0.724190993527158, 0.25189765520792373, -1.4791573194664718, 1.1465605774177101, 0.3098484329528253, 0.5464869245836507, 0.0474466547034479, -1.0511757647770876, 0.2755974099701995}}; std::cout << "\n2D Interpolation Test:\n"; assertion(interp2.uniform(0) && interp2.uniform(1), "Uniform properties check failed."); d = rel_err(interp2, std::make_pair(coords_2d.begin(), coords_2d.end()), std::make_pair(vals_2d.begin(), vals_2d.end())); assertion(d < tol); std::cout << "\n2D test " << (assertion.last_status() == 0 ? "succeed" : "failed") << '\n'; std::cout << "Relative Error = " << d << '\n'; try { interp2.at(-1, 1); assertion(false, "Out of boundary check failed.\n"); } catch (const std::domain_error& e) { std::cout << "Out of boundary check succeed.\n"; } // 3D interpolation test // random 5x6x7 mesh grid constexpr array<array<array<double, 7>, 6>, 5> f3{ {{{{0.7227454556577735, 0.12338574902709754, 0.3377337587737288, 0.8091623938771417, 0.9293380971320708, -0.5741047532957699, -0.2200926742338356}, {-0.10763006732480607, 0.0013429236738118355, 0.4513036540324049, -0.026003741605878705, -0.3695306079209315, 0.8136434953103922, -0.5116150484018025}, {-0.8677823131366349, 0.8365100339234104, 0.7501947382164902, 0.29910348046032365, 0.6232336678925097, 0.5087192462972618, -0.893065394522043}, {-0.4851529104440644, 0.03957209074264867, 0.2539529968314116, -0.34512413139965936, -0.15618833950707955, -0.41941677707757874, 0.4458983469783453}, {-0.7660093051011847, 0.5482763224961875, -0.9987913478497763, -0.9842994610123474, -0.7801902911749243, 0.5613574074106569, -0.49371188067385186}, {0.5583049111784795, -0.9511960118489133, -0.7610577450906089, 0.48188343529691346, 0.23547454702291803, 0.20415133442747058, 0.9181145422295938}}}, {{{0.14911700752757273, -0.05837746001531219, 0.5368187139585459, -0.8940613010669436, -0.5018302442340068, 0.27020723614181774, 0.12359775508403592}, {-0.3683916194955037, -0.5525267297116154, -0.5872030595156685, -0.8061235674442466, -0.23709048741408623, 0.42772609271483164, 0.4827241146251704}, {-0.8997166066727429, 0.09739710605428176, 0.5320698398177925, 0.05469688654269378, 0.4503706682941915, -0.7821018114726392, -0.3379863042117526}, {0.5105732505948533, 0.6195932582442767, 0.6841027629496503, -0.024765852986073256, 0.10834864531079891, -0.49612833775897114, 0.6109637757093997}, {-0.28292428408539205, 0.30657791183926, -0.4741374456208911, 0.714641208996071, 0.8309281186389432, 0.20447906224501944, 0.1498769698488771}, {0.38814726304764857, -0.43209235857228956, -0.8375165379497882, -0.9320039920129055, -0.5820061765266624, -0.6009461842921451, 0.8425964963548309}}}, {{{0.6848105040087451, -0.09424447387569135, 0.630497576004454, 0.319121226100175, 0.15547601325199478, 0.37766869124805513, -0.418251240744814}, {-0.5841177409538716, -0.07943995214433475, 0.6405419622330082, -0.18822915511374738, 0.9682166115359014, -0.24310913205955398, 0.4207346330747752}, {0.45689131291795304, 0.5592009847191926, -0.5794736694118892, 0.2777598519942086, 0.06893779977151926, -0.10558235108004288, 0.24127228408049373}, {0.8653133697361124, 0.8808125543307121, 0.013003929742553488, -0.25819110436923287, 0.7150667606571139, -0.8474607538945635, -0.21182942625066659}, {0.7953892915393812, -0.5146297490600227, 0.9797805357099336, -0.19418087953367502, 0.30615862986502584, 0.9621224147788383, 0.591540018663443}, {-0.0326501323196986, 0.4340496651711856, -0.6274862226468154, 0.43246185178053453, -0.6752962418803996, -0.11639979303524317, 0.04992688161509218}}}, {{{0.7246870093148794, 0.41031155832285204, 0.6075964984936815, -0.9309929613876653, -0.5305318949868476, -0.684400029780897, -0.03189572751676284}, {0.3890456863699665, 0.055814217385724785, -0.028984551458518748, 0.1946456227803317, -0.28468283193227384, 0.07443098789465097, -0.3397710281207207}, {-0.3252622666425089, -0.7764904739232343, 0.659017163729533, -0.6314623347234112, -0.4459102255849552, -0.8305995999617672, -0.6736542039955138}, {-0.09946179372459873, 0.48571832213388744, 0.06431964245524391, 0.9248711036318769, 0.27818775843144383, 0.06436195186180793, 0.4804631389346339}, {0.8394854989160261, 0.46911286378594497, -0.3880347646613327, -0.8793296857106343, 0.7535849141300499, -0.14621751679049622, -0.24084757493862208}, {0.263291050906274, 0.2426439223615553, 0.024235715636066857, -0.3441033743486446, -0.6157381917061411, 0.8654487680234961, -0.015712235651818673}}}, {{{0.25941803193881485, -0.5643528433065192, -0.6939218246816452, -0.6573164675211882, 0.3044833933508735, -0.15696192470423354, -0.7292088799733678}, {0.7157059796941971, 0.5010086085806371, 0.42635964783799274, -0.6918122089292549, 0.5343027744642965, -0.3177068701933763, 0.7728881262187897}, {0.1919928613372428, 0.9481231231381191, -0.8495829859085204, -0.5016908143642169, -0.25281765568651915, -0.8041546515214235, -0.9379455299920623}, {0.9756710429966389, 0.002338101461675013, 0.5512942665704528, 0.11255265169286277, -0.4446511594248159, 0.923624877032104, -0.35888035429907994}, {-0.4993622134330429, -0.41713411728302896, 0.5241211722633352, -0.8565133189111758, 0.009666595018221535, 0.0024308669289925255, 0.21168620320785259}, {0.7819003932609805, 0.9688407967537689, -0.438602023010886, 0.6460148816650522, -0.463700457054959, 0.7497559992824492, -0.6604977204100679}}}}}; Mesh<double, 3> f3d{f3.size(), f3[0].size(), f3[0][0].size()}; for (unsigned i = 0; i < f3d.dim_size(0); ++i) { for (unsigned j = 0; j < f3d.dim_size(1); ++j) { for (unsigned k = 0; k < f3d.dim_size(2); ++k) { f3d(i, j, k) = f3[i][j][k]; } } } InterpolationFunction<double, 3> interp3( 3, f3d, make_pair(0., f3d.dim_size(0) - 1.), make_pair(0., f3d.dim_size(1) - 1.), make_pair(0., f3d.dim_size(2) - 1.)); // some random points constexpr array<array<double, 3>, 10> coords_3d{ {{3.702442458842895, 0.3823502932775078, 2.0413783528852125}, {0.5158748832148454, 3.998837357745451, 3.063577604910418}, {0.9488026738796771, 1.0559217201840418, 2.5167646532589334}, {3.787943594036949, 1.0660346792124562, 0.39476961351333895}, {2.5437164557222864, 2.1812414553861963, 3.194304608069536}, {0.8943435648540952, 3.274226260967546, 0.3988216219352534}, {2.607886328617485, 1.718155000146739, 3.5736295561232927}, {3.0725177261490373, 1.054538982002727, 0.4944889286172529}, {1.7731799360168479, 1.237539640884, 1.0101529018305797}, {0.8655632442457968, 1.3379555874162659, 1.7103327524709568}}}; // and their spline value, pre-computed by MMA constexpr array<double, 10> vals_3d{ {-0.20015704400375117, 0.5183267778903129, -0.7197026899005371, 0.5183443130595233, -0.07245353025037997, 0.5534353986280456, -0.2674229002109916, 0.1673843822053797, -0.021928200124974297, -0.260677062462001}}; std::cout << "\n3D Interpolation Test:\n"; d = rel_err(interp3, std::make_pair(coords_3d.begin(), coords_3d.end()), std::make_pair(vals_3d.begin(), vals_3d.end())); assertion(d < tol); std::cout << "\n3D test " << (assertion.last_status() == 0 ? "succeed" : "failed") << '\n'; std::cout << "Relative Error = " << d << '\n'; assertion(!interp3.periodicity(0) && !interp3.periodicity(1) && !interp3.periodicity(2)); // 1D interpolation test with periodic boundary std::cout << "\n1D Interpolation with Periodic Boundary Test:\n"; // Since the InterpolationFunction ignores the last term along periodic // dimension, thus we can use the origin non-periodic data to interpolate a // periodic spline function InterpolationFunction1D<double> interp1_periodic( std::make_pair(f.begin(), f.end()), 4, true); auto vals_1d_periodic = { -0.09762254647017743, 1.168800757853312, -0.6682906902062101, 0.44128062499073417, 1.1642814012848224, -0.12481864202139212, -0.00445415461594469, 1.159234754035029, 0.4508845136779133, 0.45967108162968584, }; d = rel_err( interp1_periodic, std::make_pair(coords_1d.begin(), coords_1d.end()), std::make_pair(vals_1d_periodic.begin(), vals_1d_periodic.end())); assertion(d < tol); std::cout << "\n1D test with periodic boundary " << (assertion.last_status() == 0 ? "succeed" : "failed") << '\n'; std::cout << "Relative Error = " << d << '\n'; assertion(std::abs(interp1_periodic(*coords_1d.begin() - (f.size() - 1)) - *vals_1d_periodic.begin()) < tol, "Out of left periodic boundary did not work as expected.\n"); assertion(std::abs(interp1_periodic(*coords_1d.begin() + (f.size() - 1)) - *vals_1d_periodic.begin()) < tol, "Out of Right periodic boundary did not work as expected.\n"); // 2D interpolation test with one dimension being periodic boundary std::cout << "\n2D Interpolation with Periodic Boundary Test:\n"; InterpolationFunction<double, 2> interp2_periodic( 3, {false, true}, f2d, make_pair(0., f2d.dim_size(0) - 1.), make_pair(0., f2d.dim_size(1) - 1.)); auto vals_2d_periodic = {-0.5456439415470818, 0.7261218483070795, 0.21577722210958022, -1.6499933881987376, 1.224021619908732, 0.34969937176489274, 0.5845798304532657, 0.2875923130734858, -1.4740569960870218, 0.258215214830246}; d = rel_err(interp2_periodic, make_pair(coords_2d.begin(), coords_2d.end()), make_pair(vals_2d_periodic.begin(), vals_2d_periodic.end())); assertion(d < tol); std::cout << "\n2D test with periodic boundary " << (assertion.last_status() == 0 ? "succeed" : "failed") << '\n'; std::cout << "Relative Error = " << d << '\n'; #ifdef _DEBUG if (assertion.last_status() != 0) { interp2_periodic.spline().__debug_output(); } #endif // 1D interpolation derivative test std::cout << "\n1D Interpolation Derivative Test:\n"; auto vals_1d_derivative_1 = {-1.027459647923634, -0.23460057495062184, 1.626359518442344, -0.5964266359199579, -1.6344806285675368, 1.1365216604820132, 2.451880834458231, 0.14293981479176837, 0.16561298233542285, -3.58205140200432}; d = rel_err( [&](double x) { return interp.derivative_at(std::make_pair(x, 1)); }, std::make_pair(coords_1d_half.begin(), coords_1d_half.end()), std::make_pair(vals_1d_derivative_1.begin(), vals_1d_derivative_1.end())); assertion(d < tol); std::cout << "\n1D test of derivative " << (assertion.last_status() == 0 ? "succeed" : "failed") << '\n'; std::cout << "Relative Error = " << d << '\n'; // 2D interpolation derivative test std::cout << "\n2D Interpolation Derivative Test:\n"; auto vals_2d_derivative_x2_y1 = {-0.7543201698562789, 7.386529487473519, 1.4374808443975349, 0.015013232428628703, 0.4101648846318855, 0.3989275680682247, -1.2969356922668822, -3.0725969893922946, -3.4258871562563455, 0.43843555890798447}; d = rel_err( [&](std::array<double, 2> coord) { return interp2.derivative_at(coord, 2, 1); }, std::make_pair(coords_2d.begin(), coords_2d.end()), std::make_pair(vals_2d_derivative_x2_y1.begin(), vals_2d_derivative_x2_y1.end())); assertion(d < tol); std::cout << "\n2D test of derivative (2,1) " << (assertion.last_status() == 0 ? "succeed" : "failed") << '\n'; std::cout << "Relative Error = " << d << '\n'; // 3D interpolation derivative test std::cout << "\n3D Interpolation Derivative Test:\n"; auto vals_3d_derivative_x1_y0_z3 = { 26.856939941150102, -2.3883090024921603, 8.857003271951815, -5.988828759251878, -9.656188308304278, -3.8790002779026658, -8.950315245767326, 2.859291392187189, -1.0605065454924238, 0.9708580137688204}; d = rel_err( [&](std::array<double, 3> coord) { return interp3.derivative_at(coord, {1, 0, 3}); }, std::make_pair(coords_3d.begin(), coords_3d.end()), std::make_pair(vals_3d_derivative_x1_y0_z3.begin(), vals_3d_derivative_x1_y0_z3.end())); assertion(d < tol); std::cout << "\n3D test of derivative (1,0,3) " << (assertion.last_status() == 0 ? "succeed" : "failed") << '\n'; std::cout << "Relative Error = " << d << '\n'; // 1D non-uniform interpolation test std::cout << "\n1D nonuniform Interpolation Test:\n"; auto input_coords_1d = {0., 0.9248468590818175, 2.270222487146226, 3.498804659217474, 3.7530418178453955, 4.791302870662092, 6.3336649913937375, 7.041926963118405, 7.612472537805882, 9.034787492568283, 10.078257485188475, 11.440973163521294, 12.}; InterpolationFunction1D<double> interp1_nonuniform( std::make_pair(input_coords_1d.begin(), input_coords_1d.end()), std::make_pair(f.begin(), f.end())); auto vals_1d_nonuniform = {-0.4562057772431492, 1.3471094229928755, -0.6079379355534298, -0.016699918339397407, 1.2453576785633913, -0.17792750766792387, 0.05227508784539216, 1.3530673230583836, 0.877847815343884, 0.27427682690484234}; d = rel_err( interp1_nonuniform, std::make_pair(coords_1d.begin(), coords_1d.end()), std::make_pair(vals_1d_nonuniform.begin(), vals_1d_nonuniform.end())); assertion(d < tol); std::cout << "\n1D nonuniform test " << (assertion.last_status() == 0 ? "succeed" : "failed") << '\n'; std::cout << "Relative Error = " << d << '\n'; std::cout << "\n1D nonuniform Interpolation Test with Periodic Boundary:\n"; InterpolationFunction1D<double> interp1_nonuniform_peridoc( std::make_pair(input_coords_1d.begin(), input_coords_1d.end()), std::make_pair(f.begin(), f.end()), 4, true); auto vals_1d_nonuniform_periodic = { -0.4464803199487985, 1.2298382629311808, -0.6268441539418139, 0.06800541396058792, 1.1730724308997087, -0.6075709757451075, 0.00021566856863144274, 1.2284708203600656, 0.8052326379455318, 0.3011733005197456}; d = rel_err(interp1_nonuniform_peridoc, std::make_pair(coords_1d.begin(), coords_1d.end()), std::make_pair(vals_1d_nonuniform_periodic.begin(), vals_1d_nonuniform_periodic.end())); assertion(d < tol); std::cout << "\n1D nonuniform test with periodic boundary " << (assertion.last_status() == 0 ? "succced" : "failed") << '\n'; std::cout << "Relative Error = " << d << '\n'; // 2D non-uniform with one dimension being periodic boundary auto nonuniform_coord_for_2d = {0., 1.329905262345947, 2.200286645200226, 3.1202827237815516, 4.}; InterpolationFunction<double, 2> interp2_X_periodic_Y_nonuniform( 3, {true, false}, f2d, std::make_pair(0., f2d.dim_size(0) - 1.), std::make_pair(nonuniform_coord_for_2d.begin(), nonuniform_coord_for_2d.end())); auto vals_2d_X_periodic_Y_nonuniform = { -0.7160424002258807, 0.6702846215275077, 0.04933393138376427, -0.48309957376784946, 0.7622619905083738, 0.28742506313682975, 0.4762197211423307, -0.2924876444803407, -0.05355290342562366, 0.08938131323971249}; d = rel_err(interp2_X_periodic_Y_nonuniform, std::make_pair(coords_2d.begin(), coords_2d.end()), std::make_pair(vals_2d_X_periodic_Y_nonuniform.begin(), vals_2d_X_periodic_Y_nonuniform.end())); assertion(d < tol); std::cout << "\n2D test with x-periodic and y-nonuniform " << (assertion.last_status() == 0 ? "succced" : "failed") << '\n'; std::cout << "Relative Error = " << d << '\n'; return assertion.status(); }
47.402985
83
0.610291
12ff54e
ce1cfb84e2e211cf9ea9ef4e19ea69931a22b0a0
1,985
hpp
C++
include/tweedledee/quil/ast/ast_node.hpp
boschmitt/tweedledee
a7f5041681350601469b38311b9654e2c22643c0
[ "MIT" ]
4
2018-07-21T08:11:56.000Z
2019-05-30T20:06:43.000Z
include/tweedledee/quil/ast/ast_node.hpp
boschmitt/tweedledee
a7f5041681350601469b38311b9654e2c22643c0
[ "MIT" ]
null
null
null
include/tweedledee/quil/ast/ast_node.hpp
boschmitt/tweedledee
a7f5041681350601469b38311b9654e2c22643c0
[ "MIT" ]
1
2019-05-15T14:11:28.000Z
2019-05-15T14:11:28.000Z
/*------------------------------------------------------------------------------------------------- | This file is distributed under the MIT License. | See accompanying file /LICENSE for details. *------------------------------------------------------------------------------------------------*/ #pragma once #include "ast_node_kinds.hpp" #include "detail/intrusive_list.hpp" #include <cstdint> #include <memory> #include <ostream> namespace tweedledee { namespace quil { // Base class for all AST nodes class ast_node : detail::intrusive_list_node<ast_node> { public: ast_node(const ast_node&) = delete; ast_node& operator=(const ast_node&) = delete; virtual ~ast_node() = default; ast_node_kinds kind() const { return do_get_kind(); } void print(std::ostream& out) const { do_print(out); } const ast_node& parent() const { return *parent_; } uint32_t location() const { return location_; } protected: ast_node(uint32_t location) : location_(location) {} private: virtual ast_node_kinds do_get_kind() const = 0; virtual void do_print(std::ostream& out) const = 0; void on_insert(const ast_node* parent) { parent_ = parent; } private: uint32_t location_; const ast_node* parent_; template<typename T> friend struct detail::intrusive_list_access; friend detail::intrusive_list_node<ast_node>; }; // Helper class for nodes that are containers. i.e not leafs template<class Derived, typename T> class ast_node_container { public: using iterator = typename detail::intrusive_list<T>::const_iterator; iterator begin() const { return children_.begin(); } iterator end() const { return children_.end(); } iterator back() const { return children_.back(); } protected: void add_child(std::unique_ptr<T> ptr) { children_.push_back(static_cast<Derived*>(this), std::move(ptr)); } ~ast_node_container() = default; private: detail::intrusive_list<T> children_; }; } // namespace quil } // namespace tweedledee
19.086538
99
0.649874
boschmitt
ce1dceb2a3715552d34f334dece72ec95f5c8759
17,759
cpp
C++
lib/Runtime/Library/JSONParser.cpp
satheeshravi/ChakraCore
3bf47ff12bf80ab06fb7ea6925ec7579985ac1f5
[ "MIT" ]
1
2021-11-07T18:56:21.000Z
2021-11-07T18:56:21.000Z
lib/Runtime/Library/JSONParser.cpp
MaxMood96/ChakraCore
9d9fea268ce1ae6c00873fd966a6a2be048f3455
[ "MIT" ]
null
null
null
lib/Runtime/Library/JSONParser.cpp
MaxMood96/ChakraCore
9d9fea268ce1ae6c00873fd966a6a2be048f3455
[ "MIT" ]
1
2021-09-04T23:26:57.000Z
2021-09-04T23:26:57.000Z
//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- #include "RuntimeLibraryPch.h" #include "JSON.h" #include "JSONParser.h" using namespace Js; namespace JSON { // -------- Parser implementation ------------// void JSONParser::Finalizer() { m_scanner.Finalizer(); if(arenaAllocatorObject) { this->scriptContext->ReleaseTemporaryGuestAllocator(arenaAllocatorObject); } } Js::Var JSONParser::Parse(LPCWSTR str, int length) { if (length > MIN_CACHE_LENGTH) { if (!this->arenaAllocatorObject) { this->arenaAllocatorObject = scriptContext->GetTemporaryGuestAllocator(_u("JSONParse")); this->arenaAllocator = arenaAllocatorObject->GetAllocator(); } } m_scanner.Init(str, length, &m_token, scriptContext, str, this->arenaAllocator); Scan(); Js::Var ret = ParseObject(); if (m_token.tk != tkEOF) { Js::JavascriptError::ThrowSyntaxError(scriptContext, ERRsyntax); } return ret; } Js::Var JSONParser::Parse(Js::JavascriptString* input) { return Parse(input->GetSz(), input->GetLength()); } Js::Var JSONParser::Walk(Js::JavascriptString* name, Js::PropertyId id, Js::Var holder, uint32 index) { AssertMsg(reviver, "JSON post parse walk with null reviver"); Js::Var value; Js::Var values[3]; Js::Arguments args(0, values); Js::RecyclableObject *undefined = scriptContext->GetLibrary()->GetUndefined(); if (Js::DynamicObject::IsAnyArray(holder)) { // when called from an array the key is NULL and the keyId is the index. value = Js::JavascriptArray::FromAnyArray(holder)->DirectGetItem(id); name = scriptContext->GetIntegerString(id); } else { AssertMsg(Js::JavascriptOperators::GetTypeId(holder) == Js::TypeIds_Object || Js::JavascriptOperators::GetTypeId(holder) == Js::TypeIds_Arguments, "The holder argument in a JSON::Walk function must be an object or an array"); if (id == Constants::NoProperty) { if (!Js::RecyclableObject::FromVar(holder)->GetItem(holder, index, &value, scriptContext)) { value = undefined; } } else { if (!Js::RecyclableObject::FromVar(holder)->GetProperty(holder, id, &value, NULL, scriptContext)) { value = undefined; } } } // this is a post order walk. Visit the children before calling walk on this object if (Js::DynamicObject::IsAnyArray(value)) { Js::JavascriptArray* arrayVal = Js::JavascriptArray::FromAnyArray(value); // REVIEW: How do we guarantee that JSON objects are not native arrays? Assert(!Js::JavascriptNativeIntArray::Is(arrayVal) && !Js::JavascriptNativeFloatArray::Is(arrayVal)); uint length = arrayVal->GetLength(); if (!arrayVal->IsCrossSiteObject()) { for(uint k = 0; k < length; k++) { Js::Var newElement = Walk(0, k, value); if(Js::JavascriptOperators::IsUndefinedObject(newElement, undefined)) { arrayVal->DirectDeleteItemAt<Js::Var>(k); } else { arrayVal->DirectSetItemAt(k, newElement); } } } else { for(uint k = 0; k < length; k++) { Js::Var newElement = Walk(0, k, value); if(Js::JavascriptOperators::IsUndefinedObject(newElement, undefined)) { arrayVal->DirectDeleteItemAt<Js::Var>(k); } else { arrayVal->SetItem(k, newElement, Js::PropertyOperation_None); } } } } else { Js::TypeId typeId = Js::JavascriptOperators::GetTypeId(value); if (typeId == Js::TypeIds_Object || typeId == Js::TypeIds_Arguments) { Js::Var enumeratorVar; // normally we should have a JSON object here and the enumerator should be always be successful. However, the objects can be // modified by user code. It is better to skip a damaged object. ES5 spec doesn't specify an error here. if(Js::RecyclableObject::FromVar(value)->GetEnumerator(FALSE, &enumeratorVar, scriptContext)) { Js::JavascriptEnumerator* enumerator = static_cast<Js::JavascriptEnumerator*>(enumeratorVar); Js::Var propertyNameVar; Js::PropertyId idMember; while(enumerator->MoveNext()) { propertyNameVar = enumerator->GetCurrentIndex(); //NOTE: If testing key value call enumerator->GetCurrentValue() to confirm value is correct; AssertMsg(!Js::JavascriptOperators::IsUndefinedObject(propertyNameVar, undefined) && Js::JavascriptString::Is(propertyNameVar) , "bad enumeration on a JSON Object"); if (enumerator->GetCurrentPropertyId(&idMember)) { Js::Var newElement = Walk(Js::JavascriptString::FromVar(propertyNameVar), idMember, value); if (Js::JavascriptOperators::IsUndefinedObject(newElement, undefined)) { Js::JavascriptOperators::DeleteProperty(Js::RecyclableObject::FromVar(value), idMember); } else { Js::JavascriptOperators::SetProperty(value, Js::RecyclableObject::FromVar(value), idMember, newElement, scriptContext); } } // For the numeric cases the enumerator is set to a NullEnumerator (see class in ForInObjectEnumerator.h) // Numerals do not have property Ids so we need to set and delete items else { uint32 propertyIndex = enumerator->GetCurrentItemIndex(); AssertMsg(Js::JavascriptArray::InvalidIndex != propertyIndex, "Not a numeric type"); Js::Var newElement = Walk(Js::JavascriptString::FromVar(propertyNameVar), idMember, value, propertyIndex); if (Js::JavascriptOperators::IsUndefinedObject(newElement, undefined)) { Js::JavascriptOperators::DeleteItem(Js::RecyclableObject::FromVar(value), propertyIndex); } else { Js::JavascriptOperators::SetItem(value, Js::RecyclableObject::FromVar(value), propertyIndex, newElement, scriptContext); } } } } } } // apply reviver on this node now args.Info.Count = 3; args.Values[0] = holder; args.Values[1] = name; args.Values[2] = value; value = Js::JavascriptFunction::CallFunction<true>(reviver, reviver->GetEntryPoint(), args); return value; } Js::Var JSONParser::ParseObject() { PROBE_STACK(scriptContext, Js::Constants::MinStackDefault); Js::Var retVal; switch (m_token.tk) { case tkFltCon: retVal = Js::JavascriptNumber::ToVarIntCheck(m_token.GetDouble(), scriptContext); Scan(); return retVal; case tkStrCon: { // will auto-null-terminate the string (as length=len+1) uint len = m_scanner.GetCurrentStringLen(); retVal = Js::JavascriptString::NewCopyBuffer(m_scanner.GetCurrentString(), len, scriptContext); Scan(); return retVal; } case tkTRUE: retVal = scriptContext->GetLibrary()->GetTrue(); Scan(); return retVal; case tkFALSE: retVal = scriptContext->GetLibrary()->GetFalse(); Scan(); return retVal; case tkNULL: retVal = scriptContext->GetLibrary()->GetNull(); Scan(); return retVal; case tkSub: // unary minus if (Scan() == tkFltCon) { retVal = Js::JavascriptNumber::ToVarIntCheck(-m_token.GetDouble(), scriptContext); Scan(); return retVal; } else { Js::JavascriptError::ThrowSyntaxError(scriptContext, ERRbadNumber); } case tkLBrack: { Js::JavascriptArray* arrayObj = scriptContext->GetLibrary()->CreateArray(0); //skip '[' Scan(); //iterate over the array members, get JSON objects and add them in the pArrayMemberList uint k = 0; while (true) { if(tkRBrack == m_token.tk) { break; } Js::Var value = ParseObject(); arrayObj->SetItem(k++, value, Js::PropertyOperation_None); // if next token is not a comma consider the end of the array member list. if (tkComma != m_token.tk) break; Scan(); if(tkRBrack == m_token.tk) { Js::JavascriptError::ThrowSyntaxError(scriptContext, ERRillegalChar); } } //check and consume the ending ']' CheckCurrentToken(tkRBrack, ERRnoRbrack); return arrayObj; } case tkLCurly: { // Parse an object, "{"name1" : ObjMember1, "name2" : ObjMember2, ...} " if(IsCaching()) { if(!typeCacheList) { typeCacheList = Anew(this->arenaAllocator, JsonTypeCacheList, this->arenaAllocator, 8); } } // first, create the object Js::DynamicObject* object = scriptContext->GetLibrary()->CreateObject(); JS_ETW(EventWriteJSCRIPT_RECYCLER_ALLOCATE_OBJECT(object)); #if ENABLE_DEBUG_CONFIG_OPTIONS if (Js::Configuration::Global.flags.IsEnabled(Js::autoProxyFlag)) { object = DynamicObject::FromVar(JavascriptProxy::AutoProxyWrapper(object)); } #endif //next token after '{' Scan(); //if empty object "{}" return; if(tkRCurly == m_token.tk) { Scan(); return object; } JsonTypeCache* previousCache = nullptr; JsonTypeCache* currentCache = nullptr; //parse the list of members while(true) { // parse a list member: "name" : ObjMember // and add it to the object. //pick "name" if(tkStrCon != m_token.tk) { Js::JavascriptError::ThrowSyntaxError(scriptContext, ERRsyntax); } // currentStrLength = length w/o null-termination WCHAR* currentStr = m_scanner.GetCurrentString(); uint currentStrLength = m_scanner.GetCurrentStringLen(); DynamicType* typeWithoutProperty = object->GetDynamicType(); if(IsCaching()) { if(!previousCache) { // This is the first property in the list - see if we have an existing cache for it. currentCache = typeCacheList->LookupWithKey(Js::HashedCharacterBuffer<WCHAR>(currentStr, currentStrLength), nullptr); } if(currentCache && currentCache->typeWithoutProperty == typeWithoutProperty && currentCache->propertyRecord->Equals(JsUtil::CharacterBuffer<WCHAR>(currentStr, currentStrLength))) { //check and consume ":" if(Scan() != tkColon ) { Js::JavascriptError::ThrowSyntaxError(scriptContext, ERRnoColon); } Scan(); // Cache all values from currentCache as there is a chance that ParseObject might change the cache DynamicType* typeWithProperty = currentCache->typeWithProperty; PropertyId propertyId = currentCache->propertyRecord->GetPropertyId(); PropertyIndex propertyIndex = currentCache->propertyIndex; previousCache = currentCache; currentCache = currentCache->next; // fast path for type transition and property set object->EnsureSlots(typeWithoutProperty->GetTypeHandler()->GetSlotCapacity(), typeWithProperty->GetTypeHandler()->GetSlotCapacity(), scriptContext, typeWithProperty->GetTypeHandler()); object->ReplaceType(typeWithProperty); Js::Var value = ParseObject(); object->SetSlot(SetSlotArguments(propertyId, propertyIndex, value)); // if the next token is not a comma consider the list of members done. if (tkComma != m_token.tk) break; Scan(); continue; } } // slow path Js::PropertyRecord const * propertyRecord; scriptContext->GetOrAddPropertyRecord(currentStr, currentStrLength, &propertyRecord); //check and consume ":" if(Scan() != tkColon ) { Js::JavascriptError::ThrowSyntaxError(scriptContext, ERRnoColon); } Scan(); Js::Var value = ParseObject(); PropertyValueInfo info; object->SetProperty(propertyRecord->GetPropertyId(), value, PropertyOperation_None, &info); DynamicType* typeWithProperty = object->GetDynamicType(); if(IsCaching() && !propertyRecord->IsNumeric() && !info.IsNoCache() && typeWithProperty->GetIsShared() && typeWithProperty->GetTypeHandler()->IsPathTypeHandler()) { PropertyIndex propertyIndex = info.GetPropertyIndex(); if(!previousCache) { // This is the first property in the set add it to the dictionary. currentCache = JsonTypeCache::New(this->arenaAllocator, propertyRecord, typeWithoutProperty, typeWithProperty, propertyIndex); typeCacheList->AddNew(propertyRecord, currentCache); } else if(!currentCache) { currentCache = JsonTypeCache::New(this->arenaAllocator, propertyRecord, typeWithoutProperty, typeWithProperty, propertyIndex); previousCache->next = currentCache; } else { // cache miss!! currentCache->Update(propertyRecord, typeWithoutProperty, typeWithProperty, propertyIndex); } previousCache = currentCache; currentCache = currentCache->next; } // if the next token is not a comma consider the list of members done. if (tkComma != m_token.tk) break; Scan(); } // check and consume the ending '}" CheckCurrentToken(tkRCurly, ERRnoRcurly); return object; } default: Js::JavascriptError::ThrowSyntaxError(scriptContext, ERRsyntax); } } } // namespace JSON
42.689904
190
0.489724
satheeshravi
ce22dba9649bd0e6b4e343178e9abd25bcbf8319
990
cpp
C++
unit_tests/diagnostics.cpp
tay10r/pathway
20e961b6c0bf01a1c3a9e5a97396cc64d0f64cf6
[ "MIT" ]
1
2021-04-29T02:29:40.000Z
2021-04-29T02:29:40.000Z
unit_tests/diagnostics.cpp
tay10r/pathway
20e961b6c0bf01a1c3a9e5a97396cc64d0f64cf6
[ "MIT" ]
null
null
null
unit_tests/diagnostics.cpp
tay10r/pathway
20e961b6c0bf01a1c3a9e5a97396cc64d0f64cf6
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include "diagnostics.h" TEST(Diagnostics, GetClippedLocation) { Location loc1{ 1, 7, 1, 7 }; auto range1 = ConsoleDiagObserver::GetClippedLocation(1, " line 1", loc1); EXPECT_EQ(range1.index, 6); EXPECT_EQ(range1.length, 1); Location loc2{ 2, 2, 3, 5 }; auto range2 = ConsoleDiagObserver::GetClippedLocation(2, " line 2", loc2); auto range3 = ConsoleDiagObserver::GetClippedLocation(3, " line 3", loc2); EXPECT_EQ(range2.index, 1); EXPECT_EQ(range2.length, 6); EXPECT_EQ(range3.index, 0); EXPECT_EQ(range3.length, 5); } TEST(Diagnostics, GetLineView) { std::string_view lines = " line 1\n" " line 2\n" " line 3\n"; auto ln1 = ConsoleDiagObserver::GetLineView(1, lines); auto ln2 = ConsoleDiagObserver::GetLineView(2, lines); auto ln3 = ConsoleDiagObserver::GetLineView(3, lines); EXPECT_EQ(ln1, " line 1"); EXPECT_EQ(ln2, " line 2"); EXPECT_EQ(ln3, " line 3"); }
24.75
76
0.651515
tay10r
ce254b163692b17480af619db791dbb587db4184
1,102
cpp
C++
cpp/lib/string/is_parentheses_column.cpp
KATO-Hiro/atcoder-1
c2cbfcfd5c3d46ac9810ba330a37d437aa2839c2
[ "MIT" ]
null
null
null
cpp/lib/string/is_parentheses_column.cpp
KATO-Hiro/atcoder-1
c2cbfcfd5c3d46ac9810ba330a37d437aa2839c2
[ "MIT" ]
null
null
null
cpp/lib/string/is_parentheses_column.cpp
KATO-Hiro/atcoder-1
c2cbfcfd5c3d46ac9810ba330a37d437aa2839c2
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; using ll = long long; // -------------------------------------------------------- #define FOR(i,l,r) for (ll i = (l); i < (r); ++i) #define RFOR(i,l,r) for (ll i = (r)-1; (l) <= i; --i) #define REP(i,n) FOR(i,0,n) #define RREP(i,n) RFOR(i,0,n) #define BIT(b,i) (((b)>>(i)) & 1) using VS = vector<string>; // -------------------------------------------------------- // 括弧列の判定 bool is_parentheses_column(const string& S) { const ll N = (ll)S.size(); ll pos = 0; REP(i,N) { if (S[i] == '(') pos++; if (S[i] == ')') pos--; if (pos < 0) return false; } return pos == 0; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout << fixed << setprecision(15); ll N; cin >> N; VS ans; REP(S,1<<N) { string T = ""; // 001011 = (()()) RREP(i,N) T += (!BIT(S,i) ? '(' : ')'); if (is_parentheses_column(T)) ans.push_back(T); } for (string& a : ans) cout << a << '\n'; return 0; } // Verify: https://atcoder.jp/contests/typical90/tasks/typical90_b
24.488889
66
0.451906
KATO-Hiro
ce25536e9fe45588c86ded4ba219fc2d05ecc2a0
12,027
cpp
C++
plugins/OpenVR/src/VROpenVRInputDevice.cpp
elainejiang8/MinVR
d3905b0a7b6b3e324e6ab3773ef29f651b8ad9d7
[ "BSD-3-Clause" ]
null
null
null
plugins/OpenVR/src/VROpenVRInputDevice.cpp
elainejiang8/MinVR
d3905b0a7b6b3e324e6ab3773ef29f651b8ad9d7
[ "BSD-3-Clause" ]
null
null
null
plugins/OpenVR/src/VROpenVRInputDevice.cpp
elainejiang8/MinVR
d3905b0a7b6b3e324e6ab3773ef29f651b8ad9d7
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright Regents of the University of Minnesota, 2015. This software is released under the following license: http://opensource.org/licenses/GPL-2.0 * Source code originally developed at the University of Minnesota Interactive Visualization Lab (http://ivlab.cs.umn.edu). * * Code author(s): * Ben Knorlein */ #include <ctime> #include <cctype> #include "VROpenVRInputDevice.h" namespace MinVR { VROpenVRInputDevice::VROpenVRInputDevice(vr::IVRSystem *pHMD, string name):m_pHMD(pHMD), m_name(name){ updateDeviceNames(); } VROpenVRInputDevice::~VROpenVRInputDevice() { } void VROpenVRInputDevice::appendNewInputEventsSinceLastCall(VRDataQueue* queue) { //process VR Events vr::VREvent_t event; vr::TrackedDevicePose_t pose; while( m_pHMD->PollNextEventWithPose(vr::VRCompositor()->GetTrackingSpace(), &event, sizeof(event), &pose ) ) { processVREvent( event, &pose ); } //Report current States reportStates(); for (int f = 0; f < _events.size(); f++) { queue->push(_events[f]); } _events.clear(); } void VROpenVRInputDevice::updatePoses(){ vr::VRCompositor()->WaitGetPoses(m_rTrackedDevicePose, vr::k_unMaxTrackedDeviceCount, nullptr, 0); for (vr::TrackedDeviceIndex_t unDevice = 0; unDevice < vr::k_unMaxTrackedDeviceCount; unDevice++) { if (m_pHMD->IsTrackedDeviceConnected(unDevice)){ std::string event_name = getDeviceName(unDevice); _dataIndex.addData(event_name + "/Pose", poseToMatrix4(&m_rTrackedDevicePose[unDevice])); _events.push_back(_dataIndex.serialize(event_name)); } } } VRMatrix4 VROpenVRInputDevice::getPose(int device_idx){ return poseToMatrix4( &m_rTrackedDevicePose[device_idx]); } bool getButtonState(vr::EVRButtonId id, uint64_t state){ return vr::ButtonMaskFromId(id) & state; } std::string VROpenVRInputDevice::getAxisType(int device, int axis){ int32_t type = m_pHMD->GetInt32TrackedDeviceProperty( device, ((vr::ETrackedDeviceProperty) (vr::Prop_Axis0Type_Int32 + axis))); switch(type){ case vr::k_eControllerAxis_None: return "None"; case vr::k_eControllerAxis_TrackPad: return "TrackPad"; case vr::k_eControllerAxis_Joystick: return "Joystick"; case vr::k_eControllerAxis_Trigger: return "Trigger"; } return "Invalid"; } void VROpenVRInputDevice::reportStates(){ for (vr::TrackedDeviceIndex_t unDevice = 0; unDevice < vr::k_unMaxTrackedDeviceCount; unDevice++) { if (m_pHMD->IsTrackedDeviceConnected(unDevice)){ vr::VRControllerState_t state; vr::TrackedDevicePose_t pose; if (m_pHMD->GetTrackedDeviceClass(unDevice) == vr::TrackedDeviceClass_Controller){// && m_pHMD->GetControllerStateWithPose(vr::VRCompositor()->GetTrackingSpace(), unDevice, &state, sizeof(state), &pose);//){ std::string event_name = getDeviceName(unDevice); _dataIndex.addData(event_name + "/State/Pose", poseToMatrix4(&pose)); _dataIndex.addData(event_name + "/State/" + "SystemButton" + "_Pressed", getButtonState(vr::k_EButton_System, state.ulButtonPressed)); _dataIndex.addData(event_name + "/State/" + "SystemButton" + "_Touched", getButtonState(vr::k_EButton_System, state.ulButtonPressed)); _dataIndex.addData(event_name + "/State/" + "ApplicationMenuButton" + "_Pressed", getButtonState(vr::k_EButton_ApplicationMenu, state.ulButtonPressed)); _dataIndex.addData(event_name + "/State/" + "ApplicationMenuButton" + "_Touched", getButtonState(vr::k_EButton_ApplicationMenu, state.ulButtonPressed)); _dataIndex.addData(event_name + "/State/" + "GripButton" + "_Pressed", getButtonState(vr::k_EButton_Grip, state.ulButtonPressed)); _dataIndex.addData(event_name + "/State/" + "GripButton" + "_Touched", getButtonState(vr::k_EButton_Grip, state.ulButtonPressed)); _dataIndex.addData(event_name + "/State/" + "DPad_LeftButton" + "_Pressed", getButtonState(vr::k_EButton_DPad_Left, state.ulButtonPressed)); _dataIndex.addData(event_name + "/State/" + "DPad_LeftButton" + "_Touched", getButtonState(vr::k_EButton_DPad_Left, state.ulButtonPressed)); _dataIndex.addData(event_name + "/State/" + "DPad_UpButton" + "_Pressed", getButtonState(vr::k_EButton_DPad_Up, state.ulButtonPressed)); _dataIndex.addData(event_name + "/State/" + "DPad_UpButton" + "_Touched", getButtonState(vr::k_EButton_DPad_Up, state.ulButtonPressed)); _dataIndex.addData(event_name + "/State/" + "DPad_RightButton" + "_Pressed", getButtonState(vr::k_EButton_DPad_Right, state.ulButtonPressed)); _dataIndex.addData(event_name + "/State/" + "DPad_RightButton" + "_Touched", getButtonState(vr::k_EButton_DPad_Right, state.ulButtonPressed)); _dataIndex.addData(event_name + "/State/" + "DPad_DownButton" + "_Pressed", getButtonState(vr::k_EButton_DPad_Down, state.ulButtonPressed)); _dataIndex.addData(event_name + "/State/" + "DPad_DownButton" + "_Touched", getButtonState(vr::k_EButton_DPad_Down, state.ulButtonPressed)); _dataIndex.addData(event_name + "/State/" + "AButton" + "_Pressed", getButtonState(vr::k_EButton_A, state.ulButtonPressed)); _dataIndex.addData(event_name + "/State/" + "AButton" + "_Touched", getButtonState(vr::k_EButton_A, state.ulButtonPressed)); _dataIndex.addData(event_name + "/State/" + "Axis0Button" + "_Pressed", getButtonState(vr::k_EButton_Axis0, state.ulButtonPressed)); _dataIndex.addData(event_name + "/State/" + "Axis0Button" + "_Touched", getButtonState(vr::k_EButton_Axis0, state.ulButtonPressed)); _dataIndex.addData(event_name + "/State/" + "Axis1Button" + "_Pressed", getButtonState(vr::k_EButton_Axis1, state.ulButtonPressed)); _dataIndex.addData(event_name + "/State/" + "Axis1Button" + "_Touched", getButtonState(vr::k_EButton_Axis1, state.ulButtonPressed)); _dataIndex.addData(event_name + "/State/" + "Axis2Button" + "_Pressed", getButtonState(vr::k_EButton_Axis2, state.ulButtonPressed)); _dataIndex.addData(event_name + "/State/" + "Axis2Button" + "_Touched", getButtonState(vr::k_EButton_Axis2, state.ulButtonPressed)); _dataIndex.addData(event_name + "/State/" + "Axis3Button" + "_Pressed", getButtonState(vr::k_EButton_Axis3, state.ulButtonPressed)); _dataIndex.addData(event_name + "/State/" + "Axis3Button" + "_Touched", getButtonState(vr::k_EButton_Axis3, state.ulButtonPressed)); _dataIndex.addData(event_name + "/State/" + "Axis4Button" + "_Pressed", getButtonState(vr::k_EButton_Axis4, state.ulButtonPressed)); _dataIndex.addData(event_name + "/State/" + "Axis4Button" + "_Touched", getButtonState(vr::k_EButton_Axis4, state.ulButtonPressed)); //for(int axis = 0; axis < vr::k_unControllerStateAxisCount ; axis++){ for (int axis = 0; axis < 2; axis++){ std::ostringstream stringStream; stringStream << event_name << +"/State/Axis" << axis << "/"; std::string axis_name = stringStream.str(); _dataIndex.addData(axis_name + "Type", getAxisType(unDevice, 0)); _dataIndex.addData(axis_name + "XPos", state.rAxis[axis].x); _dataIndex.addData(axis_name + "YPos", state.rAxis[axis].y); } _events.push_back(_dataIndex.serialize(event_name)); } } } } std::string VROpenVRInputDevice::getDeviceName(int idx){ if (devices[idx] == "") { //this should never happen. Update deviceNames updateDeviceNames(); } return devices[idx]; } void VROpenVRInputDevice::updateDeviceNames() { devices.clear(); int hmd_count = 0; int controller_count = 0; int trackingReference_count = 0; int unknown_count = 0; for (vr::TrackedDeviceIndex_t unDevice = 0; unDevice < vr::k_unMaxTrackedDeviceCount; unDevice++) { if (m_pHMD->IsTrackedDeviceConnected(unDevice)) { std::string entry; vr::TrackedDeviceClass deviceClass = m_pHMD->GetTrackedDeviceClass(unDevice); if (deviceClass == vr::TrackedDeviceClass_HMD) { hmd_count++; entry = m_name + "_HMD_" + std::to_string(hmd_count); } else if (deviceClass == vr::TrackedDeviceClass_Controller){ controller_count++; entry = m_name + "_Controller_" + std::to_string(controller_count); } else if (deviceClass == vr::TrackedDeviceClass_TrackingReference){ trackingReference_count++; entry = m_name + "_TrackingReference_" + std::to_string(trackingReference_count); } else{ unknown_count++; entry = m_name + "_UnknownDevice_" + std::to_string(unknown_count); } devices.push_back(entry); } else { devices.push_back(""); } } } std::string VROpenVRInputDevice::getButtonName(vr::EVRButtonId id){ switch( id ) { case vr::k_EButton_System: return "SystemButton"; case vr::k_EButton_ApplicationMenu: return "ApplicationMenuButton"; case vr::k_EButton_Grip: return "GripButton"; case vr::k_EButton_DPad_Left: return "DPad_LeftButton"; case vr::k_EButton_DPad_Up: return "DPad_UpButton"; case vr::k_EButton_DPad_Right: return "DPad_RightButton"; case vr::k_EButton_DPad_Down: return "DPad_DownButton"; case vr::k_EButton_A: return "AButton"; case vr::k_EButton_Axis0: return "Axis0utton"; case vr::k_EButton_Axis1: return "Axis1Button"; case vr::k_EButton_Axis2: return "Axis2Button"; case vr::k_EButton_Axis3: return "Axis3Button"; case vr::k_EButton_Axis4: return "Axis4Button"; } return "Invalid"; } void VROpenVRInputDevice::processVREvent( const vr::VREvent_t & event ,vr::TrackedDevicePose_t *pose) { switch( event.eventType ) { case vr::VREvent_TrackedDeviceActivated: { updateDeviceNames(); std::cerr << "Device " << getDeviceName(event.trackedDeviceIndex) << " idx : " << event.trackedDeviceIndex << " attached.\n" << std::endl; } break; case vr::VREvent_TrackedDeviceDeactivated: { std::cerr << "Device " << getDeviceName( event.trackedDeviceIndex) << " detached.\n" << std::endl; updateDeviceNames(); } break; case vr::VREvent_TrackedDeviceUpdated: { std::cerr << "Device " << getDeviceName(event.trackedDeviceIndex) << " updated.\n" << std::endl; updateDeviceNames(); } break; case vr::VREvent_ButtonPress : { std::string event_name = getDeviceName(event.trackedDeviceIndex) + "_" + getButtonName((vr::EVRButtonId) event.data.controller.button) + "_Pressed"; _dataIndex.addData(event_name + "/Pose", poseToMatrix4(pose)); _events.push_back(_dataIndex.serialize(event_name)); } break; case vr::VREvent_ButtonUnpress: { std::string event_name = getDeviceName(event.trackedDeviceIndex) + "_" + getButtonName((vr::EVRButtonId) event.data.controller.button) + "_Released"; _dataIndex.addData(event_name + "/Pose", poseToMatrix4(pose)); _events.push_back(_dataIndex.serialize(event_name)); } break; case vr::VREvent_ButtonTouch: { std::string event_name = getDeviceName(event.trackedDeviceIndex) + "_" + getButtonName((vr::EVRButtonId) event.data.controller.button) + "_Touched"; _dataIndex.addData(event_name + "/Pose", poseToMatrix4(pose)); _events.push_back(_dataIndex.serialize(event_name)); } break; case vr::VREvent_ButtonUntouch: { std::string event_name = getDeviceName(event.trackedDeviceIndex) + "_" + getButtonName((vr::EVRButtonId) event.data.controller.button) + "_Untouched"; _dataIndex.addData(event_name + "/Pose", poseToMatrix4(pose)); _events.push_back(_dataIndex.serialize(event_name)); } break; } } VRMatrix4 VROpenVRInputDevice::poseToMatrix4(vr::TrackedDevicePose_t *pose) { if(!pose->bPoseIsValid) return VRMatrix4(); VRMatrix4 mat = VRMatrix4::fromRowMajorElements( pose->mDeviceToAbsoluteTracking.m[0][0], pose->mDeviceToAbsoluteTracking.m[1][0], pose->mDeviceToAbsoluteTracking.m[2][0], 0.0, pose->mDeviceToAbsoluteTracking.m[0][1], pose->mDeviceToAbsoluteTracking.m[1][1], pose->mDeviceToAbsoluteTracking.m[2][1], 0.0, pose->mDeviceToAbsoluteTracking.m[0][2], pose->mDeviceToAbsoluteTracking.m[1][2], pose->mDeviceToAbsoluteTracking.m[2][2], 0.0, pose->mDeviceToAbsoluteTracking.m[0][3], pose->mDeviceToAbsoluteTracking.m[1][3], pose->mDeviceToAbsoluteTracking.m[2][3], 1.0f ); return mat.transpose(); } } /* namespace MinVR */
40.22408
156
0.728112
elainejiang8
ce28e1f2f3e9da82cb87668869f44cf00615d388
114
hxx
C++
src/Providers/UNIXProviders/PrintSAP/UNIX_PrintSAP_FREEBSD.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
1
2020-10-12T09:00:09.000Z
2020-10-12T09:00:09.000Z
src/Providers/UNIXProviders/PrintSAP/UNIX_PrintSAP_FREEBSD.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
null
null
null
src/Providers/UNIXProviders/PrintSAP/UNIX_PrintSAP_FREEBSD.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
null
null
null
#ifdef PEGASUS_OS_FREEBSD #ifndef __UNIX_PRINTSAP_PRIVATE_H #define __UNIX_PRINTSAP_PRIVATE_H #endif #endif
9.5
33
0.833333
brunolauze
ce29d83f5cca49a329feb55b17adb09dd45e7011
395
cpp
C++
BOJ_CPP/11597.cpp
tnsgh9603/BOJ_CPP
432b1350f6c67cce83aec3e723e30a3c6b5dbfda
[ "MIT" ]
null
null
null
BOJ_CPP/11597.cpp
tnsgh9603/BOJ_CPP
432b1350f6c67cce83aec3e723e30a3c6b5dbfda
[ "MIT" ]
null
null
null
BOJ_CPP/11597.cpp
tnsgh9603/BOJ_CPP
432b1350f6c67cce83aec3e723e30a3c6b5dbfda
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define fastio ios::sync_with_stdio(0), cin.tie(0), cout.tie(0) using namespace std; int arr[100'001]; int main() { int n, ans = INT_MAX; cin >> n; for (int i = 0; i < n; ++i) { cin >> arr[i]; } sort(arr, arr + n); for (int i = 0; i < n / 2; ++i) { ans = min(ans, arr[i] + arr[n - 1 - i]); } cout << ans; return 0; }
20.789474
63
0.481013
tnsgh9603
ce2aba1accaf931fb79ef906a84914685426eec6
706
cpp
C++
dataset/test/modification/1467_rename/8/transformation_1.cpp
Karina5005/Plagiarism
ce11f72ba21a754ca84a27e5f26a31a19d6cb6fb
[ "MIT" ]
3
2022-02-15T00:29:39.000Z
2022-03-15T08:36:44.000Z
dataset/test/modification/1467_rename/8/transformation_1.cpp
Kira5005-code/Plagiarism
ce11f72ba21a754ca84a27e5f26a31a19d6cb6fb
[ "MIT" ]
null
null
null
dataset/test/modification/1467_rename/8/transformation_1.cpp
Kira5005-code/Plagiarism
ce11f72ba21a754ca84a27e5f26a31a19d6cb6fb
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef long long ll; #define fo(i, a, n) for (int i = a; i < n; i++) #define foe(i, a, n) for (int i = a; i <= n; i++) void fpx_o() { int n_d; cin >> n_d; if (n_d == 1) cout << 9 << endl; else if (n_d == 2) cout << 98 << endl; else if (n_d == 3) cout << 989 << endl; else { int ee_u = 0; cout << 989; fo(i, 0, n - 3) { cout << ee_u; ee_u = (ee_u + 1) % 10; } cout << endl; } } int main() { int bev_k = 1; cin >> bev_k; while (bev_k--) { fpx_o(); } return 0; }
18.102564
50
0.382436
Karina5005
ce2d0051690dbfc2e25292480a20eac807049323
6,847
cpp
C++
src/Squad.cpp
Kruecke/KBot
97a9abc4537d83c9b6132684b7fa41dec807d174
[ "MIT" ]
2
2017-03-18T18:22:00.000Z
2017-07-17T17:02:58.000Z
src/Squad.cpp
fklemme/KBot
97a9abc4537d83c9b6132684b7fa41dec807d174
[ "MIT" ]
3
2017-03-17T04:23:38.000Z
2017-07-02T17:43:09.000Z
src/Squad.cpp
Kruecke/KBot
97a9abc4537d83c9b6132684b7fa41dec807d174
[ "MIT" ]
null
null
null
#include "Squad.h" #include "KBot.h" #include "utils.h" #include <stdexcept> namespace KBot { using namespace BWAPI; Squad::Squad(KBot &kBot) : m_kBot(&kBot), m_state(State::scout) {} void Squad::update() { if (!empty()) { // Draw squad radius Broodwar->drawCircleMap(getPosition(), 400, Colors::Red); Broodwar->drawTextMap(getPosition(), "Squad: %s", to_string(m_state).c_str()); // Show membership for (const auto &unit : *this) Broodwar->drawLineMap(getPosition(), unit->getPosition(), Colors::Grey); // Draw path to enemy if (m_kBot->enemy().getPositionCount() > 0) { const auto enemyPosition = Position(m_kBot->enemy().getClosestPosition()); const auto path = m_kBot->map().GetPath(getPosition(), enemyPosition); if (!path.empty()) { Broodwar->drawLineMap(getPosition(), Position(path.front()->Center()), Colors::Red); for (std::size_t i = 1; i < path.size(); ++i) Broodwar->drawLineMap(Position(path[i - 1]->Center()), Position(path[i]->Center()), Colors::Red); Broodwar->drawLineMap(Position(path.back()->Center()), enemyPosition, Colors::Red); } else Broodwar->drawLineMap(getPosition(), enemyPosition, Colors::Red); } } // ----- Prevent spamming ----------------------------------------------- // Everything below is executed only occasionally and not on every frame. if (Broodwar->getFrameCount() % Broodwar->getLatencyFrames() != 0) return; // TODO: remove const auto enemiesNearBase = Broodwar->getUnitsInRadius( Position(Broodwar->self()->getStartLocation()), 1000, Filter::IsEnemy); // Update squad state const auto oldState = m_state; switch (m_state) { case State::scout: if (!enemiesNearBase.empty()) m_state = State::defend; else if (m_kBot->enemy().getPositionCount() > 0) { if (size() >= 20) m_state = State::attack; else m_state = State::defend; } break; case State::attack: if (!enemiesNearBase.empty()) m_state = State::defend; else if (m_kBot->enemy().getPositionCount() == 0) m_state = State::scout; else if (size() < 10) m_state = State::defend; break; case State::defend: if (enemiesNearBase.empty()) { if (m_kBot->enemy().getPositionCount() == 0) m_state = State::scout; if (size() >= 20) m_state = State::attack; } break; default: throw std::logic_error("Unknown Squad::State!"); } // Reassign orders on state change if (m_state != oldState) this->stop(); // TODO: Move unit logic for (const auto &unit : *this) { assert(unit->exists()); // Ignore the unit if it has one of the following status ailments if (unit->isLockedDown() || unit->isMaelstrommed() || unit->isStasised()) continue; // Ignore the unit if it is in one of the following states if (unit->isLoaded() || !unit->isPowered() || unit->isStuck()) continue; if (unit->getType() == UnitTypes::Terran_Marine) { int unitPathLength; BWEM::CPPath unitPath; switch (m_state) { case State::scout: if (unit->isIdle()) // Scout! unit->attack(Position(m_kBot->enemy().getClosestPosition())); break; case State::attack: unitPath = m_kBot->map().GetPath(unit->getPosition(), getPosition(), &unitPathLength); if (unitPathLength > 400 && !unit->isUnderAttack()) { // Regroup! // Prevent spamming, check if order is already set. TODO: Still bad bahavior. if (unit->getOrder() != Orders::AttackMove || distance(unit->getOrderTargetPosition(), getPosition()) >= 400) { Position orderPosition, lastNode; if (unitPath.empty()) lastNode = unit->getPosition(); else lastNode = Position(unitPath.back()->Center()); if (getPosition().getApproxDistance(lastNode) <= 350) orderPosition = lastNode; else { // Move further to the middle to prevent edge-sticky behavior. const Point<double> vector = lastNode - getPosition(); orderPosition = getPosition() + vector * 350 / vector.getLength(); } unit->attack(orderPosition); // debug Broodwar->registerEvent( [unit, orderPosition](Game *) { Broodwar->drawLineMap(unit->getPosition(), orderPosition, Colors::Purple); }, [unit](Game *) { return unit->exists(); }, Broodwar->getLatencyFrames()); } } else if (unit->isIdle()) // Attack! unit->attack(Position(m_kBot->enemy().getClosestPosition())); break; case State::defend: if (distance(unit->getPosition(), Broodwar->self()->getStartLocation()) > 1000) { // Retreat! // Prevent spamming, check if order is already set. if (unit->getOrder() != Orders::AttackMove || distance(unit->getOrderTargetPosition(), Broodwar->self()->getStartLocation()) > 1000) unit->attack(Position(Broodwar->self()->getStartLocation())); } else if (unit->isIdle() && !enemiesNearBase.empty()) // Defend! unit->attack(unit->getClosestUnit(Filter::IsEnemy)->getPosition()); break; default: throw std::logic_error("Unknown Squad::State!"); } } } } std::string to_string(Squad::State state) { switch (state) { case Squad::State::scout: return "Scout"; case Squad::State::attack: return "Attack"; case Squad::State::defend: return "Defend"; default: throw std::logic_error("Unknown Squad::State!"); } } } // namespace
39.350575
100
0.498174
Kruecke
ce2d2c335f7263114a7dc4cbcdd2767b153dc6b2
2,622
cpp
C++
source/lx/fvec2.cpp
zhiayang/sim-thing
8d9d5163146e2bdde15f4eadefa85453f12fac18
[ "Apache-2.0" ]
1
2021-02-07T08:40:11.000Z
2021-02-07T08:40:11.000Z
source/lx/fvec2.cpp
zhiayang/sim-thing
8d9d5163146e2bdde15f4eadefa85453f12fac18
[ "Apache-2.0" ]
null
null
null
source/lx/fvec2.cpp
zhiayang/sim-thing
8d9d5163146e2bdde15f4eadefa85453f12fac18
[ "Apache-2.0" ]
null
null
null
// fvec2.cpp // Copyright (c) 2014 - 2016, zhiayang@gmail.com // Licensed under the Apache License Version 2.0. #include "lx.h" #include "lx/fvec2.h" #include <assert.h> namespace lx { float& fvec2::operator[] (size_t i) { assert(i == 0 || i == 1); return this->ptr[i]; } const float& fvec2::operator[] (size_t i) const { assert(i == 0 || i == 1); return this->ptr[i]; } fvec2 fvec2::operator - () const { return fvec2(-this->x, -this->y); } fvec2& fvec2::operator += (const fvec2& v) { this->x += v.x; this->y += v.y; return *this; } fvec2& fvec2::operator -= (const fvec2& v) { this->x -= v.x; this->y -= v.y; return *this; } fvec2& fvec2::operator *= (const fvec2& v) { this->x *= v.x; this->y *= v.y; return *this; } fvec2& fvec2::operator /= (const fvec2& v) { this->x /= v.x; this->y /= v.y; return *this; } fvec2& fvec2::operator *= (float s) { this->x *= s; this->y *= s; return *this; } fvec2& fvec2::operator /= (float s) { this->x /= s; this->y /= s; return *this; } float fvec2::magnitudeSquared() const { return (this->x * this->x) + (this->y * this->y); } float fvec2::magnitude() const { return sqrt(this->magnitudeSquared()); } fvec2 fvec2::normalised() const { float mag = (this->x * this->x) + (this->y * this->y); float ivs = _fastInverseSqrtF(mag); return fvec2(this->x * ivs, this->y * ivs); } fvec2 operator + (const fvec2& a, const fvec2& b) { return fvec2(a.x + b.x, a.y + b.y); } fvec2 operator - (const fvec2& a, const fvec2& b) { return fvec2(a.x - b.x, a.y - b.y); } fvec2 operator * (const fvec2& a, const fvec2& b) { return fvec2(a.x * b.x, a.y * b.y); } fvec2 operator / (const fvec2& a, const fvec2& b) { return fvec2(a.x / b.x, a.y / b.y); } bool operator == (const fvec2& a, const fvec2& b) { return a.x == b.x && a.y == b.y; } fvec2 operator * (const fvec2& a, float b) { return fvec2(a.x * b, a.y * b); } fvec2 operator / (const fvec2& a, float b) { return fvec2(a.x / b, a.y / b); } fvec2 operator * (float a, const fvec2& b) { return b * a; } fvec2 operator / (float a, const fvec2& b) { return b / a; } fvec2 round(const fvec2&v) { return fvec2(lx::round(v.x), lx::round(v.y)); } fvec2 normalise(const fvec2& v) { return v.normalised(); } float magnitude(const fvec2& v) { return v.magnitude(); } float magnitudeSquared(const fvec2& v) { return v.magnitudeSquared(); } float dot(const fvec2& a, const fvec2& b) { return (a.x * b.x) + (a.y * b.y); } float distance(const fvec2& a, const fvec2& b) { return lx::sqrt( ((a.x - b.x) * (a.x - b.x)) + ((a.y - b.y) * (a.y - b.y)) ); } }
26.484848
93
0.58505
zhiayang
ce2d5a527c00b4e538c7f002b16507652cd5be62
1,602
cc
C++
firmware/src/MightyBoard/shared/Pin.cc
46cv8/Sailfish-MightyBoardFirmware
4d8456e54c537dd32775095ed2715d41f5961e6c
[ "AAL" ]
79
2015-01-13T21:00:15.000Z
2022-03-22T14:40:41.000Z
firmware/src/MightyBoard/shared/Pin.cc
46cv8/Sailfish-MightyBoardFirmware
4d8456e54c537dd32775095ed2715d41f5961e6c
[ "AAL" ]
79
2015-04-23T18:25:49.000Z
2021-10-03T14:42:07.000Z
firmware/src/MightyBoard/shared/Pin.cc
46cv8/Sailfish-MightyBoardFirmware
4d8456e54c537dd32775095ed2715d41f5961e6c
[ "AAL" ]
66
2015-01-05T04:05:09.000Z
2022-02-16T17:31:02.000Z
#include "Compat.hh" #include "Pin.hh" Pin::Pin() : port_base(NullPort.port_base), is_null(true), pin_mask(0), pin_mask_inverted((uint8_t)~0) { } Pin::Pin(const AvrPort& port_in, uint8_t pin_index_in) : port_base(port_in.port_base), is_null(port_base == NULL_PORT), pin_mask((uint8_t)_BV(pin_index_in)), pin_mask_inverted((uint8_t)~_BV(pin_index_in)) { } Pin::Pin(const Pin& other_pin) : port_base(other_pin.port_base), is_null(port_base == NULL_PORT), pin_mask(other_pin.pin_mask), pin_mask_inverted(other_pin.pin_mask_inverted) { } bool Pin::isNull() const { return is_null; } void Pin::setDirection(bool out) const { // if (is_null) // return; uint8_t oldSREG = SREG; cli(); if (out) { DDRx |= (uint8_t)pin_mask; } else { DDRx &= (uint8_t)pin_mask_inverted; } SREG = oldSREG; } void Pin::setValue(bool on) const { // if (is_null) // return; // uint8_t oldSREG = SREG; // cli(); if (on) { PORTx |= pin_mask; } else { PORTx &= pin_mask_inverted; } // SREG = oldSREG; } bool Pin::getValue() const { if (is_null) return false; // null pin is always low ... ? return (uint8_t)((uint8_t)PINx & (uint8_t)pin_mask) != 0; } /* bool Pin::getValue() const { if (is_null) return false; // null pin is always low ... ? return (uint8_t)((uint8_t)PINx & (uint8_t)pin_mask) != 0; } void Pin::setValue(bool on) const { // if (is_null) // return; uint8_t oldSREG = SREG; cli(); if (on) { PORTx |= pin_mask; } else { PORTx &= pin_mask_inverted; } SREG = oldSREG; } */
20.538462
58
0.626092
46cv8
ce2dd54b596d6c8e57b70db5d7f532404fc6fe6f
5,135
cpp
C++
Source/ppmc.cpp
leossoaress/PPMC
025ee65e94a19222d5361132bf6c3743eeae13f4
[ "MIT" ]
null
null
null
Source/ppmc.cpp
leossoaress/PPMC
025ee65e94a19222d5361132bf6c3743eeae13f4
[ "MIT" ]
null
null
null
Source/ppmc.cpp
leossoaress/PPMC
025ee65e94a19222d5361132bf6c3743eeae13f4
[ "MIT" ]
null
null
null
#include "ppmc.h" PPMC::PPMC(unsigned int order_, std::string inputname, std::string outputname) : order(order_) { root = new Node(ROOT); base = root; input.open(inputname, std::ios::in | std::ios::binary); if(!input) { std::cout << "Could not open input file" << std::endl; exit(-1); } input.seekg(0, std::ios::end); long size = input.tellg(); input.seekg(0, std::ios::beg); std::vector<unsigned char> v (size/sizeof(char)); input.read((char *) &v[0], size); this->data = new std::string(v.begin(), v.end()); step_progess = 1.0 / this->data->size(); output.open(outputname, std::ios::out | std::ios::binary); if(!output) { std::cout << "Unable to open output file" << std::endl; exit(0); } arithmetic.SetFile(&output); } void PPMC::Compress() { clock_t start = std::clock(); for(auto &ch : *data) { Encode(ch); InsertSymbol(ch); Progress(); } arithmetic.EncodeFinish(); duration = (std::clock() - start) / (double) CLOCKS_PER_SEC; std::cout << std::setprecision(3) << std::fixed; std::clog << "\nCompression duration time: " << duration << " segundos" << std::endl; } void PPMC::Encode(unsigned char symbol_) { Node* pVine = base->GetVine(); Node *pActualNode = nullptr; bool excluded[256] = {false}; while(pVine != nullptr) { pActualNode = pVine->FindChild(symbol_); if(pActualNode == nullptr && pVine->GetChild() != nullptr) { //std::cout << "esc: "; GetInterval(pVine, pVine->GetEsc(), excluded); Node* pAux = pVine->GetChild(); while(pAux != nullptr) { excluded[pAux->GetSymbol()] = true; pAux = pAux->GetSibiling(); } pVine = pVine->GetVine(); } else if(pActualNode != nullptr){ //std::cout << pActualNode->GetSymbol() << ": "; GetInterval(pVine, pActualNode, excluded); return; } else { pVine = pVine->GetVine(); } } if(pVine == nullptr) { usedCh[symbol_] = true; //std::cout << "Root: "; GetInverval2(symbol_); return; } } void PPMC::InsertSymbol(unsigned char symbol_) { int depth = GetContextDepth(base); Node *pAuxNode = (depth < order) ? base : base->GetVine();; Node *pActualNode = pAuxNode->InsertChild(symbol_); pActualNode->SetVine(pAuxNode); base = pActualNode; Node* z = pAuxNode->GetVine(); Node* b = z; Node* a = nullptr; int count = 0; while(z != nullptr) { Node *pNode = z->InsertChild(symbol_); pNode->SetVine(z); b = pNode; if(count == 0) { base->SetVine(b); } else { a->SetVine(b); a = b; } a = b; z = z->GetVine(); count++; } } void PPMC::GetInterval(Node *pDad, Node *pChild, bool *arr) { unsigned int sum = 0, sum2 = 0; Node* pAuxNode = pDad->GetChild(); while(pAuxNode != nullptr && pAuxNode != pChild) { if(arr[pAuxNode->GetSymbol()] == false) { sum += pAuxNode->GetCount(); } else { sum2 += pAuxNode->GetCount(); } pAuxNode = pAuxNode->GetSibiling(); } //printf("(%d,%d,%d)\n", sum, sum+pChild->GetCount(), pDad->GetChildrenCount()-sum2); arithmetic.Encode(sum, sum+pChild->GetCount(), pDad->GetChildrenCount()-sum2); } void PPMC::GetInverval2(unsigned char symbol_) { unsigned int sum = 0; for(unsigned i = 0; i < symbol_; ++i) { if(usedCh[i] == false) { sum++; } } //printf("(%d,%d,%d)\n", sum, sum+1, numCh); arithmetic.Encode(sum, sum+1, numCh); numCh--; } int PPMC::GetContextDepth(Node *node) { int counter = -1; while(node->GetVine() != nullptr) { counter++; node = node->GetVine(); } return counter; } void PPMC::PrintTree(Node* node, int deep) { for(auto i = 0; i < deep; ++i) std::cout << "\t"; switch (node->GetType()) { case ROOT: printf("root\n"); break; case ESC: printf("esc(%d)\n", node->GetCount()); break; default: printf("%c(%d)\n", node->GetSymbol(), node->GetCount()); break; } if(node->GetChild() != nullptr) { PrintTree(node->GetChild(), ++deep); if(node->GetEsc() != nullptr) { PrintTree(node->GetEsc(), deep); } if(node->GetSibiling() != nullptr) { PrintTree(node->GetSibiling(), --deep); } } } void PPMC::Progress() { progess = progess + step_progess; std::stringstream progress_stream; progress_stream << "\rProgress .........................: " << std::fixed << std::setw( 6 ) << std::setprecision( 2 ) << 100 * progess << "%"; std::clog << progress_stream.str(); }
23.555046
94
0.508666
leossoaress
ce2ea67d09cd6a4ef1b0b42c6a6a69b9d6e5842e
19,578
cpp
C++
src/cdnscache.cpp
Network-Tokens/oss-util
a1223835bc29ac5a291acfb02fabf513a18f6996
[ "Apache-2.0" ]
null
null
null
src/cdnscache.cpp
Network-Tokens/oss-util
a1223835bc29ac5a291acfb02fabf513a18f6996
[ "Apache-2.0" ]
null
null
null
src/cdnscache.cpp
Network-Tokens/oss-util
a1223835bc29ac5a291acfb02fabf513a18f6996
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2017 Sprint * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdarg.h> #include <stdio.h> #include <memory.h> #include <poll.h> #include <fstream> #include <iostream> #include <list> #include "serror.h" #include "sthread.h" #include "ssync.h" #include "cdnscache.h" #include "cdnsparser.h" using namespace CachedDNS; #define RAPIDJSON_NAMESPACE dnsrapidjson #include "rapidjson/rapidjson.h" #include "rapidjson/document.h" #include "rapidjson/writer.h" #include "rapidjson/filereadstream.h" #include "rapidjson/filewritestream.h" #include "rapidjson/prettywriter.h" #include "rapidjson/stringbuffer.h" using namespace RAPIDJSON_NAMESPACE; //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// template<class T> class Buffer { public: Buffer(size_t size) { msize = size; mbuf = new T[msize]; } ~Buffer() { if (mbuf) delete [] mbuf; } T *get() { return mbuf; } private: Buffer(); size_t msize; T *mbuf; }; static std::string string_format( const char *format, ... ) { va_list args; va_start( args, format ); size_t size = vsnprintf( NULL, 0, format, args ) + 1; // Extra space for '\0' va_end( args ); Buffer<char> buf( size ); va_start( args, format ); vsnprintf( buf.get(), size, format, args ); va_end( args ); return std::string( buf.get(), size - 1 ); // We don't want the '\0' inside } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// namespace CachedDNS { QueryProcessorThread::QueryProcessorThread(QueryProcessor &qp) : m_shutdown( false ), m_qp(qp), m_activequeries(0) { } unsigned long QueryProcessorThread::threadProc(void *arg) { while ( true ) { int qcnt = m_activequeries.getCurrentCount(); if ( qcnt == 0 ) { // wait for a new query to be submitted or for shutdown decActiveQueries(); if ( m_shutdown && getActiveQueries() == 0 ) break; incActiveQueries(); } else if ( m_shutdown && qcnt == 1 ) { break; } wait_for_completion(); } return 0; } void QueryProcessorThread::wait_for_completion() { struct timeval tv; int timeout; ares_socket_t sockets[ ARES_GETSOCK_MAXNUM ]; struct pollfd fds[ ARES_GETSOCK_MAXNUM ]; while( true ) { int rwbits = ares_getsock( m_qp.getChannel(), sockets, ARES_GETSOCK_MAXNUM ); int fdcnt = 0; memset( fds, 0, sizeof(fds) ); for ( int i = 0; i < ARES_GETSOCK_MAXNUM; i++ ) { fds[fdcnt].fd = sockets[i]; fds[fdcnt].events |= ARES_GETSOCK_READABLE(rwbits,i) ? (POLLIN | POLLRDNORM) : 0; fds[fdcnt].events |= ARES_GETSOCK_WRITABLE(rwbits,i) ? (POLLOUT | POLLWRNORM) : 0; if ( fds[fdcnt].events != 0 ) fdcnt++; } if ( !fdcnt ) break; memset( &tv, 0, sizeof(tv) ); ares_timeout( m_qp.getChannel(), NULL, &tv ); timeout = (tv.tv_sec * 1000) + (tv.tv_usec / 1000); if ( poll(fds,fdcnt,timeout) != 0 ) { for ( int i = 0; i < fdcnt; i++ ) { if ( fds[i].revents != 0 ) { SMutexLock l( m_qp.getChannelMutex() ); ares_process_fd( m_qp.getChannel(), fds[i].revents & (POLLIN | POLLRDNORM) ? fds[i].fd : ARES_SOCKET_BAD, fds[i].revents & (POLLOUT | POLLWRNORM) ? fds[i].fd : ARES_SOCKET_BAD); } } } else { // timeout SMutexLock l( m_qp.getChannelMutex() ); ares_process_fd( m_qp.getChannel(), ARES_SOCKET_BAD, ARES_SOCKET_BAD ); } } } void QueryProcessorThread::shutdown() { m_shutdown = true; incActiveQueries(); join(); } void QueryProcessorThread::ares_callback( void *arg, int status, int timeouts, unsigned char *abuf, int alen ) { QueryPtr *qq = reinterpret_cast<QueryPtr*>(arg); QueryProcessor *qp = (*qq)->getQueryProcessor(); if (qp) { qp->endQuery(); try { Parser p( *qq, abuf, alen ); p.parse(); } catch (std::exception &ex) { (*qq)->setError( true ); (*qq)->setErrorMsg( ex.what() ); } if ( !(*qq)->getError() ) { qp->getCache().updateCache( *qq ); } if ( (*qq)->getCompletionEvent() ) (*qq)->getCompletionEvent()->set(); if ( (*qq)->getCallback() ) { const void *data = (*qq)->getData(); (*qq)->setData(NULL); (*qq)->getCallback()( *qq, false, data ); } } delete qq; } ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// QueryProcessor::QueryProcessor( Cache &cache ) : m_cache( cache ), m_qpt( *this ) { m_channel = NULL; init(); m_qpt.init( NULL ); } QueryProcessor::~QueryProcessor() { ares_destroy( m_channel ); } void QueryProcessor::init() { int status; if ( (status = ares_init(&m_channel)) == ARES_SUCCESS ) { struct ares_options opt; opt.timeout = m_cache.getQueryTimeoutMS(); opt.tries = m_cache.getQueryTries(); opt.ndots = 0; opt.flags = ARES_FLAG_EDNS; opt.ednspsz = 8192; ares_init_options( &m_channel, &opt, ARES_OPT_TIMEOUTMS | ARES_OPT_TRIES | ARES_OPT_NDOTS | ARES_OPT_EDNSPSZ | ARES_OPT_FLAGS ); } else { std::string msg( string_format("QueryProcessor::init() - ares_init() failed status = %d", status) ); SError::throwRuntimeException( msg ); } } void QueryProcessor::shutdown() { m_qpt.shutdown(); } void QueryProcessor::addNamedServer(const char *address, int udp_port, int tcp_port) { union { struct in_addr addr4; struct ares_in6_addr addr6; } addr; struct NamedServer ns; if (ares_inet_pton(AF_INET, address, &addr.addr4) == 1) ns.family = AF_INET; else if (ares_inet_pton(AF_INET6, address, &addr.addr6) == 1) ns.family = AF_INET6; else { std::string msg( string_format("QueryProcessor::addNamedServer() - unrecognized address [%s]", address) ); SError::throwRuntimeException( msg ); } ares_inet_ntop( ns.family, &addr, ns.address, sizeof(ns.address) ); ns.udp_port = udp_port; ns.tcp_port = tcp_port; m_servers[std::string(ns.address)] = ns; } void QueryProcessor::removeNamedServer(const char *address) { m_servers.erase( address ); } void QueryProcessor::applyNamedServers() { ares_addr_port_node *head = NULL; // create linked list of named servers for (const auto &kv : m_servers) { ares_addr_port_node *p = new ares_addr_port_node(); p->next = head; p->family = kv.second.family; ares_inet_pton( p->family, kv.second.address, &p->addr ); p->udp_port = kv.second.udp_port; p->tcp_port = kv.second.tcp_port; head = p; } // apply the named server list int status = ares_set_servers_ports( m_channel, head ); // delete the list of named servers while (head) { ares_addr_port_node *p = head; head = head->next; delete p; } // throw exception if needed if ( status != ARES_SUCCESS ) SError::throwRuntimeException( "QueryProcessor::updateNamedServers() - ares_set_servers_ports() failed status = %d", status ); } void QueryProcessor::beginQuery( QueryPtr &q ) { m_qpt.incActiveQueries(); q->setQueryProcessor( this ); q->setError( false ); QueryPtr *qq = new QueryPtr(q); if ( q->getCallback() || q->getCompletionEvent() ) { SMutexLock l( getChannelMutex() ); ares_query( m_channel, q->getDomain().c_str(), ns_c_in, q->getType(), QueryProcessorThread::ares_callback, qq ); } else { SEvent event; q->setCompletionEvent( &event ); { SMutexLock l( getChannelMutex() ); ares_query( m_channel, q->getDomain().c_str(), ns_c_in, q->getType(), QueryProcessorThread::ares_callback, qq ); } event.wait(); q->setCompletionEvent( NULL ); } } void QueryProcessor::endQuery() { m_qpt.decActiveQueries(); } ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// int Cache::m_ref = 0; unsigned int Cache::m_concur = 10; int Cache::m_percent = 80; long Cache::m_interval = 60; int Cache::m_querytimeout = 500; int Cache::m_querytries = 1; Cache::Cache() : m_qp( *this ), m_refresher( *this, m_concur, m_percent, m_interval ) { if (m_ref == 0) { int status = ares_library_init( ARES_LIB_INIT_ALL ); if ( status != ARES_SUCCESS ) { std::string msg( string_format("Cache::Cache() - ares_library_init() failed status = %d", status) ); SError::throwRuntimeException( msg ); } } m_ref++; m_nsid = NS_DEFAULT; m_newquerycnt = 0; // start the refresh thread m_refresher.init(NULL); } Cache::~Cache() { // stop the refresh thread m_refresher.quit(); m_refresher.join(); // stop the query processor m_qp.shutdown(); m_ref--; if (m_ref == 0) ares_library_cleanup(); } class CacheMap { public: ~CacheMap() { std::map<namedserverid_t, Cache*>::iterator it; while ((it = m_map.begin()) != m_map.end()) { Cache *c = it->second; m_map.erase( it ); delete c; } } std::map<namedserverid_t, Cache*> &getMap() { return m_map; } private: std::map<namedserverid_t, Cache*> m_map; }; Cache& Cache::getInstance(namedserverid_t nsid) { static CacheMap cm; Cache *c; auto search = cm.getMap().find(nsid); if (search == cm.getMap().end()) { c = new Cache(); c->m_nsid = nsid; cm.getMap()[nsid] = c; } else { c = search->second; } return *c; } void Cache::addNamedServer(const char *address, int udp_port, int tcp_port) { m_qp.addNamedServer(address, udp_port, tcp_port); } void Cache::removeNamedServer(const char *address) { m_qp.removeNamedServer(address); } void Cache::applyNamedServers() { m_qp.applyNamedServers(); } QueryPtr Cache::query( ns_type rtype, const std::string & domain, bool &cacheHit, bool ignorecache ) { QueryPtr q = lookupQuery( rtype, domain ); cacheHit = !( !q || q->isExpired() ); if ( !cacheHit || ignorecache ) // query not found or expired { q.reset( new Query( rtype, domain ) ); m_qp.beginQuery( q ); if (ignorecache) cacheHit = false; } return q; } void Cache::query( ns_type rtype, const std::string &domain, CachedDNSQueryCallback cb, const void *data, bool ignorecache ) { QueryPtr q = lookupQuery( rtype, domain ); bool cacheHit = !( !q || q->isExpired() ); if ( cacheHit && !ignorecache ) { if ( cb ) cb( q, cacheHit, data ); } else { q.reset( new Query( rtype, domain ) ); q->setCallback( cb ); q->setData( data ); m_qp.beginQuery( q ); } } void Cache::loadQueries(const char *qfn) { m_refresher.loadQueries( qfn ); } void Cache::initSaveQueries(const char *qfn, long qsf) { m_refresher.initSaveQueries( qfn, qsf ); } void Cache::saveQueries() { m_refresher.saveQueries(); } void Cache::forceRefresh() { m_refresher.forceRefresh(); } QueryPtr Cache::lookupQuery( ns_type rtype, const std::string &domain ) { QueryCacheKey qck( rtype, domain ); return lookupQuery( qck ); } QueryPtr Cache::lookupQuery( QueryCacheKey &qck ) { SRdLock l( m_cacherwlock ); QueryCache::const_iterator it = m_cache.find( qck ); return it != m_cache.end() ? it->second : QueryPtr(); } void Cache::updateCache( QueryPtr q ) { if ( !q ) return; if ( !q->getError() ) { QueryCacheKey qck( q->getType(), q->getDomain() ); SWrLock l( m_cacherwlock ); if ( m_cache.find(qck) == m_cache.end() ) atomic_inc_fetch( m_newquerycnt ); m_cache[qck] = q; } } void Cache::identifyExpired( std::list<QueryCacheKey> &keys, int percent ) { SRdLock l( m_cacherwlock ); for (auto val : m_cache) { QueryPtr q = val.second; if ( q ) { if ( !q->isExpired() ) { time_t diff = (q->getTTL() - (q->getExpires() - time(NULL))) * 100; int pcnt = diff / q->getTTL(); if ( pcnt < percent ) continue; } keys.push_back( val.first ); } } } void Cache::getCacheKeys( std::list<QueryCacheKey> &keys ) { SRdLock l( m_cacherwlock ); for (auto val : m_cache ) keys.push_back( val.first ); } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// CacheRefresher::CacheRefresher(Cache &cache, unsigned int maxconcur, int percent, long interval) : m_cache( cache ), m_sem( maxconcur ), m_percent( percent ), m_interval( interval ), m_running( false ), m_qfn( "" ), m_qsf( 0 ) { } void CacheRefresher::onInit() { m_timer.setInterval( m_interval ); m_timer.setOneShot( false ); initTimer( m_timer ); m_timer.start(); } void CacheRefresher::onQuit() { m_timer.stop(); } void CacheRefresher::onTimer( SEventThread::Timer &timer) { if (timer.getId() == m_timer.getId()) _refreshQueries(); else if (timer.getId() == m_qst.getId()) _saveQueries(); } void CacheRefresher::dispatch( SEventThreadMessage &msg ) { if (msg.getId() == CR_SAVEQUERIES) _saveQueries(); else if (msg.getId() == CR_FORCEREFRESH) _forceRefresh(); } void CacheRefresher::callback( QueryPtr q, bool cacheHit, const void *data ) { CacheRefresher *ths = (CacheRefresher*)data; ths->m_sem.increment(); } void CacheRefresher::initSaveQueries(const char *qfn, long qsf) { m_qfn = qfn; m_qsf = qsf; if (querySaveFrequency() > 0 && !queryFileName().empty()) { if ( m_qst.isInitialized() ) m_qst.stop(); m_qst.setInterval( querySaveFrequency() ); m_qst.setOneShot( false ); if ( !m_qst.isInitialized() ) initTimer( m_qst ); m_qst.start(); } } void CacheRefresher::_refreshQueries() { if (m_running) return; std::list<QueryCacheKey> keys; m_cache.identifyExpired( keys, m_percent ); _submitQueries( keys ); } void CacheRefresher::_forceRefresh() { if (m_running) return; std::list<QueryCacheKey> keys; m_cache.getCacheKeys( keys ); _submitQueries( keys ); } void CacheRefresher::_submitQueries( std::list<QueryCacheKey> &keys ) { m_running = true; for (auto qck : keys) { m_sem.decrement(); m_cache.query( qck.getType(), qck.getDomain(), callback, this, true ); } m_running = false; } void CacheRefresher::_saveQueries() { long nqc = m_cache.resetNewQueryCount(); if ( nqc == 0 ) { //std::cout << "CacheRefresher::_saveQueries() - no changes to save" << std::endl; return; } std::list<QueryCacheKey> keys; Document d; Document::AllocatorType &allocator = d.GetAllocator(); m_cache.getCacheKeys( keys ); d.SetArray(); //std::cout << "CacheRefresher::_saveQueries() - there are " << nqc << " new queries, saving " << keys.size() << " queries" << std::endl; for (auto qck : keys) { Value o( kObjectType ); o.AddMember( SAVED_QUERY_TYPE, qck.getType(), allocator ); o.AddMember( SAVED_QUERY_DOMAIN, Value(qck.getDomain().c_str(), allocator), allocator ); d.PushBack( o, allocator ); } FILE *fp = fopen( queryFileName().c_str(), "w" ); if (fp) { char buf[65536]; FileWriteStream fws( fp, buf, sizeof(buf) ); Writer<FileWriteStream> writer( fws ); d.Accept( writer ); fclose( fp ); } } void CacheRefresher::loadQueries(const char *qfn) { Document doc; FILE *fp; char buf[65536]; fp = fopen(qfn, "r"); if ( fp ) { FileReadStream frs(fp, buf, sizeof(buf)); doc.ParseStream(frs); fclose(fp); if ( !doc.IsArray() ) { std::string msg( string_format("CacheRefresher::loadQueries() - root is not an array [%s]", qfn) ); SError::throwRuntimeException( msg ); } for (auto &v : doc.GetArray()) { if ( !v.HasMember(SAVED_QUERY_TYPE) || !v[SAVED_QUERY_TYPE].IsInt() ) SError::throwRuntimeException( "CacheRefresher::loadQueries() - member \"" SAVED_QUERY_TYPE "\" missing or invalid type" ); if ( !v.HasMember(SAVED_QUERY_DOMAIN) || !v[SAVED_QUERY_DOMAIN].IsString() ) SError::throwRuntimeException( "CacheRefresher::loadQueries() - member \"" SAVED_QUERY_DOMAIN "\" missing or invalid type" ); ns_type typ = (ns_type)v[SAVED_QUERY_TYPE].GetInt(); const char *dmn = v[SAVED_QUERY_DOMAIN].GetString(); m_sem.decrement(); m_cache.query( typ, dmn, callback, this ); } } else { std::string msg( string_format("CacheRefresher::loadQueries() - unable to open [%s]", qfn) ); SError::throwRuntimeException( msg ); } } } // namespace CachedDNS
25.794466
143
0.53555
Network-Tokens
ce2fcb66fa63ad030e174d66fb332117ac4c6f22
3,317
hh
C++
p1.hh
bitsofcotton/p1
8cf062d961c018c39f4f15d7bc1baf0a641dde34
[ "BSD-3-Clause" ]
null
null
null
p1.hh
bitsofcotton/p1
8cf062d961c018c39f4f15d7bc1baf0a641dde34
[ "BSD-3-Clause" ]
6
2017-04-15T08:47:59.000Z
2020-10-15T12:43:17.000Z
p1.hh
bitsofcotton/p1
8cf062d961c018c39f4f15d7bc1baf0a641dde34
[ "BSD-3-Clause" ]
null
null
null
/* BSD 3-Clause License Copyright (c) 2020-2021, kazunobu watatsu All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #if !defined(_P1_) // Get invariant structure that // \[- &alpha, &alpha;\[ register computer with deterministic calculation. // cf. bitsofcotton/randtools . template <typename T, typename feeder> class P1I { public: typedef SimpleVector<T> Vec; typedef SimpleMatrix<T> Mat; inline P1I() { varlen = 0; } inline P1I(const int& stat, const int& var, const int& step = 1) { assert(0 < stat && 1 < var && 0 < step); f = feeder(stat + (this->step = step) - 1 + (varlen = var) - 1); } inline ~P1I() { ; } inline T next(const T& in) { static const T zero(0); const auto& buf(f.next(in)); if(! f.full) return T(0); // N.B. please use catgp to compete with over learning. const auto nin(sqrt(buf.dot(buf))); if(! isfinite(nin) || nin == zero) return zero; SimpleMatrix<T> toeplitz(buf.size() - varlen - step + 2, varlen + 2); for(int i = 0; i < toeplitz.rows(); i ++) { auto work(buf.subVector(i, varlen) / nin); work[work.size() - 1] = buf[i + varlen + step - 2] / nin; toeplitz.row(i) = makeProgramInvariant<T>(move(work), T(i + 1) / T(toeplitz.rows() + 1)).first; } const auto invariant(linearInvariant<T>(toeplitz)); if(invariant[varlen - 1] == zero) return zero; SimpleVector<T> work(varlen); for(int i = 1; i < work.size(); i ++) work[i - 1] = buf[i - work.size() + buf.size()] / nin; work[work.size() - 1] = zero; const auto work2(makeProgramInvariant<T>(work, T(1))); return revertProgramInvariant<T>(make_pair( - (invariant.dot(work2.first) - invariant[varlen - 1] * work2.first[varlen - 1]) / invariant[varlen - 1], work2.second)) * nin; } feeder f; private: int varlen; int step; }; #define _P1_ #endif
39.488095
78
0.691589
bitsofcotton
ce30b4ffb1b49ddda52382ff27471fc96cb4e264
2,018
cpp
C++
unittests/testNearestNeighbor.cpp
purewind7/CS7496
ca0b8376db400f265d9515d8307d928590a1569a
[ "BSD-2-Clause" ]
4
2021-02-20T15:59:42.000Z
2022-03-25T04:04:21.000Z
unittests/testNearestNeighbor.cpp
purewind7/CS7496
ca0b8376db400f265d9515d8307d928590a1569a
[ "BSD-2-Clause" ]
1
2021-04-14T04:12:48.000Z
2021-04-14T04:12:48.000Z
unittests/testNearestNeighbor.cpp
purewind7/CS7496
ca0b8376db400f265d9515d8307d928590a1569a
[ "BSD-2-Clause" ]
2
2019-10-29T12:41:16.000Z
2021-03-22T16:38:27.000Z
/** * @file rrts02-nearestNeighbors.cpp * @author Can Erdogan * @date Feb 04, 2013 * @brief Checks if the nearest neighbor computation done by flann is correct. */ #include <iostream> #include <gtest/gtest.h> #include <Eigen/Core> #include <dart/dart.hpp> #if HAVE_FLANN #include <flann/flann.hpp> #endif // HAVE_FLANN #include "TestHelpers.hpp" /* ********************************************************************************************* */ #if HAVE_FLANN TEST(NEAREST_NEIGHBOR, 2D) { // Build the index with the first node flann::Index<flann::L2<double> > index (flann::KDTreeSingleIndexParams(10, true)); Eigen::VectorXd p1 (2); p1 << -3.04159, -3.04159; index.buildIndex(flann::Matrix<double>((double*)p1.data(), 1, p1.size())); // Add two more points Eigen::Vector2d p2 (-2.96751, -2.97443), p3 (-2.91946, -2.88672); index.addPoints(flann::Matrix<double>((double*)p2.data(), 1, p2.size())); index.addPoints(flann::Matrix<double>((double*)p3.data(), 1, p3.size())); // Check the size of the tree EXPECT_EQ(3, (int)index.size()); // Get the nearest neighbor index for a sample point Eigen::Vector2d sample (-2.26654, 2.2874); int nearest; double distance; const flann::Matrix<double> queryMatrix((double*)sample.data(), 1, sample.size()); flann::Matrix<int> nearestMatrix(&nearest, 1, 1); flann::Matrix<double> distanceMatrix(flann::Matrix<double>(&distance, 1, 1)); index.knnSearch(queryMatrix, nearestMatrix, distanceMatrix, 1, flann::SearchParams(flann::FLANN_CHECKS_UNLIMITED)); EXPECT_EQ(2, nearest); // Get the nearest neighbor double* point = index.getPoint(nearest); bool equality = equals(Vector2d(point[0], point[1]), p3, 1e-3); EXPECT_TRUE(equality); } #endif // HAVE_FLANN /* ********************************************************************************************* */ int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
34.793103
99
0.606046
purewind7
ce323ad3d9b49b086493ead14eb5658ef13a655a
1,572
hpp
C++
include/MemeCore/Function.hpp
Gurman8r/CppSandbox
a0f1cf0ade69ecaba4d167c0611a620914155e53
[ "MIT" ]
null
null
null
include/MemeCore/Function.hpp
Gurman8r/CppSandbox
a0f1cf0ade69ecaba4d167c0611a620914155e53
[ "MIT" ]
null
null
null
include/MemeCore/Function.hpp
Gurman8r/CppSandbox
a0f1cf0ade69ecaba4d167c0611a620914155e53
[ "MIT" ]
null
null
null
#ifndef _ML_FUNCTION_HPP_ #define _ML_FUNCTION_HPP_ #include <MemeCore/ITrackable.hpp> namespace ml { /* * * * * * * * * * * * * * * * * * * * */ class ML_CORE_API Function : public ITrackable { public: virtual ~Function() {} virtual void run() = 0; inline void operator()() { return run(); } }; /* * * * * * * * * * * * * * * * * * * * */ template <typename F> class VoidFun final : public Function { F m_fun; public: VoidFun(F fun) : m_fun(fun) { } inline void run() override { return m_fun(); } }; /* * * * * * * * * * * * * * * * * * * * */ template <typename F, typename A> class ArgFun final : public Function { F m_fun; A m_arg; public: ArgFun(F fun, A arg) : m_fun(fun) , m_arg(arg) { } inline void run() override { return m_fun(m_arg); } }; /* * * * * * * * * * * * * * * * * * * * */ template <typename T, typename F = void(T::*)()> class MemberFun final : public Function { F m_fun; T * m_obj; public: MemberFun(F fun, T * obj) : m_fun(fun) , m_obj(obj) { } inline void run() override { return (m_obj->*m_fun)(); } }; /* * * * * * * * * * * * * * * * * * * * */ template <typename T, typename A, typename F = void(T::*)(A)> class MemberArgFun final : public Function { F m_fun; T * m_obj; A m_arg; public: MemberArgFun(F fun, T * obj, A arg) : m_fun(fun) , m_obj(obj) , m_arg(arg) { } inline void run() override { return (m_obj->*m_fun)(m_arg); } }; /* * * * * * * * * * * * * * * * * * * * */ } #endif // !_ML_FUNCTION_HPP_
16.375
63
0.512087
Gurman8r