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
# -*- coding: utf-8 -*- require "em-websocket" require "eventmachine-tail" module Tailer # Extends FileTail to push data tailed to an EM::Channel. All open websockets # subscribe to a channel for the request stack and this pushes the data to # all of them at once. class StackTail < EventMachine::FileTail def initialize(filename, channel, startpos=-1) super(filename, startpos) @channel = channel @buffer = BufferedTokenizer.new end # This method is called whenever FileTail receives an inotify event for # the tailed file. It breaks up the data per line and pushes a line at a # time. This is to prevent the last javascript line from being broken up # over 2 pushes thus breaking the eval on the front end. def receive_data(data) # replace non UTF-8 characters with ? data.encode!('UTF-8', invalid: :replace, undef: :replace, replace: '�') @buffer.extract(data).each do |line| @channel.push line end end end # Checks if stack log symlink exists and creates Tailer for it def self.stack_tail(stack, channel, channel_count) if Deployinator.get_visible_stacks.include?(stack) filename = "#{Deployinator::Helpers::RUN_LOG_PATH}current-#{stack}" start_pos = (channel_count == 0) ? 0 : -1 File.exists?(filename) ? StackTail.new(filename, channel, start_pos) : false end end end
etsy/deployinator
lib/deployinator/stack-tail.rb
Ruby
mit
1,403
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace DotNetty.Transport.Channels.Sockets { using System; using System.Diagnostics.Contracts; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; public class DefaultDatagramChannelConfig : DefaultChannelConfiguration, IDatagramChannelConfig { const int DefaultFixedBufferSize = 2048; readonly Socket socket; public DefaultDatagramChannelConfig(IDatagramChannel channel, Socket socket) : base(channel, new FixedRecvByteBufAllocator(DefaultFixedBufferSize)) { Contract.Requires(socket != null); this.socket = socket; } public override T GetOption<T>(ChannelOption<T> option) { if (ChannelOption.SoBroadcast.Equals(option)) { return (T)(object)this.Broadcast; } if (ChannelOption.SoRcvbuf.Equals(option)) { return (T)(object)this.ReceiveBufferSize; } if (ChannelOption.SoSndbuf.Equals(option)) { return (T)(object)this.SendBufferSize; } if (ChannelOption.SoReuseaddr.Equals(option)) { return (T)(object)this.ReuseAddress; } if (ChannelOption.IpMulticastLoopDisabled.Equals(option)) { return (T)(object)this.LoopbackModeDisabled; } if (ChannelOption.IpMulticastTtl.Equals(option)) { return (T)(object)this.TimeToLive; } if (ChannelOption.IpMulticastAddr.Equals(option)) { return (T)(object)this.Interface; } if (ChannelOption.IpMulticastIf.Equals(option)) { return (T)(object)this.NetworkInterface; } if (ChannelOption.IpTos.Equals(option)) { return (T)(object)this.TrafficClass; } return base.GetOption(option); } public override bool SetOption<T>(ChannelOption<T> option, T value) { if (base.SetOption(option, value)) { return true; } if (ChannelOption.SoBroadcast.Equals(option)) { this.Broadcast = (bool)(object)value; } else if (ChannelOption.SoRcvbuf.Equals(option)) { this.ReceiveBufferSize = (int)(object)value; } else if (ChannelOption.SoSndbuf.Equals(option)) { this.SendBufferSize = (int)(object)value; } else if (ChannelOption.SoReuseaddr.Equals(option)) { this.ReuseAddress = (bool)(object)value; } else if (ChannelOption.IpMulticastLoopDisabled.Equals(option)) { this.LoopbackModeDisabled = (bool)(object)value; } else if (ChannelOption.IpMulticastTtl.Equals(option)) { this.TimeToLive = (short)(object)value; } else if (ChannelOption.IpMulticastAddr.Equals(option)) { this.Interface = (EndPoint)(object)value; } else if (ChannelOption.IpMulticastIf.Equals(option)) { this.NetworkInterface = (NetworkInterface)(object)value; } else if (ChannelOption.IpTos.Equals(option)) { this.TrafficClass = (int)(object)value; } else { return false; } return true; } public int SendBufferSize { get { try { return this.socket.SendBufferSize; } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } set { try { this.socket.SendBufferSize = value; } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } } public int ReceiveBufferSize { get { try { return this.socket.ReceiveBufferSize; } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } set { try { this.socket.ReceiveBufferSize = value; } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } } public int TrafficClass { get { try { return (int)this.socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.TypeOfService); } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } set { try { this.socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.TypeOfService, value); } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } } public bool ReuseAddress { get { try { return (int)this.socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress) != 0; } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } set { try { this.socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, value ? 1 : 0); } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } } public bool Broadcast { get { try { return this.socket.EnableBroadcast; } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } set { try { this.socket.EnableBroadcast = value; } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } } public bool LoopbackModeDisabled { get { try { return !this.socket.MulticastLoopback; } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } set { try { this.socket.MulticastLoopback = !value; } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } } public short TimeToLive { get { try { return (short)this.socket.GetSocketOption( this.AddressFamilyOptionLevel, SocketOptionName.MulticastTimeToLive); } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } set { try { this.socket.SetSocketOption( this.AddressFamilyOptionLevel, SocketOptionName.MulticastTimeToLive, value); } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } } public EndPoint Interface { get { try { return this.socket.LocalEndPoint; } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } set { Contract.Requires(value != null); try { this.socket.Bind(value); } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } } public NetworkInterface NetworkInterface { get { try { NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces(); int value = (int)this.socket.GetSocketOption( this.AddressFamilyOptionLevel, SocketOptionName.MulticastInterface); int index = IPAddress.NetworkToHostOrder(value); if (interfaces.Length > 0 && index >= 0 && index < interfaces.Length) { return interfaces[index]; } return null; } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } set { Contract.Requires(value != null); try { int index = this.GetNetworkInterfaceIndex(value); if (index >= 0) { this.socket.SetSocketOption( this.AddressFamilyOptionLevel, SocketOptionName.MulticastInterface, index); } } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } } internal SocketOptionLevel AddressFamilyOptionLevel { get { if (this.socket.AddressFamily == AddressFamily.InterNetwork) { return SocketOptionLevel.IP; } if (this.socket.AddressFamily == AddressFamily.InterNetworkV6) { return SocketOptionLevel.IPv6; } throw new NotSupportedException($"Socket address family {this.socket.AddressFamily} not supported, expecting InterNetwork or InterNetworkV6"); } } internal int GetNetworkInterfaceIndex(NetworkInterface networkInterface) { Contract.Requires(networkInterface != null); NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces(); for (int index = 0; index < interfaces.Length; index++) { if (interfaces[index].Id == networkInterface.Id) { return index; } } return -1; } } }
dragonphoenix/proto-java-csharp
DotNetty/DotNetty.Transport/Channels/Sockets/DefaultDatagramChannelConfig.cs
C#
mit
14,695
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') class Video include Claire::Client::Item end describe Claire::Client::Item do #@session.should_receive(:post).with("url", "data", "headers") #@session = mock("session") before do Claire::Client.stub(:get).with('videos/id').and_return xml :item @video = Video.new(hash_from_xml(:item)) end describe "its initializer" do describe "its base_url class attribute" do it "should default to the class name, pluralized" do Video.base_url.should == "videos" end it "should accept manual overwrite on the class" do Video.base_url = "lists" Video.base_url.should == "lists" Video.base_url = nil Video.base_url.should == "videos" end it "if the class is in a module, it should get the class name only" do eval %( module Testing class Video include Claire::Client::Item end end ) Testing::Video.base_url.should == "videos" end end context "upon receiving a Hash" do before :each do @video = Video.new(hash_from_xml(:item)) end it "should set partial do true" do @video.should be_partial end it "should skip the <rss> container if it is present" do @video.title.should be_a_kind_of String @video.should_not respond_to :rss end it "should skip the <channel> container if its present" do video = Video.new(hash_from_xml(:item_with_channel)) video.title.should be_a_kind_of String video.should_not respond_to :channel end it "should never set 'items' attributes " do %w(item item_with_channel).each do |type| video = Video.new(hash_from_xml(type)) video.should_not respond_to :item video.title.should be_a_kind_of String end end it "should set the link attribute properly (eg ignoring links to other objects/pages)" do video = Video.new hash_from_xml :item_with_channel video.link.should be_a_kind_of String end it "should set its key/values as properties of the element" do %w(title link category keywords description).each do |item| @video.send(item).should be_a_kind_of String end %w(thumbnail content).each{ |item| @video.send(item).should be_a_kind_of Array } end it "should fail if there is not a link attribute" do lambda { Video.new( {:rss => {:item => {:name => 'bla'}}} ) }.should raise_error Claire::Error end end context "upon receiving a String" do before { @video = Video.new 'id' } it "should open the given string" do lambda { Video.new "" }.should raise_error lambda { Video.new "id" }.should_not raise_error end it "should parse the result using the XML parsing rules" do @video.title.should be_a_kind_of String end it "should set partial to false" do @video.should_not be_partial end end end describe "its comparison (spaceship) operator" do it "should be defined" do @video.should respond_to '<=>' end it "should compare items by title" do @video2 = @video.clone (@video <=> @video2).should be 0 end end context "when an undefined method is called" do it "it should raise error if partial is false" context "if the item is partial" do it "should request the full object from server, and replace itself" it "should return the asked attribute" end end it "should have a list of its children as the children class attribute" do Claire::Client::Item.children.include?(Video).should be true end end
memuller/claire.client
spec/claire_client/item_spec.rb
Ruby
mit
3,595
<?php namespace Zanson\SMParser\Traits\Song; use Zanson\SMParser\SMException; trait Banner { public $banner = ''; /** * @return string */ public function getBanner() { return $this->banner; } /** * @param string $banner * * @return $this * @throws SMException */ public function setBanner($banner) { if (!is_string($banner)) { throw new SMException("Banner must be a string"); } $this->banner = $banner; return $this; } }
jasonwatt/SMParser
src/Traits/Song/Banner.php
PHP
mit
541
if ( !window.console ) window.console = { log:function(){} }; jQuery(document).ready(function($) { console.log('Keep being awesome.'); });
shampine/180
public/js/src/script.js
JavaScript
mit
143
package parser import ( "monkey/ast" "monkey/token" ) func (p *Parser) parseStringLiteralExpression() ast.Expression { return &ast.StringLiteral{Token: p.curToken, Value: p.curToken.Literal} } func (p *Parser) parseInterpolatedString() ast.Expression { is := &ast.InterpolatedString{Token: p.curToken, Value: p.curToken.Literal, ExprMap: make(map[byte]ast.Expression)} key := "0"[0] for { if p.curTokenIs(token.LBRACE) { p.nextToken() expr := p.parseExpression(LOWEST) is.ExprMap[key] = expr key++ } p.nextInterpToken() if p.curTokenIs(token.ISTRING) { break } } return is }
mayoms/monkey
parser/strings.go
GO
mit
612
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Timers; using System.Diagnostics; namespace ForumHelper { public partial class ToastForm : Form { public ToastForm() { InitializeComponent(); TopMost = true; ShowInTaskbar = false; timer = new System.Windows.Forms.Timer(); timer.Interval = 500; timer.Tick += timer_Tick; } private System.Windows.Forms.Timer timer; private int startPosX; private int startPosY; private void ToastForm_Load(object sender, EventArgs e) { } protected override void OnLoad(EventArgs e) { startPosX = Screen.PrimaryScreen.WorkingArea.Width - Width; startPosY = Screen.PrimaryScreen.WorkingArea.Height - Height; SetDesktopLocation(startPosX, startPosY); pageLinkLabel.Text = URLEventArgs.Url; // base.OnLoad(e); timer.Start(); } void timer_Tick(object sender, EventArgs e) { startPosY -= 50; if (startPosY < Screen.PrimaryScreen.WorkingArea.Height - Height) timer.Stop(); else { SetDesktopLocation(startPosX, startPosY); timer.Stop(); } } private void ToastForm_Click(object sender, EventArgs e) { this.Close(); } private void pageLinkLabelClick(object sender, EventArgs e) { Process.Start(this.pageLinkLabel.Text); this.Close(); } } }
ttitto/PersonalProjects
ForumHelper/ForumHelper/ToastForm.cs
C#
mit
1,852
<?php /* * The MIT License (MIT) * * Copyright (c) 2014-2018 Spomky-Labs * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ use Base64Url\Base64Url; use Jose\Decrypter; use Jose\Encrypter; use Jose\Factory\JWEFactory; use Jose\Loader; use Jose\Object\JWEInterface; use Jose\Object\JWK; use Jose\Object\JWKSet; use Jose\Test\Stub\FakeLogger; use Jose\Test\BaseTestCase; /** * Class EncrypterTest. * * @group Encrypter * @group Functional */ class EncrypterBaseTest extends BaseTestCase { public function testEncryptWithJWTInput() { $encrypter = Encrypter::createEncrypter(['RSA-OAEP-256'], ['A256CBC-HS512'], ['DEF'], new FakeLogger()); $decrypter = Decrypter::createDecrypter(['RSA-OAEP-256'], ['A256CBC-HS512'], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE( 'FOO', [ 'enc' => 'A256CBC-HS512', 'alg' => 'RSA-OAEP-256', 'zip' => 'DEF', ], [], 'foo,bar,baz' ); $jwe = $jwe->addRecipientInformation($this->getRSARecipientKey()); $encrypter->encrypt($jwe); $encrypted = $jwe->toFlattenedJSON(0); $loader = new Loader(new FakeLogger()); $loaded = $loader->load($encrypted); self::assertInstanceOf(JWEInterface::class, $loaded); self::assertEquals('RSA-OAEP-256', $loaded->getSharedProtectedHeader('alg')); self::assertEquals('A256CBC-HS512', $loaded->getSharedProtectedHeader('enc')); self::assertEquals('DEF', $loaded->getSharedProtectedHeader('zip')); self::assertNull($loaded->getPayload()); $decrypter->decryptUsingKeySet($loaded, $this->getPrivateKeySet(), $index); self::assertEquals(0, $index); self::assertEquals('FOO', $loaded->getPayload()); } public function testCreateCompactJWEUsingFactory() { $jwe = JWEFactory::createJWEToCompactJSON( 'FOO', $this->getRSARecipientKey(), [ 'enc' => 'A256CBC-HS512', 'alg' => 'RSA-OAEP-256', 'zip' => 'DEF', ] ); $loader = new Loader(new FakeLogger()); $loaded = $loader->load($jwe); self::assertInstanceOf(JWEInterface::class, $loaded); self::assertEquals('RSA-OAEP-256', $loaded->getSharedProtectedHeader('alg')); self::assertEquals('A256CBC-HS512', $loaded->getSharedProtectedHeader('enc')); self::assertEquals('DEF', $loaded->getSharedProtectedHeader('zip')); self::assertNull($loaded->getPayload()); $decrypter = Decrypter::createDecrypter(['RSA-OAEP-256'], ['A256CBC-HS512'], ['DEF'], new FakeLogger()); $decrypter->decryptUsingKeySet($loaded, $this->getPrivateKeySet(), $index); self::assertEquals(0, $index); self::assertEquals('FOO', $loaded->getPayload()); } public function testCreateFlattenedJWEUsingFactory() { $jwe = JWEFactory::createJWEToFlattenedJSON( 'FOO', $this->getRSARecipientKey(), [ 'enc' => 'A256CBC-HS512', 'alg' => 'RSA-OAEP-256', 'zip' => 'DEF', ], [ 'foo' => 'bar', ], [ 'plic' => 'ploc', ], 'A,B,C,D' ); $loader = new Loader(new FakeLogger()); $loaded = $loader->load($jwe); self::assertInstanceOf(JWEInterface::class, $loaded); self::assertEquals('RSA-OAEP-256', $loaded->getSharedProtectedHeader('alg')); self::assertEquals('A256CBC-HS512', $loaded->getSharedProtectedHeader('enc')); self::assertEquals('DEF', $loaded->getSharedProtectedHeader('zip')); self::assertEquals('bar', $loaded->getSharedHeader('foo')); self::assertEquals('A,B,C,D', $loaded->getAAD('foo')); self::assertEquals('ploc', $loaded->getRecipient(0)->getHeader('plic')); self::assertNull($loaded->getPayload()); $decrypter = Decrypter::createDecrypter(['RSA-OAEP-256'], ['A256CBC-HS512'], ['DEF'], new FakeLogger()); $decrypter->decryptUsingKeySet($loaded, $this->getPrivateKeySet(), $index); self::assertEquals(0, $index); self::assertEquals('FOO', $loaded->getPayload()); } public function testEncryptAndLoadFlattenedWithAAD() { $encrypter = Encrypter::createEncrypter(['RSA-OAEP-256'], ['A256CBC-HS512'], ['DEF'], new FakeLogger()); $decrypter = Decrypter::createDecrypter(['RSA-OAEP-256'], ['A256CBC-HS512'], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE( $this->getKeyToEncrypt(), [ 'enc' => 'A256CBC-HS512', 'alg' => 'RSA-OAEP-256', 'zip' => 'DEF', ], [], 'foo,bar,baz' ); $jwe = $jwe->addRecipientInformation($this->getRSARecipientKey()); $encrypter->encrypt($jwe); $encrypted = $jwe->toFlattenedJSON(0); $loader = new Loader(new FakeLogger()); $loaded = $loader->load($encrypted); self::assertInstanceOf(JWEInterface::class, $loaded); self::assertEquals('RSA-OAEP-256', $loaded->getSharedProtectedHeader('alg')); self::assertEquals('A256CBC-HS512', $loaded->getSharedProtectedHeader('enc')); self::assertEquals('DEF', $loaded->getSharedProtectedHeader('zip')); self::assertNull($loaded->getPayload()); $decrypter->decryptUsingKeySet($loaded, $this->getPrivateKeySet(), $index); self::assertEquals(0, $index); self::assertTrue(is_array($loaded->getPayload())); self::assertEquals($this->getKeyToEncrypt(), new JWK($loaded->getPayload())); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage Compression method "FIP" not supported */ public function testCompressionAlgorithmNotSupported() { $encrypter = Encrypter::createEncrypter(['RSA-OAEP-256'], ['A256CBC-HS512'], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE( $this->getKeyToEncrypt(), [ 'enc' => 'A256CBC-HS512', 'alg' => 'RSA-OAEP-256', 'zip' => 'FIP', ], [], 'foo,bar,baz' ); $jwe = $jwe->addRecipientInformation($this->getRSARecipientKey()); $encrypter->encrypt($jwe); } public function testMultipleInstructionsNotAllowedWithCompactSerialization() { $encrypter = Encrypter::createEncrypter(['RSA-OAEP', 'RSA-OAEP-256'], ['A256CBC-HS512'], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE('Live long and Prosper.'); $jwe = $jwe->withSharedProtectedHeaders([ 'enc' => 'A256CBC-HS512', ]); $jwe = $jwe->addRecipientInformation($this->getRSARecipientKeyWithAlgorithm(), ['alg' => 'RSA-OAEP']); $jwe = $jwe->addRecipientInformation($this->getRSARecipientKey(), ['alg' => 'RSA-OAEP-256']); $encrypter->encrypt($jwe); self::assertEquals(2, $jwe->countRecipients()); } public function testMultipleInstructionsNotAllowedWithFlattenedSerialization() { $encrypter = Encrypter::createEncrypter(['RSA-OAEP-256', 'ECDH-ES+A256KW'], ['A256CBC-HS512'], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE('Live long and Prosper.'); $jwe = $jwe->withSharedProtectedHeaders([ 'enc' => 'A256CBC-HS512', ]); $jwe = $jwe->addRecipientInformation( $this->getECDHRecipientPublicKey(), ['kid' => 'e9bc097a-ce51-4036-9562-d2ade882db0d', 'alg' => 'ECDH-ES+A256KW'] ); $jwe = $jwe->addRecipientInformation( $this->getRSARecipientKey(), ['kid' => '123456789', 'alg' => 'RSA-OAEP-256'] ); $encrypter->encrypt($jwe); self::assertEquals(2, $jwe->countRecipients()); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage Foreign key management mode forbidden. */ public function testForeignKeyManagementModeForbidden() { $encrypter = Encrypter::createEncrypter(['dir', 'ECDH-ES+A256KW'], ['A256CBC-HS512'], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE('Live long and Prosper.'); $jwe = $jwe->withSharedProtectedHeaders([ 'enc' => 'A256CBC-HS512', ]); $jwe = $jwe->addRecipientInformation( $this->getECDHRecipientPublicKey(), ['kid' => 'e9bc097a-ce51-4036-9562-d2ade882db0d', 'alg' => 'ECDH-ES+A256KW'] ); $jwe = $jwe->addRecipientInformation( $this->getDirectKey(), ['kid' => 'DIR_1', 'alg' => 'dir'] ); $encrypter->encrypt($jwe); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage Key cannot be used to encrypt */ public function testOperationNotAllowedForTheKey() { $encrypter = Encrypter::createEncrypter(['RSA-OAEP-256'], ['A256CBC-HS512'], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE( 'Foo', [ 'enc' => 'A256CBC-HS512', 'alg' => 'RSA-OAEP-256', 'zip' => 'DEF', ], [], 'foo,bar,baz' ); $jwe = $jwe->addRecipientInformation( $this->getSigningKey() ); $encrypter->encrypt($jwe); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage Key is only allowed for algorithm "RSA-OAEP". */ public function testAlgorithmNotAllowedForTheKey() { $encrypter = Encrypter::createEncrypter(['RSA-OAEP-256'], ['A256CBC-HS512'], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE( 'FOO', [ 'enc' => 'A256CBC-HS512', 'alg' => 'RSA-OAEP-256', 'zip' => 'DEF', ], [], 'foo,bar,baz' ); $jwe = $jwe->addRecipientInformation( $this->getRSARecipientKeyWithAlgorithm() ); $encrypter->encrypt($jwe); } public function testEncryptAndLoadFlattenedWithDeflateCompression() { $encrypter = Encrypter::createEncrypter(['RSA-OAEP-256'], ['A128CBC-HS256'], ['DEF'], new FakeLogger()); $decrypter = Decrypter::createDecrypter(['RSA-OAEP-256'], ['A128CBC-HS256'], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE($this->getKeySetToEncrypt()); $jwe = $jwe->withSharedProtectedHeaders([ 'kid' => '123456789', 'enc' => 'A128CBC-HS256', 'alg' => 'RSA-OAEP-256', 'zip' => 'DEF', ]); $jwe = $jwe->addRecipientInformation( $this->getRSARecipientKey() ); $encrypter->encrypt($jwe); $encrypted = $jwe->toCompactJSON(0); $loader = new Loader(new FakeLogger()); $loaded = $loader->load($encrypted); self::assertInstanceOf(JWEInterface::class, $loaded); self::assertEquals('RSA-OAEP-256', $loaded->getSharedProtectedHeader('alg')); self::assertEquals('A128CBC-HS256', $loaded->getSharedProtectedHeader('enc')); self::assertEquals('DEF', $loaded->getSharedProtectedHeader('zip')); self::assertNull($loaded->getPayload()); $decrypter->decryptUsingKeySet($loaded, $this->getPrivateKeySet(), $index); self::assertEquals(0, $index); self::assertTrue(is_array($loaded->getPayload())); self::assertEquals($this->getKeySetToEncrypt(), new JWKSet($loaded->getPayload())); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage Parameter "alg" is missing. */ public function testAlgParameterIsMissing() { $encrypter = Encrypter::createEncrypter(['A256CBC-HS512'], [], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE($this->getKeyToEncrypt()); $jwe = $jwe->withSharedProtectedHeaders([ 'kid' => '123456789', 'enc' => 'A256CBC-HS512', 'zip' => 'DEF', ]); $jwe = $jwe->addRecipientInformation( $this->getRSARecipientKey() ); $encrypter->encrypt($jwe); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage Parameter "enc" is missing. */ public function testEncParameterIsMissing() { $encrypter = Encrypter::createEncrypter(['RSA-OAEP-256'], [], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE($this->getKeyToEncrypt()); $jwe = $jwe->withSharedProtectedHeaders([ 'kid' => '123456789', 'alg' => 'RSA-OAEP-256', 'zip' => 'DEF', ]); $jwe = $jwe->addRecipientInformation( $this->getRSARecipientKey() ); $encrypter->encrypt($jwe); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage The key encryption algorithm "A256CBC-HS512" is not supported or not a key encryption algorithm instance. */ public function testNotAKeyEncryptionAlgorithm() { $encrypter = Encrypter::createEncrypter(['A256CBC-HS512'], [], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE($this->getKeyToEncrypt()); $jwe = $jwe->withSharedProtectedHeaders([ 'kid' => '123456789', 'enc' => 'A256CBC-HS512', 'alg' => 'A256CBC-HS512', 'zip' => 'DEF', ]); $jwe = $jwe->addRecipientInformation( $this->getRSARecipientKey() ); $encrypter->encrypt($jwe); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage The content encryption algorithm "RSA-OAEP-256" is not supported or not a content encryption algorithm instance. */ public function testNotAContentEncryptionAlgorithm() { $encrypter = Encrypter::createEncrypter(['RSA-OAEP-256'], [], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE($this->getKeyToEncrypt()); $jwe = $jwe->withSharedProtectedHeaders([ 'kid' => '123456789', 'enc' => 'RSA-OAEP-256', 'alg' => 'RSA-OAEP-256', 'zip' => 'DEF', ]); $jwe = $jwe->addRecipientInformation( $this->getRSARecipientKey() ); $encrypter->encrypt($jwe); } public function testEncryptAndLoadCompactWithDirectKeyEncryption() { $encrypter = Encrypter::createEncrypter(['dir'], ['A192CBC-HS384'], ['DEF'], new FakeLogger()); $decrypter = Decrypter::createDecrypter(['dir'], ['A192CBC-HS384'], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE($this->getKeyToEncrypt()); $jwe = $jwe->withSharedProtectedHeaders([ 'kid' => 'DIR_1', 'enc' => 'A192CBC-HS384', 'alg' => 'dir', ]); $jwe = $jwe->addRecipientInformation( $this->getDirectKey() ); $encrypter->encrypt($jwe); $encrypted = $jwe->toFlattenedJSON(0); $loader = new Loader(new FakeLogger()); $loaded = $loader->load($encrypted); self::assertInstanceOf(JWEInterface::class, $loaded); self::assertEquals('dir', $loaded->getSharedProtectedHeader('alg')); self::assertEquals('A192CBC-HS384', $loaded->getSharedProtectedHeader('enc')); self::assertFalse($loaded->hasSharedHeader('zip')); self::assertNull($loaded->getPayload()); $decrypter->decryptUsingKeySet($loaded, $this->getSymmetricKeySet(), $index); self::assertEquals(0, $index); self::assertTrue(is_array($loaded->getPayload())); self::assertEquals($this->getKeyToEncrypt(), new JWK($loaded->getPayload())); } public function testEncryptAndLoadCompactKeyAgreement() { $encrypter = Encrypter::createEncrypter(['ECDH-ES'], ['A192CBC-HS384'], ['DEF'], new FakeLogger()); $decrypter = Decrypter::createDecrypter(['ECDH-ES'], ['A192CBC-HS384'], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE(['user_id' => '1234', 'exp' => time() + 3600]); $jwe = $jwe->withSharedProtectedHeaders([ 'kid' => 'e9bc097a-ce51-4036-9562-d2ade882db0d', 'enc' => 'A192CBC-HS384', 'alg' => 'ECDH-ES', ]); $jwe = $jwe->addRecipientInformation( $this->getECDHRecipientPublicKey() ); $encrypter->encrypt($jwe); $loader = new Loader(new FakeLogger()); $loaded = $loader->load($jwe->toFlattenedJSON(0)); self::assertInstanceOf(JWEInterface::class, $loaded); self::assertEquals('ECDH-ES', $loaded->getSharedProtectedHeader('alg')); self::assertEquals('A192CBC-HS384', $loaded->getSharedProtectedHeader('enc')); self::assertFalse($loaded->hasSharedProtectedHeader('zip')); self::assertNull($loaded->getPayload()); $decrypter->decryptUsingKeySet($loaded, $this->getPrivateKeySet(), $index); self::assertEquals(0, $index); self::assertTrue($loaded->hasClaims()); self::assertTrue($loaded->hasClaim('user_id')); self::assertEquals('1234', $loaded->getClaim('user_id')); } public function testEncryptAndLoadCompactKeyAgreementWithWrappingCompact() { $encrypter = Encrypter::createEncrypter(['ECDH-ES+A256KW'], ['A256CBC-HS512'], ['DEF'], new FakeLogger()); $decrypter = Decrypter::createDecrypter(['ECDH-ES+A256KW'], ['A256CBC-HS512'], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE('Live long and Prosper.'); $jwe = $jwe->withSharedProtectedHeaders([ 'kid' => 'e9bc097a-ce51-4036-9562-d2ade882db0d', 'enc' => 'A256CBC-HS512', 'alg' => 'ECDH-ES+A256KW', ]); $jwe = $jwe->addRecipientInformation( $this->getECDHRecipientPublicKey() ); $encrypter->encrypt($jwe); $loader = new Loader(new FakeLogger()); $loaded = $loader->load($jwe->toFlattenedJSON(0)); self::assertInstanceOf(JWEInterface::class, $loaded); self::assertEquals('ECDH-ES+A256KW', $loaded->getSharedProtectedHeader('alg')); self::assertEquals('A256CBC-HS512', $loaded->getSharedProtectedHeader('enc')); self::assertFalse($loaded->hasSharedProtectedHeader('zip')); self::assertFalse($loaded->hasSharedHeader('zip')); self::assertNull($loaded->getPayload()); $decrypter->decryptUsingKeySet($loaded, $this->getPrivateKeySet(), $index); self::assertEquals(0, $index); self::assertTrue(is_string($loaded->getPayload())); self::assertEquals('Live long and Prosper.', $loaded->getPayload()); } public function testEncryptAndLoadWithGCMAndAAD() { $encrypter = Encrypter::createEncrypter(['ECDH-ES+A256KW'], ['A256GCM'], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE( 'Live long and Prosper.', [ 'kid' => 'e9bc097a-ce51-4036-9562-d2ade882db0d', 'enc' => 'A256GCM', 'alg' => 'ECDH-ES+A256KW', ], [], 'foo,bar,baz' ); $jwe = $jwe->addRecipientInformation( $this->getECDHRecipientPublicKey() ); $encrypter->encrypt($jwe); $loader = new Loader(new FakeLogger()); $loaded = $loader->load($jwe->toFlattenedJSON(0)); $decrypter = Decrypter::createDecrypter(['A256GCM'], ['ECDH-ES+A256KW'], ['DEF'], new FakeLogger()); self::assertInstanceOf(JWEInterface::class, $loaded); self::assertEquals('ECDH-ES+A256KW', $loaded->getSharedProtectedHeader('alg')); self::assertEquals('A256GCM', $loaded->getSharedProtectedHeader('enc')); self::assertFalse($loaded->hasSharedProtectedHeader('zip')); self::assertFalse($loaded->hasSharedHeader('zip')); self::assertNull($loaded->getPayload()); $decrypter->decryptUsingKeySet($loaded, $this->getPrivateKeySet(), $index); self::assertEquals(0, $index); self::assertTrue(is_string($loaded->getPayload())); self::assertEquals('Live long and Prosper.', $loaded->getPayload()); } public function testEncryptAndLoadCompactKeyAgreementWithWrapping() { $encrypter = Encrypter::createEncrypter(['RSA-OAEP-256', 'ECDH-ES+A256KW'], ['A256CBC-HS512'], ['DEF'], new FakeLogger()); $decrypter = Decrypter::createDecrypter(['RSA-OAEP-256', 'ECDH-ES+A256KW'], ['A256CBC-HS512'], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE('Live long and Prosper.'); $jwe = $jwe->withSharedProtectedHeaders(['enc' => 'A256CBC-HS512']); $jwe = $jwe->addRecipientInformation( $this->getECDHRecipientPublicKey(), ['kid' => 'e9bc097a-ce51-4036-9562-d2ade882db0d', 'alg' => 'ECDH-ES+A256KW'] ); $jwe = $jwe->addRecipientInformation( $this->getRSARecipientKey(), ['kid' => '123456789', 'alg' => 'RSA-OAEP-256'] ); $encrypter->encrypt($jwe); $loader = new Loader(new FakeLogger()); $loaded = $loader->load($jwe->toJSON()); self::assertEquals(2, $loaded->countRecipients()); self::assertInstanceOf(JWEInterface::class, $loaded); self::assertEquals('A256CBC-HS512', $loaded->getSharedProtectedHeader('enc')); self::assertEquals('ECDH-ES+A256KW', $loaded->getRecipient(0)->getHeader('alg')); self::assertEquals('RSA-OAEP-256', $loaded->getRecipient(1)->getHeader('alg')); self::assertFalse($loaded->hasSharedHeader('zip')); self::assertFalse($loaded->hasSharedProtectedHeader('zip')); self::assertNull($loaded->getPayload()); $decrypter->decryptUsingKeySet($loaded, $this->getPrivateKeySet(), $index); self::assertEquals(0, $index); self::assertTrue(is_string($loaded->getPayload())); self::assertEquals('Live long and Prosper.', $loaded->getPayload()); } /** * @return JWK */ private function getKeyToEncrypt() { $key = new JWK([ 'kty' => 'EC', 'use' => 'enc', 'crv' => 'P-256', 'x' => 'f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU', 'y' => 'x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0', 'd' => 'jpsQnnGQmL-YBIffH1136cspYG6-0iY7X1fCE9-E9LI', ]); return $key; } /** * @return JWKSet */ private function getKeySetToEncrypt() { $key = new JWK([ 'kty' => 'EC', 'use' => 'enc', 'crv' => 'P-256', 'x' => 'f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU', 'y' => 'x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0', 'd' => 'jpsQnnGQmL-YBIffH1136cspYG6-0iY7X1fCE9-E9LI', ]); $key_set = new JWKSet(); $key_set->addKey($key); return $key_set; } /** * @return JWK */ private function getRSARecipientKey() { $key = new JWK([ 'kty' => 'RSA', 'use' => 'enc', 'n' => 'tpS1ZmfVKVP5KofIhMBP0tSWc4qlh6fm2lrZSkuKxUjEaWjzZSzs72gEIGxraWusMdoRuV54xsWRyf5KeZT0S-I5Prle3Idi3gICiO4NwvMk6JwSBcJWwmSLFEKyUSnB2CtfiGc0_5rQCpcEt_Dn5iM-BNn7fqpoLIbks8rXKUIj8-qMVqkTXsEKeKinE23t1ykMldsNaaOH-hvGti5Jt2DMnH1JjoXdDXfxvSP_0gjUYb0ektudYFXoA6wekmQyJeImvgx4Myz1I4iHtkY_Cp7J4Mn1ejZ6HNmyvoTE_4OuY1uCeYv4UyXFc1s1uUyYtj4z57qsHGsS4dQ3A2MJsw', 'e' => 'AQAB', ]); return $key; } /** * @return JWK */ private function getRSARecipientKeyWithAlgorithm() { $key = new JWK([ 'kty' => 'RSA', 'use' => 'enc', 'alg' => 'RSA-OAEP', 'n' => 'tpS1ZmfVKVP5KofIhMBP0tSWc4qlh6fm2lrZSkuKxUjEaWjzZSzs72gEIGxraWusMdoRuV54xsWRyf5KeZT0S-I5Prle3Idi3gICiO4NwvMk6JwSBcJWwmSLFEKyUSnB2CtfiGc0_5rQCpcEt_Dn5iM-BNn7fqpoLIbks8rXKUIj8-qMVqkTXsEKeKinE23t1ykMldsNaaOH-hvGti5Jt2DMnH1JjoXdDXfxvSP_0gjUYb0ektudYFXoA6wekmQyJeImvgx4Myz1I4iHtkY_Cp7J4Mn1ejZ6HNmyvoTE_4OuY1uCeYv4UyXFc1s1uUyYtj4z57qsHGsS4dQ3A2MJsw', 'e' => 'AQAB', ]); return $key; } /** * @return JWK */ private function getSigningKey() { $key = new JWK([ 'kty' => 'EC', 'key_ops' => ['sign', 'verify'], 'crv' => 'P-256', 'x' => 'f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU', 'y' => 'x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0', 'd' => 'jpsQnnGQmL-YBIffH1136cspYG6-0iY7X1fCE9-E9LI', ]); return $key; } /** * @return JWK */ private function getECDHRecipientPublicKey() { $key = new JWK([ 'kty' => 'EC', 'key_ops' => ['encrypt', 'decrypt'], 'crv' => 'P-256', 'x' => 'f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU', 'y' => 'x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0', ]); return $key; } /** * @return JWK */ private function getDirectKey() { $key = new JWK([ 'kid' => 'DIR_1', 'key_ops' => ['encrypt', 'decrypt'], 'kty' => 'oct', 'k' => Base64Url::encode(hex2bin('00112233445566778899AABBCCDDEEFF000102030405060708090A0B0C0D0E0F')), ]); return $key; } }
Spomky-Labs/jose
tests/Functional/EncrypterBaseTest.php
PHP
mit
25,820
// Fill out your copyright notice in the Description page of Project Settings. using UnrealBuildTool; using System.Collections.Generic; public class UnrealCamDemoTarget : TargetRules { public UnrealCamDemoTarget(TargetInfo Target) : base(Target) { Type = TargetType.Game; ExtraModuleNames.AddRange( new string[] { "UnrealCamDemo" } ); } }
mrayy/UnityCam
UnrealCamDemo/Source/UnrealCamDemo.Target.cs
C#
mit
349
package br.com.gamemods.tutorial.ctf; import org.bukkit.plugin.java.JavaPlugin; public class CTFGameMods extends JavaPlugin { }
joserobjr/CTFGameMods
src/main/java/br/com/gamemods/tutorial/ctf/CTFGameMods.java
Java
mit
131
'use strict'; var emojiArr = require('./emojis'); var i = 0; var existingRules = {}; var generateEmoji = function(selector) { if (!existingRules[selector]) { existingRules[selector] = emojiArr[i]; if (i !== emojiArr.length) { i++ } else { i = 0; } } return existingRules[selector]; } module.exports = generateEmoji;
thuongvu/postcss-emoji
emojify.js
JavaScript
mit
382
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // Template Source: Templates\CSharp\Requests\MethodRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; /// <summary> /// The type WorkbookFunctionsBesselIRequest. /// </summary> public partial class WorkbookFunctionsBesselIRequest : BaseRequest, IWorkbookFunctionsBesselIRequest { /// <summary> /// Constructs a new WorkbookFunctionsBesselIRequest. /// </summary> public WorkbookFunctionsBesselIRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { this.ContentType = "application/json"; this.RequestBody = new WorkbookFunctionsBesselIRequestBody(); } /// <summary> /// Gets the request body. /// </summary> public WorkbookFunctionsBesselIRequestBody RequestBody { get; private set; } /// <summary> /// Issues the POST request. /// </summary> public System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync() { return this.PostAsync(CancellationToken.None); } /// <summary> /// Issues the POST request. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await for async call.</returns> public System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync( CancellationToken cancellationToken) { this.Method = "POST"; return this.SendAsync<WorkbookFunctionResult>(this.RequestBody, cancellationToken); } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IWorkbookFunctionsBesselIRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IWorkbookFunctionsBesselIRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } } }
ginach/msgraph-sdk-dotnet
src/Microsoft.Graph/Requests/Generated/WorkbookFunctionsBesselIRequest.cs
C#
mit
3,043
var fractal = fractal || {}; fractal.workerPaths = { "mandelbrot": "public/js/mandel.js", }; fractal.Fractal = function (canvas, workerCount) { this.canvas = canvas; this.workerCount = workerCount; this.workerDoneCount = 0; this.ctx = canvas.getContext("2d"); this.width = canvas.width; this.height = canvas.height; this.workerPath = fractal.workerPaths["mandelbrot"]; this.topLeft = new Complex(-1.5, 1.1); this.bottomRight = new Complex(0.8, -1.1); this.maxIter = 1200; var lingrad = this.ctx.createLinearGradient(0, 0, this.width, 0); lingrad.addColorStop(0, '#00f'); lingrad.addColorStop(0.1, '#fa0'); lingrad.addColorStop(0.5, '#ff0'); lingrad.addColorStop(0.7, '#f1b'); lingrad.addColorStop(1, '#fff'); this.ctx.fillStyle = lingrad; this.ctx.fillRect(0, 0, this.width, 2); this.gradientImage = this.ctx.getImageData(0, 0, this.width, 1); this.imgData = this.ctx.getImageData(0, 0, this.width, this.height); this.ondone = null; this.workers = []; }; fractal.Fractal.prototype = function () { var computeRow = function (workerIndex, row) { var args = { action: "computeRow", row: row, workerIndex: workerIndex }; this.workers[workerIndex].postMessage(args); }; var initializeWorker = function (workerIndex) { var drow = (this.bottomRight.imag - this.topLeft.imag) / this.height; var dcol = (this.bottomRight.real - this.topLeft.real) / this.width; var args = { action: "setup", maxIter: this.maxIter, width: this.width, height: this.height, topLeft: this.topLeft, bottomRight: this.bottomRight, drow: drow, dcol: dcol, workerIndex: workerIndex, juliaPoint: this.juliaPoint }; this.workers[workerIndex].postMessage(args); }; var createWorkers = function (workerPath) { var obj = this; var rowData = obj.ctx.createImageData(obj.width, 1); for (var workerIndex = 0; workerIndex < obj.workerCount; workerIndex++) { obj.workers[workerIndex] = new Worker(obj.workerPath); this.workers[workerIndex].onmessage = function (event) { if (event.data.logData) { console.log("Worker: " + event.data.logData); } if (event.data.row >= 0) { var wIndex = event.data.workerIndex; for (var index = 0; index < obj.width; index++) { var color = getColor.call(obj, event.data.iterData[index]); var destIndex = 4 * index; rowData.data[destIndex] = color.red; rowData.data[destIndex + 1] = color.green; rowData.data[destIndex + 2] = color.blue; rowData.data[destIndex + 3] = color.alpha; } obj.ctx.putImageData(rowData, 0, event.data.row); if (obj.nextRow < obj.height) { console.log("Worker: " + wIndex, " nextRow: " + obj.nextRow); computeRow.call(obj, wIndex, obj.nextRow); obj.nextRow = obj.nextRow + 1; } else { obj.workerDoneCount++; if (obj.workerDoneCount == obj.workerCount) { var duration = new Date().getTime() - obj.startTime; if (typeof obj.ondone === 'function') { obj.ondone(duration); } } } } }; } }; var getColor = function (iter) { if (iter == this.maxIter) { return { red: 0, green: 0, blue: 0, alpha: 255 }; } var index = (iter % this.gradientImage.width) * 4; return { red: this.gradientImage.data[index], green: this.gradientImage.data[index + 1], blue: this.gradientImage.data[index + 2], alpha: this.gradientImage.data[index + 3] }; }, render = function () { this.startTime = new Date().getTime(); this.workerDoneCount = 0; createWorkers.call(this, this.workerPath); this.nextRow = this.workerCount; for (var workerIndex = 0; workerIndex < this.workerCount; workerIndex++) { initializeWorker.call(this, workerIndex); computeRow.call(this, workerIndex, workerIndex); } } return { render: render }; } (); jQuery(function($) { var fra = new fractal.Fractal(document.getElementById("fractal"), 2); $('#draw-fractal').on('click',function() { fra.render(); }); });
hectoregm/hectoregm
Practica3/public/js/canvas_fractal.js
JavaScript
mit
4,312
describe('raureif', function () { it('test', function () { }); });
chrmod/raureif
tests/node/index-test.js
JavaScript
mit
71
/** * @file ui/core/styleguide/index//html/01-body/40-main/main.js * @description Listeners on the body, iframe, and rightpull bar. */ /* istanbul ignore if */ if (typeof window === 'object') { document.addEventListener('DOMContentLoaded', () => { const $orgs = FEPPER_UI.requerio.$orgs; const { uiFns, uiProps } = FEPPER_UI; $orgs['#sg-rightpull'].on('mouseenter', function () { $orgs['#sg-cover'].dispatchAction('addClass', 'shown-by-rightpull-hover'); }); $orgs['#sg-rightpull'].on('mouseleave', function () { $orgs['#sg-cover'].dispatchAction('removeClass', 'shown-by-rightpull-hover'); }); // Handle manually resizing the viewport. // 1. On "mousedown" store the click location. // 2. Make a hidden div visible so that the cursor doesn't get lost in the iframe. // 3. On "mousemove" calculate the math, save the results to a cookie, and update the viewport. $orgs['#sg-rightpull'].on('mousedown', function (e) { uiProps.sgRightpull.posX = e.pageX; uiProps.sgRightpull.vpWidth = uiProps.vpWidth; // Show the cover. $orgs['#sg-cover'].dispatchAction('addClass', 'shown-by-rightpull-drag'); }); // Add the mouse move event and capture data. Also update the viewport width. $orgs['#patternlab-body'].on('mousemove', function (e) { if ($orgs['#sg-cover'].getState().classArray.includes('shown-by-rightpull-drag')) { let vpWidthNew = uiProps.sgRightpull.vpWidth; if (uiProps.dockPosition === 'bottom') { vpWidthNew += 2 * (e.pageX - uiProps.sgRightpull.posX); } else { vpWidthNew += e.pageX - uiProps.sgRightpull.posX; } if (vpWidthNew > uiProps.minViewportWidth) { uiFns.sizeIframe(vpWidthNew, false); } } }); // Handle letting go of rightpull bar after dragging to resize. $orgs['#patternlab-body'].on('mouseup', function () { uiProps.sgRightpull.posX = null; uiProps.sgRightpull.vpWidth = null; $orgs['#sg-cover'].dispatchAction('removeClass', 'shown-by-rightpull-hover'); $orgs['#sg-cover'].dispatchAction('removeClass', 'shown-by-rightpull-drag'); }); }); }
electric-eloquence/fepper-npm
ui/core/styleguide/index/html/01-body/40-main/main.js
JavaScript
mit
2,224
<?php namespace Checkdomain\Holiday; use Checkdomain\Holiday\Model\Holiday; /** * Class Util */ class Util { /** * Instantiates a provider for a given iso code * * @param string $iso * * @return ProviderInterface */ protected function getProvider($iso) { $instance = null; $class = '\\Checkdomain\\Holiday\\Provider\\' . $iso; if (class_exists($class)) { $instance = new $class; } return $instance; } /** * @param \DateTime|string $date * * @return \DateTime */ protected function getDateTime($date) { if (!$date instanceof \DateTime) { $date = new \DateTime($date); } return $date; } /** * @param string $iso * * @return string */ protected function getIsoCode($iso) { return strtoupper($iso); } /** * Checks wether a given date is a holiday * * This method can be used to check whether a specific date is a holiday * in a specified country and state * * @param string $iso * @param \DateTime|string $date * @param string $state * * @return bool */ public function isHoliday($iso, $date = 'now', $state = null) { return ($this->getHoliday($iso, $date, $state) !== null); } /** * Provides detailed information about a specific holiday * * @param string $iso * @param \DateTime|string $date * @param string $state * * @return Holiday|null */ public function getHoliday($iso, $date = 'now', $state = null) { $iso = $this->getIsoCode($iso); $date = $this->getDateTime($date); $provider = $this->getProvider($iso); $holiday = $provider->getHolidayByDate($date, $state); return $holiday; } }
checkdomain/Holiday
src/Util.php
PHP
mit
1,932
import java.io.BufferedReader; import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class CharCounterMain{ final static Charset enc = StandardCharsets.US_ASCII ; public CharCounterMain(String ch, String filedir){ if(ch.length() != 1){ System.out.println("The first argument needs to be a char, found string of length "+ch.length()); System.exit(1); } char c = ch.charAt(0); if( c != ' ' && c != '.' && Character.getNumericValue(c) < 97 && Character.getNumericValue(c) > 122 ){ //compare against the ascii integer values System.out.println("Need a character in range a-z (lowercase only) or a whitespace or a dot, found "+c+"!"); System.exit(1); } Path p = Paths.get(filedir); try { BufferedReader bf = Files.newBufferedReader(p,enc); String line; String line2 = null ; while((line = bf.readLine()) != null){ line2 += line ; } CharCounter cc = new CharCounter(c,line2); int freq = cc.getFrequency(); System.out.println(String.format("Frequency of character %c was %d", c,freq)); } catch (IOException e) { e.printStackTrace(); } System.out.println("Finished, exiting..."); } public static void main(String[] args){ if(args.length != 2){ System.out.println("Usage : CharCounterMain <char-to-look-for> <text-file-dir>"); }else{ new CharCounterMain(args[0],args[1]); } } }
dperezmavro/courseworks_uni
year_3/large_scale_and_distributed_systems/src/CharCounterMain.java
Java
mit
1,792
"use strict"; (function() { // "todos-angular" is just a hard-code id for storage var LOCAL_STORAGE_KEY = 'todos-angular'; var ENTER_KEY = 13; var ESC_KEY = 27; var internalFilters = { active: function(toDoItem) { return !toDoItem.completed; }, completed: function(toDoItem) { return toDoItem.completed; } }; angular.module('ToDoAngular', ['ngRoute']) .service('storage', function($q) { // Storage service return { save: function(toDoCollection) { localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(toDoCollection)); }, load: function() { var itemCollectionString = localStorage.getItem(LOCAL_STORAGE_KEY); return itemCollectionString && JSON.parse(itemCollectionString) || []; } } }) .directive('escHandler', function() { // Define directive for esc key return { restrict: 'A', link: function(scope, iElement, iAttrs) { function keyEventHandler(event) { if (event.keyCode === ESC_KEY) { scope.$apply(iAttrs.escHandler); } } iElement.on('keydown', keyEventHandler); scope.$on('$destroy', function() { iElement.off('keydown', keyEventHandler); }); } }; }) .directive('enterHandler', function() { // Define directive for enter key return { restrict: 'A', link: function (scope, iElement, iAttrs) { function keyEventHandler(event) { if (event.keyCode === ENTER_KEY) { scope.$apply(iAttrs.enterHandler); } } iElement.on('keydown', keyEventHandler); scope.$on('$destroy', function () { iElement.off('keydown', keyEventHandler); }); } }; }) .directive('selectAndFocus', function($timeout) { // Define directive for focus return { restrict: 'A', link: function(scope, iElement, iAttrs) { var focusPromise; scope.$watch(iAttrs.selectAndFocus, function(newValue) { if (newValue && !focusPromise) { focusPromise = $timeout(function focus() { focusPromise = null; iElement[0].focus(); }, 0, false); } }); scope.$on('$destroy', function() { if (focusPromise) { $timeout.cancel(focusPromise); focusPromise = null; } }); } }; }) .directive('toDoItem', function() { // Define directive for to-do item return { restrict: 'A', templateUrl: 'angular-item-template.html', scope: { itemViewModel: '=toDoItem' }, link: function (scope, iElement, iAttrs) { scope.editing = false; scope.originalTitle = ''; scope.$watch('itemViewModel.toDoItem.completed', function(newCompleted) { iElement.toggleClass('completed', newCompleted); }); scope.$watch('editing', function(newEditing) { iElement.toggleClass('editing', newEditing); }); scope.$watch('itemViewModel.isHidden', function(newHidden) { iElement.toggleClass('hidden', newHidden); }); scope.$watchGroup([ 'itemViewModel.toDoItem.title', 'itemViewModel.toDoItem.completed'], function() { scope.$emit('item-updated'); }); scope.destroy = function() { scope.$emit('remove-item', scope.itemViewModel); }; scope.edit = function() { scope.originalTitle = scope.itemViewModel.toDoItem.title; scope.editing = true; }; scope.update = function() { var title = scope.itemViewModel.toDoItem.title || ''; var trimmedTitle = title.trim(); if (scope.editing) { if (title !== trimmedTitle) { scope.itemViewModel.toDoItem.title = trimmedTitle; } if (!trimmedTitle) { scope.destroy(); } scope.editing = false; } }; scope.revert = function() { scope.editing = false; scope.itemViewModel.toDoItem.title = scope.originalTitle; }; } }; }) .controller('AppController', function AppController( $scope, $routeParams, storedToDoCollection, storage) { // Define app controller $scope.toDoCollection = storedToDoCollection.map(function(storedToDo) { return { toDoItem: storedToDo, isHidden: $scope.filter ? !$scope.filter(storedToDo): false }; }); $scope.currentTitle = ''; $scope.$on('$routeChangeSuccess', function() { var filterString = $routeParams.filter; if (filterString && (filterString in internalFilters)) { $scope.filterString = filterString; $scope.filter = internalFilters[filterString]; } else { $scope.filterString = ''; $scope.filter = null; } }); function save() { storage.save($scope.toDoCollection.map(function(toDoViewModel) { return toDoViewModel.toDoItem; })); } $scope.$watch('filter', function(newFilter) { $scope.toDoCollection.forEach(function(toDoViewModel) { toDoViewModel.isHidden = newFilter ? !newFilter(toDoViewModel.toDoItem) : false; }); }); $scope.$watch(function() { return $scope.toDoCollection.filter(function(toDoViewModel){ return !toDoViewModel.toDoItem.completed; }).length; }, function(newValue) { if (newValue == null) { $scope.remainingLabel = ''; } else { $scope.remainingLabel = newValue === 1 ? (newValue + ' item left') : (newValue + ' items left'); } }); $scope.$watchCollection('toDoCollection', function() { save(); }); $scope.$on('item-updated', function() { save(); }); $scope.$on('remove-item', function(scope, toDoViewModel) { for(var index = 0; index < $scope.toDoCollection.length; index++) { if ($scope.toDoCollection[index] === toDoViewModel) { $scope.toDoCollection.splice(index, 1); return; } } }); $scope.create = function() { var currentTitle = $scope.currentTitle.trim(); if (currentTitle) { var toDoItem = { title: currentTitle, completed: false }; var toDoItemViewModel = { toDoItem: toDoItem, isHidden: $scope.filter ? !$scope.filter(toDoItem): false }; $scope.toDoCollection.push(toDoItemViewModel); $scope.currentTitle = ''; } }; }) .config(function($routeProvider) { // Define routing var routeConfig = { controller: 'AppController', templateUrl: 'angular-app-template.html', resolve: { storedToDoCollection: function(storage) { return storage.load(); } } }; $routeProvider .when('/', routeConfig) .when('/:filter', routeConfig) .otherwise({ redirectTo: '/' }); }); })();
sasyomaru/advanced-javascript-training-material
module3/scripts/angular-app.js
JavaScript
mit
9,478
<?php namespace Params; /** * @codeCoverageIgnore */ trait SafeAccess { public function __set($name, $value) { throw new \Exception("Property [$name] doesn't exist for class [".get_class($this)."] so can't set it"); } public function __get($name) { throw new \Exception("Property [$name] doesn't exist for class [".get_class($this)."] so can't get it"); } }
Danack/Blog
vendor/danack/params/lib/Params/SafeAccess.php
PHP
mit
403
from decimal import Decimal from django import forms from django.template.loader import render_to_string from django.template.defaultfilters import slugify class BaseWidget(forms.TextInput): """ Base widget. Do not use this directly. """ template = None instance = None def get_parent_id(self, name, attrs): final_attrs = self.build_attrs(attrs, type=self.input_type, name=name) return final_attrs['id'] def get_widget_id(self, prefix, name, key=''): if self.instance: opts = self.instance._meta widget_id = '%s-%s-%s_%s-%s' % (prefix, name, opts.app_label, opts.module_name, self.instance.pk) else: widget_id = '%s-%s' % (prefix, name) if key: widget_id = '%s_%s' % (widget_id, slugify(key)) return widget_id def get_values(self, min_value, max_value, step=1): decimal_step = Decimal(str(step)) value = Decimal(str(min_value)) while value <= max_value: yield value value += decimal_step class SliderWidget(BaseWidget): """ Slider widget. In order to use this widget you must load the jQuery.ui slider javascript. This widget triggers the following javascript events: - *slider_change* with the vote value as argument (fired when the user changes his vote) - *slider_delete* without arguments (fired when the user deletes his vote) It's easy to bind these events using jQuery, e.g.:: $(document).bind('slider_change', function(event, value) { alert('New vote: ' + value); }); """ def __init__(self, min_value, max_value, step, instance=None, can_delete_vote=True, key='', read_only=False, default='', template='ratings/slider_widget.html', attrs=None): """ The argument *default* is used when the initial value is None. """ super(SliderWidget, self).__init__(attrs) self.min_value = min_value self.max_value = max_value self.step = step self.instance = instance self.can_delete_vote = can_delete_vote self.read_only = read_only self.default = default self.template = template self.key = key def get_context(self, name, value, attrs=None): # here we convert *min_value*, *max_value*, *step* and *value* # to string to avoid odd behaviours of Django localization # in the template (and, for backward compatibility we do not # want to use the *unlocalize* filter) attrs['type'] = 'hidden' return { 'min_value': str(self.min_value), 'max_value': str(self.max_value), 'step': str(self.step), 'can_delete_vote': self.can_delete_vote, 'read_only': self.read_only, 'default': self.default, 'parent': super(SliderWidget, self).render(name, value, attrs), 'parent_id': self.get_parent_id(name, attrs), 'value': str(value), 'has_value': bool(value), 'slider_id': self.get_widget_id('slider', name, self.key), 'label_id': 'slider-label-%s' % name, 'remove_id': 'slider-remove-%s' % name, } def render(self, name, value, attrs=None): context = self.get_context(name, value, attrs or {}) return render_to_string(self.template, context) class StarWidget(BaseWidget): """ Starrating widget. In order to use this widget you must download the jQuery Star Rating Plugin available at http://www.fyneworks.com/jquery/star-rating/#tab-Download and then load the required javascripts and css, e.g.:: <link href="/path/to/jquery.rating.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="/path/to/jquery.MetaData.js"></script> <script type="text/javascript" src="/path/to/jquery.rating.js"></script> This widget triggers the following javascript events: - *star_change* with the vote value as argument (fired when the user changes his vote) - *star_delete* without arguments (fired when the user deletes his vote) It's easy to bind these events using jQuery, e.g.:: $(document).bind('star_change', function(event, value) { alert('New vote: ' + value); }); """ def __init__(self, min_value, max_value, step, instance=None, can_delete_vote=True, key='', read_only=False, template='ratings/star_widget.html', attrs=None): super(StarWidget, self).__init__(attrs) self.min_value = min_value self.max_value = max_value self.step = step self.instance = instance self.can_delete_vote = can_delete_vote self.read_only = read_only self.template = template self.key = key def get_context(self, name, value, attrs=None): # here we convert *min_value*, *max_value* and *step* # to string to avoid odd behaviours of Django localization # in the template (and, for backward compatibility we do not # want to use the *unlocalize* filter) attrs['type'] = 'hidden' split_value = int(1 / self.step) if split_value == 1: values = range(1, self.max_value+1) split = u'' else: values = self.get_values(self.min_value, self.max_value, self.step) split = u' {split:%d}' % split_value return { 'min_value': str(self.min_value), 'max_value': str(self.max_value), 'step': str(self.step), 'can_delete_vote': self.can_delete_vote, 'read_only': self.read_only, 'values': values, 'split': split, 'parent': super(StarWidget, self).render(name, value, attrs), 'parent_id': self.get_parent_id(name, attrs), 'value': self._get_value(value, split_value), 'star_id': self.get_widget_id('star', name, self.key), } def _get_value(self, original, split): if original: value = round(original * split) / split return Decimal(str(value)) def render(self, name, value, attrs=None): context = self.get_context(name, value, attrs or {}) return render_to_string(self.template, context) class LikeWidget(BaseWidget): def __init__(self, min_value, max_value, instance=None, can_delete_vote=True, template='ratings/like_widget.html', attrs=None): super(LikeWidget, self).__init__(attrs) self.min_value = min_value self.max_value = max_value self.instance = instance self.can_delete_vote = can_delete_vote self.template = template def get_context(self, name, value, attrs=None): # here we convert *min_value*, *max_value* and *step* # to string to avoid odd behaviours of Django localization # in the template (and, for backward compatibility we do not # want to use the *unlocalize* filter) attrs['type'] = 'hidden' return { 'min_value': str(self.min_value), 'max_value': str(self.max_value), 'can_delete_vote': self.can_delete_vote, 'parent': super(LikeWidget, self).render(name, value, attrs), 'parent_id': self.get_parent_id(name, attrs), 'value': str(value), 'like_id': self.get_widget_id('like', name), } def render(self, name, value, attrs=None): context = self.get_context(name, value, attrs or {}) return render_to_string(self.template, context)
redsolution/django-generic-ratings
ratings/forms/widgets.py
Python
mit
7,704
define(function() { return { draw: function(context, t) { var x = this.getNumber("x", t, 100), y = this.getNumber("y", t, 100), size = this.getNumber("size", t, 60), h = this.getNumber("h", t, 40), colorLeft = this.getColor("colorLeft", t, "#999999"), colorRight = this.getColor("colorRight", t, "#cccccc"), colorTop = this.getColor("colorTop", t, "#eeeeee"), scaleX = this.getNumber("scaleX", t, 1), scaleY = this.getNumber("scaleY", t, 1); context.translate(x, y); context.scale(scaleX, scaleY); if(h >= 0) { context.fillStyle = colorTop; context.beginPath(); context.moveTo(-size / 2, -h); context.lineTo(0, -size / 4 - h); context.lineTo(size / 2, -h); context.lineTo(size / 2, -1); context.lineTo(0, size / 4 - 1); context.lineTo(-size / 2, -1); context.lineTo(-size / 2, -h); this.drawFillAndStroke(context, t, true, false); context.fillStyle = colorLeft; context.beginPath(); context.moveTo(-size / 2, 0); context.lineTo(0, size / 4); context.lineTo(0, size / 4 - h); context.lineTo(-size / 2, -h); context.lineTo(-size / 2, 0); this.drawFillAndStroke(context, t, true, false); context.fillStyle = colorRight; context.beginPath(); context.moveTo(size / 2, 0); context.lineTo(0, size / 4); context.lineTo(0, size / 4 - h); context.lineTo(size / 2, -h); context.lineTo(size / 2, 0); this.drawFillAndStroke(context, t, true, false); } else { // clip path context.beginPath(); context.moveTo(-size / 2, 0); context.lineTo(0, -size / 4); context.lineTo(size / 2, 0); context.lineTo(0, size / 4); context.lineTo(-size / 2, 0); context.clip(); context.fillStyle = colorRight; context.beginPath(); context.moveTo(-size / 2, 0); context.lineTo(0, -size / 4); context.lineTo(0, -size / 4 -h); context.lineTo(-size / 2, -h); context.lineTo(-size / 2, 0); this.drawFillAndStroke(context, t, true, false); context.fillStyle = colorLeft; context.beginPath(); context.moveTo(size / 2, 0); context.lineTo(0, -size / 4); context.lineTo(0, -size / 4 -h); context.lineTo(size / 2, -h); context.lineTo(size / 2, 0); this.drawFillAndStroke(context, t, true, false); context.fillStyle = colorTop; context.beginPath(); context.moveTo(-size / 2, -h); context.lineTo(0, -size / 4 - h); context.lineTo(size / 2, -h); context.lineTo(0, size / 4 - h); context.lineTo(-size / 2, -h); this.drawFillAndStroke(context, t, true, false); } } } });
bit101/gifloopcoder
src/src/app/render/shapes/isobox.js
JavaScript
mit
2,755
<?php namespace BoundedContext\Contracts\Generator; use BoundedContext\Contracts\ValueObject\Identifier as IdentifierVO; interface Identifier extends ValueObject { /** * Generates a new random Identifier. * * @return IdentifierVO */ public function generate(); /** * Generates a null Identifier. * * @return IdentifierVO */ public function null(); /** * Generates a new Identifier from a string. * * @param string $identifier * @return IdentifierVO */ public function string($identifier); }
lyonscf/bounded-context
src/Contracts/Generator/Identifier.php
PHP
mit
587
<?php return array ( 'id' => 'softbank_v702nk2_ver1', 'fallback' => 'softbank_generic', 'capabilities' => array ( 'physical_screen_height' => '41', 'columns' => '15', 'physical_screen_width' => '34', 'max_image_width' => '176', 'rows' => '6', 'resolution_width' => '176', 'resolution_height' => '208', 'max_image_height' => '173', 'colors' => '262144', 'max_deck_size' => '357000', 'mms_max_size' => '307200', 'mms_max_width' => '640', 'mms_max_height' => '480', 'nokia_series' => '60', 'nokia_feature_pack' => '2', 'nokia_edition' => '2', 'model_name' => '702NKII(NOKIA 6680)', 'uaprof' => 'http://nds1.nds.nokia.com/uaprof/N6680r100-VFKK3G.xml', 'model_extra_info' => 'Vodafone', 'release_date' => '2005_may', 'directdownload_support' => 'true', 'oma_support' => 'true', 'aac' => 'true', 'mp3' => 'true', 'oma_v_1_0_separate_delivery' => 'true', 'flash_lite_version' => '', 'xhtml_file_upload' => 'supported', ), );
cuckata23/wurfl-data
data/softbank_v702nk2_ver1.php
PHP
mit
1,037
package com.company; import java.util.Scanner; public class Greeting { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String firstName = scanner.nextLine(); String lastName = scanner.nextLine(); int age = Integer.parseInt(scanner.nextLine()); System.out.printf("Hello, %s %s. You are %d years old.", firstName, lastName, age); } }
ivelin1936/Studing-SoftUni-
Programming Fundamentals/DataTypesAndVariables-Lab/src/com/company/Greeting.java
Java
mit
419
package sbahjsic.runtime; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import sbahjsic.core.Warnings; import sbahjsic.core.Warnings.Level; import sbahjsic.runtime.Operator.BiOperator; import sbahjsic.runtime.Operator.UnOperator; import sbahjsic.runtime.Operator.VarargOperator; import sbahjsic.runtime.type.AnyType; import sbahjsic.runtime.type.SVoid; /** Describes a Sbahjsic type. * * <p>For all subclasses, there must only exist one instance. To enforce * this, this class implements final {@code equals()} and {@code hashCode()} * methods as they are defined in {@code Object}.*/ public abstract class Type { private final Map<String, Operator> operators = new HashMap<>(); private final Set<Type> supertypes = new HashSet<>(); private final Set<String> fields = new HashSet<>(); private final Map<String, Method> methods = new HashMap<>(); private int priority = 0; protected Type() { // Fixes a bug where AnyType tried to add AnyType.INSTANCE, which // was null at that point, to its own supertypes if(!getClass().equals(AnyType.class)) { addSupertype(AnyType.INSTANCE); } } /** Registers a new supertype for this type. * @param supertype the new supertype*/ public final void addSupertype(Type supertype) { if(getSupertypes().contains(supertype) || supertype.getSupertypes().contains(this)) { throw new RecursiveTypedefException(this.toString()); } if(this != supertype) { supertypes.add(supertype); } } /** Removes a supertype from this type if it exists. * @param supertype the supertype to remove*/ public final void removeSupertype(Type supertype) { supertypes.remove(supertype); } /** Registers an unary operator for this type. * @param op the operator to register * @param func a function that applies this operator*/ public final void addUnOperator(String op, UnOperator func) { operators.put(op, Operator.unaryOperator(func)); } /** Registers a binary operator for this type. * @param op the operator to register * @param func a function that applies this operator*/ public final void addBiOperator(String op, BiOperator func) { operators.put(op, Operator.binaryOperator(func)); } /** Adds an operator that can accept one or two arguments. * @param op the operator * @param unary the unary operator * @param binary the binary operator*/ protected final void addDoubleOperator(String op, UnOperator unary, BiOperator binary) { operators.put(op, (con, args) -> { if(args.length == 1) return unary.apply(con, args[0]); else if(args.length == 2) return binary.apply(con, args[0], args[1]); throw new OperatorCallException("Called with " + args.length + " arguments, expected 1 or 2"); }); } /** Registers a vararg operator for this type.*/ public void addVarargOperator(String op, VarargOperator func) { operators.put(op, Operator.varargOperator(func)); } /** Adds a field to this type. * @param field the field to add*/ protected final void addField(String field) { fields.add(field); } /** Returns a specific operator of this type. * @param op the operator to search * @return the operator matching {@code op} * @throws OperatorCallException if {@code op} isn't defined*/ public final Operator getOperator(String op) { if(operators.containsKey(op)) { return operators.get(op); } Operator operator = operatorLookup(op); if(operator == null) { throw new OperatorCallException("Operator " + op + " not defined on type " + getName()); } return operator; } private final Operator operatorLookup(String op) { for(Type supertype : supertypes) { if(supertype.operators.containsKey(op)) { return supertype.operators.get(op); } } for(Type supertype : supertypes) { Operator operator = supertype.operatorLookup(op); if(operator != null) { return operator; } } return null; } /** Returns a set of all defined operators of this type. * @return a set of the defined operators of this type*/ public final Set<String> getDefinedOperators() { Set<String> ops = new HashSet<>(); ops.addAll(operators.keySet()); for(Type supertype : getSupertypes()) { ops.addAll(supertype.getDefinedOperators()); } return ops; } /** Returns a set of the supertypes of this type. * @return a set of the supertypes of this type*/ public final Set<Type> getSupertypes() { Set<Type> types = new HashSet<>(); types.addAll(supertypes); for(Type supertype : supertypes) { types.addAll(supertype.getSupertypes()); } return types; } /** Returns the fields declared for this type. * @return a set of fields declared for this type*/ public final Set<String> getFields() { Set<String> allFields = new HashSet<>(); allFields.addAll(fields); for(Type supertype : getSupertypes()) { allFields.addAll(supertype.getFields()); } return allFields; } /** Adds a method to this type. * @param name the name of the method * @param method the method*/ public final void addMethod(String name, Method method) { methods.put(name, method); } /** Returns all methods defined for this type. * @return all methods defined for this type*/ public final Set<String> getMethods() { Map<String, Method> allMethods = new HashMap<>(); allMethods.putAll(methods); for(Type supertype : getSupertypes()) { allMethods.putAll(supertype.methods); } return allMethods.keySet(); } /** Returns a method of this type. * @param name the name of the method * @return the method * @throws MethodCallException if the method isn't defined for this type*/ public final Method getMethod(String name) { if(methods.containsKey(name)) { return methods.get(name); } Method method = methodLookup(name); if(method == null) { throw new MethodCallException("Method " + name + " not defined for type " + getName()); } return method; } private final Method methodLookup(String name) { for(Type supertype : supertypes) { if(supertype.methods.containsKey(name)) { return supertype.methods.get(name); } } for(Type supertype : supertypes) { Method method = supertype.methodLookup(name); if(method != null) { return method; } } return null; } /** Returns the name of this type. * @return the name of this type*/ public abstract String getName(); /** Casts a value to this type. * @param object the value to cast * @return the casted value*/ public SValue cast(SValue object) { Warnings.warn(Level.ADVICE, "Undefined cast from " + object.getType() + " to " + this); return object; } /** Returns whether this type is the subtype of some other type. That is * true if this type or any if its supertypes is the other type. * @param other the other type * @return whether this type is the subtype of the other type */ public boolean isSubtype(Type other) { return this.equals(other) || getSupertypes().contains(other); } /** Constructs an instance of this type * @param context the RuntimeContext * @param args the arguments passed to the constructor*/ public SValue construct(RuntimeContext context, SValue...args) { Warnings.warn(Level.NOTIFICATION, "Cannot instantiate " + getName()); return SVoid.VOID; } /** Returns the priority of this type, used to determine which operand * should choose the implementation of a binary operator. Defaults to zero.*/ public int priority() { return priority; } /** Sets the priority for this type.*/ public void setPriority(int p) { priority = p; } @Override public final boolean equals(Object o) { return super.equals(o); } @Override public final int hashCode() { return super.hashCode(); } @Override public final String toString() { return getName(); } }
expositionrabbit/Sbahjsic-runtime
src/sbahjsic/runtime/Type.java
Java
mit
7,839
class Person < ActiveRecord::Base has_many :addresses, dependent: :destroy accepts_nested_attributes_for :addresses end
scotthelm/fencepost
spec/dummy/app/models/person.rb
Ruby
mit
125
import React from 'react'; import {connect} from 'cerebral-view-react'; import styles from './styles.css'; import { isObject, isArray, isString, isBoolean, isNumber, isNull } from 'common/utils'; import JSONInput from './JSONInput'; import connector from 'connector'; function isInPath(source, target) { if (!source || !target) { return false; } return target.reduce((isInPath, key, index) => { if (!isInPath) { return false; } return String(source[index]) === String(key); }, true); } function renderType(value, hasNext, path, propertyKey, highlightPath) { if (value === undefined) { return null; } if (isArray(value)) { return ( <ArrayValue value={value} hasNext={hasNext} path={path} propertyKey={propertyKey} highlightPath={highlightPath}/> ); } if (isObject(value)) { return ( <ObjectValue value={value} hasNext={hasNext} path={path} propertyKey={propertyKey} highlightPath={highlightPath}/> ); } return ( <Value value={value} hasNext={hasNext} path={path} propertyKey={propertyKey} highlightPath={highlightPath}/> ); } class ObjectValue extends React.Component { static contextTypes = { options: React.PropTypes.object.isRequired } constructor(props, context) { super(props); const numberOfKeys = Object.keys(props.value).length; const isHighlightPath = !!(this.props.highlightPath && isInPath(this.props.highlightPath, this.props.path)); const preventCollapse = this.props.path.length === 0 && context.options.expanded; this.state = { isCollapsed: !preventCollapse && !isHighlightPath && (numberOfKeys > 3 || numberOfKeys === 0 ? true : context.options.expanded ? false : true) }; this.onCollapseClick = this.onCollapseClick.bind(this); this.onExpandClick = this.onExpandClick.bind(this); } shouldComponentUpdate(nextProps, nextState) { return ( nextState.isCollapsed !== this.state.isCollapsed || this.context.options.canEdit || nextProps.path !== this.props.path || nextProps.highlightPath !== this.props.highlightPath ); } componentWillReceiveProps(nextProps) { const context = this.context; const props = nextProps; const numberOfKeys = Object.keys(props.value).length; const isHighlightPath = !!(props.highlightPath && isInPath(props.highlightPath, props.path)); const preventCollapse = props.path.length === 0 && context.options.expanded; if (this.state.isCollapsed) { this.setState({ isCollapsed: !preventCollapse && !isHighlightPath && (numberOfKeys > 3 || numberOfKeys === 0 ? true : context.options.expanded ? false : true) }); } } onExpandClick() { this.setState({isCollapsed: false}) } onCollapseClick() { this.setState({isCollapsed: true}); } renderProperty(key, value, index, hasNext, path) { this.props.path.push(key); const property = ( <div className={styles.objectProperty} key={index}> <div className={styles.objectPropertyValue}>{renderType(value, hasNext, path.slice(), key, this.props.highlightPath)}</div> </div> ); this.props.path.pop(); return property; } renderKeys(keys) { if (keys.length > 3) { return keys.slice(0, 3).join(', ') + '...' } return keys.join(', '); } render() { const {value, hasNext} = this.props; const isExactHighlightPath = this.props.highlightPath && String(this.props.highlightPath) === String(this.props.path); if (this.state.isCollapsed) { return ( <div className={isExactHighlightPath ? styles.highlightObject : styles.object} onClick={this.onExpandClick}> {this.props.propertyKey ? this.props.propertyKey + ': ' : null} <strong>{'{ '}</strong>{this.renderKeys(Object.keys(value))}<strong>{' }'}</strong> {hasNext ? ',' : null} </div> ); } else if (this.props.propertyKey) { const keys = Object.keys(value); return ( <div className={isExactHighlightPath ? styles.highlightObject : styles.object}> <div onClick={this.onCollapseClick}>{this.props.propertyKey}: <strong>{'{ '}</strong></div> {keys.map((key, index) => this.renderProperty(key, value[key], index, index < keys.length - 1, this.props.path))} <div><strong>{' }'}</strong>{hasNext ? ',' : null}</div> </div> ); } else { const keys = Object.keys(value); return ( <div className={isExactHighlightPath ? styles.highlightObject : styles.object}> <div onClick={this.onCollapseClick}><strong>{'{ '}</strong></div> {keys.map((key, index) => this.renderProperty(key, value[key], index, index < keys.length - 1, this.props.path, this.props.highlightPath))} <div><strong>{' }'}</strong>{hasNext ? ',' : null}</div> </div> ); } } } class ArrayValue extends React.Component { static contextTypes = { options: React.PropTypes.object.isRequired } constructor(props, context) { super(props); const numberOfItems = props.value.length; const isHighlightPath = this.props.highlightPath && isInPath(this.props.highlightPath, this.props.path); this.state = { isCollapsed: !isHighlightPath && (numberOfItems > 3 || numberOfItems === 0) ? true : context.options.expanded ? false : true }; this.onCollapseClick = this.onCollapseClick.bind(this); this.onExpandClick = this.onExpandClick.bind(this); } shouldComponentUpdate(nextProps, nextState) { return ( nextState.isCollapsed !== this.state.isCollapsed || this.context.options.canEdit || nextProps.path !== this.props.path || nextProps.highlightPath !== this.props.highlightPath ); } componentWillReceiveProps(nextProps) { const context = this.context; const props = nextProps; const numberOfItems = props.value.length; const isHighlightPath = props.highlightPath && isInPath(props.highlightPath, props.path); if (this.state.isCollapsed) { this.setState({ isCollapsed: !isHighlightPath && (numberOfItems > 3 || numberOfItems === 0) ? true : context.options.expanded ? false : true }); } } onExpandClick() { this.setState({isCollapsed: false}) } onCollapseClick() { this.setState({isCollapsed: true}); } renderItem(item, index, hasNext, path) { this.props.path.push(index); const arrayItem = ( <div className={styles.arrayItem} key={index}> {renderType(item, hasNext, path.slice())} </div> ); this.props.path.pop(); return arrayItem; } render() { const {value, hasNext} = this.props; const isExactHighlightPath = this.props.highlightPath && String(this.props.highlightPath) === String(this.props.path); if (this.state.isCollapsed) { return ( <div className={isExactHighlightPath ? styles.highlightArray : styles.array} onClick={this.onExpandClick}> {this.props.propertyKey ? this.props.propertyKey + ': ' : null} <strong>{'[ '}</strong>{value.length}<strong>{' ]'}</strong> {hasNext ? ',' : null} </div> ); } else if (this.props.propertyKey) { const keys = Object.keys(value); return ( <div className={isExactHighlightPath ? styles.highlightArray : styles.array}> <div onClick={this.onCollapseClick}>{this.props.propertyKey}: <strong>{'[ '}</strong></div> {value.map((item, index) => this.renderItem(item, index, index < value.length - 1, this.props.path))} <div><strong>{' ]'}</strong>{hasNext ? ',' : null}</div> </div> ); } else { return ( <div className={isExactHighlightPath ? styles.highlightArray : styles.array}> <div onClick={this.onCollapseClick}><strong>{'[ '}</strong></div> {value.map((item, index) => this.renderItem(item, index, index < value.length - 1, this.props.path))} <div><strong>{' ]'}</strong>{hasNext ? ',' : null}</div> </div> ); } } } @connect() class Value extends React.Component { static contextTypes = { options: React.PropTypes.object.isRequired } constructor(props) { super(props); this.state = { isEditing: false, path: props.path.slice() }; this.onSubmit = this.onSubmit.bind(this); this.onBlur = this.onBlur.bind(this); this.onClick = this.onClick.bind(this); } shouldComponentUpdate(nextProps, nextState) { return ( nextProps.value !== this.props.value || nextState.isEditing !== this.state.isEditing || nextProps.path !== this.props.path ); } onClick() { this.setState({ isEditing: this.context.options.canEdit ? true : false }); } onSubmit(value) { this.props.signals.debugger.modelChanged({ path: this.state.path, value }) this.setState({isEditing: false}); connector.sendEvent('changeModel', { path: this.state.path, value: value }); } onBlur() { this.setState({isEditing: false}); } renderValue(value, hasNext) { const isExactHighlightPath = this.props.highlightPath && String(this.props.highlightPath) === String(this.props.path); if (this.state.isEditing) { return ( <div className={isExactHighlightPath ? styles.highlightValue : null}> {this.props.propertyKey ? this.props.propertyKey + ': ' : <span/>} <span> <JSONInput value={value} onBlur={this.onBlur} onSubmit={this.onSubmit}/> </span> {hasNext ? ',' : null} </div> ); } else { return ( <div className={isExactHighlightPath ? styles.highlightValue : null}> {this.props.propertyKey ? this.props.propertyKey + ': ' : <span/>} <span onClick={this.onClick}>{isString(value) ? '"' + value + '"' : String(value)}</span> {hasNext ? ',' : null} </div> ); } } render() { let className = styles.string; if (isNumber(this.props.value)) className = styles.number; if (isBoolean(this.props.value)) className = styles.boolean; if (isNull(this.props.value)) className = styles.null; return ( <div className={className}> {this.renderValue(this.props.value, this.props.hasNext)} </div> ); } } class Inspector extends React.Component { static childContextTypes = { options: React.PropTypes.object.isRequired } getChildContext() { return { options: { expanded: this.props.expanded || false, canEdit: this.props.canEdit || false } } } render() { return renderType(this.props.value, false, [], null, this.props.path); } } export default Inspector;
cerebral/cerebral-debugger-prototype
versions/v1/components/Debugger/Inspector/index.js
JavaScript
mit
10,888
// Package storagedatalake implements the Azure ARM Storagedatalake service API version 2019-10-31. // // Azure Data Lake Storage provides storage for Hadoop and other big data workloads. package storagedatalake // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "github.com/Azure/go-autorest/autorest" ) const ( // DefaultDNSSuffix is the default value for dns suffix DefaultDNSSuffix = "dfs.core.windows.net" ) // BaseClient is the base client for Storagedatalake. type BaseClient struct { autorest.Client XMsVersion string AccountName string DNSSuffix string } // New creates an instance of the BaseClient client. func New(xMsVersion string, accountName string) BaseClient { return NewWithoutDefaults(xMsVersion, accountName, DefaultDNSSuffix) } // NewWithoutDefaults creates an instance of the BaseClient client. func NewWithoutDefaults(xMsVersion string, accountName string, dNSSuffix string) BaseClient { return BaseClient{ Client: autorest.NewClientWithUserAgent(UserAgent()), XMsVersion: xMsVersion, AccountName: accountName, DNSSuffix: dNSSuffix, } }
Azure/azure-sdk-for-go
services/storage/datalake/2019-10-31/storagedatalake/client.go
GO
mit
1,358
'use strict'; function valuefy(value) { if (typeof value !== 'object') { return (typeof value === 'string') ? `"${value}"` : value; } let values = []; if (Array.isArray(value)) { for (const v of value) { values.push(valuefy(v)); } values = `[${values.join(',')}]`; } else { for (let v in value) { if ({}.hasOwnProperty.call(value, v)) { values.push(`"${v}":${valuefy(value[v])}`); } } values = `{${values.join(',')}}`; } return values; } function serialize(target) { if (!target || typeof target !== 'object') { throw new TypeError('Invalid type of target'); } let values = []; for (let t in target) { if ({}.hasOwnProperty.call(target, t)) { values.push(`${t}=${valuefy(target[t])}`); } } return values; } function extract(t, outter, onlyContent) { const start = onlyContent ? 1 : 0; const pad = onlyContent ? 0 : 1; return t.slice(start, t.lastIndexOf(outter) + pad); } function objectify(v) { if (v[0] === '{') { return JSON.parse(extract(v, '}')); } else if (v[0] === '[') { const set = []; const es = extract(v, ']', true); if (es[0] === '[' || es[0] === '{') { set.push(objectify(es)); } else { for (const e of es.split(',')) { set.push(objectify(e)); } } return set; } else if (v[0] === '"') { v = extract(v, '"', true); } return v; } function deserialize(values) { if (!values) { throw new TypeError('Invalid type of values'); } else if (!Array.isArray(values)) { values = [values]; } const target = {}; for (const v of values) { const fieldValue = v.split('=', 2); target[fieldValue[0]] = objectify(fieldValue[1]); } return target; } module.exports = { pairify: serialize, parse: deserialize };
ragingwind/field-value
index.js
JavaScript
mit
1,725
<?php namespace App\Notifications\Mship; use App\Notifications\Notification; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Notifications\Messages\MailMessage; class ForgottenPasswordLink extends Notification implements ShouldQueue { use Queueable; private $token; /** * Create a new notification instance. * * @return void */ public function __construct($token) { parent::__construct(); $this->token = $token; } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { return ['mail', 'database']; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $subject = 'SSO Password Reset'; return (new MailMessage) ->from(config('mail.from.address'), 'VATSIM UK Web Services') ->subject($subject) ->view('emails.mship.security.reset_confirmation', ['subject' => $subject, 'recipient' => $notifiable, 'account' => $notifiable, 'token' => route('password.reset', $this->token)]); } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ public function toArray($notifiable) { return ['token' => $this->token]; } }
atoff/core
app/Notifications/Mship/ForgottenPasswordLink.php
PHP
mit
1,567
export default class TasksService { static async fetchTasks() { const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); await delay(1000); return [ { id: 0, description: "task1", status: "Active" }, { id: 1, description: "task2", status: "Active" }, ]; } }
guptag/js-frameworks
React/examples/hello-world/src/data/TasksService.js
JavaScript
mit
308
#ifndef RUBY_EXT_UTILS_HPP_ #define RUBY_EXT_UTILS_HPP_ 1 #include <functional> #include <ruby.h> #include <stdlib.h> #include <string.h> #include <stdarg.h> #include <typeinfo> #ifdef __GNUC__ #include <cxxabi.h> #endif template <typename T> static const char * type_name() { #ifdef __GNUC__ const int buf_size = 32; static char tname[buf_size]; if (tname[0] != 0) { return tname; } const std::type_info& id = typeid(T); int status; char *name = abi::__cxa_demangle(id.name(), NULL, 0, &status); if (name != NULL) { if (status == 0) { strncpy(tname, name, buf_size - 1); } else { strncpy(tname, id.name(), buf_size - 1); } free(name); } return tname; #else return typeid(T).name(); #endif } /* * undefined reference to ... [g++ (tdm-1) 4.5.2] */ // template<typename T> // static void // tmp_obj_free(T ptr) // { // if (ptr) { // delete ptr; // } // } // template<typename T> // static void // tmp_ary_free(T ptr) // { // if (ptr) { // delete[] ptr; // } // } template<typename T> static void tmp_obj_free(void *ptr) { if (ptr) { T obj = static_cast<T>(ptr); delete obj; } } template<typename T> static void tmp_ary_free(void *ptr) { if (ptr) { T obj = static_cast<T>(ptr); delete[] obj; } } template<typename T> static inline VALUE wrap_tmp_obj(T ptr) { return Data_Wrap_Struct(rb_cObject, 0, tmp_obj_free<T>, ptr); } template<typename T> static inline VALUE wrap_tmp_ary(T ptr) { return Data_Wrap_Struct(rb_cObject, 0, tmp_ary_free<T>, ptr); } void delete_tmp_obj(volatile VALUE *store); #define delete_tmp_ary(x) delete_tmp_obj(x) /* * http://masamitsu-murase.blogspot.jp/2013/12/sevenzipruby-2-c-ruby.html */ extern "C" VALUE rxu_run_functor(VALUE p); #define RXU_PROTECT_FUNC(func) ((VALUE (*)(VALUE))(func)) template<typename T> static inline VALUE _rb_protect(T func, int *state) { typedef std::function<VALUE ()> func_type; func_type f = func; return rb_protect(rxu_run_functor, reinterpret_cast<VALUE>(&f), state); } template<typename T1, typename T2> static inline VALUE _rb_rescue(T1 func1, T2 func2) { typedef std::function<VALUE ()> func_type; func_type f1 = func1; func_type f2 = func2; return rb_rescue( RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1), RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2)); } #if defined(_MSC_VER) && _MSC_VER <= 1800 template<VALUE& e1, typename T1, typename T2> static inline VALUE _rb_rescue2(T1 func1, T2 func2) { typedef std::function<VALUE ()> func_type; func_type f1 = func1; func_type f2 = func2; return rb_rescue2( RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1), RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), e1, NULL); } template<VALUE& e1, VALUE& e2, typename T1, typename T2> static inline VALUE _rb_rescue2(T1 func1, T2 func2) { typedef std::function<VALUE ()> func_type; func_type f1 = func1; func_type f2 = func2; return rb_rescue2( RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1), RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), e1, e2, NULL); } template<VALUE& e1, VALUE& e2, VALUE& e3, typename T1, typename T2> static inline VALUE _rb_rescue2(T1 func1, T2 func2) { typedef std::function<VALUE ()> func_type; func_type f1 = func1; func_type f2 = func2; return rb_rescue2( RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1), RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), e1, e2, e3, NULL); } template<VALUE& e1, VALUE& e2, VALUE& e3, VALUE& e4, typename T1, typename T2> static inline VALUE _rb_rescue2(T1 func1, T2 func2) { typedef std::function<VALUE ()> func_type; func_type f1 = func1; func_type f2 = func2; return rb_rescue2( RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1), RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), e1, e2, e3, e4, NULL); } template<VALUE& e1, VALUE& e2, VALUE& e3, VALUE& e4, VALUE& e5, typename T1, typename T2> static inline VALUE _rb_rescue2(T1 func1, T2 func2) { typedef std::function<VALUE ()> func_type; func_type f1 = func1; func_type f2 = func2; return rb_rescue2( RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1), RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), e1, e2, e3, e4, e5, NULL); } #else template<VALUE&... exceptions, typename T1, typename T2> static inline VALUE _rb_rescue2(T1 func1, T2 func2) { typedef std::function<VALUE ()> func_type; func_type f1 = func1; func_type f2 = func2; return rb_rescue2( RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1), RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), exceptions..., NULL); } #endif template<typename T1, typename T2> static inline VALUE _rb_rescue2(T1 func1, T2 func2, VALUE e1) { typedef std::function<VALUE ()> func_type; func_type f1 = func1; func_type f2 = func2; return rb_rescue2( RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1), RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), e1, NULL); } template<typename T1, typename T2> static inline VALUE _rb_rescue2(T1 func1, T2 func2, VALUE e1, VALUE e2) { typedef std::function<VALUE ()> func_type; func_type f1 = func1; func_type f2 = func2; return rb_rescue2( RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1), RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), e1, e2, NULL); } template<typename T1, typename T2> static inline VALUE _rb_rescue2(T1 func1, T2 func2, VALUE e1, VALUE e2, VALUE e3) { typedef std::function<VALUE ()> func_type; func_type f1 = func1; func_type f2 = func2; return rb_rescue2( RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1), RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), e1, e2, e3, NULL); } template<typename T1, typename T2> static inline VALUE _rb_rescue2(T1 func1, T2 func2, VALUE e1, VALUE e2, VALUE e3, VALUE e4) { typedef std::function<VALUE ()> func_type; func_type f1 = func1; func_type f2 = func2; return rb_rescue2( RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1), RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), e1, e2, e3, e4, NULL); } template<typename T1, typename T2> static inline VALUE _rb_rescue2(T1 func1, T2 func2, VALUE e1, VALUE e2, VALUE e3, VALUE e4, VALUE e5) { typedef std::function<VALUE ()> func_type; func_type f1 = func1; func_type f2 = func2; return rb_rescue2( RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1), RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), e1, e2, e3, e4, e5, NULL); } template<typename T1, typename T2> static inline VALUE _rb_ensure(T1 func1, T2 func2) { typedef std::function<VALUE ()> func_type; func_type f1 = func1; func_type f2 = func2; return rb_ensure( RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1), RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2)); } extern "C" int rxu_run_functor_foreach(VALUE key, VALUE val, VALUE p); #define RXU_FOREACH_FUNC(func) ((int (*)(ANYARGS))(func)) template<typename T> static inline void _rb_hash_foreach(VALUE obj, T func) { typedef std::function<int (VALUE, VALUE)> func_type; func_type f = func; rb_hash_foreach(obj, RXU_FOREACH_FUNC(rxu_run_functor_foreach), reinterpret_cast<VALUE>(&f)); } #endif /* RUBY_EXT_UTILS_HPP_ */
yagisumi/ruby-gdiplus
ext/gdiplus/ruby_ext_utils.hpp
C++
mit
8,156
/** * Vasya Hobot * * Copyright (c) 2013-2014 Vyacheslav Slinko * Licensed under the MIT License */ function Message(chat, body) { this._chat = chat; this._body = body; } Message.prototype.getChat = function() { return this._chat; }; Message.prototype.getBody = function() { return this._body; }; module.exports = Message;
vslinko-archive/vasya-hobot
src/client/api/Message.js
JavaScript
mit
351
<?php namespace PLL\SocialBundle\Form\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\TextareaType; use Symfony\Component\Form\Extension\Core\Type\SubmitType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\Translation\TranslatorInterface; class PostType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('content', TextareaType::class, array( 'required' => true, 'label' => false, )) ->add('save', SubmitType::class, array( 'label' => 'timelinepost.label.post', 'translation_domain' => 'forms', 'attr' => array( 'class' => 'post-btn w3-btn w3-theme', ) )) ; } public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( 'data_class' => 'PLL\SocialBundle\Entity\Post' )); } } ?>
Kishlin/Ehub
src/PLL/SocialBundle/Form/Type/PostType.php
PHP
mit
1,072
package septemberpack.september; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Rect; import java.util.Random; /** * Created by Vlady on 22.10.2015. */ /** * Данный класс реализует отрисовку астероидов */ public class Asteroid { Bitmap bitmap; /** * Координаты первого астероида */ private int line1x; private int line1y; /** * Координаты второго астероида */ private int line2x; private int line2y; /** * Координаты третьего астероида */ private int line3x; private int line3y; private Random random; /** * Конструктор получающий объект картинки будущего астероида и * задающий астероидам рандомные координаты * @param bmp - объект картинки астероида */ public Asteroid(Bitmap bmp){ this.bitmap = bmp; random = new Random(); line1x = random.nextInt(880); line2x = random.nextInt(880); line3x = random.nextInt(880); line1y = -random.nextInt(300); line2y = -random.nextInt(300) - 400; // За пределом экрана минус 400 line3y = -random.nextInt(300) - 800; // За пределом экрана минус 800 } /** * Метод отрисовки астероидов * @param canvas - прямоугольная область экрана для рисования */ public void draw(Canvas canvas){ canvas.drawBitmap(bitmap, line1x, line1y, null); // Первая линия canvas.drawBitmap(bitmap, line2x, line2y, null); // Вторая линия canvas.drawBitmap(bitmap, line3x, line3y, null); // Третья линия } /** * Метод обновляющий координаты астероидов и задающий новые координаты при уплытии за границы фона */ public void update(){ if(line1y > 1400) { line1y = -80; line1x = random.nextInt(880); } else if(line2y > 1400) { line2y = -80; line2x = random.nextInt(880); } else if(line3y > 1400) { line3y = -80; line3x = random.nextInt(880); } line1y += GamePanel.speed; line2y += GamePanel.speed; line3y += GamePanel.speed; } /* * Методы возвращают прямоугольную область астероида по его координатам, для проверки столкновения с кораблем * Реализацию можно было уместить в один метод с четырьмя параметрами, но его вызов был бы нечитаемым * Поскольку присутствуют всего три астероида, мы имеем возможность сделать для каждого свой метод */ public Rect getAsteroid1(){ return new Rect(line1x, line1y, line1x + 100, line1y + 120); } public Rect getAsteroid2(){ return new Rect(line2x, line2y, line2x + 100, line2y + 120); } public Rect getAsteroid3(){ return new Rect(line3x, line3y, line3x + 100, line3y + 120); } }
vladb55/SeptemberRepository
app/src/main/java/septemberpack/september/Asteroid.java
Java
mit
3,547
import React from 'react'; import { shallow } from 'enzyme'; import UserProfile from '../UserProfile'; import Wrapper from '../Wrapper'; describe('<UserProfile />', () => { it('should render <Wrapper />', () => { const wrapper = shallow(<UserProfile />); expect(wrapper.find(Wrapper).length).toEqual(1); }); });
on3iro/Gloomhaven-scenario-creator
src/containers/Auth/tests/UserProfile.test.js
JavaScript
mit
327
class CreateWriMetadataSources < ActiveRecord::Migration[5.1] def change create_table :wri_metadata_sources do |t| t.text :name t.timestamps end end end
Vizzuality/climate-watch
db/migrate/20171016113108_create_wri_metadata_sources.rb
Ruby
mit
177
<?php namespace Davidsneal\MaxCDN\OAuth; class OAuthDataStore { function lookup_consumer($consumer_key) { // implement me } function lookup_token($consumer, $token_type, $token) { // implement me } function lookup_nonce($consumer, $token, $nonce, $timestamp) { // implement me } function new_request_token($consumer, $callback = null) { // return a new token attached to this consumer } function new_access_token($token, $consumer, $verifier = null) { // return a new access token attached to this consumer // for the user associated with this token if the request token // is authorized // should also invalidate the request token } }
davidsneal/laravel-maxcdn
src/MaxCDN/OAuth/OAuthDataStore.php
PHP
mit
747
import React from 'react'; import { ActivityIndicator, StyleSheet, Image, Text, View, ListView, TouchableOpacity } from 'react-native'; import Dimensions from 'Dimensions'; const {width, height} = Dimensions.get('window'); import globalVariables from '../globalVariables.js'; import LookCell from './LookCell.js'; import User from './User.js'; import DoneFooter from './DoneFooter.js'; import Icon from 'react-native-vector-icons/Ionicons'; const LookDetail = React.createClass({ getInitialState() { return { dataSource: new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}), comments: [], next:true, pageNo:1, animating:true }; }, getDefaultProps() { return { look:{}, navigator:"", }; }, componentWillMount() { this.queryRromServer(1); }, getDataSource(comments) { // return false; return this.state.dataSource.cloneWithRows(comments); }, renderFooter() { if (!this.state.next) { return ( <DoneFooter/> ); } return <ActivityIndicator style={styles.scrollSpinner} animating={this.state.animating}/>; }, renderHeader() { return ( <LookCell look={this.props.look} navigator={this.props.navigator} onSelect={function(){}} userCell={true} /> ); }, onEndReached() { if(this.props.look.comments_count==0){ this.setState({ next:false, }); return; } if (this.state.next && !this.state.animating) { this.setState({ animating: true }); this.queryRromServer(this.state.pageNo); } }, onSelectUser(user) { this.props.navigator.push({ component: User, title: user.name, backButtonTitle:' ', passProps: { user:user, navigator:this.props.navigator, }, }); }, // shouldComponentUpdate: function(nextProps, nextState) { // console.log('LookDetail.js.js-shouldComponentUpdate'); // return JSON.stringify(nextState)!=JSON.stringify(this.state); // }, renderRow(comments) { if(!comments.comment||!comments.comment.user){ return false; } return ( <TouchableOpacity activeOpacity={0.8} onPress={()=>this.onSelectUser(comments.comment.user)} style={styles.flexContainer}> <Image source={{uri:comments.comment.user.photo}} style={styles.avatar}/> <View style={styles.commentBody}> <View style={styles.commentHeader}> <View style={{flex:1}}> <Text style={styles.userName}>{comments.comment.user.name}</Text> </View> <View style={styles.timeView}> <Icon name="ios-clock-outline" color={globalVariables.textBase} size={15}/> <Text style={styles.time}> {globalVariables.formatDateToString(comments.comment.created_at)}</Text> </View> </View> <Text style={styles.commentText}>{comments.comment.body}</Text> </View> </TouchableOpacity> ); }, render() { console.log(new Date()-0); console.log('LookDetail.js.js-render'); return ( <ListView dataSource={this.state.dataSource} renderRow={this.renderRow} onEndReached={this.onEndReached} renderHeader={this.renderHeader} renderFooter={this.renderFooter} onEndReachedThreshold={10} automaticallyAdjustContentInsets={false} keyboardDismissMode='on-drag' keyboardShouldPersistTaps={false} showsVerticalScrollIndicator={true} style={styles.container} /> ); }, queryRromServer(page) { globalVariables.queryRromServer(globalVariables.apiLookServer+this.props.look.id+'/comments/'+(page||1),this.processsResults); }, processsResults(data) { if (!data||!data.comments||!data.comments.length) { this.setState({ animating: false, next:false, }); return; } var newComments= this.state.comments.concat(data.comments); var next=newComments.length>=this.props.look.comments_count?false:true; this.setState({ comments: newComments, animating: false, dataSource: this.getDataSource(newComments), pageNo: this.state.pageNo+1, next:next, }); } }); const styles = StyleSheet.create({ container: { paddingTop: 64, backgroundColor: globalVariables.background, }, flexContainer: { opacity:0.97, padding: 10, flexDirection: 'row', justifyContent: 'flex-start', }, commentBody: { flex: 1, flexDirection: "column", justifyContent: "center", }, commentHeader: { flexDirection: "row", alignItems: "flex-start" }, userName: { color:globalVariables.base, // fontSize:12, }, timeView:{ // width:50, flexDirection: "row", alignItems:'center', marginRight:5, }, time:{ color:globalVariables.textBase, fontSize:12, // , }, commentText: { // fontSize:12, marginTop:8, flexDirection: "row", color:globalVariables.textBase, }, avatar: { borderRadius: 18, width: 36, height: 36, marginRight: 10, marginLeft: 5, backgroundColor:globalVariables.textBase2, }, scrollSpinner: { marginVertical: 20, }, }); export default LookDetail;
rollo-zhou/look
src/components/LookDetail.js
JavaScript
mit
5,317
#!/usr/bin/env python import sys import os from treestore import Treestore try: taxonomy = sys.argv[1] except: taxonomy = None t = Treestore() treebase_uri = 'http://purl.org/phylo/treebase/phylows/tree/%s' tree_files = [x for x in os.listdir('trees') if x.endswith('.nex')] base_uri = 'http://www.phylocommons.org/trees/%s' tree_list = set(t.list_trees()) for tree_uri in tree_list: if not 'TB2_' in tree_uri: continue tree_id = t.id_from_uri(tree_uri) tb_uri = treebase_uri % (tree_id.replace('_', ':')) print tree_id, tb_uri t.annotate(tree_uri, annotations='?tree bibo:cites <%s> .' % tb_uri)
NESCent/phylocommons
tools/treebase_scraper/annotate_trees.py
Python
mit
622
<?php /** * This file belongs to the AnoynmFramework * * @author vahitserifsaglam <vahit.serif119@gmail.com> * @see http://gemframework.com * * Thanks for using */ namespace Anonym\Facades; use Anonym\Patterns\Facade; /** * Class Validation * @package Anonym\Facades */ class Validation extends Facade { /** * return the validation facade * * @return string */ protected static function getFacadeClass(){ return 'validation'; } }
AnonymPHP/Anonym-Library
src/Anonym/Facades/Validation.php
PHP
mit
487
/* * The contents of this file are subject to the Mozilla Public * License Version 1.1 (the "License"); you may not use this * file except in compliance with the License. You may obtain * a copy of the License at http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express * or implied. See the License for the specific language governing * rights and limitations under the License. * * * The Original Code is OIOSAML Java Service Provider. * * The Initial Developer of the Original Code is Trifork A/S. Portions * created by Trifork A/S are Copyright (C) 2008 Danish National IT * and Telecom Agency (http://www.itst.dk). All Rights Reserved. * * Contributor(s): * Joakim Recht <jre@trifork.com> * Rolf Njor Jensen <rolf@trifork.com> * Aage Nielsen <ani@openminds.dk> * */ package dk.itst.oiosaml.sp.service; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import dk.itst.oiosaml.logging.Logger; import dk.itst.oiosaml.logging.LoggerFactory; import org.apache.commons.configuration.Configuration; import org.opensaml.DefaultBootstrap; import org.opensaml.xml.ConfigurationException; import dk.itst.oiosaml.common.SAMLUtil; import dk.itst.oiosaml.configuration.FileConfiguration; import dk.itst.oiosaml.configuration.SAMLConfiguration; import dk.itst.oiosaml.configuration.SAMLConfigurationFactory; import dk.itst.oiosaml.error.Layer; import dk.itst.oiosaml.error.WrappedException; import dk.itst.oiosaml.logging.Audit; import dk.itst.oiosaml.logging.Operation; import dk.itst.oiosaml.sp.UserAssertion; import dk.itst.oiosaml.sp.UserAssertionHolder; import dk.itst.oiosaml.sp.bindings.BindingHandler; import dk.itst.oiosaml.sp.develmode.DevelMode; import dk.itst.oiosaml.sp.develmode.DevelModeImpl; import dk.itst.oiosaml.sp.metadata.CRLChecker; import dk.itst.oiosaml.sp.metadata.IdpMetadata; import dk.itst.oiosaml.sp.metadata.SPMetadata; import dk.itst.oiosaml.sp.service.session.Request; import dk.itst.oiosaml.sp.service.session.SessionCleaner; import dk.itst.oiosaml.sp.service.session.SessionHandler; import dk.itst.oiosaml.sp.service.session.SessionHandlerFactory; import dk.itst.oiosaml.sp.service.util.Constants; /** * Servlet filter for checking if the user is authenticated. * * <p> * If the user is authenticated, a session attribute, * {@link Constants#SESSION_USER_ASSERTION} is set to contain a * {@link UserAssertion} representing the user. The application layer can access * this object to retrieve SAML attributes for the user. * </p> * * <p> * If the user is not authenticated, a &lt;AuthnRequest&gt; is created and sent * to the IdP. The protocol used for this is selected automatically based on th * available bindings in the SP and IdP metadata. * </p> * * <p> * The atual redirects are done by {@link BindingHandler} objects. * </p> * * <p> * Discovery profile is supported by looking at a request parameter named * _saml_idp. If the parameter does not exist, the browser is redirected to * {@link Constants#DISCOVERY_LOCATION}, which reads the domain cookie. If the * returned value contains ids, one of the ids is selected. If none of the ids * in the list is registered, an exception is thrown. If no value has been set, * the first configured IdP is selected automatically. * </p> * * @author Joakim Recht <jre@trifork.com> * @author Rolf Njor Jensen <rolf@trifork.com> * @author Aage Nielsen <ani@openminds.dk> */ public class SPFilter implements Filter { private static final Logger log = LoggerFactory.getLogger(SPFilter.class); private CRLChecker crlChecker = new CRLChecker(); private boolean filterInitialized; private SAMLConfiguration conf; private String hostname; private SessionHandlerFactory sessionHandlerFactory; private AtomicBoolean cleanerRunning = new AtomicBoolean(false); private DevelMode develMode; /** * Static initializer for bootstrapping OpenSAML. */ static { try { DefaultBootstrap.bootstrap(); } catch (ConfigurationException e) { throw new WrappedException(Layer.DATAACCESS, e); } } public void destroy() { SessionCleaner.stopCleaner(); crlChecker.stopChecker(); if (sessionHandlerFactory != null) { sessionHandlerFactory.close(); } SessionHandlerFactory.Factory.close(); } /** * Check whether the user is authenticated i.e. having session with a valid * assertion. If the user is not authenticated an &lt;AuthnRequest&gt; is * sent to the Login Site. * * @param request * The servletRequest * @param response * The servletResponse */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (log.isDebugEnabled()) log.debug("OIOSAML-J SP Filter invoked"); if (!(request instanceof HttpServletRequest)) { throw new RuntimeException("Not supported operation..."); } HttpServletRequest servletRequest = ((HttpServletRequest) request); Audit.init(servletRequest); if (!isFilterInitialized()) { try { Configuration conf = SAMLConfigurationFactory.getConfiguration().getSystemConfiguration(); setRuntimeConfiguration(conf); } catch (IllegalStateException e) { request.getRequestDispatcher("/saml/configure").forward(request, response); return; } } if (conf.getSystemConfiguration().getBoolean(Constants.PROP_DEVEL_MODE, false)) { log.warn("Running in debug mode, skipping regular filter"); develMode.doFilter(servletRequest, (HttpServletResponse) response, chain, conf.getSystemConfiguration()); return; } if (cleanerRunning.compareAndSet(false, true)) { SessionCleaner.startCleaner(sessionHandlerFactory.getHandler(), ((HttpServletRequest) request).getSession().getMaxInactiveInterval(), 30); } SessionHandler sessionHandler = sessionHandlerFactory.getHandler(); if (servletRequest.getServletPath().equals(conf.getSystemConfiguration().getProperty(Constants.PROP_SAML_SERVLET))) { log.debug("Request to SAML servlet, access granted"); chain.doFilter(new SAMLHttpServletRequest(servletRequest, hostname, null), response); return; } final HttpSession session = servletRequest.getSession(); if (log.isDebugEnabled()) log.debug("sessionId....:" + session.getId()); Boolean forceAuthn = false; if(request.getParameterMap().containsKey(Constants.QUERY_STRING_FORCE_AUTHN)) { String forceAuthnAsString = request.getParameter(Constants.QUERY_STRING_FORCE_AUTHN); forceAuthn = forceAuthnAsString.toLowerCase().equals("true"); } // Is the user logged in? if (sessionHandler.isLoggedIn(session.getId()) && session.getAttribute(Constants.SESSION_USER_ASSERTION) != null && !forceAuthn) { int actualAssuranceLevel = sessionHandler.getAssertion(session.getId()).getAssuranceLevel(); int assuranceLevel = conf.getSystemConfiguration().getInt(Constants.PROP_ASSURANCE_LEVEL); if ((actualAssuranceLevel > 0) && (actualAssuranceLevel < assuranceLevel)) { sessionHandler.logOut(session); log.warn("Assurance level too low: " + actualAssuranceLevel + ", required: " + assuranceLevel); throw new RuntimeException("Assurance level too low: " + actualAssuranceLevel + ", required: " + assuranceLevel); } UserAssertion ua = (UserAssertion) session.getAttribute(Constants.SESSION_USER_ASSERTION); if (log.isDebugEnabled()) log.debug("Everything is ok... Assertion: " + ua); Audit.log(Operation.ACCESS, servletRequest.getRequestURI()); try { UserAssertionHolder.set(ua); HttpServletRequestWrapper requestWrap = new SAMLHttpServletRequest(servletRequest, ua, hostname); chain.doFilter(requestWrap, response); return; } finally { UserAssertionHolder.set(null); } } else { session.removeAttribute(Constants.SESSION_USER_ASSERTION); UserAssertionHolder.set(null); saveRequestAndGotoLogin((HttpServletResponse) response, servletRequest); } } protected void saveRequestAndGotoLogin(HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException { SessionHandler sessionHandler = sessionHandlerFactory.getHandler(); String relayState = sessionHandler.saveRequest(Request.fromHttpRequest(request)); String protocol = conf.getSystemConfiguration().getString(Constants.PROP_PROTOCOL, "saml20"); String loginUrl = conf.getSystemConfiguration().getString(Constants.PROP_SAML_SERVLET, "/saml"); String protocolUrl = conf.getSystemConfiguration().getString(Constants.PROP_PROTOCOL + "." + protocol); if (protocolUrl == null) { throw new RuntimeException("No protocol url configured for " + Constants.PROP_PROTOCOL + "." + protocol); } loginUrl += protocolUrl; if (log.isDebugEnabled()) log.debug("Redirecting to " + protocol + " login handler at " + loginUrl); RequestDispatcher dispatch = request.getRequestDispatcher(loginUrl); dispatch.forward(new SAMLHttpServletRequest(request, hostname, relayState), response); } public void init(FilterConfig filterConfig) throws ServletException { conf = SAMLConfigurationFactory.getConfiguration(); if (conf.isConfigured()) { try { Configuration conf = SAMLConfigurationFactory.getConfiguration().getSystemConfiguration(); if (conf.getBoolean(Constants.PROP_DEVEL_MODE, false)) { develMode = new DevelModeImpl(); setConfiguration(conf); setFilterInitialized(true); return; } setRuntimeConfiguration(conf); setFilterInitialized(true); return; } catch (IllegalStateException e) { log.error("Unable to configure", e); } } setFilterInitialized(false); } private void setRuntimeConfiguration(Configuration conf) { restartCRLChecker(conf); setFilterInitialized(true); setConfiguration(conf); if (!IdpMetadata.getInstance().enableDiscovery()) { log.info("Discovery profile disabled, only one metadata file found"); } else { if (conf.getString(Constants.DISCOVERY_LOCATION) == null) { throw new IllegalStateException("Discovery location cannot be null when discovery profile is active"); } } setHostname(); sessionHandlerFactory = SessionHandlerFactory.Factory.newInstance(conf); sessionHandlerFactory.getHandler().resetReplayProtection(conf.getInt(Constants.PROP_NUM_TRACKED_ASSERTIONIDS)); log.info("Home url: " + conf.getString(Constants.PROP_HOME)); log.info("Assurance level: " + conf.getInt(Constants.PROP_ASSURANCE_LEVEL)); log.info("SP entity ID: " + SPMetadata.getInstance().getEntityID()); log.info("Base hostname: " + hostname); } private void setHostname() { String url = SPMetadata.getInstance().getDefaultAssertionConsumerService().getLocation(); setHostname(url.substring(0, url.indexOf('/', 8))); } private void restartCRLChecker(Configuration conf) { crlChecker.stopChecker(); int period = conf.getInt(Constants.PROP_CRL_CHECK_PERIOD, 600); if (period > 0) { crlChecker.startChecker(period, IdpMetadata.getInstance(), conf); } } public void setHostname(String hostname) { this.hostname = hostname; } public void setFilterInitialized(boolean b) { filterInitialized = b; } public boolean isFilterInitialized() { return filterInitialized; } public void setConfiguration(Configuration configuration) { SAMLConfigurationFactory.getConfiguration().setConfiguration(configuration); conf = SAMLConfigurationFactory.getConfiguration(); } public void setSessionHandlerFactory(SessionHandlerFactory sessionHandlerFactory) { this.sessionHandlerFactory = sessionHandlerFactory; } public void setDevelMode(DevelMode develMode) { this.develMode = develMode; } }
Safewhere/kombit-web-java
Kombit.Samples.CH.WebsiteDemo/src/java/dk/itst/oiosaml/sp/service/SPFilter.java
Java
mit
12,213
package queier import ( "github.com/julienschmidt/httprouter" "net/http" "encoding/json" "fmt" "strconv" "broker-gateway/entities" "github.com/satori/go.uuid" ) type Router interface { Start(port int) } type router struct { q Querier http *httprouter.Router } func NewRouter(q Querier) Router { r := httprouter.New() rte:= &router{ q: q, http: r, } rte.register() return rte } func (rte *router)futures(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { futures := rte.q.Futures() echo(w, futures) } // //func (rte *router)ordersByFirmId(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { // firmId,_ := strconv.Atoi(ps.ByName("firmId")) // orders := rte.q.Orders(firmId) // res, err := json.Marshal(orders) // if err != nil { // fmt.Println(err) // } // w.Write(res) //} // //func (rte *router)ordersByFirmIdAndId(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { // firmId,_ := strconv.Atoi(ps.ByName("firmId")) // order := rte.q.OrderById(firmId,ps.ByName("id")) // res, err := json.Marshal(order) // if err != nil { // fmt.Println(err) // } // w.Write(res) //} // //func (rte *router) consignations(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { // firmId,_ := strconv.Atoi(ps.ByName("firmId")) // rtn := rte.q.Consignations(firmId) // res, err := json.Marshal(rtn) // if err != nil { // fmt.Println(err) // } // w.Write(res) //} // //func (rte *router)consignationsByFirmIdAndId(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { // firmId,_ := strconv.Atoi(ps.ByName("firmId")) // order := rte.q.ConsignationById(firmId,ps.ByName("id")) // res, err := json.Marshal(order) // if err != nil { // fmt.Println(err) // } // w.Write(res) //} // //func (rte *router)quotationsByFutureId(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { // futureId,_ := strconv.Atoi(ps.ByName("id")) // rtn := rte.q.Quotations(futureId) // res, err := json.Marshal(rtn) // if err != nil { // fmt.Println(err) // } // w.Write(res) //} func echo(w http.ResponseWriter, entity interface{}) { if entity == nil { w.Write([]byte("{}")) return } res, err := json.Marshal(entity) if err != nil { fmt.Println(err) } w.Header().Set("Access-Control-Allow-Origin","*") w.Write(res) } func (rte *router) register() { // For firm rte.http.GET("/futures",func(w http.ResponseWriter, h *http.Request, p httprouter.Params) { futures := rte.q.Futures() echo(w, futures) }) rte.http.GET("/futures/:id", func(w http.ResponseWriter, h *http.Request, p httprouter.Params) { id,_ := strconv.Atoi(p.ByName("id")) limit,_ := strconv.Atoi(h.URL.Query().Get("limit")) offset,_ := strconv.Atoi(h.URL.Query().Get("offset")) echo(w,rte.q.Quotations(id,limit,offset)) }) rte.http.GET("/firms/:firmId/orders", func(w http.ResponseWriter, h *http.Request, p httprouter.Params) { id,_ := strconv.Atoi(p.ByName("firmId")) limit,_ := strconv.Atoi(h.URL.Query().Get("limit")) offset,_ := strconv.Atoi(h.URL.Query().Get("offset")) res := rte.q.Orders(id,limit,offset) for i:=0;i<len(res) ;i++ { res[i] = entities.TransformForFirm(res[i],id) } echo(w,res) }) rte.http.GET("/firms/:firmId/orders/:id",func(w http.ResponseWriter, h *http.Request, p httprouter.Params) { firmid,_ := strconv.Atoi(p.ByName("firmId")) res := rte.q.OrderById(firmid, p.ByName("id")) if uuid.Equal(res.ID,uuid.FromBytesOrNil(nil)) { echo(w, nil) } else { echo(w,res) } }) rte.http.GET("/firms/:firmId/consignations",func(w http.ResponseWriter, h *http.Request, p httprouter.Params) { id,_ := strconv.Atoi(p.ByName("firmId")) limit,_ := strconv.Atoi(h.URL.Query().Get("limit")) offset,_ := strconv.Atoi(h.URL.Query().Get("offset")) res := rte.q.Consignations(id,limit,offset) echo(w,res) }) rte.http.GET("/firms/:firmId/consignations/:id",func(w http.ResponseWriter, h *http.Request, p httprouter.Params) { firmid,_ := strconv.Atoi(p.ByName("firmId")) res := rte.q.ConsignationById(firmid, p.ByName("id")) if uuid.Equal(res.ID,uuid.FromBytesOrNil(nil)) { echo(w, nil) } else { echo(w,res) } }) // For admin rte.http.GET("/admin/orders", func(w http.ResponseWriter, h *http.Request, p httprouter.Params) { limit,_ := strconv.Atoi(h.URL.Query().Get("limit")) offset,_ := strconv.Atoi(h.URL.Query().Get("offset")) echo(w,rte.q.AllOrders(limit,offset)) }) rte.http.GET("/admin/consignations", func(w http.ResponseWriter, h *http.Request, p httprouter.Params) { limit,_ := strconv.Atoi(h.URL.Query().Get("limit")) offset,_ := strconv.Atoi(h.URL.Query().Get("offset")) echo(w,rte.q.AllConsignations(limit,offset)) }) rte.http.PUT("/admin/commissions/:id", func(w http.ResponseWriter, h *http.Request, p httprouter.Params) { firmId,_ :=strconv.Atoi(h.URL.Query().Get("firmId")) futureId,_ := strconv.Atoi(h.URL.Query().Get("futureId")) orderType,_ := strconv.Atoi(h.URL.Query().Get("orderType")) percent,_ := strconv.Atoi(h.URL.Query().Get("percent")) id,_ := strconv.Atoi(p.ByName("id")) comm := entities.Commission{ ID: id, FirmId: firmId, FutureId: futureId, OrderType: orderType, CommissionPercent: percent, } rte.q.Save(&comm) echo(w, comm) }) rte.http.GET("/admin/commissions", func(w http.ResponseWriter, h *http.Request, p httprouter.Params) { var res []entities.Commission rte.q.Query().Find(&res) echo(w, res) }) rte.http.POST("/admin/commissions", func(w http.ResponseWriter, h *http.Request, p httprouter.Params) { firmId,_ :=strconv.Atoi(h.URL.Query().Get("firmId")) futureId,_ := strconv.Atoi(h.URL.Query().Get("futureId")) orderType,_ := strconv.Atoi(h.URL.Query().Get("orderType")) id,_ := strconv.Atoi(p.ByName("id")) percent,_ := strconv.Atoi(h.URL.Query().Get("percent")) comm := entities.Commission{ ID: id, FirmId: firmId, FutureId: futureId, OrderType: orderType, CommissionPercent: percent, } rte.q.Save(&comm) echo(w, comm) }) rte.http.GET("/admin/firmFutures", func(w http.ResponseWriter, h *http.Request, p httprouter.Params) { var res []entities.FirmFuture rte.q.Query().Find(res) echo(w, res) }) } func (r *router) Start(port int) { http.ListenAndServe(":"+strconv.Itoa(port),r.http) }
commodity-trading-system/broker-gateway
queier/router.go
GO
mit
6,277
<?php /** * Controlador de acesso do backend * * @package MagicPHP Backend * @author André Ferreira <andrehrf@gmail.com> */ class maPrivileges{ /** * Função para verificar autorização de acesso * * @static * @access public * @param string $sUsercase * @param string $sType * @return boolean */ public static function AuthorizedAccess($sUsercase, $sType){ if(Session::CheckAuthentication()){ return (Storage::Get("user.root", false)) ? true : Storage::Get("privilege.{$sType}.{$sUsercase}", false); } else{ Output::Redirect(Storage::Join("route.root", "login")); return false; } } /** * Função para salvar os privilégios * * @static * @access public * @param integer $iID * @return void */ public static function SavePrivileges($iID){ $oDb = Db::backend(); $iID = intval($iID); $aStorage = Storage::GetList(); $aData = array(); foreach($aStorage as $sKey => $mValue){ if(substr($sKey, 0, 4) == "put.") $aData[str_replace("put.", "", $sKey)] = $mValue; } if(count($aData) > 0 && $iID > 0) $oDb->administrators->Update(array("privilegios" => json_encode($aData)), array("id" => $iID), 1); ioBackendController::ReturnAjax(true); } /** * Função para retornar lista de privilgégios de um usuário * * @static * @access public * @param integer $iID * @return void */ public static function GetPrivileges($iID){ $iID = intval($iID); if($iID){ $oDb = Db::backend(); $oDb->administrators->Select("privilegios") ->Filter("id", $iID) ->Execute(function($aData, $mError){ $aPrivileges = json_decode($aData[0]["privilegios"], true); if(count($aPrivileges) > 0) foreach($aPrivileges as $iKey => $mItem) $aPrivileges[$iKey] = ($mItem == "true"); $aPrivileges = (empty($aPrivileges)) ? json_encode(array()) : json_encode($aPrivileges); die($aPrivileges); }); } else{ die(json_encode(array())); } } /** * Função para converter privilegios em JSON para Storage * * @static * @access public * @return void */ public static function LoadPrivileges(){ //if(!empty(Session::Get("user.privileges", ""))){ $aPrivileges = json_decode(Session::Get("user.privileges", array()), true); if($aPrivileges != null) foreach($aPrivileges as $sKey => $sValue) Storage::Set("privilege.".str_replace("_", ".", $sKey), ($sValue == "true")); //} } }
magicphp/backend
modules/backend/core/maprivileges.class.php
PHP
mit
3,522
var cv = require('../lib/opencv'); var COLOR = [0, 255, 0]; // default red var thickness = 2; // default 1 cv.readImage('./files/mona.png', function(err, im) { if (err) throw err; if (im.width() < 1 || im.height() < 1) throw new Error('Image has no size'); im.detectObject('../data/haarcascade_frontalface_alt2.xml', {}, function(err, faces) { if (err) throw err; for (var i = 0; i < faces.length; i++) { var face = faces[i]; im.rectangle([face.x, face.y], [face.width, face.height], COLOR, 2); } im.save('./tmp/face-detection-rectangle.png'); console.log('Image saved to ./tmp/face-detection-rectangle.png'); }); });
peterbraden/node-opencv
examples/face-detection-rectangle.js
JavaScript
mit
664
// ======================================================================== // SproutCore -- JavaScript Application Framework // Copyright ©2006-2011, Strobe Inc. and contributors. // Portions copyright ©2008 Apple Inc. All rights reserved. // ======================================================================== sc_require('controllers/object'); sc_require('mixins/selection_support'); sc_require('private/tree_item_observer'); /** @class A TreeController manages a tree of model objects that you might want to display in the UI using a collection view. For the most part, you should work with a TreeController much like you would an ObjectController, except that the TreeController will also provide an arrangedObjects property that can be used as the content of a CollectionView. TODO: Document More @extends SC.ObjectController @extends SC.SelectionSupport @since SproutCore 1.0 */ SC.TreeController = SC.ObjectController.extend(SC.SelectionSupport, /** @scope SC.TreeController.prototype */ { // .......................................................... // PROPERTIES // /** Set to YES if you want the top-level items in the tree to be displayed as group items in the collection view. @property {Boolean} */ treeItemIsGrouped: NO, /** If your content support expanding and collapsing of content, then set this property to the name of the key on your model that should be used to determine the expansion state of the item. The default is "treeItemIsExpanded" @property {String} */ treeItemIsExpandedKey: "treeItemIsExpanded", /** Set to the name of the property on your content object that holds the children array for each tree node. The default is "treeItemChildren". @property {String} */ treeItemChildrenKey: "treeItemChildren", /** Returns an SC.Array object that actually will represent the tree as a flat array suitable for use by a CollectionView. Other than binding this property as the content of a CollectionView, you generally should not use this property directly. Instead, work on the tree content using the TreeController like you would any other ObjectController. @property {SC.Array} */ arrangedObjects: function() { var ret, content = this.get('content'); if (content) { ret = SC.TreeItemObserver.create({ item: content, delegate: this }); } else ret = null; // empty! this._sctc_arrangedObjects = ret ; return ret ; }.property().cacheable(), // .......................................................... // PRIVATE // /** @private Manually invalidate the arrangedObjects cache so that we can teardown any existing value. We do it via an observer so that this will fire immediately instead of waiting on some other component to get arrangedObjects again. */ _sctc_invalidateArrangedObjects: function() { this.propertyWillChange('arrangedObjects'); var ret = this._sctc_arrangedObjects; if (ret) ret.destroy(); this._sctc_arrangedObjects = null; this.propertyDidChange('arrangedObjects'); }.observes('content', 'treeItemIsExpandedKey', 'treeItemChildrenKey', 'treeItemIsGrouped'), _sctc_arrangedObjectsContentDidChange: function() { this.updateSelectionAfterContentChange(); }.observes('*arrangedObjects.[]'), /** @private Returns the first item in arrangeObjects that is not a group. This uses a brute force approach right now; we assume you probably don't have a lot of groups up front. */ firstSelectableObject: function() { var objects = this.get('arrangedObjects'), indexes, len, idx = 0; if (!objects) return null; // fast track indexes = objects.contentGroupIndexes(null, objects); len = objects.get('length'); while(indexes.contains(idx) && (idx<len)) idx++; return idx>=len ? null : objects.objectAt(idx); }.property() });
Eloqua/sproutcore
frameworks/foundation/controllers/tree.js
JavaScript
mit
4,038
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using Pfz.AnimationManagement; using Pfz.AnimationManagement.Abstract; using Pfz.AnimationManagement.Animations; using Pfz.AnimationManagement.Wpf; namespace WpfSample { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { private IAnimation[] _basicAnimations; private IAnimation[] _intermediaryAnimations; internal IAnimation _animation; private ReadOnlyCollection<BitmapFrame> _waitingCharacter; private ReadOnlyCollection<BitmapFrame> _movingForwardCharacter; public MainWindow() { InitializeComponent(); Pfz.AnimationManagement.Wpf.Initializer.Initialize(); tabItemBasic.RequestBringIntoView += (a, b) => _SetBasicAnimation(); tabItemIntermediary.RequestBringIntoView += (a, b) => _SetIntermediaryAnimation(); _basicAnimations = new IAnimation[] { // Range AnimationBuilder.Range(0, 450, 3, (value) => Canvas.SetLeft(circle, value)), // Accelerating Start AnimationBuilder. BeginAcceleratingStart(1). Range(0, 450, 3, (value) => Canvas.SetLeft(circle, value)). EndAcceleratingStart(), // Deaccelerating End AnimationBuilder. BeginDeacceleratingEnd(1, 3). Range(0, 450, 3, (value) => Canvas.SetLeft(circle, value)). EndDeacceleratingEnd(), // Multiple time multipliers AnimationBuilder. BeginProgressiveTimeMultipliers(0.1). Add(AnimationBuilder.Range(0, 450, 3, (value) => Canvas.SetLeft(circle, value))). MultiplySpeed(1, 1). KeepSpeed(1). MultiplySpeed(0.1, 1). EndProgressiveTimeMultipliers(), // Color Range AnimationBuilder.Range(Colors.Black, Colors.Blue, 1, (value) => circle.Fill = new SolidColorBrush(value)), // Many Color Ranges AnimationBuilder. BeginRanges((value) => circle.Fill = new SolidColorBrush(value), Colors.Black). To(Colors.Blue, 1). To(Colors.Red, 1). To(Colors.Green, 1). To(Colors.Yellow, 1). To(Colors.Magenta, 1). To(Colors.Black, 1). EndRanges(), // Parallel Animation AnimationBuilder. BeginParallel(). BeginLoop(). BeginRanges((value) => circle.Fill = new SolidColorBrush(value), Colors.Black). To(Colors.Blue, 1). To(Colors.Red, 1). To(Colors.Green, 1). To(Colors.Yellow, 1). To(Colors.Magenta, 1). To(Colors.Black, 1). EndRanges(). EndLoop(). BeginLoop(). Range(0, 450, 3, (value) => Canvas.SetLeft(circle, value)). EndLoop(). EndParallel(), // Sequential Animation AnimationBuilder. BeginSequence(). Range(0, 450, 3, (value) => Canvas.SetLeft(circle, value)). Range(Colors.Black, Colors.Green, 1, (value) => circle.Fill = new SolidColorBrush(value)). Range(0, 450, 3, (value) => Canvas.SetTop(circle, value)). Range(Colors.Green, Colors.Red, 1, (value) => circle.Fill = new SolidColorBrush(value)). Range(450, 0, 3, (value) => Canvas.SetLeft(circle, value)). Range(Colors.Red, Colors.Blue, 1, (value) => circle.Fill = new SolidColorBrush(value)). Range(450, 0, 3, (value) => Canvas.SetTop(circle, value)). Range(Colors.Blue, Colors.Black, 1, (value) => circle.Fill = new SolidColorBrush(value)). EndSequence(), // Sequential Animation + Multiple Speeds AnimationBuilder. BeginProgressiveTimeMultipliers(). KeepSpeed(1). MultiplySpeed(2, 3). KeepSpeed(1). MultiplySpeed(0.5, 2). KeepSpeedUntilEnd(). BeginSequence(). Range(0, 450, 3, (value) => Canvas.SetLeft(circle, value)). Range(Colors.Black, Colors.Green, 1, (value) => circle.Fill = new SolidColorBrush(value)). Range(0, 450, 3, (value) => Canvas.SetTop(circle, value)). Range(Colors.Green, Colors.Red, 1, (value) => circle.Fill = new SolidColorBrush(value)). Range(450, 0, 3, (value) => Canvas.SetLeft(circle, value)). Range(Colors.Red, Colors.Blue, 1, (value) => circle.Fill = new SolidColorBrush(value)). Range(450, 0, 3, (value) => Canvas.SetTop(circle, value)). Range(Colors.Blue, Colors.Black, 1, (value) => circle.Fill = new SolidColorBrush(value)). EndSequence(). EndProgressiveTimeMultipliers(), // Imperative Animation new ImperativeAnimation(_ImperativeAnimation()), // Frame-by-Frame Animation new ImperativeAnimation(_FrameBasedAnimation()) }; AnimationManager.Add(new _ShowSelectedAnimation(this)); listboxBasicAnimation.SelectionChanged += listboxBasicAnimation_SelectionChanged; _SetBasicAnimation(); bool isGoing = true; _waitingCharacter = _LoadCharacter("Images\\Waiting.gif"); _movingForwardCharacter = _LoadCharacter("Images\\MoveForward.gif"); _intermediaryAnimations = new IAnimation[] { // Animate Character AnimationBuilder.RangeBySpeed(0, _waitingCharacter.Count-1, 10, (index) => imageCharacter.Source = _waitingCharacter[index]), // Move Character AnimationBuilder. BeginParallel(). BeginLoop(). RangeBySpeed(0, _movingForwardCharacter.Count-1, 10, (index) => imageCharacter.Source = _movingForwardCharacter[index]). EndLoop(). BeginLoop(). RangeBySpeed(0, 400, 70, (value) => imageCharacter.Left = value). EndLoop(). EndParallel(), // Move (Frame-by-Frame) new ImperativeAnimation(_MoveFrameByFrame(_movingForwardCharacter)), // Go and Return AnimationBuilder. BeginSequence(). Add(() => isGoing = true). BeginParallel(). BeginPrematureEndCondition(() => !isGoing). BeginLoop(). // we need to loop the animation or else it will do a single "full-step" and then will // only move forward without walking. But we need to end the animation sometime... we // can cound the steps (bad, as the animation does not end at an exact step) or we can // put a premature end over the entire loop (good). RangeBySpeed(0, _movingForwardCharacter.Count-1, 10, (index) => imageCharacter.Source = _movingForwardCharacter[index]). EndLoop(). EndPrematureEndCondition(). BeginSequence(). RangeBySpeed(0, 400, 70, (value) => imageCharacter.Left = value). Add(() => isGoing = false). EndSequence(). EndParallel(). BeginParallel(). BeginPrematureEndCondition(() => isGoing). BeginLoop(). RangeBySpeed(_movingForwardCharacter.Count-1, 0, 10, (index) => imageCharacter.Source = _movingForwardCharacter[index]). EndLoop(). EndPrematureEndCondition(). BeginSequence(). RangeBySpeed(400, 0, 70, (value) => imageCharacter.Left = value). Add(() => isGoing = true). EndSequence(). EndParallel(). EndSequence(), // Go, Turn and Return AnimationBuilder. BeginSequence(). Add(() => isGoing = true). BeginParallel(). BeginPrematureEndCondition(() => !isGoing). BeginLoop(). // we need to loop the animation or else it will do a single "full-step" and then will // only move forward without walking. But we need to end the animation sometime... we // can cound the steps (bad, as the animation does not end at an exact step) or we can // put a premature end over the entire loop (good). RangeBySpeed(0, _movingForwardCharacter.Count-1, 10, (index) => imageCharacter.Source = _movingForwardCharacter[index]). EndLoop(). EndPrematureEndCondition(). BeginSequence(). RangeBySpeed(0, 400, 70, (value) => imageCharacter.Left = value). Add(() => isGoing = false). EndSequence(). EndParallel(). Range(1.0, -1.0, 1, (value) => imageCharacter.ScaleX = value). BeginParallel(). BeginPrematureEndCondition(() => isGoing). BeginLoop(). // Different from the last full-animation, we continue "going forward". RangeBySpeed(0, _movingForwardCharacter.Count-1, 10, (index) => imageCharacter.Source = _movingForwardCharacter[index]). EndLoop(). EndPrematureEndCondition(). BeginSequence(). RangeBySpeed(400, 0, 70, (value) => imageCharacter.Left = value). Add(() => isGoing = true). EndSequence(). EndParallel(). Range(-1.0, 1.0, 1, (value) => imageCharacter.ScaleX = value). EndSequence(), // Go, Turn and Return (* walking while turning). // This animation is similar to the previous 2, but in this case the character is always walking, even // when the animation is "turning" to the opposite side. AnimationBuilder. BeginParallel(). BeginLoop(). RangeBySpeed(0, _movingForwardCharacter.Count-1, 10, (index) => imageCharacter.Source = _movingForwardCharacter[index]). EndLoop(). BeginLoop(). BeginSequence(). RangeBySpeed(0, 400, 70, (value) => imageCharacter.Left = value). Range(1.0, -1.0, 1, (value) => imageCharacter.ScaleX = value). RangeBySpeed(400, 0, 70, (value) => imageCharacter.Left = value). Range(-1.0, 1.0, 1, (value) => imageCharacter.ScaleX = value). EndSequence(). EndLoop(). EndParallel() }; listboxIntermediaryAnimation.SelectionChanged += listboxIntermediaryAnimation_SelectionChanged; } private IEnumerable<IAnimation> _ImperativeAnimation() { Random random = new Random(); while(true) { Point origin = new Point(Canvas.GetLeft(circle), Canvas.GetTop(circle)); Point destination = new Point(random.Next(450), random.Next(450)); yield return AnimationBuilder.RangeBySpeed(origin, destination, 150, _SetLeftAndTop); } } private void _SetLeftAndTop(Point point) { Canvas.SetLeft(circle, point.X); Canvas.SetTop(circle, point.Y); } private IEnumerable<IAnimation> _FrameBasedAnimation() { var helper = FrameBasedAnimationHelper.CreateByFps(100); while(true) { double yPosition = 0; double xPosition = 0; double ySpeed = 0.5; while(yPosition < 500) { xPosition++; yPosition += ySpeed; ySpeed += 0.1; Canvas.SetLeft(circle, xPosition); Canvas.SetTop(circle, yPosition); yield return helper.WaitNextFrame(); } } } private void listboxBasicAnimation_SelectionChanged(object sender, SelectionChangedEventArgs e) { _SetBasicAnimation(); } private void _SetBasicAnimation() { Canvas.SetLeft(circle, 0); Canvas.SetTop(circle, 0); circle.Fill = Brushes.Black; if (_animation != null) _animation.Reset(); _animation = _basicAnimations[listboxBasicAnimation.SelectedIndex]; } private void listboxIntermediaryAnimation_SelectionChanged(object sender, SelectionChangedEventArgs e) { _SetIntermediaryAnimation(); } private void _SetIntermediaryAnimation() { imageCharacter.Left = 0; imageCharacter.Top = 0; imageCharacter.ScaleX = 1; if (_animation != null) _animation.Reset(); _animation = _intermediaryAnimations[listboxIntermediaryAnimation.SelectedIndex]; } private ReadOnlyCollection<BitmapFrame> _LoadCharacter(string path) { using(var stream = File.OpenRead(path)) { var decoder = GifBitmapDecoder.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); var frames = decoder.Frames; return frames; } } private IEnumerable<IAnimation> _MoveFrameByFrame(ReadOnlyCollection<BitmapFrame> character) { var helper = FrameBasedAnimationHelper.CreateByFps(80); int frameCount = character.Count*7; int frameIndex = 0; imageCharacter.Top = canvasIntermediary.ActualHeight - character[0].Height; while(true) { for(int left=0; left<400; left++) { frameIndex++; if (frameIndex >= frameCount) frameIndex = 0; imageCharacter.Source = character[frameIndex/7]; imageCharacter.Left = left; yield return helper.WaitNextFrame(); } } } private void tabItemAdvanced_RequestBringIntoView(object sender, RequestBringIntoViewEventArgs e) { if (_animation != null) _animation.Reset(); _animation = new ImperativeAnimation(_AdvancedAnimation()); } private int _direction = 0; private bool _isUpPressed; private IEnumerable<IAnimation> _AdvancedAnimation() { var helper = FrameBasedAnimationHelper.CreateByFps(80); canvasAdvanced.Focus(); var canvasChildren = canvasAdvanced.Children; double playerLeft = 0; double playerScale = 1; var playerCharacter = new ImageWithShadow(); playerCharacter.Left = playerLeft; playerCharacter.Top = 300; var otherCharacter = new ImageWithShadow(); otherCharacter.ScaleX = -1; otherCharacter.Left = 350; otherCharacter.Top = 300; var presentationAnimation = AnimationBuilder. BeginSequence(). Add(_ShowText("This is an interactive animation.\r\nPress the Left, Up and Right arrows to Move.")). Add(_ShowText("Yet this is not a game, the other character will only flee from you.")). EndSequence(); bool ending = false; bool jumping = false; try { // This animation will run in parallel to the actual imperative animaion. // It is "subordinated" and so, if this animation is ended prematurely, such // parallel animation will also end prematurely. // This is different than adding the animation to the WpfAnimationManager directly. // Also, there is an additional difference, as time modifiers that are affecting // this animation will also affect its subordinated parallel (even if this is not // happening in this sample application). ImperativeAnimation.AddSubordinatedParallel(presentationAnimation); canvasChildren.Add(playerCharacter); canvasChildren.Add(otherCharacter); canvasAdvanced.PreviewKeyDown += canvasAdvanced_PreviewKeyDown; canvasAdvanced.PreviewKeyUp += canvasAdvanced_PreviewKeyUp; int actualMovingFrame = 0; int totalMovingFrames = _movingForwardCharacter.Count * 8; int totalWaitingFrames = _waitingCharacter.Count * 8; int actualWaitingFrame = totalWaitingFrames; bool running = true; while(running) { actualWaitingFrame++; if (actualWaitingFrame >= totalWaitingFrames) actualWaitingFrame = 0; int actualRealFrame = actualWaitingFrame / 8; otherCharacter.Source = _waitingCharacter[actualRealFrame]; if (_isUpPressed && !jumping) { jumping = true; Action<double> setTop = (value) => playerCharacter.JumpingHeight = value; var animation = AnimationBuilder.BeginSequence(). Range(0, 100, 0.3, setTop). Range(100, 0, 0.3, setTop). Add(() => jumping = false). EndSequence(); ImperativeAnimation.AddSubordinatedParallel(animation); } if (_direction == 0) playerCharacter.Source = _waitingCharacter[actualRealFrame]; else { bool canMove = false; if (_direction < 0) { if (playerScale > -1) { playerScale -= 0.1; if (playerScale < -1) playerScale = -1; } else canMove = true; playerCharacter.ScaleX = playerScale; } else { if (playerScale < 1) { playerScale += 0.1; if (playerScale > 1) playerScale = 1; } else canMove = true; playerCharacter.ScaleX = playerScale; } if (canMove) { actualMovingFrame++; if (actualMovingFrame >= totalMovingFrames) actualMovingFrame = 0; playerCharacter.Source = _movingForwardCharacter[actualMovingFrame/8]; playerLeft += _direction * 1; if (playerLeft < 0) playerLeft = 0; // The typical invisible barrier in which the character // continues walking without moving. playerCharacter.Left = playerLeft; if (playerLeft > 250 && !ending) { // this is to avoid playing the ending animation more // than once. ending = true; // and this is just in case the presentation is still running, // as we don't want messages to overlap. presentationAnimation.Dispose(); Action<double> setLeft = (value) => otherCharacter.Left = value; Action<double> setTop = (value) => otherCharacter.Top = value; var finalAnimation = AnimationBuilder. BeginSequence(). BeginParallel(). Range(350, 370, 0.10, setLeft). Range(300, 280, 0.10, setTop). EndParallel(). BeginParallel(). Range(370, 390, 0.10, setLeft). Range(280, 300, 0.10, setTop). EndParallel(). Range(-1.0, 1.0, 0.5, (value) => otherCharacter.ScaleX = value). Range(390, 510, 0.5, setLeft). Add(_ShowText("The other character fled from you...")). Add(_ShowText("... he is a COWARD!!!")). Add(() => running=false). EndSequence(); ImperativeAnimation.AddSubordinatedParallel(finalAnimation); } } } yield return helper.WaitNextFrame(); } } finally { canvasAdvanced.PreviewKeyDown -= canvasAdvanced_PreviewKeyDown; canvasChildren.Remove(playerCharacter); canvasChildren.Remove(otherCharacter); } } void canvasAdvanced_PreviewKeyDown(object sender, KeyEventArgs e) { switch(e.Key) { case Key.Left: _direction = -1; e.Handled = true; break; case Key.Right: _direction = 1; e.Handled = true; break; case Key.Up: _isUpPressed = true; e.Handled = true; break; } } void canvasAdvanced_PreviewKeyUp(object sender, KeyEventArgs e) { switch(e.Key) { case Key.Left: case Key.Right: e.Handled = true; _direction = 0; break; case Key.Up: e.Handled = true; _isUpPressed = false; break; } } private IEnumerable<IAnimation> _ShowText(string message) { var textBlock = new TextBlock(); try { textBlock.Text = message; canvasAdvanced.Children.Add(textBlock); Action<double> setOpacity = (value) => textBlock.Opacity = value; yield return AnimationBuilder. BeginSequence(). Range(0.0, 1.0, 1, setOpacity). Wait(2). Range(1.0, 0.0, 1, setOpacity). EndSequence(); } finally { canvasAdvanced.Children.Remove(textBlock); } } } }
flysnoopy1984/DDZ_Live
ReferenceCode/Pfz.AnimationManagement.2013_08_25/Pfz.AnimationManagement/WpfSample/MainWindow.xaml.cs
C#
mit
26,050
package fables.kotlin.jee.rest; import fables.kotlin.jee.business.KittenBusinessService; import fables.kotlin.jee.business.KittenEntity; import javax.inject.Inject; import javax.ws.rs.*; /** * JSON REST CRud service. * JEE will first create one noarg instance, and then injected instances. * * @author Zeljko Trogrlic */ @Path("kitten") public class KittenRestService { @Inject protected KittenBusinessService kittenBusinessService; @GET @Path("{id}") @Produces({"application/json"}) public KittenRest find( @PathParam("id") final int id ) { return kittenBusinessService .find(id) .map(kittenEntity -> new KittenRest(kittenEntity.getName(), kittenEntity.getCuteness())) .orElseThrow(() -> new NotFoundException("ID " + id + " not found")); } @POST @Produces({"application/json"}) public Integer add(KittenRest kittenRest) { KittenEntity kittenEntity = new KittenEntity(kittenRest.getName(), kittenRest.getCuteness()); return kittenBusinessService.add(kittenEntity); } }
zeljkot/fables-kotlin
jee/java/src/main/java/fables/kotlin/jee/rest/KittenRestService.java
Java
mit
1,047
<?php return array( /* |-------------------------------------------------------------------------- | Application Debug Mode |-------------------------------------------------------------------------- | | When your application is in debug mode, detailed error messages with | stack traces will be shown on every error that occurs within your | application. If disabled, a simple generic error page is shown. | */ 'debug' => true, /* |-------------------------------------------------------------------------- | Application URL |-------------------------------------------------------------------------- | | This URL is used by the console to properly generate URLs when using | the Artisan command line tool. You should set this to the root of | your application so that it is used when running Artisan tasks. | */ 'url' => 'http://localhost/web.api', /* |-------------------------------------------------------------------------- | Application Timezone |-------------------------------------------------------------------------- | | Here you may specify the default timezone for your application, which | will be used by the PHP date and date-time functions. We have gone | ahead and set this to a sensible default for you out of the box. | */ 'timezone' => 'UTC', /* |-------------------------------------------------------------------------- | Application Locale Configuration |-------------------------------------------------------------------------- | | The application locale determines the default locale that will be used | by the translation service provider. You are free to set this value | to any of the locales which will be supported by the application. | */ 'locale' => 'en', /* |-------------------------------------------------------------------------- | Encryption Key |-------------------------------------------------------------------------- | | This key is used by the Illuminate encrypter service and should be set | to a random, 32 character string, otherwise these encrypted strings | will not be safe. Please do this before deploying an application! | */ 'key' => 'GZxF3oujFlAL4GVeC1n57tAzXLWK0wsv', /* |-------------------------------------------------------------------------- | Autoloaded Service Providers |-------------------------------------------------------------------------- | | The service providers listed here will be automatically loaded on the | request to your application. Feel free to add your own services to | this array to grant expanded functionality to your applications. | */ 'providers' => array( 'Illuminate\Foundation\Providers\ArtisanServiceProvider', 'Illuminate\Auth\AuthServiceProvider', 'Illuminate\Cache\CacheServiceProvider', 'Illuminate\Session\CommandsServiceProvider', 'Illuminate\Foundation\Providers\ConsoleSupportServiceProvider', 'Illuminate\Routing\ControllerServiceProvider', 'Illuminate\Cookie\CookieServiceProvider', 'Illuminate\Database\DatabaseServiceProvider', 'Illuminate\Encryption\EncryptionServiceProvider', 'Illuminate\Filesystem\FilesystemServiceProvider', 'Illuminate\Hashing\HashServiceProvider', 'Illuminate\Html\HtmlServiceProvider', 'Illuminate\Log\LogServiceProvider', 'Illuminate\Mail\MailServiceProvider', 'Illuminate\Database\MigrationServiceProvider', 'Illuminate\Pagination\PaginationServiceProvider', 'Illuminate\Queue\QueueServiceProvider', 'Illuminate\Redis\RedisServiceProvider', 'Illuminate\Remote\RemoteServiceProvider', 'Illuminate\Auth\Reminders\ReminderServiceProvider', 'Illuminate\Database\SeedServiceProvider', 'Illuminate\Session\SessionServiceProvider', 'Illuminate\Translation\TranslationServiceProvider', 'Illuminate\Validation\ValidationServiceProvider', 'Illuminate\View\ViewServiceProvider', 'Illuminate\Workbench\WorkbenchServiceProvider', 'Way\Generators\GeneratorsServiceProvider', 'Aws\Laravel\AwsServiceProvider', 'Intervention\Image\ImageServiceProvider', 'Twilio\Laratwilio\LaratwilioServiceProvider' ), /* |-------------------------------------------------------------------------- | Service Provider Manifest |-------------------------------------------------------------------------- | | The service provider manifest is used by Laravel to lazy load service | providers which are not needed for each request, as well to keep a | list of all of the services. Here, you may set its storage spot. | */ 'manifest' => storage_path().'/meta', /* |-------------------------------------------------------------------------- | Class Aliases |-------------------------------------------------------------------------- | | This array of class aliases will be registered when this application | is started. However, feel free to register as many as you wish as | the aliases are "lazy" loaded so they don't hinder performance. | */ 'aliases' => array( 'App' => 'Illuminate\Support\Facades\App', 'Artisan' => 'Illuminate\Support\Facades\Artisan', 'Auth' => 'Illuminate\Support\Facades\Auth', 'Blade' => 'Illuminate\Support\Facades\Blade', 'Cache' => 'Illuminate\Support\Facades\Cache', 'ClassLoader' => 'Illuminate\Support\ClassLoader', 'Config' => 'Illuminate\Support\Facades\Config', 'Controller' => 'Illuminate\Routing\Controller', 'Cookie' => 'Illuminate\Support\Facades\Cookie', 'Crypt' => 'Illuminate\Support\Facades\Crypt', 'DB' => 'Illuminate\Support\Facades\DB', 'Eloquent' => 'Illuminate\Database\Eloquent\Model', 'Event' => 'Illuminate\Support\Facades\Event', 'File' => 'Illuminate\Support\Facades\File', 'Form' => 'Illuminate\Support\Facades\Form', 'Hash' => 'Illuminate\Support\Facades\Hash', 'HTML' => 'Illuminate\Support\Facades\HTML', 'Input' => 'Illuminate\Support\Facades\Input', 'Lang' => 'Illuminate\Support\Facades\Lang', 'Log' => 'Illuminate\Support\Facades\Log', 'Mail' => 'Illuminate\Support\Facades\Mail', 'Paginator' => 'Illuminate\Support\Facades\Paginator', 'Password' => 'Illuminate\Support\Facades\Password', 'Queue' => 'Illuminate\Support\Facades\Queue', 'Redirect' => 'Illuminate\Support\Facades\Redirect', 'Redis' => 'Illuminate\Support\Facades\Redis', 'Request' => 'Illuminate\Support\Facades\Request', 'Response' => 'Illuminate\Support\Facades\Response', 'Route' => 'Illuminate\Support\Facades\Route', 'Schema' => 'Illuminate\Support\Facades\Schema', 'Seeder' => 'Illuminate\Database\Seeder', 'Session' => 'Illuminate\Support\Facades\Session', 'SSH' => 'Illuminate\Support\Facades\SSH', 'Str' => 'Illuminate\Support\Str', 'URL' => 'Illuminate\Support\Facades\URL', 'Validator' => 'Illuminate\Support\Facades\Validator', 'View' => 'Illuminate\Support\Facades\View', 'AWS' => 'Aws\Laravel\AwsFacade', 'Image' => 'Intervention\Image\Facades\Image', 'Sms' => 'Twilio\Laratwilio\Facades\Laratwilio' ), );
TeenahApp/web.api
app/config/app.php
PHP
mit
7,278
import React, {Component} from 'react'; import PdfJS from './pdfJS'; import Contract from "../../contract"; import Event from '../../event'; import AnnotationLoader from '../../annotator/loader'; class Viewer extends Component { constructor(props) { super(props); this.state = ({ page_no: 0, pdf_url: "", scale: 0, loading: true }); } componentDidMount() { this.subscribe_zoom = Event.subscribe('zoom:change', (scale) => { this.setState({scale: scale}); }); this.updateState(this.props); } updateState(props) { var {page_no, pdf_url} = props.page; var scale = Contract.getPdfScale(); this.setState({ page_no, pdf_url, scale, loading: false }); } componentWillUnmount() { this.subscribe_zoom.remove(); } getPageID() { return 'pdf-' + this.state.page_no; } getAnnotations() { let page = []; let annotations = Contract.getAnnotations(); annotations.result.forEach(annotation=> { if (typeof annotation.shapes == 'object' && this.state.page_no == annotation.page_no) { page.push(annotation); } }); return page; } onPageRendered() { if (!this.annotator) { this.annotator = new AnnotationLoader('.pdf-annotator'); this.annotator.init(); Contract.setAnnotatorInstance(this.annotator); } const annotations = this.getAnnotations(); if (annotations.length > 0) { this.annotator.content.annotator("loadAnnotations", annotations); } Event.publish('annotation:loaded', 'pdf'); } componentWillReceiveProps(props) { this.updateState(props); } shouldComponentUpdate(nextProps, nextState) { return (nextProps.page.page_no !== this.state.page_no || this.state.scale !== nextState.scale); } render() { if (this.state.loading) { return ( <div className="pdf-viewer pdf-annotator"> <div className="pdf-wrapper"> Loading... </div> </div>); } return ( <div className="pdf-viewer pdf-annotator"> <div id={this.getPageID()} className="pdf-wrapper"> <PdfJS onPageRendered={this.onPageRendered.bind(this)} file={this.state.pdf_url} page={this.state.page_no} scale={this.state.scale}/> </div> <a href="#" className="change-view-icon exit-fullscreen"></a> </div> ); } } export default Viewer;
younginnovations/resourcecontracts-rc-subsite
resources/assets/scripts/contract/components/pdf/viewer.js
JavaScript
mit
2,838
var ratio = require('ratio') function error(actual, expected) { return Math.abs(actual - expected) / expected } function approx(target, max) { max = (max || 10) // find a good approximation var best = 1, j, e, result for (var i = 1; i < max; i++) { j = Math.round(i * target) e = error(j / i, target) if (e >= best) continue best = e result = ratio(j, i) } return result } module.exports = approx
agnoster/approx
index.js
JavaScript
mit
474
/* * Copyright (c) 2015 by Rafael Angel Aznar Aparici (rafaaznar at gmail dot com) * * openAUSIAS: The stunning micro-library that helps you to develop easily * AJAX web applications by using Java and jQuery * openAUSIAS is distributed under the MIT License (MIT) * Sources at https://github.com/rafaelaznar/ * * 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. * */ 'use strict'; /* Controllers */ moduloUsuariocursoxusuario.controller('UsuariocursoxusuarioPListController', ['$scope', '$routeParams', 'serverService', '$location', 'redirectService', 'sharedSpaceService', 'checkSessionStorageService', function ($scope, $routeParams, serverService, $location, redirectService, sharedSpaceService, checkSessionStorageService) { checkSessionStorageService.isSessionSessionStoraged(); $scope.visibles = {}; $scope.visibles.id = true; $scope.visibles.titulo = true; $scope.visibles.descripcion = true; $scope.visibles.nota = true; $scope.ob = "usuariocursoxusuario"; $scope.op = "plist"; $scope.title = "Listado de usuariocursoxusuario"; $scope.icon = "fa-file-text-o"; $scope.neighbourhood = 2; if (!$routeParams.page) { $routeParams.page = 1; } if (!$routeParams.rpp) { $routeParams.rpp = 999; } $scope.numpage = $routeParams.page; $scope.rpp = $routeParams.rpp; $scope.predicate = 'id'; $scope.reverse = false; $scope.orderCliente = function (predicate) { $scope.predicate = predicate; $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false; }; $scope.getListaCursos = function () { serverService.getDataFromPromise(serverService.promise_getListaCursos()).then(function (data) { redirectService.checkAndRedirect(data); if (data.status != 200) { $scope.statusListaCursos = "Error en la recepción de datos del servidor"; } else { $scope.listaCursos = data.message; for (var i = 0; i < $scope.listaCursos.length; i++) { if (i > 0) { if ($scope.listaCursos[i].obj_curso.id == $scope.listaCursos[i - 1].obj_curso.id) { $scope.listaCursos[i - 1].alProfesores.push($scope.listaCursos[i].alProfesores[0]); $scope.listaCursos.splice(i, 1); i = i - 1; } } } } }); }; //$scope.rppPad = serverService.getNrppBar($scope.ob, $scope.op, $scope.numpage, $scope.rpp); // $scope.order = $routeParams.order; // $scope.ordervalue = $routeParams.value; // // $scope.filter = $routeParams.filter; // $scope.filteroperator = $routeParams.filteroperator; // $scope.filtervalue = $routeParams.filtervalue; // // $scope.systemfilter = $routeParams.systemfilter; // $scope.systemfilteroperator = $routeParams.systemfilteroperator; // $scope.systemfiltervalue = $routeParams.systemfiltervalue; $scope.order = ""; $scope.ordervalue = ""; $scope.filter = "id"; $scope.filteroperator = "like"; $scope.filtervalue = ""; $scope.systemfilter = ""; $scope.systemfilteroperator = ""; $scope.systemfiltervalue = ""; $scope.params = ""; $scope.paramsWithoutOrder = ""; $scope.paramsWithoutFilter = ""; $scope.paramsWithoutSystemFilter = ""; if ($routeParams.order && $routeParams.ordervalue) { $scope.order = $routeParams.order; $scope.ordervalue = $routeParams.ordervalue; $scope.orderParams = "&order=" + $routeParams.order + "&ordervalue=" + $routeParams.ordervalue; $scope.paramsWithoutFilter += $scope.orderParams; $scope.paramsWithoutSystemFilter += $scope.orderParams; } else { $scope.orderParams = ""; } if ($routeParams.filter && $routeParams.filteroperator && $routeParams.filtervalue) { $scope.filter = $routeParams.filter; $scope.filteroperator = $routeParams.filteroperator; $scope.filtervalue = $routeParams.filtervalue; $scope.filterParams = "&filter=" + $routeParams.filter + "&filteroperator=" + $routeParams.filteroperator + "&filtervalue=" + $routeParams.filtervalue; $scope.paramsWithoutOrder += $scope.filterParams; $scope.paramsWithoutSystemFilter += $scope.filterParams; } else { $scope.filterParams = ""; } if ($routeParams.systemfilter && $routeParams.systemfilteroperator && $routeParams.systemfiltervalue) { $scope.systemFilterParams = "&systemfilter=" + $routeParams.systemfilter + "&systemfilteroperator=" + $routeParams.systemfilteroperator + "&systemfiltervalue=" + $routeParams.systemfiltervalue; $scope.paramsWithoutOrder += $scope.systemFilterParams; $scope.paramsWithoutFilter += $scope.systemFilterParams; } else { $scope.systemFilterParams = ""; } $scope.params = ($scope.orderParams + $scope.filterParams + $scope.systemFilterParams); //$scope.paramsWithoutOrder = $scope.paramsWithoutOrder.replace('&', '?'); //$scope.paramsWithoutFilter = $scope.paramsWithoutFilter.replace('&', '?'); //$scope.paramsWithoutSystemFilter = $scope.paramsWithoutSystemFilter.replace('&', '?'); $scope.params = $scope.params.replace('&', '?'); $scope.getCursosPage = function () { serverService.getDataFromPromise(serverService.promise_getSomeUsuariocursoXUsuario($scope.ob, $scope.rpp, $scope.numpage, $scope.filterParams, $scope.orderParams, $scope.systemFilterParams)).then(function (data) { redirectService.checkAndRedirect(data); if (data.status != 200) { $scope.status = "Error en la recepción de datos del servidor"; } else { $scope.pages = data.message.pages.message; if (parseInt($scope.numpage) > parseInt($scope.pages)) $scope.numpage = $scope.pages; $scope.page = data.message.page.message; $scope.registers = data.message.registers.message; $scope.status = ""; } }); } $scope.getCursosPage(); // $scope.pages = serverService.getPages($scope.ob, $scope.rpp, null, null, null, null, null, null).then(function (datos5) { // $scope.pages = data['data']; // if (parseInt($scope.page) > parseInt($scope.pages)) // $scope.page = $scope.pages; // //$location.path( "#/clientes/" +$scope.pages + "/" + $scope.pages); // }); // $scope.$watch('pages', function () { // $scope.$broadcast('myApp.construirBotoneraPaginas'); // }, true) // $scope.getRangeArray = function (lowEnd, highEnd) { var rangeArray = []; for (var i = lowEnd; i <= highEnd; i++) { rangeArray.push(i); } return rangeArray; }; $scope.evaluateMin = function (lowEnd, highEnd) { return Math.min(lowEnd, highEnd); }; $scope.evaluateMax = function (lowEnd, highEnd) { return Math.max(lowEnd, highEnd); }; $scope.dofilter = function () { if ($scope.filter != "" && $scope.filteroperator != "" && $scope.filtervalue != "") { //console.log('#/' + $scope.ob + '/' + $scope.op + '/' + $scope.numpage + '/' + $scope.rpp + '?filter=' + $scope.filter + '&filteroperator=' + $scope.filteroperator + '&filtervalue=' + $scope.filtervalue + $scope.paramsWithoutFilter); if ($routeParams.order && $routeParams.ordervalue) { if ($routeParams.systemfilter && $routeParams.systemfilteroperator) { $location.path($scope.ob + '/' + $scope.op + '/' + $scope.numpage + '/' + $scope.rpp).search('filter', $scope.filter).search('filteroperator', $scope.filteroperator).search('filtervalue', $scope.filtervalue).search('order', $routeParams.order).search('ordervalue', $routeParams.ordervalue).search('systemfilter', $routeParams.systemfilter).search('systemfilteroperator', $routeParams.systemfilteroperator).search('systemfiltervalue', $routeParams.systemfiltervalue); } else { $location.path($scope.ob + '/' + $scope.op + '/' + $scope.numpage + '/' + $scope.rpp).search('filter', $scope.filter).search('filteroperator', $scope.filteroperator).search('filtervalue', $scope.filtervalue).search('order', $routeParams.order).search('ordervalue', $routeParams.ordervalue); } } else { $location.path($scope.ob + '/' + $scope.op + '/' + $scope.numpage + '/' + $scope.rpp).search('filter', $scope.filter).search('filteroperator', $scope.filteroperator).search('filtervalue', $scope.filtervalue); } } return false; }; //$scope.$on('myApp.construirBotoneraPaginas', function () { // $scope.botoneraPaginas = serverService.getPaginationBar($scope.ob, $scope.op, $scope.page, $scope.pages, 2, $scope.rpp); //}) // // $scope.prettyFieldNames = serverService.getPrettyFieldNames($scope.ob).then(function (datos4) { // datos4['data'].push('acciones'); // $scope.prettyFieldNames = datos4['data']; // }); // // $scope.clientes = serverService.getPage($scope.ob, $scope.page, null, null, $scope.rpp, null, null, null, null, null, null).then(function (datos3) { // $scope.clientes = datos3['list']; // // }); // // $scope.fieldNames = serverService.getFieldNames($scope.ob).then(function (datos6) { // $scope.fieldNames = datos6['data']; // $scope.selectedFilterFieldName = null; // }); // // // $scope.$watch('numPagina', function () { // $scope.$broadcast('myApp.construirPagina'); // }, true) // // $scope.$on('myApp.construirPagina', function () { // // $scope.clientes = serverService.getPage($scope.ob, $scope.page, null, null, $scope.rpp, null, null, null, null, null, null).then(function (datos3) { // $scope.clientes = datos3['list']; // // }); // // }) // // $scope.filtrar = function () { // alert("f") // // // }; // $scope.$watch('filteroperator', function () { // console.log($scope.filter); // console.log($scope.filteroperator); // console.log($scope.filtervalue); // }, true) $scope.newObj = function (args) { $scope.objEdit = {}; $scope.position = undefined; switch (args.strClass) { case 'curso': $scope.objEdit.id = 0; break; case 'inscribirse': $scope.mostrarPass={}; if (sharedSpaceService.getFase() == 0) { serverService.getDataFromPromise(serverService.promise_getOne('curso', args.id)).then(function (data) { $scope.objEdit = data.message; $scope.objEdit.password; $scope.mostrarPass.mostrar=true; $scope.mostrarPass.idCurso=args.id; }); } else { $scope.objEdit = sharedSpaceService.getObject(); sharedSpaceService.setFase(0); } break; } ; }; $scope.edit = function (args) { $scope.objEdit = {}; switch (args.strClass) { case 'curso': $scope.position = $scope.page.alUsuariocursos.indexOf(args.levelOne); if (sharedSpaceService.getFase() == 0) { serverService.getDataFromPromise(serverService.promise_getOne(args.strClass, args.id)).then(function (data) { $scope.objEdit = data.message; //date conversion }); } else { $scope.objEdit = sharedSpaceService.getObject(); sharedSpaceService.setFase(0); } break; } ; }; $scope.save = function (type) { switch (type) { case 'curso': serverService.getDataFromPromise(serverService.promise_setCurso('curso', {json: JSON.stringify(serverService.array_identificarArray($scope.objEdit))})).then(function (data) { redirectService.checkAndRedirect(data); if (data.status = 200) { $scope.result = data; if ($scope.position !== undefined) { $scope.page.alUsuariocursos[$scope.position].obj_curso = $scope.objEdit; $scope.position = undefined; } else { $scope.objFinal = {}; $scope.objFinal.id = $scope.result.message.idUsuarioCurso; $scope.objFinal.obj_curso = {id: $scope.result.message.idCurso}; $scope.objFinal.obj_curso.titulo = $scope.objEdit.titulo; $scope.objFinal.obj_curso.descripcion = $scope.objEdit.descripcion; $scope.page.alUsuariocursos.push($scope.objFinal); } } }); break; case 'inscribirse': serverService.getDataFromPromise(serverService.promise_setUsuariocurso('usuariocurso', {json: JSON.stringify(serverService.array_identificarArray($scope.objEdit))})).then(function (data) { redirectService.checkAndRedirect(data); if (data.status = 200) { $scope.getCursosPage(); $scope.mostrarContraseña.mostrar=undefined; $scope.mostrarContraseña.idCurso=undefined; } }); break; } ; }; $scope.remove = function (type, id, idUsuarioCurso) { switch (type) { case 'curso': serverService.getDataFromPromise(serverService.promise_removeCurso(type, id, idUsuarioCurso)).then(function (data) { redirectService.checkAndRedirect(data); if (data.status = 200) { $scope.result = data; $scope.page.alUsuariocursos.splice($scope.position, 1); $scope.position = undefined; } }); break; } }; }]);
Ilthur/boletinweb
src/main/webapp/js/usuariocursoxusuario/plist.js
JavaScript
mit
16,663
/** * Write the input to the paramsified file * * --- * INPUTS: * * - FILES * Write the list of files to the paramsified file (line feed after each filename). * * - STRINGS * Write the strings (concatenated) to the paramsified file. * * - STRING * Write the string to the paramsified file. * * - UNDEFINED * Touch the file. * * OUTPUT: * * - FILES * The filename that was written. * --- * * @module tasks * @submodule write */ var State = require('../state'), path = require('path'), mkdirp = require('mkdirp').mkdirp, fs = require('fs'); /** * Write out the input to the destination filename. * * This can only apply to single string inputs. * * @method writeTask * @param options {Object} Write task options * @param options.name {String} Filename to write to. * @param options.encoding {String} [default='utf8'] Encoding to use when writing the file * @param options.mkdir {Boolean} [default=true] Make destination directory if it does not exist * @param options.dirmode {String} [default='0755'] Create new directories with this mode (chmod) * @param status {EventEmitter} Status object, handles 'complete' and 'failed' task exit statuses. * @param logger {winston.Logger} Logger instance, if additional logging required (other than task exit status) * @return {undefined} * @public */ function writeTask(options, status, logger) { var self = this, pathname = path.resolve(path.dirname(options.name)), name = options.name, encoding = options && options.encoding || 'utf8', mkdir = options && options.mkdir || true, dirmode = options && options.dirmode || '0755'; // Write the content to the specified file. function writeFile(filename, data) { fs.writeFile(filename, data, encoding, function(err) { if (err) { status.emit('failed', 'write', 'error writing destination file: ' + err); } else { self._state.set(State.TYPES.FILES, [ filename ]); status.emit('complete', 'write', 'wrote ' + filename); } }); } // Create the paramsified path if it does not exist. function mkdirIfNotExist(filename, callback) { path.exists(filename, function(exists) { if (!exists) { if (mkdir === true) { mkdirp(filename, dirmode, function(err) { if (err) { callback(err); } else { callback(null); } }); } else { callback('tried to write a file to a non-existing directory and mkdir is false'); } } else { callback(null); } }); } switch (this._state.get().type) { case State.TYPES.FILES: mkdirIfNotExist(pathname, function(err) { if (err) { status.emit('failed', 'write', 'error creating destination directory: ' + err); } else { writeFile(name, self._state.get().value.join("\n")); } }); break; case State.TYPES.STRING: mkdirIfNotExist(pathname, function(err) { if (err) { status.emit('failed', 'write', 'error creating destination directory: ' + err); } else { writeFile(name, self._state.get().value); } }); break; case State.TYPES.STRINGS: mkdirIfNotExist(pathname, function(err) { if (err) { status.emit('failed', 'write', 'error creating destination directory: ' + err); } else { writeFile(name, self._state.get().value.join("")); } }); break; case State.TYPES.UNDEFINED: mkdirIfNotExist(pathname, function(err) { if (err) { status.emit('failed', 'write', 'error creating destination directory: ' + err); } else { writeFile(name, ""); } }); break; default: status.emit('failed', 'write', 'unrecognised input type: ' + this._type); break; } } exports.tasks = { 'write' : { callback: writeTask } };
mosen/buildy
lib/buildy/tasks/write.js
JavaScript
mit
4,521
# frozen_string_literal: true require 'grape/router' require 'grape/api/instance' module Grape # The API class is the primary entry point for creating Grape APIs. Users # should subclass this class in order to build an API. class API # Class methods that we want to call on the API rather than on the API object NON_OVERRIDABLE = (Class.new.methods + %i[call call! configuration compile! inherited]).freeze class << self attr_accessor :base_instance, :instances # Rather than initializing an object of type Grape::API, create an object of type Instance def new(*args, &block) base_instance.new(*args, &block) end # When inherited, will create a list of all instances (times the API was mounted) # It will listen to the setup required to mount that endpoint, and replicate it on any new instance def inherited(api, base_instance_parent = Grape::API::Instance) api.initial_setup(base_instance_parent) api.override_all_methods! make_inheritable(api) end # Initialize the instance variables on the remountable class, and the base_instance # an instance that will be used to create the set up but will not be mounted def initial_setup(base_instance_parent) @instances = [] @setup = Set.new @base_parent = base_instance_parent @base_instance = mount_instance end # Redefines all methods so that are forwarded to add_setup and be recorded def override_all_methods! (base_instance.methods - NON_OVERRIDABLE).each do |method_override| define_singleton_method(method_override) do |*args, &block| add_setup(method_override, *args, &block) end end end # Configure an API from the outside. If a block is given, it'll pass a # configuration hash to the block which you can use to configure your # API. If no block is given, returns the configuration hash. # The configuration set here is accessible from inside an API with # `configuration` as normal. def configure config = @base_instance.configuration if block_given? yield config self else config end end # This is the interface point between Rack and Grape; it accepts a request # from Rack and ultimately returns an array of three values: the status, # the headers, and the body. See [the rack specification] # (http://www.rubydoc.info/github/rack/rack/master/file/SPEC) for more. # NOTE: This will only be called on an API directly mounted on RACK def call(*args, &block) instance_for_rack.call(*args, &block) end # Allows an API to itself be inheritable: def make_inheritable(api) # When a child API inherits from a parent API. def api.inherited(child_api) # The instances of the child API inherit from the instances of the parent API Grape::API.inherited(child_api, base_instance) end end # Alleviates problems with autoloading by tring to search for the constant def const_missing(*args) if base_instance.const_defined?(*args) base_instance.const_get(*args) else super end end # The remountable class can have a configuration hash to provide some dynamic class-level variables. # For instance, a description could be done using: `desc configuration[:description]` if it may vary # depending on where the endpoint is mounted. Use with care, if you find yourself using configuration # too much, you may actually want to provide a new API rather than remount it. def mount_instance(**opts) instance = Class.new(@base_parent) instance.configuration = Grape::Util::EndpointConfiguration.new(opts[:configuration] || {}) instance.base = self replay_setup_on(instance) instance end # Replays the set up to produce an API as defined in this class, can be called # on classes that inherit from Grape::API def replay_setup_on(instance) @setup.each do |setup_step| replay_step_on(instance, setup_step) end end def respond_to?(method, include_private = false) super(method, include_private) || base_instance.respond_to?(method, include_private) end def respond_to_missing?(method, include_private = false) base_instance.respond_to?(method, include_private) end def method_missing(method, *args, &block) # If there's a missing method, it may be defined on the base_instance instead. if respond_to_missing?(method) base_instance.send(method, *args, &block) else super end end def compile! require 'grape/eager_load' instance_for_rack.compile! # See API::Instance.compile! end private def instance_for_rack if never_mounted? base_instance else mounted_instances.first end end # Adds a new stage to the set up require to get a Grape::API up and running def add_setup(method, *args, &block) setup_step = { method: method, args: args, block: block } @setup += [setup_step] last_response = nil @instances.each do |instance| last_response = replay_step_on(instance, setup_step) end last_response end def replay_step_on(instance, setup_step) return if skip_immediate_run?(instance, setup_step[:args]) args = evaluate_arguments(instance.configuration, *setup_step[:args]) response = instance.send(setup_step[:method], *args, &setup_step[:block]) if skip_immediate_run?(instance, [response]) response else evaluate_arguments(instance.configuration, response).first end end # Skips steps that contain arguments to be lazily executed (on re-mount time) def skip_immediate_run?(instance, args) instance.base_instance? && (any_lazy?(args) || args.any? { |arg| arg.is_a?(Hash) && any_lazy?(arg.values) }) end def any_lazy?(args) args.any? { |argument| argument.respond_to?(:lazy?) && argument.lazy? } end def evaluate_arguments(configuration, *args) args.map do |argument| if argument.respond_to?(:lazy?) && argument.lazy? argument.evaluate_from(configuration) elsif argument.is_a?(Hash) argument.transform_values { |value| evaluate_arguments(configuration, value).first } elsif argument.is_a?(Array) evaluate_arguments(configuration, *argument) else argument end end end def never_mounted? mounted_instances.empty? end def mounted_instances instances - [base_instance] end end end end
dblock/grape
lib/grape/api.rb
Ruby
mit
7,030
# frozen_string_literal: true module RuboCop module Formatter # This formatter formats report data in clang style. # The precise location of the problem is shown together with the # relevant source code. class ClangStyleFormatter < SimpleTextFormatter ELLIPSES = '...' def report_file(file, offenses) offenses.each { |offense| report_offense(file, offense) } end private def report_offense(file, offense) output.printf( "%<path>s:%<line>d:%<column>d: %<severity>s: %<message>s\n", path: cyan(smart_path(file)), line: offense.line, column: offense.real_column, severity: colored_severity_code(offense), message: message(offense) ) begin return unless valid_line?(offense) report_line(offense.location) report_highlighted_area(offense.highlighted_area) rescue IndexError # rubocop:disable Lint/SuppressedException # range is not on a valid line; perhaps the source file is empty end end def valid_line?(offense) !offense.location.source_line.blank? end def report_line(location) source_line = location.source_line if location.first_line == location.last_line output.puts(source_line) else output.puts("#{source_line} #{yellow(ELLIPSES)}") end end def report_highlighted_area(highlighted_area) output.puts("#{' ' * highlighted_area.begin_pos}" \ "#{'^' * highlighted_area.size}") end end end end
smakagon/rubocop
lib/rubocop/formatter/clang_style_formatter.rb
Ruby
mit
1,635
package me.nereo.multi_image_selector; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.graphics.RectF; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.support.annotation.Nullable; import android.text.TextUtils; import android.util.DisplayMetrics; import android.util.Log; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.facebook.common.executors.CallerThreadExecutor; import com.facebook.common.references.CloseableReference; import com.facebook.datasource.DataSource; import com.facebook.drawee.backends.pipeline.Fresco; import com.facebook.drawee.controller.AbstractDraweeController; import com.facebook.drawee.drawable.ProgressBarDrawable; import com.facebook.drawee.drawable.ScalingUtils; import com.facebook.drawee.generic.GenericDraweeHierarchy; import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder; import com.facebook.drawee.interfaces.DraweeController; import com.facebook.imagepipeline.core.ImagePipeline; import com.facebook.imagepipeline.datasource.BaseBitmapDataSubscriber; import com.facebook.imagepipeline.image.CloseableImage; import com.facebook.imagepipeline.request.ImageRequest; import com.facebook.imagepipeline.request.ImageRequestBuilder; import java.io.File; import me.nereo.multi_image_selector.view.ClipImageBorderView; import me.nereo.multi_image_selector.view.zoomable.DefaultZoomableController; import me.nereo.multi_image_selector.view.zoomable.ZoomableDraweeView; /** * Created by sunny on 2015/12/22. * 图片裁剪 */ public class ClipPhotoActivity extends Activity implements OnClickListener, IBitmapShow { public static final String TAG = ClipPhotoActivity.class.getSimpleName(); private String imgUrl; private TextView mTitle; private Button mCommit; private ImageView mBack; private ZoomableDraweeView mGestureImageView; private ClipImageBorderView clip_image_borderview; //图片的平移与缩放 float mCurrentScale; float last_x = -1; float last_y = -1; boolean move = false; public static void startClipPhotoActivity(Context context, String uri) { Intent targetIntent = new Intent(context, ClipPhotoActivity.class); targetIntent.putExtra(TAG, uri); context.startActivity(targetIntent); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_clip_photo); setTitle("图片裁剪"); initIntentParams(); } @Override protected void onStart() { super.onStart(); } @Override protected void onResume() { super.onResume(); /* new Handler(Looper.getMainLooper()).postDelayed(new Runnable() { @Override public void run() { getBitmap(); } },100);*/ getBitmap(); } private void getBitmap() { int width = clip_image_borderview.getWidth(); int height = clip_image_borderview.getHeight(); Log.e("with", "with===" + width + "\nheight===" + height); DisplayMetrics displayMetrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); int screenWidth = displayMetrics.widthPixels; int screenHeight = displayMetrics.heightPixels; /* FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(screenWidth - 40, screenWidth - 40); layoutParams.gravity = Gravity.CENTER; mGestureImageView.setLayoutParams(layoutParams);*/ if (!TextUtils.isEmpty(imgUrl)) { // ImageLoaderUtils.load(imgUrl,mGestureImageView); //解决图片倒置 ImageRequest imageRequest = ImageRequestBuilder .newBuilderWithSource(Uri.parse("file://" + imgUrl)) .setAutoRotateEnabled(true).build(); //解决图片多指缩放 DraweeController controller = Fresco.newDraweeControllerBuilder() .setImageRequest(imageRequest) .setTapToRetryEnabled(true) .build(); /* DefaultZoomableController controller = DefaultZoomableController.newInstance(); controller.setEnabled(true);*/ GenericDraweeHierarchy hierarchy = new GenericDraweeHierarchyBuilder(getResources()) .setActualImageScaleType(ScalingUtils.ScaleType.FIT_CENTER) .setProgressBarImage(new ProgressBarDrawable()) .build(); mGestureImageView.setController(controller); mGestureImageView.setHierarchy(hierarchy); //图片等比例缩放 // getAvatarBitmap(imageRequest, controller, hierarchy, ClipPhotoActivity.this); } } @Override public void onContentChanged() { mTitle = (TextView) findViewById(R.id.photo_title); mGestureImageView = (ZoomableDraweeView) findViewById(R.id.gesture_iv); mBack = (ImageView) findViewById(R.id.btn_back); mBack.setOnClickListener(this); clip_image_borderview = (ClipImageBorderView) findViewById(R.id.clip_image_borderview); mCommit = (Button) findViewById(R.id.commit); mCommit.setOnClickListener(this); } @Override public void setTitle(CharSequence title) { mTitle.setText(title); } private void initIntentParams() { Intent mIntent = getIntent(); if (mIntent != null) { imgUrl = mIntent.getStringExtra(TAG); } } @Override public void onClick(View v) { int id = v.getId(); if (id == R.id.btn_back) { finish(); } else if (id == R.id.commit) { if (mGestureImageView != null) { Bitmap bm = mGestureImageView.clip(); Log.e("bm", "bm:" + bm.toString()); Intent resultIntent = new Intent(); Bundle mBundle = new Bundle(); mBundle.putParcelable(TAG, bm); resultIntent.putExtras(mBundle); setResult(101, resultIntent); finish(); } } } private void getAvatarBitmap(ImageRequest imageRequest, final DefaultZoomableController controller, final GenericDraweeHierarchy hierarchy, final IBitmapShow callback) { ImagePipeline imagePipeline = Fresco.getImagePipeline(); DataSource<CloseableReference<CloseableImage>> dataSource = imagePipeline.fetchDecodedImage(imageRequest, ClipPhotoActivity.this); dataSource.subscribe(new BaseBitmapDataSubscriber() { @Override protected void onNewResultImpl(@Nullable Bitmap bitmap) { if (bitmap != null) { if (callback != null) { callback.onBitmapLoadedSuccess(bitmap, controller, hierarchy); } } } @Override protected void onFailureImpl(DataSource<CloseableReference<CloseableImage>> dataSource) { } }, CallerThreadExecutor.getInstance()); } @Override public void onBitmapLoadedSuccess(Bitmap bm, DefaultZoomableController controller, GenericDraweeHierarchy hierarchy) { int bmWidth = bm.getWidth(); int bmHeight = bm.getHeight(); int newWidth = clip_image_borderview.getWidth() == 0 ? 200 : clip_image_borderview.getWidth(); int newHeight = clip_image_borderview.getHeight() == 0 ? 200 : clip_image_borderview.getHeight(); Log.e("bmWidth", "bmWidth:" + bmWidth + ",\nbmHeight:" + bmHeight + ",\nnewWidth:" + newWidth + ",\nnewHeight:" + newHeight); float scaleWidth = ((float) newWidth) / bmWidth; float scaleHeight = ((float) newHeight) / bmHeight; Matrix matrix = new Matrix(); matrix.postScale(scaleWidth, scaleHeight); Bitmap newBm = Bitmap.createBitmap(bm, 0, 0, bmWidth, bmHeight, matrix, true); mGestureImageView.setZoomableController(controller); mGestureImageView.setHierarchy(hierarchy); mGestureImageView.setImageBitmap(newBm); mGestureImageView.setOnTouchListener(new View.OnTouchListener() { float baseValue = 0; @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: float x = last_x = event.getRawX(); float y = last_y = event.getRawY(); move = false; break; case MotionEvent.ACTION_MOVE: if (event.getPointerCount() == 2) { //双指 float x1 = event.getX(0) - event.getX(1); float y1 = event.getY(0) - event.getY(1); //计算2点之间的距离 float value = (float) Math.sqrt(x1 * x1 + y1 * y1); if (baseValue == 0) { baseValue = value; } else { //由2点之间的距离来计算缩放比例 if ((value - baseValue) >= 10 || (baseValue - value) >= 10) { float scale = value / baseValue; img_scale(scale); } } } else if (event.getPointerCount() == 1) { //单指 float x2 = event.getRawX(); float y2 = event.getRawY(); x2 -= last_x; y2 -= last_y; if (x2 >= 10 || y2 >= 10 || x2 <= -10 || y2 <= -10) { img_translate(x2, y2); last_x = event.getRawX(); last_y = event.getRawY(); } } break; } return false; } }); } /** * 平移 * * @param x2 * @param y2 */ private void img_translate(float x2, float y2) { if (mGestureImageView != null) mGestureImageView.img_translate(x2, y2); } /** * 缩放 * * @param scale */ private void img_scale(float scale) { if (mGestureImageView != null) { mGestureImageView.img_scale(scale); } } }
SunnyLy/LocalImageChoose
multi-image-selector/src/main/java/me/nereo/multi_image_selector/ClipPhotoActivity.java
Java
mit
11,258
#include <onyxudp/udpclient.h> #include <stdio.h> #include <string.h> #include <assert.h> /* This test just makes sure the client library compiles and doens't crash on start. */ void on_error(udp_client_params_t *client, UDPERR code, char const *name) { fprintf(stderr, "on_error: code %d: %s\n", code, name); assert(!"should not happen"); } int main() { udp_client_params_t params; memset(&params, 0, sizeof(params)); params.app_id = 123; params.app_version = 321; params.on_error = on_error; params.on_idle = NULL; params.on_payload = NULL; params.on_disconnect = NULL; udp_client_t *client = udp_client_initialize(&params); assert(client != NULL); udp_client_terminate(client); return 0; }
jwatte/onyxnet
test/client/client.cpp
C++
mit
756
package wanghaisheng.com.yakerweather; import org.junit.Test; import static org.junit.Assert.*; /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
sheng-xiaoya/YakerWeather
app/src/test/java/wanghaisheng/com/yakerweather/ExampleUnitTest.java
Java
mit
322
<?php /** * Copyright 2012 Klarna AB * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file demonstrates the use of the Klarna library to complete * the purchase and display the thank you page snippet. * * PHP version 5.3.4 * * @category Payment * @package Payment_Klarna * @subpackage Examples * @author Klarna <support@klarna.com> * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://developers.klarna.com/ */ require_once 'src/Klarna/Checkout.php'; session_start(); Klarna_Checkout_Order::$contentType = "application/vnd.klarna.checkout.aggregated-order-v2+json"; $sharedSecret = 'sharedSecret'; @$checkoutId = $_GET['klarna_order']; $connector = Klarna_Checkout_Connector::create($sharedSecret); $order = new Klarna_Checkout_Order($connector, $checkoutId); $order->fetch(); if ($order['status'] == "checkout_complete") { // At this point make sure the order is created in your system and send a // confirmation email to the customer $update['status'] = 'created'; $update['merchant_reference'] = array( 'orderid1' => uniqid() ); $order->update($update); }
chrisVdd/Time2web
vendor/klarna/checkout/docs/examples/push.php
PHP
mit
1,718
import * as React from 'react'; import { AppliedFilter, DataTypes, GridFilters, numberWithCommas, ReactPowerTable, withInternalPaging, withInternalSorting } from '../../src/'; import { defaultColumns, partyList, sampledata } from './shared'; // //if coming in from DTO // const availDTO = [ // { fieldName: 'number', dataType: 'int' }, // { fieldName: 'president', dataType: 'string' }, // { fieldName: 'birth_year', dataType: 'int' }, // { fieldName: 'death_year', dataType: 'int', canBeNull: true }, // { fieldName: 'took_office', dataType: 'date' }, // { fieldName: 'left_office', dataType: 'date', canBeNull: true }, // { fieldName: 'party', dataType: 'string' }, // ]; // const availableFiltersMap = createKeyedMap(availDTO.map(m => new DataTypes[m.dataType](m)), m=>m.fieldName); //availableFilters.party = new DataTypes.list(availableFilters.party, partyList); const partyListOptions = partyList.map(m => ({ label: m.label, value: m.label })); //if building in JS const availableFilters = [ new DataTypes.int('number'), new DataTypes.string('president'), new DataTypes.int('birth_year'), new DataTypes.decimal({ fieldName: 'death_year', canBeNull: true }), new DataTypes.date({ fieldName: 'took_office' }), new DataTypes.date({ fieldName: 'left_office', canBeNull: true }), new DataTypes.list('party', partyListOptions), new DataTypes.boolean({ fieldName: 'assasinated', displayName: 'was assasinated' }), new DataTypes.timespan({ fieldName: 'timeBorn', displayName: 'time born' }), ]; //const columns = [...defaultColumns, { field: m => m.timeBorn, width: 80, formatter: formatTimeValue }]; const assasinatedPresidents = [16, 20, 25, 35]; function padStart(str: string, targetLength: number, padString: string) { // tslint:disable-next-line:no-bitwise targetLength = targetLength >> 0; //truncate if number, or convert non-number to 0; padString = String(typeof padString !== 'undefined' ? padString : ' '); if (str.length >= targetLength) { return String(str); } else { targetLength = targetLength - str.length; if (targetLength > padString.length) { padString += padString.repeat(targetLength / padString.length); //append to original to ensure we are longer than needed } return padString.slice(0, targetLength) + str; } } const data = sampledata.map(m => ({ ...m, assasinated: assasinatedPresidents.indexOf(m.number) > -1, timeBorn: padStart(Math.floor((Math.random() * 24)).toString(), 2, '0') + ':00' })); //const availableFiltersMap = createKeyedMap(availableFilters, m => m.fieldName); //availableFiltersMap.number.operations.gt.displayName = 'greater than TEST'; availableFilters.find(m => m.fieldName === 'death_year').operations['null'].displayName = 'still alive'; interface FiltersExampleState { appliedFilters: Array<AppliedFilter<any>>; } const Table = withInternalSorting(withInternalPaging(ReactPowerTable)); export class FiltersExample extends React.Component<never, FiltersExampleState> { constructor(props: never) { super(props); this.state = { appliedFilters: [] }; this.handleFiltersChange = this.handleFiltersChange.bind(this); } handleFiltersChange(newFilters: Array<AppliedFilter<any>>) { console.log('onFiltersChange', newFilters); this.setState({ appliedFilters: newFilters }); } render() { let filteredData = data; this.state.appliedFilters.forEach(m => { filteredData = m.filter.applyFilter(filteredData, m.operation, m.value); }); return ( <div className="row"> <div className="col-md-3"> <div className="grid-filters"> <div className="small"> {numberWithCommas(filteredData.length) + ' Presidents'} &nbsp; </div> <div style={{ marginTop: 10 }} /> <GridFilters availableFilters={availableFilters} appliedFilters={this.state.appliedFilters} onFiltersChange={this.handleFiltersChange} /> </div> </div> <div className="col-md-9"> <Table columns={defaultColumns} keyColumn="number" rows={filteredData} sorting={{ column: 'number' }} /> </div> </div> ); } }
coolkev/react-power-table
examples/src/filters.tsx
TypeScript
mit
4,479
<section id="content"> <!--start container--> <div id="breadcrumbs-wrapper" class="" style="width:100%;"> <div class="header-search-wrapper grey hide-on-large-only"> <i class="mdi-action-search active"></i> <input type="text" name="Search" class="header-search-input z-depth-2" placeholder="Explore Materialize"> </div> <div class="container"> <div class="row"> <div class="col s12 m12 l12"> <h5 class="breadcrumbs-title">New Progres perunit</h5> <ol class="breadcrumb"> <li><a href="<?php echo site_url('administrator'); ?>">Dashboard</a></li> <li><a href="<?php echo site_url('administrator/main/progres_unit');?>">Progres perUnit</a></li> <li class="active">New Progres perUnit</li> </ol> </div> </div> </div> </div> <div class="col s12 m12 l6"> <div class="card-panel"> <div class="col s12 m12 l6" style="width:100%;"> <div class="card-panel" style="width:100%;"> <h4 class="header2">New Progres perUnit</h4> <div class="row"> <div class="row"> <?=form_open('action/save_progresunit');?> <div class="input-field col s12"> <label for="spk" class="active">SPK</label> <select name="spk" id="spk"> <?php $query = $this->db->query("SELECT DISTINCT spk FROM tbl_resume"); foreach ($query->result() as $datap) { ?> <option value="<?=$datap->spk;?>"><?=$datap->spk;?></option> <?php } ?> </select> </div> </div> <div class="row"> <div class="input-field col s12"> <input type="hidden" name="nama_kavling_hidden" id="nama_kavling_hidden"> <label for="nama_kavling" class="active">Kavling</label> <select id="nama_kavling" name="nama_kavling"> <option></option> </select> </div> </div> <div class="row"> <div class="input-field col s12"> <input placeholder="" id="sdmingguini" type="text" name="sdmingguini"> <label for="sdmingguini" class="active">Progres</label> </div> </div> <div class="input-field col s12"> <button class="btn cyan waves-effect waves-light right" type="submit" name="action" style="margin-left:10px;">Submit </button> <button onclick="goBack()" class="btn cyan waves-effect waves-light right" type="submit" name="action">Cancel </button> <?=form_close();?> </div> </div> </div> </div> </div> </div> </form> <!--start container--> </section> <!--end container--> <!-- END CONTENT --> <!--end container--> <script> function goBack() { window.history.go(-1); } </script> <script> $("#spk").on('change', function(){ $('#spk_hidden').val($(this).val()); $("#nama_kavling").empty(); $.ajax({ url: '<?php echo site_url("action/get_rsm")?>', type: 'POST', data: {spk: $(this).val()}, dataType:'json', success : function(data){ console.log(data); for(var index in data){ $("#nama_kavling").append('<option value='+data[index].nama_kavling+'>'+data[index].nama_kavling+'</option>'); } $("#nama_kavling").material_select(); } }) .done(function(response) { $("#nama_kavling").append('<option>'+response+'</option>') }); $("#nama_kavling").on('change', function(){ $('#nama_kavling_hidden').val($(this).val()); $.ajax({ url: '<?php echo site_url("action/getdata")?>', type: 'POST', data: {nama_kavling : $(this).val()}, dataType : 'json', success : function(data){ $("#sdmingguini").val(data.sdmingguini) console.log(data); } }) }) }) $("#nama_kavling").on('change', function(){ $('#nama_kavling_hidden').val($(this).val()); $.ajax({ url: '<?php echo site_url("action/getdata")?>', type: 'POST', data: {nama_kavling : $(this).val()}, dataType : 'json', success : function(data){ $("#sdmingguini").val(data.sdmingguini) console.log(data); } }) }) </script>
MiftahulxHuda/rekon
application/views/page/new_progresunit.php
PHP
mit
5,595
package network // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "context" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/tracing" "net/http" ) // HubVirtualNetworkConnectionsClient is the network Client type HubVirtualNetworkConnectionsClient struct { BaseClient } // NewHubVirtualNetworkConnectionsClient creates an instance of the HubVirtualNetworkConnectionsClient client. func NewHubVirtualNetworkConnectionsClient(subscriptionID string) HubVirtualNetworkConnectionsClient { return NewHubVirtualNetworkConnectionsClientWithBaseURI(DefaultBaseURI, subscriptionID) } // NewHubVirtualNetworkConnectionsClientWithBaseURI creates an instance of the HubVirtualNetworkConnectionsClient // client using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI // (sovereign clouds, Azure stack). func NewHubVirtualNetworkConnectionsClientWithBaseURI(baseURI string, subscriptionID string) HubVirtualNetworkConnectionsClient { return HubVirtualNetworkConnectionsClient{NewWithBaseURI(baseURI, subscriptionID)} } // Get retrieves the details of a HubVirtualNetworkConnection. // Parameters: // resourceGroupName - the resource group name of the VirtualHub. // virtualHubName - the name of the VirtualHub. // connectionName - the name of the vpn connection. func (client HubVirtualNetworkConnectionsClient) Get(ctx context.Context, resourceGroupName string, virtualHubName string, connectionName string) (result HubVirtualNetworkConnection, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/HubVirtualNetworkConnectionsClient.Get") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.GetPreparer(ctx, resourceGroupName, virtualHubName, connectionName) if err != nil { err = autorest.NewErrorWithError(err, "network.HubVirtualNetworkConnectionsClient", "Get", nil, "Failure preparing request") return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "network.HubVirtualNetworkConnectionsClient", "Get", resp, "Failure sending request") return } result, err = client.GetResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "network.HubVirtualNetworkConnectionsClient", "Get", resp, "Failure responding to request") return } return } // GetPreparer prepares the Get request. func (client HubVirtualNetworkConnectionsClient) GetPreparer(ctx context.Context, resourceGroupName string, virtualHubName string, connectionName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "connectionName": autorest.Encode("path", connectionName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "virtualHubName": autorest.Encode("path", virtualHubName), } const APIVersion = "2018-11-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/hubVirtualNetworkConnections/{connectionName}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client HubVirtualNetworkConnectionsClient) GetSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // GetResponder handles the response to the Get request. The method always // closes the http.Response Body. func (client HubVirtualNetworkConnectionsClient) GetResponder(resp *http.Response) (result HubVirtualNetworkConnection, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // List retrieves the details of all HubVirtualNetworkConnections. // Parameters: // resourceGroupName - the resource group name of the VirtualHub. // virtualHubName - the name of the VirtualHub. func (client HubVirtualNetworkConnectionsClient) List(ctx context.Context, resourceGroupName string, virtualHubName string) (result ListHubVirtualNetworkConnectionsResultPage, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/HubVirtualNetworkConnectionsClient.List") defer func() { sc := -1 if result.lhvncr.Response.Response != nil { sc = result.lhvncr.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } result.fn = client.listNextResults req, err := client.ListPreparer(ctx, resourceGroupName, virtualHubName) if err != nil { err = autorest.NewErrorWithError(err, "network.HubVirtualNetworkConnectionsClient", "List", nil, "Failure preparing request") return } resp, err := client.ListSender(req) if err != nil { result.lhvncr.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "network.HubVirtualNetworkConnectionsClient", "List", resp, "Failure sending request") return } result.lhvncr, err = client.ListResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "network.HubVirtualNetworkConnectionsClient", "List", resp, "Failure responding to request") return } if result.lhvncr.hasNextLink() && result.lhvncr.IsEmpty() { err = result.NextWithContext(ctx) return } return } // ListPreparer prepares the List request. func (client HubVirtualNetworkConnectionsClient) ListPreparer(ctx context.Context, resourceGroupName string, virtualHubName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "virtualHubName": autorest.Encode("path", virtualHubName), } const APIVersion = "2018-11-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/hubVirtualNetworkConnections", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client HubVirtualNetworkConnectionsClient) ListSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // ListResponder handles the response to the List request. The method always // closes the http.Response Body. func (client HubVirtualNetworkConnectionsClient) ListResponder(resp *http.Response) (result ListHubVirtualNetworkConnectionsResult, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // listNextResults retrieves the next set of results, if any. func (client HubVirtualNetworkConnectionsClient) listNextResults(ctx context.Context, lastResults ListHubVirtualNetworkConnectionsResult) (result ListHubVirtualNetworkConnectionsResult, err error) { req, err := lastResults.listHubVirtualNetworkConnectionsResultPreparer(ctx) if err != nil { return result, autorest.NewErrorWithError(err, "network.HubVirtualNetworkConnectionsClient", "listNextResults", nil, "Failure preparing next results request") } if req == nil { return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} return result, autorest.NewErrorWithError(err, "network.HubVirtualNetworkConnectionsClient", "listNextResults", resp, "Failure sending next results request") } result, err = client.ListResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "network.HubVirtualNetworkConnectionsClient", "listNextResults", resp, "Failure responding to next results request") } return } // ListComplete enumerates all values, automatically crossing page boundaries as required. func (client HubVirtualNetworkConnectionsClient) ListComplete(ctx context.Context, resourceGroupName string, virtualHubName string) (result ListHubVirtualNetworkConnectionsResultIterator, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/HubVirtualNetworkConnectionsClient.List") defer func() { sc := -1 if result.Response().Response.Response != nil { sc = result.page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } result.page, err = client.List(ctx, resourceGroupName, virtualHubName) return }
Azure/azure-sdk-for-go
services/network/mgmt/2018-11-01/network/hubvirtualnetworkconnections.go
GO
mit
9,593
var address = ''; var config = {}; var requestGroupId = 0; var readRequestsTodo = 0; var readRequestsDone = 0; var scanRequestsTodo = [0, 0, 0]; var scanRequestsDone = [0, 0, 0]; var scanResults = []; var requestSentCounter = 0; var requestSuccessCounter = 0; var requestFailureCounter = 0; var requestInProgress = false; var requestQueue = []; var socket = io({ transports: ['websocket'], timeout: 10000, reconnectionDelay: 500, autoConnect: true }); socket.on('reconnect', function() { window.location.reload(); }); var READ_RESPONSE_HANDLERS = { in: handleReadInputResponse, out: handleReadOutputResponse, anal: handleReadAnalogResponse, func: handleReadFunctionResponse }; $(function() { $('#config-address').on('change', function(e) { updateAddress(e.target.value); reset(); }); $('#config-scan').on('click', scan); $('#config-file').on('change', function(e) { var file = e.target.files[0]; if (!file || !/\.conf/.test(file.name)) { updateInput(''); reset(); return; } var reader = new FileReader(); reader.onload = function(e) { updateInput(e.target.result); reset(); }; reader.readAsText(file); }); $('#config-input').on('change', function(e) { $('#config-file').val(''); updateInput(e.target.value); reset(); }); $('#outputs').on('click', '.output', function(e) { toggleOutput(config[e.currentTarget.dataset.id]); }); $('#analogs') .on('change', '.form-control', function(e) { setAnalog(config[$(e.currentTarget).closest('.analog')[0].dataset.id], e.currentTarget.value); }) .on('keyup', '.form-control', function(e) { if (e.keyCode === 13) { setAnalog(config[$(e.currentTarget).closest('.analog')[0].dataset.id], e.currentTarget.value); } }); $('#functions') .on('change', '.form-control', function(e) { setFunction(config[$(e.currentTarget).closest('.function')[0].dataset.id], e.currentTarget.value); }) .on('keyup', '.form-control', function(e) { if (e.keyCode === 13) { setFunction(config[$(e.currentTarget).closest('.function')[0].dataset.id], e.currentTarget.value); } }); $(window).on('resize', resizeInput); resizeInput(); updateAddress(localStorage.ADDRESS || ''); updateInput(localStorage.INPUT || ''); reset(); }); function resizeInput() { var height = window.innerHeight - 90 - 54 - 20 - 53 - 15 - 53 - 15 - 30; $('#config-input').css('height', height + 'px'); } function updateAddress(newAddress) { newAddress = newAddress.trim(); localStorage.ADDRESS = newAddress; $('#config-address').val(newAddress); if (newAddress.length && newAddress.indexOf('.') === -1) { newAddress = '[' + newAddress + ']'; } address = newAddress; } function updateInput(newInput) { parseInput(newInput); if (!Object.keys(config).length) { newInput = 'Nieprawidłowy lub pusty plik!'; } else { localStorage.INPUT = newInput; } $('#config-input').val(newInput); } function parseInput(input) { config = {}; var re = /([A-Z0-9_-]+)\s+([0-9]+)\s+([0-9]+)\s+(in|out|anal|func)/ig; var matches; while (matches = re.exec(input)) { var name = matches[1]; config[name] = { type: matches[4], name: name, tim: parseInt(matches[2], 10), channel: parseInt(matches[3], 10), writing: false, value: null }; } } function renderIo() { var html = { inputs: [], outputs: [], analogs: [], functions: [] }; Object.keys(config).forEach(function(key) { var io = config[key]; if (io.type === 'in') { renderInput(html.inputs, io); } else if (io.type === 'out') { renderOutput(html.outputs, io); } else if (io.type === 'anal') { renderAnalog(html.analogs, io); } else if (io.type === 'func') { renderFunction(html.functions, io); } }); Object.keys(html).forEach(function(ioType) { $('#' + ioType).html(html[ioType].join('')); }); } function renderInput(html, io) { html.push( '<span class="input label label-default" data-id="', io.name, '">', io.name, '</span>' ); } function renderOutput(html, io) { html.push( '<button class="output btn btn-default" data-id="', io.name, '">', io.name, '</button>' ); } function renderAnalog(html, io) { html.push( '<div class="analog" data-id="', io.name, '"><div class="input-group"><span class="input-group-addon">', io.name, '</span><input type="number" class="form-control" min="0" max="65535" step="1"></div></div>' ); } function renderFunction(html, io) { html.push( '<div class="function" data-id="', io.name, '"><div class="input-group"><span class="input-group-addon">', io.name, '</span><input type="text" class="form-control"></div></div>' ); } function reset() { ++requestGroupId; Object.keys(config).forEach(function(key) { config[key].value = null; }); readRequestsDone = 0; readRequestsTodo = 0; requestSentCounter = 0; requestSuccessCounter = 0; requestFailureCounter = 0; updateRequestCounter(); renderIo(); readAll(); } function updateRequestCounter() { $('#requestCounter-success').text(requestSuccessCounter); $('#requestCounter-failure').text(requestFailureCounter); $('#requestCounter-sent').text(requestSentCounter); } function readAll() { if (readRequestsDone !== readRequestsTodo) { return; } if (!address.length) { return; } var keys = Object.keys(config); readRequestsDone = 0; readRequestsTodo = keys.length; keys.forEach(function(key) { read(config[key]); }); requestSentCounter += readRequestsTodo; updateRequestCounter(); } function read(io) { var reqGroupId = requestGroupId; var req = { type: 'NON', code: 'GET', uri: 'coap://' + address + '/io/RD?tim=' + io.tim + '&ch=' + io.channel + '&t=' + io.type }; socket.emit('request', req, function(err, res) { if (requestGroupId !== reqGroupId) { return; } ++readRequestsDone; if (err) { ++requestFailureCounter; //console.error('Error reading %s: %s', io.name, err.message); } else if (res.payload.indexOf('0') !== 0) { ++requestFailureCounter; console.error('Error reading %s (%s): %d', io.name, res.code, res.payload.split('\n')[0]); } else { ++requestSuccessCounter; READ_RESPONSE_HANDLERS[io.type](io, res); } updateRequestCounter(); if (readRequestsDone === readRequestsTodo) { setTimeout(readAll, 333); } }); } function handleReadInputResponse(io, res) { var $input = $('.input[data-id="' + io.name + '"]'); if (!$input.length) { return; } $input.removeClass('label-default label-success label-danger'); io.value = res.payload.indexOf('ON') !== -1 ? true : res.payload.indexOf('OFF') !== -1 ? false : null; if (io.value === true) { $input.addClass('label-success'); } else if (io.value === false) { $input.addClass('label-danger'); } else { $input.addClass('label-default'); } } function handleReadOutputResponse(io, res) { if (io.writing) { return; } var $output = $('.output[data-id="' + io.name + '"]'); if (!$output.length) { return; } io.value = res.payload.indexOf('ON') !== -1 ? true : res.payload.indexOf('OFF') !== -1 ? false : null; $output .removeClass('btn-default btn-success btn-danger') .addClass(io.value === null ? 'btn-default' : io.value ? 'btn-success' : 'btn-danger'); } function handleReadAnalogResponse(io, res) { if (io.writing) { return; } var $analog = $('.analog[data-id="' + io.name + '"]'); var $input = $analog.find('.form-control'); if (!$analog.length || document.activeElement === $input[0]) { return; } io.value = parseInt(res.payload.split('\n')[3], 10) || 0; $input.val(io.value); } function handleReadFunctionResponse(io, res) { if (io.writing) { return; } var $function = $('.function[data-id="' + io.name + '"]'); var $input = $function.find('.form-control'); if (!$function.length || document.activeElement === $input[0]) { return; } io.value = res.payload.trim().split('\n')[3]; if (io.value === undefined) { io.value = ''; } $input.val(io.value); } function toggleOutput(io) { if (io.writing) { return; } io.writing = true; var $output = $('.output[data-id="' + io.name + '"]'); $output .removeClass('btn-default btn-success btn-danger') .addClass('btn-warning'); ++requestSentCounter; updateRequestCounter(); var reqGroupId = requestGroupId; var req = { type: 'NON', code: 'POST', uri: 'coap://' + address + '/io/WD?tim=' + io.tim + '&ch=' + io.channel + '&t=' + io.type + '&tD=' + (io.value ? 'OFF' : 'ON') }; socket.emit('request', req, function(err, res) { if (requestGroupId !== reqGroupId) { return; } io.writing = false; if (err) { ++requestFailureCounter; console.error('Error writing %s: %s', io.name, err.message); } else if (res.payload.indexOf('0') !== 0) { ++requestFailureCounter; console.error('Error writing %s (%s): %d', io.name, res.code, res.payload.split('\n')[0]); } else { ++requestSuccessCounter; io.value = !io.value; } $output .removeClass('btn-warning') .addClass(io.value === null ? 'btn-default' : io.value ? 'btn-success' : 'btn-danger'); updateRequestCounter(); }); } function setAnalog(io, value) { value = parseInt(value, 10); if (io.writing || isNaN(value) || value < 0 || value > 0xFFFF) { return; } io.writing = true; var $analog = $('.analog[data-id="' + io.name + '"]'); var $input = $analog.find('.form-control'); $analog.addClass('is-writing'); $input.attr('readonly', true); ++requestSentCounter; updateRequestCounter(); var reqGroupId = requestGroupId; var req = { type: 'NON', code: 'POST', uri: 'coap://' + address + '/io/WD?tim=' + io.tim + '&ch=' + io.channel + '&t=' + io.type + '&tD=' + value }; socket.emit('request', req, function(err, res) { if (requestGroupId !== reqGroupId) { return; } $analog.removeClass('is-writing'); io.writing = false; if (err) { ++requestFailureCounter; console.error('Error writing %s: %s', io.name, err.message); } else if (res.payload.indexOf('0') !== 0) { ++requestFailureCounter; console.error('Error writing %s (%s): %d', io.name, res.code, res.payload.split('\n')[0]); } else { ++requestSuccessCounter; io.value = value; $input.val(value).attr('readonly', false); } updateRequestCounter(); }); } function setFunction(io, value) { if (io.writing) { return; } io.writing = true; var $function = $('.function[data-id="' + io.name + '"]'); var $input = $function.find('.form-control'); $function.addClass('is-writing'); $input.attr('readonly', true); ++requestSentCounter; updateRequestCounter(); var reqGroupId = requestGroupId; var req = { type: 'NON', code: 'POST', uri: 'coap://' + address + '/io/WD?tim=' + io.tim + '&ch=' + io.channel + '&t=' + io.type + '&tD=' + value }; socket.emit('request', req, function(err, res) { if (requestGroupId !== reqGroupId) { return; } $function.removeClass('is-writing'); io.writing = false; if (err) { ++requestFailureCounter; console.error('Error writing %s: %s', io.name, err.message); } else if (res.payload.indexOf('0') !== 0) { ++requestFailureCounter; console.error('Error writing %s (%s): %d', io.name, res.code, res.payload.split('\n')[0]); } else { ++requestSuccessCounter; io.value = value; $input.val(value).attr('readonly', false); } updateRequestCounter(); }); } function unlockAfterScan() { scanRequestsDone = [0, 0]; scanRequestsTodo = [0, 0]; scanResults = []; $('#config').find('.form-control').prop('disabled', false); } function scan() { if (!address.length || scanRequestsTodo[0] !== 0) { return; } updateInput(''); reset(); $('#config').find('.form-control').prop('disabled', true); var req = { type: 'CON', code: 'GET', uri: 'coap://' + address + '/io/TDisc' }; var options = { exchangeTimeout: 10000, transactionTimeout: 1000, maxRetransmit: 3, blockSize: 64 }; updateRequestCounter(++requestSentCounter); queueRequest(req, options, function(err, res) { if (err) { updateRequestCounter(++requestFailureCounter); unlockAfterScan(); return console.error("Error scanning: %s", err.message); } updateRequestCounter(++requestSuccessCounter); var tims = res.payload.split('\n')[1].split(','); scanRequestsDone = [0, 0]; scanRequestsTodo = [tims.length, 0]; scanResults = []; tims.forEach(function(timId) { scanTim(parseInt(timId.trim(), 10)); }); }); } function scanTim(timId) { var req = { type: 'CON', code: 'GET', uri: 'coap://' + address + '/io/CDisc?tim=' + timId }; var options = { exchangeTimeout: 10000, transactionTimeout: 1000, maxRetransmit: 3, blockSize: 64 }; updateRequestCounter(++requestSentCounter); queueRequest(req, options, function(err, res) { if (err) { updateRequestCounter(++requestFailureCounter); unlockAfterScan(); return console.error("Error scanning TIM %d: %s", timId, err.message); } updateRequestCounter(++requestSuccessCounter); ++scanRequestsDone[0]; var lines = res.payload.split('\n'); var channelIds = lines[2].split(','); var transducerNames = lines[3].replace(/"/g, '').split(','); scanRequestsTodo[1] += channelIds.length; channelIds.forEach(function(channelId, i) { setTimeout( scanChannel, Math.round(10 + Math.random() * 200), timId, parseInt(channelId.trim(), 10), transducerNames[i] ); }); }); } function scanChannel(timId, channelId, transducerName) { var req = { type: 'CON', code: 'GET', uri: 'coap://' + address + '/io/RTeds?tim=' + timId + '&ch=' + channelId + '&TT=4' }; var options = { exchangeTimeout: 10000, transactionTimeout: 1000, maxRetransmit: 3, blockSize: 64 }; updateRequestCounter(++requestSentCounter); queueRequest(req, options, function(err, res) { if (err) { updateRequestCounter(++requestFailureCounter); unlockAfterScan(); return console.error("Error scanning channel %d of TIM %d: %s", channelId, timId, err.message); } updateRequestCounter(++requestSuccessCounter); ++scanRequestsDone[1]; var type = null; if (/Digital Input/i.test(res.payload)) { type = 'in'; } else if (/Digital Output/i.test(res.payload)) { type = 'out'; } else if (/(Digit.*?|Analog|Step g) (Input|Output)/i.test(res.payload)) { type = 'anal'; } if (type) { scanResults.push({ timId: timId, channelId: channelId, name: (transducerName || ('T_' + timId + '_' + channelId)).trim(), type: type }); } if (scanRequestsDone[1] === scanRequestsTodo[1]) { buildInputFromScanResults(); } }); } function buildInputFromScanResults() { var input = []; scanResults.sort(function(a, b) { var r = a.timId - b.timId; if (r === 0) { r = a.channelId - b.channelId; } return r; }); scanResults.forEach(function(io) { input.push(io.name + ' ' + io.timId + ' ' + io.channelId + ' ' + io.type); }); unlockAfterScan(); updateInput(input.join('\n')); renderIo(); readAll(); } function queueRequest(req, options, callback) { requestQueue.push(req, options, callback); if (!requestInProgress) { sendNextRequest(); } } function sendNextRequest() { var req = requestQueue.shift(); var options = requestQueue.shift(); var callback = requestQueue.shift(); if (!callback) { return; } requestInProgress = true; socket.emit('request', req, options, function(err, res) { requestInProgress = false; callback(err, res); sendNextRequest(); }); }
morkai/walkner-iovis
frontend/main.js
JavaScript
mit
16,664
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Matrix { public class Matrix<T> where T : struct { private T[,] matrix; public Matrix(int x, int y) { matrix = new T[x, y]; } public int LengthX { get { return this.matrix.GetLength(0); } } public int LengthY { get { return this.matrix.GetLength(1); } } public T this [int x, int y] { get { if (matrix.GetLength(0) > x && matrix.GetLength(1) > y) { return this.matrix[x, y]; } else { throw new IndexOutOfRangeException(); } } set { if (matrix.GetLength(0) > x && matrix.GetLength(1) > y) { this.matrix[x, y] = value; } else { throw new IndexOutOfRangeException(); } } } private static bool IsMatricesTheSameSize(Matrix<T> matrix1, Matrix<T> matrix2) { if (matrix1.matrix.GetLength(0) == matrix2.matrix.GetLength(0) && matrix1.matrix.GetLength(1) == matrix2.matrix.GetLength(1)) { return true; } else { return false; } } private static bool IsMultiplicationPossible(Matrix<T> matrix1, Matrix<T> matrix2) { if (matrix1.LengthX == matrix2.LengthY && matrix1.LengthY == matrix2.LengthX) { return true; } else { return false; } } public static Matrix<T> operator +(Matrix<T> matrix1, Matrix<T> matrix2) { Matrix<T> newMatrix = new Matrix<T>(matrix1.LengthX, matrix1.LengthY); dynamic matrice1 = matrix1; dynamic matrice2 = matrix2; if (Matrix<T>.IsMatricesTheSameSize(matrix1, matrix2)) { for (int i = 0; i < matrix1.LengthX; i++) { for (int j = 0; j < matrix1.LengthY; j++) { newMatrix[i, j] = matrice1[i, j] + matrice2[i, j]; } } } else { throw new InvalidOperationException(); } return newMatrix; } public static Matrix<T> operator -(Matrix<T> matrix1, Matrix<T> matrix2) { Matrix<T> newMatrix = new Matrix<T>(matrix1.LengthX, matrix1.LengthY); dynamic matrice1 = matrix1; dynamic matrice2 = matrix2; if (Matrix<T>.IsMatricesTheSameSize(matrix1, matrix2)) { for (int i = 0; i < matrix1.LengthX; i++) { for (int j = 0; j < matrix1.LengthY; j++) { newMatrix[i, j] = matrice1[i, j] - matrice2[i, j]; } } } else { throw new InvalidOperationException(); } return newMatrix; } public static Matrix<T> operator *(Matrix<T> matrix1, Matrix<T> matrix2) { Matrix<T> newMatrix = new Matrix<T>(matrix1.LengthX, matrix2.LengthY); dynamic matrice1 = matrix1; dynamic matrice2 = matrix2; if (Matrix<T>.IsMultiplicationPossible(matrix1, matrix2)) { for (int i = 0; i < matrix1.LengthX; i++) { for (int j = 0; j < matrix1.LengthY; j++) { newMatrix[i, j] = matrice1[i, j] * matrice2[j, i]; } } } else { throw new InvalidOperationException(); } return newMatrix; } public static bool operator true(T elementOfMetrix) { return elementOfMetrix.Equals(default(T)); } } }
dirk-dagger-667/telerik-c--OOP-lectures
DefineClassPartTwo1/Matrix/Matrix.cs
C#
mit
4,419
// 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. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel; using System.Globalization; using System.IO; using System.IO.MemoryMappedFiles; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Test.Resources.Proprietary; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.DiaSymReader; using Roslyn.Test.PdbUtilities; using Roslyn.Test.Utilities; using Roslyn.Test.Utilities.TestGenerators; using Roslyn.Utilities; using Xunit; using Basic.Reference.Assemblies; using static Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers; using static Roslyn.Test.Utilities.SharedResourceHelpers; using static Roslyn.Test.Utilities.TestMetadata; namespace Microsoft.CodeAnalysis.CSharp.CommandLine.UnitTests { public class CommandLineTests : CommandLineTestBase { #if NETCOREAPP private static readonly string s_CSharpCompilerExecutable; private static readonly string s_DotnetCscRun; #else private static readonly string s_CSharpCompilerExecutable = Path.Combine( Path.GetDirectoryName(typeof(CommandLineTests).GetTypeInfo().Assembly.Location), Path.Combine("dependency", "csc.exe")); private static readonly string s_DotnetCscRun = ExecutionConditionUtil.IsMono ? "mono" : string.Empty; #endif private static readonly string s_CSharpScriptExecutable; private static readonly string s_compilerVersion = CommonCompiler.GetProductVersion(typeof(CommandLineTests)); static CommandLineTests() { #if NETCOREAPP var cscDllPath = Path.Combine( Path.GetDirectoryName(typeof(CommandLineTests).GetTypeInfo().Assembly.Location), Path.Combine("dependency", "csc.dll")); var dotnetExe = DotNetCoreSdk.ExePath; var netStandardDllPath = AppDomain.CurrentDomain.GetAssemblies() .FirstOrDefault(assembly => !assembly.IsDynamic && assembly.Location.EndsWith("netstandard.dll")).Location; var netStandardDllDir = Path.GetDirectoryName(netStandardDllPath); // Since we are using references based on the UnitTest's runtime, we need to use // its runtime config when executing out program. var runtimeConfigPath = Path.ChangeExtension(Assembly.GetExecutingAssembly().Location, "runtimeconfig.json"); s_CSharpCompilerExecutable = $@"""{dotnetExe}"" ""{cscDllPath}"" /r:""{netStandardDllPath}"" /r:""{netStandardDllDir}/System.Private.CoreLib.dll"" /r:""{netStandardDllDir}/System.Console.dll"" /r:""{netStandardDllDir}/System.Runtime.dll"""; s_DotnetCscRun = $@"""{dotnetExe}"" exec --runtimeconfig ""{runtimeConfigPath}"""; s_CSharpScriptExecutable = s_CSharpCompilerExecutable.Replace("csc.dll", Path.Combine("csi", "csi.dll")); #else s_CSharpScriptExecutable = s_CSharpCompilerExecutable.Replace("csc.exe", Path.Combine("csi", "csi.exe")); #endif } private class TestCommandLineParser : CSharpCommandLineParser { private readonly Dictionary<string, string> _responseFiles; private readonly Dictionary<string, string[]> _recursivePatterns; private readonly Dictionary<string, string[]> _patterns; public TestCommandLineParser( Dictionary<string, string> responseFiles = null, Dictionary<string, string[]> patterns = null, Dictionary<string, string[]> recursivePatterns = null, bool isInteractive = false) : base(isInteractive) { _responseFiles = responseFiles; _recursivePatterns = recursivePatterns; _patterns = patterns; } internal override IEnumerable<string> EnumerateFiles(string directory, string fileNamePattern, SearchOption searchOption) { var key = directory + "|" + fileNamePattern; if (searchOption == SearchOption.TopDirectoryOnly) { return _patterns[key]; } else { return _recursivePatterns[key]; } } internal override TextReader CreateTextFileReader(string fullPath) { return new StringReader(_responseFiles[fullPath]); } } private CSharpCommandLineArguments ScriptParse(IEnumerable<string> args, string baseDirectory) { return CSharpCommandLineParser.Script.Parse(args, baseDirectory, SdkDirectory); } private CSharpCommandLineArguments FullParse(string commandLine, string baseDirectory, string sdkDirectory = null, string additionalReferenceDirectories = null) { sdkDirectory = sdkDirectory ?? SdkDirectory; var args = CommandLineParser.SplitCommandLineIntoArguments(commandLine, removeHashComments: true); return CSharpCommandLineParser.Default.Parse(args, baseDirectory, sdkDirectory, additionalReferenceDirectories); } [ConditionalFact(typeof(WindowsDesktopOnly))] [WorkItem(34101, "https://github.com/dotnet/roslyn/issues/34101")] public void SuppressedWarnAsErrorsStillEmit() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" #pragma warning disable 1591 public class P { public static void Main() {} }"); const string docName = "doc.xml"; var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/errorlog:errorlog", $"/doc:{docName}", "/warnaserror", src.Path }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString()); string exePath = Path.Combine(dir.Path, "temp.exe"); Assert.True(File.Exists(exePath)); var result = ProcessUtilities.Run(exePath, arguments: ""); Assert.Equal(0, result.ExitCode); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] public void XmlMemoryMapped() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText("class C {}"); const string docName = "doc.xml"; var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/preferreduilang:en", $"/doc:{docName}", src.Path }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString()); var xmlPath = Path.Combine(dir.Path, docName); using (var fileStream = new FileStream(xmlPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (var mmf = MemoryMappedFile.CreateFromFile(fileStream, "xmlMap", 0, MemoryMappedFileAccess.Read, HandleInheritability.None, leaveOpen: true)) { exitCode = cmd.Run(outWriter); Assert.StartsWith($"error CS0016: Could not write to output file '{xmlPath}' -- ", outWriter.ToString()); Assert.Equal(1, exitCode); } } [Fact] public void SimpleAnalyzerConfig() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@" class C { int _f; }"); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] dotnet_diagnostic.cs0169.severity = none"); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/preferreduilang:en", "/analyzerconfig:" + analyzerConfig.Path, src.Path }); Assert.Equal(analyzerConfig.Path, Assert.Single(cmd.Arguments.AnalyzerConfigPaths)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString()); Assert.Null(cmd.AnalyzerOptions); } [Fact] public void AnalyzerConfigWithOptions() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@" class C { int _f; }"); var additionalFile = dir.CreateFile("file.txt"); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] dotnet_diagnostic.cs0169.severity = none dotnet_diagnostic.Warning01.severity = none my_option = my_val [*.txt] dotnet_diagnostic.cs0169.severity = none my_option2 = my_val2"); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/analyzerconfig:" + analyzerConfig.Path, "/analyzer:" + Assembly.GetExecutingAssembly().Location, "/nowarn:8032", "/additionalfile:" + additionalFile.Path, src.Path }); Assert.Equal(analyzerConfig.Path, Assert.Single(cmd.Arguments.AnalyzerConfigPaths)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal("", outWriter.ToString()); Assert.Equal(0, exitCode); var comp = cmd.Compilation; var tree = comp.SyntaxTrees.Single(); var compilerTreeOptions = comp.Options.SyntaxTreeOptionsProvider; Assert.True(compilerTreeOptions.TryGetDiagnosticValue(tree, "cs0169", CancellationToken.None, out var severity)); Assert.Equal(ReportDiagnostic.Suppress, severity); Assert.True(compilerTreeOptions.TryGetDiagnosticValue(tree, "warning01", CancellationToken.None, out severity)); Assert.Equal(ReportDiagnostic.Suppress, severity); var analyzerOptions = cmd.AnalyzerOptions.AnalyzerConfigOptionsProvider; var options = analyzerOptions.GetOptions(tree); Assert.NotNull(options); Assert.True(options.TryGetValue("my_option", out string val)); Assert.Equal("my_val", val); Assert.False(options.TryGetValue("my_option2", out _)); Assert.False(options.TryGetValue("dotnet_diagnostic.cs0169.severity", out _)); options = analyzerOptions.GetOptions(cmd.AnalyzerOptions.AdditionalFiles.Single()); Assert.NotNull(options); Assert.True(options.TryGetValue("my_option2", out val)); Assert.Equal("my_val2", val); Assert.False(options.TryGetValue("my_option", out _)); Assert.False(options.TryGetValue("dotnet_diagnostic.cs0169.severity", out _)); } [Fact] public void AnalyzerConfigBadSeverity() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@" class C { int _f; }"); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] dotnet_diagnostic.cs0169.severity = garbage"); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/preferreduilang:en", "/analyzerconfig:" + analyzerConfig.Path, src.Path }); Assert.Equal(analyzerConfig.Path, Assert.Single(cmd.Arguments.AnalyzerConfigPaths)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal( $@"warning InvalidSeverityInAnalyzerConfig: The diagnostic 'cs0169' was given an invalid severity 'garbage' in the analyzer config file at '{analyzerConfig.Path}'. test.cs(4,9): warning CS0169: The field 'C._f' is never used ", outWriter.ToString()); Assert.Null(cmd.AnalyzerOptions); } [Fact] public void AnalyzerConfigsInSameDir() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@" class C { int _f; }"); var configText = @" [*.cs] dotnet_diagnostic.cs0169.severity = suppress"; var analyzerConfig1 = dir.CreateFile("analyzerconfig1").WriteAllText(configText); var analyzerConfig2 = dir.CreateFile("analyzerconfig2").WriteAllText(configText); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/preferreduilang:en", "/analyzerconfig:" + analyzerConfig1.Path, "/analyzerconfig:" + analyzerConfig2.Path, src.Path }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal( $"error CS8700: Multiple analyzer config files cannot be in the same directory ('{dir.Path}').", outWriter.ToString().TrimEnd()); } // This test should only run when the machine's default encoding is shift-JIS [ConditionalFact(typeof(WindowsDesktopOnly), typeof(HasShiftJisDefaultEncoding), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void CompileShiftJisOnShiftJis() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("sjis.cs").WriteAllBytes(TestResources.General.ShiftJisSource); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", src.Path }); Assert.Null(cmd.Arguments.Encoding); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString()); var result = ProcessUtilities.Run(Path.Combine(dir.Path, "sjis.exe"), arguments: "", workingDirectory: dir.Path); Assert.Equal(0, result.ExitCode); Assert.Equal("星野 八郎太", File.ReadAllText(Path.Combine(dir.Path, "output.txt"), Encoding.GetEncoding(932))); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void RunWithShiftJisFile() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("sjis.cs").WriteAllBytes(TestResources.General.ShiftJisSource); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/codepage:932", src.Path }); Assert.Equal(932, cmd.Arguments.Encoding?.WindowsCodePage); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString()); var result = ProcessUtilities.Run(Path.Combine(dir.Path, "sjis.exe"), arguments: "", workingDirectory: dir.Path); Assert.Equal(0, result.ExitCode); Assert.Equal("星野 八郎太", File.ReadAllText(Path.Combine(dir.Path, "output.txt"), Encoding.GetEncoding(932))); } [WorkItem(946954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/946954")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void CompilerBinariesAreAnyCPU() { Assert.Equal(ProcessorArchitecture.MSIL, AssemblyName.GetAssemblyName(s_CSharpCompilerExecutable).ProcessorArchitecture); } [Fact] public void ResponseFiles1() { string rsp = Temp.CreateFile().WriteAllText(@" /r:System.dll /nostdlib # this is ignored System.Console.WriteLine(""*?""); # this is error a.cs ").Path; var cmd = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { "b.cs" }); cmd.Arguments.Errors.Verify( // error CS2001: Source file 'System.Console.WriteLine(*?);' could not be found Diagnostic(ErrorCode.ERR_FileNotFound).WithArguments("System.Console.WriteLine(*?);")); AssertEx.Equal(new[] { "System.dll" }, cmd.Arguments.MetadataReferences.Select(r => r.Reference)); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "a.cs"), Path.Combine(WorkingDirectory, "b.cs") }, cmd.Arguments.SourceFiles.Select(file => file.Path)); CleanupAllGeneratedFiles(rsp); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] public void ResponseFiles_RelativePaths() { var parentDir = Temp.CreateDirectory(); var baseDir = parentDir.CreateDirectory("temp"); var dirX = baseDir.CreateDirectory("x"); var dirAB = baseDir.CreateDirectory("a b"); var dirSubDir = baseDir.CreateDirectory("subdir"); var dirGoo = parentDir.CreateDirectory("goo"); var dirBar = parentDir.CreateDirectory("bar"); string basePath = baseDir.Path; Func<string, string> prependBasePath = fileName => Path.Combine(basePath, fileName); var parser = new TestCommandLineParser(responseFiles: new Dictionary<string, string>() { { prependBasePath(@"a.rsp"), @" ""@subdir\b.rsp"" /r:..\v4.0.30319\System.dll /r:.\System.Data.dll a.cs @""..\c.rsp"" @\d.rsp /libpaths:..\goo;../bar;""a b"" " }, { Path.Combine(dirSubDir.Path, @"b.rsp"), @" b.cs " }, { prependBasePath(@"..\c.rsp"), @" c.cs /lib:x " }, { Path.Combine(Path.GetPathRoot(basePath), @"d.rsp"), @" # comment d.cs " } }, isInteractive: false); var args = parser.Parse(new[] { "first.cs", "second.cs", "@a.rsp", "last.cs" }, basePath, SdkDirectory); args.Errors.Verify(); Assert.False(args.IsScriptRunner); string[] resolvedSourceFiles = args.SourceFiles.Select(f => f.Path).ToArray(); string[] references = args.MetadataReferences.Select(r => r.Reference).ToArray(); AssertEx.Equal(new[] { "first.cs", "second.cs", "b.cs", "a.cs", "c.cs", "d.cs", "last.cs" }.Select(prependBasePath), resolvedSourceFiles); AssertEx.Equal(new[] { typeof(object).Assembly.Location, @"..\v4.0.30319\System.dll", @".\System.Data.dll" }, references); AssertEx.Equal(new[] { RuntimeEnvironment.GetRuntimeDirectory() }.Concat(new[] { @"x", @"..\goo", @"../bar", @"a b" }.Select(prependBasePath)), args.ReferencePaths.ToArray()); Assert.Equal(basePath, args.BaseDirectory); } #nullable enable [ConditionalFact(typeof(WindowsOnly))] public void NullBaseDirectoryNotAddedToKeyFileSearchPaths() { var parser = CSharpCommandLineParser.Default.Parse(new[] { "c:/test.cs" }, baseDirectory: null, SdkDirectory); AssertEx.Equal(ImmutableArray.Create<string>(), parser.KeyFileSearchPaths); Assert.Null(parser.OutputDirectory); parser.Errors.Verify( // error CS8762: Output directory could not be determined Diagnostic(ErrorCode.ERR_NoOutputDirectory).WithLocation(1, 1) ); } [ConditionalFact(typeof(WindowsOnly))] public void NullBaseDirectoryWithAdditionalFiles() { var parser = CSharpCommandLineParser.Default.Parse(new[] { "/additionalfile:web.config", "c:/test.cs" }, baseDirectory: null, SdkDirectory); AssertEx.Equal(ImmutableArray.Create<string>(), parser.KeyFileSearchPaths); Assert.Null(parser.OutputDirectory); parser.Errors.Verify( // error CS2021: File name 'web.config' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("web.config").WithLocation(1, 1), // error CS8762: Output directory could not be determined Diagnostic(ErrorCode.ERR_NoOutputDirectory).WithLocation(1, 1) ); } [ConditionalFact(typeof(WindowsOnly))] public void NullBaseDirectoryWithAdditionalFiles_Wildcard() { var parser = CSharpCommandLineParser.Default.Parse(new[] { "/additionalfile:*", "c:/test.cs" }, baseDirectory: null, SdkDirectory); AssertEx.Equal(ImmutableArray.Create<string>(), parser.KeyFileSearchPaths); Assert.Null(parser.OutputDirectory); parser.Errors.Verify( // error CS2001: Source file '*' could not be found. Diagnostic(ErrorCode.ERR_FileNotFound).WithArguments("*").WithLocation(1, 1), // error CS8762: Output directory could not be determined Diagnostic(ErrorCode.ERR_NoOutputDirectory).WithLocation(1, 1) ); } #nullable disable [Fact, WorkItem(29252, "https://github.com/dotnet/roslyn/issues/29252")] public void NoSdkPath() { var parentDir = Temp.CreateDirectory(); var parser = CSharpCommandLineParser.Default.Parse(new[] { "file.cs", $"-out:{parentDir.Path}", "/noSdkPath" }, parentDir.Path, null); AssertEx.Equal(ImmutableArray<string>.Empty, parser.ReferencePaths); } [Fact, WorkItem(29252, "https://github.com/dotnet/roslyn/issues/29252")] public void NoSdkPathReferenceSystemDll() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/nosdkpath", "/r:System.dll", "a.cs" }); var exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS0006: Metadata file 'System.dll' could not be found", outWriter.ToString().Trim()); } [ConditionalFact(typeof(WindowsOnly))] public void SourceFiles_Patterns() { var parser = new TestCommandLineParser( patterns: new Dictionary<string, string[]>() { { @"C:\temp|*.cs", new[] { "a.cs", "b.cs", "c.cs" } } }, recursivePatterns: new Dictionary<string, string[]>() { { @"C:\temp\a|*.cs", new[] { @"a\x.cs", @"a\b\b.cs", @"a\c.cs" } }, }); var args = parser.Parse(new[] { @"*.cs", @"/recurse:a\*.cs" }, @"C:\temp", SdkDirectory); args.Errors.Verify(); string[] resolvedSourceFiles = args.SourceFiles.Select(f => f.Path).ToArray(); AssertEx.Equal(new[] { @"C:\temp\a.cs", @"C:\temp\b.cs", @"C:\temp\c.cs", @"C:\temp\a\x.cs", @"C:\temp\a\b\b.cs", @"C:\temp\a\c.cs" }, resolvedSourceFiles); } [Fact] public void ParseQuotedMainType() { // Verify the main switch are unquoted when used because of the issue with // MSBuild quoting some usages and not others. A quote character is not valid in either // these names. CSharpCommandLineArguments args; var folder = Temp.CreateDirectory(); CreateFile(folder, "a.cs"); args = DefaultParse(new[] { "/main:Test", "a.cs" }, folder.Path); args.Errors.Verify(); Assert.Equal("Test", args.CompilationOptions.MainTypeName); args = DefaultParse(new[] { "/main:\"Test\"", "a.cs" }, folder.Path); args.Errors.Verify(); Assert.Equal("Test", args.CompilationOptions.MainTypeName); args = DefaultParse(new[] { "/main:\"Test.Class1\"", "a.cs" }, folder.Path); args.Errors.Verify(); Assert.Equal("Test.Class1", args.CompilationOptions.MainTypeName); args = DefaultParse(new[] { "/m:Test", "a.cs" }, folder.Path); args.Errors.Verify(); Assert.Equal("Test", args.CompilationOptions.MainTypeName); args = DefaultParse(new[] { "/m:\"Test\"", "a.cs" }, folder.Path); args.Errors.Verify(); Assert.Equal("Test", args.CompilationOptions.MainTypeName); args = DefaultParse(new[] { "/m:\"Test.Class1\"", "a.cs" }, folder.Path); args.Errors.Verify(); Assert.Equal("Test.Class1", args.CompilationOptions.MainTypeName); // Use of Cyrillic namespace args = DefaultParse(new[] { "/m:\"решения.Class1\"", "a.cs" }, folder.Path); args.Errors.Verify(); Assert.Equal("решения.Class1", args.CompilationOptions.MainTypeName); } [Fact] [WorkItem(21508, "https://github.com/dotnet/roslyn/issues/21508")] public void ArgumentStartWithDashAndContainingSlash() { CSharpCommandLineArguments args; var folder = Temp.CreateDirectory(); args = DefaultParse(new[] { "-debug+/debug:portable" }, folder.Path); args.Errors.Verify( // error CS2007: Unrecognized option: '-debug+/debug:portable' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("-debug+/debug:portable").WithLocation(1, 1), // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1) ); } [WorkItem(546009, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546009")] [WorkItem(545991, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545991")] [ConditionalFact(typeof(WindowsOnly))] public void SourceFiles_Patterns2() { var folder = Temp.CreateDirectory(); CreateFile(folder, "a.cs"); CreateFile(folder, "b.vb"); CreateFile(folder, "c.cpp"); var folderA = folder.CreateDirectory("A"); CreateFile(folderA, "A_a.cs"); CreateFile(folderA, "A_b.cs"); CreateFile(folderA, "A_c.vb"); var folderB = folder.CreateDirectory("B"); CreateFile(folderB, "B_a.cs"); CreateFile(folderB, "B_b.vb"); CreateFile(folderB, "B_c.cpx"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, folder.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", @"/recurse:.", "/out:abc.dll" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2008: No source files specified.", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, folder.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", @"/recurse:. ", "/out:abc.dll" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2008: No source files specified.", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, folder.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", @"/recurse: . ", "/out:abc.dll" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2008: No source files specified.", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, folder.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", @"/recurse:././.", "/out:abc.dll" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2008: No source files specified.", outWriter.ToString().Trim()); CSharpCommandLineArguments args; string[] resolvedSourceFiles; args = DefaultParse(new[] { @"/recurse:*.cp*", @"/recurse:a\*.c*", @"/out:a.dll" }, folder.Path); args.Errors.Verify(); resolvedSourceFiles = args.SourceFiles.Select(f => f.Path).ToArray(); AssertEx.Equal(new[] { folder.Path + @"\c.cpp", folder.Path + @"\B\B_c.cpx", folder.Path + @"\a\A_a.cs", folder.Path + @"\a\A_b.cs", }, resolvedSourceFiles); args = DefaultParse(new[] { @"/recurse:.\\\\\\*.cs", @"/out:a.dll" }, folder.Path); args.Errors.Verify(); resolvedSourceFiles = args.SourceFiles.Select(f => f.Path).ToArray(); Assert.Equal(4, resolvedSourceFiles.Length); args = DefaultParse(new[] { @"/recurse:.////*.cs", @"/out:a.dll" }, folder.Path); args.Errors.Verify(); resolvedSourceFiles = args.SourceFiles.Select(f => f.Path).ToArray(); Assert.Equal(4, resolvedSourceFiles.Length); } [ConditionalFact(typeof(WindowsOnly))] public void SourceFile_BadPath() { var args = DefaultParse(new[] { @"e:c:\test\test.cs", "/t:library" }, WorkingDirectory); Assert.Equal(3, args.Errors.Length); Assert.Equal((int)ErrorCode.FTL_InvalidInputFileName, args.Errors[0].Code); Assert.Equal((int)ErrorCode.WRN_NoSources, args.Errors[1].Code); Assert.Equal((int)ErrorCode.ERR_OutputNeedsName, args.Errors[2].Code); } private void CreateFile(TempDirectory folder, string file) { var f = folder.CreateFile(file); f.WriteAllText(""); } [Fact, WorkItem(546023, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546023")] public void Win32ResourceArguments() { string[] args = new string[] { @"/win32manifest:..\here\there\everywhere\nonexistent" }; var parsedArgs = DefaultParse(args, WorkingDirectory); var compilation = CreateCompilation(new SyntaxTree[0]); IEnumerable<DiagnosticInfo> errors; CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors); Assert.Equal(1, errors.Count()); Assert.Equal((int)ErrorCode.ERR_CantOpenWin32Manifest, errors.First().Code); Assert.Equal(2, errors.First().Arguments.Count()); args = new string[] { @"/Win32icon:\bogus" }; parsedArgs = DefaultParse(args, WorkingDirectory); CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors); Assert.Equal(1, errors.Count()); Assert.Equal((int)ErrorCode.ERR_CantOpenIcon, errors.First().Code); Assert.Equal(2, errors.First().Arguments.Count()); args = new string[] { @"/Win32Res:\bogus" }; parsedArgs = DefaultParse(args, WorkingDirectory); CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors); Assert.Equal(1, errors.Count()); Assert.Equal((int)ErrorCode.ERR_CantOpenWin32Res, errors.First().Code); Assert.Equal(2, errors.First().Arguments.Count()); args = new string[] { @"/Win32Res:goo.win32data:bar.win32data2" }; parsedArgs = DefaultParse(args, WorkingDirectory); CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors); Assert.Equal(1, errors.Count()); Assert.Equal((int)ErrorCode.ERR_CantOpenWin32Res, errors.First().Code); Assert.Equal(2, errors.First().Arguments.Count()); args = new string[] { @"/Win32icon:goo.win32data:bar.win32data2" }; parsedArgs = DefaultParse(args, WorkingDirectory); CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors); Assert.Equal(1, errors.Count()); Assert.Equal((int)ErrorCode.ERR_CantOpenIcon, errors.First().Code); Assert.Equal(2, errors.First().Arguments.Count()); args = new string[] { @"/Win32manifest:goo.win32data:bar.win32data2" }; parsedArgs = DefaultParse(args, WorkingDirectory); CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors); Assert.Equal(1, errors.Count()); Assert.Equal((int)ErrorCode.ERR_CantOpenWin32Manifest, errors.First().Code); Assert.Equal(2, errors.First().Arguments.Count()); } [Fact] public void Win32ResConflicts() { var parsedArgs = DefaultParse(new[] { "/win32res:goo", "/win32icon:goob", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_CantHaveWin32ResAndIcon, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "/win32res:goo", "/win32manifest:goob", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_CantHaveWin32ResAndManifest, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "/win32res:", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_NoFileSpec, parsedArgs.Errors.First().Code); Assert.Equal(1, parsedArgs.Errors.First().Arguments.Count); parsedArgs = DefaultParse(new[] { "/win32Icon: ", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_NoFileSpec, parsedArgs.Errors.First().Code); Assert.Equal(1, parsedArgs.Errors.First().Arguments.Count); parsedArgs = DefaultParse(new[] { "/win32Manifest:", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_NoFileSpec, parsedArgs.Errors.First().Code); Assert.Equal(1, parsedArgs.Errors.First().Arguments.Count); parsedArgs = DefaultParse(new[] { "/win32Manifest:goo", "/noWin32Manifest", "a.cs" }, WorkingDirectory); Assert.Equal(0, parsedArgs.Errors.Length); Assert.True(parsedArgs.NoWin32Manifest); Assert.Null(parsedArgs.Win32Manifest); } [Fact] public void Win32ResInvalid() { var parsedArgs = DefaultParse(new[] { "/win32res", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/win32res")); parsedArgs = DefaultParse(new[] { "/win32res+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/win32res+")); parsedArgs = DefaultParse(new[] { "/win32icon", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/win32icon")); parsedArgs = DefaultParse(new[] { "/win32icon+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/win32icon+")); parsedArgs = DefaultParse(new[] { "/win32manifest", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/win32manifest")); parsedArgs = DefaultParse(new[] { "/win32manifest+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/win32manifest+")); } [Fact] public void Win32IconContainsGarbage() { string tmpFileName = Temp.CreateFile().WriteAllBytes(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }).Path; var parsedArgs = DefaultParse(new[] { "/win32icon:" + tmpFileName, "a.cs" }, WorkingDirectory); var compilation = CreateCompilation(new SyntaxTree[0]); IEnumerable<DiagnosticInfo> errors; CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors); Assert.Equal(1, errors.Count()); Assert.Equal((int)ErrorCode.ERR_ErrorBuildingWin32Resources, errors.First().Code); Assert.Equal(1, errors.First().Arguments.Count()); CleanupAllGeneratedFiles(tmpFileName); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void Win32ResQuotes() { string[] responseFile = new string[] { @" /win32res:d:\\""abc def""\a""b c""d\a.res", }; CSharpCommandLineArguments args = DefaultParse(CSharpCommandLineParser.ParseResponseLines(responseFile), @"c:\"); Assert.Equal(@"d:\abc def\ab cd\a.res", args.Win32ResourceFile); responseFile = new string[] { @" /win32icon:d:\\""abc def""\a""b c""d\a.ico", }; args = DefaultParse(CSharpCommandLineParser.ParseResponseLines(responseFile), @"c:\"); Assert.Equal(@"d:\abc def\ab cd\a.ico", args.Win32Icon); responseFile = new string[] { @" /win32manifest:d:\\""abc def""\a""b c""d\a.manifest", }; args = DefaultParse(CSharpCommandLineParser.ParseResponseLines(responseFile), @"c:\"); Assert.Equal(@"d:\abc def\ab cd\a.manifest", args.Win32Manifest); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void ParseResources() { var diags = new List<Diagnostic>(); ResourceDescription desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar", WorkingDirectory, diags, embedded: false); Assert.Equal(0, diags.Count); Assert.Equal(@"someFile.goo.bar", desc.FileName); Assert.Equal("someFile.goo.bar", desc.ResourceName); desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,someName", WorkingDirectory, diags, embedded: false); Assert.Equal(0, diags.Count); Assert.Equal(@"someFile.goo.bar", desc.FileName); Assert.Equal("someName", desc.ResourceName); desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\s""ome Fil""e.goo.bar,someName", WorkingDirectory, diags, embedded: false); Assert.Equal(0, diags.Count); Assert.Equal(@"some File.goo.bar", desc.FileName); Assert.Equal("someName", desc.ResourceName); desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,""some Name"",public", WorkingDirectory, diags, embedded: false); Assert.Equal(0, diags.Count); Assert.Equal(@"someFile.goo.bar", desc.FileName); Assert.Equal("some Name", desc.ResourceName); Assert.True(desc.IsPublic); // Use file name in place of missing resource name. desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,,private", WorkingDirectory, diags, embedded: false); Assert.Equal(0, diags.Count); Assert.Equal(@"someFile.goo.bar", desc.FileName); Assert.Equal("someFile.goo.bar", desc.ResourceName); Assert.False(desc.IsPublic); // Quoted accessibility is fine. desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,,""private""", WorkingDirectory, diags, embedded: false); Assert.Equal(0, diags.Count); Assert.Equal(@"someFile.goo.bar", desc.FileName); Assert.Equal("someFile.goo.bar", desc.ResourceName); Assert.False(desc.IsPublic); // Leading commas are not ignored... desc = CSharpCommandLineParser.ParseResourceDescription("", @",,\somepath\someFile.goo.bar,,private", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS1906: Invalid option '\somepath\someFile.goo.bar'; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(@"\somepath\someFile.goo.bar")); diags.Clear(); Assert.Null(desc); // ...even if there's whitespace between them. desc = CSharpCommandLineParser.ParseResourceDescription("", @", ,\somepath\someFile.goo.bar,,private", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS1906: Invalid option '\somepath\someFile.goo.bar'; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(@"\somepath\someFile.goo.bar")); diags.Clear(); Assert.Null(desc); // Trailing commas are ignored... desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,,private", WorkingDirectory, diags, embedded: false); diags.Verify(); diags.Clear(); Assert.Equal("someFile.goo.bar", desc.FileName); Assert.Equal("someFile.goo.bar", desc.ResourceName); Assert.False(desc.IsPublic); // ...even if there's whitespace between them. desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,,private, ,", WorkingDirectory, diags, embedded: false); diags.Verify(); diags.Clear(); Assert.Equal("someFile.goo.bar", desc.FileName); Assert.Equal("someFile.goo.bar", desc.ResourceName); Assert.False(desc.IsPublic); desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,someName,publi", WorkingDirectory, diags, embedded: false); diags.Verify(Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments("publi")); Assert.Null(desc); diags.Clear(); desc = CSharpCommandLineParser.ParseResourceDescription("", @"D:rive\relative\path,someName,public", WorkingDirectory, diags, embedded: false); diags.Verify(Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"D:rive\relative\path")); Assert.Null(desc); diags.Clear(); desc = CSharpCommandLineParser.ParseResourceDescription("", @"inva\l*d?path,someName,public", WorkingDirectory, diags, embedded: false); diags.Verify(Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"inva\l*d?path")); Assert.Null(desc); diags.Clear(); desc = CSharpCommandLineParser.ParseResourceDescription("", (string)null, WorkingDirectory, diags, embedded: false); diags.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("")); Assert.Null(desc); diags.Clear(); desc = CSharpCommandLineParser.ParseResourceDescription("", "", WorkingDirectory, diags, embedded: false); diags.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("")); Assert.Null(desc); diags.Clear(); desc = CSharpCommandLineParser.ParseResourceDescription("", " ", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS2005: Missing file specification for '' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("").WithLocation(1, 1)); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", " , ", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS2005: Missing file specification for '' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("").WithLocation(1, 1)); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", "path, ", WorkingDirectory, diags, embedded: false); diags.Verify(); diags.Clear(); Assert.Equal("path", desc.FileName); Assert.Equal("path", desc.ResourceName); Assert.True(desc.IsPublic); desc = CSharpCommandLineParser.ParseResourceDescription("", " ,name", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS2005: Missing file specification for '' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("").WithLocation(1, 1)); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", " , , ", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS1906: Invalid option ' '; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(" ")); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", "path, , ", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS1906: Invalid option ' '; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(" ")); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", " ,name, ", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS1906: Invalid option ' '; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(" ")); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", " , ,private", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS2005: Missing file specification for '' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("").WithLocation(1, 1)); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", "path,name,", WorkingDirectory, diags, embedded: false); diags.Verify( // CONSIDER: Dev10 actually prints "Invalid option '|'" (note the pipe) // error CS1906: Invalid option ''; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments("")); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", "path,name,,", WorkingDirectory, diags, embedded: false); diags.Verify( // CONSIDER: Dev10 actually prints "Invalid option '|'" (note the pipe) // error CS1906: Invalid option ''; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments("")); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", "path,name, ", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS1906: Invalid option ''; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(" ")); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", "path, ,private", WorkingDirectory, diags, embedded: false); diags.Verify(); diags.Clear(); Assert.Equal("path", desc.FileName); Assert.Equal("path", desc.ResourceName); Assert.False(desc.IsPublic); desc = CSharpCommandLineParser.ParseResourceDescription("", " ,name,private", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS2005: Missing file specification for '' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("").WithLocation(1, 1)); diags.Clear(); Assert.Null(desc); var longE = new String('e', 1024); desc = CSharpCommandLineParser.ParseResourceDescription("", String.Format("path,{0},private", longE), WorkingDirectory, diags, embedded: false); diags.Verify(); // Now checked during emit. diags.Clear(); Assert.Equal("path", desc.FileName); Assert.Equal(longE, desc.ResourceName); Assert.False(desc.IsPublic); var longI = new String('i', 260); desc = CSharpCommandLineParser.ParseResourceDescription("", String.Format("{0},e,private", longI), WorkingDirectory, diags, embedded: false); diags.Verify( // error CS2021: File name 'iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii").WithLocation(1, 1)); } [Fact] public void ManagedResourceOptions() { CSharpCommandLineArguments parsedArgs; ResourceDescription resourceDescription; parsedArgs = DefaultParse(new[] { "/resource:a", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); resourceDescription = parsedArgs.ManifestResources.Single(); Assert.Null(resourceDescription.FileName); // since embedded Assert.Equal("a", resourceDescription.ResourceName); parsedArgs = DefaultParse(new[] { "/res:b", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); resourceDescription = parsedArgs.ManifestResources.Single(); Assert.Null(resourceDescription.FileName); // since embedded Assert.Equal("b", resourceDescription.ResourceName); parsedArgs = DefaultParse(new[] { "/linkresource:c", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); resourceDescription = parsedArgs.ManifestResources.Single(); Assert.Equal("c", resourceDescription.FileName); Assert.Equal("c", resourceDescription.ResourceName); parsedArgs = DefaultParse(new[] { "/linkres:d", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); resourceDescription = parsedArgs.ManifestResources.Single(); Assert.Equal("d", resourceDescription.FileName); Assert.Equal("d", resourceDescription.ResourceName); } [Fact] public void ManagedResourceOptions_SimpleErrors() { var parsedArgs = DefaultParse(new[] { "/resource:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/resource:")); parsedArgs = DefaultParse(new[] { "/resource: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/resource:")); parsedArgs = DefaultParse(new[] { "/res", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/res")); parsedArgs = DefaultParse(new[] { "/RES+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/RES+")); parsedArgs = DefaultParse(new[] { "/res-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/res-:")); parsedArgs = DefaultParse(new[] { "/linkresource:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/linkresource:")); parsedArgs = DefaultParse(new[] { "/linkresource: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/linkresource:")); parsedArgs = DefaultParse(new[] { "/linkres", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/linkres")); parsedArgs = DefaultParse(new[] { "/linkRES+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/linkRES+")); parsedArgs = DefaultParse(new[] { "/linkres-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/linkres-:")); } [Fact] public void Link_SimpleTests() { var parsedArgs = DefaultParse(new[] { "/link:a", "/link:b,,,,c", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { "a", "b", "c" }, parsedArgs.MetadataReferences. Where((res) => res.Properties.EmbedInteropTypes). Select((res) => res.Reference)); parsedArgs = DefaultParse(new[] { "/Link: ,,, b ,,", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { " b " }, parsedArgs.MetadataReferences. Where((res) => res.Properties.EmbedInteropTypes). Select((res) => res.Reference)); parsedArgs = DefaultParse(new[] { "/l:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/l:")); parsedArgs = DefaultParse(new[] { "/L", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/L")); parsedArgs = DefaultParse(new[] { "/l+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/l+")); parsedArgs = DefaultParse(new[] { "/link-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/link-:")); } [ConditionalFact(typeof(WindowsOnly))] public void Recurse_SimpleTests() { var dir = Temp.CreateDirectory(); var file1 = dir.CreateFile("a.cs"); var file2 = dir.CreateFile("b.cs"); var file3 = dir.CreateFile("c.txt"); var file4 = dir.CreateDirectory("d1").CreateFile("d.txt"); var file5 = dir.CreateDirectory("d2").CreateFile("e.cs"); file1.WriteAllText(""); file2.WriteAllText(""); file3.WriteAllText(""); file4.WriteAllText(""); file5.WriteAllText(""); var parsedArgs = DefaultParse(new[] { "/recurse:" + dir.ToString() + "\\*.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { "{DIR}\\a.cs", "{DIR}\\b.cs", "{DIR}\\d2\\e.cs" }, parsedArgs.SourceFiles.Select((file) => file.Path.Replace(dir.ToString(), "{DIR}"))); parsedArgs = DefaultParse(new[] { "*.cs" }, dir.ToString()); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { "{DIR}\\a.cs", "{DIR}\\b.cs" }, parsedArgs.SourceFiles.Select((file) => file.Path.Replace(dir.ToString(), "{DIR}"))); parsedArgs = DefaultParse(new[] { "/reCURSE:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/reCURSE:")); parsedArgs = DefaultParse(new[] { "/RECURSE: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/RECURSE:")); parsedArgs = DefaultParse(new[] { "/recurse", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/recurse")); parsedArgs = DefaultParse(new[] { "/recurse+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/recurse+")); parsedArgs = DefaultParse(new[] { "/recurse-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/recurse-:")); CleanupAllGeneratedFiles(file1.Path); CleanupAllGeneratedFiles(file2.Path); CleanupAllGeneratedFiles(file3.Path); CleanupAllGeneratedFiles(file4.Path); CleanupAllGeneratedFiles(file5.Path); } [Fact] public void Reference_SimpleTests() { var parsedArgs = DefaultParse(new[] { "/nostdlib", "/r:a", "/REFERENCE:b,,,,c", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { "a", "b", "c" }, parsedArgs.MetadataReferences. Where((res) => !res.Properties.EmbedInteropTypes). Select((res) => res.Reference)); parsedArgs = DefaultParse(new[] { "/Reference: ,,, b ,,", "/nostdlib", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { " b " }, parsedArgs.MetadataReferences. Where((res) => !res.Properties.EmbedInteropTypes). Select((res) => res.Reference)); parsedArgs = DefaultParse(new[] { "/Reference:a=b,,,", "/nostdlib", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("a", parsedArgs.MetadataReferences.Single().Properties.Aliases.Single()); Assert.Equal("b", parsedArgs.MetadataReferences.Single().Reference); parsedArgs = DefaultParse(new[] { "/r:a=b,,,c", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_OneAliasPerReference).WithArguments("b,,,c")); parsedArgs = DefaultParse(new[] { "/r:1=b", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadExternIdentifier).WithArguments("1")); parsedArgs = DefaultParse(new[] { "/r:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/r:")); parsedArgs = DefaultParse(new[] { "/R", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/R")); parsedArgs = DefaultParse(new[] { "/reference+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/reference+")); parsedArgs = DefaultParse(new[] { "/reference-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/reference-:")); } [Fact] public void Target_SimpleTests() { var parsedArgs = DefaultParse(new[] { "/target:exe", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OutputKind.ConsoleApplication, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/t:module", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OutputKind.NetModule, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:library", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OutputKind.DynamicallyLinkedLibrary, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/TARGET:winexe", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OutputKind.WindowsApplication, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:appcontainerexe", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OutputKind.WindowsRuntimeApplication, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:winmdobj", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OutputKind.WindowsRuntimeMetadata, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:winexe", "/T:exe", "/target:module", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OutputKind.NetModule, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/t", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/t")); parsedArgs = DefaultParse(new[] { "/target:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_InvalidTarget)); parsedArgs = DefaultParse(new[] { "/target:xyz", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_InvalidTarget)); parsedArgs = DefaultParse(new[] { "/T+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/T+")); parsedArgs = DefaultParse(new[] { "/TARGET-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/TARGET-:")); } [Fact] public void Target_SimpleTestsNoSource() { var parsedArgs = DefaultParse(new[] { "/target:exe" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); Assert.Equal(OutputKind.ConsoleApplication, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/t:module" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); Assert.Equal(OutputKind.NetModule, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:library" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); Assert.Equal(OutputKind.DynamicallyLinkedLibrary, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/TARGET:winexe" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); Assert.Equal(OutputKind.WindowsApplication, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:appcontainerexe" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); Assert.Equal(OutputKind.WindowsRuntimeApplication, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:winmdobj" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); Assert.Equal(OutputKind.WindowsRuntimeMetadata, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:winexe", "/T:exe", "/target:module" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); Assert.Equal(OutputKind.NetModule, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/t" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/t' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/t").WithLocation(1, 1), // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); parsedArgs = DefaultParse(new[] { "/target:" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2019: Invalid target type for /target: must specify 'exe', 'winexe', 'library', or 'module' Diagnostic(ErrorCode.FTL_InvalidTarget).WithLocation(1, 1), // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); parsedArgs = DefaultParse(new[] { "/target:xyz" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2019: Invalid target type for /target: must specify 'exe', 'winexe', 'library', or 'module' Diagnostic(ErrorCode.FTL_InvalidTarget).WithLocation(1, 1), // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); parsedArgs = DefaultParse(new[] { "/T+" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/T+' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/T+").WithLocation(1, 1), // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); parsedArgs = DefaultParse(new[] { "/TARGET-:" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/TARGET-:' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/TARGET-:").WithLocation(1, 1), // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); } [Fact] public void ModuleManifest() { CSharpCommandLineArguments args = DefaultParse(new[] { "/win32manifest:blah", "/target:module", "a.cs" }, WorkingDirectory); args.Errors.Verify( // warning CS1927: Ignoring /win32manifest for module because it only applies to assemblies Diagnostic(ErrorCode.WRN_CantHaveManifestForModule)); // Illegal, but not clobbered. Assert.Equal("blah", args.Win32Manifest); } // The following test is failing in the Linux Debug test leg of CI. // This issus is being tracked by https://github.com/dotnet/roslyn/issues/58077 [ConditionalFact(typeof(WindowsOrMacOSOnly))] public void ArgumentParsing() { var sdkDirectory = SdkDirectory; var parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "a + b" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "a + b; c" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/help" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.DisplayHelp); Assert.False(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/version" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.DisplayVersion); Assert.False(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/langversion:?" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.DisplayLangVersions); Assert.False(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "//langversion:?" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify( // error CS2001: Source file '//langversion:?' could not be found. Diagnostic(ErrorCode.ERR_FileNotFound).WithArguments("//langversion:?").WithLocation(1, 1) ); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/version", "c.csx" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.DisplayVersion); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/version:something" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.DisplayVersion); Assert.False(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/?" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.DisplayHelp); Assert.False(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "c.csx /langversion:6" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/langversion:-1", "c.csx", }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify( // error CS1617: Invalid option '-1' for /langversion. Use '/langversion:?' to list supported values. Diagnostic(ErrorCode.ERR_BadCompatMode).WithArguments("-1").WithLocation(1, 1)); Assert.False(parsedArgs.DisplayHelp); Assert.Equal(1, parsedArgs.SourceFiles.Length); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "c.csx /r:s=d /r:d.dll" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "@roslyn_test_non_existing_file" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify( // error CS2011: Error opening response file 'D:\R0\Main\Binaries\Debug\dd' Diagnostic(ErrorCode.ERR_OpenResponseFile).WithArguments(Path.Combine(WorkingDirectory, @"roslyn_test_non_existing_file"))); Assert.False(parsedArgs.DisplayHelp); Assert.False(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "c /define:DEBUG" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "\\" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/r:d.dll", "c.csx" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/define:goo", "c.csx" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/define:goo' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/define:goo")); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "\"/r d.dll\"" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/r: d.dll", "a.cs" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); } [Theory] [InlineData("iso-1", LanguageVersion.CSharp1)] [InlineData("iso-2", LanguageVersion.CSharp2)] [InlineData("1", LanguageVersion.CSharp1)] [InlineData("1.0", LanguageVersion.CSharp1)] [InlineData("2", LanguageVersion.CSharp2)] [InlineData("2.0", LanguageVersion.CSharp2)] [InlineData("3", LanguageVersion.CSharp3)] [InlineData("3.0", LanguageVersion.CSharp3)] [InlineData("4", LanguageVersion.CSharp4)] [InlineData("4.0", LanguageVersion.CSharp4)] [InlineData("5", LanguageVersion.CSharp5)] [InlineData("5.0", LanguageVersion.CSharp5)] [InlineData("6", LanguageVersion.CSharp6)] [InlineData("6.0", LanguageVersion.CSharp6)] [InlineData("7", LanguageVersion.CSharp7)] [InlineData("7.0", LanguageVersion.CSharp7)] [InlineData("7.1", LanguageVersion.CSharp7_1)] [InlineData("7.2", LanguageVersion.CSharp7_2)] [InlineData("7.3", LanguageVersion.CSharp7_3)] [InlineData("8", LanguageVersion.CSharp8)] [InlineData("8.0", LanguageVersion.CSharp8)] [InlineData("9", LanguageVersion.CSharp9)] [InlineData("9.0", LanguageVersion.CSharp9)] [InlineData("preview", LanguageVersion.Preview)] public void LangVersion_CanParseCorrectVersions(string value, LanguageVersion expectedVersion) { var parsedArgs = DefaultParse(new[] { $"/langversion:{value}", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(expectedVersion, parsedArgs.ParseOptions.LanguageVersion); Assert.Equal(expectedVersion, parsedArgs.ParseOptions.SpecifiedLanguageVersion); var scriptParsedArgs = ScriptParse(new[] { $"/langversion:{value}" }, WorkingDirectory); scriptParsedArgs.Errors.Verify(); Assert.Equal(expectedVersion, scriptParsedArgs.ParseOptions.LanguageVersion); Assert.Equal(expectedVersion, scriptParsedArgs.ParseOptions.SpecifiedLanguageVersion); } [Theory] [InlineData("6", "7", LanguageVersion.CSharp7)] [InlineData("7", "6", LanguageVersion.CSharp6)] [InlineData("7", "1", LanguageVersion.CSharp1)] [InlineData("6", "iso-1", LanguageVersion.CSharp1)] [InlineData("6", "iso-2", LanguageVersion.CSharp2)] [InlineData("6", "default", LanguageVersion.Default)] [InlineData("7", "default", LanguageVersion.Default)] [InlineData("iso-2", "6", LanguageVersion.CSharp6)] public void LangVersion_LatterVersionOverridesFormerOne(string formerValue, string latterValue, LanguageVersion expectedVersion) { var parsedArgs = DefaultParse(new[] { $"/langversion:{formerValue}", $"/langversion:{latterValue}", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(expectedVersion, parsedArgs.ParseOptions.SpecifiedLanguageVersion); } [Fact] public void LangVersion_DefaultMapsCorrectly() { LanguageVersion defaultEffectiveVersion = LanguageVersion.Default.MapSpecifiedToEffectiveVersion(); Assert.NotEqual(LanguageVersion.Default, defaultEffectiveVersion); var parsedArgs = DefaultParse(new[] { "/langversion:default", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(LanguageVersion.Default, parsedArgs.ParseOptions.SpecifiedLanguageVersion); Assert.Equal(defaultEffectiveVersion, parsedArgs.ParseOptions.LanguageVersion); } [Fact] public void LangVersion_LatestMapsCorrectly() { LanguageVersion latestEffectiveVersion = LanguageVersion.Latest.MapSpecifiedToEffectiveVersion(); Assert.NotEqual(LanguageVersion.Latest, latestEffectiveVersion); var parsedArgs = DefaultParse(new[] { "/langversion:latest", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(LanguageVersion.Latest, parsedArgs.ParseOptions.SpecifiedLanguageVersion); Assert.Equal(latestEffectiveVersion, parsedArgs.ParseOptions.LanguageVersion); } [Fact] public void LangVersion_NoValueSpecified() { var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(LanguageVersion.Default, parsedArgs.ParseOptions.SpecifiedLanguageVersion); } [Theory] [InlineData("iso-3")] [InlineData("iso1")] [InlineData("8.1")] [InlineData("10.1")] [InlineData("11")] [InlineData("1000")] public void LangVersion_BadVersion(string value) { DefaultParse(new[] { $"/langversion:{value}", "a.cs" }, WorkingDirectory).Errors.Verify( // error CS1617: Invalid option 'XXX' for /langversion. Use '/langversion:?' to list supported values. Diagnostic(ErrorCode.ERR_BadCompatMode).WithArguments(value).WithLocation(1, 1) ); } [Theory] [InlineData("0")] [InlineData("05")] [InlineData("07")] [InlineData("07.1")] [InlineData("08")] [InlineData("09")] public void LangVersion_LeadingZeroes(string value) { DefaultParse(new[] { $"/langversion:{value}", "a.cs" }, WorkingDirectory).Errors.Verify( // error CS8303: Specified language version 'XXX' cannot have leading zeroes Diagnostic(ErrorCode.ERR_LanguageVersionCannotHaveLeadingZeroes).WithArguments(value).WithLocation(1, 1)); } [Theory] [InlineData("/langversion")] [InlineData("/langversion:")] [InlineData("/LANGversion:")] public void LangVersion_NoVersion(string option) { DefaultParse(new[] { option, "a.cs" }, WorkingDirectory).Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for '/langversion:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/langversion:").WithLocation(1, 1)); } [Fact] public void LangVersion_LangVersions() { var args = DefaultParse(new[] { "/langversion:?" }, WorkingDirectory); args.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1) ); Assert.True(args.DisplayLangVersions); } [Fact] public void LanguageVersionAdded_Canary() { // When a new version is added, this test will break. This list must be checked: // - update the "UpgradeProject" codefixer // - update all the tests that call this canary // - update MaxSupportedLangVersion (a relevant test should break when new version is introduced) // - email release management to add to the release notes (see old example: https://github.com/dotnet/core/pull/1454) AssertEx.SetEqual(new[] { "default", "1", "2", "3", "4", "5", "6", "7.0", "7.1", "7.2", "7.3", "8.0", "9.0", "10.0", "latest", "latestmajor", "preview" }, Enum.GetValues(typeof(LanguageVersion)).Cast<LanguageVersion>().Select(v => v.ToDisplayString())); // For minor versions and new major versions, the format should be "x.y", such as "7.1" } [Fact] public void LanguageVersion_GetErrorCode() { var versions = Enum.GetValues(typeof(LanguageVersion)) .Cast<LanguageVersion>() .Except(new[] { LanguageVersion.Default, LanguageVersion.Latest, LanguageVersion.LatestMajor, LanguageVersion.Preview }) .Select(v => v.GetErrorCode()); var errorCodes = new[] { ErrorCode.ERR_FeatureNotAvailableInVersion1, ErrorCode.ERR_FeatureNotAvailableInVersion2, ErrorCode.ERR_FeatureNotAvailableInVersion3, ErrorCode.ERR_FeatureNotAvailableInVersion4, ErrorCode.ERR_FeatureNotAvailableInVersion5, ErrorCode.ERR_FeatureNotAvailableInVersion6, ErrorCode.ERR_FeatureNotAvailableInVersion7, ErrorCode.ERR_FeatureNotAvailableInVersion7_1, ErrorCode.ERR_FeatureNotAvailableInVersion7_2, ErrorCode.ERR_FeatureNotAvailableInVersion7_3, ErrorCode.ERR_FeatureNotAvailableInVersion8, ErrorCode.ERR_FeatureNotAvailableInVersion9, ErrorCode.ERR_FeatureNotAvailableInVersion10, }; AssertEx.SetEqual(versions, errorCodes); // The canary check is a reminder that this test needs to be updated when a language version is added LanguageVersionAdded_Canary(); } [Theory, InlineData(LanguageVersion.CSharp1, LanguageVersion.CSharp1), InlineData(LanguageVersion.CSharp2, LanguageVersion.CSharp2), InlineData(LanguageVersion.CSharp3, LanguageVersion.CSharp3), InlineData(LanguageVersion.CSharp4, LanguageVersion.CSharp4), InlineData(LanguageVersion.CSharp5, LanguageVersion.CSharp5), InlineData(LanguageVersion.CSharp6, LanguageVersion.CSharp6), InlineData(LanguageVersion.CSharp7, LanguageVersion.CSharp7), InlineData(LanguageVersion.CSharp7_1, LanguageVersion.CSharp7_1), InlineData(LanguageVersion.CSharp7_2, LanguageVersion.CSharp7_2), InlineData(LanguageVersion.CSharp7_3, LanguageVersion.CSharp7_3), InlineData(LanguageVersion.CSharp8, LanguageVersion.CSharp8), InlineData(LanguageVersion.CSharp9, LanguageVersion.CSharp9), InlineData(LanguageVersion.CSharp10, LanguageVersion.CSharp10), InlineData(LanguageVersion.CSharp10, LanguageVersion.LatestMajor), InlineData(LanguageVersion.CSharp10, LanguageVersion.Latest), InlineData(LanguageVersion.CSharp10, LanguageVersion.Default), InlineData(LanguageVersion.Preview, LanguageVersion.Preview), ] public void LanguageVersion_MapSpecifiedToEffectiveVersion(LanguageVersion expectedMappedVersion, LanguageVersion input) { Assert.Equal(expectedMappedVersion, input.MapSpecifiedToEffectiveVersion()); Assert.True(expectedMappedVersion.IsValid()); // The canary check is a reminder that this test needs to be updated when a language version is added LanguageVersionAdded_Canary(); } [Theory, InlineData("iso-1", true, LanguageVersion.CSharp1), InlineData("ISO-1", true, LanguageVersion.CSharp1), InlineData("iso-2", true, LanguageVersion.CSharp2), InlineData("1", true, LanguageVersion.CSharp1), InlineData("1.0", true, LanguageVersion.CSharp1), InlineData("2", true, LanguageVersion.CSharp2), InlineData("2.0", true, LanguageVersion.CSharp2), InlineData("3", true, LanguageVersion.CSharp3), InlineData("3.0", true, LanguageVersion.CSharp3), InlineData("4", true, LanguageVersion.CSharp4), InlineData("4.0", true, LanguageVersion.CSharp4), InlineData("5", true, LanguageVersion.CSharp5), InlineData("5.0", true, LanguageVersion.CSharp5), InlineData("05", false, LanguageVersion.Default), InlineData("6", true, LanguageVersion.CSharp6), InlineData("6.0", true, LanguageVersion.CSharp6), InlineData("7", true, LanguageVersion.CSharp7), InlineData("7.0", true, LanguageVersion.CSharp7), InlineData("07", false, LanguageVersion.Default), InlineData("7.1", true, LanguageVersion.CSharp7_1), InlineData("7.2", true, LanguageVersion.CSharp7_2), InlineData("7.3", true, LanguageVersion.CSharp7_3), InlineData("8", true, LanguageVersion.CSharp8), InlineData("8.0", true, LanguageVersion.CSharp8), InlineData("9", true, LanguageVersion.CSharp9), InlineData("9.0", true, LanguageVersion.CSharp9), InlineData("10", true, LanguageVersion.CSharp10), InlineData("10.0", true, LanguageVersion.CSharp10), InlineData("08", false, LanguageVersion.Default), InlineData("07.1", false, LanguageVersion.Default), InlineData("default", true, LanguageVersion.Default), InlineData("latest", true, LanguageVersion.Latest), InlineData("latestmajor", true, LanguageVersion.LatestMajor), InlineData("preview", true, LanguageVersion.Preview), InlineData("latestpreview", false, LanguageVersion.Default), InlineData(null, true, LanguageVersion.Default), InlineData("bad", false, LanguageVersion.Default)] public void LanguageVersion_TryParseDisplayString(string input, bool success, LanguageVersion expected) { Assert.Equal(success, LanguageVersionFacts.TryParse(input, out var version)); Assert.Equal(expected, version); // The canary check is a reminder that this test needs to be updated when a language version is added LanguageVersionAdded_Canary(); } [Fact] public void LanguageVersion_TryParseTurkishDisplayString() { var originalCulture = Thread.CurrentThread.CurrentCulture; Thread.CurrentThread.CurrentCulture = new CultureInfo("tr-TR", useUserOverride: false); Assert.True(LanguageVersionFacts.TryParse("ISO-1", out var version)); Assert.Equal(LanguageVersion.CSharp1, version); Thread.CurrentThread.CurrentCulture = originalCulture; } [Fact] public void LangVersion_ListLangVersions() { var dir = Temp.CreateDirectory(); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/langversion:?" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var expected = Enum.GetValues(typeof(LanguageVersion)).Cast<LanguageVersion>() .Select(v => v.ToDisplayString()); var actual = outWriter.ToString(); var acceptableSurroundingChar = new[] { '\r', '\n', '(', ')', ' ' }; foreach (var version in expected) { if (version == "latest") continue; var foundIndex = actual.IndexOf(version); Assert.True(foundIndex > 0, $"Missing version '{version}'"); Assert.True(Array.IndexOf(acceptableSurroundingChar, actual[foundIndex - 1]) >= 0); Assert.True(Array.IndexOf(acceptableSurroundingChar, actual[foundIndex + version.Length]) >= 0); } } [Fact] [WorkItem(546961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546961")] public void Define() { var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); Assert.Equal(0, parsedArgs.ParseOptions.PreprocessorSymbolNames.Count()); Assert.False(parsedArgs.Errors.Any()); parsedArgs = DefaultParse(new[] { "/d:GOO", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.ParseOptions.PreprocessorSymbolNames.Count()); Assert.Contains("GOO", parsedArgs.ParseOptions.PreprocessorSymbolNames); Assert.False(parsedArgs.Errors.Any()); parsedArgs = DefaultParse(new[] { "/d:GOO;BAR,ZIP", "a.cs" }, WorkingDirectory); Assert.Equal(3, parsedArgs.ParseOptions.PreprocessorSymbolNames.Count()); Assert.Contains("GOO", parsedArgs.ParseOptions.PreprocessorSymbolNames); Assert.Contains("BAR", parsedArgs.ParseOptions.PreprocessorSymbolNames); Assert.Contains("ZIP", parsedArgs.ParseOptions.PreprocessorSymbolNames); Assert.False(parsedArgs.Errors.Any()); parsedArgs = DefaultParse(new[] { "/d:GOO;4X", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.ParseOptions.PreprocessorSymbolNames.Count()); Assert.Contains("GOO", parsedArgs.ParseOptions.PreprocessorSymbolNames); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.WRN_DefineIdentifierRequired, parsedArgs.Errors.First().Code); Assert.Equal("4X", parsedArgs.Errors.First().Arguments[0]); IEnumerable<Diagnostic> diagnostics; // The docs say /d:def1[;def2] string compliant = "def1;def2;def3"; var expected = new[] { "def1", "def2", "def3" }; var parsed = CSharpCommandLineParser.ParseConditionalCompilationSymbols(compliant, out diagnostics); diagnostics.Verify(); Assert.Equal<string>(expected, parsed); // Bug 17360: Dev11 allows for a terminating semicolon var dev11Compliant = "def1;def2;def3;"; parsed = CSharpCommandLineParser.ParseConditionalCompilationSymbols(dev11Compliant, out diagnostics); diagnostics.Verify(); Assert.Equal<string>(expected, parsed); // And comma dev11Compliant = "def1,def2,def3,"; parsed = CSharpCommandLineParser.ParseConditionalCompilationSymbols(dev11Compliant, out diagnostics); diagnostics.Verify(); Assert.Equal<string>(expected, parsed); // This breaks everything var nonCompliant = "def1;;def2;"; parsed = CSharpCommandLineParser.ParseConditionalCompilationSymbols(nonCompliant, out diagnostics); diagnostics.Verify( // warning CS2029: Invalid name for a preprocessing symbol; '' is not a valid identifier Diagnostic(ErrorCode.WRN_DefineIdentifierRequired).WithArguments("")); Assert.Equal(new[] { "def1", "def2" }, parsed); // Bug 17360 parsedArgs = DefaultParse(new[] { "/d:public1;public2;", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); } [Fact] public void Debug() { var platformPdbKind = PathUtilities.IsUnixLikePlatform ? DebugInformationFormat.PortablePdb : DebugInformationFormat.Pdb; var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.False(parsedArgs.EmitPdb); Assert.False(parsedArgs.EmitPdbFile); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.False(parsedArgs.EmitPdb); Assert.False(parsedArgs.EmitPdbFile); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.True(parsedArgs.EmitPdbFile); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.True(parsedArgs.EmitPdbFile); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug+", "/debug-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.False(parsedArgs.EmitPdb); Assert.False(parsedArgs.EmitPdbFile); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug:full", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug:FULL", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); Assert.Equal(Path.Combine(WorkingDirectory, "a.pdb"), parsedArgs.GetPdbFilePath("a.dll")); parsedArgs = DefaultParse(new[] { "/debug:pdbonly", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug:portable", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(DebugInformationFormat.PortablePdb, parsedArgs.EmitOptions.DebugInformationFormat); Assert.Equal(Path.Combine(WorkingDirectory, "a.pdb"), parsedArgs.GetPdbFilePath("a.dll")); parsedArgs = DefaultParse(new[] { "/debug:embedded", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(DebugInformationFormat.Embedded, parsedArgs.EmitOptions.DebugInformationFormat); Assert.Equal(Path.Combine(WorkingDirectory, "a.pdb"), parsedArgs.GetPdbFilePath("a.dll")); parsedArgs = DefaultParse(new[] { "/debug:PDBONLY", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug:full", "/debug:pdbonly", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug:pdbonly", "/debug:full", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(platformPdbKind, parsedArgs.EmitOptions.DebugInformationFormat); parsedArgs = DefaultParse(new[] { "/debug:pdbonly", "/debug-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.False(parsedArgs.EmitPdb); Assert.Equal(platformPdbKind, parsedArgs.EmitOptions.DebugInformationFormat); parsedArgs = DefaultParse(new[] { "/debug:pdbonly", "/debug-", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(platformPdbKind, parsedArgs.EmitOptions.DebugInformationFormat); parsedArgs = DefaultParse(new[] { "/debug:pdbonly", "/debug-", "/debug+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(platformPdbKind, parsedArgs.EmitOptions.DebugInformationFormat); parsedArgs = DefaultParse(new[] { "/debug:embedded", "/debug-", "/debug+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(DebugInformationFormat.Embedded, parsedArgs.EmitOptions.DebugInformationFormat); parsedArgs = DefaultParse(new[] { "/debug:embedded", "/debug-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.False(parsedArgs.EmitPdb); Assert.Equal(DebugInformationFormat.Embedded, parsedArgs.EmitOptions.DebugInformationFormat); parsedArgs = DefaultParse(new[] { "/debug:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "debug")); parsedArgs = DefaultParse(new[] { "/debug:+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadDebugType).WithArguments("+")); parsedArgs = DefaultParse(new[] { "/debug:invalid", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadDebugType).WithArguments("invalid")); parsedArgs = DefaultParse(new[] { "/debug-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/debug-:")); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void Pdb() { var parsedArgs = DefaultParse(new[] { "/pdb:something", "a.cs" }, WorkingDirectory); Assert.Equal(Path.Combine(WorkingDirectory, "something.pdb"), parsedArgs.PdbPath); Assert.Equal(Path.Combine(WorkingDirectory, "something.pdb"), parsedArgs.GetPdbFilePath("a.dll")); Assert.False(parsedArgs.EmitPdbFile); parsedArgs = DefaultParse(new[] { "/pdb:something", "/debug:embedded", "a.cs" }, WorkingDirectory); Assert.Equal(Path.Combine(WorkingDirectory, "something.pdb"), parsedArgs.PdbPath); Assert.Equal(Path.Combine(WorkingDirectory, "something.pdb"), parsedArgs.GetPdbFilePath("a.dll")); Assert.False(parsedArgs.EmitPdbFile); parsedArgs = DefaultParse(new[] { "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Null(parsedArgs.PdbPath); Assert.True(parsedArgs.EmitPdbFile); Assert.Equal(Path.Combine(WorkingDirectory, "a.pdb"), parsedArgs.GetPdbFilePath("a.dll")); parsedArgs = DefaultParse(new[] { "/pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/pdb")); Assert.Equal(Path.Combine(WorkingDirectory, "a.pdb"), parsedArgs.GetPdbFilePath("a.dll")); parsedArgs = DefaultParse(new[] { "/pdb:", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/pdb:")); parsedArgs = DefaultParse(new[] { "/pdb:something", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); // temp: path changed //parsedArgs = DefaultParse(new[] { "/debug", "/pdb:.x", "a.cs" }, baseDirectory); //parsedArgs.Errors.Verify( // // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long // Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".x")); parsedArgs = DefaultParse(new[] { @"/pdb:""""", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2005: Missing file specification for '/pdb:""' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments(@"/pdb:""""").WithLocation(1, 1)); parsedArgs = DefaultParse(new[] { "/pdb:C:\\", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("C:\\")); // Should preserve fully qualified paths parsedArgs = DefaultParse(new[] { @"/pdb:C:\MyFolder\MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\MyFolder\MyPdb.pdb", parsedArgs.PdbPath); // Should preserve fully qualified paths parsedArgs = DefaultParse(new[] { @"/pdb:c:\MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"c:\MyPdb.pdb", parsedArgs.PdbPath); parsedArgs = DefaultParse(new[] { @"/pdb:\MyFolder\MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(Path.GetPathRoot(WorkingDirectory), @"MyFolder\MyPdb.pdb"), parsedArgs.PdbPath); // Should handle quotes parsedArgs = DefaultParse(new[] { @"/pdb:""C:\My Folder\MyPdb.pdb""", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\My Folder\MyPdb.pdb", parsedArgs.PdbPath); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/pdb:MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(FileUtilities.ResolveRelativePath("MyPdb.pdb", WorkingDirectory), parsedArgs.PdbPath); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/pdb:..\MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); // Temp: Path info changed // Assert.Equal(FileUtilities.ResolveRelativePath("MyPdb.pdb", "..\\", baseDirectory), parsedArgs.PdbPath); parsedArgs = DefaultParse(new[] { @"/pdb:\\b", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"\\b")); Assert.Null(parsedArgs.PdbPath); parsedArgs = DefaultParse(new[] { @"/pdb:\\b\OkFileName.pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"\\b\OkFileName.pdb")); Assert.Null(parsedArgs.PdbPath); parsedArgs = DefaultParse(new[] { @"/pdb:\\server\share\MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"\\server\share\MyPdb.pdb", parsedArgs.PdbPath); // invalid name: parsedArgs = DefaultParse(new[] { "/pdb:a.b\0b", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a.b\0b")); Assert.Null(parsedArgs.PdbPath); parsedArgs = DefaultParse(new[] { "/pdb:a\uD800b.pdb", "/debug", "a.cs" }, WorkingDirectory); //parsedArgs.Errors.Verify( // Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a\uD800b.pdb")); Assert.Null(parsedArgs.PdbPath); // Dev11 reports CS0016: Could not write to output file 'd:\Temp\q\a<>.z' parsedArgs = DefaultParse(new[] { @"/pdb:""a<>.pdb""", "a.vb" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2021: File name 'a<>.pdb' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a<>.pdb")); Assert.Null(parsedArgs.PdbPath); parsedArgs = DefaultParse(new[] { "/pdb:.x", "/debug", "a.cs" }, WorkingDirectory); //parsedArgs.Errors.Verify( // // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long // Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".x")); Assert.Null(parsedArgs.PdbPath); } [Fact] public void SourceLink() { var parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug:portable", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, "sl.json"), parsedArgs.SourceLink); parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug:embedded", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, "sl.json"), parsedArgs.SourceLink); parsedArgs = DefaultParse(new[] { @"/sourcelink:""s l.json""", "/debug:embedded", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, "s l.json"), parsedArgs.SourceLink); parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug:full", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug:pdbonly", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SourceLinkRequiresPdb)); parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SourceLinkRequiresPdb)); } [Fact] public void SourceLink_EndToEnd_EmbeddedPortable() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("a.cs"); src.WriteAllText(@"class C { public static void Main() {} }"); var sl = dir.CreateFile("sl.json"); sl.WriteAllText(@"{ ""documents"" : {} }"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/debug:embedded", "/sourcelink:sl.json", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var peStream = File.OpenRead(Path.Combine(dir.Path, "a.exe")); using (var peReader = new PEReader(peStream)) { var entry = peReader.ReadDebugDirectory().Single(e => e.Type == DebugDirectoryEntryType.EmbeddedPortablePdb); using (var mdProvider = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(entry)) { var blob = mdProvider.GetMetadataReader().GetSourceLinkBlob(); AssertEx.Equal(File.ReadAllBytes(sl.Path), blob); } } // Clean up temp files CleanupAllGeneratedFiles(src.Path); } [Fact] public void SourceLink_EndToEnd_Portable() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("a.cs"); src.WriteAllText(@"class C { public static void Main() {} }"); var sl = dir.CreateFile("sl.json"); sl.WriteAllText(@"{ ""documents"" : {} }"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/debug:portable", "/sourcelink:sl.json", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var pdbStream = File.OpenRead(Path.Combine(dir.Path, "a.pdb")); using (var mdProvider = MetadataReaderProvider.FromPortablePdbStream(pdbStream)) { var blob = mdProvider.GetMetadataReader().GetSourceLinkBlob(); AssertEx.Equal(File.ReadAllBytes(sl.Path), blob); } // Clean up temp files CleanupAllGeneratedFiles(src.Path); } [Fact] public void SourceLink_EndToEnd_Windows() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("a.cs"); src.WriteAllText(@"class C { public static void Main() {} }"); var sl = dir.CreateFile("sl.json"); byte[] slContent = Encoding.UTF8.GetBytes(@"{ ""documents"" : {} }"); sl.WriteAllBytes(slContent); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/debug:full", "/sourcelink:sl.json", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var pdbStream = File.OpenRead(Path.Combine(dir.Path, "a.pdb")); var actualData = PdbValidation.GetSourceLinkData(pdbStream); AssertEx.Equal(slContent, actualData); // Clean up temp files CleanupAllGeneratedFiles(src.Path); } [Fact] public void Embed() { var parsedArgs = DefaultParse(new[] { "a.cs " }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Empty(parsedArgs.EmbeddedFiles); parsedArgs = DefaultParse(new[] { "/embed", "/debug:portable", "a.cs", "b.cs", "c.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(parsedArgs.SourceFiles, parsedArgs.EmbeddedFiles); AssertEx.Equal( new[] { "a.cs", "b.cs", "c.cs" }.Select(f => Path.Combine(WorkingDirectory, f)), parsedArgs.EmbeddedFiles.Select(f => f.Path)); parsedArgs = DefaultParse(new[] { "/embed:a.cs", "/embed:b.cs", "/debug:embedded", "a.cs", "b.cs", "c.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal( new[] { "a.cs", "b.cs" }.Select(f => Path.Combine(WorkingDirectory, f)), parsedArgs.EmbeddedFiles.Select(f => f.Path)); parsedArgs = DefaultParse(new[] { "/embed:a.cs;b.cs", "/debug:portable", "a.cs", "b.cs", "c.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal( new[] { "a.cs", "b.cs" }.Select(f => Path.Combine(WorkingDirectory, f)), parsedArgs.EmbeddedFiles.Select(f => f.Path)); parsedArgs = DefaultParse(new[] { "/embed:a.cs,b.cs", "/debug:portable", "a.cs", "b.cs", "c.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal( new[] { "a.cs", "b.cs" }.Select(f => Path.Combine(WorkingDirectory, f)), parsedArgs.EmbeddedFiles.Select(f => f.Path)); parsedArgs = DefaultParse(new[] { @"/embed:""a,b.cs""", "/debug:portable", "a,b.cs", "c.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal( new[] { "a,b.cs" }.Select(f => Path.Combine(WorkingDirectory, f)), parsedArgs.EmbeddedFiles.Select(f => f.Path)); parsedArgs = DefaultParse(new[] { "/embed:a.txt", "/embed", "/debug:portable", "a.cs", "b.cs", "c.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); ; AssertEx.Equal( new[] { "a.txt", "a.cs", "b.cs", "c.cs" }.Select(f => Path.Combine(WorkingDirectory, f)), parsedArgs.EmbeddedFiles.Select(f => f.Path)); parsedArgs = DefaultParse(new[] { "/embed", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_CannotEmbedWithoutPdb)); parsedArgs = DefaultParse(new[] { "/embed:a.txt", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_CannotEmbedWithoutPdb)); parsedArgs = DefaultParse(new[] { "/embed", "/debug-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_CannotEmbedWithoutPdb)); parsedArgs = DefaultParse(new[] { "/embed:a.txt", "/debug-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_CannotEmbedWithoutPdb)); parsedArgs = DefaultParse(new[] { "/embed", "/debug:full", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/embed", "/debug:pdbonly", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/embed", "/debug+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); } [Theory] [InlineData("/debug:portable", "/embed", new[] { "embed.cs", "embed2.cs", "embed.xyz" })] [InlineData("/debug:portable", "/embed:embed.cs", new[] { "embed.cs", "embed.xyz" })] [InlineData("/debug:portable", "/embed:embed2.cs", new[] { "embed2.cs" })] [InlineData("/debug:portable", "/embed:embed.xyz", new[] { "embed.xyz" })] [InlineData("/debug:embedded", "/embed", new[] { "embed.cs", "embed2.cs", "embed.xyz" })] [InlineData("/debug:embedded", "/embed:embed.cs", new[] { "embed.cs", "embed.xyz" })] [InlineData("/debug:embedded", "/embed:embed2.cs", new[] { "embed2.cs" })] [InlineData("/debug:embedded", "/embed:embed.xyz", new[] { "embed.xyz" })] public void Embed_EndToEnd_Portable(string debugSwitch, string embedSwitch, string[] expectedEmbedded) { // embed.cs: large enough to compress, has #line directives const string embed_cs = @"/////////////////////////////////////////////////////////////////////////////// class Program { static void Main() { #line 1 ""embed.xyz"" System.Console.WriteLine(""Hello, World""); #line 3 System.Console.WriteLine(""Goodbye, World""); } } ///////////////////////////////////////////////////////////////////////////////"; // embed2.cs: small enough to not compress, no sequence points const string embed2_cs = @"class C { }"; // target of #line const string embed_xyz = @"print Hello, World print Goodbye, World"; Assert.True(embed_cs.Length >= EmbeddedText.CompressionThreshold); Assert.True(embed2_cs.Length < EmbeddedText.CompressionThreshold); var dir = Temp.CreateDirectory(); var src = dir.CreateFile("embed.cs"); var src2 = dir.CreateFile("embed2.cs"); var txt = dir.CreateFile("embed.xyz"); src.WriteAllText(embed_cs); src2.WriteAllText(embed2_cs); txt.WriteAllText(embed_xyz); var expectedEmbeddedMap = new Dictionary<string, string>(); if (expectedEmbedded.Contains("embed.cs")) { expectedEmbeddedMap.Add(src.Path, embed_cs); } if (expectedEmbedded.Contains("embed2.cs")) { expectedEmbeddedMap.Add(src2.Path, embed2_cs); } if (expectedEmbedded.Contains("embed.xyz")) { expectedEmbeddedMap.Add(txt.Path, embed_xyz); } var output = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", debugSwitch, embedSwitch, "embed.cs", "embed2.cs" }); int exitCode = csc.Run(output); Assert.Equal("", output.ToString().Trim()); Assert.Equal(0, exitCode); switch (debugSwitch) { case "/debug:embedded": ValidateEmbeddedSources_Portable(expectedEmbeddedMap, dir, isEmbeddedPdb: true); break; case "/debug:portable": ValidateEmbeddedSources_Portable(expectedEmbeddedMap, dir, isEmbeddedPdb: false); break; case "/debug:full": ValidateEmbeddedSources_Windows(expectedEmbeddedMap, dir); break; } Assert.Empty(expectedEmbeddedMap); CleanupAllGeneratedFiles(src.Path); } private static void ValidateEmbeddedSources_Portable(Dictionary<string, string> expectedEmbeddedMap, TempDirectory dir, bool isEmbeddedPdb) { using (var peReader = new PEReader(File.OpenRead(Path.Combine(dir.Path, "embed.exe")))) { var entry = peReader.ReadDebugDirectory().SingleOrDefault(e => e.Type == DebugDirectoryEntryType.EmbeddedPortablePdb); Assert.Equal(isEmbeddedPdb, entry.DataSize > 0); using (var mdProvider = isEmbeddedPdb ? peReader.ReadEmbeddedPortablePdbDebugDirectoryData(entry) : MetadataReaderProvider.FromPortablePdbStream(File.OpenRead(Path.Combine(dir.Path, "embed.pdb")))) { var mdReader = mdProvider.GetMetadataReader(); foreach (var handle in mdReader.Documents) { var doc = mdReader.GetDocument(handle); var docPath = mdReader.GetString(doc.Name); SourceText embeddedSource = mdReader.GetEmbeddedSource(handle); if (embeddedSource == null) { continue; } Assert.Equal(expectedEmbeddedMap[docPath], embeddedSource.ToString()); Assert.True(expectedEmbeddedMap.Remove(docPath)); } } } } private static void ValidateEmbeddedSources_Windows(Dictionary<string, string> expectedEmbeddedMap, TempDirectory dir) { ISymUnmanagedReader5 symReader = null; try { symReader = SymReaderFactory.CreateReader(File.OpenRead(Path.Combine(dir.Path, "embed.pdb"))); foreach (var doc in symReader.GetDocuments()) { var docPath = doc.GetName(); var sourceBlob = doc.GetEmbeddedSource(); if (sourceBlob.Array == null) { continue; } var sourceStr = Encoding.UTF8.GetString(sourceBlob.Array, sourceBlob.Offset, sourceBlob.Count); Assert.Equal(expectedEmbeddedMap[docPath], sourceStr); Assert.True(expectedEmbeddedMap.Remove(docPath)); } } catch { symReader?.Dispose(); } } private static void ValidateWrittenSources(Dictionary<string, Dictionary<string, string>> expectedFilesMap, Encoding encoding = null) { foreach ((var dirPath, var fileMap) in expectedFilesMap.ToArray()) { foreach (var file in Directory.GetFiles(dirPath)) { var name = Path.GetFileName(file); var content = File.ReadAllText(file, encoding ?? Encoding.UTF8); Assert.Equal(fileMap[name], content); Assert.True(fileMap.Remove(name)); } Assert.Empty(fileMap); Assert.True(expectedFilesMap.Remove(dirPath)); } Assert.Empty(expectedFilesMap); } [Fact] public void Optimize() { var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(new CSharpCompilationOptions(OutputKind.ConsoleApplication).OptimizationLevel, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new[] { "/optimize-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OptimizationLevel.Debug, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new[] { "/optimize", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OptimizationLevel.Release, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new[] { "/optimize+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OptimizationLevel.Release, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new[] { "/optimize+", "/optimize-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OptimizationLevel.Debug, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new[] { "/optimize:+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/optimize:+")); parsedArgs = DefaultParse(new[] { "/optimize:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/optimize:")); parsedArgs = DefaultParse(new[] { "/optimize-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/optimize-:")); parsedArgs = DefaultParse(new[] { "/o-", "a.cs" }, WorkingDirectory); Assert.Equal(OptimizationLevel.Debug, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new string[] { "/o", "a.cs" }, WorkingDirectory); Assert.Equal(OptimizationLevel.Release, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new string[] { "/o+", "a.cs" }, WorkingDirectory); Assert.Equal(OptimizationLevel.Release, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new string[] { "/o+", "/optimize-", "a.cs" }, WorkingDirectory); Assert.Equal(OptimizationLevel.Debug, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new string[] { "/o:+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/o:+")); parsedArgs = DefaultParse(new string[] { "/o:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/o:")); parsedArgs = DefaultParse(new string[] { "/o-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/o-:")); } [Fact] public void Deterministic() { var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.Deterministic); parsedArgs = DefaultParse(new[] { "/deterministic+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.Deterministic); parsedArgs = DefaultParse(new[] { "/deterministic", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.Deterministic); parsedArgs = DefaultParse(new[] { "/deterministic-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.Deterministic); } [Fact] public void ParseReferences() { var parsedArgs = DefaultParse(new string[] { "/r:goo.dll", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(2, parsedArgs.MetadataReferences.Length); parsedArgs = DefaultParse(new string[] { "/r:goo.dll;", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(2, parsedArgs.MetadataReferences.Length); Assert.Equal(MscorlibFullPath, parsedArgs.MetadataReferences[0].Reference); Assert.Equal(MetadataReferenceProperties.Assembly, parsedArgs.MetadataReferences[0].Properties); Assert.Equal("goo.dll", parsedArgs.MetadataReferences[1].Reference); Assert.Equal(MetadataReferenceProperties.Assembly, parsedArgs.MetadataReferences[1].Properties); parsedArgs = DefaultParse(new string[] { @"/l:goo.dll", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(2, parsedArgs.MetadataReferences.Length); Assert.Equal(MscorlibFullPath, parsedArgs.MetadataReferences[0].Reference); Assert.Equal(MetadataReferenceProperties.Assembly, parsedArgs.MetadataReferences[0].Properties); Assert.Equal("goo.dll", parsedArgs.MetadataReferences[1].Reference); Assert.Equal(MetadataReferenceProperties.Assembly.WithEmbedInteropTypes(true), parsedArgs.MetadataReferences[1].Properties); parsedArgs = DefaultParse(new string[] { @"/addmodule:goo.dll", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(2, parsedArgs.MetadataReferences.Length); Assert.Equal(MscorlibFullPath, parsedArgs.MetadataReferences[0].Reference); Assert.Equal(MetadataReferenceProperties.Assembly, parsedArgs.MetadataReferences[0].Properties); Assert.Equal("goo.dll", parsedArgs.MetadataReferences[1].Reference); Assert.Equal(MetadataReferenceProperties.Module, parsedArgs.MetadataReferences[1].Properties); parsedArgs = DefaultParse(new string[] { @"/r:a=goo.dll", "/l:b=bar.dll", "/addmodule:c=mod.dll", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(4, parsedArgs.MetadataReferences.Length); Assert.Equal(MscorlibFullPath, parsedArgs.MetadataReferences[0].Reference); Assert.Equal(MetadataReferenceProperties.Assembly, parsedArgs.MetadataReferences[0].Properties); Assert.Equal("goo.dll", parsedArgs.MetadataReferences[1].Reference); Assert.Equal(MetadataReferenceProperties.Assembly.WithAliases(new[] { "a" }), parsedArgs.MetadataReferences[1].Properties); Assert.Equal("bar.dll", parsedArgs.MetadataReferences[2].Reference); Assert.Equal(MetadataReferenceProperties.Assembly.WithAliases(new[] { "b" }).WithEmbedInteropTypes(true), parsedArgs.MetadataReferences[2].Properties); Assert.Equal("c=mod.dll", parsedArgs.MetadataReferences[3].Reference); Assert.Equal(MetadataReferenceProperties.Module, parsedArgs.MetadataReferences[3].Properties); // TODO: multiple files, quotes, etc. } [Fact] public void ParseAnalyzers() { var parsedArgs = DefaultParse(new string[] { @"/a:goo.dll", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(1, parsedArgs.AnalyzerReferences.Length); Assert.Equal("goo.dll", parsedArgs.AnalyzerReferences[0].FilePath); parsedArgs = DefaultParse(new string[] { @"/analyzer:goo.dll", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(1, parsedArgs.AnalyzerReferences.Length); Assert.Equal("goo.dll", parsedArgs.AnalyzerReferences[0].FilePath); parsedArgs = DefaultParse(new string[] { "/analyzer:\"goo.dll\"", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(1, parsedArgs.AnalyzerReferences.Length); Assert.Equal("goo.dll", parsedArgs.AnalyzerReferences[0].FilePath); parsedArgs = DefaultParse(new string[] { @"/a:goo.dll;bar.dll", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(2, parsedArgs.AnalyzerReferences.Length); Assert.Equal("goo.dll", parsedArgs.AnalyzerReferences[0].FilePath); Assert.Equal("bar.dll", parsedArgs.AnalyzerReferences[1].FilePath); parsedArgs = DefaultParse(new string[] { @"/a:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/a:")); parsedArgs = DefaultParse(new string[] { "/a", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/a")); } [Fact] public void Analyzers_Missing() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/a:missing.dll", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS0006: Metadata file 'missing.dll' could not be found", outWriter.ToString().Trim()); // Clean up temp files CleanupAllGeneratedFiles(file.Path); } [Fact] public void Analyzers_Empty() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/a:" + typeof(object).Assembly.Location, "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.DoesNotContain("warning", outWriter.ToString()); CleanupAllGeneratedFiles(file.Path); } private TempFile CreateRuleSetFile(string source) { var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.ruleset"); file.WriteAllText(source); return file; } [Fact] public void RuleSetSwitchPositive() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> <Rule Id=""CA1013"" Action=""Warning"" /> <Rule Id=""CA1014"" Action=""None"" /> </Rules> </RuleSet> "; var file = CreateRuleSetFile(source); var parsedArgs = DefaultParse(new string[] { @"/ruleset:" + file.Path, "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(expected: file.Path, actual: parsedArgs.RuleSetPath); Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions.ContainsKey("CA1012")); Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions["CA1012"] == ReportDiagnostic.Error); Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions.ContainsKey("CA1013")); Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions["CA1013"] == ReportDiagnostic.Warn); Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions.ContainsKey("CA1014")); Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions["CA1014"] == ReportDiagnostic.Suppress); Assert.True(parsedArgs.CompilationOptions.GeneralDiagnosticOption == ReportDiagnostic.Warn); } [Fact] public void RuleSetSwitchQuoted() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> <Rule Id=""CA1013"" Action=""Warning"" /> <Rule Id=""CA1014"" Action=""None"" /> </Rules> </RuleSet> "; var file = CreateRuleSetFile(source); var parsedArgs = DefaultParse(new string[] { @"/ruleset:" + "\"" + file.Path + "\"", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(expected: file.Path, actual: parsedArgs.RuleSetPath); } [Fact] public void RuleSetSwitchParseErrors() { var parsedArgs = DefaultParse(new string[] { @"/ruleset", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "ruleset")); Assert.Null(parsedArgs.RuleSetPath); parsedArgs = DefaultParse(new string[] { @"/ruleset:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "ruleset")); Assert.Null(parsedArgs.RuleSetPath); parsedArgs = DefaultParse(new string[] { @"/ruleset:blah", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_CantReadRulesetFile).WithArguments(Path.Combine(TempRoot.Root, "blah"), "File not found.")); Assert.Equal(expected: Path.Combine(TempRoot.Root, "blah"), actual: parsedArgs.RuleSetPath); parsedArgs = DefaultParse(new string[] { @"/ruleset:blah;blah.ruleset", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_CantReadRulesetFile).WithArguments(Path.Combine(TempRoot.Root, "blah;blah.ruleset"), "File not found.")); Assert.Equal(expected: Path.Combine(TempRoot.Root, "blah;blah.ruleset"), actual: parsedArgs.RuleSetPath); var file = CreateRuleSetFile("Random text"); parsedArgs = DefaultParse(new string[] { @"/ruleset:" + file.Path, "a.cs" }, WorkingDirectory); //parsedArgs.Errors.Verify( // Diagnostic(ErrorCode.ERR_CantReadRulesetFile).WithArguments(file.Path, "Data at the root level is invalid. Line 1, position 1.")); Assert.Equal(expected: file.Path, actual: parsedArgs.RuleSetPath); var err = parsedArgs.Errors.Single(); Assert.Equal((int)ErrorCode.ERR_CantReadRulesetFile, err.Code); Assert.Equal(2, err.Arguments.Count); Assert.Equal(file.Path, (string)err.Arguments[0]); var currentUICultureName = Thread.CurrentThread.CurrentUICulture.Name; if (currentUICultureName.Length == 0 || currentUICultureName.StartsWith("en", StringComparison.OrdinalIgnoreCase)) { Assert.Equal("Data at the root level is invalid. Line 1, position 1.", (string)err.Arguments[1]); } } [WorkItem(892467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/892467")] [Fact] public void Analyzers_Found() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); // This assembly has a MockAbstractDiagnosticAnalyzer type which should get run by this compilation. var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); // Diagnostic thrown Assert.True(outWriter.ToString().Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared")); // Diagnostic cannot be instantiated Assert.True(outWriter.ToString().Contains("warning CS8032")); CleanupAllGeneratedFiles(file.Path); } [Fact] public void Analyzers_WithRuleSet() { string source = @" class C { int x; } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); string rulesetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Warning01"" Action=""Error"" /> </Rules> </RuleSet> "; var ruleSetFile = CreateRuleSetFile(rulesetSource); var outWriter = new StringWriter(CultureInfo.InvariantCulture); // This assembly has a MockAbstractDiagnosticAnalyzer type which should get run by this compilation. var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.cs", "/ruleset:" + ruleSetFile.Path }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); // Diagnostic thrown as error. Assert.True(outWriter.ToString().Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared")); // Clean up temp files CleanupAllGeneratedFiles(file.Path); } [WorkItem(912906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/912906")] [Fact] public void Analyzers_CommandLineOverridesRuleset1() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); string rulesetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> </RuleSet> "; var ruleSetFile = CreateRuleSetFile(rulesetSource); var outWriter = new StringWriter(CultureInfo.InvariantCulture); // This assembly has a MockAbstractDiagnosticAnalyzer type which should get run by this compilation. var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.cs", "/ruleset:" + ruleSetFile.Path, "/warnaserror+", "/nowarn:8032" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); // Diagnostic thrown as error: command line always overrides ruleset. Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.cs", "/warnaserror+", "/ruleset:" + ruleSetFile.Path, "/nowarn:8032" }); exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); // Diagnostic thrown as error: command line always overrides ruleset. Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", outWriter.ToString(), StringComparison.Ordinal); // Clean up temp files CleanupAllGeneratedFiles(file.Path); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_GeneralCommandLineOptionOverridesGeneralRuleSetOption() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Error); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_GeneralWarnAsErrorPromotesWarningFromRuleSet() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Error); Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Error); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_GeneralWarnAsErrorDoesNotPromoteInfoFromRuleSet() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Info"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Error); Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Info); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_SpecificWarnAsErrorPromotesInfoFromRuleSet() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Info"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+:Test001", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Default); Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Error); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_GeneralWarnAsErrorMinusResetsRules() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+", "/warnaserror-", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Default); Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Warn); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_SpecificWarnAsErrorMinusResetsRules() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+", "/warnaserror-:Test001", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Error); Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Warn); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_SpecificWarnAsErrorMinusDefaultsRuleNotInRuleSet() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+:Test002", "/warnaserror-:Test002", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Default); Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Warn); Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test002"], expected: ReportDiagnostic.Default); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void NoWarn_SpecificNoWarnOverridesRuleSet() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/nowarn:Test001", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(expected: ReportDiagnostic.Default, actual: arguments.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(expected: 1, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"]); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void NoWarn_SpecificNoWarnOverridesGeneralWarnAsError() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+", "/nowarn:Test001", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(expected: ReportDiagnostic.Error, actual: arguments.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(expected: 1, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"]); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void NoWarn_SpecificNoWarnOverridesSpecificWarnAsError() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/nowarn:Test001", "/warnaserror+:Test001", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(expected: ReportDiagnostic.Default, actual: arguments.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(expected: 1, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"]); } [Fact] [WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void NoWarn_Nullable() { var dir = Temp.CreateDirectory(); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/nowarn:nullable", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(expected: ReportDiagnostic.Default, actual: arguments.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(expected: ErrorFacts.NullableWarnings.Count + 2, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count); foreach (string warning in ErrorFacts.NullableWarnings) { Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[warning]); } Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation)]); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotationInGeneratedCode)]); } [Fact] [WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void NoWarn_Nullable_Capitalization() { var dir = Temp.CreateDirectory(); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/nowarn:NullABLE", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(expected: ReportDiagnostic.Default, actual: arguments.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(expected: ErrorFacts.NullableWarnings.Count + 2, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count); foreach (string warning in ErrorFacts.NullableWarnings) { Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[warning]); } Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation)]); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotationInGeneratedCode)]); } [Fact] [WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void NoWarn_Nullable_MultipleArguments() { var dir = Temp.CreateDirectory(); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/nowarn:nullable,Test001", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(expected: ReportDiagnostic.Default, actual: arguments.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(expected: ErrorFacts.NullableWarnings.Count + 3, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count); foreach (string warning in ErrorFacts.NullableWarnings) { Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[warning]); } Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"]); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation)]); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotationInGeneratedCode)]); } [Fact] [WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void WarnAsError_Nullable() { var dir = Temp.CreateDirectory(); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/warnaserror:nullable", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(expected: ReportDiagnostic.Default, actual: arguments.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(expected: ErrorFacts.NullableWarnings.Count + 2, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count); foreach (string warning in ErrorFacts.NullableWarnings) { Assert.Equal(expected: ReportDiagnostic.Error, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[warning]); } Assert.Equal(expected: ReportDiagnostic.Error, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation)]); Assert.Equal(expected: ReportDiagnostic.Error, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotationInGeneratedCode)]); } [WorkItem(912906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/912906")] [Fact] public void Analyzers_CommandLineOverridesRuleset2() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); string rulesetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Warning01"" Action=""Error"" /> </Rules> </RuleSet> "; var ruleSetFile = CreateRuleSetFile(rulesetSource); var outWriter = new StringWriter(CultureInfo.InvariantCulture); // This assembly has a MockAbstractDiagnosticAnalyzer type which should get run by this compilation. var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.cs", "/ruleset:" + ruleSetFile.Path, "/warn:0" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); // Diagnostic suppressed: commandline always overrides ruleset. Assert.DoesNotContain("Warning01", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.cs", "/warn:0", "/ruleset:" + ruleSetFile.Path }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); // Diagnostic suppressed: commandline always overrides ruleset. Assert.DoesNotContain("Warning01", outWriter.ToString(), StringComparison.Ordinal); // Clean up temp files CleanupAllGeneratedFiles(file.Path); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void DiagnosticFormatting() { string source = @" using System; class C { public static void Main() { Goo(0); #line 10 ""c:\temp\a\1.cs"" Goo(1); #line 20 ""C:\a\..\b.cs"" Goo(2); #line 30 ""C:\a\../B.cs"" Goo(3); #line 40 ""../b.cs"" Goo(4); #line 50 ""..\b.cs"" Goo(5); #line 60 ""C:\X.cs"" Goo(6); #line 70 ""C:\x.cs"" Goo(7); #line 90 "" "" Goo(9); #line 100 ""C:\*.cs"" Goo(10); #line 110 """" Goo(11); #line hidden Goo(12); #line default Goo(13); #line 140 ""***"" Goo(14); } } "; var dir = Temp.CreateDirectory(); dir.CreateFile("a.cs").WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); // with /fullpaths off string expected = @" a.cs(8,13): error CS0103: The name 'Goo' does not exist in the current context c:\temp\a\1.cs(10,13): error CS0103: The name 'Goo' does not exist in the current context C:\b.cs(20,13): error CS0103: The name 'Goo' does not exist in the current context C:\B.cs(30,13): error CS0103: The name 'Goo' does not exist in the current context " + Path.GetFullPath(Path.Combine(dir.Path, @"..\b.cs")) + @"(40,13): error CS0103: The name 'Goo' does not exist in the current context " + Path.GetFullPath(Path.Combine(dir.Path, @"..\b.cs")) + @"(50,13): error CS0103: The name 'Goo' does not exist in the current context C:\X.cs(60,13): error CS0103: The name 'Goo' does not exist in the current context C:\x.cs(70,13): error CS0103: The name 'Goo' does not exist in the current context (90,7): error CS0103: The name 'Goo' does not exist in the current context C:\*.cs(100,7): error CS0103: The name 'Goo' does not exist in the current context (110,7): error CS0103: The name 'Goo' does not exist in the current context (112,13): error CS0103: The name 'Goo' does not exist in the current context a.cs(32,13): error CS0103: The name 'Goo' does not exist in the current context ***(140,13): error CS0103: The name 'Goo' does not exist in the current context"; AssertEx.Equal( expected.Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries), outWriter.ToString().Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries), itemSeparator: "\r\n"); // with /fullpaths on outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/fullpaths", "a.cs" }); exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); expected = @" " + Path.Combine(dir.Path, @"a.cs") + @"(8,13): error CS0103: The name 'Goo' does not exist in the current context c:\temp\a\1.cs(10,13): error CS0103: The name 'Goo' does not exist in the current context C:\b.cs(20,13): error CS0103: The name 'Goo' does not exist in the current context C:\B.cs(30,13): error CS0103: The name 'Goo' does not exist in the current context " + Path.GetFullPath(Path.Combine(dir.Path, @"..\b.cs")) + @"(40,13): error CS0103: The name 'Goo' does not exist in the current context " + Path.GetFullPath(Path.Combine(dir.Path, @"..\b.cs")) + @"(50,13): error CS0103: The name 'Goo' does not exist in the current context C:\X.cs(60,13): error CS0103: The name 'Goo' does not exist in the current context C:\x.cs(70,13): error CS0103: The name 'Goo' does not exist in the current context (90,7): error CS0103: The name 'Goo' does not exist in the current context C:\*.cs(100,7): error CS0103: The name 'Goo' does not exist in the current context (110,7): error CS0103: The name 'Goo' does not exist in the current context (112,13): error CS0103: The name 'Goo' does not exist in the current context " + Path.Combine(dir.Path, @"a.cs") + @"(32,13): error CS0103: The name 'Goo' does not exist in the current context ***(140,13): error CS0103: The name 'Goo' does not exist in the current context"; AssertEx.Equal( expected.Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries), outWriter.ToString().Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries), itemSeparator: "\r\n"); } [WorkItem(540891, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540891")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void ParseOut() { const string baseDirectory = @"C:\abc\def\baz"; var parsedArgs = DefaultParse(new[] { @"/out:""""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '' contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("")); parsedArgs = DefaultParse(new[] { @"/out:", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2005: Missing file specification for '/out:' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/out:")); parsedArgs = DefaultParse(new[] { @"/refout:", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2005: Missing file specification for '/refout:' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/refout:")); parsedArgs = DefaultParse(new[] { @"/refout:ref.dll", "/refonly", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS8301: Do not use refout when using refonly. Diagnostic(ErrorCode.ERR_NoRefOutWhenRefOnly).WithLocation(1, 1)); parsedArgs = DefaultParse(new[] { @"/refout:ref.dll", "/link:b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/refonly", "/link:b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/refonly:incorrect", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/refonly:incorrect' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/refonly:incorrect").WithLocation(1, 1) ); parsedArgs = DefaultParse(new[] { @"/refout:ref.dll", "/target:module", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS8302: Cannot compile net modules when using /refout or /refonly. Diagnostic(ErrorCode.ERR_NoNetModuleOutputWhenRefOutOrRefOnly).WithLocation(1, 1) ); parsedArgs = DefaultParse(new[] { @"/refonly", "/target:module", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS8302: Cannot compile net modules when using /refout or /refonly. Diagnostic(ErrorCode.ERR_NoNetModuleOutputWhenRefOutOrRefOnly).WithLocation(1, 1) ); // Dev11 reports CS2007: Unrecognized option: '/out' parsedArgs = DefaultParse(new[] { @"/out", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2005: Missing file specification for '/out' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/out")); parsedArgs = DefaultParse(new[] { @"/out+", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/out+")); // Should preserve fully qualified paths parsedArgs = DefaultParse(new[] { @"/out:C:\MyFolder\MyBinary.dll", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal("MyBinary", parsedArgs.CompilationName); Assert.Equal("MyBinary.dll", parsedArgs.OutputFileName); Assert.Equal("MyBinary.dll", parsedArgs.CompilationOptions.ModuleName); Assert.Equal(@"C:\MyFolder", parsedArgs.OutputDirectory); Assert.Equal(@"C:\MyFolder\MyBinary.dll", parsedArgs.GetOutputFilePath(parsedArgs.OutputFileName)); // Should handle quotes parsedArgs = DefaultParse(new[] { @"/out:""C:\My Folder\MyBinary.dll""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"MyBinary", parsedArgs.CompilationName); Assert.Equal("MyBinary.dll", parsedArgs.OutputFileName); Assert.Equal("MyBinary.dll", parsedArgs.CompilationOptions.ModuleName); Assert.Equal(@"C:\My Folder", parsedArgs.OutputDirectory); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/out:MyBinary.dll", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal("MyBinary", parsedArgs.CompilationName); Assert.Equal("MyBinary.dll", parsedArgs.OutputFileName); Assert.Equal("MyBinary.dll", parsedArgs.CompilationOptions.ModuleName); Assert.Equal(baseDirectory, parsedArgs.OutputDirectory); Assert.Equal(Path.Combine(baseDirectory, "MyBinary.dll"), parsedArgs.GetOutputFilePath(parsedArgs.OutputFileName)); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/out:..\MyBinary.dll", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal("MyBinary", parsedArgs.CompilationName); Assert.Equal("MyBinary.dll", parsedArgs.OutputFileName); Assert.Equal("MyBinary.dll", parsedArgs.CompilationOptions.ModuleName); Assert.Equal(@"C:\abc\def", parsedArgs.OutputDirectory); // not specified: exe parsedArgs = DefaultParse(new[] { @"a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); Assert.Equal(baseDirectory, parsedArgs.OutputDirectory); // not specified: dll parsedArgs = DefaultParse(new[] { @"/target:library", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal("a", parsedArgs.CompilationName); Assert.Equal("a.dll", parsedArgs.OutputFileName); Assert.Equal("a.dll", parsedArgs.CompilationOptions.ModuleName); Assert.Equal(baseDirectory, parsedArgs.OutputDirectory); // not specified: module parsedArgs = DefaultParse(new[] { @"/target:module", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Null(parsedArgs.CompilationName); Assert.Equal("a.netmodule", parsedArgs.CompilationOptions.ModuleName); Assert.Equal(baseDirectory, parsedArgs.OutputDirectory); // not specified: appcontainerexe parsedArgs = DefaultParse(new[] { @"/target:appcontainerexe", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); Assert.Equal(baseDirectory, parsedArgs.OutputDirectory); // not specified: winmdobj parsedArgs = DefaultParse(new[] { @"/target:winmdobj", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal("a", parsedArgs.CompilationName); Assert.Equal("a.winmdobj", parsedArgs.OutputFileName); Assert.Equal("a.winmdobj", parsedArgs.CompilationOptions.ModuleName); Assert.Equal(baseDirectory, parsedArgs.OutputDirectory); // drive-relative path: char currentDrive = Directory.GetCurrentDirectory()[0]; parsedArgs = DefaultParse(new[] { currentDrive + @":a.cs", "b.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name 'D:a.cs' is contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(currentDrive + ":a.cs")); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); Assert.Equal(baseDirectory, parsedArgs.OutputDirectory); // UNC parsedArgs = DefaultParse(new[] { @"/out:\\b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"\\b")); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/out:\\server\share\file.exe", "a.vb" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"\\server\share", parsedArgs.OutputDirectory); Assert.Equal("file.exe", parsedArgs.OutputFileName); Assert.Equal("file", parsedArgs.CompilationName); Assert.Equal("file.exe", parsedArgs.CompilationOptions.ModuleName); // invalid name: parsedArgs = DefaultParse(new[] { "/out:a.b\0b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a.b\0b")); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); // Temporary skip following scenarios because of the error message changed (path) //parsedArgs = DefaultParse(new[] { "/out:a\uD800b.dll", "a.cs" }, baseDirectory); //parsedArgs.Errors.Verify( // // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long // Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a\uD800b.dll")); // Dev11 reports CS0016: Could not write to output file 'd:\Temp\q\a<>.z' parsedArgs = DefaultParse(new[] { @"/out:""a<>.dll""", "a.vb" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name 'a<>.dll' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a<>.dll")); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/out:.exe", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.exe' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".exe") ); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/t:exe", @"/out:.exe", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.exe' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".exe") ); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/t:library", @"/out:.dll", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.dll' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".dll") ); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/t:module", @"/out:.netmodule", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.netmodule' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".netmodule") ); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { ".cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/t:exe", ".cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/t:library", ".cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.dll' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".dll") ); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/t:module", ".cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(".netmodule", parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Equal(".netmodule", parsedArgs.CompilationOptions.ModuleName); } [WorkItem(546012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546012")] [WorkItem(546007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546007")] [Fact] public void ParseOut2() { var parsedArgs = DefaultParse(new[] { "/out:.x", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".x")); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { "/out:.x", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".x")); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); } [Fact] public void ParseInstrumentTestNames() { var parsedArgs = DefaultParse(SpecializedCollections.EmptyEnumerable<string>(), WorkingDirectory); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty)); parsedArgs = DefaultParse(new[] { @"/instrument", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'instrument' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "instrument")); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty)); parsedArgs = DefaultParse(new[] { @"/instrument:""""", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'instrument' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "instrument")); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty)); parsedArgs = DefaultParse(new[] { @"/instrument:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'instrument' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "instrument")); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty)); parsedArgs = DefaultParse(new[] { "/instrument:", "Test.Flag.Name", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'instrument' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "instrument")); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty)); parsedArgs = DefaultParse(new[] { "/instrument:InvalidOption", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_InvalidInstrumentationKind).WithArguments("InvalidOption")); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty)); parsedArgs = DefaultParse(new[] { "/instrument:None", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_InvalidInstrumentationKind).WithArguments("None")); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty)); parsedArgs = DefaultParse(new[] { "/instrument:TestCoverage,InvalidOption", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_InvalidInstrumentationKind).WithArguments("InvalidOption")); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage))); parsedArgs = DefaultParse(new[] { "/instrument:TestCoverage", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage))); parsedArgs = DefaultParse(new[] { @"/instrument:""TestCoverage""", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage))); parsedArgs = DefaultParse(new[] { @"/instrument:""TESTCOVERAGE""", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage))); parsedArgs = DefaultParse(new[] { "/instrument:TestCoverage,TestCoverage", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage))); parsedArgs = DefaultParse(new[] { "/instrument:TestCoverage", "/instrument:TestCoverage", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage))); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void ParseDoc() { const string baseDirectory = @"C:\abc\def\baz"; var parsedArgs = DefaultParse(new[] { @"/doc:""""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for '/doc:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/doc:")); Assert.Null(parsedArgs.DocumentationPath); parsedArgs = DefaultParse(new[] { @"/doc:", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for '/doc:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/doc:")); Assert.Null(parsedArgs.DocumentationPath); // NOTE: no colon in error message '/doc' parsedArgs = DefaultParse(new[] { @"/doc", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for '/doc' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/doc")); Assert.Null(parsedArgs.DocumentationPath); parsedArgs = DefaultParse(new[] { @"/doc+", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/doc+")); Assert.Null(parsedArgs.DocumentationPath); // Should preserve fully qualified paths parsedArgs = DefaultParse(new[] { @"/doc:C:\MyFolder\MyBinary.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\MyFolder\MyBinary.xml", parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); // Should handle quotes parsedArgs = DefaultParse(new[] { @"/doc:""C:\My Folder\MyBinary.xml""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\My Folder\MyBinary.xml", parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/doc:MyBinary.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(baseDirectory, "MyBinary.xml"), parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/doc:..\MyBinary.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\abc\def\MyBinary.xml", parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); // drive-relative path: char currentDrive = Directory.GetCurrentDirectory()[0]; parsedArgs = DefaultParse(new[] { "/doc:" + currentDrive + @":a.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name 'D:a.xml' is contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(currentDrive + ":a.xml")); Assert.Null(parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); //Even though the format was incorrect // UNC parsedArgs = DefaultParse(new[] { @"/doc:\\b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"\\b")); Assert.Null(parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); //Even though the format was incorrect parsedArgs = DefaultParse(new[] { @"/doc:\\server\share\file.xml", "a.vb" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"\\server\share\file.xml", parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); // invalid name: parsedArgs = DefaultParse(new[] { "/doc:a.b\0b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a.b\0b")); Assert.Null(parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); //Even though the format was incorrect // Temp // parsedArgs = DefaultParse(new[] { "/doc:a\uD800b.xml", "a.cs" }, baseDirectory); // parsedArgs.Errors.Verify( // Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a\uD800b.xml")); // Assert.Null(parsedArgs.DocumentationPath); // Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); //Even though the format was incorrect parsedArgs = DefaultParse(new[] { @"/doc:""a<>.xml""", "a.vb" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name 'a<>.xml' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a<>.xml")); Assert.Null(parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); //Even though the format was incorrect } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void ParseErrorLog() { const string baseDirectory = @"C:\abc\def\baz"; var parsedArgs = DefaultParse(new[] { @"/errorlog:""""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<(error log option format>' for '/errorlog:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(CSharpCommandLineParser.ErrorLogOptionFormat, "/errorlog:")); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); parsedArgs = DefaultParse(new[] { @"/errorlog:", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<(error log option format>' for '/errorlog:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(CSharpCommandLineParser.ErrorLogOptionFormat, "/errorlog:")); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); parsedArgs = DefaultParse(new[] { @"/errorlog", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<(error log option format>' for '/errorlog' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(CSharpCommandLineParser.ErrorLogOptionFormat, "/errorlog")); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // Should preserve fully qualified paths parsedArgs = DefaultParse(new[] { @"/errorlog:C:\MyFolder\MyBinary.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\MyFolder\MyBinary.xml", parsedArgs.ErrorLogOptions.Path); Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // Escaped quote in the middle is an error parsedArgs = DefaultParse(new[] { @"/errorlog:C:\""My Folder""\MyBinary.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"C:""My Folder\MyBinary.xml").WithLocation(1, 1)); // Should handle quotes parsedArgs = DefaultParse(new[] { @"/errorlog:""C:\My Folder\MyBinary.xml""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\My Folder\MyBinary.xml", parsedArgs.ErrorLogOptions.Path); Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/errorlog:MyBinary.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(baseDirectory, "MyBinary.xml"), parsedArgs.ErrorLogOptions.Path); Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/errorlog:..\MyBinary.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\abc\def\MyBinary.xml", parsedArgs.ErrorLogOptions.Path); Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // drive-relative path: char currentDrive = Directory.GetCurrentDirectory()[0]; parsedArgs = DefaultParse(new[] { "/errorlog:" + currentDrive + @":a.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name 'D:a.xml' is contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(currentDrive + ":a.xml")); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // UNC parsedArgs = DefaultParse(new[] { @"/errorlog:\\b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"\\b")); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); parsedArgs = DefaultParse(new[] { @"/errorlog:\\server\share\file.xml", "a.vb" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"\\server\share\file.xml", parsedArgs.ErrorLogOptions.Path); // invalid name: parsedArgs = DefaultParse(new[] { "/errorlog:a.b\0b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a.b\0b")); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); parsedArgs = DefaultParse(new[] { @"/errorlog:""a<>.xml""", "a.vb" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name 'a<>.xml' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a<>.xml")); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // Parses SARIF version. parsedArgs = DefaultParse(new[] { @"/errorlog:C:\MyFolder\MyBinary.xml,version=2", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\MyFolder\MyBinary.xml", parsedArgs.ErrorLogOptions.Path); Assert.Equal(SarifVersion.Sarif2, parsedArgs.ErrorLogOptions.SarifVersion); Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // Invalid SARIF version. string[] invalidSarifVersions = new string[] { @"C:\MyFolder\MyBinary.xml,version=1.0.0", @"C:\MyFolder\MyBinary.xml,version=2.1.0", @"C:\MyFolder\MyBinary.xml,version=42" }; foreach (string invalidSarifVersion in invalidSarifVersions) { parsedArgs = DefaultParse(new[] { $"/errorlog:{invalidSarifVersion}", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2046: Command-line syntax error: 'C:\MyFolder\MyBinary.xml,version=42' is not a valid value for the '/errorlog:' option. The value must be of the form '<file>[,version={1|1.0|2|2.1}]'. Diagnostic(ErrorCode.ERR_BadSwitchValue).WithArguments(invalidSarifVersion, "/errorlog:", CSharpCommandLineParser.ErrorLogOptionFormat)); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); } // Invalid errorlog qualifier. const string InvalidErrorLogQualifier = @"C:\MyFolder\MyBinary.xml,invalid=42"; parsedArgs = DefaultParse(new[] { $"/errorlog:{InvalidErrorLogQualifier}", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2046: Command-line syntax error: 'C:\MyFolder\MyBinary.xml,invalid=42' is not a valid value for the '/errorlog:' option. The value must be of the form '<file>[,version={1|1.0|2|2.1}]'. Diagnostic(ErrorCode.ERR_BadSwitchValue).WithArguments(InvalidErrorLogQualifier, "/errorlog:", CSharpCommandLineParser.ErrorLogOptionFormat)); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // Too many errorlog qualifiers. const string TooManyErrorLogQualifiers = @"C:\MyFolder\MyBinary.xml,version=2,version=2"; parsedArgs = DefaultParse(new[] { $"/errorlog:{TooManyErrorLogQualifiers}", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2046: Command-line syntax error: 'C:\MyFolder\MyBinary.xml,version=2,version=2' is not a valid value for the '/errorlog:' option. The value must be of the form '<file>[,version={1|1.0|2|2.1}]'. Diagnostic(ErrorCode.ERR_BadSwitchValue).WithArguments(TooManyErrorLogQualifiers, "/errorlog:", CSharpCommandLineParser.ErrorLogOptionFormat)); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); } [ConditionalFact(typeof(WindowsOnly))] public void AppConfigParse() { const string baseDirectory = @"C:\abc\def\baz"; var parsedArgs = DefaultParse(new[] { @"/appconfig:""""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing ':<text>' for '/appconfig:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(":<text>", "/appconfig:")); Assert.Null(parsedArgs.AppConfigPath); parsedArgs = DefaultParse(new[] { "/appconfig:", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing ':<text>' for '/appconfig:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(":<text>", "/appconfig:")); Assert.Null(parsedArgs.AppConfigPath); parsedArgs = DefaultParse(new[] { "/appconfig", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing ':<text>' for '/appconfig' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(":<text>", "/appconfig")); Assert.Null(parsedArgs.AppConfigPath); parsedArgs = DefaultParse(new[] { "/appconfig:a.exe.config", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\abc\def\baz\a.exe.config", parsedArgs.AppConfigPath); // If ParseDoc succeeds, all other possible AppConfig paths should succeed as well -- they both call ParseGenericFilePath } [Fact] public void AppConfigBasic() { var srcFile = Temp.CreateFile().WriteAllText(@"class A { static void Main(string[] args) { } }"); var srcDirectory = Path.GetDirectoryName(srcFile.Path); var appConfigFile = Temp.CreateFile().WriteAllText( @"<?xml version=""1.0"" encoding=""utf-8"" ?> <configuration> <runtime> <assemblyBinding xmlns=""urn:schemas-microsoft-com:asm.v1""> <supportPortability PKT=""7cec85d7bea7798e"" enable=""false""/> </assemblyBinding> </runtime> </configuration>"); var silverlight = Temp.CreateFile().WriteAllBytes(ProprietaryTestResources.silverlight_v5_0_5_0.System_v5_0_5_0_silverlight).Path; var net4_0dll = Temp.CreateFile().WriteAllBytes(ResourcesNet451.System).Path; // Test linking two appconfig dlls with simple src var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = CreateCSharpCompiler(null, srcDirectory, new[] { "/nologo", "/r:" + silverlight, "/r:" + net4_0dll, "/appconfig:" + appConfigFile.Path, srcFile.Path }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(srcFile.Path); CleanupAllGeneratedFiles(appConfigFile.Path); } [ConditionalFact(typeof(WindowsOnly))] public void AppConfigBasicFail() { var srcFile = Temp.CreateFile().WriteAllText(@"class A { static void Main(string[] args) { } }"); var srcDirectory = Path.GetDirectoryName(srcFile.Path); string root = Path.GetPathRoot(srcDirectory); // Make sure we pick a drive that exists and is plugged in to avoid 'Drive not ready' var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = CreateCSharpCompiler(null, srcDirectory, new[] { "/nologo", "/preferreduilang:en", $@"/appconfig:{root}DoesNotExist\NOwhere\bonobo.exe.config" , srcFile.Path }).Run(outWriter); Assert.NotEqual(0, exitCode); Assert.Equal($@"error CS7093: Cannot read config file '{root}DoesNotExist\NOwhere\bonobo.exe.config' -- 'Could not find a part of the path '{root}DoesNotExist\NOwhere\bonobo.exe.config'.'", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(srcFile.Path); } [ConditionalFact(typeof(WindowsOnly))] public void ParseDocAndOut() { const string baseDirectory = @"C:\abc\def\baz"; // Can specify separate directories for binary and XML output. var parsedArgs = DefaultParse(new[] { @"/doc:a\b.xml", @"/out:c\d.exe", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\abc\def\baz\a\b.xml", parsedArgs.DocumentationPath); Assert.Equal(@"C:\abc\def\baz\c", parsedArgs.OutputDirectory); Assert.Equal("d.exe", parsedArgs.OutputFileName); // XML does not fall back on output directory. parsedArgs = DefaultParse(new[] { @"/doc:b.xml", @"/out:c\d.exe", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\abc\def\baz\b.xml", parsedArgs.DocumentationPath); Assert.Equal(@"C:\abc\def\baz\c", parsedArgs.OutputDirectory); Assert.Equal("d.exe", parsedArgs.OutputFileName); } [ConditionalFact(typeof(WindowsOnly))] public void ParseErrorLogAndOut() { const string baseDirectory = @"C:\abc\def\baz"; // Can specify separate directories for binary and error log output. var parsedArgs = DefaultParse(new[] { @"/errorlog:a\b.xml", @"/out:c\d.exe", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\abc\def\baz\a\b.xml", parsedArgs.ErrorLogOptions.Path); Assert.Equal(@"C:\abc\def\baz\c", parsedArgs.OutputDirectory); Assert.Equal("d.exe", parsedArgs.OutputFileName); // XML does not fall back on output directory. parsedArgs = DefaultParse(new[] { @"/errorlog:b.xml", @"/out:c\d.exe", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\abc\def\baz\b.xml", parsedArgs.ErrorLogOptions.Path); Assert.Equal(@"C:\abc\def\baz\c", parsedArgs.OutputDirectory); Assert.Equal("d.exe", parsedArgs.OutputFileName); } [Fact] public void ModuleAssemblyName() { var parsedArgs = DefaultParse(new[] { @"/target:module", "/moduleassemblyname:goo", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("goo", parsedArgs.CompilationName); Assert.Equal("a.netmodule", parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/target:library", "/moduleassemblyname:goo", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS0734: The /moduleassemblyname option may only be specified when building a target type of 'module' Diagnostic(ErrorCode.ERR_AssemblyNameOnNonModule)); parsedArgs = DefaultParse(new[] { @"/target:exe", "/moduleassemblyname:goo", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS0734: The /moduleassemblyname option may only be specified when building a target type of 'module' Diagnostic(ErrorCode.ERR_AssemblyNameOnNonModule)); parsedArgs = DefaultParse(new[] { @"/target:winexe", "/moduleassemblyname:goo", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS0734: The /moduleassemblyname option may only be specified when building a target type of 'module' Diagnostic(ErrorCode.ERR_AssemblyNameOnNonModule)); } [Fact] public void ModuleName() { var parsedArgs = DefaultParse(new[] { @"/target:module", "/modulename:goo", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("goo", parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/target:library", "/modulename:bar", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("bar", parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/target:exe", "/modulename:CommonLanguageRuntimeLibrary", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("CommonLanguageRuntimeLibrary", parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/target:winexe", "/modulename:goo", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("goo", parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/target:exe", "/modulename:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'modulename' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "modulename").WithLocation(1, 1) ); } [Fact] public void ModuleName001() { var dir = Temp.CreateDirectory(); var file1 = dir.CreateFile("a.cs"); file1.WriteAllText(@" class c1 { public static void Main(){} } "); var exeName = "aa.exe"; var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/modulename:hocusPocus ", "/out:" + exeName + " ", file1.Path }); int exitCode = csc.Run(outWriter); if (exitCode != 0) { Console.WriteLine(outWriter.ToString()); Assert.Equal(0, exitCode); } Assert.Equal(1, Directory.EnumerateFiles(dir.Path, exeName).Count()); using (var metadata = ModuleMetadata.CreateFromImage(File.ReadAllBytes(Path.Combine(dir.Path, "aa.exe")))) { var peReader = metadata.Module.GetMetadataReader(); Assert.True(peReader.IsAssembly); Assert.Equal("aa", peReader.GetString(peReader.GetAssemblyDefinition().Name)); Assert.Equal("hocusPocus", peReader.GetString(peReader.GetModuleDefinition().Name)); } if (System.IO.File.Exists(exeName)) { System.IO.File.Delete(exeName); } CleanupAllGeneratedFiles(file1.Path); } [Fact] public void ParsePlatform() { var parsedArgs = DefaultParse(new[] { @"/platform:x64", "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.Errors.Any()); Assert.Equal(Platform.X64, parsedArgs.CompilationOptions.Platform); parsedArgs = DefaultParse(new[] { @"/platform:X86", "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.Errors.Any()); Assert.Equal(Platform.X86, parsedArgs.CompilationOptions.Platform); parsedArgs = DefaultParse(new[] { @"/platform:itanum", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadPlatformType, parsedArgs.Errors.First().Code); Assert.Equal(Platform.AnyCpu, parsedArgs.CompilationOptions.Platform); parsedArgs = DefaultParse(new[] { "/platform:itanium", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Platform.Itanium, parsedArgs.CompilationOptions.Platform); parsedArgs = DefaultParse(new[] { "/platform:anycpu", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Platform.AnyCpu, parsedArgs.CompilationOptions.Platform); parsedArgs = DefaultParse(new[] { "/platform:anycpu32bitpreferred", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Platform.AnyCpu32BitPreferred, parsedArgs.CompilationOptions.Platform); parsedArgs = DefaultParse(new[] { "/platform:arm", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Platform.Arm, parsedArgs.CompilationOptions.Platform); parsedArgs = DefaultParse(new[] { "/platform", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<string>' for 'platform' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<string>", "/platform")); Assert.Equal(Platform.AnyCpu, parsedArgs.CompilationOptions.Platform); //anycpu is default parsedArgs = DefaultParse(new[] { "/platform:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<string>' for 'platform' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<string>", "/platform:")); Assert.Equal(Platform.AnyCpu, parsedArgs.CompilationOptions.Platform); //anycpu is default } [WorkItem(546016, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546016")] [WorkItem(545997, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545997")] [WorkItem(546019, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546019")] [WorkItem(546029, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546029")] [Fact] public void ParseBaseAddress() { var parsedArgs = DefaultParse(new[] { @"/baseaddress:x64", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadBaseNumber, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { @"/platform:x64", @"/baseaddress:0x8000000000011111", "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.Errors.Any()); Assert.Equal(0x8000000000011111ul, parsedArgs.EmitOptions.BaseAddress); parsedArgs = DefaultParse(new[] { @"/platform:x86", @"/baseaddress:0x8000000000011111", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadBaseNumber, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { @"/baseaddress:", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_SwitchNeedsNumber, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { @"/baseaddress:-23", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadBaseNumber, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { @"/platform:x64", @"/baseaddress:01777777777777777777777", "a.cs" }, WorkingDirectory); Assert.Equal(ulong.MaxValue, parsedArgs.EmitOptions.BaseAddress); parsedArgs = DefaultParse(new[] { @"/platform:x64", @"/baseaddress:0x0000000100000000", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { @"/platform:x64", @"/baseaddress:0xffff8000", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "test.cs", "/platform:x86", "/baseaddress:0xffffffff" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0xFFFFFFFF")); parsedArgs = DefaultParse(new[] { "test.cs", "/platform:x86", "/baseaddress:0xffff8000" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0xFFFF8000")); parsedArgs = DefaultParse(new[] { "test.cs", "/baseaddress:0xffff8000" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0xFFFF8000")); parsedArgs = DefaultParse(new[] { "C:\\test.cs", "/platform:x86", "/baseaddress:0xffff7fff" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "C:\\test.cs", "/platform:x64", "/baseaddress:0xffff8000" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "C:\\test.cs", "/platform:x64", "/baseaddress:0x100000000" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "test.cs", "/baseaddress:0xFFFF0000FFFF0000" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0xFFFF0000FFFF0000")); parsedArgs = DefaultParse(new[] { "C:\\test.cs", "/platform:x64", "/baseaddress:0x10000000000000000" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0x10000000000000000")); parsedArgs = DefaultParse(new[] { "C:\\test.cs", "/baseaddress:0xFFFF0000FFFF0000" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0xFFFF0000FFFF0000")); } [Fact] public void ParseFileAlignment() { var parsedArgs = DefaultParse(new[] { @"/filealign:x64", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2024: Invalid file section alignment number 'x64' Diagnostic(ErrorCode.ERR_InvalidFileAlignment).WithArguments("x64")); parsedArgs = DefaultParse(new[] { @"/filealign:0x200", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(0x200, parsedArgs.EmitOptions.FileAlignment); parsedArgs = DefaultParse(new[] { @"/filealign:512", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(512, parsedArgs.EmitOptions.FileAlignment); parsedArgs = DefaultParse(new[] { @"/filealign:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for 'filealign' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("filealign")); parsedArgs = DefaultParse(new[] { @"/filealign:-23", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2024: Invalid file section alignment number '-23' Diagnostic(ErrorCode.ERR_InvalidFileAlignment).WithArguments("-23")); parsedArgs = DefaultParse(new[] { @"/filealign:020000", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(8192, parsedArgs.EmitOptions.FileAlignment); parsedArgs = DefaultParse(new[] { @"/filealign:0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2024: Invalid file section alignment number '0' Diagnostic(ErrorCode.ERR_InvalidFileAlignment).WithArguments("0")); parsedArgs = DefaultParse(new[] { @"/filealign:123", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2024: Invalid file section alignment number '123' Diagnostic(ErrorCode.ERR_InvalidFileAlignment).WithArguments("123")); } [ConditionalFact(typeof(WindowsOnly))] public void SdkPathAndLibEnvVariable() { var dir = Temp.CreateDirectory(); var lib1 = dir.CreateDirectory("lib1"); var lib2 = dir.CreateDirectory("lib2"); var lib3 = dir.CreateDirectory("lib3"); var sdkDirectory = SdkDirectory; var parsedArgs = DefaultParse(new[] { @"/lib:lib1", @"/libpath:lib2", @"/libpaths:lib3", "a.cs" }, dir.Path, sdkDirectory: sdkDirectory); AssertEx.Equal(new[] { sdkDirectory, lib1.Path, lib2.Path, lib3.Path }, parsedArgs.ReferencePaths); } [ConditionalFact(typeof(WindowsOnly))] public void SdkPathAndLibEnvVariable_Errors() { var parsedArgs = DefaultParse(new[] { @"/lib:c:lib2", @"/lib:o:\sdk1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS1668: Invalid search path 'c:lib2' specified in '/LIB option' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"c:lib2", "/LIB option", "path is too long or invalid"), // warning CS1668: Invalid search path 'o:\sdk1' specified in '/LIB option' -- 'directory does not exist' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"o:\sdk1", "/LIB option", "directory does not exist")); parsedArgs = DefaultParse(new[] { @"/lib:c:\Windows,o:\Windows;e:;", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS1668: Invalid search path 'o:\Windows' specified in '/LIB option' -- 'directory does not exist' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"o:\Windows", "/LIB option", "directory does not exist"), // warning CS1668: Invalid search path 'e:' specified in '/LIB option' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"e:", "/LIB option", "path is too long or invalid")); parsedArgs = DefaultParse(new[] { @"/lib:c:\Windows,.\Windows;e;", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS1668: Invalid search path '.\Windows' specified in '/LIB option' -- 'directory does not exist' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@".\Windows", "/LIB option", "directory does not exist"), // warning CS1668: Invalid search path 'e' specified in '/LIB option' -- 'directory does not exist' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"e", "/LIB option", "directory does not exist")); parsedArgs = DefaultParse(new[] { @"/lib:c:\Windows,o:\Windows;e:; ; ; ; ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS1668: Invalid search path 'o:\Windows' specified in '/LIB option' -- 'directory does not exist' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"o:\Windows", "/LIB option", "directory does not exist"), // warning CS1668: Invalid search path 'e:' specified in '/LIB option' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments("e:", "/LIB option", "path is too long or invalid"), // warning CS1668: Invalid search path ' ' specified in '/LIB option' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(" ", "/LIB option", "path is too long or invalid"), // warning CS1668: Invalid search path ' ' specified in '/LIB option' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(" ", "/LIB option", "path is too long or invalid"), // warning CS1668: Invalid search path ' ' specified in '/LIB option' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(" ", "/LIB option", "path is too long or invalid")); parsedArgs = DefaultParse(new[] { @"/lib", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<path list>", "lib")); parsedArgs = DefaultParse(new[] { @"/lib:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<path list>", "lib")); parsedArgs = DefaultParse(new[] { @"/lib+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/lib+")); parsedArgs = DefaultParse(new[] { @"/lib: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<path list>", "lib")); } [Fact, WorkItem(546005, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546005")] public void SdkPathAndLibEnvVariable_Relative_csc() { var tempFolder = Temp.CreateDirectory(); var baseDirectory = tempFolder.ToString(); var subFolder = tempFolder.CreateDirectory("temp"); var subDirectory = subFolder.ToString(); var src = Temp.CreateFile("a.cs"); src.WriteAllText("public class C{}"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, subDirectory, new[] { "/nologo", "/t:library", "/out:abc.xyz", src.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, baseDirectory, new[] { "/nologo", "/lib:temp", "/r:abc.xyz", "/t:library", src.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(src.Path); } [Fact] public void UnableWriteOutput() { var tempFolder = Temp.CreateDirectory(); var baseDirectory = tempFolder.ToString(); var subFolder = tempFolder.CreateDirectory("temp"); var src = Temp.CreateFile("a.cs"); src.WriteAllText("public class C{}"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/out:" + subFolder.ToString(), src.ToString() }).Run(outWriter); Assert.Equal(1, exitCode); Assert.True(outWriter.ToString().Trim().StartsWith("error CS2012: Cannot open '" + subFolder.ToString() + "' for writing -- '", StringComparison.Ordinal)); // Cannot create a file when that file already exists. CleanupAllGeneratedFiles(src.Path); } [Fact] public void ParseHighEntropyVA() { var parsedArgs = DefaultParse(new[] { @"/highentropyva", "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.Errors.Any()); Assert.True(parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace); parsedArgs = DefaultParse(new[] { @"/highentropyva+", "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.Errors.Any()); Assert.True(parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace); parsedArgs = DefaultParse(new[] { @"/highentropyva-", "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.Errors.Any()); Assert.False(parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace); parsedArgs = DefaultParse(new[] { @"/highentropyva:-", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal(EmitOptions.Default.HighEntropyVirtualAddressSpace, parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace); parsedArgs = DefaultParse(new[] { @"/highentropyva:", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal(EmitOptions.Default.HighEntropyVirtualAddressSpace, parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace); //last one wins parsedArgs = DefaultParse(new[] { @"/highenTROPyva+", @"/HIGHentropyva-", "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.Errors.Any()); Assert.False(parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace); } [Fact] public void Checked() { var parsedArgs = DefaultParse(new[] { @"/checked+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.CheckOverflow); parsedArgs = DefaultParse(new[] { @"/checked-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.CheckOverflow); parsedArgs = DefaultParse(new[] { @"/checked", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.CheckOverflow); parsedArgs = DefaultParse(new[] { @"/checked-", @"/checked", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.CheckOverflow); parsedArgs = DefaultParse(new[] { @"/checked:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/checked:")); } [Fact] public void Nullable() { var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Enabled' for C# 7.0. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Enable", "7.0", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:yes", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'yes' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("yes").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:enable", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Enable' for C# 7.0. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Enable", "7.0", "8.0").WithLocation(1, 1)); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:disable", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1)); parsedArgs = DefaultParse(new[] { @"/nullable+", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:yes", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'yes' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("yes").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:eNable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:disablE", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Safeonly", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'Safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("Safeonly").WithLocation(1, 1) ); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable-", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable+", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:YES", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'YES' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("YES").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:disable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:enable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:safeonly", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable-", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable+", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:YES", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'YES' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("YES").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:disable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:enable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:safeonly", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable-", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable+", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable:", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1), // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable:YES", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1), // error CS8636: Invalid option 'YES' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("YES").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable:disable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable:enable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable:safeonly", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1), // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:", "/langversion:7.3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:yeS", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'yeS' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("yeS").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", "/langversion:7.3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Enable' for C# 7.3. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Enable", "7.3", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable", "/langversion:7.3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Enabled' for C# 7.3. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Enable", "7.3", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:enable", "/langversion:7.3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Enabled' for C# 7.3. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Enable", "7.3", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:disable", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", "/langversion:7.3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { "a.cs", "/langversion:8" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { "a.cs", "/langversion:7.3" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:""safeonly""", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:\""enable\""", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option '"enable"' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("\"enable\"").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:\\disable\\", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option '\\disable\\' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("\\\\disable\\\\").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:\\""enable\\""", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option '\enable\' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("\\enable\\").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonlywarnings", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonlywarnings' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonlywarnings").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:SafeonlyWarnings", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'SafeonlyWarnings' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("SafeonlyWarnings").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:safeonlyWarnings", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonlyWarnings' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonlyWarnings").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:warnings", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Warnings' for C# 7.0. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Warnings", "7.0", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:Warnings", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:Warnings", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable-", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable+", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable:", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable:YES", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'YES' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("YES").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable:disable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable:enable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable:Warnings", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", "/langversion:7.3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Annotations' for C# 7.3. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Warnings", "7.3", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:annotations", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Annotations' for C# 7.0. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Annotations", "7.0", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:Annotations", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:Annotations", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable-", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable+", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable:", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable:YES", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'YES' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("YES").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable:disable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable:enable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable:Annotations", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", "/langversion:7.3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Annotations' for C# 7.3. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Annotations", "7.3", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); } [Fact] public void Usings() { CSharpCommandLineArguments parsedArgs; var sdkDirectory = SdkDirectory; parsedArgs = CSharpCommandLineParser.Script.Parse(new string[] { "/u:Goo.Bar" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { "Goo.Bar" }, parsedArgs.CompilationOptions.Usings.AsEnumerable()); parsedArgs = CSharpCommandLineParser.Script.Parse(new string[] { "/u:Goo.Bar;Baz", "/using:System.Core;System" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { "Goo.Bar", "Baz", "System.Core", "System" }, parsedArgs.CompilationOptions.Usings.AsEnumerable()); parsedArgs = CSharpCommandLineParser.Script.Parse(new string[] { "/u:Goo;;Bar" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { "Goo", "Bar" }, parsedArgs.CompilationOptions.Usings.AsEnumerable()); parsedArgs = CSharpCommandLineParser.Script.Parse(new string[] { "/u:" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<namespace>' for '/u:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<namespace>", "/u:")); } [Fact] public void WarningsErrors() { var parsedArgs = DefaultParse(new string[] { "/nowarn", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for 'nowarn' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("nowarn")); parsedArgs = DefaultParse(new string[] { "/nowarn:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for 'nowarn' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("nowarn")); // Previous versions of the compiler used to report a warning (CS1691) // whenever an unrecognized warning code was supplied via /nowarn or /warnaserror. // We no longer generate a warning in such cases. parsedArgs = DefaultParse(new string[] { "/nowarn:-1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/nowarn:abc", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/warnaserror:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for 'warnaserror' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("warnaserror")); parsedArgs = DefaultParse(new string[] { "/warnaserror:-1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/warnaserror:70000", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/warnaserror:abc", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/warnaserror+:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for '/warnaserror+:' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("warnaserror+")); parsedArgs = DefaultParse(new string[] { "/warnaserror-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for '/warnaserror-:' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("warnaserror-")); parsedArgs = DefaultParse(new string[] { "/w", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for '/w' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("w")); parsedArgs = DefaultParse(new string[] { "/w:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for '/w:' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("w")); parsedArgs = DefaultParse(new string[] { "/warn:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for '/warn:' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("warn")); parsedArgs = DefaultParse(new string[] { "/w:-1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS1900: Warning level must be zero or greater Diagnostic(ErrorCode.ERR_BadWarningLevel).WithArguments("w")); parsedArgs = DefaultParse(new string[] { "/w:5", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/warn:-1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS1900: Warning level must be zero or greater Diagnostic(ErrorCode.ERR_BadWarningLevel).WithArguments("warn")); parsedArgs = DefaultParse(new string[] { "/warn:5", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); // Previous versions of the compiler used to report a warning (CS1691) // whenever an unrecognized warning code was supplied via /nowarn or /warnaserror. // We no longer generate a warning in such cases. parsedArgs = DefaultParse(new string[] { "/warnaserror:1,2,3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/nowarn:1,2,3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/nowarn:1;2;;3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); } private static void AssertSpecificDiagnostics(int[] expectedCodes, ReportDiagnostic[] expectedOptions, CSharpCommandLineArguments args) { var actualOrdered = args.CompilationOptions.SpecificDiagnosticOptions.OrderBy(entry => entry.Key); AssertEx.Equal( expectedCodes.Select(i => MessageProvider.Instance.GetIdForErrorCode(i)), actualOrdered.Select(entry => entry.Key)); AssertEx.Equal(expectedOptions, actualOrdered.Select(entry => entry.Value)); } [Fact] public void WarningsParse() { var parsedArgs = DefaultParse(new string[] { "/warnaserror", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Error, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); Assert.Equal(0, parsedArgs.CompilationOptions.SpecificDiagnosticOptions.Count); parsedArgs = DefaultParse(new string[] { "/warnaserror:1062,1066,1734", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Error }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror:+1062,+1066,+1734", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Error }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Error, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new int[0], new ReportDiagnostic[0], parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror+:1062,1066,1734", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Error }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new int[0], new ReportDiagnostic[0], parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror-:1062,1066,1734", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Default, ReportDiagnostic.Default, ReportDiagnostic.Default }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror+:1062,1066,1734", "/warnaserror-:1762,1974", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics( new[] { 1062, 1066, 1734, 1762, 1974 }, new[] { ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Default, ReportDiagnostic.Default }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror+:1062,1066,1734", "/warnaserror-:1062,1974", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); Assert.Equal(4, parsedArgs.CompilationOptions.SpecificDiagnosticOptions.Count); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734, 1974 }, new[] { ReportDiagnostic.Default, ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Default }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror-:1062,1066,1734", "/warnaserror+:1062,1974", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734, 1974 }, new[] { ReportDiagnostic.Error, ReportDiagnostic.Default, ReportDiagnostic.Default, ReportDiagnostic.Error }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/w:1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(1, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new int[0], new ReportDiagnostic[0], parsedArgs); parsedArgs = DefaultParse(new string[] { "/warn:1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(1, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new int[0], new ReportDiagnostic[0], parsedArgs); parsedArgs = DefaultParse(new string[] { "/warn:1", "/warnaserror+:1062,1974", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(1, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1974 }, new[] { ReportDiagnostic.Error, ReportDiagnostic.Error }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/nowarn:1062,1066,1734", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Suppress }, parsedArgs); parsedArgs = DefaultParse(new string[] { @"/nowarn:""1062 1066 1734""", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Suppress }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/nowarn:1062,1066,1734", "/warnaserror:1066,1762", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734, 1762 }, new[] { ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Error }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror:1066,1762", "/nowarn:1062,1066,1734", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734, 1762 }, new[] { ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Error }, parsedArgs); } [Fact] public void AllowUnsafe() { CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/unsafe", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.AllowUnsafe); parsedArgs = DefaultParse(new[] { "/unsafe+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.AllowUnsafe); parsedArgs = DefaultParse(new[] { "/UNSAFE-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.AllowUnsafe); parsedArgs = DefaultParse(new[] { "/unsafe-", "/unsafe+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.AllowUnsafe); parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); // default parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.AllowUnsafe); parsedArgs = DefaultParse(new[] { "/unsafe:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/unsafe:")); parsedArgs = DefaultParse(new[] { "/unsafe:+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/unsafe:+")); parsedArgs = DefaultParse(new[] { "/unsafe-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/unsafe-:")); } [Fact] public void DelaySign() { CSharpCommandLineArguments parsedArgs; parsedArgs = DefaultParse(new[] { "/delaysign", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.NotNull(parsedArgs.CompilationOptions.DelaySign); Assert.True((bool)parsedArgs.CompilationOptions.DelaySign); parsedArgs = DefaultParse(new[] { "/delaysign+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.NotNull(parsedArgs.CompilationOptions.DelaySign); Assert.True((bool)parsedArgs.CompilationOptions.DelaySign); parsedArgs = DefaultParse(new[] { "/DELAYsign-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.NotNull(parsedArgs.CompilationOptions.DelaySign); Assert.False((bool)parsedArgs.CompilationOptions.DelaySign); parsedArgs = DefaultParse(new[] { "/delaysign:-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/delaysign:-' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/delaysign:-")); Assert.Null(parsedArgs.CompilationOptions.DelaySign); } [Fact] public void PublicSign() { var parsedArgs = DefaultParse(new[] { "/publicsign", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.PublicSign); parsedArgs = DefaultParse(new[] { "/publicsign+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.PublicSign); parsedArgs = DefaultParse(new[] { "/PUBLICsign-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.PublicSign); parsedArgs = DefaultParse(new[] { "/publicsign:-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/publicsign:-' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/publicsign:-").WithLocation(1, 1)); Assert.False(parsedArgs.CompilationOptions.PublicSign); } [WorkItem(8360, "https://github.com/dotnet/roslyn/issues/8360")] [Fact] public void PublicSign_KeyFileRelativePath() { var parsedArgs = DefaultParse(new[] { "/publicsign", "/keyfile:test.snk", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, "test.snk"), parsedArgs.CompilationOptions.CryptoKeyFile); } [Fact] [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] public void PublicSignWithEmptyKeyPath() { DefaultParse(new[] { "/publicsign", "/keyfile:", "a.cs" }, WorkingDirectory).Errors.Verify( // error CS2005: Missing file specification for 'keyfile' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("keyfile").WithLocation(1, 1)); } [Fact] [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] public void PublicSignWithEmptyKeyPath2() { DefaultParse(new[] { "/publicsign", "/keyfile:\"\"", "a.cs" }, WorkingDirectory).Errors.Verify( // error CS2005: Missing file specification for 'keyfile' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("keyfile").WithLocation(1, 1)); } [WorkItem(546301, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546301")] [Fact] public void SubsystemVersionTests() { CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/subsystemversion:4.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(SubsystemVersion.Create(4, 0), parsedArgs.EmitOptions.SubsystemVersion); // wrongly supported subsystem version. CompilationOptions data will be faithful to the user input. // It is normalized at the time of emit. parsedArgs = DefaultParse(new[] { "/subsystemversion:0.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); // no error in Dev11 Assert.Equal(SubsystemVersion.Create(0, 0), parsedArgs.EmitOptions.SubsystemVersion); parsedArgs = DefaultParse(new[] { "/subsystemversion:0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); // no error in Dev11 Assert.Equal(SubsystemVersion.Create(0, 0), parsedArgs.EmitOptions.SubsystemVersion); parsedArgs = DefaultParse(new[] { "/subsystemversion:3.99", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); // no error in Dev11 Assert.Equal(SubsystemVersion.Create(3, 99), parsedArgs.EmitOptions.SubsystemVersion); parsedArgs = DefaultParse(new[] { "/subsystemversion:4.0", "/SUBsystemversion:5.333", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(SubsystemVersion.Create(5, 333), parsedArgs.EmitOptions.SubsystemVersion); parsedArgs = DefaultParse(new[] { "/subsystemversion:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "subsystemversion")); parsedArgs = DefaultParse(new[] { "/subsystemversion", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "subsystemversion")); parsedArgs = DefaultParse(new[] { "/subsystemversion-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/subsystemversion-")); parsedArgs = DefaultParse(new[] { "/subsystemversion: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "subsystemversion")); parsedArgs = DefaultParse(new[] { "/subsystemversion: 4.1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments(" 4.1")); parsedArgs = DefaultParse(new[] { "/subsystemversion:4 .0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("4 .0")); parsedArgs = DefaultParse(new[] { "/subsystemversion:4. 0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("4. 0")); parsedArgs = DefaultParse(new[] { "/subsystemversion:.", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments(".")); parsedArgs = DefaultParse(new[] { "/subsystemversion:4.", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("4.")); parsedArgs = DefaultParse(new[] { "/subsystemversion:.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments(".0")); parsedArgs = DefaultParse(new[] { "/subsystemversion:4.2 ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/subsystemversion:4.65536", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("4.65536")); parsedArgs = DefaultParse(new[] { "/subsystemversion:65536.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("65536.0")); parsedArgs = DefaultParse(new[] { "/subsystemversion:-4.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("-4.0")); // TODO: incompatibilities: versions lower than '6.2' and 'arm', 'winmdobj', 'appcontainer' } [Fact] public void MainType() { CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/m:A.B.C", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("A.B.C", parsedArgs.CompilationOptions.MainTypeName); parsedArgs = DefaultParse(new[] { "/m: ", "a.cs" }, WorkingDirectory); // Mimicking Dev11 parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "m")); Assert.Null(parsedArgs.CompilationOptions.MainTypeName); // overriding the value parsedArgs = DefaultParse(new[] { "/m:A.B.C", "/MAIN:X.Y.Z", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("X.Y.Z", parsedArgs.CompilationOptions.MainTypeName); // error parsedArgs = DefaultParse(new[] { "/maiN:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "main")); parsedArgs = DefaultParse(new[] { "/MAIN+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/MAIN+")); parsedArgs = DefaultParse(new[] { "/M", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "m")); // incompatible values /main && /target parsedArgs = DefaultParse(new[] { "/main:a", "/t:library", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoMainOnDLL)); parsedArgs = DefaultParse(new[] { "/main:a", "/t:module", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoMainOnDLL)); } [Fact] public void Codepage() { CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/CodePage:1200", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("Unicode", parsedArgs.Encoding.EncodingName); parsedArgs = DefaultParse(new[] { "/CodePage:1200", "/codePAGE:65001", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("Unicode (UTF-8)", parsedArgs.Encoding.EncodingName); // error parsedArgs = DefaultParse(new[] { "/codepage:0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadCodepage).WithArguments("0")); parsedArgs = DefaultParse(new[] { "/codepage:abc", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadCodepage).WithArguments("abc")); parsedArgs = DefaultParse(new[] { "/codepage:-5", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadCodepage).WithArguments("-5")); parsedArgs = DefaultParse(new[] { "/codepage: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadCodepage).WithArguments("")); parsedArgs = DefaultParse(new[] { "/codepage:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadCodepage).WithArguments("")); parsedArgs = DefaultParse(new[] { "/codepage", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "codepage")); parsedArgs = DefaultParse(new[] { "/codepage+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/codepage+")); } [Fact, WorkItem(24735, "https://github.com/dotnet/roslyn/issues/24735")] public void ChecksumAlgorithm() { CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:sHa1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(SourceHashAlgorithm.Sha1, parsedArgs.ChecksumAlgorithm); Assert.Equal(HashAlgorithmName.SHA256, parsedArgs.EmitOptions.PdbChecksumAlgorithm); parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:sha256", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(SourceHashAlgorithm.Sha256, parsedArgs.ChecksumAlgorithm); Assert.Equal(HashAlgorithmName.SHA256, parsedArgs.EmitOptions.PdbChecksumAlgorithm); parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(SourceHashAlgorithm.Sha256, parsedArgs.ChecksumAlgorithm); Assert.Equal(HashAlgorithmName.SHA256, parsedArgs.EmitOptions.PdbChecksumAlgorithm); // error parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:256", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadChecksumAlgorithm).WithArguments("256")); parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:sha-1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadChecksumAlgorithm).WithArguments("sha-1")); parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:sha", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadChecksumAlgorithm).WithArguments("sha")); parsedArgs = DefaultParse(new[] { "/checksumAlgorithm: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "checksumalgorithm")); parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "checksumalgorithm")); parsedArgs = DefaultParse(new[] { "/checksumAlgorithm", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "checksumalgorithm")); parsedArgs = DefaultParse(new[] { "/checksumAlgorithm+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/checksumAlgorithm+")); } [Fact] public void AddModule() { CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/noconfig", "/nostdlib", "/addmodule:abc.netmodule", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(1, parsedArgs.MetadataReferences.Length); Assert.Equal("abc.netmodule", parsedArgs.MetadataReferences[0].Reference); Assert.Equal(MetadataImageKind.Module, parsedArgs.MetadataReferences[0].Properties.Kind); parsedArgs = DefaultParse(new[] { "/noconfig", "/nostdlib", "/aDDmodule:c:\\abc;c:\\abc;d:\\xyz", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(3, parsedArgs.MetadataReferences.Length); Assert.Equal("c:\\abc", parsedArgs.MetadataReferences[0].Reference); Assert.Equal(MetadataImageKind.Module, parsedArgs.MetadataReferences[0].Properties.Kind); Assert.Equal("c:\\abc", parsedArgs.MetadataReferences[1].Reference); Assert.Equal(MetadataImageKind.Module, parsedArgs.MetadataReferences[1].Properties.Kind); Assert.Equal("d:\\xyz", parsedArgs.MetadataReferences[2].Reference); Assert.Equal(MetadataImageKind.Module, parsedArgs.MetadataReferences[2].Properties.Kind); // error parsedArgs = DefaultParse(new[] { "/ADDMODULE", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/addmodule:")); parsedArgs = DefaultParse(new[] { "/ADDMODULE+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/ADDMODULE+")); parsedArgs = DefaultParse(new[] { "/ADDMODULE:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/ADDMODULE:")); } [Fact, WorkItem(530751, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530751")] public void CS7061fromCS0647_ModuleWithCompilationRelaxations() { string source1 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" using System.Runtime.CompilerServices; [assembly: CompilationRelaxations(CompilationRelaxations.NoStringInterning)] public class Mod { }").Path; string source2 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" using System.Runtime.CompilerServices; [assembly: CompilationRelaxations(4)] public class Mod { }").Path; string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" using System.Runtime.CompilerServices; [assembly: CompilationRelaxations(CompilationRelaxations.NoStringInterning)] class Test { static void Main() {} }").Path; var baseDir = Path.GetDirectoryName(source); // === Scenario 1 === var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/t:module", source1 }).Run(outWriter); Assert.Equal(0, exitCode); var modfile = source1.Substring(0, source1.Length - 2) + "netmodule"; outWriter = new StringWriter(CultureInfo.InvariantCulture); var parsedArgs = DefaultParse(new[] { "/nologo", "/addmodule:" + modfile, source }, WorkingDirectory); parsedArgs.Errors.Verify(); exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/addmodule:" + modfile, source }).Run(outWriter); Assert.Empty(outWriter.ToString()); // === Scenario 2 === outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/t:module", source2 }).Run(outWriter); Assert.Equal(0, exitCode); modfile = source2.Substring(0, source2.Length - 2) + "netmodule"; outWriter = new StringWriter(CultureInfo.InvariantCulture); parsedArgs = DefaultParse(new[] { "/nologo", "/addmodule:" + modfile, source }, WorkingDirectory); parsedArgs.Errors.Verify(); exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", "/addmodule:" + modfile, source }).Run(outWriter); Assert.Equal(1, exitCode); // Dev11: CS0647 (Emit) Assert.Contains("error CS7061: Duplicate 'CompilationRelaxationsAttribute' attribute in", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(source1); CleanupAllGeneratedFiles(source2); CleanupAllGeneratedFiles(source); } [Fact, WorkItem(530780, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530780")] public void AddModuleWithExtensionMethod() { string source1 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"public static class Extensions { public static bool EB(this bool b) { return b; } }").Path; string source2 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"class C { static void Main() {} }").Path; var baseDir = Path.GetDirectoryName(source2); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/t:module", source1 }).Run(outWriter); Assert.Equal(0, exitCode); var modfile = source1.Substring(0, source1.Length - 2) + "netmodule"; outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/addmodule:" + modfile, source2 }).Run(outWriter); Assert.Equal(0, exitCode); CleanupAllGeneratedFiles(source1); CleanupAllGeneratedFiles(source2); } [Fact, WorkItem(546297, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546297")] public void OLDCS0013FTL_MetadataEmitFailureSameModAndRes() { string source1 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"class Mod { }").Path; string source2 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"class C { static void Main() {} }").Path; var baseDir = Path.GetDirectoryName(source2); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/t:module", source1 }).Run(outWriter); Assert.Equal(0, exitCode); var modfile = source1.Substring(0, source1.Length - 2) + "netmodule"; outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", "/addmodule:" + modfile, "/linkres:" + modfile, source2 }).Run(outWriter); Assert.Equal(1, exitCode); // Native gives CS0013 at emit stage Assert.Equal("error CS7041: Each linked resource and module must have a unique filename. Filename '" + Path.GetFileName(modfile) + "' is specified more than once in this assembly", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source1); CleanupAllGeneratedFiles(source2); } [Fact] public void Utf8Output() { CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/utf8output", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True((bool)parsedArgs.Utf8Output); parsedArgs = DefaultParse(new[] { "/utf8output", "/utf8output", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True((bool)parsedArgs.Utf8Output); parsedArgs = DefaultParse(new[] { "/utf8output:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/utf8output:")); } [Fact] public void CscCompile_WithSourceCodeRedirectedViaStandardInput_ProducesRunnableProgram() { string tempDir = Temp.CreateDirectory().Path; ProcessResult result = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ProcessUtilities.Run("cmd", $@"/C echo ^ class A ^ {{ ^ public static void Main() =^^^> ^ System.Console.WriteLine(""Hello World!""); ^ }} | {s_CSharpCompilerExecutable} /nologo /t:exe -" .Replace(Environment.NewLine, string.Empty), workingDirectory: tempDir) : ProcessUtilities.Run("/usr/bin/env", $@"sh -c ""echo \ class A \ {{ \ public static void Main\(\) =\> \ System.Console.WriteLine\(\\\""Hello World\!\\\""\)\; \ }} | {s_CSharpCompilerExecutable} /nologo /t:exe -""", workingDirectory: tempDir, // we are testing shell's piped/redirected stdin behavior explicitly // instead of using Process.StandardInput.Write(), so we set // redirectStandardInput to true, which implies that isatty of child // process is false and thereby Console.IsInputRedirected will return // true in csc code. redirectStandardInput: true); Assert.False(result.ContainsErrors, $"Compilation error(s) occurred: {result.Output} {result.Errors}"); string output = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ProcessUtilities.RunAndGetOutput("cmd.exe", $@"/C ""{s_DotnetCscRun} -.exe""", expectedRetCode: 0, startFolder: tempDir) : ProcessUtilities.RunAndGetOutput("sh", $@"-c ""{s_DotnetCscRun} -.exe""", expectedRetCode: 0, startFolder: tempDir); Assert.Equal("Hello World!", output.Trim()); } [Fact] public void CscCompile_WithSourceCodeRedirectedViaStandardInput_ProducesLibrary() { var name = Guid.NewGuid().ToString() + ".dll"; string tempDir = Temp.CreateDirectory().Path; ProcessResult result = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ProcessUtilities.Run("cmd", $@"/C echo ^ class A ^ {{ ^ public A Get() =^^^> default; ^ }} | {s_CSharpCompilerExecutable} /nologo /t:library /out:{name} -" .Replace(Environment.NewLine, string.Empty), workingDirectory: tempDir) : ProcessUtilities.Run("/usr/bin/env", $@"sh -c ""echo \ class A \ {{ \ public A Get\(\) =\> default\; \ }} | {s_CSharpCompilerExecutable} /nologo /t:library /out:{name} -""", workingDirectory: tempDir, // we are testing shell's piped/redirected stdin behavior explicitly // instead of using Process.StandardInput.Write(), so we set // redirectStandardInput to true, which implies that isatty of child // process is false and thereby Console.IsInputRedirected will return // true in csc code. redirectStandardInput: true); Assert.False(result.ContainsErrors, $"Compilation error(s) occurred: {result.Output} {result.Errors}"); var assemblyName = AssemblyName.GetAssemblyName(Path.Combine(tempDir, name)); Assert.Equal(name.Replace(".dll", ", Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), assemblyName.ToString()); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/55727")] public void CsiScript_WithSourceCodeRedirectedViaStandardInput_ExecutesNonInteractively() { string tempDir = Temp.CreateDirectory().Path; ProcessResult result = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ProcessUtilities.Run("cmd", $@"/C echo Console.WriteLine(""Hello World!"") | {s_CSharpScriptExecutable} -") : ProcessUtilities.Run("/usr/bin/env", $@"sh -c ""echo Console.WriteLine\(\\\""Hello World\!\\\""\) | {s_CSharpScriptExecutable} -""", workingDirectory: tempDir, // we are testing shell's piped/redirected stdin behavior explicitly // instead of using Process.StandardInput.Write(), so we set // redirectStandardInput to true, which implies that isatty of child // process is false and thereby Console.IsInputRedirected will return // true in csc code. redirectStandardInput: true); Assert.False(result.ContainsErrors, $"Compilation error(s) occurred: {result.Output} {result.Errors}"); Assert.Equal("Hello World!", result.Output.Trim()); } [Fact] public void CscCompile_WithRedirectedInputIndicatorAndStandardInputNotRedirected_ReportsCS8782() { if (Console.IsInputRedirected) { // [applicable to both Windows and Unix] // if our parent (xunit) process itself has input redirected, we cannot test this // error case because our child process will inherit it and we cannot achieve what // we are aiming for: isatty(0):true and thereby Console.IsInputerRedirected:false in // child. running this case will make StreamReader to hang (waiting for input, that // we do not propagate: parent.In->child.In). // // note: in Unix we can "close" fd0 by appending `0>&-` in the `sh -c` command below, // but that will also not impact the result of isatty(), and in turn causes a different // compiler error. return; } string tempDir = Temp.CreateDirectory().Path; ProcessResult result = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ProcessUtilities.Run("cmd", $@"/C ""{s_CSharpCompilerExecutable} /nologo /t:exe -""", workingDirectory: tempDir) : ProcessUtilities.Run("/usr/bin/env", $@"sh -c ""{s_CSharpCompilerExecutable} /nologo /t:exe -""", workingDirectory: tempDir); Assert.True(result.ContainsErrors); Assert.Contains(((int)ErrorCode.ERR_StdInOptionProvidedButConsoleInputIsNotRedirected).ToString(), result.Output); } [Fact] public void CscCompile_WithMultipleStdInOperators_WarnsCS2002() { string tempDir = Temp.CreateDirectory().Path; ProcessResult result = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ProcessUtilities.Run("cmd", $@"/C echo ^ class A ^ {{ ^ public static void Main() =^^^> ^ System.Console.WriteLine(""Hello World!""); ^ }} | {s_CSharpCompilerExecutable} /nologo - /t:exe -" .Replace(Environment.NewLine, string.Empty)) : ProcessUtilities.Run("/usr/bin/env", $@"sh -c ""echo \ class A \ {{ \ public static void Main\(\) =\> \ System.Console.WriteLine\(\\\""Hello World\!\\\""\)\; \ }} | {s_CSharpCompilerExecutable} /nologo - /t:exe -""", workingDirectory: tempDir, // we are testing shell's piped/redirected stdin behavior explicitly // instead of using Process.StandardInput.Write(), so we set // redirectStandardInput to true, which implies that isatty of child // process is false and thereby Console.IsInputRedirected will return // true in csc code. redirectStandardInput: true); Assert.Contains(((int)ErrorCode.WRN_FileAlreadyIncluded).ToString(), result.Output); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void CscUtf8Output_WithRedirecting_Off() { var srcFile = Temp.CreateFile().WriteAllText("\u265A").Path; var tempOut = Temp.CreateFile(); var output = ProcessUtilities.RunAndGetOutput("cmd", "/C \"" + s_CSharpCompilerExecutable + "\" /nologo /preferreduilang:en /t:library " + srcFile + " > " + tempOut.Path, expectedRetCode: 1); Assert.Equal("", output.Trim()); Assert.Equal("SRC.CS(1,1): error CS1056: Unexpected character '?'", tempOut.ReadAllText().Trim().Replace(srcFile, "SRC.CS")); CleanupAllGeneratedFiles(srcFile); CleanupAllGeneratedFiles(tempOut.Path); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void CscUtf8Output_WithRedirecting_On() { var srcFile = Temp.CreateFile().WriteAllText("\u265A").Path; var tempOut = Temp.CreateFile(); var output = ProcessUtilities.RunAndGetOutput("cmd", "/C \"" + s_CSharpCompilerExecutable + "\" /utf8output /nologo /preferreduilang:en /t:library " + srcFile + " > " + tempOut.Path, expectedRetCode: 1); Assert.Equal("", output.Trim()); Assert.Equal("SRC.CS(1,1): error CS1056: Unexpected character '♚'", tempOut.ReadAllText().Trim().Replace(srcFile, "SRC.CS")); CleanupAllGeneratedFiles(srcFile); CleanupAllGeneratedFiles(tempOut.Path); } [WorkItem(546653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546653")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void NoSourcesWithModule() { var folder = Temp.CreateDirectory(); var aCs = folder.CreateFile("a.cs"); aCs.WriteAllText("public class C {}"); var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, $"/nologo /t:module /out:a.netmodule \"{aCs}\"", startFolder: folder.ToString()); Assert.Equal("", output.Trim()); output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, "/nologo /t:library /out:b.dll /addmodule:a.netmodule ", startFolder: folder.ToString()); Assert.Equal("", output.Trim()); output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, "/nologo /preferreduilang:en /t:module /out:b.dll /addmodule:a.netmodule ", startFolder: folder.ToString()); Assert.Equal("warning CS2008: No source files specified.", output.Trim()); CleanupAllGeneratedFiles(aCs.Path); } [WorkItem(546653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546653")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void NoSourcesWithResource() { var folder = Temp.CreateDirectory(); var aCs = folder.CreateFile("a.cs"); aCs.WriteAllText("public class C {}"); var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, "/nologo /t:library /out:b.dll /resource:a.cs", startFolder: folder.ToString()); Assert.Equal("", output.Trim()); CleanupAllGeneratedFiles(aCs.Path); } [WorkItem(546653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546653")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void NoSourcesWithLinkResource() { var folder = Temp.CreateDirectory(); var aCs = folder.CreateFile("a.cs"); aCs.WriteAllText("public class C {}"); var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, "/nologo /t:library /out:b.dll /linkresource:a.cs", startFolder: folder.ToString()); Assert.Equal("", output.Trim()); CleanupAllGeneratedFiles(aCs.Path); } [Fact] public void KeyContainerAndKeyFile() { // KEYCONTAINER CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/keycontainer:RIPAdamYauch", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("RIPAdamYauch", parsedArgs.CompilationOptions.CryptoKeyContainer); parsedArgs = DefaultParse(new[] { "/keycontainer", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'keycontainer' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "keycontainer")); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer); parsedArgs = DefaultParse(new[] { "/keycontainer-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/keycontainer-' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/keycontainer-")); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer); parsedArgs = DefaultParse(new[] { "/keycontainer:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'keycontainer' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "keycontainer")); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer); parsedArgs = DefaultParse(new[] { "/keycontainer: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "keycontainer")); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer); // KEYFILE parsedArgs = DefaultParse(new[] { @"/keyfile:\somepath\s""ome Fil""e.goo.bar", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); //EDMAURER let's not set the option in the event that there was an error. //Assert.Equal(@"\somepath\some File.goo.bar", parsedArgs.CompilationOptions.CryptoKeyFile); parsedArgs = DefaultParse(new[] { "/keyFile", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2005: Missing file specification for 'keyfile' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("keyfile")); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyFile); parsedArgs = DefaultParse(new[] { "/keyFile: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("keyfile")); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyFile); parsedArgs = DefaultParse(new[] { "/keyfile-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/keyfile-' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/keyfile-")); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyFile); // DEFAULTS parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyFile); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer); // KEYFILE | KEYCONTAINER conflicts parsedArgs = DefaultParse(new[] { "/keyFile:a", "/keyContainer:b", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("a", parsedArgs.CompilationOptions.CryptoKeyFile); Assert.Equal("b", parsedArgs.CompilationOptions.CryptoKeyContainer); parsedArgs = DefaultParse(new[] { "/keyContainer:b", "/keyFile:a", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("a", parsedArgs.CompilationOptions.CryptoKeyFile); Assert.Equal("b", parsedArgs.CompilationOptions.CryptoKeyContainer); } [Fact, WorkItem(554551, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554551")] public void CS1698WRN_AssumedMatchThis() { // compile with: /target:library /keyfile:mykey.snk var text1 = @"[assembly:System.Reflection.AssemblyVersion(""2"")] public class CS1698_a {} "; // compile with: /target:library /reference:CS1698_a.dll /keyfile:mykey.snk var text2 = @"public class CS1698_b : CS1698_a {} "; //compile with: /target:library /out:cs1698_a.dll /reference:cs1698_b.dll /keyfile:mykey.snk var text = @"[assembly:System.Reflection.AssemblyVersion(""3"")] public class CS1698_c : CS1698_b {} public class CS1698_a {} "; var folder = Temp.CreateDirectory(); var cs1698a = folder.CreateFile("CS1698a.cs"); cs1698a.WriteAllText(text1); var cs1698b = folder.CreateFile("CS1698b.cs"); cs1698b.WriteAllText(text2); var cs1698 = folder.CreateFile("CS1698.cs"); cs1698.WriteAllText(text); var snkFile = Temp.CreateFile().WriteAllBytes(TestResources.General.snKey); var kfile = "/keyfile:" + snkFile.Path; CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/t:library", kfile, "CS1698a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/t:library", kfile, "/r:" + cs1698a.Path, "CS1698b.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/t:library", kfile, "/r:" + cs1698b.Path, "/out:" + cs1698a.Path, "CS1698.cs" }, WorkingDirectory); // Roslyn no longer generates a warning for this...since this was only a warning, we're not really // saving anyone...does not provide high value to implement... // warning CS1698: Circular assembly reference 'CS1698a, Version=2.0.0.0, Culture=neutral,PublicKeyToken = 9e9d6755e7bb4c10' // does not match the output assembly name 'CS1698a, Version = 3.0.0.0, Culture = neutral, PublicKeyToken = 9e9d6755e7bb4c10'. // Try adding a reference to 'CS1698a, Version = 2.0.0.0, Culture = neutral, PublicKeyToken = 9e9d6755e7bb4c10' or changing the output assembly name to match. parsedArgs.Errors.Verify(); CleanupAllGeneratedFiles(snkFile.Path); CleanupAllGeneratedFiles(cs1698a.Path); CleanupAllGeneratedFiles(cs1698b.Path); CleanupAllGeneratedFiles(cs1698.Path); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/dotnet/roslyn/issues/30926")] public void BinaryFileErrorTest() { var binaryPath = Temp.CreateFile().WriteAllBytes(ResourcesNet451.mscorlib).Path; var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", binaryPath }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal( "error CS2015: '" + binaryPath + "' is a binary file instead of a text file", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(binaryPath); } #if !NETCOREAPP [WorkItem(530221, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530221")] [WorkItem(5660, "https://github.com/dotnet/roslyn/issues/5660")] [ConditionalFact(typeof(WindowsOnly), typeof(IsEnglishLocal))] public void Bug15538() { // Several Jenkins VMs are still running with local systems permissions. This suite won't run properly // in that environment. Removing this check is being tracked by issue #79. using (var identity = System.Security.Principal.WindowsIdentity.GetCurrent()) { if (identity.IsSystem) { return; } // The icacls command fails on our Helix machines and it appears to be related to the use of the $ in // the username. // https://github.com/dotnet/roslyn/issues/28836 if (StringComparer.OrdinalIgnoreCase.Equals(Environment.UserDomainName, "WORKGROUP")) { return; } } var folder = Temp.CreateDirectory(); var source = folder.CreateFile("src.vb").WriteAllText("").Path; var _ref = folder.CreateFile("ref.dll").WriteAllText("").Path; try { var output = ProcessUtilities.RunAndGetOutput("cmd", "/C icacls " + _ref + " /inheritance:r /Q"); Assert.Equal("Successfully processed 1 files; Failed processing 0 files", output.Trim()); output = ProcessUtilities.RunAndGetOutput("cmd", "/C icacls " + _ref + @" /deny %USERDOMAIN%\%USERNAME%:(r,WDAC) /Q"); Assert.Equal("Successfully processed 1 files; Failed processing 0 files", output.Trim()); output = ProcessUtilities.RunAndGetOutput("cmd", "/C \"" + s_CSharpCompilerExecutable + "\" /nologo /preferreduilang:en /r:" + _ref + " /t:library " + source, expectedRetCode: 1); Assert.Equal("error CS0009: Metadata file '" + _ref + "' could not be opened -- Access to the path '" + _ref + "' is denied.", output.Trim()); } finally { var output = ProcessUtilities.RunAndGetOutput("cmd", "/C icacls " + _ref + " /reset /Q"); Assert.Equal("Successfully processed 1 files; Failed processing 0 files", output.Trim()); File.Delete(_ref); } CleanupAllGeneratedFiles(source); } #endif [WorkItem(545832, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545832")] [Fact] public void ResponseFilesWithEmptyAliasReference() { string source = Temp.CreateFile("a.cs").WriteAllText(@" // <Area> ExternAlias - command line alias</Area> // <Title> // negative test cases: empty file name ("""") // </Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=error>CS1680:.*myAlias=</Expects> // <Code> class myClass { static int Main() { return 1; } } // </Code> ").Path; string rsp = Temp.CreateFile().WriteAllText(@" /nologo /r:myAlias="""" ").Path; var outWriter = new StringWriter(CultureInfo.InvariantCulture); // csc errors_whitespace_008.cs @errors_whitespace_008.cs.rsp var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS1680: Invalid reference alias option: 'myAlias=' -- missing filename", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [Fact] public void ResponseFileOrdering() { var rspFilePath1 = Temp.CreateFile().WriteAllText(@" /b /c ").Path; assertOrder( new[] { "/a", "/b", "/c", "/d" }, new[] { "/a", @$"@""{rspFilePath1}""", "/d" }); var rspFilePath2 = Temp.CreateFile().WriteAllText(@" /c /d ").Path; rspFilePath1 = Temp.CreateFile().WriteAllText(@$" /b @""{rspFilePath2}"" ").Path; assertOrder( new[] { "/a", "/b", "/c", "/d", "/e" }, new[] { "/a", @$"@""{rspFilePath1}""", "/e" }); rspFilePath1 = Temp.CreateFile().WriteAllText(@$" /b ").Path; rspFilePath2 = Temp.CreateFile().WriteAllText(@" # this will be ignored /c /d ").Path; assertOrder( new[] { "/a", "/b", "/c", "/d", "/e" }, new[] { "/a", @$"@""{rspFilePath1}""", $@"@""{rspFilePath2}""", "/e" }); void assertOrder(string[] expected, string[] args) { var flattenedArgs = ArrayBuilder<string>.GetInstance(); var diagnostics = new List<Diagnostic>(); CSharpCommandLineParser.Default.FlattenArgs( args, diagnostics, flattenedArgs, scriptArgsOpt: null, baseDirectory: Path.DirectorySeparatorChar == '\\' ? @"c:\" : "/"); Assert.Empty(diagnostics); Assert.Equal(expected, flattenedArgs); flattenedArgs.Free(); } } [WorkItem(545832, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545832")] [Fact] public void ResponseFilesWithEmptyAliasReference2() { string source = Temp.CreateFile("a.cs").WriteAllText(@" // <Area> ExternAlias - command line alias</Area> // <Title> // negative test cases: empty file name ("""") // </Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=error>CS1680:.*myAlias=</Expects> // <Code> class myClass { static int Main() { return 1; } } // </Code> ").Path; string rsp = Temp.CreateFile().WriteAllText(@" /nologo /r:myAlias="" "" ").Path; var outWriter = new StringWriter(CultureInfo.InvariantCulture); // csc errors_whitespace_008.cs @errors_whitespace_008.cs.rsp var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS1680: Invalid reference alias option: 'myAlias=' -- missing filename", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [WorkItem(1784, "https://github.com/dotnet/roslyn/issues/1784")] [Fact] public void QuotedDefineInRespFile() { string source = Temp.CreateFile("a.cs").WriteAllText(@" #if NN class myClass { #endif static int Main() #if DD { return 1; #endif #if AA } #endif #if BB } #endif ").Path; string rsp = Temp.CreateFile().WriteAllText(@" /d:""DD"" /d:""AA;BB"" /d:""N""N ").Path; var outWriter = new StringWriter(CultureInfo.InvariantCulture); // csc errors_whitespace_008.cs @errors_whitespace_008.cs.rsp var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [WorkItem(1784, "https://github.com/dotnet/roslyn/issues/1784")] [Fact] public void QuotedDefineInRespFileErr() { string source = Temp.CreateFile("a.cs").WriteAllText(@" #if NN class myClass { #endif static int Main() #if DD { return 1; #endif #if AA } #endif #if BB } #endif ").Path; string rsp = Temp.CreateFile().WriteAllText(@" /d:""DD"""" /d:""AA;BB"" /d:""N"" ""N ").Path; var outWriter = new StringWriter(CultureInfo.InvariantCulture); // csc errors_whitespace_008.cs @errors_whitespace_008.cs.rsp var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [Fact] public void ResponseFileSplitting() { string[] responseFile; responseFile = new string[] { @"a.cs b.cs ""c.cs e.cs""", @"hello world # this is a comment" }; IEnumerable<string> args = CSharpCommandLineParser.ParseResponseLines(responseFile); AssertEx.Equal(new[] { "a.cs", "b.cs", @"c.cs e.cs", "hello", "world" }, args); // Check comment handling; comment character only counts at beginning of argument responseFile = new string[] { @" # ignore this", @" # ignore that ""hello""", @" a.cs #3.cs", @" b#.cs c#d.cs #e.cs", @" ""#f.cs""", @" ""#g.cs #h.cs""" }; args = CSharpCommandLineParser.ParseResponseLines(responseFile); AssertEx.Equal(new[] { "a.cs", "b#.cs", "c#d.cs", "#f.cs", "#g.cs #h.cs" }, args); // Check backslash escaping responseFile = new string[] { @"a\b\c d\\e\\f\\ \\\g\\\h\\\i \\\\ \\\\\k\\\\\", }; args = CSharpCommandLineParser.ParseResponseLines(responseFile); AssertEx.Equal(new[] { @"a\b\c", @"d\\e\\f\\", @"\\\g\\\h\\\i", @"\\\\", @"\\\\\k\\\\\" }, args); // More backslash escaping and quoting responseFile = new string[] { @"a\""a b\\""b c\\\""c d\\\\""d e\\\\\""e f"" g""", }; args = CSharpCommandLineParser.ParseResponseLines(responseFile); AssertEx.Equal(new[] { @"a\""a", @"b\\""b c\\\""c d\\\\""d", @"e\\\\\""e", @"f"" g""" }, args); // Quoting inside argument is valid. responseFile = new string[] { @" /o:""goo.cs"" /o:""abc def""\baz ""/o:baz bar""bing", }; args = CSharpCommandLineParser.ParseResponseLines(responseFile); AssertEx.Equal(new[] { @"/o:""goo.cs""", @"/o:""abc def""\baz", @"""/o:baz bar""bing" }, args); } [ConditionalFact(typeof(WindowsOnly))] private void SourceFileQuoting() { string[] responseFile = new string[] { @"d:\\""abc def""\baz.cs ab""c d""e.cs", }; CSharpCommandLineArguments args = DefaultParse(CSharpCommandLineParser.ParseResponseLines(responseFile), @"c:\"); AssertEx.Equal(new[] { @"d:\abc def\baz.cs", @"c:\abc de.cs" }, args.SourceFiles.Select(file => file.Path)); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName1() { string source1 = @" class A { } "; string source2 = @" class B { static void Main() { } } "; // Name comes from first input (file, not class) name, since DLL. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:library" }, expectedOutputName: "p.dll"); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName2() { string source1 = @" class A { } "; string source2 = @" class B { static void Main() { } } "; // Name comes from command-line option. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:library", "/out:r.dll" }, expectedOutputName: "r.dll"); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName3() { string source1 = @" class A { } "; string source2 = @" class B { static void Main() { } } "; // Name comes from name of file containing entrypoint, since EXE. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:exe" }, expectedOutputName: "q.exe"); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName4() { string source1 = @" class A { } "; string source2 = @" class B { static void Main() { } } "; // Name comes from command-line option. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:exe", "/out:r.exe" }, expectedOutputName: "r.exe"); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName5() { string source1 = @" class A { static void Main() { } } "; string source2 = @" class B { static void Main() { } } "; // Name comes from name of file containing entrypoint - affected by /main, since EXE. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:exe", "/main:A" }, expectedOutputName: "p.exe"); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName6() { string source1 = @" class A { static void Main() { } } "; string source2 = @" class B { static void Main() { } } "; // Name comes from name of file containing entrypoint - affected by /main, since EXE. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:exe", "/main:B" }, expectedOutputName: "q.exe"); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName7() { string source1 = @" partial class A { static partial void Main() { } } "; string source2 = @" partial class A { static partial void Main(); } "; // Name comes from name of file containing entrypoint, since EXE. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:exe" }, expectedOutputName: "p.exe"); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName8() { string source1 = @" partial class A { static partial void Main(); } "; string source2 = @" partial class A { static partial void Main() { } } "; // Name comes from name of file containing entrypoint, since EXE. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:exe" }, expectedOutputName: "q.exe"); } [Fact] public void OutputFileName9() { string source1 = @" class A { } "; string source2 = @" class B { static void Main() { } } "; // Name comes from first input (file, not class) name, since winmdobj. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:winmdobj" }, expectedOutputName: "p.winmdobj"); } [Fact] public void OutputFileName10() { string source1 = @" class A { } "; string source2 = @" class B { static void Main() { } } "; // Name comes from name of file containing entrypoint, since appcontainerexe. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:appcontainerexe" }, expectedOutputName: "q.exe"); } [Fact] public void OutputFileName_Switch() { string source1 = @" class A { } "; string source2 = @" class B { static void Main() { } } "; // Name comes from name of file containing entrypoint, since EXE. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:exe", "/out:r.exe" }, expectedOutputName: "r.exe"); } [Fact] public void OutputFileName_NoEntryPoint() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/target:exe", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.NotEqual(0, exitCode); Assert.Equal("error CS5001: Program does not contain a static 'Main' method suitable for an entry point", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(file.Path); } [Fact, WorkItem(1093063, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1093063")] public void VerifyDiagnosticSeverityNotLocalized() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/target:exe", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.NotEqual(0, exitCode); // If "error" was localized, below assert will fail on PLOC builds. The output would be something like: "!pTCvB!vbc : !FLxft!error 表! CS5001:" Assert.Contains("error CS5001:", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(file.Path); } [Fact] public void NoLogo_1() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/target:library", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal(@"", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(file.Path); } [Fact] public void NoLogo_2() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/target:library", "/preferreduilang:en", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var patched = Regex.Replace(outWriter.ToString().Trim(), "version \\d+\\.\\d+\\.\\d+(-[\\w\\d]+)*", "version A.B.C-d"); patched = ReplaceCommitHash(patched); Assert.Equal(@" Microsoft (R) Visual C# Compiler version A.B.C-d (HASH) Copyright (C) Microsoft Corporation. All rights reserved.".Trim(), patched); CleanupAllGeneratedFiles(file.Path); } [Theory, InlineData("Microsoft (R) Visual C# Compiler version A.B.C-d (<developer build>)", "Microsoft (R) Visual C# Compiler version A.B.C-d (HASH)"), InlineData("Microsoft (R) Visual C# Compiler version A.B.C-d (ABCDEF01)", "Microsoft (R) Visual C# Compiler version A.B.C-d (HASH)"), InlineData("Microsoft (R) Visual C# Compiler version A.B.C-d (abcdef90)", "Microsoft (R) Visual C# Compiler version A.B.C-d (HASH)"), InlineData("Microsoft (R) Visual C# Compiler version A.B.C-d (12345678)", "Microsoft (R) Visual C# Compiler version A.B.C-d (HASH)")] public void TestReplaceCommitHash(string orig, string expected) { Assert.Equal(expected, ReplaceCommitHash(orig)); } private static string ReplaceCommitHash(string s) { // open paren, followed by either <developer build> or 8 hex, followed by close paren return Regex.Replace(s, "(\\((<developer build>|[a-fA-F0-9]{8})\\))", "(HASH)"); } [Fact] public void ExtractShortCommitHash() { Assert.Null(CommonCompiler.ExtractShortCommitHash(null)); Assert.Equal("", CommonCompiler.ExtractShortCommitHash("")); Assert.Equal("<", CommonCompiler.ExtractShortCommitHash("<")); Assert.Equal("<developer build>", CommonCompiler.ExtractShortCommitHash("<developer build>")); Assert.Equal("1", CommonCompiler.ExtractShortCommitHash("1")); Assert.Equal("1234567", CommonCompiler.ExtractShortCommitHash("1234567")); Assert.Equal("12345678", CommonCompiler.ExtractShortCommitHash("12345678")); Assert.Equal("12345678", CommonCompiler.ExtractShortCommitHash("123456789")); } private void CheckOutputFileName(string source1, string source2, string inputName1, string inputName2, string[] commandLineArguments, string expectedOutputName) { var dir = Temp.CreateDirectory(); var file1 = dir.CreateFile(inputName1); file1.WriteAllText(source1); var file2 = dir.CreateFile(inputName2); file2.WriteAllText(source2); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, commandLineArguments.Concat(new[] { inputName1, inputName2 }).ToArray()); int exitCode = csc.Run(outWriter); if (exitCode != 0) { Console.WriteLine(outWriter.ToString()); Assert.Equal(0, exitCode); } Assert.Equal(1, Directory.EnumerateFiles(dir.Path, "*" + PathUtilities.GetExtension(expectedOutputName)).Count()); Assert.Equal(1, Directory.EnumerateFiles(dir.Path, expectedOutputName).Count()); using (var metadata = ModuleMetadata.CreateFromImage(File.ReadAllBytes(Path.Combine(dir.Path, expectedOutputName)))) { var peReader = metadata.Module.GetMetadataReader(); Assert.True(peReader.IsAssembly); Assert.Equal(PathUtilities.RemoveExtension(expectedOutputName), peReader.GetString(peReader.GetAssemblyDefinition().Name)); Assert.Equal(expectedOutputName, peReader.GetString(peReader.GetModuleDefinition().Name)); } if (System.IO.File.Exists(expectedOutputName)) { System.IO.File.Delete(expectedOutputName); } CleanupAllGeneratedFiles(file1.Path); CleanupAllGeneratedFiles(file2.Path); } [Fact] public void MissingReference() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/r:missing.dll", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS0006: Metadata file 'missing.dll' could not be found", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(file.Path); } [WorkItem(545025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545025")] [ConditionalFact(typeof(WindowsOnly))] public void CompilationWithWarnAsError_01() { string source = @" public class C { public static void Main() { } }"; // Baseline without warning options (expect success) int exitCode = GetExitCode(source, "a.cs", new String[] { }); Assert.Equal(0, exitCode); // The case with /warnaserror (expect to be success, since there will be no warning) exitCode = GetExitCode(source, "b.cs", new[] { "/warnaserror" }); Assert.Equal(0, exitCode); // The case with /warnaserror and /nowarn:1 (expect success) // Note that even though the command line option has a warning, it is not going to become an error // in order to avoid the halt of compilation. exitCode = GetExitCode(source, "c.cs", new[] { "/warnaserror", "/nowarn:1" }); Assert.Equal(0, exitCode); } [WorkItem(545025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545025")] [ConditionalFact(typeof(WindowsOnly))] public void CompilationWithWarnAsError_02() { string source = @" public class C { public static void Main() { int x; // CS0168 } }"; // Baseline without warning options (expect success) int exitCode = GetExitCode(source, "a.cs", new String[] { }); Assert.Equal(0, exitCode); // The case with /warnaserror (expect failure) exitCode = GetExitCode(source, "b.cs", new[] { "/warnaserror" }); Assert.NotEqual(0, exitCode); // The case with /warnaserror:168 (expect failure) exitCode = GetExitCode(source, "c.cs", new[] { "/warnaserror:168" }); Assert.NotEqual(0, exitCode); // The case with /warnaserror:219 (expect success) exitCode = GetExitCode(source, "c.cs", new[] { "/warnaserror:219" }); Assert.Equal(0, exitCode); // The case with /warnaserror and /nowarn:168 (expect success) exitCode = GetExitCode(source, "d.cs", new[] { "/warnaserror", "/nowarn:168" }); Assert.Equal(0, exitCode); } private int GetExitCode(string source, string fileName, string[] commandLineArguments) { var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, commandLineArguments.Concat(new[] { fileName }).ToArray()); int exitCode = csc.Run(outWriter); return exitCode; } [WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")] [ConditionalFact(typeof(WindowsOnly))] public void CompilationWithNonExistingOutPath() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { fileName, "/preferreduilang:en", "/target:exe", "/out:sub\\a.exe" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("error CS2012: Cannot open '" + dir.Path + "\\sub\\a.exe' for writing", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")] [Fact] public void CompilationWithWrongOutPath_01() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { fileName, "/preferreduilang:en", "/target:exe", "/out:sub\\" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); var message = outWriter.ToString(); Assert.Contains("error CS2021: File name", message, StringComparison.Ordinal); Assert.Contains("sub", message, StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")] [Fact] public void CompilationWithWrongOutPath_02() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { fileName, "/preferreduilang:en", "/target:exe", "/out:sub\\ " }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); var message = outWriter.ToString(); Assert.Contains("error CS2021: File name", message, StringComparison.Ordinal); Assert.Contains("sub", message, StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")] [ConditionalFact(typeof(WindowsDesktopOnly))] public void CompilationWithWrongOutPath_03() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { fileName, "/preferreduilang:en", "/target:exe", "/out:aaa:\\a.exe" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains(@"error CS2021: File name 'aaa:\a.exe' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")] [Fact] public void CompilationWithWrongOutPath_04() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { fileName, "/preferreduilang:en", "/target:exe", "/out: " }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("error CS2005: Missing file specification for '/out:' option", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [Fact] public void EmittedSubsystemVersion() { var compilation = CSharpCompilation.Create("a.dll", references: new[] { MscorlibRef }, options: TestOptions.ReleaseDll); var peHeaders = new PEHeaders(compilation.EmitToStream(options: new EmitOptions(subsystemVersion: SubsystemVersion.Create(5, 1)))); Assert.Equal(5, peHeaders.PEHeader.MajorSubsystemVersion); Assert.Equal(1, peHeaders.PEHeader.MinorSubsystemVersion); } [Fact] public void CreateCompilationWithKeyFile() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "a.cs", "/keyfile:key.snk", }); var comp = cmd.CreateCompilation(TextWriter.Null, new TouchedFileLogger(), NullErrorLogger.Instance); Assert.IsType<DesktopStrongNameProvider>(comp.Options.StrongNameProvider); } [Fact] public void CreateCompilationWithKeyContainer() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "a.cs", "/keycontainer:bbb", }); var comp = cmd.CreateCompilation(TextWriter.Null, new TouchedFileLogger(), NullErrorLogger.Instance); Assert.Equal(typeof(DesktopStrongNameProvider), comp.Options.StrongNameProvider.GetType()); } [Fact] public void CreateCompilationFallbackCommand() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "a.cs", "/keyFile:key.snk", "/features:UseLegacyStrongNameProvider" }); var comp = cmd.CreateCompilation(TextWriter.Null, new TouchedFileLogger(), NullErrorLogger.Instance); Assert.Equal(typeof(DesktopStrongNameProvider), comp.Options.StrongNameProvider.GetType()); } [Fact] public void CreateCompilation_MainAndTargetIncompatibilities() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var compilation = CSharpCompilation.Create("a.dll", options: TestOptions.ReleaseDll); var options = compilation.Options; Assert.Equal(0, options.Errors.Length); options = options.WithMainTypeName("a"); options.Errors.Verify( // error CS2017: Cannot specify /main if building a module or library Diagnostic(ErrorCode.ERR_NoMainOnDLL) ); var comp = CSharpCompilation.Create("a.dll", options: options); comp.GetDiagnostics().Verify( // error CS2017: Cannot specify /main if building a module or library Diagnostic(ErrorCode.ERR_NoMainOnDLL) ); options = options.WithOutputKind(OutputKind.WindowsApplication); options.Errors.Verify(); comp = CSharpCompilation.Create("a.dll", options: options); comp.GetDiagnostics().Verify( // error CS1555: Could not find 'a' specified for Main method Diagnostic(ErrorCode.ERR_MainClassNotFound).WithArguments("a") ); options = options.WithOutputKind(OutputKind.NetModule); options.Errors.Verify( // error CS2017: Cannot specify /main if building a module or library Diagnostic(ErrorCode.ERR_NoMainOnDLL) ); comp = CSharpCompilation.Create("a.dll", options: options); comp.GetDiagnostics().Verify( // error CS2017: Cannot specify /main if building a module or library Diagnostic(ErrorCode.ERR_NoMainOnDLL) ); options = options.WithMainTypeName(null); options.Errors.Verify(); comp = CSharpCompilation.Create("a.dll", options: options); comp.GetDiagnostics().Verify(); CleanupAllGeneratedFiles(file.Path); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30328")] public void SpecifyProperCodePage() { byte[] source = { 0x63, // c 0x6c, // l 0x61, // a 0x73, // s 0x73, // s 0x20, // 0xd0, 0x96, // Utf-8 Cyrillic character 0x7b, // { 0x7d, // } }; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllBytes(source); var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, $"/nologo /t:library \"{file}\"", startFolder: dir.Path); Assert.Equal("", output); // Autodetected UTF8, NO ERROR output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, $"/nologo /preferreduilang:en /t:library /codepage:20127 \"{file}\"", expectedRetCode: 1, startFolder: dir.Path); // 20127: US-ASCII // 0xd0, 0x96 ==> ERROR Assert.Equal(@" a.cs(1,7): error CS1001: Identifier expected a.cs(1,7): error CS1514: { expected a.cs(1,7): error CS1513: } expected a.cs(1,7): error CS8803: Top-level statements must precede namespace and type declarations. a.cs(1,7): error CS1525: Invalid expression term '??' a.cs(1,9): error CS1525: Invalid expression term '{' a.cs(1,9): error CS1002: ; expected ".Trim(), Regex.Replace(output, "^.*a.cs", "a.cs", RegexOptions.Multiline).Trim()); CleanupAllGeneratedFiles(file.Path); } [ConditionalFact(typeof(WindowsOnly))] public void DefaultWin32ResForExe() { var source = @" class C { static void Main() { } } "; CheckManifestString(source, OutputKind.ConsoleApplication, explicitManifest: null, expectedManifest: @"<?xml version=""1.0"" encoding=""utf-16""?> <ManifestResource Size=""490""> <Contents><![CDATA[<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0""> <assemblyIdentity version=""1.0.0.0"" name=""MyApplication.app""/> <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2""> <security> <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3""> <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/> </requestedPrivileges> </security> </trustInfo> </assembly>]]></Contents> </ManifestResource>"); } [ConditionalFact(typeof(WindowsOnly))] public void DefaultManifestForDll() { var source = @" class C { } "; CheckManifestString(source, OutputKind.DynamicallyLinkedLibrary, explicitManifest: null, expectedManifest: null); } [ConditionalFact(typeof(WindowsOnly))] public void DefaultManifestForWinExe() { var source = @" class C { static void Main() { } } "; CheckManifestString(source, OutputKind.WindowsApplication, explicitManifest: null, expectedManifest: @"<?xml version=""1.0"" encoding=""utf-16""?> <ManifestResource Size=""490""> <Contents><![CDATA[<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0""> <assemblyIdentity version=""1.0.0.0"" name=""MyApplication.app""/> <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2""> <security> <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3""> <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/> </requestedPrivileges> </security> </trustInfo> </assembly>]]></Contents> </ManifestResource>"); } [ConditionalFact(typeof(WindowsOnly))] public void DefaultManifestForAppContainerExe() { var source = @" class C { static void Main() { } } "; CheckManifestString(source, OutputKind.WindowsRuntimeApplication, explicitManifest: null, expectedManifest: @"<?xml version=""1.0"" encoding=""utf-16""?> <ManifestResource Size=""490""> <Contents><![CDATA[<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0""> <assemblyIdentity version=""1.0.0.0"" name=""MyApplication.app""/> <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2""> <security> <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3""> <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/> </requestedPrivileges> </security> </trustInfo> </assembly>]]></Contents> </ManifestResource>"); } [ConditionalFact(typeof(WindowsOnly))] public void DefaultManifestForWinMD() { var source = @" class C { } "; CheckManifestString(source, OutputKind.WindowsRuntimeMetadata, explicitManifest: null, expectedManifest: null); } [ConditionalFact(typeof(WindowsOnly))] public void DefaultWin32ResForModule() { var source = @" class C { } "; CheckManifestString(source, OutputKind.NetModule, explicitManifest: null, expectedManifest: null); } [ConditionalFact(typeof(WindowsOnly))] public void ExplicitWin32ResForExe() { var source = @" class C { static void Main() { } } "; var explicitManifest = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0""> <assemblyIdentity version=""1.0.0.0"" name=""Test.app""/> <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2""> <security> <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3""> <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/> </requestedPrivileges> </security> </trustInfo> </assembly>"; var explicitManifestStream = new MemoryStream(Encoding.UTF8.GetBytes(explicitManifest)); var expectedManifest = @"<?xml version=""1.0"" encoding=""utf-16""?> <ManifestResource Size=""476""> <Contents><![CDATA[" + explicitManifest + @"]]></Contents> </ManifestResource>"; CheckManifestString(source, OutputKind.ConsoleApplication, explicitManifest, expectedManifest); } // DLLs don't get the default manifest, but they do respect explicitly set manifests. [ConditionalFact(typeof(WindowsOnly))] public void ExplicitWin32ResForDll() { var source = @" class C { static void Main() { } } "; var explicitManifest = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0""> <assemblyIdentity version=""1.0.0.0"" name=""Test.app""/> <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2""> <security> <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3""> <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/> </requestedPrivileges> </security> </trustInfo> </assembly>"; var expectedManifest = @"<?xml version=""1.0"" encoding=""utf-16""?> <ManifestResource Size=""476""> <Contents><![CDATA[" + explicitManifest + @"]]></Contents> </ManifestResource>"; CheckManifestString(source, OutputKind.DynamicallyLinkedLibrary, explicitManifest, expectedManifest); } // Modules don't have manifests, even if one is explicitly specified. [ConditionalFact(typeof(WindowsOnly))] public void ExplicitWin32ResForModule() { var source = @" class C { } "; var explicitManifest = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0""> <assemblyIdentity version=""1.0.0.0"" name=""Test.app""/> <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2""> <security> <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3""> <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/> </requestedPrivileges> </security> </trustInfo> </assembly>"; CheckManifestString(source, OutputKind.NetModule, explicitManifest, expectedManifest: null); } [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr LoadLibraryEx(string lpFileName, IntPtr hFile, uint dwFlags); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool FreeLibrary([In] IntPtr hFile); private void CheckManifestString(string source, OutputKind outputKind, string explicitManifest, string expectedManifest) { var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("Test.cs").WriteAllText(source); string outputFileName; string target; switch (outputKind) { case OutputKind.ConsoleApplication: outputFileName = "Test.exe"; target = "exe"; break; case OutputKind.WindowsApplication: outputFileName = "Test.exe"; target = "winexe"; break; case OutputKind.DynamicallyLinkedLibrary: outputFileName = "Test.dll"; target = "library"; break; case OutputKind.NetModule: outputFileName = "Test.netmodule"; target = "module"; break; case OutputKind.WindowsRuntimeMetadata: outputFileName = "Test.winmdobj"; target = "winmdobj"; break; case OutputKind.WindowsRuntimeApplication: outputFileName = "Test.exe"; target = "appcontainerexe"; break; default: throw TestExceptionUtilities.UnexpectedValue(outputKind); } MockCSharpCompiler csc; if (explicitManifest == null) { csc = CreateCSharpCompiler(null, dir.Path, new[] { string.Format("/target:{0}", target), string.Format("/out:{0}", outputFileName), Path.GetFileName(sourceFile.Path), }); } else { var manifestFile = dir.CreateFile("Test.config").WriteAllText(explicitManifest); csc = CreateCSharpCompiler(null, dir.Path, new[] { string.Format("/target:{0}", target), string.Format("/out:{0}", outputFileName), string.Format("/win32manifest:{0}", Path.GetFileName(manifestFile.Path)), Path.GetFileName(sourceFile.Path), }); } int actualExitCode = csc.Run(new StringWriter(CultureInfo.InvariantCulture)); Assert.Equal(0, actualExitCode); //Open as data IntPtr lib = LoadLibraryEx(Path.Combine(dir.Path, outputFileName), IntPtr.Zero, 0x00000002); if (lib == IntPtr.Zero) throw new Win32Exception(Marshal.GetLastWin32Error()); const string resourceType = "#24"; var resourceId = outputKind == OutputKind.DynamicallyLinkedLibrary ? "#2" : "#1"; uint manifestSize; if (expectedManifest == null) { Assert.Throws<Win32Exception>(() => Win32Res.GetResource(lib, resourceId, resourceType, out manifestSize)); } else { IntPtr manifestResourcePointer = Win32Res.GetResource(lib, resourceId, resourceType, out manifestSize); string actualManifest = Win32Res.ManifestResourceToXml(manifestResourcePointer, manifestSize); Assert.Equal(expectedManifest, actualManifest); } FreeLibrary(lib); } [WorkItem(544926, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544926")] [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void ResponseFilesWithNoconfig_01() { string source = Temp.CreateFile("a.cs").WriteAllText(@" public class C { public static void Main() { int x; // CS0168 } }").Path; string rsp = Temp.CreateFile().WriteAllText(@" /warnaserror ").Path; // Checks the base case without /noconfig (expect to see error) var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("error CS0168: The variable 'x' is declared but never used\r\n", outWriter.ToString(), StringComparison.Ordinal); // Checks the case with /noconfig (expect to see warning, instead of error) outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/noconfig", "/preferreduilang:en" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS0168: The variable 'x' is declared but never used\r\n", outWriter.ToString(), StringComparison.Ordinal); // Checks the case with /NOCONFIG (expect to see warning, instead of error) outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/NOCONFIG", "/preferreduilang:en" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS0168: The variable 'x' is declared but never used\r\n", outWriter.ToString(), StringComparison.Ordinal); // Checks the case with -noconfig (expect to see warning, instead of error) outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "-noconfig", "/preferreduilang:en" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS0168: The variable 'x' is declared but never used\r\n", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [WorkItem(544926, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544926")] [ConditionalFact(typeof(WindowsOnly))] public void ResponseFilesWithNoconfig_02() { string source = Temp.CreateFile("a.cs").WriteAllText(@" public class C { public static void Main() { } }").Path; string rsp = Temp.CreateFile().WriteAllText(@" /noconfig ").Path; // Checks the case with /noconfig inside the response file (expect to see warning) var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal); // Checks the case with /noconfig inside the response file as along with /nowarn (expect to see warning) // to verify that this warning is not suppressed by the /nowarn option (See MSDN). outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en", "/nowarn:2023" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [WorkItem(544926, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544926")] [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void ResponseFilesWithNoconfig_03() { string source = Temp.CreateFile("a.cs").WriteAllText(@" public class C { public static void Main() { } }").Path; string rsp = Temp.CreateFile().WriteAllText(@" /NOCONFIG ").Path; // Checks the case with /noconfig inside the response file (expect to see warning) var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal); // Checks the case with /NOCONFIG inside the response file as along with /nowarn (expect to see warning) // to verify that this warning is not suppressed by the /nowarn option (See MSDN). outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en", "/nowarn:2023" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [WorkItem(544926, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544926")] [ConditionalFact(typeof(WindowsOnly))] public void ResponseFilesWithNoconfig_04() { string source = Temp.CreateFile("a.cs").WriteAllText(@" public class C { public static void Main() { } }").Path; string rsp = Temp.CreateFile().WriteAllText(@" -noconfig ").Path; // Checks the case with /noconfig inside the response file (expect to see warning) var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal); // Checks the case with -noconfig inside the response file as along with /nowarn (expect to see warning) // to verify that this warning is not suppressed by the /nowarn option (See MSDN). outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en", "/nowarn:2023" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [Fact, WorkItem(530024, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530024")] public void NoStdLib() { var src = Temp.CreateFile("a.cs"); src.WriteAllText("public class C{}"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/t:library", src.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/nostdlib", "/t:library", src.ToString() }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("{FILE}(1,14): error CS0518: Predefined type 'System.Object' is not defined or imported", outWriter.ToString().Replace(Path.GetFileName(src.Path), "{FILE}").Trim()); // Bug#15021: breaking change - empty source no error with /nostdlib src.WriteAllText("namespace System { }"); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/nostdlib", "/t:library", "/runtimemetadataversion:v4.0.30319", "/langversion:8", src.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(src.Path); } private string GetDefaultResponseFilePath() { var cscRsp = global::TestResources.ResourceLoader.GetResourceBlob("csc.rsp"); return Temp.CreateFile().WriteAllBytes(cscRsp).Path; } [Fact, WorkItem(530359, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530359")] public void NoStdLib02() { #region "source" var source = @" // <Title>A collection initializer can be declared with a user-defined IEnumerable that is declared in a user-defined System.Collections</Title> using System.Collections; class O<T> where T : new() { public T list = new T(); } class C { static StructCollection sc = new StructCollection { 1 }; public static int Main() { ClassCollection cc = new ClassCollection { 2 }; var o1 = new O<ClassCollection> { list = { 5 } }; var o2 = new O<StructCollection> { list = sc }; return 0; } } struct StructCollection : IEnumerable { public int added; #region IEnumerable Members public void Add(int t) { added = t; } #endregion } class ClassCollection : IEnumerable { public int added; #region IEnumerable Members public void Add(int t) { added = t; } #endregion } namespace System.Collections { public interface IEnumerable { void Add(int t); } } "; #endregion #region "mslib" var mslib = @" namespace System { public class Object {} public struct Byte { } public struct Int16 { } public struct Int32 { } public struct Int64 { } public struct Single { } public struct Double { } public struct SByte { } public struct UInt32 { } public struct UInt64 { } public struct Char { } public struct Boolean { } public struct UInt16 { } public struct UIntPtr { } public struct IntPtr { } public class Delegate { } public class String { public int Length { get { return 10; } } } public class MulticastDelegate { } public class Array { } public class Exception { public Exception(string s){} } public class Type { } public class ValueType { } public class Enum { } public interface IEnumerable { } public interface IDisposable { } public class Attribute { } public class ParamArrayAttribute { } public struct Void { } public struct RuntimeFieldHandle { } public struct RuntimeTypeHandle { } public class Activator { public static T CreateInstance<T>(){return default(T);} } namespace Collections { public interface IEnumerator { } } namespace Runtime { namespace InteropServices { public class OutAttribute { } } namespace CompilerServices { public class RuntimeHelpers { } } } namespace Reflection { public class DefaultMemberAttribute { } } } "; #endregion var src = Temp.CreateFile("NoStdLib02.cs"); src.WriteAllText(source + mslib); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/noconfig", "/nostdlib", "/runtimemetadataversion:v4.0.30319", "/nowarn:8625", src.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/nostdlib", "/runtimemetadataversion:v4.0.30319", "/nowarn:8625", src.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); string OriginalSource = src.Path; src = Temp.CreateFile("NoStdLib02b.cs"); src.WriteAllText(mslib); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(GetDefaultResponseFilePath(), WorkingDirectory, new[] { "/nologo", "/noconfig", "/nostdlib", "/t:library", "/runtimemetadataversion:v4.0.30319", "/nowarn:8625", src.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(OriginalSource); CleanupAllGeneratedFiles(src.Path); } [Fact, WorkItem(546018, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546018"), WorkItem(546020, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546020"), WorkItem(546024, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546024"), WorkItem(546049, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546049")] public void InvalidDefineSwitch() { var src = Temp.CreateFile("a.cs"); src.WriteAllText("public class C{}"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", src.ToString(), "/define" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2006: Command-line syntax error: Missing '<text>' for '/define' option", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), @"/define:""""" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; '' is not a valid identifier", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define: " }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2006: Command-line syntax error: Missing '<text>' for '/define:' option", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define:" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2006: Command-line syntax error: Missing '<text>' for '/define:' option", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define:,,," }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; '' is not a valid identifier", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define:,blah,Blah" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; '' is not a valid identifier", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define:a;;b@" }).Run(outWriter); Assert.Equal(0, exitCode); var errorLines = outWriter.ToString().Trim().Split(new string[] { Environment.NewLine }, StringSplitOptions.None); Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; '' is not a valid identifier", errorLines[0]); Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; 'b@' is not a valid identifier", errorLines[1]); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define:a,b@;" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; 'b@' is not a valid identifier", outWriter.ToString().Trim()); //Bug 531612 - Native would normally not give the 2nd warning outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), @"/define:OE_WIN32=-1:LANG_HOST_EN=-1:LANG_OE_EN=-1:LANG_PRJ_EN=-1:HOST_COM20SDKEVERETT=-1:EXEMODE=-1:OE_NT5=-1:Win32=-1", @"/d:TRACE=TRUE,DEBUG=TRUE" }).Run(outWriter); Assert.Equal(0, exitCode); errorLines = outWriter.ToString().Trim().Split(new string[] { Environment.NewLine }, StringSplitOptions.None); Assert.Equal(@"warning CS2029: Invalid name for a preprocessing symbol; 'OE_WIN32=-1:LANG_HOST_EN=-1:LANG_OE_EN=-1:LANG_PRJ_EN=-1:HOST_COM20SDKEVERETT=-1:EXEMODE=-1:OE_NT5=-1:Win32=-1' is not a valid identifier", errorLines[0]); Assert.Equal(@"warning CS2029: Invalid name for a preprocessing symbol; 'TRACE=TRUE' is not a valid identifier", errorLines[1]); CleanupAllGeneratedFiles(src.Path); } [WorkItem(733242, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/733242")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void Bug733242() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("a.cs"); src.WriteAllText( @" /// <summary>ABC...XYZ</summary> class C {} "); var xml = dir.CreateFile("a.xml"); xml.WriteAllText("EMPTY"); using (var xmlFileHandle = File.Open(xml.ToString(), FileMode.Open, FileAccess.Read, FileShare.Delete | FileShare.ReadWrite)) { var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, String.Format("/nologo /t:library /doc:\"{1}\" \"{0}\"", src.ToString(), xml.ToString()), startFolder: dir.ToString()); Assert.Equal("", output.Trim()); Assert.True(File.Exists(Path.Combine(dir.ToString(), "a.xml"))); using (var reader = new StreamReader(xmlFileHandle)) { var content = reader.ReadToEnd(); Assert.Equal( @"<?xml version=""1.0""?> <doc> <assembly> <name>a</name> </assembly> <members> <member name=""T:C""> <summary>ABC...XYZ</summary> </member> </members> </doc>".Trim(), content.Trim()); } } CleanupAllGeneratedFiles(src.Path); CleanupAllGeneratedFiles(xml.Path); } [WorkItem(768605, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768605")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void Bug768605() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("a.cs"); src.WriteAllText( @" /// <summary>ABC</summary> class C {} /// <summary>XYZ</summary> class E {} "); var xml = dir.CreateFile("a.xml"); xml.WriteAllText("EMPTY"); var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, String.Format("/nologo /t:library /doc:\"{1}\" \"{0}\"", src.ToString(), xml.ToString()), startFolder: dir.ToString()); Assert.Equal("", output.Trim()); using (var reader = new StreamReader(xml.ToString())) { var content = reader.ReadToEnd(); Assert.Equal( @"<?xml version=""1.0""?> <doc> <assembly> <name>a</name> </assembly> <members> <member name=""T:C""> <summary>ABC</summary> </member> <member name=""T:E""> <summary>XYZ</summary> </member> </members> </doc>".Trim(), content.Trim()); } src.WriteAllText( @" /// <summary>ABC</summary> class C {} "); output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, String.Format("/nologo /t:library /doc:\"{1}\" \"{0}\"", src.ToString(), xml.ToString()), startFolder: dir.ToString()); Assert.Equal("", output.Trim()); using (var reader = new StreamReader(xml.ToString())) { var content = reader.ReadToEnd(); Assert.Equal( @"<?xml version=""1.0""?> <doc> <assembly> <name>a</name> </assembly> <members> <member name=""T:C""> <summary>ABC</summary> </member> </members> </doc>".Trim(), content.Trim()); } CleanupAllGeneratedFiles(src.Path); CleanupAllGeneratedFiles(xml.Path); } [Fact] public void ParseFullpaths() { var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.PrintFullPaths); parsedArgs = DefaultParse(new[] { "a.cs", "/fullpaths" }, WorkingDirectory); Assert.True(parsedArgs.PrintFullPaths); parsedArgs = DefaultParse(new[] { "a.cs", "/fullpaths:" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadSwitch, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/fullpaths: " }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadSwitch, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/fullpaths+" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadSwitch, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/fullpaths+:" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadSwitch, parsedArgs.Errors.First().Code); } [Fact] public void CheckFullpaths() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" public class C { public static void Main() { string x; } }").Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); // Checks the base case without /fullpaths (expect to see relative path name) // c:\temp> csc.exe c:\temp\a.cs // a.cs(6,16): warning CS0168: The variable 'x' is declared but never used var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, baseDir, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains(fileName + "(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal); // Checks the base case without /fullpaths when the file is located in the sub-folder (expect to see relative path name) // c:\temp> csc.exe c:\temp\example\a.cs // example\a.cs(6,16): warning CS0168: The variable 'x' is declared but never used outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, Directory.GetParent(baseDir).FullName, new[] { source, "/preferreduilang:en" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains(fileName + "(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal); Assert.DoesNotContain(source, outWriter.ToString(), StringComparison.Ordinal); // Checks the base case without /fullpaths when the file is not located under the base directory (expect to see the full path name) // c:\temp> csc.exe c:\test\a.cs // c:\test\a.cs(6,16): warning CS0168: The variable 'x' is declared but never used outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, Temp.CreateDirectory().Path, new[] { source, "/preferreduilang:en" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains(source + "(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal); // Checks the case with /fullpaths (expect to see the full paths) // c:\temp> csc.exe c:\temp\a.cs /fullpaths // c:\temp\a.cs(6,16): warning CS0168: The variable 'x' is declared but never used outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, baseDir, new[] { source, "/fullpaths", "/preferreduilang:en" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains(source + @"(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal); // Checks the base case without /fullpaths when the file is located in the sub-folder (expect to see the full path name) // c:\temp> csc.exe c:\temp\example\a.cs /fullpaths // c:\temp\example\a.cs(6,16): warning CS0168: The variable 'x' is declared but never used outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, Directory.GetParent(baseDir).FullName, new[] { source, "/preferreduilang:en", "/fullpaths" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains(source + "(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal); // Checks the base case without /fullpaths when the file is not located under the base directory (expect to see the full path name) // c:\temp> csc.exe c:\test\a.cs /fullpaths // c:\test\a.cs(6,16): warning CS0168: The variable 'x' is declared but never used outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, Temp.CreateDirectory().Path, new[] { source, "/preferreduilang:en", "/fullpaths" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains(source + "(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(source)), Path.GetFileName(source))); } [Fact] public void DefaultResponseFile() { var sdkDirectory = SdkDirectory; MockCSharpCompiler csc = new MockCSharpCompiler( GetDefaultResponseFilePath(), RuntimeUtilities.CreateBuildPaths(WorkingDirectory, sdkDirectory), new string[0]); AssertEx.Equal(csc.Arguments.MetadataReferences.Select(r => r.Reference), new string[] { MscorlibFullPath, "Accessibility.dll", "Microsoft.CSharp.dll", "System.Configuration.dll", "System.Configuration.Install.dll", "System.Core.dll", "System.Data.dll", "System.Data.DataSetExtensions.dll", "System.Data.Linq.dll", "System.Data.OracleClient.dll", "System.Deployment.dll", "System.Design.dll", "System.DirectoryServices.dll", "System.dll", "System.Drawing.Design.dll", "System.Drawing.dll", "System.EnterpriseServices.dll", "System.Management.dll", "System.Messaging.dll", "System.Runtime.Remoting.dll", "System.Runtime.Serialization.dll", "System.Runtime.Serialization.Formatters.Soap.dll", "System.Security.dll", "System.ServiceModel.dll", "System.ServiceModel.Web.dll", "System.ServiceProcess.dll", "System.Transactions.dll", "System.Web.dll", "System.Web.Extensions.Design.dll", "System.Web.Extensions.dll", "System.Web.Mobile.dll", "System.Web.RegularExpressions.dll", "System.Web.Services.dll", "System.Windows.Forms.dll", "System.Workflow.Activities.dll", "System.Workflow.ComponentModel.dll", "System.Workflow.Runtime.dll", "System.Xml.dll", "System.Xml.Linq.dll", }, StringComparer.OrdinalIgnoreCase); } [Fact] public void DefaultResponseFileNoConfig() { MockCSharpCompiler csc = CreateCSharpCompiler(GetDefaultResponseFilePath(), WorkingDirectory, new[] { "/noconfig" }); Assert.Equal(csc.Arguments.MetadataReferences.Select(r => r.Reference), new string[] { MscorlibFullPath, }, StringComparer.OrdinalIgnoreCase); } [Fact, WorkItem(545954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545954")] public void TestFilterParseDiagnostics() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" #pragma warning disable 440 using global = A; // CS0440 class A { static void Main() { #pragma warning suppress 440 } }").Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", source.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal(Path.GetFileName(source) + "(7,17): warning CS1634: Expected 'disable' or 'restore'", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/nowarn:1634", source.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", Path.Combine(baseDir, "nonexistent.cs"), source.ToString() }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2001: Source file '" + Path.Combine(baseDir, "nonexistent.cs") + "' could not be found.", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); } [Fact, WorkItem(546058, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546058")] public void TestNoWarnParseDiagnostics() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" class Test { static void Main() { //Generates warning CS1522: Empty switch block switch (1) { } //Generates warning CS0642: Possible mistaken empty statement while (false) ; { } } } ").Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/nowarn:1522,642", source.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); } [Fact, WorkItem(41610, "https://github.com/dotnet/roslyn/issues/41610")] public void TestWarnAsError_CS8632() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" public class C { public string? field; public static void Main() { } } ").Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", "/warn:3", "/warnaserror:nullable", source.ToString() }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal( $@"{fileName}(4,18): error CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); } [Fact, WorkItem(546076, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546076")] public void TestWarnAsError_CS1522() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" public class Test { // CS0169 (level 3) private int x; // CS0109 (level 4) public new void Method() { } public static int Main() { int i = 5; // CS1522 (level 1) switch (i) { } return 0; // CS0162 (level 2) i = 6; } } ").Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", "/warn:3", "/warnaserror", source.ToString() }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal( $@"{fileName}(12,20): error CS1522: Empty switch block {fileName}(15,9): error CS0162: Unreachable code detected {fileName}(5,17): error CS0169: The field 'Test.x' is never used", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); } [Fact(), WorkItem(546025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546025")] public void TestWin32ResWithBadResFile_CS1583ERR_BadWin32Res_01() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"class Test { static void Main() {} }").Path; string badres = Temp.CreateFile().WriteAllBytes(TestResources.DiagnosticTests.badresfile).Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", "/win32res:" + badres, source }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS1583: Error reading Win32 resources -- Image is too small.", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(badres); } [Fact(), WorkItem(217718, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=217718")] public void TestWin32ResWithBadResFile_CS1583ERR_BadWin32Res_02() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"class Test { static void Main() {} }").Path; string badres = Temp.CreateFile().WriteAllBytes(new byte[] { 0, 0 }).Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", "/win32res:" + badres, source }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS1583: Error reading Win32 resources -- Unrecognized resource file format.", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(badres); } [Fact, WorkItem(546114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546114")] public void TestFilterCommandLineDiagnostics() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" class A { static void Main() { } }").Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/target:library", "/out:goo.dll", "/nowarn:2008" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); System.IO.File.Delete(System.IO.Path.Combine(baseDir, "goo.dll")); CleanupAllGeneratedFiles(source); } [Fact, WorkItem(546452, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546452")] public void CS1691WRN_BadWarningNumber_Bug15905() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" class Program { #pragma warning disable 1998 public static void Main() { } #pragma warning restore 1998 } ").Path; var outWriter = new StringWriter(CultureInfo.InvariantCulture); // Repro case 1 int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/warnaserror", source.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); // Repro case 2 exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/nowarn:1998", source.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void ExistingPdb() { var dir = Temp.CreateDirectory(); var source1 = dir.CreateFile("program1.cs").WriteAllText(@" class " + new string('a', 10000) + @" { public static void Main() { } }"); var source2 = dir.CreateFile("program2.cs").WriteAllText(@" class Program2 { public static void Main() { } }"); var source3 = dir.CreateFile("program3.cs").WriteAllText(@" class Program3 { public static void Main() { } }"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int oldSize = 16 * 1024; var exe = dir.CreateFile("Program.exe"); using (var stream = File.OpenWrite(exe.Path)) { byte[] buffer = new byte[oldSize]; stream.Write(buffer, 0, buffer.Length); } var pdb = dir.CreateFile("Program.pdb"); using (var stream = File.OpenWrite(pdb.Path)) { byte[] buffer = new byte[oldSize]; stream.Write(buffer, 0, buffer.Length); } int exitCode1 = CreateCSharpCompiler(null, dir.Path, new[] { "/debug:full", "/out:Program.exe", source1.Path }).Run(outWriter); Assert.NotEqual(0, exitCode1); ValidateZeroes(exe.Path, oldSize); ValidateZeroes(pdb.Path, oldSize); int exitCode2 = CreateCSharpCompiler(null, dir.Path, new[] { "/debug:full", "/out:Program.exe", source2.Path }).Run(outWriter); Assert.Equal(0, exitCode2); using (var peFile = File.OpenRead(exe.Path)) { PdbValidation.ValidateDebugDirectory(peFile, null, pdb.Path, hashAlgorithm: default, hasEmbeddedPdb: false, isDeterministic: false); } Assert.True(new FileInfo(exe.Path).Length < oldSize); Assert.True(new FileInfo(pdb.Path).Length < oldSize); int exitCode3 = CreateCSharpCompiler(null, dir.Path, new[] { "/debug:full", "/out:Program.exe", source3.Path }).Run(outWriter); Assert.Equal(0, exitCode3); using (var peFile = File.OpenRead(exe.Path)) { PdbValidation.ValidateDebugDirectory(peFile, null, pdb.Path, hashAlgorithm: default, hasEmbeddedPdb: false, isDeterministic: false); } } private static void ValidateZeroes(string path, int count) { using (var stream = File.OpenRead(path)) { byte[] buffer = new byte[count]; stream.Read(buffer, 0, buffer.Length); for (int i = 0; i < buffer.Length; i++) { if (buffer[i] != 0) { Assert.True(false); } } } } /// <summary> /// When the output file is open with <see cref="FileShare.Read"/> | <see cref="FileShare.Delete"/> /// the compiler should delete the file to unblock build while allowing the reader to continue /// reading the previous snapshot of the file content. /// /// On Windows we can read the original data directly from the stream without creating a memory map. /// </summary> [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void FileShareDeleteCompatibility_Windows() { var dir = Temp.CreateDirectory(); var libSrc = dir.CreateFile("Lib.cs").WriteAllText("class C { }"); var libDll = dir.CreateFile("Lib.dll").WriteAllText("DLL"); var libPdb = dir.CreateFile("Lib.pdb").WriteAllText("PDB"); var fsDll = new FileStream(libDll.Path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); var fsPdb = new FileStream(libPdb.Path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, dir.Path, new[] { "/target:library", "/debug:full", libSrc.Path }).Run(outWriter); if (exitCode != 0) { AssertEx.AssertEqualToleratingWhitespaceDifferences("", outWriter.ToString()); } Assert.Equal(0, exitCode); AssertEx.Equal(new byte[] { 0x4D, 0x5A }, ReadBytes(libDll.Path, 2)); AssertEx.Equal(new[] { (byte)'D', (byte)'L', (byte)'L' }, ReadBytes(fsDll, 3)); AssertEx.Equal(new byte[] { 0x4D, 0x69 }, ReadBytes(libPdb.Path, 2)); AssertEx.Equal(new[] { (byte)'P', (byte)'D', (byte)'B' }, ReadBytes(fsPdb, 3)); fsDll.Dispose(); fsPdb.Dispose(); AssertEx.Equal(new[] { "Lib.cs", "Lib.dll", "Lib.pdb" }, Directory.GetFiles(dir.Path).Select(p => Path.GetFileName(p)).Order()); } /// <summary> /// On Linux/Mac <see cref="FileShare.Delete"/> on its own doesn't do anything. /// We need to create the actual memory map. This works on Windows as well. /// </summary> [WorkItem(8896, "https://github.com/dotnet/roslyn/issues/8896")] [ConditionalFact(typeof(WindowsDesktopOnly), typeof(IsEnglishLocal), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void FileShareDeleteCompatibility_Xplat() { var bytes = TestResources.MetadataTests.InterfaceAndClass.CSClasses01; var mvid = ReadMvid(new MemoryStream(bytes)); var dir = Temp.CreateDirectory(); var libSrc = dir.CreateFile("Lib.cs").WriteAllText("class C { }"); var libDll = dir.CreateFile("Lib.dll").WriteAllBytes(bytes); var libPdb = dir.CreateFile("Lib.pdb").WriteAllBytes(bytes); var fsDll = new FileStream(libDll.Path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); var fsPdb = new FileStream(libPdb.Path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); var peDll = new PEReader(fsDll); var pePdb = new PEReader(fsPdb); // creates memory map view: var imageDll = peDll.GetEntireImage(); var imagePdb = pePdb.GetEntireImage(); var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, $"/target:library /debug:portable \"{libSrc.Path}\"", startFolder: dir.ToString()); AssertEx.AssertEqualToleratingWhitespaceDifferences($@" Microsoft (R) Visual C# Compiler version {s_compilerVersion} Copyright (C) Microsoft Corporation. All rights reserved.", output); // reading original content from the memory map: Assert.Equal(mvid, ReadMvid(new MemoryStream(imageDll.GetContent().ToArray()))); Assert.Equal(mvid, ReadMvid(new MemoryStream(imagePdb.GetContent().ToArray()))); // reading original content directly from the streams: fsDll.Position = 0; fsPdb.Position = 0; Assert.Equal(mvid, ReadMvid(fsDll)); Assert.Equal(mvid, ReadMvid(fsPdb)); // reading new content from the file: using (var fsNewDll = File.OpenRead(libDll.Path)) { Assert.NotEqual(mvid, ReadMvid(fsNewDll)); } // Portable PDB metadata signature: AssertEx.Equal(new[] { (byte)'B', (byte)'S', (byte)'J', (byte)'B' }, ReadBytes(libPdb.Path, 4)); // dispose PEReaders (they dispose the underlying file streams) peDll.Dispose(); pePdb.Dispose(); AssertEx.Equal(new[] { "Lib.cs", "Lib.dll", "Lib.pdb" }, Directory.GetFiles(dir.Path).Select(p => Path.GetFileName(p)).Order()); // files can be deleted now: File.Delete(libSrc.Path); File.Delete(libDll.Path); File.Delete(libPdb.Path); // directory can be deleted (should be empty): Directory.Delete(dir.Path, recursive: false); } private static Guid ReadMvid(Stream stream) { using (var peReader = new PEReader(stream, PEStreamOptions.LeaveOpen)) { var mdReader = peReader.GetMetadataReader(); return mdReader.GetGuid(mdReader.GetModuleDefinition().Mvid); } } // Seems like File.SetAttributes(libDll.Path, FileAttributes.ReadOnly) doesn't restrict access to the file on Mac (Linux passes). [ConditionalFact(typeof(WindowsOnly)), WorkItem(8939, "https://github.com/dotnet/roslyn/issues/8939")] public void FileShareDeleteCompatibility_ReadOnlyFiles() { var dir = Temp.CreateDirectory(); var libSrc = dir.CreateFile("Lib.cs").WriteAllText("class C { }"); var libDll = dir.CreateFile("Lib.dll").WriteAllText("DLL"); File.SetAttributes(libDll.Path, FileAttributes.ReadOnly); var fsDll = new FileStream(libDll.Path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, dir.Path, new[] { "/target:library", "/preferreduilang:en", libSrc.Path }).Run(outWriter); Assert.Contains($"error CS2012: Cannot open '{libDll.Path}' for writing", outWriter.ToString()); AssertEx.Equal(new[] { (byte)'D', (byte)'L', (byte)'L' }, ReadBytes(libDll.Path, 3)); AssertEx.Equal(new[] { (byte)'D', (byte)'L', (byte)'L' }, ReadBytes(fsDll, 3)); fsDll.Dispose(); AssertEx.Equal(new[] { "Lib.cs", "Lib.dll" }, Directory.GetFiles(dir.Path).Select(p => Path.GetFileName(p)).Order()); } [Fact] public void FileShareDeleteCompatibility_ExistingDirectory() { var dir = Temp.CreateDirectory(); var libSrc = dir.CreateFile("Lib.cs").WriteAllText("class C { }"); var libDll = dir.CreateDirectory("Lib.dll"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, dir.Path, new[] { "/target:library", "/preferreduilang:en", libSrc.Path }).Run(outWriter); Assert.Contains($"error CS2012: Cannot open '{libDll.Path}' for writing", outWriter.ToString()); } private byte[] ReadBytes(Stream stream, int count) { var buffer = new byte[count]; stream.Read(buffer, 0, count); return buffer; } private byte[] ReadBytes(string path, int count) { using (var stream = File.OpenRead(path)) { return ReadBytes(stream, count); } } [Fact] public void IOFailure_DisposeOutputFile() { var srcPath = MakeTrivialExe(Temp.CreateDirectory().Path); var exePath = Path.Combine(Path.GetDirectoryName(srcPath), "test.exe"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", $"/out:{exePath}", srcPath }); csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) => { if (file == exePath) { return new TestStream(backingStream: new MemoryStream(), dispose: () => { throw new IOException("Fake IOException"); }); } return File.Open(file, mode, access, share); }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); Assert.Equal(1, csc.Run(outWriter)); Assert.Contains($"error CS0016: Could not write to output file '{exePath}' -- 'Fake IOException'{Environment.NewLine}", outWriter.ToString()); } [Fact] public void IOFailure_DisposePdbFile() { var srcPath = MakeTrivialExe(Temp.CreateDirectory().Path); var exePath = Path.Combine(Path.GetDirectoryName(srcPath), "test.exe"); var pdbPath = Path.ChangeExtension(exePath, "pdb"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/debug", $"/out:{exePath}", srcPath }); csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) => { if (file == pdbPath) { return new TestStream(backingStream: new MemoryStream(), dispose: () => { throw new IOException("Fake IOException"); }); } return File.Open(file, mode, access, share); }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); Assert.Equal(1, csc.Run(outWriter)); Assert.Contains($"error CS0016: Could not write to output file '{pdbPath}' -- 'Fake IOException'{Environment.NewLine}", outWriter.ToString()); } [Fact] public void IOFailure_DisposeXmlFile() { var srcPath = MakeTrivialExe(Temp.CreateDirectory().Path); var xmlPath = Path.Combine(Path.GetDirectoryName(srcPath), "test.xml"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", $"/doc:{xmlPath}", srcPath }); csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) => { if (file == xmlPath) { return new TestStream(backingStream: new MemoryStream(), dispose: () => { throw new IOException("Fake IOException"); }); } return File.Open(file, mode, access, share); }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); Assert.Equal(1, csc.Run(outWriter)); Assert.Equal($"error CS0016: Could not write to output file '{xmlPath}' -- 'Fake IOException'{Environment.NewLine}", outWriter.ToString()); } [Theory] [InlineData("portable")] [InlineData("full")] public void IOFailure_DisposeSourceLinkFile(string format) { var srcPath = MakeTrivialExe(Temp.CreateDirectory().Path); var sourceLinkPath = Path.Combine(Path.GetDirectoryName(srcPath), "test.json"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/debug:" + format, $"/sourcelink:{sourceLinkPath}", srcPath }); csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) => { if (file == sourceLinkPath) { return new TestStream(backingStream: new MemoryStream(Encoding.UTF8.GetBytes(@" { ""documents"": { ""f:/build/*"" : ""https://raw.githubusercontent.com/my-org/my-project/1111111111111111111111111111111111111111/*"" } } ")), dispose: () => { throw new IOException("Fake IOException"); }); } return File.Open(file, mode, access, share); }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); Assert.Equal(1, csc.Run(outWriter)); Assert.Equal($"error CS0016: Could not write to output file '{sourceLinkPath}' -- 'Fake IOException'{Environment.NewLine}", outWriter.ToString()); } [Fact] public void IOFailure_OpenOutputFile() { string sourcePath = MakeTrivialExe(); string exePath = Path.Combine(Path.GetDirectoryName(sourcePath), "test.exe"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", $"/out:{exePath}", sourcePath }); csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) => { if (file == exePath) { throw new IOException(); } return File.Open(file, mode, access, share); }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); Assert.Equal(1, csc.Run(outWriter)); Assert.Contains($"error CS2012: Cannot open '{exePath}' for writing", outWriter.ToString()); System.IO.File.Delete(sourcePath); System.IO.File.Delete(exePath); CleanupAllGeneratedFiles(sourcePath); } [Fact] public void IOFailure_OpenPdbFileNotCalled() { string sourcePath = MakeTrivialExe(); string exePath = Path.Combine(Path.GetDirectoryName(sourcePath), "test.exe"); string pdbPath = Path.ChangeExtension(exePath, ".pdb"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/debug-", $"/out:{exePath}", sourcePath }); csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) => { if (file == pdbPath) { throw new IOException(); } return File.Open(file, (FileMode)mode, (FileAccess)access, (FileShare)share); }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); Assert.Equal(0, csc.Run(outWriter)); System.IO.File.Delete(sourcePath); System.IO.File.Delete(exePath); System.IO.File.Delete(pdbPath); CleanupAllGeneratedFiles(sourcePath); } [Fact] public void IOFailure_OpenXmlFinal() { string sourcePath = MakeTrivialExe(); string xmlPath = Path.Combine(WorkingDirectory, "Test.xml"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/doc:" + xmlPath, sourcePath }); csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) => { if (file == xmlPath) { throw new IOException(); } else { return File.Open(file, (FileMode)mode, (FileAccess)access, (FileShare)share); } }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = csc.Run(outWriter); var expectedOutput = string.Format("error CS0016: Could not write to output file '{0}' -- 'I/O error occurred.'", xmlPath); Assert.Equal(expectedOutput, outWriter.ToString().Trim()); Assert.NotEqual(0, exitCode); System.IO.File.Delete(xmlPath); System.IO.File.Delete(sourcePath); CleanupAllGeneratedFiles(sourcePath); } private string MakeTrivialExe(string directory = null) { return Temp.CreateFile(directory: directory, prefix: "", extension: ".cs").WriteAllText(@" class Program { public static void Main() { } } ").Path; } [Fact, WorkItem(546452, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546452")] public void CS1691WRN_BadWarningNumber_AllErrorCodes() { const int jump = 200; for (int i = 0; i < 8000; i += (8000 / jump)) { int startErrorCode = (int)i * jump; int endErrorCode = startErrorCode + jump; string source = ComputeSourceText(startErrorCode, endErrorCode); // Previous versions of the compiler used to report a warning (CS1691) // whenever an unrecognized warning code was supplied in a #pragma directive // (or via /nowarn /warnaserror flags on the command line). // Going forward, we won't generate any warning in such cases. This will make // maintenance of backwards compatibility easier (we no longer need to worry // about breaking existing projects / command lines if we deprecate / remove // an old warning code). Test(source, startErrorCode, endErrorCode); } } private static string ComputeSourceText(int startErrorCode, int endErrorCode) { string pragmaDisableWarnings = String.Empty; for (int errorCode = startErrorCode; errorCode < endErrorCode; errorCode++) { string pragmaDisableStr = @"#pragma warning disable " + errorCode.ToString() + @" "; pragmaDisableWarnings += pragmaDisableStr; } return pragmaDisableWarnings + @" public class C { public static void Main() { } }"; } private void Test(string source, int startErrorCode, int endErrorCode) { string sourcePath = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(source).Path; var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", sourcePath }).Run(outWriter); Assert.Equal(0, exitCode); var cscOutput = outWriter.ToString().Trim(); for (int errorCode = startErrorCode; errorCode < endErrorCode; errorCode++) { Assert.True(cscOutput == string.Empty, "Failed at error code: " + errorCode); } CleanupAllGeneratedFiles(sourcePath); } [Fact] public void WriteXml() { var source = @" /// <summary> /// A subtype of <see cref=""object""/>. /// </summary> public class C { } "; var sourcePath = Temp.CreateFile(directory: WorkingDirectory, extension: ".cs").WriteAllText(source).Path; string xmlPath = Path.Combine(WorkingDirectory, "Test.xml"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/target:library", "/out:Test.dll", "/doc:" + xmlPath, sourcePath }); var writer = new StringWriter(CultureInfo.InvariantCulture); var exitCode = csc.Run(writer); if (exitCode != 0) { Console.WriteLine(writer.ToString()); Assert.Equal(0, exitCode); } var bytes = File.ReadAllBytes(xmlPath); var actual = new string(Encoding.UTF8.GetChars(bytes)); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary> A subtype of <see cref=""T:System.Object""/>. </summary> </member> </members> </doc> "; Assert.Equal(expected.Trim(), actual.Trim()); System.IO.File.Delete(xmlPath); System.IO.File.Delete(sourcePath); CleanupAllGeneratedFiles(sourcePath); CleanupAllGeneratedFiles(xmlPath); } [WorkItem(546468, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546468")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void CS2002WRN_FileAlreadyIncluded() { const string cs2002 = @"warning CS2002: Source file '{0}' specified multiple times"; TempDirectory tempParentDir = Temp.CreateDirectory(); TempDirectory tempDir = tempParentDir.CreateDirectory("tmpDir"); TempFile tempFile = tempDir.CreateFile("a.cs").WriteAllText(@"public class A { }"); // Simple case var commandLineArgs = new[] { "a.cs", "a.cs" }; // warning CS2002: Source file 'a.cs' specified multiple times string aWrnString = String.Format(cs2002, "a.cs"); TestCS2002(commandLineArgs, tempDir.Path, 0, aWrnString); // Multiple duplicates commandLineArgs = new[] { "a.cs", "a.cs", "a.cs" }; // warning CS2002: Source file 'a.cs' specified multiple times var warnings = new[] { aWrnString }; TestCS2002(commandLineArgs, tempDir.Path, 0, warnings); // Case-insensitive commandLineArgs = new[] { "a.cs", "A.cs" }; // warning CS2002: Source file 'A.cs' specified multiple times string AWrnString = String.Format(cs2002, "A.cs"); TestCS2002(commandLineArgs, tempDir.Path, 0, AWrnString); // Different extensions tempDir.CreateFile("a.csx"); commandLineArgs = new[] { "a.cs", "a.csx" }; // No errors or warnings TestCS2002(commandLineArgs, tempDir.Path, 0, String.Empty); // Absolute vs Relative commandLineArgs = new[] { @"tmpDir\a.cs", tempFile.Path }; // warning CS2002: Source file 'tmpDir\a.cs' specified multiple times string tmpDiraString = String.Format(cs2002, @"tmpDir\a.cs"); TestCS2002(commandLineArgs, tempParentDir.Path, 0, tmpDiraString); // Both relative commandLineArgs = new[] { @"tmpDir\..\tmpDir\a.cs", @"tmpDir\a.cs" }; // warning CS2002: Source file 'tmpDir\a.cs' specified multiple times TestCS2002(commandLineArgs, tempParentDir.Path, 0, tmpDiraString); // With wild cards commandLineArgs = new[] { tempFile.Path, @"tmpDir\*.cs" }; // warning CS2002: Source file 'tmpDir\a.cs' specified multiple times TestCS2002(commandLineArgs, tempParentDir.Path, 0, tmpDiraString); // "/recurse" scenarios commandLineArgs = new[] { @"/recurse:a.cs", @"tmpDir\a.cs" }; // warning CS2002: Source file 'tmpDir\a.cs' specified multiple times TestCS2002(commandLineArgs, tempParentDir.Path, 0, tmpDiraString); commandLineArgs = new[] { @"/recurse:a.cs", @"/recurse:tmpDir\..\tmpDir\*.cs" }; // warning CS2002: Source file 'tmpDir\a.cs' specified multiple times TestCS2002(commandLineArgs, tempParentDir.Path, 0, tmpDiraString); // Invalid file/path characters const string cs1504 = @"error CS1504: Source file '{0}' could not be opened -- {1}"; commandLineArgs = new[] { "/preferreduilang:en", tempFile.Path, "tmpDir\a.cs" }; // error CS1504: Source file '{0}' could not be opened: Illegal characters in path. var formattedcs1504Str = String.Format(cs1504, PathUtilities.CombineAbsoluteAndRelativePaths(tempParentDir.Path, "tmpDir\a.cs"), "Illegal characters in path."); TestCS2002(commandLineArgs, tempParentDir.Path, 1, formattedcs1504Str); commandLineArgs = new[] { tempFile.Path, @"tmpDi\r*a?.cs" }; var parseDiags = new[] { // error CS2021: File name 'tmpDi\r*a?.cs' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"tmpDi\r*a?.cs"), // error CS2001: Source file 'tmpDi\r*a?.cs' could not be found. Diagnostic(ErrorCode.ERR_FileNotFound).WithArguments(@"tmpDi\r*a?.cs")}; TestCS2002(commandLineArgs, tempParentDir.Path, 1, (string[])null, parseDiags); char currentDrive = Directory.GetCurrentDirectory()[0]; commandLineArgs = new[] { tempFile.Path, currentDrive + @":a.cs" }; parseDiags = new[] { // error CS2021: File name 'e:a.cs' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(currentDrive + @":a.cs")}; TestCS2002(commandLineArgs, tempParentDir.Path, 1, (string[])null, parseDiags); commandLineArgs = new[] { "/preferreduilang:en", tempFile.Path, @":a.cs" }; // error CS1504: Source file '{0}' could not be opened: {1} var formattedcs1504 = String.Format(cs1504, PathUtilities.CombineAbsoluteAndRelativePaths(tempParentDir.Path, @":a.cs"), @"The given path's format is not supported."); TestCS2002(commandLineArgs, tempParentDir.Path, 1, formattedcs1504); CleanupAllGeneratedFiles(tempFile.Path); System.IO.Directory.Delete(tempParentDir.Path, true); } private void TestCS2002(string[] commandLineArgs, string baseDirectory, int expectedExitCode, string compileDiagnostic, params DiagnosticDescription[] parseDiagnostics) { TestCS2002(commandLineArgs, baseDirectory, expectedExitCode, new[] { compileDiagnostic }, parseDiagnostics); } private void TestCS2002(string[] commandLineArgs, string baseDirectory, int expectedExitCode, string[] compileDiagnostics, params DiagnosticDescription[] parseDiagnostics) { var outWriter = new StringWriter(CultureInfo.InvariantCulture); var allCommandLineArgs = new[] { "/nologo", "/preferreduilang:en", "/t:library" }.Concat(commandLineArgs).ToArray(); // Verify command line parser diagnostics. DefaultParse(allCommandLineArgs, baseDirectory).Errors.Verify(parseDiagnostics); // Verify compile. int exitCode = CreateCSharpCompiler(null, baseDirectory, allCommandLineArgs).Run(outWriter); Assert.Equal(expectedExitCode, exitCode); if (parseDiagnostics.IsEmpty()) { // Verify compile diagnostics. string outString = String.Empty; for (int i = 0; i < compileDiagnostics.Length; i++) { if (i != 0) { outString += @" "; } outString += compileDiagnostics[i]; } Assert.Equal(outString, outWriter.ToString().Trim()); } else { Assert.Null(compileDiagnostics); } } [Fact] public void ErrorLineEnd() { var tree = SyntaxFactory.ParseSyntaxTree("class C public { }", path: "goo"); var comp = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/errorendlocation" }); var loc = new SourceLocation(tree.GetCompilationUnitRoot().FindToken(6)); var diag = new CSDiagnostic(new DiagnosticInfo(MessageProvider.Instance, (int)ErrorCode.ERR_MetadataNameTooLong), loc); var text = comp.DiagnosticFormatter.Format(diag); string stringStart = "goo(1,7,1,8)"; Assert.Equal(stringStart, text.Substring(0, stringStart.Length)); } [Fact] public void ReportAnalyzer() { var parsedArgs1 = DefaultParse(new[] { "a.cs", "/reportanalyzer" }, WorkingDirectory); Assert.True(parsedArgs1.ReportAnalyzer); var parsedArgs2 = DefaultParse(new[] { "a.cs", "" }, WorkingDirectory); Assert.False(parsedArgs2.ReportAnalyzer); } [Fact] public void ReportAnalyzerOutput() { var srcFile = Temp.CreateFile().WriteAllText(@"class C {}"); var srcDirectory = Path.GetDirectoryName(srcFile.Path); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, srcDirectory, new[] { "/reportanalyzer", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, srcFile.Path }); var exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var output = outWriter.ToString(); Assert.Contains(CodeAnalysisResources.AnalyzerExecutionTimeColumnHeader, output, StringComparison.Ordinal); Assert.Contains("WarningDiagnosticAnalyzer (Warning01)", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [Fact] [WorkItem(40926, "https://github.com/dotnet/roslyn/issues/40926")] public void SkipAnalyzersParse() { var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.SkipAnalyzers); parsedArgs = DefaultParse(new[] { "/skipanalyzers+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.SkipAnalyzers); parsedArgs = DefaultParse(new[] { "/skipanalyzers", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.SkipAnalyzers); parsedArgs = DefaultParse(new[] { "/SKIPANALYZERS+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.SkipAnalyzers); parsedArgs = DefaultParse(new[] { "/skipanalyzers-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.SkipAnalyzers); parsedArgs = DefaultParse(new[] { "/skipanalyzers-", "/skipanalyzers+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.SkipAnalyzers); parsedArgs = DefaultParse(new[] { "/skipanalyzers", "/skipanalyzers-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.SkipAnalyzers); } [Theory, CombinatorialData] [WorkItem(40926, "https://github.com/dotnet/roslyn/issues/40926")] public void SkipAnalyzersSemantics(bool skipAnalyzers) { var srcFile = Temp.CreateFile().WriteAllText(@"class C {}"); var srcDirectory = Path.GetDirectoryName(srcFile.Path); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var skipAnalyzersFlag = "/skipanalyzers" + (skipAnalyzers ? "+" : "-"); var csc = CreateCSharpCompiler(null, srcDirectory, new[] { skipAnalyzersFlag, "/reportanalyzer", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, srcFile.Path }); var exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var output = outWriter.ToString(); if (skipAnalyzers) { Assert.DoesNotContain(CodeAnalysisResources.AnalyzerExecutionTimeColumnHeader, output, StringComparison.Ordinal); Assert.DoesNotContain(new WarningDiagnosticAnalyzer().ToString(), output, StringComparison.Ordinal); } else { Assert.Contains(CodeAnalysisResources.AnalyzerExecutionTimeColumnHeader, output, StringComparison.Ordinal); Assert.Contains(new WarningDiagnosticAnalyzer().ToString(), output, StringComparison.Ordinal); } CleanupAllGeneratedFiles(srcFile.Path); } [Fact] [WorkItem(24835, "https://github.com/dotnet/roslyn/issues/24835")] public void TestCompilationSuccessIfOnlySuppressedDiagnostics() { var srcFile = Temp.CreateFile().WriteAllText(@" #pragma warning disable Warning01 class C { } "); var errorLog = Temp.CreateFile(); var csc = CreateCSharpCompiler( null, workingDirectory: Path.GetDirectoryName(srcFile.Path), args: new[] { "/errorlog:" + errorLog.Path, "/warnaserror+", "/nologo", "/t:library", srcFile.Path }, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new WarningDiagnosticAnalyzer())); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = csc.Run(outWriter); // Previously, the compiler would return error code 1 without printing any diagnostics Assert.Empty(outWriter.ToString()); Assert.Equal(0, exitCode); CleanupAllGeneratedFiles(srcFile.Path); CleanupAllGeneratedFiles(errorLog.Path); } [Fact] [WorkItem(1759, "https://github.com/dotnet/roslyn/issues/1759")] public void AnalyzerDiagnosticThrowsInGetMessage() { var srcFile = Temp.CreateFile().WriteAllText(@"class C {}"); var srcDirectory = Path.GetDirectoryName(srcFile.Path); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/t:library", srcFile.Path }, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new AnalyzerThatThrowsInGetMessage())); var exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var output = outWriter.ToString(); // Verify that the diagnostic reported by AnalyzerThatThrowsInGetMessage is reported, though it doesn't have the message. Assert.Contains(AnalyzerThatThrowsInGetMessage.Rule.Id, output, StringComparison.Ordinal); // Verify that the analyzer exception diagnostic for the exception throw in AnalyzerThatThrowsInGetMessage is also reported. Assert.Contains(AnalyzerExecutor.AnalyzerExceptionDiagnosticId, output, StringComparison.Ordinal); Assert.Contains(nameof(NotImplementedException), output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [Fact] [WorkItem(3707, "https://github.com/dotnet/roslyn/issues/3707")] public void AnalyzerExceptionDiagnosticCanBeConfigured() { var srcFile = Temp.CreateFile().WriteAllText(@"class C {}"); var srcDirectory = Path.GetDirectoryName(srcFile.Path); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/t:library", $"/warnaserror:{AnalyzerExecutor.AnalyzerExceptionDiagnosticId}", srcFile.Path }, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new AnalyzerThatThrowsInGetMessage())); var exitCode = csc.Run(outWriter); Assert.NotEqual(0, exitCode); var output = outWriter.ToString(); // Verify that the analyzer exception diagnostic for the exception throw in AnalyzerThatThrowsInGetMessage is also reported. Assert.Contains(AnalyzerExecutor.AnalyzerExceptionDiagnosticId, output, StringComparison.Ordinal); Assert.Contains(nameof(NotImplementedException), output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [Fact] [WorkItem(4589, "https://github.com/dotnet/roslyn/issues/4589")] public void AnalyzerReportsMisformattedDiagnostic() { var srcFile = Temp.CreateFile().WriteAllText(@"class C {}"); var srcDirectory = Path.GetDirectoryName(srcFile.Path); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/t:library", srcFile.Path }, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new AnalyzerReportingMisformattedDiagnostic())); var exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var output = outWriter.ToString(); // Verify that the diagnostic reported by AnalyzerReportingMisformattedDiagnostic is reported with the message format string, instead of the formatted message. Assert.Contains(AnalyzerThatThrowsInGetMessage.Rule.Id, output, StringComparison.Ordinal); Assert.Contains(AnalyzerThatThrowsInGetMessage.Rule.MessageFormat.ToString(CultureInfo.InvariantCulture), output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [Fact] public void ErrorPathsFromLineDirectives() { string sampleProgram = @" #line 10 "".."" //relative path using System* "; var syntaxTree = SyntaxFactory.ParseSyntaxTree(sampleProgram, path: "filename.cs"); var comp = CreateCSharpCompiler(null, WorkingDirectory, new string[] { }); var text = comp.DiagnosticFormatter.Format(syntaxTree.GetDiagnostics().First()); //Pull off the last segment of the current directory. var expectedPath = Path.GetDirectoryName(WorkingDirectory); //the end of the diagnostic's "file" portion should be signaled with the '(' of the line/col info. Assert.Equal('(', text[expectedPath.Length]); sampleProgram = @" #line 10 "".>"" //invalid path character using System* "; syntaxTree = SyntaxFactory.ParseSyntaxTree(sampleProgram, path: "filename.cs"); text = comp.DiagnosticFormatter.Format(syntaxTree.GetDiagnostics().First()); Assert.True(text.StartsWith(".>", StringComparison.Ordinal)); sampleProgram = @" #line 10 ""http://goo.bar/baz.aspx"" //URI using System* "; syntaxTree = SyntaxFactory.ParseSyntaxTree(sampleProgram, path: "filename.cs"); text = comp.DiagnosticFormatter.Format(syntaxTree.GetDiagnostics().First()); Assert.True(text.StartsWith("http://goo.bar/baz.aspx", StringComparison.Ordinal)); } [WorkItem(1119609, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1119609")] [Fact] public void PreferredUILang() { var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("CS2006", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("CS2006", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:zz" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("CS2038", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:en-zz" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("CS2038", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:en-US" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.DoesNotContain("CS2038", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:de" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.DoesNotContain("CS2038", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:de-AT" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.DoesNotContain("CS2038", outWriter.ToString(), StringComparison.Ordinal); } [WorkItem(531263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531263")] [Fact] public void EmptyFileName() { var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "" }).Run(outWriter); Assert.NotEqual(0, exitCode); // error CS2021: File name '' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Assert.Contains("CS2021", outWriter.ToString(), StringComparison.Ordinal); } [WorkItem(747219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/747219")] [Fact] public void NoInfoDiagnostics() { string filePath = Temp.CreateFile().WriteAllText(@" using System.Diagnostics; // Unused. ").Path; var cmd = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/target:library", filePath }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(filePath); } [Fact] public void RuntimeMetadataVersion() { var parsedArgs = DefaultParse(new[] { "a.cs", "/runtimemetadataversion" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_SwitchNeedsString, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/runtimemetadataversion:" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_SwitchNeedsString, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/runtimemetadataversion: " }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_SwitchNeedsString, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/runtimemetadataversion:v4.0.30319" }, WorkingDirectory); Assert.Equal(0, parsedArgs.Errors.Length); Assert.Equal("v4.0.30319", parsedArgs.EmitOptions.RuntimeMetadataVersion); parsedArgs = DefaultParse(new[] { "a.cs", "/runtimemetadataversion:-_+@%#*^" }, WorkingDirectory); Assert.Equal(0, parsedArgs.Errors.Length); Assert.Equal("-_+@%#*^", parsedArgs.EmitOptions.RuntimeMetadataVersion); var comp = CreateEmptyCompilation(string.Empty); Assert.Equal("v4.0.30319", ModuleMetadata.CreateFromImage(comp.EmitToArray(new EmitOptions(runtimeMetadataVersion: "v4.0.30319"))).Module.MetadataVersion); comp = CreateEmptyCompilation(string.Empty); Assert.Equal("_+@%#*^", ModuleMetadata.CreateFromImage(comp.EmitToArray(new EmitOptions(runtimeMetadataVersion: "_+@%#*^"))).Module.MetadataVersion); } [WorkItem(715339, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/715339")] [ConditionalFact(typeof(WindowsOnly))] public void WRN_InvalidSearchPathDir() { var baseDir = Temp.CreateDirectory(); var sourceFile = baseDir.CreateFile("Source.cs"); var invalidPath = "::"; var nonExistentPath = "DoesNotExist"; // lib switch DefaultParse(new[] { "/lib:" + invalidPath, sourceFile.Path }, WorkingDirectory).Errors.Verify( // warning CS1668: Invalid search path '::' specified in '/LIB option' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments("::", "/LIB option", "path is too long or invalid")); DefaultParse(new[] { "/lib:" + nonExistentPath, sourceFile.Path }, WorkingDirectory).Errors.Verify( // warning CS1668: Invalid search path 'DoesNotExist' specified in '/LIB option' -- 'directory does not exist' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments("DoesNotExist", "/LIB option", "directory does not exist")); // LIB environment variable DefaultParse(new[] { sourceFile.Path }, WorkingDirectory, additionalReferenceDirectories: invalidPath).Errors.Verify( // warning CS1668: Invalid search path '::' specified in 'LIB environment variable' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments("::", "LIB environment variable", "path is too long or invalid")); DefaultParse(new[] { sourceFile.Path }, WorkingDirectory, additionalReferenceDirectories: nonExistentPath).Errors.Verify( // warning CS1668: Invalid search path 'DoesNotExist' specified in 'LIB environment variable' -- 'directory does not exist' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments("DoesNotExist", "LIB environment variable", "directory does not exist")); CleanupAllGeneratedFiles(sourceFile.Path); } [WorkItem(650083, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/650083")] [InlineData("a.cs /t:library /appconfig:.\\aux.config")] [InlineData("a.cs /out:com1.dll")] [InlineData("a.cs /doc:..\\lpt2.xml")] [InlineData("a.cs /pdb:..\\prn.pdb")] [Theory] public void ReservedDeviceNameAsFileName(string commandLine) { var parsedArgs = DefaultParse(commandLine.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries), WorkingDirectory); if (ExecutionConditionUtil.OperatingSystemRestrictsFileNames) { Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.FTL_InvalidInputFileName, parsedArgs.Errors.First().Code); } else { Assert.Equal(0, parsedArgs.Errors.Length); } } [Fact] public void ReservedDeviceNameAsFileName2() { string filePath = Temp.CreateFile().WriteAllText(@"class C {}").Path; // make sure reserved device names don't var cmd = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/r:com2.dll", "/target:library", "/preferreduilang:en", filePath }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("error CS0006: Metadata file 'com2.dll' could not be found", outWriter.ToString(), StringComparison.Ordinal); cmd = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/link:..\\lpt8.dll", "/target:library", "/preferreduilang:en", filePath }); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = cmd.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("error CS0006: Metadata file '..\\lpt8.dll' could not be found", outWriter.ToString(), StringComparison.Ordinal); cmd = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/lib:aux", "/preferreduilang:en", filePath }); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = cmd.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("warning CS1668: Invalid search path 'aux' specified in '/LIB option' -- 'directory does not exist'", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(filePath); } [Fact] public void ParseFeatures() { var args = DefaultParse(new[] { "/features:Test", "a.vb" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal("Test", args.ParseOptions.Features.Single().Key); args = DefaultParse(new[] { "/features:Test", "a.vb", "/Features:Experiment" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.ParseOptions.Features.Count); Assert.True(args.ParseOptions.Features.ContainsKey("Test")); Assert.True(args.ParseOptions.Features.ContainsKey("Experiment")); args = DefaultParse(new[] { "/features:Test=false,Key=value", "a.vb" }, WorkingDirectory); args.Errors.Verify(); Assert.True(args.ParseOptions.Features.SetEquals(new Dictionary<string, string> { { "Test", "false" }, { "Key", "value" } })); args = DefaultParse(new[] { "/features:Test,", "a.vb" }, WorkingDirectory); args.Errors.Verify(); Assert.True(args.ParseOptions.Features.SetEquals(new Dictionary<string, string> { { "Test", "true" } })); } [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void ParseAdditionalFile() { var args = DefaultParse(new[] { "/additionalfile:web.config", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles.Single().Path); args = DefaultParse(new[] { "/additionalfile:web.config", "a.cs", "/additionalfile:app.manifest" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[0].Path); Assert.Equal(Path.Combine(WorkingDirectory, "app.manifest"), args.AdditionalFiles[1].Path); args = DefaultParse(new[] { "/additionalfile:web.config", "a.cs", "/additionalfile:web.config" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[0].Path); Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[1].Path); args = DefaultParse(new[] { "/additionalfile:..\\web.config", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, "..\\web.config"), args.AdditionalFiles.Single().Path); var baseDir = Temp.CreateDirectory(); baseDir.CreateFile("web1.config"); baseDir.CreateFile("web2.config"); baseDir.CreateFile("web3.config"); args = DefaultParse(new[] { "/additionalfile:web*.config", "a.cs" }, baseDir.Path); args.Errors.Verify(); Assert.Equal(3, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(baseDir.Path, "web1.config"), args.AdditionalFiles[0].Path); Assert.Equal(Path.Combine(baseDir.Path, "web2.config"), args.AdditionalFiles[1].Path); Assert.Equal(Path.Combine(baseDir.Path, "web3.config"), args.AdditionalFiles[2].Path); args = DefaultParse(new[] { "/additionalfile:web.config;app.manifest", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[0].Path); Assert.Equal(Path.Combine(WorkingDirectory, "app.manifest"), args.AdditionalFiles[1].Path); args = DefaultParse(new[] { "/additionalfile:web.config,app.manifest", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[0].Path); Assert.Equal(Path.Combine(WorkingDirectory, "app.manifest"), args.AdditionalFiles[1].Path); args = DefaultParse(new[] { "/additionalfile:web.config,app.manifest", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[0].Path); Assert.Equal(Path.Combine(WorkingDirectory, "app.manifest"), args.AdditionalFiles[1].Path); args = DefaultParse(new[] { @"/additionalfile:""web.config,app.manifest""", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(1, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(WorkingDirectory, "web.config,app.manifest"), args.AdditionalFiles[0].Path); args = DefaultParse(new[] { "/additionalfile:web.config:app.manifest", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(1, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(WorkingDirectory, "web.config:app.manifest"), args.AdditionalFiles[0].Path); args = DefaultParse(new[] { "/additionalfile", "a.cs" }, WorkingDirectory); args.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<file list>", "additionalfile")); Assert.Equal(0, args.AdditionalFiles.Length); args = DefaultParse(new[] { "/additionalfile:", "a.cs" }, WorkingDirectory); args.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<file list>", "additionalfile")); Assert.Equal(0, args.AdditionalFiles.Length); } [Fact] public void ParseEditorConfig() { var args = DefaultParse(new[] { "/analyzerconfig:.editorconfig", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, ".editorconfig"), args.AnalyzerConfigPaths.Single()); args = DefaultParse(new[] { "/analyzerconfig:.editorconfig", "a.cs", "/analyzerconfig:subdir\\.editorconfig" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AnalyzerConfigPaths.Length); Assert.Equal(Path.Combine(WorkingDirectory, ".editorconfig"), args.AnalyzerConfigPaths[0]); Assert.Equal(Path.Combine(WorkingDirectory, "subdir\\.editorconfig"), args.AnalyzerConfigPaths[1]); args = DefaultParse(new[] { "/analyzerconfig:.editorconfig", "a.cs", "/analyzerconfig:.editorconfig" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AnalyzerConfigPaths.Length); Assert.Equal(Path.Combine(WorkingDirectory, ".editorconfig"), args.AnalyzerConfigPaths[0]); Assert.Equal(Path.Combine(WorkingDirectory, ".editorconfig"), args.AnalyzerConfigPaths[1]); args = DefaultParse(new[] { "/analyzerconfig:..\\.editorconfig", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, "..\\.editorconfig"), args.AnalyzerConfigPaths.Single()); args = DefaultParse(new[] { "/analyzerconfig:.editorconfig;subdir\\.editorconfig", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AnalyzerConfigPaths.Length); Assert.Equal(Path.Combine(WorkingDirectory, ".editorconfig"), args.AnalyzerConfigPaths[0]); Assert.Equal(Path.Combine(WorkingDirectory, "subdir\\.editorconfig"), args.AnalyzerConfigPaths[1]); args = DefaultParse(new[] { "/analyzerconfig", "a.cs" }, WorkingDirectory); args.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<file list>' for 'analyzerconfig' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<file list>", "analyzerconfig").WithLocation(1, 1)); Assert.Equal(0, args.AnalyzerConfigPaths.Length); args = DefaultParse(new[] { "/analyzerconfig:", "a.cs" }, WorkingDirectory); args.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<file list>' for 'analyzerconfig' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<file list>", "analyzerconfig").WithLocation(1, 1)); Assert.Equal(0, args.AnalyzerConfigPaths.Length); } [Fact] public void NullablePublicOnly() { string source = @"namespace System.Runtime.CompilerServices { public sealed class NullableAttribute : Attribute { } // missing constructor } public class Program { private object? F = null; }"; string errorMessage = "error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'"; string filePath = Temp.CreateFile().WriteAllText(source).Path; int exitCode; string output; // No /feature (exitCode, output) = compileAndRun(featureOpt: null); Assert.Equal(1, exitCode); Assert.Contains(errorMessage, output, StringComparison.Ordinal); // /features:nullablePublicOnly (exitCode, output) = compileAndRun("/features:nullablePublicOnly"); Assert.Equal(0, exitCode); Assert.DoesNotContain(errorMessage, output, StringComparison.Ordinal); // /features:nullablePublicOnly=true (exitCode, output) = compileAndRun("/features:nullablePublicOnly=true"); Assert.Equal(0, exitCode); Assert.DoesNotContain(errorMessage, output, StringComparison.Ordinal); // /features:nullablePublicOnly=false (the value is ignored) (exitCode, output) = compileAndRun("/features:nullablePublicOnly=false"); Assert.Equal(0, exitCode); Assert.DoesNotContain(errorMessage, output, StringComparison.Ordinal); CleanupAllGeneratedFiles(filePath); (int, string) compileAndRun(string featureOpt) { var args = new[] { "/target:library", "/preferreduilang:en", "/langversion:8", "/nullable+", filePath }; if (featureOpt != null) args = args.Concat(featureOpt).ToArray(); var compiler = CreateCSharpCompiler(null, WorkingDirectory, args); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = compiler.Run(outWriter); return (exitCode, outWriter.ToString()); }; } // See also NullableContextTests.NullableAnalysisFlags_01(). [Fact] public void NullableAnalysisFlags() { string source = @"class Program { #nullable enable static object F1() => null; #nullable disable static object F2() => null; }"; string filePath = Temp.CreateFile().WriteAllText(source).Path; string fileName = Path.GetFileName(filePath); string[] expectedWarningsAll = new[] { fileName + "(4,27): warning CS8603: Possible null reference return." }; string[] expectedWarningsNone = Array.Empty<string>(); AssertEx.Equal(expectedWarningsAll, compileAndRun(featureOpt: null)); AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis")); AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis=always")); AssertEx.Equal(expectedWarningsNone, compileAndRun("/features:run-nullable-analysis=never")); AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis=ALWAYS")); // unrecognized value (incorrect case) ignored AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis=NEVER")); // unrecognized value (incorrect case) ignored AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis=true")); // unrecognized value ignored AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis=false")); // unrecognized value ignored AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis=unknown")); // unrecognized value ignored CleanupAllGeneratedFiles(filePath); string[] compileAndRun(string featureOpt) { var args = new[] { "/target:library", "/preferreduilang:en", "/nologo", filePath }; if (featureOpt != null) args = args.Concat(featureOpt).ToArray(); var compiler = CreateCSharpCompiler(null, WorkingDirectory, args); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = compiler.Run(outWriter); return outWriter.ToString().Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); }; } [Fact] public void Compiler_Uses_DriverCache() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); int sourceCallbackCount = 0; var generator = new PipelineCallbackGenerator((ctx) => { ctx.RegisterSourceOutput(ctx.ParseOptionsProvider, (spc, po) => { sourceCallbackCount++; }); }); // with no cache, we'll see the callback execute multiple times RunWithNoCache(); Assert.Equal(1, sourceCallbackCount); RunWithNoCache(); Assert.Equal(2, sourceCallbackCount); RunWithNoCache(); Assert.Equal(3, sourceCallbackCount); // now re-run with a cache GeneratorDriverCache cache = new GeneratorDriverCache(); sourceCallbackCount = 0; RunWithCache(); Assert.Equal(1, sourceCallbackCount); RunWithCache(); Assert.Equal(1, sourceCallbackCount); RunWithCache(); Assert.Equal(1, sourceCallbackCount); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); void RunWithNoCache() => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview" }, generators: new[] { generator.AsSourceGenerator() }, analyzers: null); void RunWithCache() => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview", "/features:enable-generator-cache" }, generators: new[] { generator.AsSourceGenerator() }, driverCache: cache, analyzers: null); } [Fact] public void Compiler_Doesnt_Use_Cache_From_Other_Compilation() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); int sourceCallbackCount = 0; var generator = new PipelineCallbackGenerator((ctx) => { ctx.RegisterSourceOutput(ctx.ParseOptionsProvider, (spc, po) => { sourceCallbackCount++; }); }); // now re-run with a cache GeneratorDriverCache cache = new GeneratorDriverCache(); sourceCallbackCount = 0; RunWithCache("1.dll"); Assert.Equal(1, sourceCallbackCount); RunWithCache("1.dll"); Assert.Equal(1, sourceCallbackCount); // now emulate a new compilation, and check we were invoked, but only once RunWithCache("2.dll"); Assert.Equal(2, sourceCallbackCount); RunWithCache("2.dll"); Assert.Equal(2, sourceCallbackCount); // now re-run our first compilation RunWithCache("1.dll"); Assert.Equal(2, sourceCallbackCount); // a new one RunWithCache("3.dll"); Assert.Equal(3, sourceCallbackCount); // and another old one RunWithCache("2.dll"); Assert.Equal(3, sourceCallbackCount); RunWithCache("1.dll"); Assert.Equal(3, sourceCallbackCount); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); void RunWithCache(string outputPath) => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview", "/out:" + outputPath, "/features:enable-generator-cache" }, generators: new[] { generator.AsSourceGenerator() }, driverCache: cache, analyzers: null); } [Fact] public void Compiler_Can_Enable_DriverCache() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); int sourceCallbackCount = 0; var generator = new PipelineCallbackGenerator((ctx) => { ctx.RegisterSourceOutput(ctx.ParseOptionsProvider, (spc, po) => { sourceCallbackCount++; }); }); // run with the cache GeneratorDriverCache cache = new GeneratorDriverCache(); sourceCallbackCount = 0; RunWithCache(); Assert.Equal(1, sourceCallbackCount); RunWithCache(); Assert.Equal(1, sourceCallbackCount); RunWithCache(); Assert.Equal(1, sourceCallbackCount); // now re-run with the cache disabled sourceCallbackCount = 0; RunWithCacheDisabled(); Assert.Equal(1, sourceCallbackCount); RunWithCacheDisabled(); Assert.Equal(2, sourceCallbackCount); RunWithCacheDisabled(); Assert.Equal(3, sourceCallbackCount); // now clear the cache as well as disabling, and verify we don't put any entries into it either cache = new GeneratorDriverCache(); sourceCallbackCount = 0; RunWithCacheDisabled(); Assert.Equal(1, sourceCallbackCount); Assert.Equal(0, cache.CacheSize); RunWithCacheDisabled(); Assert.Equal(2, sourceCallbackCount); Assert.Equal(0, cache.CacheSize); RunWithCacheDisabled(); Assert.Equal(3, sourceCallbackCount); Assert.Equal(0, cache.CacheSize); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); void RunWithCache() => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview", "/features:enable-generator-cache" }, generators: new[] { generator.AsSourceGenerator() }, driverCache: cache, analyzers: null); void RunWithCacheDisabled() => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview" }, generators: new[] { generator.AsSourceGenerator() }, driverCache: cache, analyzers: null); } [Fact] public void Adding_Or_Removing_A_Generator_Invalidates_Cache() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); int sourceCallbackCount = 0; int sourceCallbackCount2 = 0; var generator = new PipelineCallbackGenerator((ctx) => { ctx.RegisterSourceOutput(ctx.ParseOptionsProvider, (spc, po) => { sourceCallbackCount++; }); }); var generator2 = new PipelineCallbackGenerator2((ctx) => { ctx.RegisterSourceOutput(ctx.ParseOptionsProvider, (spc, po) => { sourceCallbackCount2++; }); }); // run with the cache GeneratorDriverCache cache = new GeneratorDriverCache(); RunWithOneGenerator(); Assert.Equal(1, sourceCallbackCount); Assert.Equal(0, sourceCallbackCount2); RunWithOneGenerator(); Assert.Equal(1, sourceCallbackCount); Assert.Equal(0, sourceCallbackCount2); RunWithTwoGenerators(); Assert.Equal(2, sourceCallbackCount); Assert.Equal(1, sourceCallbackCount2); RunWithTwoGenerators(); Assert.Equal(2, sourceCallbackCount); Assert.Equal(1, sourceCallbackCount2); // this seems counterintuitive, but when the only thing to change is the generator, we end up back at the state of the project when // we just ran a single generator. Thus we already have an entry in the cache we can use (the one created by the original call to // RunWithOneGenerator above) meaning we can use the previously cached results and not run. RunWithOneGenerator(); Assert.Equal(2, sourceCallbackCount); Assert.Equal(1, sourceCallbackCount2); void RunWithOneGenerator() => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview", "/features:enable-generator-cache" }, generators: new[] { generator.AsSourceGenerator() }, driverCache: cache, analyzers: null); void RunWithTwoGenerators() => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview", "/features:enable-generator-cache" }, generators: new[] { generator.AsSourceGenerator(), generator2.AsSourceGenerator() }, driverCache: cache, analyzers: null); } [Fact] public void Compiler_Updates_Cached_Driver_AdditionalTexts() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText("class C { }"); var additionalFile = dir.CreateFile("additionalFile.txt").WriteAllText("some text"); int sourceCallbackCount = 0; int additionalFileCallbackCount = 0; var generator = new PipelineCallbackGenerator((ctx) => { ctx.RegisterSourceOutput(ctx.ParseOptionsProvider, (spc, po) => { sourceCallbackCount++; }); ctx.RegisterSourceOutput(ctx.AdditionalTextsProvider, (spc, po) => { additionalFileCallbackCount++; }); }); GeneratorDriverCache cache = new GeneratorDriverCache(); RunWithCache(); Assert.Equal(1, sourceCallbackCount); Assert.Equal(1, additionalFileCallbackCount); RunWithCache(); Assert.Equal(1, sourceCallbackCount); Assert.Equal(1, additionalFileCallbackCount); additionalFile.WriteAllText("some new content"); RunWithCache(); Assert.Equal(1, sourceCallbackCount); Assert.Equal(2, additionalFileCallbackCount); // additional file was updated // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); void RunWithCache() => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview", "/features:enable-generator-cache", "/additionalFile:" + additionalFile.Path }, generators: new[] { generator.AsSourceGenerator() }, driverCache: cache, analyzers: null); } [Fact] public void Compiler_DoesNotCache_Driver_ConfigProvider() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText("class C { }"); var editorconfig = dir.CreateFile(".editorconfig").WriteAllText(@" [temp.cs] a = localA "); var globalconfig = dir.CreateFile(".globalconfig").WriteAllText(@" is_global = true a = globalA"); int sourceCallbackCount = 0; int configOptionsCallbackCount = 0; int filteredGlobalCallbackCount = 0; int filteredLocalCallbackCount = 0; string globalA = ""; string localA = ""; var generator = new PipelineCallbackGenerator((ctx) => { ctx.RegisterSourceOutput(ctx.ParseOptionsProvider, (spc, po) => { sourceCallbackCount++; }); ctx.RegisterSourceOutput(ctx.AnalyzerConfigOptionsProvider, (spc, po) => { configOptionsCallbackCount++; po.GlobalOptions.TryGetValue("a", out globalA); }); ctx.RegisterSourceOutput(ctx.AnalyzerConfigOptionsProvider.Select((p, _) => { p.GlobalOptions.TryGetValue("a", out var value); return value; }), (spc, value) => { filteredGlobalCallbackCount++; globalA = value; }); var syntaxTreeInput = ctx.CompilationProvider.Select((c, _) => c.SyntaxTrees.First()); ctx.RegisterSourceOutput(ctx.AnalyzerConfigOptionsProvider.Combine(syntaxTreeInput).Select((p, _) => { p.Left.GetOptions(p.Right).TryGetValue("a", out var value); return value; }), (spc, value) => { filteredLocalCallbackCount++; localA = value; }); }); GeneratorDriverCache cache = new GeneratorDriverCache(); RunWithCache(); Assert.Equal(1, sourceCallbackCount); Assert.Equal(1, configOptionsCallbackCount); Assert.Equal(1, filteredGlobalCallbackCount); Assert.Equal(1, filteredLocalCallbackCount); Assert.Equal("globalA", globalA); Assert.Equal("localA", localA); RunWithCache(); Assert.Equal(1, sourceCallbackCount); Assert.Equal(2, configOptionsCallbackCount); // we can't compare the provider directly, so we consider it modified Assert.Equal(1, filteredGlobalCallbackCount); // however, the values in it will cache out correctly. Assert.Equal(1, filteredLocalCallbackCount); editorconfig.WriteAllText(@" [temp.cs] a = diffLocalA "); RunWithCache(); Assert.Equal(1, sourceCallbackCount); Assert.Equal(3, configOptionsCallbackCount); Assert.Equal(1, filteredGlobalCallbackCount); // the provider changed, but only the local value changed Assert.Equal(2, filteredLocalCallbackCount); Assert.Equal("globalA", globalA); Assert.Equal("diffLocalA", localA); globalconfig.WriteAllText(@" is_global = true a = diffGlobalA "); RunWithCache(); Assert.Equal(1, sourceCallbackCount); Assert.Equal(4, configOptionsCallbackCount); Assert.Equal(2, filteredGlobalCallbackCount); // only the global value was changed Assert.Equal(2, filteredLocalCallbackCount); Assert.Equal("diffGlobalA", globalA); Assert.Equal("diffLocalA", localA); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); void RunWithCache() => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview", "/features:enable-generator-cache", "/analyzerConfig:" + editorconfig.Path, "/analyzerConfig:" + globalconfig.Path }, generators: new[] { generator.AsSourceGenerator() }, driverCache: cache, analyzers: null); } [Fact] public void Compiler_DoesNotCache_Compilation() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); int sourceCallbackCount = 0; var generator = new PipelineCallbackGenerator((ctx) => { ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, po) => { sourceCallbackCount++; }); }); // now re-run with a cache GeneratorDriverCache cache = new GeneratorDriverCache(); RunWithCache(); Assert.Equal(1, sourceCallbackCount); RunWithCache(); Assert.Equal(2, sourceCallbackCount); RunWithCache(); Assert.Equal(3, sourceCallbackCount); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); void RunWithCache() => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview", "/features:enable-generator-cache" }, generators: new[] { generator.AsSourceGenerator() }, driverCache: cache, analyzers: null); } private static int OccurrenceCount(string source, string word) { var n = 0; var index = source.IndexOf(word, StringComparison.Ordinal); while (index >= 0) { ++n; index = source.IndexOf(word, index + word.Length, StringComparison.Ordinal); } return n; } private string VerifyOutput(TempDirectory sourceDir, TempFile sourceFile, bool includeCurrentAssemblyAsAnalyzerReference = true, string[] additionalFlags = null, int expectedInfoCount = 0, int expectedWarningCount = 0, int expectedErrorCount = 0, int? expectedExitCode = null, bool errorlog = false, bool skipAnalyzers = false, IEnumerable<ISourceGenerator> generators = null, GeneratorDriverCache driverCache = null, params DiagnosticAnalyzer[] analyzers) { var args = new[] { "/nologo", "/preferreduilang:en", "/t:library", sourceFile.Path }; if (includeCurrentAssemblyAsAnalyzerReference) { args = args.Append("/a:" + Assembly.GetExecutingAssembly().Location); } if (errorlog) { args = args.Append("/errorlog:errorlog"); } if (skipAnalyzers) { args = args.Append("/skipAnalyzers"); } if (additionalFlags != null) { args = args.Append(additionalFlags); } var csc = CreateCSharpCompiler(null, sourceDir.Path, args, analyzers: analyzers.ToImmutableArrayOrEmpty(), generators: generators.ToImmutableArrayOrEmpty(), driverCache: driverCache); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = csc.Run(outWriter); var output = outWriter.ToString(); expectedExitCode ??= expectedErrorCount > 0 ? 1 : 0; Assert.True( expectedExitCode == exitCode, string.Format("Expected exit code to be '{0}' was '{1}'.{2} Output:{3}{4}", expectedExitCode, exitCode, Environment.NewLine, Environment.NewLine, output)); Assert.DoesNotContain("hidden", output, StringComparison.Ordinal); if (expectedInfoCount == 0) { Assert.DoesNotContain("info", output, StringComparison.Ordinal); } else { // Info diagnostics are only logged with /errorlog. Assert.True(errorlog); Assert.Equal(expectedInfoCount, OccurrenceCount(output, "info")); } if (expectedWarningCount == 0) { Assert.DoesNotContain("warning", output, StringComparison.Ordinal); } else { Assert.Equal(expectedWarningCount, OccurrenceCount(output, "warning")); } if (expectedErrorCount == 0) { Assert.DoesNotContain("error", output, StringComparison.Ordinal); } else { Assert.Equal(expectedErrorCount, OccurrenceCount(output, "error")); } return output; } [WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")] [Fact] public void NoWarnAndWarnAsError_AnalyzerDriverWarnings() { // This assembly has an abstract MockAbstractDiagnosticAnalyzer type which should cause // compiler warning CS8032 to be produced when compilations created in this test try to load it. string source = @"using System;"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var output = VerifyOutput(dir, file, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that compiler warning CS8032 can be suppressed via /warn:0. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that compiler warning CS8032 can be individually suppressed via /nowarn:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:CS8032" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that compiler warning CS8032 can be promoted to an error via /warnaserror. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that compiler warning CS8032 can be individually promoted to an error via /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:8032" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")] [WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")] [WorkItem(1021115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1021115")] [Fact] public void NoWarnAndWarnAsError_HiddenDiagnostic() { // This assembly has a HiddenDiagnosticAnalyzer type which should produce custom hidden // diagnostics for #region directives present in the compilations created in this test. var source = @"using System; #region Region #endregion"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var output = VerifyOutput(dir, file, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /warn:0 has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that /nowarn: has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /warnaserror+ has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/nowarn:8032" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that /warnaserror- has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /warnaserror: promotes custom hidden diagnostic Hidden01 to an error. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Hidden01" }, expectedWarningCount: 1, expectedErrorCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Hidden01: Throwing a diagnostic for #region", output, StringComparison.Ordinal); // TEST: Verify that /warnaserror-: has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify /nowarn: overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Hidden01", "/nowarn:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify /nowarn: overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Hidden01", "/warnaserror:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify /nowarn: overrides /warnaserror-:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Hidden01", "/nowarn:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify /nowarn: overrides /warnaserror-:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Hidden01", "/warnaserror-:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /warn:0 has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0", "/warnaserror:Hidden01" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that /warn:0 has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Hidden01", "/warn:0" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:Hidden01", "/warnaserror-:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Hidden01", "/warnaserror+:Hidden01" }, expectedWarningCount: 1, expectedErrorCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Hidden01: Throwing a diagnostic for #region", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warnaserror+:Hidden01" }, expectedWarningCount: 1, expectedErrorCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Hidden01: Throwing a diagnostic for #region", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Hidden01", "/warnaserror+" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/warnaserror+:Hidden01", "/nowarn:8032" }, expectedErrorCount: 1); Assert.Contains("a.cs(2,1): error Hidden01: Throwing a diagnostic for #region", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:Hidden01", "/warnaserror+", "/nowarn:8032" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:Hidden01", "/warnaserror-" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/warnaserror-:Hidden01", "/nowarn:8032" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Hidden01", "/warnaserror-" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warnaserror-:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")] [WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")] [WorkItem(1021115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1021115")] [WorkItem(42166, "https://github.com/dotnet/roslyn/issues/42166")] [CombinatorialData, Theory] public void NoWarnAndWarnAsError_InfoDiagnostic(bool errorlog) { // NOTE: Info diagnostics are only logged on command line when /errorlog is specified. See https://github.com/dotnet/roslyn/issues/42166 for details. // This assembly has an InfoDiagnosticAnalyzer type which should produce custom info // diagnostics for the #pragma warning restore directives present in the compilations created in this test. var source = @"using System; #pragma warning restore"; var name = "a.cs"; string output; output = GetOutput(name, source, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that /warn:0 suppresses custom info diagnostic Info01. output = GetOutput(name, source, additionalFlags: new[] { "/warn:0" }, errorlog: errorlog); // TEST: Verify that custom info diagnostic Info01 can be individually suppressed via /nowarn:. output = GetOutput(name, source, additionalFlags: new[] { "/nowarn:Info01" }, expectedWarningCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that custom info diagnostic Info01 can never be promoted to an error via /warnaserror+. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+", "/nowarn:8032" }, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that custom info diagnostic Info01 is still reported as an info when /warnaserror- is used. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-" }, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that custom info diagnostic Info01 can be individually promoted to an error via /warnaserror:. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror:Info01" }, expectedWarningCount: 1, expectedErrorCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that custom info diagnostic Info01 is still reported as an info when passed to /warnaserror-:. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-:Info01" }, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify /nowarn overrides /warnaserror. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror:Info01", "/nowarn:Info01" }, expectedWarningCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify /nowarn overrides /warnaserror. output = GetOutput(name, source, additionalFlags: new[] { "/nowarn:Info01", "/warnaserror:Info01" }, expectedWarningCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify /nowarn overrides /warnaserror-. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-:Info01", "/nowarn:Info01" }, expectedWarningCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify /nowarn overrides /warnaserror-. output = GetOutput(name, source, additionalFlags: new[] { "/nowarn:Info01", "/warnaserror-:Info01" }, expectedWarningCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /warn:0 has no impact on custom info diagnostic Info01. output = GetOutput(name, source, additionalFlags: new[] { "/warn:0", "/warnaserror:Info01" }, errorlog: errorlog); // TEST: Verify that /warn:0 has no impact on custom info diagnostic Info01. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror:Info01", "/warn:0" }); // TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+:Info01", "/warnaserror-:Info01" }, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-:Info01", "/warnaserror+:Info01" }, expectedWarningCount: 1, expectedErrorCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-", "/warnaserror+:Info01" }, expectedWarningCount: 1, expectedErrorCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-:Info01", "/warnaserror+", "/nowarn:8032" }, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+:Info01", "/warnaserror+", "/nowarn:8032" }, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+", "/warnaserror+:Info01", "/nowarn:8032" }, expectedErrorCount: 1, errorlog: errorlog); Assert.Contains("a.cs(2,1): error Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+:Info01", "/warnaserror-" }, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+", "/warnaserror-:Info01", "/nowarn:8032" }, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-:Info01", "/warnaserror-" }, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-", "/warnaserror-:Info01" }, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); } private string GetOutput( string name, string source, bool includeCurrentAssemblyAsAnalyzerReference = true, string[] additionalFlags = null, int expectedInfoCount = 0, int expectedWarningCount = 0, int expectedErrorCount = 0, bool errorlog = false) { var dir = Temp.CreateDirectory(); var file = dir.CreateFile(name); file.WriteAllText(source); var output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference, additionalFlags, expectedInfoCount, expectedWarningCount, expectedErrorCount, null, errorlog); CleanupAllGeneratedFiles(file.Path); return output; } [WorkItem(11368, "https://github.com/dotnet/roslyn/issues/11368")] [WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")] [WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")] [WorkItem(998069, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/998069")] [WorkItem(998724, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/998724")] [WorkItem(1021115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1021115")] [Fact] public void NoWarnAndWarnAsError_WarningDiagnostic() { // This assembly has a WarningDiagnosticAnalyzer type which should produce custom warning // diagnostics for source types present in the compilations created in this test. string source = @" class C { static void Main() { int i; } } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var output = VerifyOutput(dir, file, expectedWarningCount: 3); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); // TEST: Verify that compiler warning CS0168 as well as custom warning diagnostic Warning01 can be suppressed via /warn:0. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that compiler warning CS0168 as well as custom warning diagnostic Warning01 can be individually suppressed via /nowarn:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:0168,Warning01,58000" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that diagnostic ids are processed in case-sensitive fashion inside /nowarn:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:cs0168,warning01,700000" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that compiler warning CS0168 as well as custom warning diagnostic Warning01 can be promoted to errors via /warnaserror. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror", "/nowarn:8032" }, expectedErrorCount: 2); Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): error CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); // TEST: Verify that compiler warning CS0168 as well as custom warning diagnostic Warning01 can be promoted to errors via /warnaserror+. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/nowarn:8032" }, expectedErrorCount: 2); Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): error CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); // TEST: Verify that /warnaserror- keeps compiler warning CS0168 as well as custom warning diagnostic Warning01 as warnings. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that custom warning diagnostic Warning01 can be individually promoted to an error via /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Something,Warning01" }, expectedWarningCount: 2, expectedErrorCount: 1); Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that compiler warning CS0168 can be individually promoted to an error via /warnaserror+:. // This doesn't work correctly currently - promoting compiler warning CS0168 to an error causes us to no longer report any custom warning diagnostics as errors (Bug 998069). output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:CS0168" }, expectedWarningCount: 2, expectedErrorCount: 1); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): error CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that diagnostic ids are processed in case-sensitive fashion inside /warnaserror. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:cs0168,warning01,58000" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that custom warning diagnostic Warning01 as well as compiler warning CS0168 can be promoted to errors via /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:CS0168,Warning01" }, expectedWarningCount: 1, expectedErrorCount: 2); Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): error CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /warn:0 overrides /warnaserror+. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0", "/warnaserror+" }); // TEST: Verify that /warn:0 overrides /warnaserror. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror", "/warn:0" }); // TEST: Verify that /warn:0 overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warn:0" }); // TEST: Verify that /warn:0 overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0", "/warnaserror-" }); // TEST: Verify that /nowarn: overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Something,CS0168,Warning01", "/nowarn:0168,Warning01,58000" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:0168,Warning01,58000", "/warnaserror:Something,CS0168,Warning01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror-:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Something,CS0168,Warning01", "/nowarn:0168,Warning01,58000" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror-:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:0168,Warning01,58000", "/warnaserror-:Something,CS0168,Warning01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror+. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/nowarn:0168,Warning01,58000,8032" }); // TEST: Verify that /nowarn: overrides /warnaserror+. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:0168,Warning01,58000,8032", "/warnaserror+" }); // TEST: Verify that /nowarn: overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/nowarn:0168,Warning01,58000,8032" }); // TEST: Verify that /nowarn: overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:0168,Warning01,58000,8032", "/warnaserror-" }); // TEST: Verify that /warn:0 overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Something,CS0168,Warning01", "/warn:0" }); // TEST: Verify that /warn:0 overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0", "/warnaserror:Something,CS0168,Warning01" }); // TEST: Verify that last /warnaserror[+/-] flag on command line wins. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warnaserror+" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that last /warnaserror[+/-] flag on command line wins. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror", "/warnaserror-" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Warning01", "/warnaserror+:Warning01" }, expectedWarningCount: 2, expectedErrorCount: 1); Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:Warning01", "/warnaserror-:Warning01" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Warning01,CS0168,58000,8032", "/warnaserror+" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror", "/warnaserror-:Warning01,CS0168,58000,8032" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Warning01,58000,8032", "/warnaserror-" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warnaserror+:Warning01" }, expectedWarningCount: 2, expectedErrorCount: 1); Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Warning01,CS0168,58000", "/warnaserror+" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror", "/warnaserror+:Warning01,CS0168,58000" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Warning01,58000,8032", "/warnaserror-" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warnaserror-:Warning01,58000,8032" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")] [WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")] [Fact] public void NoWarnAndWarnAsError_ErrorDiagnostic() { // This assembly has an ErrorDiagnosticAnalyzer type which should produce custom error // diagnostics for #pragma warning disable directives present in the compilations created in this test. string source = @"using System; #pragma warning disable"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var output = VerifyOutput(dir, file, expectedErrorCount: 1, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal); // TEST: Verify that custom error diagnostic Error01 can't be suppressed via /warn:0. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0" }, expectedErrorCount: 1); Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal); // TEST: Verify that custom error diagnostic Error01 can be suppressed via /nowarn:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Error01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror+. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/nowarn:Error01" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Error01", "/warnaserror" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror+:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Error01", "/warnaserror+:Error01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Error01", "/nowarn:Error01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/nowarn:Error01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Error01", "/warnaserror-" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Error01", "/nowarn:Error01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Error01", "/warnaserror-:Error01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that nothing bad happens when using /warnaserror[+/-] when custom error diagnostic Error01 is present. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-" }, expectedErrorCount: 1, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal); // TEST: Verify that nothing bad happens if someone passes custom error diagnostic Error01 to /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Error01" }, expectedErrorCount: 1, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:Error01" }, expectedErrorCount: 1, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Error01" }, expectedErrorCount: 1, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [Fact] [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] public void ConsistentErrorMessageWhenProvidingNoKeyFile() { var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/keyfile:", "/target:library", "/nologo", "/preferreduilang:en", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2005: Missing file specification for 'keyfile' option", outWriter.ToString().Trim()); } [Fact] [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] public void ConsistentErrorMessageWhenProvidingEmptyKeyFile() { var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/keyfile:\"\"", "/target:library", "/nologo", "/preferreduilang:en", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2005: Missing file specification for 'keyfile' option", outWriter.ToString().Trim()); } [Fact] [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] public void ConsistentErrorMessageWhenProvidingNoKeyFile_PublicSign() { var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/keyfile:", "/publicsign", "/target:library", "/nologo", "/preferreduilang:en", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2005: Missing file specification for 'keyfile' option", outWriter.ToString().Trim()); } [Fact] [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] public void ConsistentErrorMessageWhenProvidingEmptyKeyFile_PublicSign() { var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/keyfile:\"\"", "/publicsign", "/target:library", "/nologo", "/preferreduilang:en", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2005: Missing file specification for 'keyfile' option", outWriter.ToString().Trim()); } [WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")] [Fact] public void NoWarnAndWarnAsError_CompilerErrorDiagnostic() { string source = @"using System; class C { static void Main() { int i = new Exception(); } }"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); // TEST: Verify that compiler error CS0029 can't be suppressed via /warn:0. output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warn:0" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); // TEST: Verify that compiler error CS0029 can't be suppressed via /nowarn:. output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/nowarn:29" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/nowarn:CS0029" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); // TEST: Verify that nothing bad happens when using /warnaserror[+/-] when compiler error CS0029 is present. output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror+" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror-" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); // TEST: Verify that nothing bad happens if someone passes compiler error CS0029 to /warnaserror[+/-]:. output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror:0029" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror+:CS0029" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror-:29" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror-:CS0029" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(1021115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1021115")] [Fact] public void WarnAsError_LastOneWins1() { var arguments = DefaultParse(new[] { "/warnaserror-:3001", "/warnaserror" }, null); var options = arguments.CompilationOptions; var comp = CreateCompilation(@"[assembly: System.CLSCompliant(true)] public class C { public void M(ushort i) { } public static void Main(string[] args) {} }", options: options); comp.VerifyDiagnostics( // (4,26): warning CS3001: Argument type 'ushort' is not CLS-compliant // public void M(ushort i) Diagnostic(ErrorCode.WRN_CLS_BadArgType, "i") .WithArguments("ushort") .WithLocation(4, 26) .WithWarningAsError(true)); } [WorkItem(1021115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1021115")] [Fact] public void WarnAsError_LastOneWins2() { var arguments = DefaultParse(new[] { "/warnaserror", "/warnaserror-:3001" }, null); var options = arguments.CompilationOptions; var comp = CreateCompilation(@"[assembly: System.CLSCompliant(true)] public class C { public void M(ushort i) { } public static void Main(string[] args) {} }", options: options); comp.VerifyDiagnostics( // (4,26): warning CS3001: Argument type 'ushort' is not CLS-compliant // public void M(ushort i) Diagnostic(ErrorCode.WRN_CLS_BadArgType, "i") .WithArguments("ushort") .WithLocation(4, 26) .WithWarningAsError(false)); } [WorkItem(1091972, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1091972")] [WorkItem(444, "CodePlex")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void Bug1091972() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("a.cs"); src.WriteAllText( @" /// <summary>ABC...XYZ</summary> class C { static void Main() { var textStreamReader = new System.IO.StreamReader(typeof(C).Assembly.GetManifestResourceStream(""doc.xml"")); System.Console.WriteLine(textStreamReader.ReadToEnd()); } } "); var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, String.Format("/nologo /doc:doc.xml /out:out.exe /resource:doc.xml \"{0}\"", src.ToString()), startFolder: dir.ToString()); Assert.Equal("", output.Trim()); Assert.True(File.Exists(Path.Combine(dir.ToString(), "doc.xml"))); var expected = @"<?xml version=""1.0""?> <doc> <assembly> <name>out</name> </assembly> <members> <member name=""T:C""> <summary>ABC...XYZ</summary> </member> </members> </doc>".Trim(); using (var reader = new StreamReader(Path.Combine(dir.ToString(), "doc.xml"))) { var content = reader.ReadToEnd(); Assert.Equal(expected, content.Trim()); } output = ProcessUtilities.RunAndGetOutput(Path.Combine(dir.ToString(), "out.exe"), startFolder: dir.ToString()); Assert.Equal(expected, output.Trim()); CleanupAllGeneratedFiles(src.Path); } [ConditionalFact(typeof(WindowsOnly))] public void CommandLineMisc() { CSharpCommandLineArguments args = null; string baseDirectory = @"c:\test"; Func<string, CSharpCommandLineArguments> parse = (x) => FullParse(x, baseDirectory); args = parse(@"/out:""a.exe"""); Assert.Equal(@"a.exe", args.OutputFileName); args = parse(@"/pdb:""a.pdb"""); Assert.Equal(Path.Combine(baseDirectory, @"a.pdb"), args.PdbPath); // The \ here causes " to be treated as a quote, not as an escaping construct args = parse(@"a\""b c""\d.cs"); Assert.Equal( new[] { @"c:\test\a""b", @"c:\test\c\d.cs" }, args.SourceFiles.Select(x => x.Path)); args = parse(@"a\\""b c""\d.cs"); Assert.Equal( new[] { @"c:\test\a\b c\d.cs" }, args.SourceFiles.Select(x => x.Path)); args = parse(@"/nostdlib /r:""a.dll"",""b.dll"" c.cs"); Assert.Equal( new[] { @"a.dll", @"b.dll" }, args.MetadataReferences.Select(x => x.Reference)); args = parse(@"/nostdlib /r:""a-s.dll"",""b-s.dll"" c.cs"); Assert.Equal( new[] { @"a-s.dll", @"b-s.dll" }, args.MetadataReferences.Select(x => x.Reference)); args = parse(@"/nostdlib /r:""a,;s.dll"",""b,;s.dll"" c.cs"); Assert.Equal( new[] { @"a,;s.dll", @"b,;s.dll" }, args.MetadataReferences.Select(x => x.Reference)); } [Fact] public void CommandLine_ScriptRunner1() { var args = ScriptParse(new[] { "--", "script.csx", "b", "c" }, baseDirectory: WorkingDirectory); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "--", "@script.csx", "b", "c" }, baseDirectory: WorkingDirectory); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "@script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "--", "-script.csx", "b", "c" }, baseDirectory: WorkingDirectory); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "-script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "script.csx", "--", "b", "c" }, baseDirectory: WorkingDirectory); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "--", "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "script.csx", "a", "b", "c" }, baseDirectory: WorkingDirectory); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "a", "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "script.csx", "a", "--", "b", "c" }, baseDirectory: WorkingDirectory); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "a", "--", "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "-i", "script.csx", "a", "b", "c" }, baseDirectory: WorkingDirectory); Assert.True(args.InteractiveMode); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "a", "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "-i", "--", "script.csx", "a", "b", "c" }, baseDirectory: WorkingDirectory); Assert.True(args.InteractiveMode); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "a", "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "-i", "--", "--", "--" }, baseDirectory: WorkingDirectory); Assert.True(args.InteractiveMode); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "--") }, args.SourceFiles.Select(f => f.Path)); Assert.True(args.SourceFiles[0].IsScript); AssertEx.Equal(new[] { "--" }, args.ScriptArguments); // TODO: fails on Linux (https://github.com/dotnet/roslyn/issues/5904) // Result: C:\/script.csx //args = ScriptParse(new[] { "-i", "script.csx", "--", "--" }, baseDirectory: @"C:\"); //Assert.True(args.InteractiveMode); //AssertEx.Equal(new[] { @"C:\script.csx" }, args.SourceFiles.Select(f => f.Path)); //Assert.True(args.SourceFiles[0].IsScript); //AssertEx.Equal(new[] { "--" }, args.ScriptArguments); } [WorkItem(127403, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/127403")] [Fact] public void ParseSeparatedPaths_QuotedComma() { var paths = CSharpCommandLineParser.ParseSeparatedPaths(@"""a, b"""); Assert.Equal( new[] { @"a, b" }, paths); } [Fact] [CompilerTrait(CompilerFeature.Determinism)] public void PathMapParser() { var s = PathUtilities.DirectorySeparatorStr; var parsedArgs = DefaultParse(new[] { "/pathmap:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ImmutableArray.Create<KeyValuePair<string, string>>(), parsedArgs.PathMap); parsedArgs = DefaultParse(new[] { "/pathmap:K1=V1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create("K1" + s, "V1" + s), parsedArgs.PathMap[0]); parsedArgs = DefaultParse(new[] { $"/pathmap:abc{s}=/", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create("abc" + s, "/"), parsedArgs.PathMap[0]); parsedArgs = DefaultParse(new[] { "/pathmap:K1=V1,K2=V2", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create("K1" + s, "V1" + s), parsedArgs.PathMap[0]); Assert.Equal(KeyValuePairUtil.Create("K2" + s, "V2" + s), parsedArgs.PathMap[1]); parsedArgs = DefaultParse(new[] { "/pathmap:,", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ImmutableArray.Create<KeyValuePair<string, string>>(), parsedArgs.PathMap); parsedArgs = DefaultParse(new[] { "/pathmap:,,", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Count()); Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[0].Code); parsedArgs = DefaultParse(new[] { "/pathmap:,,,", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Count()); Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[0].Code); parsedArgs = DefaultParse(new[] { "/pathmap:k=,=v", "a.cs" }, WorkingDirectory); Assert.Equal(2, parsedArgs.Errors.Count()); Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[0].Code); Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[1].Code); parsedArgs = DefaultParse(new[] { "/pathmap:k=v=bad", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Count()); Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[0].Code); parsedArgs = DefaultParse(new[] { "/pathmap:k=", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Count()); Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[0].Code); parsedArgs = DefaultParse(new[] { "/pathmap:=v", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Count()); Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[0].Code); parsedArgs = DefaultParse(new[] { "/pathmap:\"supporting spaces=is hard\"", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create("supporting spaces" + s, "is hard" + s), parsedArgs.PathMap[0]); parsedArgs = DefaultParse(new[] { "/pathmap:\"K 1=V 1\",\"K 2=V 2\"", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create("K 1" + s, "V 1" + s), parsedArgs.PathMap[0]); Assert.Equal(KeyValuePairUtil.Create("K 2" + s, "V 2" + s), parsedArgs.PathMap[1]); parsedArgs = DefaultParse(new[] { "/pathmap:\"K 1\"=\"V 1\",\"K 2\"=\"V 2\"", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create("K 1" + s, "V 1" + s), parsedArgs.PathMap[0]); Assert.Equal(KeyValuePairUtil.Create("K 2" + s, "V 2" + s), parsedArgs.PathMap[1]); parsedArgs = DefaultParse(new[] { "/pathmap:\"a ==,,b\"=\"1,,== 2\",\"x ==,,y\"=\"3 4\",", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create("a =,b" + s, "1,= 2" + s), parsedArgs.PathMap[0]); Assert.Equal(KeyValuePairUtil.Create("x =,y" + s, "3 4" + s), parsedArgs.PathMap[1]); parsedArgs = DefaultParse(new[] { @"/pathmap:C:\temp\=/_1/,C:\temp\a\=/_2/,C:\temp\a\b\=/_3/", "a.cs", @"a\b.cs", @"a\b\c.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create(@"C:\temp\a\b\", "/_3/"), parsedArgs.PathMap[0]); Assert.Equal(KeyValuePairUtil.Create(@"C:\temp\a\", "/_2/"), parsedArgs.PathMap[1]); Assert.Equal(KeyValuePairUtil.Create(@"C:\temp\", "/_1/"), parsedArgs.PathMap[2]); } [Theory] [InlineData("", new string[0])] [InlineData(",", new[] { "", "" })] [InlineData(",,", new[] { "," })] [InlineData(",,,", new[] { ",", "" })] [InlineData(",,,,", new[] { ",," })] [InlineData("a,", new[] { "a", "" })] [InlineData("a,b", new[] { "a", "b" })] [InlineData(",,a,,,,,b,,", new[] { ",a,,", "b," })] public void SplitWithDoubledSeparatorEscaping(string str, string[] expected) { AssertEx.Equal(expected, CommandLineParser.SplitWithDoubledSeparatorEscaping(str, ',')); } [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] [CompilerTrait(CompilerFeature.Determinism)] public void PathMapPdbParser() { var dir = Path.Combine(WorkingDirectory, "a"); var parsedArgs = DefaultParse(new[] { $@"/pathmap:{dir}=b:\", "a.cs", @"/pdb:a\data.pdb", "/debug:full" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(dir, @"data.pdb"), parsedArgs.PdbPath); // This value is calculate during Emit phases and should be null even in the face of a pathmap targeting it. Assert.Null(parsedArgs.EmitOptions.PdbFilePath); } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] [CompilerTrait(CompilerFeature.Determinism)] public void PathMapPdbEmit() { void AssertPdbEmit(TempDirectory dir, string pdbPath, string pePdbPath, params string[] extraArgs) { var source = @"class Program { static void Main() { } }"; var src = dir.CreateFile("a.cs").WriteAllText(source); var defaultArgs = new[] { "/nologo", "a.cs", "/out:a.exe", "/debug:full", $"/pdb:{pdbPath}" }; var isDeterministic = extraArgs.Contains("/deterministic"); var args = defaultArgs.Concat(extraArgs).ToArray(); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, args); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var exePath = Path.Combine(dir.Path, "a.exe"); Assert.True(File.Exists(exePath)); Assert.True(File.Exists(pdbPath)); using (var peStream = File.OpenRead(exePath)) { PdbValidation.ValidateDebugDirectory(peStream, null, pePdbPath, hashAlgorithm: default, hasEmbeddedPdb: false, isDeterministic); } } // Case with no mappings using (var dir = new DisposableDirectory(Temp)) { var pdbPath = Path.Combine(dir.Path, "a.pdb"); AssertPdbEmit(dir, pdbPath, pdbPath); } // Simple mapping using (var dir = new DisposableDirectory(Temp)) { var pdbPath = Path.Combine(dir.Path, "a.pdb"); AssertPdbEmit(dir, pdbPath, @"q:\a.pdb", $@"/pathmap:{dir.Path}=q:\"); } // Simple mapping deterministic using (var dir = new DisposableDirectory(Temp)) { var pdbPath = Path.Combine(dir.Path, "a.pdb"); AssertPdbEmit(dir, pdbPath, @"q:\a.pdb", $@"/pathmap:{dir.Path}=q:\", "/deterministic"); } // Partial mapping using (var dir = new DisposableDirectory(Temp)) { dir.CreateDirectory("pdb"); var pdbPath = Path.Combine(dir.Path, @"pdb\a.pdb"); AssertPdbEmit(dir, pdbPath, @"q:\pdb\a.pdb", $@"/pathmap:{dir.Path}=q:\"); } // Legacy feature flag using (var dir = new DisposableDirectory(Temp)) { var pdbPath = Path.Combine(dir.Path, "a.pdb"); AssertPdbEmit(dir, pdbPath, @"a.pdb", $@"/features:pdb-path-determinism"); } // Unix path map using (var dir = new DisposableDirectory(Temp)) { var pdbPath = Path.Combine(dir.Path, "a.pdb"); AssertPdbEmit(dir, pdbPath, @"/a.pdb", $@"/pathmap:{dir.Path}=/"); } // Multi-specified path map with mixed slashes using (var dir = new DisposableDirectory(Temp)) { var pdbPath = Path.Combine(dir.Path, "a.pdb"); AssertPdbEmit(dir, pdbPath, "/goo/a.pdb", $"/pathmap:{dir.Path}=/goo,{dir.Path}{PathUtilities.DirectorySeparatorChar}=/bar"); } } [CompilerTrait(CompilerFeature.Determinism)] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void DeterministicPdbsRegardlessOfBitness() { var dir = Temp.CreateDirectory(); var dir32 = dir.CreateDirectory("32"); var dir64 = dir.CreateDirectory("64"); var programExe32 = dir32.CreateFile("Program.exe"); var programPdb32 = dir32.CreateFile("Program.pdb"); var programExe64 = dir64.CreateFile("Program.exe"); var programPdb64 = dir64.CreateFile("Program.pdb"); var sourceFile = dir.CreateFile("Source.cs").WriteAllText(@" using System; using System.Linq; using System.Collections.Generic; namespace N { using I4 = System.Int32; class Program { public static IEnumerable<int> F() { I4 x = 1; yield return 1; yield return x; } public static void Main(string[] args) { dynamic x = 1; const int a = 1; F().ToArray(); Console.WriteLine(x + a); } } }"); var csc32src = $@" using System; using System.Reflection; class Runner {{ static int Main(string[] args) {{ var assembly = Assembly.LoadFrom(@""{s_CSharpCompilerExecutable}""); var program = assembly.GetType(""Microsoft.CodeAnalysis.CSharp.CommandLine.Program""); var main = program.GetMethod(""Main""); return (int)main.Invoke(null, new object[] {{ args }}); }} }} "; var csc32 = CreateCompilationWithMscorlib46(csc32src, options: TestOptions.ReleaseExe.WithPlatform(Platform.X86), assemblyName: "csc32"); var csc32exe = dir.CreateFile("csc32.exe").WriteAllBytes(csc32.EmitToArray()); dir.CopyFile(Path.ChangeExtension(s_CSharpCompilerExecutable, ".exe.config"), "csc32.exe.config"); dir.CopyFile(Path.Combine(Path.GetDirectoryName(s_CSharpCompilerExecutable), "csc.rsp")); var output = ProcessUtilities.RunAndGetOutput(csc32exe.Path, $@"/nologo /debug:full /deterministic /out:Program.exe /pathmap:""{dir32.Path}""=X:\ ""{sourceFile.Path}""", expectedRetCode: 0, startFolder: dir32.Path); Assert.Equal("", output); output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, $@"/nologo /debug:full /deterministic /out:Program.exe /pathmap:""{dir64.Path}""=X:\ ""{sourceFile.Path}""", expectedRetCode: 0, startFolder: dir64.Path); Assert.Equal("", output); AssertEx.Equal(programExe32.ReadAllBytes(), programExe64.ReadAllBytes()); AssertEx.Equal(programPdb32.ReadAllBytes(), programPdb64.ReadAllBytes()); } [WorkItem(7588, "https://github.com/dotnet/roslyn/issues/7588")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void Version() { var folderName = Temp.CreateDirectory().ToString(); var argss = new[] { "/version", "a.cs /version /preferreduilang:en", "/version /nologo", "/version /help", }; foreach (var args in argss) { var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, args, startFolder: folderName); Assert.Equal(s_compilerVersion, output.Trim()); } } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void RefOut() { var dir = Temp.CreateDirectory(); var refDir = dir.CreateDirectory("ref"); var src = dir.CreateFile("a.cs"); src.WriteAllText(@" public class C { /// <summary>Main method</summary> public static void Main() { System.Console.Write(""Hello""); } /// <summary>Private method</summary> private static void PrivateMethod() { System.Console.Write(""Private""); } }"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/out:a.exe", "/refout:ref/a.dll", "/doc:doc.xml", "/deterministic", "/langversion:7", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var exe = Path.Combine(dir.Path, "a.exe"); Assert.True(File.Exists(exe)); MetadataReaderUtils.VerifyPEMetadata(exe, new[] { "TypeDefinition:<Module>", "TypeDefinition:C" }, new[] { "MethodDefinition:Void C.Main()", "MethodDefinition:Void C.PrivateMethod()", "MethodDefinition:Void C..ctor()" }, new[] { "CompilationRelaxationsAttribute", "RuntimeCompatibilityAttribute", "DebuggableAttribute" } ); var doc = Path.Combine(dir.Path, "doc.xml"); Assert.True(File.Exists(doc)); var content = File.ReadAllText(doc); var expectedDoc = @"<?xml version=""1.0""?> <doc> <assembly> <name>a</name> </assembly> <members> <member name=""M:C.Main""> <summary>Main method</summary> </member> <member name=""M:C.PrivateMethod""> <summary>Private method</summary> </member> </members> </doc>"; Assert.Equal(expectedDoc, content.Trim()); var output = ProcessUtilities.RunAndGetOutput(exe, startFolder: dir.Path); Assert.Equal("Hello", output.Trim()); var refDll = Path.Combine(refDir.Path, "a.dll"); Assert.True(File.Exists(refDll)); // The types and members that are included needs further refinement. // See issue https://github.com/dotnet/roslyn/issues/17612 MetadataReaderUtils.VerifyPEMetadata(refDll, new[] { "TypeDefinition:<Module>", "TypeDefinition:C" }, new[] { "MethodDefinition:Void C.Main()", "MethodDefinition:Void C..ctor()" }, new[] { "CompilationRelaxationsAttribute", "RuntimeCompatibilityAttribute", "DebuggableAttribute", "ReferenceAssemblyAttribute" } ); // Clean up temp files CleanupAllGeneratedFiles(dir.Path); CleanupAllGeneratedFiles(refDir.Path); } [Fact] public void RefOutWithError() { var dir = Temp.CreateDirectory(); dir.CreateDirectory("ref"); var src = dir.CreateFile("a.cs"); src.WriteAllText(@"class C { public static void Main() { error(); } }"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/out:a.dll", "/refout:ref/a.dll", "/deterministic", "/preferreduilang:en", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); var dll = Path.Combine(dir.Path, "a.dll"); Assert.False(File.Exists(dll)); var refDll = Path.Combine(dir.Path, Path.Combine("ref", "a.dll")); Assert.False(File.Exists(refDll)); Assert.Equal("a.cs(1,39): error CS0103: The name 'error' does not exist in the current context", outWriter.ToString().Trim()); // Clean up temp files CleanupAllGeneratedFiles(dir.Path); } [Fact] public void RefOnly() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("a.cs"); src.WriteAllText(@" using System; class C { /// <summary>Main method</summary> public static void Main() { error(); // semantic error in method body } private event Action E1 { add { } remove { } } private event Action E2; /// <summary>Private Class Field</summary> private int field; /// <summary>Private Struct</summary> private struct S { /// <summary>Private Struct Field</summary> private int field; } }"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/out:a.dll", "/refonly", "/debug", "/deterministic", "/langversion:7", "/doc:doc.xml", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal("", outWriter.ToString()); Assert.Equal(0, exitCode); var refDll = Path.Combine(dir.Path, "a.dll"); Assert.True(File.Exists(refDll)); // The types and members that are included needs further refinement. // See issue https://github.com/dotnet/roslyn/issues/17612 MetadataReaderUtils.VerifyPEMetadata(refDll, new[] { "TypeDefinition:<Module>", "TypeDefinition:C", "TypeDefinition:S" }, new[] { "MethodDefinition:Void C.Main()", "MethodDefinition:Void C..ctor()" }, new[] { "CompilationRelaxationsAttribute", "RuntimeCompatibilityAttribute", "DebuggableAttribute", "ReferenceAssemblyAttribute" } ); var pdb = Path.Combine(dir.Path, "a.pdb"); Assert.False(File.Exists(pdb)); var doc = Path.Combine(dir.Path, "doc.xml"); Assert.True(File.Exists(doc)); var content = File.ReadAllText(doc); var expectedDoc = @"<?xml version=""1.0""?> <doc> <assembly> <name>a</name> </assembly> <members> <member name=""M:C.Main""> <summary>Main method</summary> </member> <member name=""F:C.field""> <summary>Private Class Field</summary> </member> <member name=""T:C.S""> <summary>Private Struct</summary> </member> <member name=""F:C.S.field""> <summary>Private Struct Field</summary> </member> </members> </doc>"; Assert.Equal(expectedDoc, content.Trim()); // Clean up temp files CleanupAllGeneratedFiles(dir.Path); } [Fact] public void CompilingCodeWithInvalidPreProcessorSymbolsShouldProvideDiagnostics() { var parsedArgs = DefaultParse(new[] { "/define:1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2029: Invalid name for a preprocessing symbol; '1' is not a valid identifier Diagnostic(ErrorCode.WRN_DefineIdentifierRequired).WithArguments("1").WithLocation(1, 1)); } [Fact] public void WhitespaceInDefine() { var parsedArgs = DefaultParse(new[] { "/define:\" a\"", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("a", parsedArgs.ParseOptions.PreprocessorSymbols.Single()); } [Fact] public void WhitespaceInDefine_OnlySpaces() { var parsedArgs = DefaultParse(new[] { "/define:\" \"", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.WRN_DefineIdentifierRequired).WithArguments(" ").WithLocation(1, 1) ); Assert.True(parsedArgs.ParseOptions.PreprocessorSymbols.IsEmpty); } [Fact] public void CompilingCodeWithInvalidLanguageVersionShouldProvideDiagnostics() { var parsedArgs = DefaultParse(new[] { "/langversion:1000", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS1617: Invalid option '1000' for /langversion. Use '/langversion:?' to list supported values. Diagnostic(ErrorCode.ERR_BadCompatMode).WithArguments("1000").WithLocation(1, 1)); } [Fact, WorkItem(16913, "https://github.com/dotnet/roslyn/issues/16913")] public void CompilingCodeWithMultipleInvalidPreProcessorSymbolsShouldErrorOut() { var parsedArgs = DefaultParse(new[] { "/define:valid1,2invalid,valid3", "/define:4,5,valid6", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2029: Invalid value for '/define'; '2invalid' is not a valid identifier Diagnostic(ErrorCode.WRN_DefineIdentifierRequired).WithArguments("2invalid"), // warning CS2029: Invalid value for '/define'; '4' is not a valid identifier Diagnostic(ErrorCode.WRN_DefineIdentifierRequired).WithArguments("4"), // warning CS2029: Invalid value for '/define'; '5' is not a valid identifier Diagnostic(ErrorCode.WRN_DefineIdentifierRequired).WithArguments("5")); } [WorkItem(406649, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=406649")] [ConditionalFact(typeof(WindowsDesktopOnly), typeof(IsEnglishLocal), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void MissingCompilerAssembly() { var dir = Temp.CreateDirectory(); var cscPath = dir.CopyFile(s_CSharpCompilerExecutable).Path; dir.CopyFile(typeof(Compilation).Assembly.Location); // Missing Microsoft.CodeAnalysis.CSharp.dll. var result = ProcessUtilities.Run(cscPath, arguments: "/nologo /t:library unknown.cs", workingDirectory: dir.Path); Assert.Equal(1, result.ExitCode); Assert.Equal( $"Could not load file or assembly '{typeof(CSharpCompilation).Assembly.FullName}' or one of its dependencies. The system cannot find the file specified.", result.Output.Trim()); // Missing System.Collections.Immutable.dll. dir.CopyFile(typeof(CSharpCompilation).Assembly.Location); result = ProcessUtilities.Run(cscPath, arguments: "/nologo /t:library unknown.cs", workingDirectory: dir.Path); Assert.Equal(1, result.ExitCode); Assert.Equal( $"Could not load file or assembly '{typeof(ImmutableArray).Assembly.FullName}' or one of its dependencies. The system cannot find the file specified.", result.Output.Trim()); } #if NET472 [ConditionalFact(typeof(WindowsDesktopOnly), typeof(IsEnglishLocal), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void LoadinganalyzerNetStandard13() { var analyzerFileName = "AnalyzerNS13.dll"; var srcFileName = "src.cs"; var analyzerDir = Temp.CreateDirectory(); var analyzerFile = analyzerDir.CreateFile(analyzerFileName).WriteAllBytes(CreateCSharpAnalyzerNetStandard13(Path.GetFileNameWithoutExtension(analyzerFileName))); var srcFile = analyzerDir.CreateFile(srcFileName).WriteAllText("public class C { }"); var result = ProcessUtilities.Run(s_CSharpCompilerExecutable, arguments: $"/nologo /t:library /analyzer:{analyzerFileName} {srcFileName}", workingDirectory: analyzerDir.Path); var outputWithoutPaths = Regex.Replace(result.Output, " in .*", ""); AssertEx.AssertEqualToleratingWhitespaceDifferences( $@"warning AD0001: Analyzer 'TestAnalyzer' threw an exception of type 'System.NotImplementedException' with message '28'. System.NotImplementedException: 28 at TestAnalyzer.get_SupportedDiagnostics() at Microsoft.CodeAnalysis.Diagnostics.AnalyzerManager.AnalyzerExecutionContext.<>c__DisplayClass20_0.<ComputeDiagnosticDescriptors>b__0(Object _) at Microsoft.CodeAnalysis.Diagnostics.AnalyzerExecutor.ExecuteAndCatchIfThrows_NoLock[TArg](DiagnosticAnalyzer analyzer, Action`1 analyze, TArg argument, Nullable`1 info) -----", outputWithoutPaths); Assert.Equal(0, result.ExitCode); } #endif private static ImmutableArray<byte> CreateCSharpAnalyzerNetStandard13(string analyzerAssemblyName) { var minSystemCollectionsImmutableSource = @" [assembly: System.Reflection.AssemblyVersion(""1.2.3.0"")] namespace System.Collections.Immutable { public struct ImmutableArray<T> { } } "; var minCodeAnalysisSource = @" using System; [assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] namespace Microsoft.CodeAnalysis.Diagnostics { [AttributeUsage(AttributeTargets.Class)] public sealed class DiagnosticAnalyzerAttribute : Attribute { public DiagnosticAnalyzerAttribute(string firstLanguage, params string[] additionalLanguages) {} } public abstract class DiagnosticAnalyzer { public abstract System.Collections.Immutable.ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } public abstract void Initialize(AnalysisContext context); } public abstract class AnalysisContext { } } namespace Microsoft.CodeAnalysis { public sealed class DiagnosticDescriptor { } } "; var minSystemCollectionsImmutableImage = CSharpCompilation.Create( "System.Collections.Immutable", new[] { SyntaxFactory.ParseSyntaxTree(minSystemCollectionsImmutableSource) }, new MetadataReference[] { NetStandard13.SystemRuntime }, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, cryptoPublicKey: TestResources.TestKeys.PublicKey_b03f5f7f11d50a3a)).EmitToArray(); var minSystemCollectionsImmutableRef = MetadataReference.CreateFromImage(minSystemCollectionsImmutableImage); var minCodeAnalysisImage = CSharpCompilation.Create( "Microsoft.CodeAnalysis", new[] { SyntaxFactory.ParseSyntaxTree(minCodeAnalysisSource) }, new MetadataReference[] { NetStandard13.SystemRuntime, minSystemCollectionsImmutableRef }, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, cryptoPublicKey: TestResources.TestKeys.PublicKey_31bf3856ad364e35)).EmitToArray(); var minCodeAnalysisRef = MetadataReference.CreateFromImage(minCodeAnalysisImage); var analyzerSource = @" using System; using System.Collections.ObjectModel; using System.Collections.Immutable; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.IO.Compression; using System.Net.Http; using System.Net.Security; using System.Net.Sockets; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Security.AccessControl; using System.Security.Cryptography; using System.Security.Principal; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml; using System.Xml.Serialization; using System.Xml.XPath; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.Win32.SafeHandles; [DiagnosticAnalyzer(""C#"")] public class TestAnalyzer : DiagnosticAnalyzer { public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => throw new NotImplementedException(new[] { typeof(Win32Exception), // Microsoft.Win32.Primitives typeof(AppContext), // System.AppContext typeof(Console), // System.Console typeof(ValueTuple), // System.ValueTuple typeof(FileVersionInfo), // System.Diagnostics.FileVersionInfo typeof(Process), // System.Diagnostics.Process typeof(ChineseLunisolarCalendar), // System.Globalization.Calendars typeof(ZipArchive), // System.IO.Compression typeof(ZipFile), // System.IO.Compression.ZipFile typeof(FileOptions), // System.IO.FileSystem typeof(FileAttributes), // System.IO.FileSystem.Primitives typeof(HttpClient), // System.Net.Http typeof(AuthenticatedStream), // System.Net.Security typeof(IOControlCode), // System.Net.Sockets typeof(RuntimeInformation), // System.Runtime.InteropServices.RuntimeInformation typeof(SerializationException), // System.Runtime.Serialization.Primitives typeof(GenericIdentity), // System.Security.Claims typeof(Aes), // System.Security.Cryptography.Algorithms typeof(CspParameters), // System.Security.Cryptography.Csp typeof(AsnEncodedData), // System.Security.Cryptography.Encoding typeof(AsymmetricAlgorithm), // System.Security.Cryptography.Primitives typeof(SafeX509ChainHandle), // System.Security.Cryptography.X509Certificates typeof(IXmlLineInfo), // System.Xml.ReaderWriter typeof(XmlNode), // System.Xml.XmlDocument typeof(XPathDocument), // System.Xml.XPath typeof(XDocumentExtensions), // System.Xml.XPath.XDocument typeof(CodePagesEncodingProvider),// System.Text.Encoding.CodePages typeof(ValueTask<>), // System.Threading.Tasks.Extensions // csc doesn't ship with facades for the following assemblies. // Analyzers can't use them unless they carry the facade with them. // typeof(SafePipeHandle), // System.IO.Pipes // typeof(StackFrame), // System.Diagnostics.StackTrace // typeof(BindingFlags), // System.Reflection.TypeExtensions // typeof(AccessControlActions), // System.Security.AccessControl // typeof(SafeAccessTokenHandle), // System.Security.Principal.Windows // typeof(Thread), // System.Threading.Thread }.Length.ToString()); public override void Initialize(AnalysisContext context) { } }"; var references = new MetadataReference[] { minCodeAnalysisRef, minSystemCollectionsImmutableRef }; references = references.Concat(NetStandard13.All).ToArray(); var analyzerImage = CSharpCompilation.Create( analyzerAssemblyName, new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree(analyzerSource) }, references: references, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)).EmitToArray(); return analyzerImage; } [WorkItem(406649, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=484417")] [ConditionalFact(typeof(WindowsDesktopOnly), typeof(IsEnglishLocal), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void MicrosoftDiaSymReaderNativeAltLoadPath() { var dir = Temp.CreateDirectory(); var cscDir = Path.GetDirectoryName(s_CSharpCompilerExecutable); // copy csc and dependencies except for DSRN: foreach (var filePath in Directory.EnumerateFiles(cscDir)) { var fileName = Path.GetFileName(filePath); if (fileName.StartsWith("csc") || fileName.StartsWith("System.") || fileName.StartsWith("Microsoft.") && !fileName.StartsWith("Microsoft.DiaSymReader.Native")) { dir.CopyFile(filePath); } } dir.CreateFile("Source.cs").WriteAllText("class C { void F() { } }"); var cscCopy = Path.Combine(dir.Path, "csc.exe"); var arguments = "/nologo /t:library /debug:full Source.cs"; // env variable not set (deterministic) -- DSRN is required: var result = ProcessUtilities.Run( cscCopy, arguments + " /deterministic", workingDirectory: dir.Path, additionalEnvironmentVars: new[] { KeyValuePairUtil.Create("MICROSOFT_DIASYMREADER_NATIVE_ALT_LOAD_PATH", "") }); AssertEx.AssertEqualToleratingWhitespaceDifferences( "error CS0041: Unexpected error writing debug information -- 'Unable to load DLL 'Microsoft.DiaSymReader.Native.amd64.dll': " + "The specified module could not be found. (Exception from HRESULT: 0x8007007E)'", result.Output.Trim()); // env variable not set (non-deterministic) -- globally registered SymReader is picked up: result = ProcessUtilities.Run(cscCopy, arguments, workingDirectory: dir.Path); AssertEx.AssertEqualToleratingWhitespaceDifferences("", result.Output.Trim()); // env variable set: result = ProcessUtilities.Run( cscCopy, arguments + " /deterministic", workingDirectory: dir.Path, additionalEnvironmentVars: new[] { KeyValuePairUtil.Create("MICROSOFT_DIASYMREADER_NATIVE_ALT_LOAD_PATH", cscDir) }); Assert.Equal("", result.Output.Trim()); } [ConditionalFact(typeof(WindowsOnly))] [WorkItem(21935, "https://github.com/dotnet/roslyn/issues/21935")] public void PdbPathNotEmittedWithoutPdb() { var dir = Temp.CreateDirectory(); var source = @"class Program { static void Main() { } }"; var src = dir.CreateFile("a.cs").WriteAllText(source); var args = new[] { "/nologo", "a.cs", "/out:a.exe", "/debug-" }; var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, args); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var exePath = Path.Combine(dir.Path, "a.exe"); Assert.True(File.Exists(exePath)); using (var peStream = File.OpenRead(exePath)) using (var peReader = new PEReader(peStream)) { var debugDirectory = peReader.PEHeaders.PEHeader.DebugTableDirectory; Assert.Equal(0, debugDirectory.Size); Assert.Equal(0, debugDirectory.RelativeVirtualAddress); } } [Fact] public void StrongNameProviderWithCustomTempPath() { var tempDir = Temp.CreateDirectory(); var workingDir = Temp.CreateDirectory(); workingDir.CreateFile("a.cs"); var buildPaths = new BuildPaths(clientDir: "", workingDir: workingDir.Path, sdkDir: null, tempDir: tempDir.Path); var csc = new MockCSharpCompiler(null, buildPaths, args: new[] { "/features:UseLegacyStrongNameProvider", "/nostdlib", "a.cs" }); var comp = csc.CreateCompilation(new StringWriter(), new TouchedFileLogger(), errorLogger: null); Assert.True(!comp.SignUsingBuilder); } public class QuotedArgumentTests : CommandLineTestBase { private static readonly string s_rootPath = ExecutionConditionUtil.IsWindows ? @"c:\" : "/"; private void VerifyQuotedValid<T>(string name, string value, T expected, Func<CSharpCommandLineArguments, T> getValue) { var args = DefaultParse(new[] { $"/{name}:{value}", "a.cs" }, s_rootPath); Assert.Equal(0, args.Errors.Length); Assert.Equal(expected, getValue(args)); args = DefaultParse(new[] { $@"/{name}:""{value}""", "a.cs" }, s_rootPath); Assert.Equal(0, args.Errors.Length); Assert.Equal(expected, getValue(args)); } private void VerifyQuotedInvalid<T>(string name, string value, T expected, Func<CSharpCommandLineArguments, T> getValue) { var args = DefaultParse(new[] { $"/{name}:{value}", "a.cs" }, s_rootPath); Assert.Equal(0, args.Errors.Length); Assert.Equal(expected, getValue(args)); args = DefaultParse(new[] { $@"/{name}:""{value}""", "a.cs" }, s_rootPath); Assert.True(args.Errors.Length > 0); } [WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")] [Fact] public void DebugFlag() { var platformPdbKind = PathUtilities.IsUnixLikePlatform ? DebugInformationFormat.PortablePdb : DebugInformationFormat.Pdb; var list = new List<Tuple<string, DebugInformationFormat>>() { Tuple.Create("portable", DebugInformationFormat.PortablePdb), Tuple.Create("full", platformPdbKind), Tuple.Create("pdbonly", platformPdbKind), Tuple.Create("embedded", DebugInformationFormat.Embedded) }; foreach (var tuple in list) { VerifyQuotedValid("debug", tuple.Item1, tuple.Item2, x => x.EmitOptions.DebugInformationFormat); } } [WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30328")] public void CodePage() { VerifyQuotedValid("codepage", "1252", 1252, x => x.Encoding.CodePage); } [WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")] [Fact] public void Target() { var list = new List<Tuple<string, OutputKind>>() { Tuple.Create("exe", OutputKind.ConsoleApplication), Tuple.Create("winexe", OutputKind.WindowsApplication), Tuple.Create("library", OutputKind.DynamicallyLinkedLibrary), Tuple.Create("module", OutputKind.NetModule), Tuple.Create("appcontainerexe", OutputKind.WindowsRuntimeApplication), Tuple.Create("winmdobj", OutputKind.WindowsRuntimeMetadata) }; foreach (var tuple in list) { VerifyQuotedInvalid("target", tuple.Item1, tuple.Item2, x => x.CompilationOptions.OutputKind); } } [WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")] [Fact] public void PlatformFlag() { var list = new List<Tuple<string, Platform>>() { Tuple.Create("x86", Platform.X86), Tuple.Create("x64", Platform.X64), Tuple.Create("itanium", Platform.Itanium), Tuple.Create("anycpu", Platform.AnyCpu), Tuple.Create("anycpu32bitpreferred",Platform.AnyCpu32BitPreferred), Tuple.Create("arm", Platform.Arm) }; foreach (var tuple in list) { VerifyQuotedValid("platform", tuple.Item1, tuple.Item2, x => x.CompilationOptions.Platform); } } [WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")] [Fact] public void WarnFlag() { VerifyQuotedValid("warn", "1", 1, x => x.CompilationOptions.WarningLevel); } [WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")] [Fact] public void LangVersionFlag() { VerifyQuotedValid("langversion", "2", LanguageVersion.CSharp2, x => x.ParseOptions.LanguageVersion); } } [Fact] [WorkItem(23525, "https://github.com/dotnet/roslyn/issues/23525")] public void InvalidPathCharacterInPathMap() { string filePath = Temp.CreateFile().WriteAllText("").Path; var compiler = CreateCSharpCompiler(null, WorkingDirectory, new[] { filePath, "/debug:embedded", "/pathmap:test\\=\"", "/target:library", "/preferreduilang:en" }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = compiler.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("error CS8101: The pathmap option was incorrectly formatted.", outWriter.ToString(), StringComparison.Ordinal); } [WorkItem(23525, "https://github.com/dotnet/roslyn/issues/23525")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void InvalidPathCharacterInPdbPath() { string filePath = Temp.CreateFile().WriteAllText("").Path; var compiler = CreateCSharpCompiler(null, WorkingDirectory, new[] { filePath, "/debug:embedded", "/pdb:test\\?.pdb", "/target:library", "/preferreduilang:en" }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = compiler.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("error CS2021: File name 'test\\?.pdb' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long", outWriter.ToString(), StringComparison.Ordinal); } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] [ConditionalFact(typeof(IsEnglishLocal))] public void TestSuppression_CompilerParserWarningAsError() { string source = @" class C { long M(int i) { // warning CS0078 : The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity return 0l; } } "; var srcDirectory = Temp.CreateDirectory(); var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); // Verify that parser warning CS0078 is reported. var output = VerifyOutput(srcDirectory, srcFile, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); Assert.Contains("warning CS0078", output, StringComparison.Ordinal); // Verify that parser warning CS0078 is reported as error for /warnaserror. output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false); Assert.Contains("error CS0078", output, StringComparison.Ordinal); // Verify that parser warning CS0078 is suppressed with diagnostic suppressor even with /warnaserror // and info diagnostic is logged with programmatic suppression information. var suppressor = new DiagnosticSuppressorForId("CS0078"); output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, expectedErrorCount: 0, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false, errorlog: true, analyzers: suppressor); Assert.DoesNotContain($"error CS0078", output, StringComparison.Ordinal); Assert.DoesNotContain($"warning CS0078", output, StringComparison.Ordinal); // Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppression ID '{2}' and justification '{3}' var suppressionMessage = string.Format(CodeAnalysisResources.SuppressionDiagnosticDescriptorMessage, suppressor.SuppressionDescriptor.SuppressedDiagnosticId, new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.WRN_LowercaseEllSuffix, "l"), Location.None).GetMessage(CultureInfo.InvariantCulture), suppressor.SuppressionDescriptor.Id, suppressor.SuppressionDescriptor.Justification); Assert.Contains("info SP0001", output, StringComparison.Ordinal); Assert.Contains(suppressionMessage, output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] [ConditionalTheory(typeof(IsEnglishLocal)), CombinatorialData] public void TestSuppression_CompilerSyntaxWarning(bool skipAnalyzers) { // warning CS1522: Empty switch block // NOTE: Empty switch block warning is reported by the C# language parser string source = @" class C { void M(int i) { switch (i) { } } }"; var srcDirectory = Temp.CreateDirectory(); var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); // Verify that compiler warning CS1522 is reported. var output = VerifyOutput(srcDirectory, srcFile, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, skipAnalyzers: skipAnalyzers); Assert.Contains("warning CS1522", output, StringComparison.Ordinal); // Verify that compiler warning CS1522 is suppressed with diagnostic suppressor // and info diagnostic is logged with programmatic suppression information. var suppressor = new DiagnosticSuppressorForId("CS1522"); // Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppression ID '{2}' and justification '{3}' var suppressionMessage = string.Format(CodeAnalysisResources.SuppressionDiagnosticDescriptorMessage, suppressor.SuppressionDescriptor.SuppressedDiagnosticId, new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.WRN_EmptySwitch), Location.None).GetMessage(CultureInfo.InvariantCulture), suppressor.SuppressionDescriptor.Id, suppressor.SuppressionDescriptor.Justification); output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: suppressor, errorlog: true, skipAnalyzers: skipAnalyzers); Assert.DoesNotContain($"warning CS1522", output, StringComparison.Ordinal); Assert.Contains($"info SP0001", output, StringComparison.Ordinal); Assert.Contains(suppressionMessage, output, StringComparison.Ordinal); // Verify that compiler warning CS1522 is reported as error for /warnaserror. output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false, skipAnalyzers: skipAnalyzers); Assert.Contains("error CS1522", output, StringComparison.Ordinal); // Verify that compiler warning CS1522 is suppressed with diagnostic suppressor even with /warnaserror // and info diagnostic is logged with programmatic suppression information. output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, expectedErrorCount: 0, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false, errorlog: true, skipAnalyzers: skipAnalyzers, analyzers: suppressor); Assert.DoesNotContain($"error CS1522", output, StringComparison.Ordinal); Assert.DoesNotContain($"warning CS1522", output, StringComparison.Ordinal); Assert.Contains("info SP0001", output, StringComparison.Ordinal); Assert.Contains(suppressionMessage, output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] [ConditionalTheory(typeof(IsEnglishLocal)), CombinatorialData] public void TestSuppression_CompilerSemanticWarning(bool skipAnalyzers) { string source = @" class C { // warning CS0169: The field 'C.f' is never used private readonly int f; }"; var srcDirectory = Temp.CreateDirectory(); var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); // Verify that compiler warning CS0169 is reported. var output = VerifyOutput(srcDirectory, srcFile, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, skipAnalyzers: skipAnalyzers); Assert.Contains("warning CS0169", output, StringComparison.Ordinal); // Verify that compiler warning CS0169 is suppressed with diagnostic suppressor // and info diagnostic is logged with programmatic suppression information. var suppressor = new DiagnosticSuppressorForId("CS0169"); // Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppression ID '{2}' and justification '{3}' var suppressionMessage = string.Format(CodeAnalysisResources.SuppressionDiagnosticDescriptorMessage, suppressor.SuppressionDescriptor.SuppressedDiagnosticId, new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.WRN_UnreferencedField, "C.f"), Location.None).GetMessage(CultureInfo.InvariantCulture), suppressor.SuppressionDescriptor.Id, suppressor.SuppressionDescriptor.Justification); output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: suppressor, errorlog: true, skipAnalyzers: skipAnalyzers); Assert.DoesNotContain($"warning CS0169", output, StringComparison.Ordinal); Assert.Contains("info SP0001", output, StringComparison.Ordinal); Assert.Contains(suppressionMessage, output, StringComparison.Ordinal); // Verify that compiler warning CS0169 is reported as error for /warnaserror. output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false, skipAnalyzers: skipAnalyzers); Assert.Contains("error CS0169", output, StringComparison.Ordinal); // Verify that compiler warning CS0169 is suppressed with diagnostic suppressor even with /warnaserror // and info diagnostic is logged with programmatic suppression information. output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, expectedErrorCount: 0, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false, errorlog: true, skipAnalyzers: skipAnalyzers, analyzers: suppressor); Assert.DoesNotContain($"error CS0169", output, StringComparison.Ordinal); Assert.DoesNotContain($"warning CS0169", output, StringComparison.Ordinal); Assert.Contains("info SP0001", output, StringComparison.Ordinal); Assert.Contains(suppressionMessage, output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] [Fact] public void TestNoSuppression_CompilerSyntaxError() { // error CS1001: Identifier expected string source = @" class { }"; var srcDirectory = Temp.CreateDirectory(); var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); // Verify that compiler syntax error CS1001 is reported. var output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); Assert.Contains("error CS1001", output, StringComparison.Ordinal); // Verify that compiler syntax error CS1001 cannot be suppressed with diagnostic suppressor. output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: new DiagnosticSuppressorForId("CS1001")); Assert.Contains("error CS1001", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] [Fact] public void TestNoSuppression_CompilerSemanticError() { // error CS0246: The type or namespace name 'UndefinedType' could not be found (are you missing a using directive or an assembly reference?) string source = @" class C { void M(UndefinedType x) { } }"; var srcDirectory = Temp.CreateDirectory(); var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); // Verify that compiler error CS0246 is reported. var output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); Assert.Contains("error CS0246", output, StringComparison.Ordinal); // Verify that compiler error CS0246 cannot be suppressed with diagnostic suppressor. output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: new DiagnosticSuppressorForId("CS0246")); Assert.Contains("error CS0246", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] [ConditionalFact(typeof(IsEnglishLocal))] public void TestSuppression_AnalyzerWarning() { string source = @" class C { }"; var srcDirectory = Temp.CreateDirectory(); var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); // Verify that analyzer warning is reported. var analyzer = new CompilationAnalyzerWithSeverity(DiagnosticSeverity.Warning, configurable: true); var output = VerifyOutput(srcDirectory, srcFile, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: analyzer); Assert.Contains($"warning {analyzer.Descriptor.Id}", output, StringComparison.Ordinal); // Verify that analyzer warning is suppressed with diagnostic suppressor // and info diagnostic is logged with programmatic suppression information. var suppressor = new DiagnosticSuppressorForId(analyzer.Descriptor.Id); // Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppression ID '{2}' and justification '{3}' var suppressionMessage = string.Format(CodeAnalysisResources.SuppressionDiagnosticDescriptorMessage, suppressor.SuppressionDescriptor.SuppressedDiagnosticId, analyzer.Descriptor.MessageFormat, suppressor.SuppressionDescriptor.Id, suppressor.SuppressionDescriptor.Justification); var analyzerAndSuppressor = new DiagnosticAnalyzer[] { analyzer, suppressor }; output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, includeCurrentAssemblyAsAnalyzerReference: false, errorlog: true, analyzers: analyzerAndSuppressor); Assert.DoesNotContain($"warning {analyzer.Descriptor.Id}", output, StringComparison.Ordinal); Assert.Contains("info SP0001", output, StringComparison.Ordinal); Assert.Contains(suppressionMessage, output, StringComparison.Ordinal); // Verify that analyzer warning is reported as error for /warnaserror. output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: analyzer); Assert.Contains($"error {analyzer.Descriptor.Id}", output, StringComparison.Ordinal); // Verify that analyzer warning is suppressed with diagnostic suppressor even with /warnaserror // and info diagnostic is logged with programmatic suppression information. output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false, errorlog: true, analyzers: analyzerAndSuppressor); Assert.DoesNotContain($"warning {analyzer.Descriptor.Id}", output, StringComparison.Ordinal); Assert.Contains("info SP0001", output, StringComparison.Ordinal); Assert.Contains(suppressionMessage, output, StringComparison.Ordinal); // Verify that "NotConfigurable" analyzer warning cannot be suppressed with diagnostic suppressor. analyzer = new CompilationAnalyzerWithSeverity(DiagnosticSeverity.Warning, configurable: false); suppressor = new DiagnosticSuppressorForId(analyzer.Descriptor.Id); analyzerAndSuppressor = new DiagnosticAnalyzer[] { analyzer, suppressor }; output = VerifyOutput(srcDirectory, srcFile, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: analyzerAndSuppressor); Assert.Contains($"warning {analyzer.Descriptor.Id}", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] [Fact] public void TestNoSuppression_AnalyzerError() { string source = @" class C { }"; var srcDirectory = Temp.CreateDirectory(); var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); // Verify that analyzer error is reported. var analyzer = new CompilationAnalyzerWithSeverity(DiagnosticSeverity.Error, configurable: true); var output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: analyzer); Assert.Contains($"error {analyzer.Descriptor.Id}", output, StringComparison.Ordinal); // Verify that analyzer error cannot be suppressed with diagnostic suppressor. var suppressor = new DiagnosticSuppressorForId(analyzer.Descriptor.Id); var analyzerAndSuppressor = new DiagnosticAnalyzer[] { analyzer, suppressor }; output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: analyzerAndSuppressor); Assert.Contains($"error {analyzer.Descriptor.Id}", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [WorkItem(38674, "https://github.com/dotnet/roslyn/issues/38674")] [InlineData(DiagnosticSeverity.Warning, false)] [InlineData(DiagnosticSeverity.Info, true)] [InlineData(DiagnosticSeverity.Info, false)] [InlineData(DiagnosticSeverity.Hidden, false)] [Theory] public void TestCategoryBasedBulkAnalyzerDiagnosticConfiguration(DiagnosticSeverity defaultSeverity, bool errorlog) { var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity); var diagnosticId = analyzer.Descriptor.Id; var category = analyzer.Descriptor.Category; // Verify category based configuration without any diagnostic ID configuration is respected. var analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.category-{category}.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Error); // Verify category based configuration does not get applied for suppressed diagnostic. TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress, noWarn: true); // Verify category based configuration does not get applied for diagnostic configured in ruleset. var rulesetText = $@"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.CodeAnalysis"" RuleNamespace=""Microsoft.CodeAnalysis""> <Rule Id=""{diagnosticId}"" Action=""Warning"" /> </Rules> </RuleSet>"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn, rulesetText: rulesetText); // Verify category based configuration before diagnostic ID configuration is not respected. analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.category-{category}.severity = error dotnet_diagnostic.{diagnosticId}.severity = warning"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn); // Verify category based configuration after diagnostic ID configuration is not respected. analyzerConfigText = $@" [*.cs] dotnet_diagnostic.{diagnosticId}.severity = warning dotnet_analyzer_diagnostic.category-{category}.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn); // Verify global config based configuration before diagnostic ID configuration is not respected. analyzerConfigText = $@" is_global = true dotnet_analyzer_diagnostic.category-{category}.severity = error dotnet_diagnostic.{diagnosticId}.severity = warning"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn); // Verify global config based configuration after diagnostic ID configuration is not respected. analyzerConfigText = $@" is_global = true dotnet_diagnostic.{diagnosticId}.severity = warning dotnet_analyzer_diagnostic.category-{category}.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn); // Verify category based configuration to warning + /warnaserror reports errors. analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.category-{category}.severity = warning"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, warnAsError: true, expectedDiagnosticSeverity: ReportDiagnostic.Error); // Verify disabled by default analyzer is not enabled by category based configuration. analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: false, defaultSeverity); analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.category-{category}.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); // Verify disabled by default analyzer is not enabled by category based configuration in global config analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: false, defaultSeverity); analyzerConfigText = $@" is_global=true dotnet_analyzer_diagnostic.category-{category}.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); if (defaultSeverity == DiagnosticSeverity.Hidden || defaultSeverity == DiagnosticSeverity.Info && !errorlog) { // Verify analyzer with Hidden severity OR Info severity + no /errorlog is not executed. analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity, throwOnAllNamedTypes: true); TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText: string.Empty, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); // Verify that bulk configuration 'none' entry does not enable this analyzer. analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.category-{category}.severity = none"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); // Verify that bulk configuration 'none' entry does not enable this analyzer via global config analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.category-{category}.severity = none"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); } } [WorkItem(38674, "https://github.com/dotnet/roslyn/issues/38674")] [InlineData(DiagnosticSeverity.Warning, false)] [InlineData(DiagnosticSeverity.Info, true)] [InlineData(DiagnosticSeverity.Info, false)] [InlineData(DiagnosticSeverity.Hidden, false)] [Theory] public void TestBulkAnalyzerDiagnosticConfiguration(DiagnosticSeverity defaultSeverity, bool errorlog) { var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity); var diagnosticId = analyzer.Descriptor.Id; // Verify bulk configuration without any diagnostic ID configuration is respected. var analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Error); // Verify bulk configuration does not get applied for suppressed diagnostic. TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress, noWarn: true); // Verify bulk configuration does not get applied for diagnostic configured in ruleset. var rulesetText = $@"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.CodeAnalysis"" RuleNamespace=""Microsoft.CodeAnalysis""> <Rule Id=""{diagnosticId}"" Action=""Warning"" /> </Rules> </RuleSet>"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn, rulesetText: rulesetText); // Verify bulk configuration before diagnostic ID configuration is not respected. analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.severity = error dotnet_diagnostic.{diagnosticId}.severity = warning"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn); // Verify bulk configuration after diagnostic ID configuration is not respected. analyzerConfigText = $@" [*.cs] dotnet_diagnostic.{diagnosticId}.severity = warning dotnet_analyzer_diagnostic.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn); // Verify bulk configuration to warning + /warnaserror reports errors. analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.severity = warning"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, warnAsError: true, expectedDiagnosticSeverity: ReportDiagnostic.Error); // Verify disabled by default analyzer is not enabled by bulk configuration. analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: false, defaultSeverity); analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); if (defaultSeverity == DiagnosticSeverity.Hidden || defaultSeverity == DiagnosticSeverity.Info && !errorlog) { // Verify analyzer with Hidden severity OR Info severity + no /errorlog is not executed. analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity, throwOnAllNamedTypes: true); TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText: string.Empty, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); // Verify that bulk configuration 'none' entry does not enable this analyzer. analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.severity = none"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); } } [WorkItem(38674, "https://github.com/dotnet/roslyn/issues/38674")] [InlineData(DiagnosticSeverity.Warning, false)] [InlineData(DiagnosticSeverity.Info, true)] [InlineData(DiagnosticSeverity.Info, false)] [InlineData(DiagnosticSeverity.Hidden, false)] [Theory] public void TestMixedCategoryBasedAndBulkAnalyzerDiagnosticConfiguration(DiagnosticSeverity defaultSeverity, bool errorlog) { var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity); var diagnosticId = analyzer.Descriptor.Id; var category = analyzer.Descriptor.Category; // Verify category based configuration before bulk analyzer diagnostic configuration is respected. var analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.category-{category}.severity = error dotnet_analyzer_diagnostic.severity = warning"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Error); // Verify category based configuration after bulk analyzer diagnostic configuration is respected. analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.severity = warning dotnet_analyzer_diagnostic.category-{category}.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Error); // Verify neither category based nor bulk diagnostic configuration is respected when specific diagnostic ID is configured in analyzer config. analyzerConfigText = $@" [*.cs] dotnet_diagnostic.{diagnosticId}.severity = warning dotnet_analyzer_diagnostic.category-{category}.severity = none dotnet_analyzer_diagnostic.severity = suggestion"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn); // Verify neither category based nor bulk diagnostic configuration is respected when specific diagnostic ID is configured in ruleset. analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.category-{category}.severity = none dotnet_analyzer_diagnostic.severity = suggestion"; var rulesetText = $@"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.CodeAnalysis"" RuleNamespace=""Microsoft.CodeAnalysis""> <Rule Id=""{diagnosticId}"" Action=""Warning"" /> </Rules> </RuleSet>"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn, rulesetText); } private void TestBulkAnalyzerConfigurationCore( NamedTypeAnalyzerWithConfigurableEnabledByDefault analyzer, string analyzerConfigText, bool errorlog, ReportDiagnostic expectedDiagnosticSeverity, string rulesetText = null, bool noWarn = false, bool warnAsError = false) { var diagnosticId = analyzer.Descriptor.Id; var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@"class C { }"); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(analyzerConfigText); var arguments = new[] { "/nologo", "/t:library", "/preferreduilang:en", "/analyzerconfig:" + analyzerConfig.Path, src.Path }; if (noWarn) { arguments = arguments.Append($"/nowarn:{diagnosticId}"); } if (warnAsError) { arguments = arguments.Append($"/warnaserror"); } if (errorlog) { arguments = arguments.Append($"/errorlog:errorlog"); } if (rulesetText != null) { var rulesetFile = CreateRuleSetFile(rulesetText); arguments = arguments.Append($"/ruleset:{rulesetFile.Path}"); } var cmd = CreateCSharpCompiler(null, dir.Path, arguments, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(analyzer)); Assert.Equal(analyzerConfig.Path, Assert.Single(cmd.Arguments.AnalyzerConfigPaths)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); var expectedErrorCode = expectedDiagnosticSeverity == ReportDiagnostic.Error ? 1 : 0; Assert.Equal(expectedErrorCode, exitCode); var prefix = expectedDiagnosticSeverity switch { ReportDiagnostic.Error => "error", ReportDiagnostic.Warn => "warning", ReportDiagnostic.Info => errorlog ? "info" : null, ReportDiagnostic.Hidden => null, ReportDiagnostic.Suppress => null, _ => throw ExceptionUtilities.UnexpectedValue(expectedDiagnosticSeverity) }; if (prefix == null) { Assert.DoesNotContain(diagnosticId, outWriter.ToString()); } else { Assert.Contains($"{prefix} {diagnosticId}: {analyzer.Descriptor.MessageFormat}", outWriter.ToString()); } } [Theory] [InlineData(true)] [InlineData(false)] [WorkItem(37779, "https://github.com/dotnet/roslyn/issues/37779")] public void CompilerWarnAsErrorDoesNotEmit(bool warnAsError) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { int _f; // CS0169: unused field }"); var docName = "temp.xml"; var pdbName = "temp.pdb"; var additionalArgs = new[] { $"/doc:{docName}", $"/pdb:{pdbName}", "/debug" }; if (warnAsError) { additionalArgs = additionalArgs.Append("/warnaserror").AsArray(); } var expectedErrorCount = warnAsError ? 1 : 0; var expectedWarningCount = !warnAsError ? 1 : 0; var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalArgs, expectedErrorCount: expectedErrorCount, expectedWarningCount: expectedWarningCount); var expectedOutput = warnAsError ? "error CS0169" : "warning CS0169"; Assert.Contains(expectedOutput, output); string binaryPath = Path.Combine(dir.Path, "temp.dll"); Assert.True(File.Exists(binaryPath) == !warnAsError); string pdbPath = Path.Combine(dir.Path, pdbName); Assert.True(File.Exists(pdbPath) == !warnAsError); string xmlDocFilePath = Path.Combine(dir.Path, docName); Assert.True(File.Exists(xmlDocFilePath) == !warnAsError); } [Theory] [InlineData(true)] [InlineData(false)] [WorkItem(37779, "https://github.com/dotnet/roslyn/issues/37779")] public void AnalyzerConfigSeverityEscalationToErrorDoesNotEmit(bool analyzerConfigSetToError) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { int _f; // CS0169: unused field }"); var docName = "temp.xml"; var pdbName = "temp.pdb"; var additionalArgs = new[] { $"/doc:{docName}", $"/pdb:{pdbName}", "/debug" }; if (analyzerConfigSetToError) { var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] dotnet_diagnostic.cs0169.severity = error"); additionalArgs = additionalArgs.Append("/analyzerconfig:" + analyzerConfig.Path).ToArray(); } var expectedErrorCount = analyzerConfigSetToError ? 1 : 0; var expectedWarningCount = !analyzerConfigSetToError ? 1 : 0; var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalArgs, expectedErrorCount: expectedErrorCount, expectedWarningCount: expectedWarningCount); var expectedOutput = analyzerConfigSetToError ? "error CS0169" : "warning CS0169"; Assert.Contains(expectedOutput, output); string binaryPath = Path.Combine(dir.Path, "temp.dll"); Assert.True(File.Exists(binaryPath) == !analyzerConfigSetToError); string pdbPath = Path.Combine(dir.Path, pdbName); Assert.True(File.Exists(pdbPath) == !analyzerConfigSetToError); string xmlDocFilePath = Path.Combine(dir.Path, docName); Assert.True(File.Exists(xmlDocFilePath) == !analyzerConfigSetToError); } [Theory] [InlineData(true)] [InlineData(false)] [WorkItem(37779, "https://github.com/dotnet/roslyn/issues/37779")] public void RulesetSeverityEscalationToErrorDoesNotEmit(bool rulesetSetToError) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { int _f; // CS0169: unused field }"); var docName = "temp.xml"; var pdbName = "temp.pdb"; var additionalArgs = new[] { $"/doc:{docName}", $"/pdb:{pdbName}", "/debug" }; if (rulesetSetToError) { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.CodeAnalysis"" RuleNamespace=""Microsoft.CodeAnalysis""> <Rule Id=""CS0169"" Action=""Error"" /> </Rules> </RuleSet> "; var rulesetFile = CreateRuleSetFile(source); additionalArgs = additionalArgs.Append("/ruleset:" + rulesetFile.Path).ToArray(); } var expectedErrorCount = rulesetSetToError ? 1 : 0; var expectedWarningCount = !rulesetSetToError ? 1 : 0; var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalArgs, expectedErrorCount: expectedErrorCount, expectedWarningCount: expectedWarningCount); var expectedOutput = rulesetSetToError ? "error CS0169" : "warning CS0169"; Assert.Contains(expectedOutput, output); string binaryPath = Path.Combine(dir.Path, "temp.dll"); Assert.True(File.Exists(binaryPath) == !rulesetSetToError); string pdbPath = Path.Combine(dir.Path, pdbName); Assert.True(File.Exists(pdbPath) == !rulesetSetToError); string xmlDocFilePath = Path.Combine(dir.Path, docName); Assert.True(File.Exists(xmlDocFilePath) == !rulesetSetToError); } [Theory] [InlineData(true)] [InlineData(false)] [WorkItem(37779, "https://github.com/dotnet/roslyn/issues/37779")] public void AnalyzerWarnAsErrorDoesNotEmit(bool warnAsError) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText("class C { }"); var additionalArgs = warnAsError ? new[] { "/warnaserror" } : null; var expectedErrorCount = warnAsError ? 1 : 0; var expectedWarningCount = !warnAsError ? 1 : 0; var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalArgs, expectedErrorCount: expectedErrorCount, expectedWarningCount: expectedWarningCount, analyzers: new[] { new WarningDiagnosticAnalyzer() }); var expectedDiagnosticSeverity = warnAsError ? "error" : "warning"; Assert.Contains($"{expectedDiagnosticSeverity} {WarningDiagnosticAnalyzer.Warning01.Id}", output); string binaryPath = Path.Combine(dir.Path, "temp.dll"); Assert.True(File.Exists(binaryPath) == !warnAsError); } // Currently, configuring no location diagnostics through editorconfig is not supported. [Theory(Skip = "https://github.com/dotnet/roslyn/issues/38042")] [CombinatorialData] public void AnalyzerConfigRespectedForNoLocationDiagnostic(ReportDiagnostic reportDiagnostic, bool isEnabledByDefault, bool noWarn, bool errorlog) { var analyzer = new AnalyzerWithNoLocationDiagnostics(isEnabledByDefault); TestAnalyzerConfigRespectedCore(analyzer, analyzer.Descriptor, reportDiagnostic, noWarn, errorlog); } [WorkItem(37876, "https://github.com/dotnet/roslyn/issues/37876")] [Theory] [CombinatorialData] public void AnalyzerConfigRespectedForDisabledByDefaultDiagnostic(ReportDiagnostic analyzerConfigSeverity, bool isEnabledByDefault, bool noWarn, bool errorlog) { var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault, defaultSeverity: DiagnosticSeverity.Warning); TestAnalyzerConfigRespectedCore(analyzer, analyzer.Descriptor, analyzerConfigSeverity, noWarn, errorlog); } private void TestAnalyzerConfigRespectedCore(DiagnosticAnalyzer analyzer, DiagnosticDescriptor descriptor, ReportDiagnostic analyzerConfigSeverity, bool noWarn, bool errorlog) { if (analyzerConfigSeverity == ReportDiagnostic.Default) { // "dotnet_diagnostic.ID.severity = default" is not supported. return; } var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@"class C { }"); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText($@" [*.cs] dotnet_diagnostic.{descriptor.Id}.severity = {analyzerConfigSeverity.ToAnalyzerConfigString()}"); var arguments = new[] { "/nologo", "/t:library", "/preferreduilang:en", "/analyzerconfig:" + analyzerConfig.Path, src.Path }; if (noWarn) { arguments = arguments.Append($"/nowarn:{descriptor.Id}"); } if (errorlog) { arguments = arguments.Append($"/errorlog:errorlog"); } var cmd = CreateCSharpCompiler(null, dir.Path, arguments, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(analyzer)); Assert.Equal(analyzerConfig.Path, Assert.Single(cmd.Arguments.AnalyzerConfigPaths)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); var expectedErrorCode = !noWarn && analyzerConfigSeverity == ReportDiagnostic.Error ? 1 : 0; Assert.Equal(expectedErrorCode, exitCode); // NOTE: Info diagnostics are only logged on command line when /errorlog is specified. See https://github.com/dotnet/roslyn/issues/42166 for details. if (!noWarn && (analyzerConfigSeverity == ReportDiagnostic.Error || analyzerConfigSeverity == ReportDiagnostic.Warn || (analyzerConfigSeverity == ReportDiagnostic.Info && errorlog))) { var prefix = analyzerConfigSeverity == ReportDiagnostic.Error ? "error" : analyzerConfigSeverity == ReportDiagnostic.Warn ? "warning" : "info"; Assert.Contains($"{prefix} {descriptor.Id}: {descriptor.MessageFormat}", outWriter.ToString()); } else { Assert.DoesNotContain(descriptor.Id.ToString(), outWriter.ToString()); } } [Fact] [WorkItem(3705, "https://github.com/dotnet/roslyn/issues/3705")] public void IsUserConfiguredGeneratedCodeInAnalyzerConfig() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { void M(C? c) { _ = c.ToString(); // warning CS8602: Dereference of a possibly null reference. } }"); var output = VerifyOutput(dir, src, additionalFlags: new[] { "/nullable" }, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); // warning CS8602: Dereference of a possibly null reference. Assert.Contains("warning CS8602", output, StringComparison.Ordinal); // generated_code = true var analyzerConfigFile = dir.CreateFile(".editorconfig"); var analyzerConfig = analyzerConfigFile.WriteAllText(@" [*.cs] generated_code = true"); output = VerifyOutput(dir, src, additionalFlags: new[] { "/nullable", "/analyzerconfig:" + analyzerConfig.Path }, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); Assert.DoesNotContain("warning CS8602", output, StringComparison.Ordinal); // warning CS8669: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. Auto-generated code requires an explicit '#nullable' directive in source. Assert.Contains("warning CS8669", output, StringComparison.Ordinal); // generated_code = false analyzerConfig = analyzerConfigFile.WriteAllText(@" [*.cs] generated_code = false"); output = VerifyOutput(dir, src, additionalFlags: new[] { "/nullable", "/analyzerconfig:" + analyzerConfig.Path }, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); // warning CS8602: Dereference of a possibly null reference. Assert.Contains("warning CS8602", output, StringComparison.Ordinal); // generated_code = auto analyzerConfig = analyzerConfigFile.WriteAllText(@" [*.cs] generated_code = auto"); output = VerifyOutput(dir, src, additionalFlags: new[] { "/nullable", "/analyzerconfig:" + analyzerConfig.Path }, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); // warning CS8602: Dereference of a possibly null reference. Assert.Contains("warning CS8602", output, StringComparison.Ordinal); } [WorkItem(42166, "https://github.com/dotnet/roslyn/issues/42166")] [CombinatorialData, Theory] public void TestAnalyzerFilteringBasedOnSeverity(DiagnosticSeverity defaultSeverity, bool errorlog) { // This test verifies that analyzer execution is skipped at build time for the following: // 1. Analyzer reporting Hidden diagnostics // 2. Analyzer reporting Info diagnostics, when /errorlog is not specified var analyzerShouldBeSkipped = defaultSeverity == DiagnosticSeverity.Hidden || defaultSeverity == DiagnosticSeverity.Info && !errorlog; // We use an analyzer that throws an exception on every analyzer callback. // So an AD0001 analyzer exception diagnostic is reported if analyzer executed, otherwise not. var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity, throwOnAllNamedTypes: true); var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@"class C { }"); var args = new[] { "/nologo", "/t:library", "/preferreduilang:en", src.Path }; if (errorlog) args = args.Append("/errorlog:errorlog"); var cmd = CreateCSharpCompiler(null, dir.Path, args, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(analyzer)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); var output = outWriter.ToString(); if (analyzerShouldBeSkipped) { Assert.Empty(output); } else { Assert.Contains("warning AD0001: Analyzer 'Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers+NamedTypeAnalyzerWithConfigurableEnabledByDefault' threw an exception of type 'System.NotImplementedException'", output, StringComparison.Ordinal); } } [WorkItem(47017, "https://github.com/dotnet/roslyn/issues/47017")] [CombinatorialData, Theory] public void TestWarnAsErrorMinusDoesNotEnableDisabledByDefaultAnalyzers(DiagnosticSeverity defaultSeverity, bool isEnabledByDefault) { // This test verifies that '/warnaserror-:DiagnosticId' does not affect if analyzers are executed or skipped.. // Setup the analyzer to always throw an exception on analyzer callbacks for cases where we expect analyzer execution to be skipped: // 1. Disabled by default analyzer, i.e. 'isEnabledByDefault == false'. // 2. Default severity Hidden/Info: We only execute analyzers reporting Warning/Error severity diagnostics on command line builds. var analyzerShouldBeSkipped = !isEnabledByDefault || defaultSeverity == DiagnosticSeverity.Hidden || defaultSeverity == DiagnosticSeverity.Info; var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault, defaultSeverity, throwOnAllNamedTypes: analyzerShouldBeSkipped); var diagnosticId = analyzer.Descriptor.Id; var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@"class C { }"); // Verify '/warnaserror-:DiagnosticId' behavior. var args = new[] { "/warnaserror+", $"/warnaserror-:{diagnosticId}", "/nologo", "/t:library", "/preferreduilang:en", src.Path }; var cmd = CreateCSharpCompiler(null, dir.Path, args, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(analyzer)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); var expectedExitCode = !analyzerShouldBeSkipped && defaultSeverity == DiagnosticSeverity.Error ? 1 : 0; Assert.Equal(expectedExitCode, exitCode); var output = outWriter.ToString(); if (analyzerShouldBeSkipped) { Assert.Empty(output); } else { var prefix = defaultSeverity == DiagnosticSeverity.Warning ? "warning" : "error"; Assert.Contains($"{prefix} {diagnosticId}: {analyzer.Descriptor.MessageFormat}", output); } } [WorkItem(49446, "https://github.com/dotnet/roslyn/issues/49446")] [Theory] // Verify '/warnaserror-:ID' prevents escalation to 'Error' when config file bumps severity to 'Warning' [InlineData(false, DiagnosticSeverity.Info, DiagnosticSeverity.Warning, DiagnosticSeverity.Error)] [InlineData(true, DiagnosticSeverity.Info, DiagnosticSeverity.Warning, DiagnosticSeverity.Warning)] // Verify '/warnaserror-:ID' prevents escalation to 'Error' when default severity is 'Warning' and no config file setting is specified. [InlineData(false, DiagnosticSeverity.Warning, null, DiagnosticSeverity.Error)] [InlineData(true, DiagnosticSeverity.Warning, null, DiagnosticSeverity.Warning)] // Verify '/warnaserror-:ID' prevents escalation to 'Error' when default severity is 'Warning' and config file bumps severity to 'Error' [InlineData(false, DiagnosticSeverity.Warning, DiagnosticSeverity.Error, DiagnosticSeverity.Error)] [InlineData(true, DiagnosticSeverity.Warning, DiagnosticSeverity.Error, DiagnosticSeverity.Warning)] // Verify '/warnaserror-:ID' has no effect when default severity is 'Info' and config file bumps severity to 'Error' [InlineData(false, DiagnosticSeverity.Info, DiagnosticSeverity.Error, DiagnosticSeverity.Error)] [InlineData(true, DiagnosticSeverity.Info, DiagnosticSeverity.Error, DiagnosticSeverity.Error)] public void TestWarnAsErrorMinusDoesNotNullifyEditorConfig( bool warnAsErrorMinus, DiagnosticSeverity defaultSeverity, DiagnosticSeverity? severityInConfigFile, DiagnosticSeverity expectedEffectiveSeverity) { var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity, throwOnAllNamedTypes: false); var diagnosticId = analyzer.Descriptor.Id; var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@"class C { }"); var additionalFlags = new[] { "/warnaserror+" }; if (severityInConfigFile.HasValue) { var severityString = DiagnosticDescriptor.MapSeverityToReport(severityInConfigFile.Value).ToAnalyzerConfigString(); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText($@" [*.cs] dotnet_diagnostic.{diagnosticId}.severity = {severityString}"); additionalFlags = additionalFlags.Append($"/analyzerconfig:{analyzerConfig.Path}").ToArray(); } if (warnAsErrorMinus) { additionalFlags = additionalFlags.Append($"/warnaserror-:{diagnosticId}").ToArray(); } int expectedWarningCount = 0, expectedErrorCount = 0; switch (expectedEffectiveSeverity) { case DiagnosticSeverity.Warning: expectedWarningCount = 1; break; case DiagnosticSeverity.Error: expectedErrorCount = 1; break; default: throw ExceptionUtilities.UnexpectedValue(expectedEffectiveSeverity); } VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, expectedWarningCount: expectedWarningCount, expectedErrorCount: expectedErrorCount, additionalFlags: additionalFlags, analyzers: new[] { analyzer }); } [Fact] public void SourceGenerators_EmbeddedSources() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedSource = "public class D { }"; var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/debug:embedded", "/out:embed.exe" }, generators: new[] { generator }, analyzers: null); var generatorPrefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator); ValidateEmbeddedSources_Portable(new Dictionary<string, string> { { Path.Combine(dir.Path, generatorPrefix, $"generatedSource.cs"), generatedSource } }, dir, true); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Theory, CombinatorialData] [WorkItem(40926, "https://github.com/dotnet/roslyn/issues/40926")] public void TestSourceGeneratorsWithAnalyzers(bool includeCurrentAssemblyAsAnalyzerReference, bool skipAnalyzers) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedSource = "public class D { }"; var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs"); // 'skipAnalyzers' should have no impact on source generator execution, but should prevent analyzer execution. var skipAnalyzersFlag = "/skipAnalyzers" + (skipAnalyzers ? "+" : "-"); // Verify analyzers were executed only if both the following conditions were satisfied: // 1. Current assembly was added as an analyzer reference, i.e. "includeCurrentAssemblyAsAnalyzerReference = true" and // 2. We did not explicitly request skipping analyzers, i.e. "skipAnalyzers = false". var expectedAnalyzerExecution = includeCurrentAssemblyAsAnalyzerReference && !skipAnalyzers; // 'WarningDiagnosticAnalyzer' generates a warning for each named type. // We expect two warnings for this test: type "C" defined in source and the source generator defined type. // Additionally, we also have an analyzer that generates "warning CS8032: An instance of analyzer cannot be created" // CS8032 is generated with includeCurrentAssemblyAsAnalyzerReference even when we are skipping analyzers as we will instantiate all analyzers, just not execute them. var expectedWarningCount = expectedAnalyzerExecution ? 3 : (includeCurrentAssemblyAsAnalyzerReference ? 1 : 0); var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference, expectedWarningCount: expectedWarningCount, additionalFlags: new[] { "/debug:embedded", "/out:embed.exe", skipAnalyzersFlag }, generators: new[] { generator }); // Verify source generator was executed, regardless of the value of 'skipAnalyzers'. var generatorPrefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator); ValidateEmbeddedSources_Portable(new Dictionary<string, string> { { Path.Combine(dir.Path, generatorPrefix, "generatedSource.cs"), generatedSource } }, dir, true); if (expectedAnalyzerExecution) { Assert.Contains("warning Warning01", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); } else if (includeCurrentAssemblyAsAnalyzerReference) { Assert.Contains("warning CS8032", output, StringComparison.Ordinal); } else { Assert.Empty(output); } // Clean up temp files CleanupAllGeneratedFiles(src.Path); } [Theory] [InlineData("partial class D {}", "file1.cs", "partial class E {}", "file2.cs")] // different files, different names [InlineData("partial class D {}", "file1.cs", "partial class E {}", "file1.cs")] // different files, same names [InlineData("partial class D {}", "file1.cs", "partial class D {}", "file2.cs")] // same files, different names [InlineData("partial class D {}", "file1.cs", "partial class D {}", "file1.cs")] // same files, same names [InlineData("partial class D {}", "file1.cs", "", "file2.cs")] // empty second file public void SourceGenerators_EmbeddedSources_MultipleFiles(string source1, string source1Name, string source2, string source2Name) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generator = new SingleFileTestGenerator(source1, source1Name); var generator2 = new SingleFileTestGenerator2(source2, source2Name); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/debug:embedded", "/out:embed.exe" }, generators: new[] { generator, generator2 }, analyzers: null); var generator1Prefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator); var generator2Prefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator2); ValidateEmbeddedSources_Portable(new Dictionary<string, string> { { Path.Combine(dir.Path, generator1Prefix, source1Name), source1}, { Path.Combine(dir.Path, generator2Prefix, source2Name), source2}, }, dir, true); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Fact] public void SourceGenerators_WriteGeneratedSources() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedDir = dir.CreateDirectory("generated"); var generatedSource = "public class D { }"; var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator }, analyzers: null); var generatorPrefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator); ValidateWrittenSources(new() { { Path.Combine(generatedDir.Path, generatorPrefix), new() { { "generatedSource.cs", generatedSource } } } }); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Fact] public void SourceGenerators_OverwriteGeneratedSources() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedDir = dir.CreateDirectory("generated"); var generatedSource1 = "class D { } class E { }"; var generator1 = new SingleFileTestGenerator(generatedSource1, "generatedSource.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator1 }, analyzers: null); var generatorPrefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator1); ValidateWrittenSources(new() { { Path.Combine(generatedDir.Path, generatorPrefix), new() { { "generatedSource.cs", generatedSource1 } } } }); var generatedSource2 = "public class D { }"; var generator2 = new SingleFileTestGenerator(generatedSource2, "generatedSource.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator2 }, analyzers: null); ValidateWrittenSources(new() { { Path.Combine(generatedDir.Path, generatorPrefix), new() { { "generatedSource.cs", generatedSource2 } } } }); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Theory] [InlineData("partial class D {}", "file1.cs", "partial class E {}", "file2.cs")] // different files, different names [InlineData("partial class D {}", "file1.cs", "partial class E {}", "file1.cs")] // different files, same names [InlineData("partial class D {}", "file1.cs", "partial class D {}", "file2.cs")] // same files, different names [InlineData("partial class D {}", "file1.cs", "partial class D {}", "file1.cs")] // same files, same names [InlineData("partial class D {}", "file1.cs", "", "file2.cs")] // empty second file public void SourceGenerators_WriteGeneratedSources_MultipleFiles(string source1, string source1Name, string source2, string source2Name) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedDir = dir.CreateDirectory("generated"); var generator = new SingleFileTestGenerator(source1, source1Name); var generator2 = new SingleFileTestGenerator2(source2, source2Name); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator, generator2 }, analyzers: null); var generator1Prefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator); var generator2Prefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator2); ValidateWrittenSources(new() { { Path.Combine(generatedDir.Path, generator1Prefix), new() { { source1Name, source1 } } }, { Path.Combine(generatedDir.Path, generator2Prefix), new() { { source2Name, source2 } } } }); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [ConditionalFact(typeof(DesktopClrOnly))] //CoreCLR doesn't support SxS loading [WorkItem(47990, "https://github.com/dotnet/roslyn/issues/47990")] public void SourceGenerators_SxS_AssemblyLoading() { // compile the generators var dir = Temp.CreateDirectory(); var snk = Temp.CreateFile("TestKeyPair_", ".snk", dir.Path).WriteAllBytes(TestResources.General.snKey); var src = dir.CreateFile("generator.cs"); var virtualSnProvider = new DesktopStrongNameProvider(ImmutableArray.Create(dir.Path)); string createGenerator(string version) { var generatorSource = $@" using Microsoft.CodeAnalysis; [assembly:System.Reflection.AssemblyVersion(""{version}"")] [Generator] public class TestGenerator : ISourceGenerator {{ public void Execute(GeneratorExecutionContext context) {{ context.AddSource(""generatedSource.cs"", ""//from version {version}""); }} public void Initialize(GeneratorInitializationContext context) {{ }} }}"; var path = Path.Combine(dir.Path, Guid.NewGuid().ToString() + ".dll"); var comp = CreateEmptyCompilation(source: generatorSource, references: TargetFrameworkUtil.NetStandard20References.Add(MetadataReference.CreateFromAssemblyInternal(typeof(ISourceGenerator).Assembly)), options: TestOptions.DebugDll.WithCryptoKeyFile(Path.GetFileName(snk.Path)).WithStrongNameProvider(virtualSnProvider), assemblyName: "generator"); comp.VerifyDiagnostics(); comp.Emit(path); return path; } var gen1 = createGenerator("1.0.0.0"); var gen2 = createGenerator("2.0.0.0"); var generatedDir = dir.CreateDirectory("generated"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, "/analyzer:" + gen1, "/analyzer:" + gen2 }.ToArray()); // This is wrong! Both generators are writing the same file out, over the top of each other // See https://github.com/dotnet/roslyn/issues/47990 ValidateWrittenSources(new() { // { Path.Combine(generatedDir.Path, "generator", "TestGenerator"), new() { { "generatedSource.cs", "//from version 1.0.0.0" } } }, { Path.Combine(generatedDir.Path, "generator", "TestGenerator"), new() { { "generatedSource.cs", "//from version 2.0.0.0" } } } }); } [Fact] public void SourceGenerators_DoNotWriteGeneratedSources_When_No_Directory_Supplied() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedDir = dir.CreateDirectory("generated"); var generatedSource = "public class D { }"; var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator }, analyzers: null); ValidateWrittenSources(new() { { generatedDir.Path, new() } }); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Fact] public void SourceGenerators_Error_When_GeneratedDir_NotExist() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedDirPath = Path.Combine(dir.Path, "noexist"); var generatedSource = "public class D { }"; var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs"); var output = VerifyOutput(dir, src, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDirPath, "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator }, analyzers: null); Assert.Contains("CS0016:", output); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Fact] public void SourceGenerators_GeneratedDir_Has_Spaces() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedDir = dir.CreateDirectory("generated files"); var generatedSource = "public class D { }"; var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator }, analyzers: null); var generatorPrefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator); ValidateWrittenSources(new() { { Path.Combine(generatedDir.Path, generatorPrefix), new() { { "generatedSource.cs", generatedSource } } } }); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Fact] public void ParseGeneratedFilesOut() { string root = PathUtilities.IsUnixLikePlatform ? "/" : "c:\\"; string baseDirectory = Path.Combine(root, "abc", "def"); var parsedArgs = DefaultParse(new[] { @"/generatedfilesout:", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for '/generatedfilesout:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/generatedfilesout:")); Assert.Null(parsedArgs.GeneratedFilesOutputDirectory); parsedArgs = DefaultParse(new[] { @"/generatedfilesout:""""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for '/generatedfilesout:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/generatedfilesout:\"\"")); Assert.Null(parsedArgs.GeneratedFilesOutputDirectory); parsedArgs = DefaultParse(new[] { @"/generatedfilesout:outdir", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(baseDirectory, "outdir"), parsedArgs.GeneratedFilesOutputDirectory); parsedArgs = DefaultParse(new[] { @"/generatedfilesout:""outdir""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(baseDirectory, "outdir"), parsedArgs.GeneratedFilesOutputDirectory); parsedArgs = DefaultParse(new[] { @"/generatedfilesout:out dir", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(baseDirectory, "out dir"), parsedArgs.GeneratedFilesOutputDirectory); parsedArgs = DefaultParse(new[] { @"/generatedfilesout:""out dir""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(baseDirectory, "out dir"), parsedArgs.GeneratedFilesOutputDirectory); var absPath = Path.Combine(root, "outdir"); parsedArgs = DefaultParse(new[] { $@"/generatedfilesout:{absPath}", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(absPath, parsedArgs.GeneratedFilesOutputDirectory); parsedArgs = DefaultParse(new[] { $@"/generatedfilesout:""{absPath}""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(absPath, parsedArgs.GeneratedFilesOutputDirectory); absPath = Path.Combine(root, "generated files"); parsedArgs = DefaultParse(new[] { $@"/generatedfilesout:{absPath}", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(absPath, parsedArgs.GeneratedFilesOutputDirectory); parsedArgs = DefaultParse(new[] { $@"/generatedfilesout:""{absPath}""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(absPath, parsedArgs.GeneratedFilesOutputDirectory); } [Fact] public void SourceGenerators_Error_When_NoDirectoryArgumentGiven() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var output = VerifyOutput(dir, src, expectedErrorCount: 2, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:", "/langversion:preview", "/out:embed.exe" }); Assert.Contains("error CS2006: Command-line syntax error: Missing '<text>' for '/generatedfilesout:' option", output); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Fact] public void SourceGenerators_ReportedWrittenFiles_To_TouchedFilesLogger() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedDir = dir.CreateDirectory("generated"); var generatedSource = "public class D { }"; var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, $"/touchedfiles:{dir.Path}/touched", "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator }, analyzers: null); var touchedFiles = Directory.GetFiles(dir.Path, "touched*"); Assert.Equal(2, touchedFiles.Length); string[] writtenText = File.ReadAllLines(Path.Combine(dir.Path, "touched.write")); Assert.Equal(2, writtenText.Length); Assert.EndsWith("EMBED.EXE", writtenText[0], StringComparison.OrdinalIgnoreCase); Assert.EndsWith("GENERATEDSOURCE.CS", writtenText[1], StringComparison.OrdinalIgnoreCase); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Fact] [WorkItem(44087, "https://github.com/dotnet/roslyn/issues/44087")] public void SourceGeneratorsAndAnalyzerConfig() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] key = value"); var generator = new SingleFileTestGenerator("public class D {}", "generated.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/analyzerconfig:" + analyzerConfig.Path }, generators: new[] { generator }, analyzers: null); } [Fact] public void SourceGeneratorsCanReadAnalyzerConfig() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var analyzerConfig1 = dir.CreateFile(".globaleditorconfig").WriteAllText(@" is_global = true key1 = value1 [*.cs] key2 = value2 [*.vb] key3 = value3"); var analyzerConfig2 = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] key4 = value4 [*.vb] key5 = value5"); var subDir = dir.CreateDirectory("subDir"); var analyzerConfig3 = subDir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] key6 = value6 [*.vb] key7 = value7"); var generator = new CallbackGenerator((ic) => { }, (gc) => { // can get the global options var globalOptions = gc.AnalyzerConfigOptions.GlobalOptions; Assert.True(globalOptions.TryGetValue("key1", out var keyValue)); Assert.Equal("value1", keyValue); Assert.False(globalOptions.TryGetValue("key2", out _)); Assert.False(globalOptions.TryGetValue("key3", out _)); Assert.False(globalOptions.TryGetValue("key4", out _)); Assert.False(globalOptions.TryGetValue("key5", out _)); Assert.False(globalOptions.TryGetValue("key6", out _)); Assert.False(globalOptions.TryGetValue("key7", out _)); // can get the options for class C var classOptions = gc.AnalyzerConfigOptions.GetOptions(gc.Compilation.SyntaxTrees.First()); Assert.True(classOptions.TryGetValue("key1", out keyValue)); Assert.Equal("value1", keyValue); Assert.False(classOptions.TryGetValue("key2", out _)); Assert.False(classOptions.TryGetValue("key3", out _)); Assert.True(classOptions.TryGetValue("key4", out keyValue)); Assert.Equal("value4", keyValue); Assert.False(classOptions.TryGetValue("key5", out _)); Assert.False(classOptions.TryGetValue("key6", out _)); Assert.False(classOptions.TryGetValue("key7", out _)); }); var args = new[] { "/analyzerconfig:" + analyzerConfig1.Path, "/analyzerconfig:" + analyzerConfig2.Path, "/analyzerconfig:" + analyzerConfig3.Path, "/t:library", src.Path }; var cmd = CreateCSharpCompiler(null, dir.Path, args, generators: ImmutableArray.Create<ISourceGenerator>(generator)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); // test for both the original tree and the generated one var provider = cmd.AnalyzerOptions.AnalyzerConfigOptionsProvider; // get the global options var globalOptions = provider.GlobalOptions; Assert.True(globalOptions.TryGetValue("key1", out var keyValue)); Assert.Equal("value1", keyValue); Assert.False(globalOptions.TryGetValue("key2", out _)); Assert.False(globalOptions.TryGetValue("key3", out _)); Assert.False(globalOptions.TryGetValue("key4", out _)); Assert.False(globalOptions.TryGetValue("key5", out _)); Assert.False(globalOptions.TryGetValue("key6", out _)); Assert.False(globalOptions.TryGetValue("key7", out _)); // get the options for class C var classOptions = provider.GetOptions(cmd.Compilation.SyntaxTrees.First()); Assert.True(classOptions.TryGetValue("key1", out keyValue)); Assert.Equal("value1", keyValue); Assert.False(classOptions.TryGetValue("key2", out _)); Assert.False(classOptions.TryGetValue("key3", out _)); Assert.True(classOptions.TryGetValue("key4", out keyValue)); Assert.Equal("value4", keyValue); Assert.False(classOptions.TryGetValue("key5", out _)); Assert.False(classOptions.TryGetValue("key6", out _)); Assert.False(classOptions.TryGetValue("key7", out _)); // get the options for generated class D var generatedOptions = provider.GetOptions(cmd.Compilation.SyntaxTrees.Last()); Assert.True(generatedOptions.TryGetValue("key1", out keyValue)); Assert.Equal("value1", keyValue); Assert.False(generatedOptions.TryGetValue("key2", out _)); Assert.False(generatedOptions.TryGetValue("key3", out _)); Assert.True(classOptions.TryGetValue("key4", out keyValue)); Assert.Equal("value4", keyValue); Assert.False(generatedOptions.TryGetValue("key5", out _)); Assert.False(generatedOptions.TryGetValue("key6", out _)); Assert.False(generatedOptions.TryGetValue("key7", out _)); } [Theory] [CombinatorialData] public void SourceGeneratorsRunRegardlessOfLanguageVersion(LanguageVersion version) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@"class C {}"); var generator = new CallbackGenerator(i => { }, e => throw null); var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:" + version.ToDisplayString() }, generators: new[] { generator }, expectedWarningCount: 1, expectedErrorCount: 1, expectedExitCode: 0); Assert.Contains("CS8785: Generator 'CallbackGenerator' failed to generate source.", output); } [DiagnosticAnalyzer(LanguageNames.CSharp)] private sealed class FieldAnalyzer : DiagnosticAnalyzer { private static readonly DiagnosticDescriptor _rule = new DiagnosticDescriptor("Id", "Title", "Message", "Category", DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(_rule); public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(AnalyzeFieldDeclaration, SyntaxKind.FieldDeclaration); } private static void AnalyzeFieldDeclaration(SyntaxNodeAnalysisContext context) { } } [Fact] [WorkItem(44000, "https://github.com/dotnet/roslyn/issues/44000")] public void TupleField_ForceComplete() { var source = @"namespace System { public struct ValueTuple<T1> { public T1 Item1; public ValueTuple(T1 item1) { Item1 = item1; } } }"; var srcFile = Temp.CreateFile().WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler( null, WorkingDirectory, new[] { "/nologo", "/t:library", srcFile.Path }, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new FieldAnalyzer())); // at least one analyzer required var exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var output = outWriter.ToString(); Assert.Empty(output); CleanupAllGeneratedFiles(srcFile.Path); } [Fact] public void GlobalAnalyzerConfigsAllowedInSameDir() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@" class C { int _f; }"); var configText = @" is_global = true "; var analyzerConfig1 = dir.CreateFile("analyzerconfig1").WriteAllText(configText); var analyzerConfig2 = dir.CreateFile("analyzerconfig2").WriteAllText(configText); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/preferreduilang:en", "/analyzerconfig:" + analyzerConfig1.Path, "/analyzerconfig:" + analyzerConfig2.Path, src.Path }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); } [Fact] public void GlobalAnalyzerConfigMultipleSetKeys() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var analyzerConfigFile = dir.CreateFile(".globalconfig"); var analyzerConfig = analyzerConfigFile.WriteAllText(@" is_global = true global_level = 100 option1 = abc"); var analyzerConfigFile2 = dir.CreateFile(".globalconfig2"); var analyzerConfig2 = analyzerConfigFile2.WriteAllText(@" is_global = true global_level = 100 option1 = def"); var output = VerifyOutput(dir, src, additionalFlags: new[] { "/analyzerconfig:" + analyzerConfig.Path + "," + analyzerConfig2.Path }, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); // warning MultipleGlobalAnalyzerKeys: Multiple global analyzer config files set the same key 'option1' in section 'Global Section'. It has been unset. Key was set by the following files: ... Assert.Contains("MultipleGlobalAnalyzerKeys:", output, StringComparison.Ordinal); Assert.Contains("'option1'", output, StringComparison.Ordinal); Assert.Contains("'Global Section'", output, StringComparison.Ordinal); analyzerConfig = analyzerConfigFile.WriteAllText(@" is_global = true global_level = 100 [/file.cs] option1 = abc"); analyzerConfig2 = analyzerConfigFile2.WriteAllText(@" is_global = true global_level = 100 [/file.cs] option1 = def"); output = VerifyOutput(dir, src, additionalFlags: new[] { "/analyzerconfig:" + analyzerConfig.Path + "," + analyzerConfig2.Path }, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); // warning MultipleGlobalAnalyzerKeys: Multiple global analyzer config files set the same key 'option1' in section 'file.cs'. It has been unset. Key was set by the following files: ... Assert.Contains("MultipleGlobalAnalyzerKeys:", output, StringComparison.Ordinal); Assert.Contains("'option1'", output, StringComparison.Ordinal); Assert.Contains("'/file.cs'", output, StringComparison.Ordinal); } [Fact] public void GlobalAnalyzerConfigWithOptions() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@" class C { }"); var additionalFile = dir.CreateFile("file.txt"); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] key1 = value1 [*.txt] key2 = value2"); var globalConfig = dir.CreateFile(".globalconfig").WriteAllText(@" is_global = true key3 = value3"); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/analyzerconfig:" + analyzerConfig.Path, "/analyzerconfig:" + globalConfig.Path, "/analyzer:" + Assembly.GetExecutingAssembly().Location, "/nowarn:8032,Warning01", "/additionalfile:" + additionalFile.Path, src.Path }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal("", outWriter.ToString()); Assert.Equal(0, exitCode); var comp = cmd.Compilation; var tree = comp.SyntaxTrees.Single(); var provider = cmd.AnalyzerOptions.AnalyzerConfigOptionsProvider; var options = provider.GetOptions(tree); Assert.NotNull(options); Assert.True(options.TryGetValue("key1", out string val)); Assert.Equal("value1", val); Assert.False(options.TryGetValue("key2", out _)); Assert.True(options.TryGetValue("key3", out val)); Assert.Equal("value3", val); options = provider.GetOptions(cmd.AnalyzerOptions.AdditionalFiles.Single()); Assert.NotNull(options); Assert.False(options.TryGetValue("key1", out _)); Assert.True(options.TryGetValue("key2", out val)); Assert.Equal("value2", val); Assert.True(options.TryGetValue("key3", out val)); Assert.Equal("value3", val); options = provider.GlobalOptions; Assert.NotNull(options); Assert.False(options.TryGetValue("key1", out _)); Assert.False(options.TryGetValue("key2", out _)); Assert.True(options.TryGetValue("key3", out val)); Assert.Equal("value3", val); } [Fact] [WorkItem(44087, "https://github.com/dotnet/roslyn/issues/44804")] public void GlobalAnalyzerConfigDiagnosticOptionsCanBeOverridenByCommandLine() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { void M() { label1:; } }"); var globalConfig = dir.CreateFile(".globalconfig").WriteAllText(@" is_global = true dotnet_diagnostic.CS0164.severity = error; "); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] dotnet_diagnostic.CS0164.severity = warning; "); var none = Array.Empty<TempFile>(); var globalOnly = new[] { globalConfig }; var globalAndSpecific = new[] { globalConfig, analyzerConfig }; // by default a warning, which can be suppressed via cmdline verify(configs: none, expectedWarnings: 1); verify(configs: none, noWarn: "CS0164", expectedWarnings: 0); // the global analyzer config ups the warning to an error, but the cmdline setting overrides it verify(configs: globalOnly, expectedErrors: 1); verify(configs: globalOnly, noWarn: "CS0164", expectedWarnings: 0); verify(configs: globalOnly, noWarn: "164", expectedWarnings: 0); // cmdline can be shortened, but still works // the editor config downgrades the error back to warning, but the cmdline setting overrides it verify(configs: globalAndSpecific, expectedWarnings: 1); verify(configs: globalAndSpecific, noWarn: "CS0164", expectedWarnings: 0); void verify(TempFile[] configs, int expectedWarnings = 0, int expectedErrors = 0, string noWarn = "0") => VerifyOutput(dir, src, expectedErrorCount: expectedErrors, expectedWarningCount: expectedWarnings, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: null, additionalFlags: configs.SelectAsArray(c => "/analyzerconfig:" + c.Path) .Add("/noWarn:" + noWarn).ToArray()); } [Fact] [WorkItem(44087, "https://github.com/dotnet/roslyn/issues/44804")] public void GlobalAnalyzerConfigSpecificDiagnosticOptionsOverrideGeneralCommandLineOptions() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { void M() { label1:; } }"); var globalConfig = dir.CreateFile(".globalconfig").WriteAllText($@" is_global = true dotnet_diagnostic.CS0164.severity = none; "); VerifyOutput(dir, src, additionalFlags: new[] { "/warnaserror+", "/analyzerconfig:" + globalConfig.Path }, includeCurrentAssemblyAsAnalyzerReference: false); } [Theory, CombinatorialData] [WorkItem(43051, "https://github.com/dotnet/roslyn/issues/43051")] public void WarnAsErrorIsRespectedForForWarningsConfiguredInRulesetOrGlobalConfig(bool useGlobalConfig) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { void M() { label1:; } }"); var additionalFlags = new[] { "/warnaserror+" }; if (useGlobalConfig) { var globalConfig = dir.CreateFile(".globalconfig").WriteAllText($@" is_global = true dotnet_diagnostic.CS0164.severity = warning; "); additionalFlags = additionalFlags.Append("/analyzerconfig:" + globalConfig.Path).ToArray(); } else { string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""15.0""> <Rules AnalyzerId=""Compiler"" RuleNamespace=""Compiler""> <Rule Id=""CS0164"" Action=""Warning"" /> </Rules> </RuleSet> "; _ = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); additionalFlags = additionalFlags.Append("/ruleset:Rules.ruleset").ToArray(); } VerifyOutput(dir, src, additionalFlags: additionalFlags, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); } [Fact] [WorkItem(44087, "https://github.com/dotnet/roslyn/issues/44804")] public void GlobalAnalyzerConfigSectionsDoNotOverrideCommandLine() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { void M() { label1:; } }"); var globalConfig = dir.CreateFile(".globalconfig").WriteAllText($@" is_global = true [{PathUtilities.NormalizeWithForwardSlash(src.Path)}] dotnet_diagnostic.CS0164.severity = error; "); VerifyOutput(dir, src, additionalFlags: new[] { "/nowarn:0164", "/analyzerconfig:" + globalConfig.Path }, expectedErrorCount: 0, includeCurrentAssemblyAsAnalyzerReference: false); } [Fact] [WorkItem(44087, "https://github.com/dotnet/roslyn/issues/44804")] public void GlobalAnalyzerConfigCanSetDiagnosticWithNoLocation() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@" class C { }"); var globalConfig = dir.CreateFile(".globalconfig").WriteAllText(@" is_global = true dotnet_diagnostic.Warning01.severity = error; "); VerifyOutput(dir, src, additionalFlags: new[] { "/analyzerconfig:" + globalConfig.Path }, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: new WarningDiagnosticAnalyzer()); VerifyOutput(dir, src, additionalFlags: new[] { "/nowarn:Warning01", "/analyzerconfig:" + globalConfig.Path }, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: new WarningDiagnosticAnalyzer()); } [Theory, CombinatorialData] public void TestAdditionalFileAnalyzer(bool registerFromInitialize) { var srcDirectory = Temp.CreateDirectory(); var source = "class C { }"; var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); var additionalText = "Additional Text"; var additionalFile = srcDirectory.CreateFile("b.txt"); additionalFile.WriteAllText(additionalText); var diagnosticSpan = new TextSpan(2, 2); var analyzer = new AdditionalFileAnalyzer(registerFromInitialize, diagnosticSpan); var output = VerifyOutput(srcDirectory, srcFile, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/additionalfile:" + additionalFile.Path }, analyzers: analyzer); Assert.Contains("b.txt(1,3): warning ID0001", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcDirectory.Path); } [Theory] // "/warnaserror" tests [InlineData(/*analyzerConfigSeverity*/"warning", "/warnaserror", /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/"error", "/warnaserror", /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, "/warnaserror", /*expectError*/true, /*expectWarning*/false)] // "/warnaserror:CS0169" tests [InlineData(/*analyzerConfigSeverity*/"warning", "/warnaserror:CS0169", /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/"error", "/warnaserror:CS0169", /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, "/warnaserror:CS0169", /*expectError*/true, /*expectWarning*/false)] // "/nowarn" tests [InlineData(/*analyzerConfigSeverity*/"warning", "/nowarn:CS0169", /*expectError*/false, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/"error", "/nowarn:CS0169", /*expectError*/false, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, "/nowarn:CS0169", /*expectError*/false, /*expectWarning*/false)] // Neither "/nowarn" nor "/warnaserror" tests [InlineData(/*analyzerConfigSeverity*/"warning", /*additionalArg*/null, /*expectError*/false, /*expectWarning*/true)] [InlineData(/*analyzerConfigSeverity*/"error", /*additionalArg*/null, /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, /*additionalArg*/null, /*expectError*/false, /*expectWarning*/true)] [WorkItem(43051, "https://github.com/dotnet/roslyn/issues/43051")] public void TestCompilationOptionsOverrideAnalyzerConfig_CompilerWarning(string analyzerConfigSeverity, string additionalArg, bool expectError, bool expectWarning) { var src = @" class C { int _f; // CS0169: unused field }"; TestCompilationOptionsOverrideAnalyzerConfigCore(src, diagnosticId: "CS0169", analyzerConfigSeverity, additionalArg, expectError, expectWarning); } [Theory] // "/warnaserror" tests [InlineData(/*analyzerConfigSeverity*/"warning", "/warnaserror", /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/"error", "/warnaserror", /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, "/warnaserror", /*expectError*/true, /*expectWarning*/false)] // "/warnaserror:DiagnosticId" tests [InlineData(/*analyzerConfigSeverity*/"warning", "/warnaserror:" + CompilationAnalyzerWithSeverity.DiagnosticId, /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/"error", "/warnaserror:" + CompilationAnalyzerWithSeverity.DiagnosticId, /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, "/warnaserror:" + CompilationAnalyzerWithSeverity.DiagnosticId, /*expectError*/true, /*expectWarning*/false)] // "/nowarn" tests [InlineData(/*analyzerConfigSeverity*/"warning", "/nowarn:" + CompilationAnalyzerWithSeverity.DiagnosticId, /*expectError*/false, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/"error", "/nowarn:" + CompilationAnalyzerWithSeverity.DiagnosticId, /*expectError*/false, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, "/nowarn:" + CompilationAnalyzerWithSeverity.DiagnosticId, /*expectError*/false, /*expectWarning*/false)] // Neither "/nowarn" nor "/warnaserror" tests [InlineData(/*analyzerConfigSeverity*/"warning", /*additionalArg*/null, /*expectError*/false, /*expectWarning*/true)] [InlineData(/*analyzerConfigSeverity*/"error", /*additionalArg*/null, /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, /*additionalArg*/null, /*expectError*/false, /*expectWarning*/true)] [WorkItem(43051, "https://github.com/dotnet/roslyn/issues/43051")] public void TestCompilationOptionsOverrideAnalyzerConfig_AnalyzerWarning(string analyzerConfigSeverity, string additionalArg, bool expectError, bool expectWarning) { var analyzer = new CompilationAnalyzerWithSeverity(DiagnosticSeverity.Warning, configurable: true); var src = @"class C { }"; TestCompilationOptionsOverrideAnalyzerConfigCore(src, CompilationAnalyzerWithSeverity.DiagnosticId, analyzerConfigSeverity, additionalArg, expectError, expectWarning, analyzer); } private void TestCompilationOptionsOverrideAnalyzerConfigCore( string source, string diagnosticId, string analyzerConfigSeverity, string additionalArg, bool expectError, bool expectWarning, params DiagnosticAnalyzer[] analyzers) { Assert.True(!expectError || !expectWarning); var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(source); var additionalArgs = Array.Empty<string>(); if (analyzerConfigSeverity != null) { var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText($@" [*.cs] dotnet_diagnostic.{diagnosticId}.severity = {analyzerConfigSeverity}"); additionalArgs = additionalArgs.Append("/analyzerconfig:" + analyzerConfig.Path).ToArray(); } if (!string.IsNullOrEmpty(additionalArg)) { additionalArgs = additionalArgs.Append(additionalArg); } var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalArgs, expectedErrorCount: expectError ? 1 : 0, expectedWarningCount: expectWarning ? 1 : 0, analyzers: analyzers); if (expectError) { Assert.Contains($"error {diagnosticId}", output); } else if (expectWarning) { Assert.Contains($"warning {diagnosticId}", output); } else { Assert.DoesNotContain(diagnosticId, output); } } [ConditionalFact(typeof(CoreClrOnly), Reason = "Can't load a coreclr targeting generator on net framework / mono")] public void TestGeneratorsCantTargetNetFramework() { var directory = Temp.CreateDirectory(); var src = directory.CreateFile("test.cs").WriteAllText(@" class C { }"); // core var coreGenerator = emitGenerator(".NETCoreApp,Version=v5.0"); VerifyOutput(directory, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/analyzer:" + coreGenerator }); // netstandard var nsGenerator = emitGenerator(".NETStandard,Version=v2.0"); VerifyOutput(directory, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/analyzer:" + nsGenerator }); // no target var ntGenerator = emitGenerator(targetFramework: null); VerifyOutput(directory, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/analyzer:" + ntGenerator }); // framework var frameworkGenerator = emitGenerator(".NETFramework,Version=v4.7.2"); var output = VerifyOutput(directory, src, expectedWarningCount: 2, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/analyzer:" + frameworkGenerator }); Assert.Contains("CS8850", output); // ref's net fx Assert.Contains("CS8033", output); // no analyzers in assembly // framework, suppressed output = VerifyOutput(directory, src, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/nowarn:CS8850", "/analyzer:" + frameworkGenerator }); Assert.Contains("CS8033", output); VerifyOutput(directory, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/nowarn:CS8850,CS8033", "/analyzer:" + frameworkGenerator }); string emitGenerator(string targetFramework) { string targetFrameworkAttributeText = targetFramework is object ? $"[assembly: System.Runtime.Versioning.TargetFramework(\"{targetFramework}\")]" : string.Empty; string generatorSource = $@" using Microsoft.CodeAnalysis; {targetFrameworkAttributeText} [Generator] public class Generator : ISourceGenerator {{ public void Execute(GeneratorExecutionContext context) {{ }} public void Initialize(GeneratorInitializationContext context) {{ }} }}"; var directory = Temp.CreateDirectory(); var generatorPath = Path.Combine(directory.Path, "generator.dll"); var compilation = CSharpCompilation.Create($"generator", new[] { CSharpSyntaxTree.ParseText(generatorSource) }, TargetFrameworkUtil.GetReferences(TargetFramework.Standard, new[] { MetadataReference.CreateFromAssemblyInternal(typeof(ISourceGenerator).Assembly) }), new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); compilation.VerifyDiagnostics(); var result = compilation.Emit(generatorPath); Assert.True(result.Success); return generatorPath; } } [Theory] [InlineData("a.txt", "b.txt", 2)] [InlineData("a.txt", "a.txt", 1)] [InlineData("abc/a.txt", "def/a.txt", 2)] [InlineData("abc/a.txt", "abc/a.txt", 1)] [InlineData("abc/a.txt", "abc/../a.txt", 2)] [InlineData("abc/a.txt", "abc/./a.txt", 1)] [InlineData("abc/a.txt", "abc/../abc/a.txt", 1)] [InlineData("abc/a.txt", "abc/.././abc/a.txt", 1)] [InlineData("abc/a.txt", "./abc/a.txt", 1)] [InlineData("abc/a.txt", "../abc/../abc/a.txt", 2)] [InlineData("abc/a.txt", "./abc/../abc/a.txt", 1)] [InlineData("../abc/a.txt", "../abc/../abc/a.txt", 1)] [InlineData("../abc/a.txt", "../abc/a.txt", 1)] [InlineData("./abc/a.txt", "abc/a.txt", 1)] public void TestDuplicateAdditionalFiles(string additionalFilePath1, string additionalFilePath2, int expectedCount) { var srcDirectory = Temp.CreateDirectory(); var srcFile = srcDirectory.CreateFile("a.cs").WriteAllText("class C { }"); // make sure any parent or sub dirs exist too Directory.CreateDirectory(Path.GetDirectoryName(Path.Combine(srcDirectory.Path, additionalFilePath1))); Directory.CreateDirectory(Path.GetDirectoryName(Path.Combine(srcDirectory.Path, additionalFilePath2))); var additionalFile1 = srcDirectory.CreateFile(additionalFilePath1); var additionalFile2 = expectedCount == 2 ? srcDirectory.CreateFile(additionalFilePath2) : null; string path1 = additionalFile1.Path; string path2 = additionalFile2?.Path ?? Path.Combine(srcDirectory.Path, additionalFilePath2); int count = 0; var generator = new PipelineCallbackGenerator(ctx => { ctx.RegisterSourceOutput(ctx.AdditionalTextsProvider, (spc, t) => { count++; }); }); var output = VerifyOutput(srcDirectory, srcFile, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/additionalfile:" + path1, "/additionalfile:" + path2 }, generators: new[] { generator.AsSourceGenerator() }); Assert.Equal(expectedCount, count); CleanupAllGeneratedFiles(srcDirectory.Path); } [ConditionalTheory(typeof(WindowsOnly))] [InlineData("abc/a.txt", "abc\\a.txt", 1)] [InlineData("abc\\a.txt", "abc\\a.txt", 1)] [InlineData("abc/a.txt", "abc\\..\\a.txt", 2)] [InlineData("abc/a.txt", "abc\\..\\abc\\a.txt", 1)] [InlineData("abc/a.txt", "../abc\\../abc\\a.txt", 2)] [InlineData("abc/a.txt", "./abc\\../abc\\a.txt", 1)] [InlineData("../abc/a.txt", "../abc\\../abc\\a.txt", 1)] [InlineData("a.txt", "A.txt", 1)] [InlineData("abc/a.txt", "ABC\\a.txt", 1)] [InlineData("abc/a.txt", "ABC\\A.txt", 1)] public void TestDuplicateAdditionalFiles_Windows(string additionalFilePath1, string additionalFilePath2, int expectedCount) => TestDuplicateAdditionalFiles(additionalFilePath1, additionalFilePath2, expectedCount); [ConditionalTheory(typeof(LinuxOnly))] [InlineData("a.txt", "A.txt", 2)] [InlineData("abc/a.txt", "abc/A.txt", 2)] [InlineData("abc/a.txt", "ABC/a.txt", 2)] [InlineData("abc/a.txt", "./../abc/A.txt", 2)] [InlineData("abc/a.txt", "./../ABC/a.txt", 2)] public void TestDuplicateAdditionalFiles_Linux(string additionalFilePath1, string additionalFilePath2, int expectedCount) => TestDuplicateAdditionalFiles(additionalFilePath1, additionalFilePath2, expectedCount); } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] internal abstract class CompilationStartedAnalyzer : DiagnosticAnalyzer { public abstract override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } public abstract void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context); public override void Initialize(AnalysisContext context) { context.RegisterCompilationStartAction(CreateAnalyzerWithinCompilation); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] internal class HiddenDiagnosticAnalyzer : CompilationStartedAnalyzer { internal static readonly DiagnosticDescriptor Hidden01 = new DiagnosticDescriptor("Hidden01", "", "Throwing a diagnostic for #region", "", DiagnosticSeverity.Hidden, isEnabledByDefault: true); internal static readonly DiagnosticDescriptor Hidden02 = new DiagnosticDescriptor("Hidden02", "", "Throwing a diagnostic for something else", "", DiagnosticSeverity.Hidden, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Hidden01, Hidden02); } } private void AnalyzeNode(SyntaxNodeAnalysisContext context) { context.ReportDiagnostic(Diagnostic.Create(Hidden01, context.Node.GetLocation())); } public override void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context) { context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.RegionDirectiveTrivia); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] internal class InfoDiagnosticAnalyzer : CompilationStartedAnalyzer { internal static readonly DiagnosticDescriptor Info01 = new DiagnosticDescriptor("Info01", "", "Throwing a diagnostic for #pragma restore", "", DiagnosticSeverity.Info, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Info01); } } private void AnalyzeNode(SyntaxNodeAnalysisContext context) { if ((context.Node as PragmaWarningDirectiveTriviaSyntax).DisableOrRestoreKeyword.IsKind(SyntaxKind.RestoreKeyword)) { context.ReportDiagnostic(Diagnostic.Create(Info01, context.Node.GetLocation())); } } public override void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context) { context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.PragmaWarningDirectiveTrivia); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] internal class WarningDiagnosticAnalyzer : CompilationStartedAnalyzer { internal static readonly DiagnosticDescriptor Warning01 = new DiagnosticDescriptor("Warning01", "", "Throwing a diagnostic for types declared", "", DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Warning01); } } public override void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context) { context.RegisterSymbolAction( (symbolContext) => { symbolContext.ReportDiagnostic(Diagnostic.Create(Warning01, symbolContext.Symbol.Locations.First())); }, SymbolKind.NamedType); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] internal class ErrorDiagnosticAnalyzer : CompilationStartedAnalyzer { internal static readonly DiagnosticDescriptor Error01 = new DiagnosticDescriptor("Error01", "", "Throwing a diagnostic for #pragma disable", "", DiagnosticSeverity.Error, isEnabledByDefault: true); internal static readonly DiagnosticDescriptor Error02 = new DiagnosticDescriptor("Error02", "", "Throwing a diagnostic for something else", "", DiagnosticSeverity.Error, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Error01, Error02); } } public override void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context) { context.RegisterSyntaxNodeAction( (nodeContext) => { if ((nodeContext.Node as PragmaWarningDirectiveTriviaSyntax).DisableOrRestoreKeyword.IsKind(SyntaxKind.DisableKeyword)) { nodeContext.ReportDiagnostic(Diagnostic.Create(Error01, nodeContext.Node.GetLocation())); } }, SyntaxKind.PragmaWarningDirectiveTrivia ); } } }
sharwell/roslyn
src/Compilers/CSharp/Test/CommandLine/CommandLineTests.cs
C#
mit
730,075
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ module.exports = { "default": require("core-js/library/fn/get-iterator"), __esModule: true }; },{"core-js/library/fn/get-iterator":6}],2:[function(require,module,exports){ module.exports = { "default": require("core-js/library/fn/object/define-property"), __esModule: true }; },{"core-js/library/fn/object/define-property":7}],3:[function(require,module,exports){ module.exports = { "default": require("core-js/library/fn/object/keys"), __esModule: true }; },{"core-js/library/fn/object/keys":8}],4:[function(require,module,exports){ "use strict"; exports.__esModule = true; exports.default = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; },{}],5:[function(require,module,exports){ "use strict"; exports.__esModule = true; var _defineProperty = require("../core-js/object/define-property"); var _defineProperty2 = _interopRequireDefault(_defineProperty); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; (0, _defineProperty2.default)(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); },{"../core-js/object/define-property":2}],6:[function(require,module,exports){ require('../modules/web.dom.iterable'); require('../modules/es6.string.iterator'); module.exports = require('../modules/core.get-iterator'); },{"../modules/core.get-iterator":57,"../modules/es6.string.iterator":61,"../modules/web.dom.iterable":62}],7:[function(require,module,exports){ require('../../modules/es6.object.define-property'); var $Object = require('../../modules/_core').Object; module.exports = function defineProperty(it, key, desc){ return $Object.defineProperty(it, key, desc); }; },{"../../modules/_core":15,"../../modules/es6.object.define-property":59}],8:[function(require,module,exports){ require('../../modules/es6.object.keys'); module.exports = require('../../modules/_core').Object.keys; },{"../../modules/_core":15,"../../modules/es6.object.keys":60}],9:[function(require,module,exports){ module.exports = function(it){ if(typeof it != 'function')throw TypeError(it + ' is not a function!'); return it; }; },{}],10:[function(require,module,exports){ module.exports = function(){ /* empty */ }; },{}],11:[function(require,module,exports){ var isObject = require('./_is-object'); module.exports = function(it){ if(!isObject(it))throw TypeError(it + ' is not an object!'); return it; }; },{"./_is-object":29}],12:[function(require,module,exports){ // false -> Array#indexOf // true -> Array#includes var toIObject = require('./_to-iobject') , toLength = require('./_to-length') , toIndex = require('./_to-index'); module.exports = function(IS_INCLUDES){ return function($this, el, fromIndex){ var O = toIObject($this) , length = toLength(O.length) , index = toIndex(fromIndex, length) , value; // Array#includes uses SameValueZero equality algorithm if(IS_INCLUDES && el != el)while(length > index){ value = O[index++]; if(value != value)return true; // Array#toIndex ignores holes, Array#includes - not } else for(;length > index; index++)if(IS_INCLUDES || index in O){ if(O[index] === el)return IS_INCLUDES || index || 0; } return !IS_INCLUDES && -1; }; }; },{"./_to-index":48,"./_to-iobject":50,"./_to-length":51}],13:[function(require,module,exports){ // getting tag from 19.1.3.6 Object.prototype.toString() var cof = require('./_cof') , TAG = require('./_wks')('toStringTag') // ES3 wrong here , ARG = cof(function(){ return arguments; }()) == 'Arguments'; // fallback for IE11 Script Access Denied error var tryGet = function(it, key){ try { return it[key]; } catch(e){ /* empty */ } }; module.exports = function(it){ var O, T, B; return it === undefined ? 'Undefined' : it === null ? 'Null' // @@toStringTag case : typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T // builtinTag case : ARG ? cof(O) // ES3 arguments fallback : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B; }; },{"./_cof":14,"./_wks":55}],14:[function(require,module,exports){ var toString = {}.toString; module.exports = function(it){ return toString.call(it).slice(8, -1); }; },{}],15:[function(require,module,exports){ var core = module.exports = {version: '2.4.0'}; if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef },{}],16:[function(require,module,exports){ // optional / simple context binding var aFunction = require('./_a-function'); module.exports = function(fn, that, length){ aFunction(fn); if(that === undefined)return fn; switch(length){ case 1: return function(a){ return fn.call(that, a); }; case 2: return function(a, b){ return fn.call(that, a, b); }; case 3: return function(a, b, c){ return fn.call(that, a, b, c); }; } return function(/* ...args */){ return fn.apply(that, arguments); }; }; },{"./_a-function":9}],17:[function(require,module,exports){ // 7.2.1 RequireObjectCoercible(argument) module.exports = function(it){ if(it == undefined)throw TypeError("Can't call method on " + it); return it; }; },{}],18:[function(require,module,exports){ // Thank's IE8 for his funny defineProperty module.exports = !require('./_fails')(function(){ return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7; }); },{"./_fails":22}],19:[function(require,module,exports){ var isObject = require('./_is-object') , document = require('./_global').document // in old IE typeof document.createElement is 'object' , is = isObject(document) && isObject(document.createElement); module.exports = function(it){ return is ? document.createElement(it) : {}; }; },{"./_global":23,"./_is-object":29}],20:[function(require,module,exports){ // IE 8- don't enum bug keys module.exports = ( 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf' ).split(','); },{}],21:[function(require,module,exports){ var global = require('./_global') , core = require('./_core') , ctx = require('./_ctx') , hide = require('./_hide') , PROTOTYPE = 'prototype'; var $export = function(type, name, source){ var IS_FORCED = type & $export.F , IS_GLOBAL = type & $export.G , IS_STATIC = type & $export.S , IS_PROTO = type & $export.P , IS_BIND = type & $export.B , IS_WRAP = type & $export.W , exports = IS_GLOBAL ? core : core[name] || (core[name] = {}) , expProto = exports[PROTOTYPE] , target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE] , key, own, out; if(IS_GLOBAL)source = name; for(key in source){ // contains in native own = !IS_FORCED && target && target[key] !== undefined; if(own && key in exports)continue; // export native or passed out = own ? target[key] : source[key]; // prevent global pollution for namespaces exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key] // bind timers to global for call from export context : IS_BIND && own ? ctx(out, global) // wrap global constructors for prevent change them in library : IS_WRAP && target[key] == out ? (function(C){ var F = function(a, b, c){ if(this instanceof C){ switch(arguments.length){ case 0: return new C; case 1: return new C(a); case 2: return new C(a, b); } return new C(a, b, c); } return C.apply(this, arguments); }; F[PROTOTYPE] = C[PROTOTYPE]; return F; // make static versions for prototype methods })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; // export proto methods to core.%CONSTRUCTOR%.methods.%NAME% if(IS_PROTO){ (exports.virtual || (exports.virtual = {}))[key] = out; // export proto methods to core.%CONSTRUCTOR%.prototype.%NAME% if(type & $export.R && expProto && !expProto[key])hide(expProto, key, out); } } }; // type bitmap $export.F = 1; // forced $export.G = 2; // global $export.S = 4; // static $export.P = 8; // proto $export.B = 16; // bind $export.W = 32; // wrap $export.U = 64; // safe $export.R = 128; // real proto method for `library` module.exports = $export; },{"./_core":15,"./_ctx":16,"./_global":23,"./_hide":25}],22:[function(require,module,exports){ module.exports = function(exec){ try { return !!exec(); } catch(e){ return true; } }; },{}],23:[function(require,module,exports){ // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 var global = module.exports = typeof window != 'undefined' && window.Math == Math ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')(); if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef },{}],24:[function(require,module,exports){ var hasOwnProperty = {}.hasOwnProperty; module.exports = function(it, key){ return hasOwnProperty.call(it, key); }; },{}],25:[function(require,module,exports){ var dP = require('./_object-dp') , createDesc = require('./_property-desc'); module.exports = require('./_descriptors') ? function(object, key, value){ return dP.f(object, key, createDesc(1, value)); } : function(object, key, value){ object[key] = value; return object; }; },{"./_descriptors":18,"./_object-dp":36,"./_property-desc":42}],26:[function(require,module,exports){ module.exports = require('./_global').document && document.documentElement; },{"./_global":23}],27:[function(require,module,exports){ module.exports = !require('./_descriptors') && !require('./_fails')(function(){ return Object.defineProperty(require('./_dom-create')('div'), 'a', {get: function(){ return 7; }}).a != 7; }); },{"./_descriptors":18,"./_dom-create":19,"./_fails":22}],28:[function(require,module,exports){ // fallback for non-array-like ES3 and non-enumerable old V8 strings var cof = require('./_cof'); module.exports = Object('z').propertyIsEnumerable(0) ? Object : function(it){ return cof(it) == 'String' ? it.split('') : Object(it); }; },{"./_cof":14}],29:[function(require,module,exports){ module.exports = function(it){ return typeof it === 'object' ? it !== null : typeof it === 'function'; }; },{}],30:[function(require,module,exports){ 'use strict'; var create = require('./_object-create') , descriptor = require('./_property-desc') , setToStringTag = require('./_set-to-string-tag') , IteratorPrototype = {}; // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() require('./_hide')(IteratorPrototype, require('./_wks')('iterator'), function(){ return this; }); module.exports = function(Constructor, NAME, next){ Constructor.prototype = create(IteratorPrototype, {next: descriptor(1, next)}); setToStringTag(Constructor, NAME + ' Iterator'); }; },{"./_hide":25,"./_object-create":35,"./_property-desc":42,"./_set-to-string-tag":44,"./_wks":55}],31:[function(require,module,exports){ 'use strict'; var LIBRARY = require('./_library') , $export = require('./_export') , redefine = require('./_redefine') , hide = require('./_hide') , has = require('./_has') , Iterators = require('./_iterators') , $iterCreate = require('./_iter-create') , setToStringTag = require('./_set-to-string-tag') , getPrototypeOf = require('./_object-gpo') , ITERATOR = require('./_wks')('iterator') , BUGGY = !([].keys && 'next' in [].keys()) // Safari has buggy iterators w/o `next` , FF_ITERATOR = '@@iterator' , KEYS = 'keys' , VALUES = 'values'; var returnThis = function(){ return this; }; module.exports = function(Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED){ $iterCreate(Constructor, NAME, next); var getMethod = function(kind){ if(!BUGGY && kind in proto)return proto[kind]; switch(kind){ case KEYS: return function keys(){ return new Constructor(this, kind); }; case VALUES: return function values(){ return new Constructor(this, kind); }; } return function entries(){ return new Constructor(this, kind); }; }; var TAG = NAME + ' Iterator' , DEF_VALUES = DEFAULT == VALUES , VALUES_BUG = false , proto = Base.prototype , $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT] , $default = $native || getMethod(DEFAULT) , $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined , $anyNative = NAME == 'Array' ? proto.entries || $native : $native , methods, key, IteratorPrototype; // Fix native if($anyNative){ IteratorPrototype = getPrototypeOf($anyNative.call(new Base)); if(IteratorPrototype !== Object.prototype){ // Set @@toStringTag to native iterators setToStringTag(IteratorPrototype, TAG, true); // fix for some old engines if(!LIBRARY && !has(IteratorPrototype, ITERATOR))hide(IteratorPrototype, ITERATOR, returnThis); } } // fix Array#{values, @@iterator}.name in V8 / FF if(DEF_VALUES && $native && $native.name !== VALUES){ VALUES_BUG = true; $default = function values(){ return $native.call(this); }; } // Define iterator if((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])){ hide(proto, ITERATOR, $default); } // Plug for library Iterators[NAME] = $default; Iterators[TAG] = returnThis; if(DEFAULT){ methods = { values: DEF_VALUES ? $default : getMethod(VALUES), keys: IS_SET ? $default : getMethod(KEYS), entries: $entries }; if(FORCED)for(key in methods){ if(!(key in proto))redefine(proto, key, methods[key]); } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods); } return methods; }; },{"./_export":21,"./_has":24,"./_hide":25,"./_iter-create":30,"./_iterators":33,"./_library":34,"./_object-gpo":38,"./_redefine":43,"./_set-to-string-tag":44,"./_wks":55}],32:[function(require,module,exports){ module.exports = function(done, value){ return {value: value, done: !!done}; }; },{}],33:[function(require,module,exports){ module.exports = {}; },{}],34:[function(require,module,exports){ module.exports = true; },{}],35:[function(require,module,exports){ // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) var anObject = require('./_an-object') , dPs = require('./_object-dps') , enumBugKeys = require('./_enum-bug-keys') , IE_PROTO = require('./_shared-key')('IE_PROTO') , Empty = function(){ /* empty */ } , PROTOTYPE = 'prototype'; // Create object with fake `null` prototype: use iframe Object with cleared prototype var createDict = function(){ // Thrash, waste and sodomy: IE GC bug var iframe = require('./_dom-create')('iframe') , i = enumBugKeys.length , lt = '<' , gt = '>' , iframeDocument; iframe.style.display = 'none'; require('./_html').appendChild(iframe); iframe.src = 'javascript:'; // eslint-disable-line no-script-url // createDict = iframe.contentWindow.Object; // html.removeChild(iframe); iframeDocument = iframe.contentWindow.document; iframeDocument.open(); iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt); iframeDocument.close(); createDict = iframeDocument.F; while(i--)delete createDict[PROTOTYPE][enumBugKeys[i]]; return createDict(); }; module.exports = Object.create || function create(O, Properties){ var result; if(O !== null){ Empty[PROTOTYPE] = anObject(O); result = new Empty; Empty[PROTOTYPE] = null; // add "__proto__" for Object.getPrototypeOf polyfill result[IE_PROTO] = O; } else result = createDict(); return Properties === undefined ? result : dPs(result, Properties); }; },{"./_an-object":11,"./_dom-create":19,"./_enum-bug-keys":20,"./_html":26,"./_object-dps":37,"./_shared-key":45}],36:[function(require,module,exports){ var anObject = require('./_an-object') , IE8_DOM_DEFINE = require('./_ie8-dom-define') , toPrimitive = require('./_to-primitive') , dP = Object.defineProperty; exports.f = require('./_descriptors') ? Object.defineProperty : function defineProperty(O, P, Attributes){ anObject(O); P = toPrimitive(P, true); anObject(Attributes); if(IE8_DOM_DEFINE)try { return dP(O, P, Attributes); } catch(e){ /* empty */ } if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!'); if('value' in Attributes)O[P] = Attributes.value; return O; }; },{"./_an-object":11,"./_descriptors":18,"./_ie8-dom-define":27,"./_to-primitive":53}],37:[function(require,module,exports){ var dP = require('./_object-dp') , anObject = require('./_an-object') , getKeys = require('./_object-keys'); module.exports = require('./_descriptors') ? Object.defineProperties : function defineProperties(O, Properties){ anObject(O); var keys = getKeys(Properties) , length = keys.length , i = 0 , P; while(length > i)dP.f(O, P = keys[i++], Properties[P]); return O; }; },{"./_an-object":11,"./_descriptors":18,"./_object-dp":36,"./_object-keys":40}],38:[function(require,module,exports){ // 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) var has = require('./_has') , toObject = require('./_to-object') , IE_PROTO = require('./_shared-key')('IE_PROTO') , ObjectProto = Object.prototype; module.exports = Object.getPrototypeOf || function(O){ O = toObject(O); if(has(O, IE_PROTO))return O[IE_PROTO]; if(typeof O.constructor == 'function' && O instanceof O.constructor){ return O.constructor.prototype; } return O instanceof Object ? ObjectProto : null; }; },{"./_has":24,"./_shared-key":45,"./_to-object":52}],39:[function(require,module,exports){ var has = require('./_has') , toIObject = require('./_to-iobject') , arrayIndexOf = require('./_array-includes')(false) , IE_PROTO = require('./_shared-key')('IE_PROTO'); module.exports = function(object, names){ var O = toIObject(object) , i = 0 , result = [] , key; for(key in O)if(key != IE_PROTO)has(O, key) && result.push(key); // Don't enum bug & hidden keys while(names.length > i)if(has(O, key = names[i++])){ ~arrayIndexOf(result, key) || result.push(key); } return result; }; },{"./_array-includes":12,"./_has":24,"./_shared-key":45,"./_to-iobject":50}],40:[function(require,module,exports){ // 19.1.2.14 / 15.2.3.14 Object.keys(O) var $keys = require('./_object-keys-internal') , enumBugKeys = require('./_enum-bug-keys'); module.exports = Object.keys || function keys(O){ return $keys(O, enumBugKeys); }; },{"./_enum-bug-keys":20,"./_object-keys-internal":39}],41:[function(require,module,exports){ // most Object methods by ES6 should accept primitives var $export = require('./_export') , core = require('./_core') , fails = require('./_fails'); module.exports = function(KEY, exec){ var fn = (core.Object || {})[KEY] || Object[KEY] , exp = {}; exp[KEY] = exec(fn); $export($export.S + $export.F * fails(function(){ fn(1); }), 'Object', exp); }; },{"./_core":15,"./_export":21,"./_fails":22}],42:[function(require,module,exports){ module.exports = function(bitmap, value){ return { enumerable : !(bitmap & 1), configurable: !(bitmap & 2), writable : !(bitmap & 4), value : value }; }; },{}],43:[function(require,module,exports){ module.exports = require('./_hide'); },{"./_hide":25}],44:[function(require,module,exports){ var def = require('./_object-dp').f , has = require('./_has') , TAG = require('./_wks')('toStringTag'); module.exports = function(it, tag, stat){ if(it && !has(it = stat ? it : it.prototype, TAG))def(it, TAG, {configurable: true, value: tag}); }; },{"./_has":24,"./_object-dp":36,"./_wks":55}],45:[function(require,module,exports){ var shared = require('./_shared')('keys') , uid = require('./_uid'); module.exports = function(key){ return shared[key] || (shared[key] = uid(key)); }; },{"./_shared":46,"./_uid":54}],46:[function(require,module,exports){ var global = require('./_global') , SHARED = '__core-js_shared__' , store = global[SHARED] || (global[SHARED] = {}); module.exports = function(key){ return store[key] || (store[key] = {}); }; },{"./_global":23}],47:[function(require,module,exports){ var toInteger = require('./_to-integer') , defined = require('./_defined'); // true -> String#at // false -> String#codePointAt module.exports = function(TO_STRING){ return function(that, pos){ var s = String(defined(that)) , i = toInteger(pos) , l = s.length , a, b; if(i < 0 || i >= l)return TO_STRING ? '' : undefined; a = s.charCodeAt(i); return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff ? TO_STRING ? s.charAt(i) : a : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; }; }; },{"./_defined":17,"./_to-integer":49}],48:[function(require,module,exports){ var toInteger = require('./_to-integer') , max = Math.max , min = Math.min; module.exports = function(index, length){ index = toInteger(index); return index < 0 ? max(index + length, 0) : min(index, length); }; },{"./_to-integer":49}],49:[function(require,module,exports){ // 7.1.4 ToInteger var ceil = Math.ceil , floor = Math.floor; module.exports = function(it){ return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); }; },{}],50:[function(require,module,exports){ // to indexed object, toObject with fallback for non-array-like ES3 strings var IObject = require('./_iobject') , defined = require('./_defined'); module.exports = function(it){ return IObject(defined(it)); }; },{"./_defined":17,"./_iobject":28}],51:[function(require,module,exports){ // 7.1.15 ToLength var toInteger = require('./_to-integer') , min = Math.min; module.exports = function(it){ return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 }; },{"./_to-integer":49}],52:[function(require,module,exports){ // 7.1.13 ToObject(argument) var defined = require('./_defined'); module.exports = function(it){ return Object(defined(it)); }; },{"./_defined":17}],53:[function(require,module,exports){ // 7.1.1 ToPrimitive(input [, PreferredType]) var isObject = require('./_is-object'); // instead of the ES6 spec version, we didn't implement @@toPrimitive case // and the second argument - flag - preferred type is a string module.exports = function(it, S){ if(!isObject(it))return it; var fn, val; if(S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val; if(typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it)))return val; if(!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val; throw TypeError("Can't convert object to primitive value"); }; },{"./_is-object":29}],54:[function(require,module,exports){ var id = 0 , px = Math.random(); module.exports = function(key){ return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); }; },{}],55:[function(require,module,exports){ var store = require('./_shared')('wks') , uid = require('./_uid') , Symbol = require('./_global').Symbol , USE_SYMBOL = typeof Symbol == 'function'; var $exports = module.exports = function(name){ return store[name] || (store[name] = USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name)); }; $exports.store = store; },{"./_global":23,"./_shared":46,"./_uid":54}],56:[function(require,module,exports){ var classof = require('./_classof') , ITERATOR = require('./_wks')('iterator') , Iterators = require('./_iterators'); module.exports = require('./_core').getIteratorMethod = function(it){ if(it != undefined)return it[ITERATOR] || it['@@iterator'] || Iterators[classof(it)]; }; },{"./_classof":13,"./_core":15,"./_iterators":33,"./_wks":55}],57:[function(require,module,exports){ var anObject = require('./_an-object') , get = require('./core.get-iterator-method'); module.exports = require('./_core').getIterator = function(it){ var iterFn = get(it); if(typeof iterFn != 'function')throw TypeError(it + ' is not iterable!'); return anObject(iterFn.call(it)); }; },{"./_an-object":11,"./_core":15,"./core.get-iterator-method":56}],58:[function(require,module,exports){ 'use strict'; var addToUnscopables = require('./_add-to-unscopables') , step = require('./_iter-step') , Iterators = require('./_iterators') , toIObject = require('./_to-iobject'); // 22.1.3.4 Array.prototype.entries() // 22.1.3.13 Array.prototype.keys() // 22.1.3.29 Array.prototype.values() // 22.1.3.30 Array.prototype[@@iterator]() module.exports = require('./_iter-define')(Array, 'Array', function(iterated, kind){ this._t = toIObject(iterated); // target this._i = 0; // next index this._k = kind; // kind // 22.1.5.2.1 %ArrayIteratorPrototype%.next() }, function(){ var O = this._t , kind = this._k , index = this._i++; if(!O || index >= O.length){ this._t = undefined; return step(1); } if(kind == 'keys' )return step(0, index); if(kind == 'values')return step(0, O[index]); return step(0, [index, O[index]]); }, 'values'); // argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) Iterators.Arguments = Iterators.Array; addToUnscopables('keys'); addToUnscopables('values'); addToUnscopables('entries'); },{"./_add-to-unscopables":10,"./_iter-define":31,"./_iter-step":32,"./_iterators":33,"./_to-iobject":50}],59:[function(require,module,exports){ var $export = require('./_export'); // 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes) $export($export.S + $export.F * !require('./_descriptors'), 'Object', {defineProperty: require('./_object-dp').f}); },{"./_descriptors":18,"./_export":21,"./_object-dp":36}],60:[function(require,module,exports){ // 19.1.2.14 Object.keys(O) var toObject = require('./_to-object') , $keys = require('./_object-keys'); require('./_object-sap')('keys', function(){ return function keys(it){ return $keys(toObject(it)); }; }); },{"./_object-keys":40,"./_object-sap":41,"./_to-object":52}],61:[function(require,module,exports){ 'use strict'; var $at = require('./_string-at')(true); // 21.1.3.27 String.prototype[@@iterator]() require('./_iter-define')(String, 'String', function(iterated){ this._t = String(iterated); // target this._i = 0; // next index // 21.1.5.2.1 %StringIteratorPrototype%.next() }, function(){ var O = this._t , index = this._i , point; if(index >= O.length)return {value: undefined, done: true}; point = $at(O, index); this._i += point.length; return {value: point, done: false}; }); },{"./_iter-define":31,"./_string-at":47}],62:[function(require,module,exports){ require('./es6.array.iterator'); var global = require('./_global') , hide = require('./_hide') , Iterators = require('./_iterators') , TO_STRING_TAG = require('./_wks')('toStringTag'); for(var collections = ['NodeList', 'DOMTokenList', 'MediaList', 'StyleSheetList', 'CSSRuleList'], i = 0; i < 5; i++){ var NAME = collections[i] , Collection = global[NAME] , proto = Collection && Collection.prototype; if(proto && !proto[TO_STRING_TAG])hide(proto, TO_STRING_TAG, NAME); Iterators[NAME] = Iterators.Array; } },{"./_global":23,"./_hide":25,"./_iterators":33,"./_wks":55,"./es6.array.iterator":58}],63:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _keys = require("babel-runtime/core-js/object/keys"); var _keys2 = _interopRequireDefault(_keys); var _getIterator2 = require("babel-runtime/core-js/get-iterator"); var _getIterator3 = _interopRequireDefault(_getIterator2); var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = require("babel-runtime/helpers/createClass"); var _createClass3 = _interopRequireDefault(_createClass2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Emitter */ var Emitter = function () { function Emitter() { (0, _classCallCheck3.default)(this, Emitter); this._data = {}; } (0, _createClass3.default)(Emitter, [{ key: "on", value: function on(name, data) { if (!name) return; if (!this._data[name]) { this._data[name] = {}; } this._data[name] = data; } }, { key: "emit", value: function emit(name, method, context) { if (!name || !method) return; this._data[name].run(method, context); } }, { key: "broadcast", value: function broadcast(method, context) { if (!method) return; var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = (0, _getIterator3.default)((0, _keys2.default)(this._data)), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var name = _step.value; this._data[name].run(method, context); } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } } }, { key: "keys", value: function keys() { return (0, _keys2.default)(this._data); } }, { key: "is", value: function is(name) { return !!this._data[name]; } }, { key: "get", value: function get(name) { return this._data[name]; } }]); return Emitter; }(); exports.default = Emitter; },{"babel-runtime/core-js/get-iterator":1,"babel-runtime/core-js/object/keys":3,"babel-runtime/helpers/classCallCheck":4,"babel-runtime/helpers/createClass":5}],64:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _keys = require('babel-runtime/core-js/object/keys'); var _keys2 = _interopRequireDefault(_keys); var _getIterator2 = require('babel-runtime/core-js/get-iterator'); var _getIterator3 = _interopRequireDefault(_getIterator2); var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck'); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = require('babel-runtime/helpers/createClass'); var _createClass3 = _interopRequireDefault(_createClass2); var _Emitter = require('../class/_Emitter'); var _Emitter2 = _interopRequireDefault(_Emitter); var _Subscriber = require('../class/_Subscriber'); var _Subscriber2 = _interopRequireDefault(_Subscriber); var _RequestAnim = require('../class/_RequestAnim'); var _RequestAnim2 = _interopRequireDefault(_RequestAnim); var _calc = require('../module/_calc'); var _calc2 = _interopRequireDefault(_calc); var _help = require('../module/_help'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var Flyby = function () { function Flyby(options) { (0, _classCallCheck3.default)(this, Flyby); this.enabled = false; this.mode = ''; this.painting = false; this.startX = 0; this.startY = 0; this.ghostX = 0; this.ghostY = 0; this.currentX = 0; this.currentY = 0; this.distanceX = 0; this.distanceY = 0; this.distanceAngle = 0; this.invertX = 0; this.invertY = 0; this.originX = 0; this.originY = 0; this.between = 0; this.betweenX = 0; this.betweenY = 0; this.betweenAngle = 0; this.previousX = 0; this.previousY = 0; this.direction = ''; this.directionX = ''; this.directionY = ''; this.targetElement = null; // <event.target> this.startTime = 0; // timestamp by OnStart this.elapsed = 0; // <endTime> - <startTime> this.ghostTime = 0; // previously <startTime> this.onStart = this.onStart.bind(this); this.onMove = this.onMove.bind(this); this.onEnd = this.onEnd.bind(this); this.update = this.update.bind(this); // In this element, that enabled to mouse and touch events. this.rangeElement = options.rangeElement || document; this._addEventListeners(); // Browser painting update // call requestAnimationFrame this.paint = new _RequestAnim2.default(); this.paint.tick = this.update; this.first = false; this.pinchOnDesktop = false; this.flickTime = 250; // event emitter this.emitter = new _Emitter2.default(); this._initSubscribe(options.subscribers); // emit configuration this.emitter.broadcast('onConfig', this); this.subscriber = null; } (0, _createClass3.default)(Flyby, [{ key: 'onStart', value: function onStart(event) { // set the flags to initialize this.enabled = true; this.painting = true; this.touched = event.touches ? true : false; this.first = true; this.pinchOnDesktop = false; // set the position to initalize this.startTime = Date.now(); this.startX = (0, _help.pageX)(event); this.startY = (0, _help.pageY)(event); this.distanceX = 0; this.distanceY = 0; this.distanceAngle = 0; this.distance = 0; this.currentX = this.startX; this.currentY = this.startY; this.invertX = this.startX; this.invertY = this.startY; this.previousX = this.startX; this.previousY = this.startY; this.between = 0; this.betweenX = 0; this.betweenY = 0; this.betweenAngle = 0; this.direction = ''; this.directionX = ''; this.directionY = ''; this.targetElement = event.target; if (!this.touched) { if (this.startTime - this.ghostTime < 750) { this.pinchOnDesktop = true; } } // find a target & subscriber this._find(event.target); // subscribe this._emit('onStart'); // paint this.paint.cancel(); this.paint.play(); this.ghostTime = this.startTime; event.preventDefault(); } }, { key: 'onMove', value: function onMove(event) { if (!this.enabled) return; if ((0, _help.hasTouches)(event, 2) || this.pinchOnDesktop) { this.mode = 'pinch'; } else { this.mode = 'swipe'; } this.currentX = (0, _help.pageX)(event); this.currentY = (0, _help.pageY)(event); if (this.mode === 'pinch') { this._invert(event); this._between(); } this._distance(); this.originX = this.currentX - parseInt(this.betweenX / 2, 10); this.originY = this.currentY - parseInt(this.betweenY / 2, 10); this._direction(); this.targetElement = event.target; // check ignore list to subscribe if (!this._inIgnore(this.mode)) { if (this.first) { // do of only once on `onMove` method. this.direction = _calc2.default.which(this.distanceAngle); } if (this.mode !== 'swipe' || !this._inIgnore(this.direction)) { if (this.first) { this._emit('onOnce'); } else { this._emit('on' + (0, _help.camel)(this.mode)); } event.preventDefault(); } } // to next step this.first = false; this.previousX = this.currentX; this.previousY = this.currentY; } }, { key: 'onEnd', value: function onEnd(event) { this.enabled = false; this.touched = false; this.elapsed = Date.now() - this.startTime; this.ghostX = this.startX; this.ghostY = this.startY; this.targetElement = event.target; if (this._isFlick(this.elapsed)) { this._emit('onFlick'); } // element & subscriber this._emit('onEnd'); } /** * update * Call in requestAnimationFrame * Related Paiting Dom is here. */ }, { key: 'update', value: function update() { if (!this.painting) return; this.paint.play(); // subscribe this._emit('onUpdate'); } /** * invert * The posision is another one that is B. * @private * @param {Object} event<EventObject> */ }, { key: '_invert', value: function _invert(event) { if (this.touched && event.touches[1]) { this.currentX = event.touches[0].pageX; this.currentY = event.touches[0].pageY; this.invertX = event.touches[1].pageX; this.invertY = event.touches[1].pageY; } else { this.invertX = this.ghostX; this.invertY = this.ghostY; } } /** * distance * @private */ }, { key: '_distance', value: function _distance() { this.distanceX = this.currentX - this.startX; this.distanceY = this.currentY - this.startY; this.distance = _calc2.default.diagonal(this.distanceX, this.distanceY); this.distanceAngle = _calc2.default.angle(this.distanceY * -1, this.distanceX, true); } /** * between * Distance of between A and B * @private */ }, { key: '_between', value: function _between() { this.betweenX = this.currentX - this.invertX; this.betweenY = this.currentY - this.invertY; this.between = _calc2.default.diagonal(this.betweenX, this.betweenY); this.betweenAngle = _calc2.default.angle(this.betweenY * -1, this.betweenX, true); } /** * direction * @private */ }, { key: '_direction', value: function _direction() { if (this.currentX > this.previousX) { this.directionX = 'to right'; } else if (this.currentX < this.previousX) { this.directionX = 'to left'; } if (this.currentY > this.previousY) { this.directionY = 'to bottom'; } else if (this.currentY < this.previousY) { this.directionY = 'to top'; } } /** * emit * @private * @param {String} suffix * 指定された文字列をキャメルケースに変換し, on と結合してメソッド名にする * subscriber 内のメソッドを実行する */ }, { key: '_emit', value: function _emit(method) { if (!method || !this.subscriber) return; this.emitter.emit(this.subscriber.selector, method, this); } /** * find * @private * @param {Object} node<HTMLElement> * 今回実行するべき subscriber を探します */ }, { key: '_find', value: function _find(el) { var found = false; this.subscriber = null; // nodeTree を上方向に探索します while (el && !found) { if (el === (0, _help.documentElement)()) { return found; } var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = (0, _getIterator3.default)(this.emitter.keys()), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var name = _step.value; var prefix = name.slice(0, 1); var selector = name.substr(1); if ((0, _help.matchElement)(el, selector)) { if (this.emitter.is(name)) { this.subscriber = this.emitter.get(name); this.subscriber.el = el; found = true; return found; } } } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } el = el.parentNode; } return found; } /** * initSubscribe * @private */ }, { key: '_initSubscribe', value: function _initSubscribe(subscribers) { if (subscribers) { var _iteratorNormalCompletion2 = true; var _didIteratorError2 = false; var _iteratorError2 = undefined; try { for (var _iterator2 = (0, _getIterator3.default)((0, _keys2.default)(subscribers)), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { var name = _step2.value; this.emitter.on(name, new _Subscriber2.default(name, subscribers[name])); } } catch (err) { _didIteratorError2 = true; _iteratorError2 = err; } finally { try { if (!_iteratorNormalCompletion2 && _iterator2.return) { _iterator2.return(); } } finally { if (_didIteratorError2) { throw _iteratorError2; } } } } } /** * The `str` includes in ignore list. * @param {String} str * @return {Boolean} */ }, { key: '_inIgnore', value: function _inIgnore(str) { return this.subscriber.ignore.includes(str); } /** * is Flick? * @return {Boolean} */ }, { key: '_isFlick', value: function _isFlick(elapsed) { return elapsed < this.flickTime && elapsed > 50; } /** * addEventListeners * @private */ }, { key: '_addEventListeners', value: function _addEventListeners() { this.rangeElement.addEventListener('mousedown', this.onStart); this.rangeElement.addEventListener('mousemove', this.onMove); this.rangeElement.addEventListener('mouseup', this.onEnd); this.rangeElement.addEventListener('touchstart', this.onStart); this.rangeElement.addEventListener('touchmove', this.onMove); this.rangeElement.addEventListener('touchend', this.onEnd); } }]); return Flyby; }(); exports.default = Flyby; },{"../class/_Emitter":63,"../class/_RequestAnim":65,"../class/_Subscriber":66,"../module/_calc":68,"../module/_help":69,"babel-runtime/core-js/get-iterator":1,"babel-runtime/core-js/object/keys":3,"babel-runtime/helpers/classCallCheck":4,"babel-runtime/helpers/createClass":5}],65:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = require("babel-runtime/helpers/createClass"); var _createClass3 = _interopRequireDefault(_createClass2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.setTimeout; var cancelAnimationFrame = window.cancelAnimationFrame || window.mozCancelAnimationFrame || window.clearTimeout; window.requestAnimationFrame = requestAnimationFrame; window.cancelAnimationFrame = cancelAnimationFrame; var ReqestAnim = function () { function ReqestAnim() { (0, _classCallCheck3.default)(this, ReqestAnim); this._id = null; this._tick = null; } (0, _createClass3.default)(ReqestAnim, [{ key: "play", value: function play(callback) { var _this = this; this.id = requestAnimationFrame(function () { if (callback) callback(); _this._tick(); }); } }, { key: "cancel", value: function cancel() { if (this._id != null) { cancelAnimationFrame(this._id); } } }, { key: "id", set: function set(id) { this._id = id; }, get: function get() { return this._id; } }, { key: "tick", set: function set(callback) { this._tick = callback; } }]); return ReqestAnim; }(); exports.default = ReqestAnim; },{"babel-runtime/helpers/classCallCheck":4,"babel-runtime/helpers/createClass":5}],66:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _keys = require('babel-runtime/core-js/object/keys'); var _keys2 = _interopRequireDefault(_keys); var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck'); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = require('babel-runtime/helpers/createClass'); var _createClass3 = _interopRequireDefault(_createClass2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Target * @member {String} _name * @member {HTMLElement} _el * @member {Object} _methods * @member {Array} _ignore */ var Subscriber = function () { function Subscriber(name, body) { (0, _classCallCheck3.default)(this, Subscriber); this._name = ''; this._selector = ''; this._element = null; this._methods = this._defaultMethods(); this._ignore = []; this._scope = {}; this.name = name.replace(/^[.#]/, ''); this.selector = name; this.ignore = body.ignore; this.methods = body; } (0, _createClass3.default)(Subscriber, [{ key: 'run', value: function run(methodName, context) { if (this._methods[methodName]) { this._methods[methodName].bind(context)(this._scope, this._elementement); } } }, { key: '_defaultMethods', value: function _defaultMethods() { var noop = function noop() {}; var methods = ['Config', 'Start', 'Once', 'Swipe', 'Pinch', 'Flick', 'End', 'Update']; return function (res) { methods.forEach(function (name) { var key = ['on', name].join(''); res[key] = noop; }); return res; }({}); } }, { key: 'name', set: function set(str) { this._name = str; }, get: function get() { return this._name; } }, { key: 'selector', set: function set(str) { this._selector = str; }, get: function get() { return this._selector; } }, { key: 'methods', set: function set(obj) { var _this = this; (0, _keys2.default)(obj).forEach(function (key) { if (typeof obj[key] === 'function') { _this._methods[key] = obj[key]; } }); }, get: function get() { return this._methods; } }, { key: 'ignore', set: function set(array) { this._ignore = array || []; }, get: function get() { return this._ignore; } }, { key: 'el', set: function set(element) { this._element = element; }, get: function get() { return this._element; } }]); return Subscriber; }(); exports.default = Subscriber; },{"babel-runtime/core-js/object/keys":3,"babel-runtime/helpers/classCallCheck":4,"babel-runtime/helpers/createClass":5}],67:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _Flyby = require('./class/_Flyby'); var _Flyby2 = _interopRequireDefault(_Flyby); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = _Flyby2.default; /** * NOTE: Positions declarations * Start - 始点 <x, y> * End - 終点 <x, y> **不要?** * Current - 現在地 <x, y> * Distance - 始点から現在地への距離 <x, y> [swipe] * Invert - 2つ目の始点 <x, y> [pinch] * Between - Start と Invert の距離 <d> [pinch] * Origin - Start と Invert の開始時の中間地点 <x, y> [pinch] * Offset - 対象ノードの座標 <x, y> **外側でやる** */ /** * NOTE: API methods * onConfig(scope) * onStart(scope, element) * onEnd(scope, element) * onFirstStep(scope, element) * onPinch(scope, element) * onSwipe(scope, element) * onFlick(scope, element) * onUpdate(scope, element) * ignore [x, y, swipe, pinch] */ },{"./class/_Flyby":64}],68:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _help = require('./_help'); exports.default = function () { return { degree: degree, radian: radian, angle: angle, diagonal: diagonal, which: which }; }(); /** * diagonal * @param {Number} x * @param {Number} y * @return {Number} d */ function diagonal(x, y) { return parseInt((0, _help.sqrt)((0, _help.pow)(x, 2) + (0, _help.pow)(y, 2))); } /** * Wrapped `Math.atan2` * @private * @param {Number} y * @param {Number} x */ function angle(y, x) { var toDegree = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2]; if (toDegree) { return degree((0, _help.atan2)(y, x)); } return (0, _help.atan2)(y, x); } /** * which * swipe の軸の向きを検出します * @return {String} */ function which(angle) { angle = (0, _help.abs)(angle); if (angle < 180 + 5 && angle > 180 - 5 || angle < 10) { return 'x'; } return 'y'; } /** * degree * The radian convert to degree. * @private * @param {Number} radian * @param {Number} degree */ function degree(radian) { return radian * 180 / _help.PI; } /** * radian * The degree convert to radian * @private * @param {Number} degree * @return {Number} radian */ function radian(degree) { return degree * _help.PI / 180; } },{"./_help":69}],69:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.camel = camel; exports.hasClass = hasClass; exports.hasId = hasId; exports.matchElement = matchElement; exports.documentElement = documentElement; exports.pageX = pageX; exports.pageY = pageY; exports.touches = touches; exports.hasTouches = hasTouches; exports.noop = noop; /** * help.js */ var PI = Math.PI; var sqrt = Math.sqrt; var atan2 = Math.atan2; var abs = Math.abs; var pow = Math.pow; exports.PI = PI; exports.sqrt = sqrt; exports.atan2 = atan2; exports.abs = abs; exports.pow = pow; function camel(str) { return [str.substr(0, 1).toUpperCase(), str.substr(1)].join(''); } function hasClass(el, selector) { return el.classList.contains(selector); } function hasId(el, selector) { return el.getAttribute('id') === selector; } function matchElement(el, selector) { return hasClass(el, selector) || hasId(el, selector); } function documentElement() { return document.documentElement; } /** * pageX * @private * @param {Object} event<EventObject> */ function pageX(event) { if (event.pageX != null) { return event.pageX; } return event.touches[0].pageX; } /** * pageY * @private * @param {Object} event<EventObject> */ function pageY(event) { if (event.pageY != null) { return event.pageY; } return event.touches[0].pageY; } /** * touches * @param {Object} event<EventObject> * @return {Boolean} * Event オブジェクトから touches 抽出して返す */ function touches(event) { return event.originalEvent ? event.originalEvent.touches : event.touches; } /** * hasTouches * @private * @param {Object} event<EventObject> * @param {Number} length * @return {Boolean} */ function hasTouches(event, length) { var _touches = touches(event); if (_touches != null && _touches.length === length) { return true; } return false; } /** * No operation */ function noop() { return; } },{}]},{},[67]);
pixel-metal/flyby.js
dist/flyby.js
JavaScript
mit
53,276
from .stats_view_base import StatsViewSwagger, StatsViewSwaggerKeyRequired from .stats_util_dataverses import StatsMakerDataverses class DataverseCountByMonthView(StatsViewSwaggerKeyRequired): """API View - Dataverse counts by Month.""" # Define the swagger attributes # Note: api_path must match the path in urls.py # api_path = '/dataverses/count/monthly' summary = ('Number of published Dataverses by' ' the month they were created*. (*' ' Not month published)') description = ('Returns a list of counts and' ' cumulative counts of all Dataverses added in a month') description_200 = 'A list of Dataverse counts by month' param_names = StatsViewSwagger.PARAM_DV_API_KEY +\ StatsViewSwagger.BASIC_DATE_PARAMS +\ StatsViewSwagger.PUBLISH_PARAMS +\ StatsViewSwagger.PRETTY_JSON_PARAM +\ StatsViewSwagger.PARAM_AS_CSV tags = [StatsViewSwagger.TAG_DATAVERSES] def get_stats_result(self, request): """Return the StatsResult object for this statistic""" stats_datasets = StatsMakerDataverses(**request.GET.dict()) pub_state = self.get_pub_state(request) if pub_state == self.PUB_STATE_ALL: stats_result = stats_datasets.get_dataverse_counts_by_month() elif pub_state == self.PUB_STATE_UNPUBLISHED: stats_result = stats_datasets.get_dataverse_counts_by_month_unpublished() else: stats_result = stats_datasets.get_dataverse_counts_by_month_published() return stats_result class DataverseTotalCounts(StatsViewSwaggerKeyRequired): """API View - Total count of all Dataverses""" # Define the swagger attributes # Note: api_path must match the path in urls.py # api_path = '/dataverses/count' summary = ('Simple count of published Dataverses') description = ('Returns number of published Dataverses') description_200 = 'Number of published Dataverses' param_names = StatsViewSwagger.PARAM_DV_API_KEY + StatsViewSwagger.PUBLISH_PARAMS + StatsViewSwagger.PRETTY_JSON_PARAM tags = [StatsViewSwagger.TAG_DATAVERSES] result_name = StatsViewSwagger.RESULT_NAME_TOTAL_COUNT def get_stats_result(self, request): """Return the StatsResult object for this statistic""" stats_datasets = StatsMakerDataverses(**request.GET.dict()) pub_state = self.get_pub_state(request) if pub_state == self.PUB_STATE_ALL: stats_result = stats_datasets.get_dataverse_count() elif pub_state == self.PUB_STATE_UNPUBLISHED: stats_result = stats_datasets.get_dataverse_count_unpublished() else: stats_result = stats_datasets.get_dataverse_count_published() return stats_result class DataverseAffiliationCounts(StatsViewSwaggerKeyRequired): """API View - Number of Dataverses by Affiliation""" # Define the swagger attributes # Note: api_path must match the path in urls.py # api_path = '/dataverses/count/by-affiliation' summary = ('Number of Dataverses by Affiliation') description = ('Number of Dataverses by Affiliation.') description_200 = 'Number of published Dataverses by Affiliation.' param_names = StatsViewSwagger.PARAM_DV_API_KEY\ + StatsViewSwagger.PUBLISH_PARAMS\ + StatsViewSwagger.PRETTY_JSON_PARAM\ + StatsViewSwagger.PARAM_AS_CSV result_name = StatsViewSwagger.RESULT_NAME_AFFILIATION_COUNTS tags = [StatsViewSwagger.TAG_DATAVERSES] def get_stats_result(self, request): """Return the StatsResult object for this statistic""" stats_datasets = StatsMakerDataverses(**request.GET.dict()) pub_state = self.get_pub_state(request) if pub_state == self.PUB_STATE_ALL: stats_result = stats_datasets.get_dataverse_affiliation_counts() elif pub_state == self.PUB_STATE_UNPUBLISHED: stats_result = stats_datasets.get_dataverse_affiliation_counts_unpublished() else: stats_result = stats_datasets.get_dataverse_affiliation_counts_published() return stats_result class DataverseTypeCounts(StatsViewSwaggerKeyRequired): # Define the swagger attributes # Note: api_path must match the path in urls.py # api_path = '/dataverses/count/by-type' summary = ('Number of Dataverses by Type') description = ('Number of Dataverses by Type.') description_200 = 'Number of published Dataverses by Type.' param_names = StatsViewSwagger.PARAM_DV_API_KEY + StatsViewSwagger.PUBLISH_PARAMS +\ StatsViewSwagger.PRETTY_JSON_PARAM +\ StatsViewSwagger.DV_TYPE_UNCATEGORIZED_PARAM +\ StatsViewSwagger.PARAM_AS_CSV result_name = StatsViewSwagger.RESULT_NAME_DATAVERSE_TYPE_COUNTS tags = [StatsViewSwagger.TAG_DATAVERSES] def is_show_uncategorized(self, request): """Return the result of the "?show_uncategorized" query string param""" show_uncategorized = request.GET.get('show_uncategorized', False) if show_uncategorized is True or show_uncategorized == 'true': return True return False def get_stats_result(self, request): """Return the StatsResult object for this statistic""" stats_datasets = StatsMakerDataverses(**request.GET.dict()) if self.is_show_uncategorized(request): exclude_uncategorized = False else: exclude_uncategorized = True pub_state = self.get_pub_state(request) if pub_state == self.PUB_STATE_ALL: stats_result = stats_datasets.get_dataverse_counts_by_type(exclude_uncategorized) elif pub_state == self.PUB_STATE_UNPUBLISHED: stats_result = stats_datasets.get_dataverse_counts_by_type_unpublished(exclude_uncategorized) else: stats_result = stats_datasets.get_dataverse_counts_by_type_published(exclude_uncategorized) return stats_result
IQSS/miniverse
dv_apps/metrics/stats_views_dataverses.py
Python
mit
6,085
/* * Code used in the "Software Engineering" course. * * Copyright 2017 by Claudio Cusano (claudio.cusano@unipv.it) * Dept of Electrical, Computer and Biomedical Engineering, * University of Pavia. */ package goldrush; /** * @author Reina Michele cl418656 * @author Bonissone Davidecl427113 */ public class BoniMichele extends GoldDigger{ // int t=0; int j=99; @Override public int chooseDiggingSite(int[] distances) { for (int i=0; i<distances.length; i++){ if (t==0){ if (distances[i]==140) { j=i; t++; } } else if (t<3) { if (distances[i]== 30) { j=i; t=0; } } else { if (distances[i]== 200) { j=i; t=0; } } } return j; } }
IngSW-unipv/GoldRush
GoldRush/src/goldrush/BoniMichele.java
Java
mit
932
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input; namespace Paradix { public sealed class KeyboardController : IController { // TODO : List of keys UP / DOWN / PRESSED / RELEASED public PlayerIndex Player { get; set; } = PlayerIndex.One; public KeyboardState CurrentState { get; private set; } public KeyboardState PreviousState { get; private set; } public KeyboardController (PlayerIndex player = PlayerIndex.One) { Player = player; CurrentState = Keyboard.GetState (Player); PreviousState = CurrentState; } public bool IsKeyDown (Keys key) { return CurrentState.IsKeyDown (key); } public bool IsKeyUp (Keys key) { return CurrentState.IsKeyUp (key); } public bool IsKeyPressed (Keys key) { return CurrentState.IsKeyDown (key) && PreviousState.IsKeyUp (key); } public bool IsKeyReleased (Keys key) { return PreviousState.IsKeyDown (key) && CurrentState.IsKeyUp (key); } public void Flush (GameTime gameTime) { PreviousState = CurrentState; CurrentState = Keyboard.GetState (Player); } } }
NySwann/Paradix
Paradix.Engine/Input/KeyboardController.cs
C#
mit
1,092
module.exports = { parserOptions: { sourceType: 'script', }, };
jpikl/cfxnes
core/bin/.eslintrc.js
JavaScript
mit
72
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.docuware.dev.Extensions; import java.io.Closeable; import java.io.InputStream; /** * * @author Patrick */ public class EasyCheckoutResult implements Closeable { private String EncodedFileName; public String getEncodedFileName() { return EncodedFileName; } void setEncodedFileName(String data) { EncodedFileName = data; } private DeserializedHttpResponseGen<InputStream> response; public DeserializedHttpResponseGen<InputStream> getResponse() { return response; } void setResponse(DeserializedHttpResponseGen<InputStream> data) { response = data; } @Override public void close() { this.response.close(); } }
DocuWare/PlatformJavaClient
src/com/docuware/dev/Extensions/EasyCheckoutResult.java
Java
mit
949
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("BB.Poker.WinFormsClient")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("BB.Poker.WinFormsClient")] [assembly: AssemblyCopyright("Copyright © 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("9703352c-1cab-4c2a-bbc9-183b9245edc6")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
bberak/PokerDotNet
BB.Poker.WinFormsClient/Properties/AssemblyInfo.cs
C#
mit
1,422
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CharacterModelLib.Models { public class CharacterProject : NotifyableBase { public CharacterProject() { characterCollection = new ObservableCollection<Character>(); } void characterCollection_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { RaisePropertyChanged("CharacterCollection"); } Character selectedCharacter; public Character SelectedCharacter { get { return selectedCharacter; } set { if (selectedCharacter != null) { selectedCharacter.PropertyChanged -= selectedCharacter_PropertyChanged; } selectedCharacter = value; if (selectedCharacter != null) { selectedCharacter.PropertyChanged += selectedCharacter_PropertyChanged; } RaisePropertyChanged("SelectedCharacter"); RaisePropertyChanged("NextCharacter"); RaisePropertyChanged("PreviousCharacter"); } } public Character NextCharacter { get { if (selectedCharacter == null) { return CharacterCollection[0]; } int index = CharacterCollection.IndexOf(selectedCharacter); if (index >= CharacterCollection.Count - 1) { return CharacterCollection[0]; } else { return CharacterCollection[index + 1]; } } } public Character PreviousCharacter { get { if (selectedCharacter == null) { return CharacterCollection[CharacterCollection.Count - 1]; } int index = CharacterCollection.IndexOf(selectedCharacter); if (index <= 0) { return CharacterCollection[CharacterCollection.Count - 1]; } else { return CharacterCollection[index - 1]; } } } private void selectedCharacter_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { RaisePropertyChanged("SelectedCharacter." + e.PropertyName); //RaisePropertyChanged(e.PropertyName); //RaisePropertyChanged("SelectedCharacter"); } private ObservableCollection<Character> characterCollection; public ObservableCollection<Character> CharacterCollection { get { return characterCollection; } set { if (characterCollection != null) { characterCollection.CollectionChanged -= characterCollection_CollectionChanged; } characterCollection = value; if (characterCollection != null) { characterCollection.CollectionChanged += characterCollection_CollectionChanged; } RaisePropertyChanged("CharacterCollection"); } } private string name; public string Name { get { return name; } set { name = value; RaisePropertyChanged("Name"); } } private string projectPath; public string ProjectPath { get { return projectPath; } set { projectPath = value; RaisePropertyChanged("ProjectPath"); } } public override string ToString() { return base.ToString() + ": Name=" + Name; } public override bool Equals(object obj) { if (obj.GetType() == this.GetType()) { return ((obj as CharacterProject).Name == this.Name); } return false; } public override int GetHashCode() { return base.GetHashCode(); } } }
Salem5/CharacterEditor
CharacterModelLib/Models/CharacterProject.cs
C#
mit
4,559
import uuid from django.db import models from django.conf import settings from django.contrib.auth.models import AbstractUser from django.contrib.auth.models import BaseUserManager from django.utils import timezone from accelerator_abstract.models import BaseUserRole from accelerator_abstract.models.base_base_profile import EXPERT_USER_TYPE MAX_USERNAME_LENGTH = 30 class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, is_staff, is_superuser, **extra_fields): """ Creates and saves an User with the given email and password. """ now = timezone.now() if not email: raise ValueError('An email address must be provided.') email = self.normalize_email(email) if "is_active" not in extra_fields: extra_fields["is_active"] = True if "username" not in extra_fields: # For now we need to have a unique id that is at # most 30 characters long. Using uuid and truncating. # Ideally username goes away entirely at some point # since we're really using email. If we have to keep # username for some reason then we could switch over # to a string version of the pk which is guaranteed # be unique. extra_fields["username"] = str(uuid.uuid4())[:MAX_USERNAME_LENGTH] user = self.model(email=email, is_staff=is_staff, is_superuser=is_superuser, last_login=None, date_joined=now, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email=None, password=None, **extra_fields): return self._create_user(email, password, False, False, **extra_fields) def create_superuser(self, email, password, **extra_fields): return self._create_user(email, password, True, True, **extra_fields) class User(AbstractUser): # Override the parent email field to add uniqueness constraint email = models.EmailField(blank=True, unique=True) objects = UserManager() class Meta: db_table = 'auth_user' managed = settings.ACCELERATOR_MODELS_ARE_MANAGED def __init__(self, *args, **kwargs): super(User, self).__init__(*args, **kwargs) self.startup = None self.team_member = None self.profile = None self.user_finalist_roles = None class AuthenticationException(Exception): pass def __str__(self): return self.email def full_name(self): fn = self.first_name ln = self.last_name if fn and ln: name = u"%s %s" % (fn, ln) else: name = str(self.email) return name def user_phone(self): return self._get_profile().phone def image_url(self): return self._get_profile().image_url() def team_member_id(self): return self.team_member.id if self._get_member() else '' def user_title(self): return self._get_title_and_company()['title'] def user_twitter_handle(self): return self._get_profile().twitter_handle def user_linked_in_url(self): return self._get_profile().linked_in_url def user_facebook_url(self): return self._get_profile().facebook_url def user_personal_website_url(self): return self._get_profile().personal_website_url def type(self): return self._get_profile().user_type def startup_name(self): return self._get_title_and_company()['company'] def _get_title_and_company(self): if self._is_expert() and self._has_expert_details(): profile = self._get_profile() title = profile.title company = profile.company return { "title": title, "company": company } self._get_member() title = self.team_member.title if self.team_member else "" company = self.startup.name if self._get_startup() else None return { "title": title, "company": company } def _has_expert_details(self): if self._is_expert(): profile = self._get_profile() return True if profile.title or profile.company else False def startup_industry(self): return self.startup.primary_industry if self._get_startup() else None def top_level_startup_industry(self): industry = ( self.startup.primary_industry if self._get_startup() else None) return industry.parent if industry and industry.parent else industry def startup_status_names(self): if self._get_startup(): return [startup_status.program_startup_status.startup_status for startup_status in self.startup.startupstatus_set.all()] def finalist_user_roles(self): if not self.user_finalist_roles: finalist_roles = BaseUserRole.FINALIST_USER_ROLES self.user_finalist_roles = self.programrolegrant_set.filter( program_role__user_role__name__in=finalist_roles ).values_list('program_role__name', flat=True).distinct() return list(self.user_finalist_roles) def program(self): return self.startup.current_program() if self._get_startup() else None def location(self): program = self.program() return program.program_family.name if program else None def year(self): program = self.program() return program.start_date.year if program else None def is_team_member(self): return True if self._get_member() else False def _get_startup(self): if not self.startup: self._get_member() if self.team_member: self.startup = self.team_member.startup return self.startup def _get_member(self): if not self.team_member: self.team_member = self.startupteammember_set.last() return self.team_member def _get_profile(self): if self.profile: return self.profile self.profile = self.get_profile() return self.profile def has_a_finalist_role(self): return len(self.finalist_user_roles()) > 0 def _is_expert(self): profile = self._get_profile() return profile.user_type == EXPERT_USER_TYPE.lower()
masschallenge/django-accelerator
simpleuser/models.py
Python
mit
6,632
from setuptools import setup, find_packages from codecs import open import os def read(*paths): """Build a file path from *paths* and return the contents.""" with open(os.path.join(*paths), 'r') as f: return f.read() setup( name='transposer', version='0.0.3', description='Transposes columns and rows in delimited text files', long_description=(read('README.rst')), url='https://github.com/keithhamilton/transposer', author='Keith Hamilton', maintainer='Keith Hamilton', maintainer_email='the.keith.hamilton@gmail.com', license='BSD License', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Office/Business' ], keywords='text, csv, tab-delimited, delimited, excel, sheet, spreadsheet', packages=find_packages(exclude=['contrib', 'docs', 'test*', 'bin', 'include', 'lib', '.idea']), install_requires=[], package_data={}, data_files=[], entry_points={ 'console_scripts': [ 'transposer=transposer.script.console_script:main' ] } )
keithhamilton/transposer
setup.py
Python
mit
1,307
package experiments; import java.io.File; import java.util.Arrays; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import data.StateImpl; import datahandler.word2vec.MedicalSequenceIterator; import state2vec.State2Vec; public class State2VecTest { protected static final Logger logger = LoggerFactory.getLogger(State2VecTest.class); public State2VecTest(File file, String run) throws Exception { List<Integer> windowSizes; List<Double> learningRates; if(run.equals("0")){ logger.info("Run 0"); windowSizes = Arrays.asList(5); learningRates = Arrays.asList(0.025, 0.1); } else if(run.equals("1")) { logger.info("Run 1"); windowSizes = Arrays.asList(5); learningRates = Arrays.asList(0.1); } else if(run.equals("2")) { logger.info("Run 2"); windowSizes = Arrays.asList(10); learningRates = Arrays.asList(0.025); } else if(run.equals("3")) { logger.info("Run 3"); windowSizes = Arrays.asList(10); learningRates = Arrays.asList(0.1); } else if(run.equals("4")) { logger.info("Run 4"); windowSizes = Arrays.asList(15); learningRates = Arrays.asList(0.025); } else { logger.info("Run " + run); windowSizes = Arrays.asList(15); learningRates = Arrays.asList(0.1); } //List<Integer> windowSizes = Arrays.asList(5, 10, 15); //List<Double> learningRates = Arrays.asList(0.025, 0.1); List<Integer> vectorLengths = Arrays.asList(50, 100); List<Integer> minWordFreqs = Arrays.asList(5, 10); int batchsize = 500; int epoch = 1; MedicalSequenceIterator<StateImpl> sequenceIterator = new MedicalSequenceIterator<StateImpl>(file, false); for(int windowSize: windowSizes) { for(double learningRate: learningRates) { for(int vectorLength: vectorLengths) { for(int minWordFreq: minWordFreqs) { logger.info("STATE2VEC - EXPERIMENT"); logger.info(""); logger.info("==PARAMETERS=="); logger.info("windowSize: " + windowSize); logger.info("learningRate: " + learningRate); logger.info("vectorLength: " + vectorLength); logger.info("batchSize: " + batchsize); logger.info("epoch: " + epoch); logger.info("minWordFreq: " + minWordFreq); logger.info(""); sequenceIterator.reset(); State2Vec state2vec = new State2Vec(); state2vec.trainSequenceVectors(sequenceIterator, windowSize, learningRate, vectorLength, batchsize, epoch, minWordFreq); List<Integer> ks = Arrays.asList(100, 1000, 5000); ClusterSeqTest clusterTest = new ClusterSeqTest(); for(int k: ks) { ResultWriter writer1 = new ResultWriter("State2Vec - ", "Cluster1Test"); writer1.writeLine("STATE2VEC - EXPERIMENT"); writer1.writeLine(""); writer1.writeLine("==PARAMETERS=="); writer1.writeLine("windowSize: " + windowSize); writer1.writeLine("learningRate: " + learningRate); writer1.writeLine("vectorLength: " + vectorLength); writer1.writeLine("batchSize: " + batchsize); writer1.writeLine("epoch: " + epoch); writer1.writeLine("minWordFreq: " + minWordFreq); writer1.writeLine(""); clusterTest.checkClusters1(state2vec.getTrainedModel(), k, writer1); ResultWriter writer2 = new ResultWriter("State2Vec - ", "Cluster2Test"); writer2.writeLine("STATE2VEC - EXPERIMENT"); writer2.writeLine(""); writer2.writeLine("==PARAMETERS=="); writer2.writeLine("windowSize: " + windowSize); writer2.writeLine("learningRate: " + learningRate); writer2.writeLine("vectorLength: " + vectorLength); writer2.writeLine("batchSize: " + batchsize); writer2.writeLine("epoch: " + epoch); writer2.writeLine("minWordFreq: " + minWordFreq); writer2.writeLine(""); clusterTest.checkClusters2(state2vec.getTrainedModel(), k, writer2); } } } } } } }
Milanvdm/MedicalLSTM
src/main/java/experiments/State2VecTest.java
Java
mit
4,075
<?php /* * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This software consists of voluntary contributions made by many individuals * and is licensed under the MIT license. For more information, see * <http://www.doctrine-project.org>. */ namespace Doctrine\ODM\MongoDB\Mapping\Annotations; use Doctrine\Common\Annotations\Annotation; abstract class AbstractDocument extends Annotation { }
CaoPhiHung/CRM
vendor/doctrine/mongodb-odm/lib/Doctrine/ODM/MongoDB/Mapping/Annotations/AbstractDocument.php
PHP
mit
1,168
package lv.emes.libraries.utilities.validation; /** * Actions for error that occur in validation process. * * @author eMeS * @version 1.2. */ public interface MS_ValidationError<T> { MS_ValidationError withErrorMessageFormingAction(IFuncFormValidationErrorMessage action); /** * Returns message of validation error using pre-defined method to form message. * @return formatted message describing essence of this particular validation error. */ String getMessage(); Integer getNumber(); T getObject(); /** * @param object an object to validate. * @return reference to validation error itself. */ MS_ValidationError withObject(T object); }
LV-eMeS/eMeS_Libraries
src/main/java/lv/emes/libraries/utilities/validation/MS_ValidationError.java
Java
mit
706
window.ImageViewer = function(url, alt, title){ var img = $('<img />').attr('src', url).attr('alt', title).css({ display: 'inline-block', 'max-width': '90vw', 'max-height': '90vh' }); var a = $('<a></a>').attr('target', '_blank') .attr('title', title) .attr('href', url) .css({ display: 'inline-block', height: '100%' }) .append(img); var close_it = function(){ overlay.remove(); container.remove(); }; var closeBtn = $('<a class="icon-remove-sign"></a>').css({ color: 'red', 'font-size': 'x-large', 'margin-left': '-0.1em' }).bind('click', close_it); var closeWrapper = $('<div></div>').css({ height: '100%', width: '2em', 'text-align': 'left', 'display': 'inline-block', 'vertical-algin': 'top', 'margin-top': '-0.6em', 'float': 'right' }).append(closeBtn); var container = $('<div></div>').append( $('<div></div>').css({ margin: '5vh 1vw', display: 'inline-block', 'vertical-align': 'top' }).append(a).append(closeWrapper)) .css({ 'z-index': 30000000, 'position': 'fixed', 'padding': 0, 'margin': 0, 'width': '100vw', 'height': '100vh', 'top': 0, 'left': 0, 'text-align': 'center', 'cursor': 'default', 'vertical-align': 'middle' }) .bind('click',close_it) .appendTo('body'); var overlay = $('<div class="blockUI blockMsg blockPage">').css({ 'z-index': 9999, 'position': 'fixed', padding: 0, margin: 0, width: '100vw', height: '100vh', top: '0vh', left: '0vw', 'text-align': 'center', 'cursor': 'default', 'vertical-align': 'middle', 'background-color': 'gray', 'opacity': '0.4' }).bind('click', close_it).appendTo('body'); this.close = close_it; return this; }
clazz/clazz.github.io
js/image-viewer.js
JavaScript
mit
2,216
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-11-01 20:02 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('phone_numbers', '0001_initial'), ('sims', '0001_initial'), ] operations = [ migrations.AddField( model_name='phonenumber', name='related_sim', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='phone_numbers', to='sims.Sim'), ), ]
RobSpectre/garfield
garfield/phone_numbers/migrations/0002_phonenumber_related_sim.py
Python
mit
626
package ch.spacebase.openclassic.api; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.net.URLEncoder; import java.security.SecureRandom; import java.util.HashMap; import java.util.Map; import ch.spacebase.openclassic.api.util.Constants; /** * Manages the server's web heartbeats. */ public final class HeartbeatManager { private static final long salt = new SecureRandom().nextLong(); private static final Map<String, Runnable> customBeats = new HashMap<String, Runnable>(); private static String url = ""; /** * Gets the server's current salt. * @return The server's salt. */ public static long getSalt() { return salt; } /** * Gets the server's minecraft.net url. * @return The url. */ public static String getURL() { return url; } /** * Sets the server's known minecraft.net url. * @param url The url. */ public static void setURL(String url) { HeartbeatManager.url = url; } /** * Triggers a heartbeat. */ public static void beat() { mineBeat(); womBeat(); for(String id : customBeats.keySet()) { try { customBeats.get(id).run(); } catch(Exception e) { OpenClassic.getLogger().severe("Exception while running a custom heartbeat with the ID \"" + id + "\"!"); e.printStackTrace(); } } } /** * Adds a custom heartbeat to run when {@link beat()} is called. * @param id ID of the custom heartbeat. * @param run Runnable to call when beating. */ public static void addBeat(String id, Runnable run) { customBeats.put(id, run); } /** * Removes a custom heartbeat. * @param id ID of the heartbeat. */ public static void removeBeat(String id) { customBeats.remove(id); } /** * Clears the custom heartbeat list. */ public static void clearBeats() { customBeats.clear(); } private static void mineBeat() { URL url = null; try { url = new URL("https://minecraft.net/heartbeat.jsp?port=" + OpenClassic.getServer().getPort() + "&max=" + OpenClassic.getServer().getMaxPlayers() + "&name=" + URLEncoder.encode(Color.stripColor(OpenClassic.getServer().getServerName()), "UTF-8") + "&public=" + OpenClassic.getServer().isPublic() + "&version=" + Constants.PROTOCOL_VERSION + "&salt=" + salt + "&users=" + OpenClassic.getServer().getPlayers().size()); } catch(MalformedURLException e) { OpenClassic.getLogger().severe("Malformed URL while attempting minecraft.net heartbeat?"); return; } catch(UnsupportedEncodingException e) { OpenClassic.getLogger().severe("UTF-8 URL encoding is unsupported on your system."); return; } HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); try { conn.setRequestMethod("GET"); } catch (ProtocolException e) { OpenClassic.getLogger().severe("Exception while performing minecraft.net heartbeat: Connection doesn't support GET...?"); return; } conn.setDoOutput(false); conn.setDoInput(true); conn.setUseCaches(false); conn.setAllowUserInteraction(false); conn.setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8"); InputStream input = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(input)); String result = reader.readLine(); reader.close(); input.close(); if(!HeartbeatManager.url.equals(result)) { HeartbeatManager.url = result; OpenClassic.getLogger().info(Color.GREEN + "The server's URL is now \"" + getURL() + "\"."); try { File file = new File(OpenClassic.getGame().getDirectory(), "server-address.txt"); if(!file.exists()) file.createNewFile(); BufferedWriter writer = new BufferedWriter(new FileWriter(file)); writer.write(result); writer.close(); } catch(IOException e) { OpenClassic.getLogger().severe("Failed to save server address!"); e.printStackTrace(); } } } catch (IOException e) { OpenClassic.getLogger().severe("Exception while performing minecraft.net heartbeat!"); e.printStackTrace(); } finally { if (conn != null) conn.disconnect(); } } private static void womBeat() { URL url = null; try { url = new URL("http://direct.worldofminecraft.com/hb.php?port=" + OpenClassic.getServer().getPort() + "&max=" + OpenClassic.getServer().getMaxPlayers() + "&name=" + URLEncoder.encode(Color.stripColor(OpenClassic.getServer().getServerName()), "UTF-8") + "&public=" + OpenClassic.getServer().isPublic() + "&version=" + Constants.PROTOCOL_VERSION + "&salt=" + salt + "&users=" + OpenClassic.getServer().getPlayers().size() + "&noforward=1"); } catch(MalformedURLException e) { OpenClassic.getLogger().severe("Malformed URL while attempting WOM heartbeat?"); return; } catch(UnsupportedEncodingException e) { OpenClassic.getLogger().severe("UTF-8 URL encoding is unsupported on your system."); return; } HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(false); conn.setDoInput(false); conn.setUseCaches(false); conn.setAllowUserInteraction(false); conn.setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8"); } catch (IOException e) { OpenClassic.getLogger().severe("Exception while performing WOM heartbeat!"); e.printStackTrace(); } finally { if (conn != null) conn.disconnect(); } } }
good2000mo/OpenClassicAPI
src/main/java/ch/spacebase/openclassic/api/HeartbeatManager.java
Java
mit
5,720
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ParkingRampSimulator { public class ParkingRamp : ParkingConstruct { [Newtonsoft.Json.JsonIgnore] public List<ParkingFloor> Floors { get; private set; } public override bool IsFull { get { return OpenLocations < 1; } } public override int OpenLocations { get { return Floors.Sum(r => r.OpenLocations) - InQueue.Count; } } public override int TotalLocations { get { return Floors.Sum(r => r.TotalLocations); } } public ParkingRamp(ParkingConstruct parent, string name, int floorCount, int locationCount) : base(parent, name) { Name = name; Floors = new List<ParkingFloor>(); for (int i = 0; i < floorCount; i++) { Floors.Add(new ParkingFloor(this, string.Format("{0}-{1}", Name, i.ToString()), locationCount)); } } public override void Tick() { var openCount = Floors.Count(r => !r.IsFull); if (openCount > 0) { var gateCapacity = (int)(Simulator.Interval.TotalSeconds / 10.0); for (int i = 0; i < gateCapacity; i++) { var floorsWithRoom = Floors.Where(r => !r.IsFull).ToList(); if (InQueue.Count > 0 && floorsWithRoom.Count > 0) { var floor = Simulator.Random.Next(floorsWithRoom.Count); floorsWithRoom[floor].InQueue.Enqueue(InQueue.Dequeue()); } } } foreach (var item in Floors) item.Tick(); base.Tick(); while (OutQueue.Count > 0) Parent.OutQueue.Enqueue(OutQueue.Dequeue()); } } }
rockfordlhotka/DistributedComputingDemo
src/ParkingSim/ParkingRampSimulator/ParkingRamp.cs
C#
mit
2,080
package org.gojul.gojulutils.data; /** * Class {@code GojulPair} is a simple stupid pair class. This class is notably necessary * when emulating JOIN in database and such a class does not exist natively in the JDK. * This object is immutable as long as the object it contains are immutable. Since * this object is not serializable it should not be stored in objects which could be serialized, * especially Java HttpSession objects. * * @param <S> the type of the first object of the pair. * @param <T> the type of the second object of the pair. * @author jaubin */ public final class GojulPair<S, T> { private final S first; private final T second; /** * Constructor. Both parameters are nullable. Note that this constructor * does not perform any defensive copy as it is not possible there. * * @param first the first object. * @param second the second object. */ public GojulPair(final S first, final T second) { this.first = first; this.second = second; } /** * Return the first object. * * @return the first object. */ public S getFirst() { return first; } /** * Return the second object. * * @return the second object. */ public T getSecond() { return second; } /** * {@inheritDoc} */ @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; GojulPair<?, ?> pair = (GojulPair<?, ?>) o; if (getFirst() != null ? !getFirst().equals(pair.getFirst()) : pair.getFirst() != null) return false; return getSecond() != null ? getSecond().equals(pair.getSecond()) : pair.getSecond() == null; } /** * {@inheritDoc} */ @Override public int hashCode() { int result = getFirst() != null ? getFirst().hashCode() : 0; result = 31 * result + (getSecond() != null ? getSecond().hashCode() : 0); return result; } /** * {@inheritDoc} */ @Override public String toString() { return "GojulPair{" + "first=" + first + ", second=" + second + '}'; } }
jaubin/gojulutils
src/main/java/org/gojul/gojulutils/data/GojulPair.java
Java
mit
2,277
using System.Collections.Generic; using System.Diagnostics.Contracts; using Microsoft.CodeAnalysis; namespace ErrorProne.NET.Extensions { public static class SyntaxNodeExtensions { public static IEnumerable<SyntaxNode> EnumerateParents(this SyntaxNode node) { Contract.Requires(node != null); while (node.Parent != null) { yield return node.Parent; node = node.Parent; } } } }
SergeyTeplyakov/ErrorProne.NET
src/ErrorProne.NET/ErrorProne.NET/Extensions/SyntaxNodeExtensions.cs
C#
mit
496
/*-------------------------------------------- Created by Sina on 06/05/13. Copyright (c) 2013 MIT. All rights reserved. --------------------------------------------*/ #include "elements.h" #include "mpi_compat.h" #include "gcmc.h" #include "memory.h" #include "random.h" #include "neighbor.h" #include "ff_md.h" #include "MAPP.h" #include "atoms_md.h" #include "comm.h" #include "dynamic_md.h" using namespace MAPP_NS; /*-------------------------------------------- constructor --------------------------------------------*/ GCMC::GCMC(AtomsMD*& __atoms,ForceFieldMD*&__ff,DynamicMD*& __dynamic,elem_type __gas_type,type0 __mu,type0 __T,int seed): gas_type(__gas_type), T(__T), mu(__mu), natms_lcl(__atoms->natms_lcl), natms_ph(__atoms->natms_ph), cut_sq(__ff->cut_sq), s_lo(__atoms->comm.s_lo), s_hi(__atoms->comm.s_hi), dynamic(__dynamic), world(__atoms->comm.world), atoms(__atoms), ff(__ff), ielem(gas_type) { random=new Random(seed); s_trials=new type0*[__dim__]; *s_trials=NULL; del_ids=NULL; del_ids_sz=del_ids_cpcty=0; vars=lcl_vars=NULL; } /*-------------------------------------------- destructor --------------------------------------------*/ GCMC::~GCMC() { delete [] del_ids; delete [] s_trials; delete random; } /*-------------------------------------------- --------------------------------------------*/ void GCMC::add_del_id(int* new_ids,int no) { if(del_ids_sz+no>del_ids_cpcty) { int* del_ids_=new int[del_ids_sz+no]; memcpy(del_ids_,del_ids,del_ids_sz*sizeof(int)); del_ids_cpcty=del_ids_sz+no; delete [] del_ids; del_ids=del_ids_; } memcpy(del_ids+del_ids_sz,new_ids,sizeof(int)*no); del_ids_sz+=no; } /*-------------------------------------------- --------------------------------------------*/ int GCMC::get_new_id() { if(del_ids_sz) { del_ids_sz--; return del_ids[del_ids_sz]; } else { max_id++; return max_id; } } /*-------------------------------------------- --------------------------------------------*/ void GCMC::init() { cut=ff->cut[ielem][0]; for(size_t i=1;i<atoms->elements.nelems;i++) cut=MAX(cut,ff->cut[ielem][i]); gas_mass=atoms->elements.masses[gas_type]; kbT=atoms->kB*T; beta=1.0/kbT; lambda=atoms->hP/sqrt(2.0*M_PI*kbT*gas_mass); sigma=sqrt(kbT/gas_mass); z_fac=1.0; for(int i=0;i<__dim__;i++) z_fac/=lambda; z_fac*=exp(beta*mu); vol=1.0; for(int i=0;i<__dim__;i++)vol*=atoms->H[i][i]; id_type max_id_=0; id_type* id=atoms->id->begin(); for(int i=0;i<natms_lcl;i++) max_id_=MAX(id[i],max_id_); MPI_Allreduce(&max_id_,&max_id,1,Vec<id_type>::MPI_T,MPI_MAX,world); for(int i=0;i<del_ids_sz;i++) max_id=MAX(max_id,del_ids[i]); ngas_lcl=0; elem_type* elem=atoms->elem->begin(); for(int i=0;i<natms_lcl;i++) if(elem[i]==gas_type) ngas_lcl++; MPI_Allreduce(&ngas_lcl,&ngas,1,MPI_INT,MPI_SUM,world); } /*-------------------------------------------- --------------------------------------------*/ void GCMC::fin() { } /*-------------------------------------------- --------------------------------------------*/ void GCMC::box_setup() { int sz=0; max_ntrial_atms=1; for(int i=0;i<__dim__;i++) { type0 tmp=0.0; for(int j=i;j<__dim__;j++) tmp+=atoms->B[j][i]*atoms->B[j][i]; cut_s[i]=sqrt(tmp)*cut; s_lo_ph[i]=s_lo[i]-cut_s[i]; s_hi_ph[i]=s_hi[i]+cut_s[i]; nimages_per_dim[i][0]=static_cast<int>(floor(s_hi_ph[i])); nimages_per_dim[i][1]=-static_cast<int>(floor(s_lo_ph[i])); max_ntrial_atms*=1+nimages_per_dim[i][0]+nimages_per_dim[i][1]; sz+=1+nimages_per_dim[i][0]+nimages_per_dim[i][1]; } *s_trials=new type0[sz]; for(int i=1;i<__dim__;i++) s_trials[i]=s_trials[i-1]+1+nimages_per_dim[i-1][0]+nimages_per_dim[i-1][1]; } /*-------------------------------------------- --------------------------------------------*/ void GCMC::box_dismantle() { delete [] *s_trials; *s_trials=NULL; }
sinamoeini/mapp4py
src/gcmc.cpp
C++
mit
4,193
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ var app = { // Application Constructor initialize: function() { this.bindEvents(); }, // Bind Event Listeners // // Bind any events that are required on startup. Common events are: // 'load', 'deviceready', 'offline', and 'online'. bindEvents: function() { document.addEventListener('deviceready', this.onDeviceReady, false); }, // deviceready Event Handler // // The scope of 'this' is the event. In order to call the 'receivedEvent' // function, we must explicitly call 'app.receivedEvent(...);' onDeviceReady: function() { app.receivedEvent('deviceready'); }, // Update DOM on a Received Event receivedEvent: function(id) { } }; app.initialize();
ttosi/moodbeam
mobile/www/js/index.js
JavaScript
mit
1,553
#include <ESP8266WiFi.h> #include <PubSubClient.h> #include "mqtt.h" // Connect to MQTT and set up subscriptions based on configuration void MQTT::connect() { // Connect to broker this->mqttClient.setServer(this->host, this->port); mqttClient.connect(this->clientId); Serial.print("Connected to MQTT, with server: "); Serial.print(this->host); Serial.print(", port: "); Serial.print(this->port); Serial.print(", with client ID: "); Serial.println(this->clientId); // Send ping ping(); } // Send ping to MQTT broker void MQTT::ping() { char payload[50]; sprintf(payload, "%s ok", this->clientId); this->mqttClient.publish("/status", payload); Serial.println("Sent ping to broker"); }
capmake/robot-firmware
src/mqtt.cpp
C++
mit
745
using System.Collections.Generic; namespace SmartMeter.Business.Interface.Mapper { public interface IMapTelegram { Persistence.Interface.ITelegram Map(ITelegram businessTelegram); Business.Interface.ITelegram Map(Persistence.Interface.ITelegram persistenceTelegram); IEnumerable<ITelegram> Map(IEnumerable<Persistence.Interface.ITelegram> persistenceTelegrams); } }
jeroen-corsius/smart-meter
SmartMeter.Business.Interface/Mapper/IMapTelegram.cs
C#
mit
393
define("helios/Helios-Debugger", ["amber/boot", "amber_core/Kernel-Objects", "helios/Helios-Core", "helios/Helios-Workspace"], function($boot){ var smalltalk=$boot.vm,nil=$boot.nil,_st=$boot.asReceiver,globals=$boot.globals; smalltalk.addPackage('Helios-Debugger'); smalltalk.packages["Helios-Debugger"].transport = {"type":"amd","amdNamespace":"helios"}; smalltalk.addClass('HLContextInspectorDecorator', globals.Object, ['context'], 'Helios-Debugger'); smalltalk.addMethod( smalltalk.method({ selector: "context", protocol: 'accessing', fn: function (){ var self=this; var $1; $1=self["@context"]; return $1; }, args: [], source: "context\x0a\x09^ context", messageSends: [], referencedClasses: [] }), globals.HLContextInspectorDecorator); smalltalk.addMethod( smalltalk.method({ selector: "evaluate:on:", protocol: 'evaluating', fn: function (aString,anEvaluator){ var self=this; return smalltalk.withContext(function($ctx1) { var $1; $1=_st(self._context())._evaluate_on_(aString,anEvaluator); return $1; }, function($ctx1) {$ctx1.fill(self,"evaluate:on:",{aString:aString,anEvaluator:anEvaluator},globals.HLContextInspectorDecorator)})}, args: ["aString", "anEvaluator"], source: "evaluate: aString on: anEvaluator\x0a\x09^ self context evaluate: aString on: anEvaluator", messageSends: ["evaluate:on:", "context"], referencedClasses: [] }), globals.HLContextInspectorDecorator); smalltalk.addMethod( smalltalk.method({ selector: "initializeFromContext:", protocol: 'initialization', fn: function (aContext){ var self=this; self["@context"]=aContext; return self}, args: ["aContext"], source: "initializeFromContext: aContext\x0a\x09context := aContext", messageSends: [], referencedClasses: [] }), globals.HLContextInspectorDecorator); smalltalk.addMethod( smalltalk.method({ selector: "inspectOn:", protocol: 'inspecting', fn: function (anInspector){ var self=this; var variables,inspectedContext; function $Dictionary(){return globals.Dictionary||(typeof Dictionary=="undefined"?nil:Dictionary)} return smalltalk.withContext(function($ctx1) { var $1,$2,$3,$4,$receiver; variables=_st($Dictionary())._new(); inspectedContext=self._context(); $1=variables; $2=_st(inspectedContext)._locals(); $ctx1.sendIdx["locals"]=1; _st($1)._addAll_($2); $ctx1.sendIdx["addAll:"]=1; _st((function(){ return smalltalk.withContext(function($ctx2) { return _st(_st(inspectedContext)._notNil())._and_((function(){ return smalltalk.withContext(function($ctx3) { return _st(inspectedContext)._isBlockContext(); }, function($ctx3) {$ctx3.fillBlock({},$ctx2,2)})})); }, function($ctx2) {$ctx2.fillBlock({},$ctx1,1)})}))._whileTrue_((function(){ return smalltalk.withContext(function($ctx2) { inspectedContext=_st(inspectedContext)._outerContext(); inspectedContext; $3=inspectedContext; if(($receiver = $3) == null || $receiver.isNil){ return $3; } else { return _st(variables)._addAll_(_st(inspectedContext)._locals()); }; }, function($ctx2) {$ctx2.fillBlock({},$ctx1,3)})})); _st(anInspector)._setLabel_("Context"); $4=_st(anInspector)._setVariables_(variables); return self}, function($ctx1) {$ctx1.fill(self,"inspectOn:",{anInspector:anInspector,variables:variables,inspectedContext:inspectedContext},globals.HLContextInspectorDecorator)})}, args: ["anInspector"], source: "inspectOn: anInspector\x0a\x09| variables inspectedContext |\x0a\x09\x0a\x09variables := Dictionary new.\x0a\x09inspectedContext := self context.\x0a\x09\x0a\x09variables addAll: inspectedContext locals.\x0a\x09\x0a\x09[ inspectedContext notNil and: [ inspectedContext isBlockContext ] ] whileTrue: [\x0a\x09\x09inspectedContext := inspectedContext outerContext.\x0a\x09\x09inspectedContext ifNotNil: [\x0a\x09\x09\x09variables addAll: inspectedContext locals ] ].\x0a\x09\x0a\x09anInspector\x0a\x09\x09setLabel: 'Context';\x0a\x09\x09setVariables: variables", messageSends: ["new", "context", "addAll:", "locals", "whileTrue:", "and:", "notNil", "isBlockContext", "outerContext", "ifNotNil:", "setLabel:", "setVariables:"], referencedClasses: ["Dictionary"] }), globals.HLContextInspectorDecorator); smalltalk.addMethod( smalltalk.method({ selector: "on:", protocol: 'instance creation', fn: function (aContext){ var self=this; return smalltalk.withContext(function($ctx1) { var $2,$3,$1; $2=self._new(); _st($2)._initializeFromContext_(aContext); $3=_st($2)._yourself(); $1=$3; return $1; }, function($ctx1) {$ctx1.fill(self,"on:",{aContext:aContext},globals.HLContextInspectorDecorator.klass)})}, args: ["aContext"], source: "on: aContext\x0a\x09^ self new\x0a\x09\x09initializeFromContext: aContext;\x0a\x09\x09yourself", messageSends: ["initializeFromContext:", "new", "yourself"], referencedClasses: [] }), globals.HLContextInspectorDecorator.klass); smalltalk.addClass('HLDebugger', globals.HLFocusableWidget, ['model', 'stackListWidget', 'codeWidget', 'inspectorWidget'], 'Helios-Debugger'); globals.HLDebugger.comment="I am the main widget for the Helios debugger."; smalltalk.addMethod( smalltalk.method({ selector: "codeWidget", protocol: 'widgets', fn: function (){ var self=this; function $HLDebuggerCodeWidget(){return globals.HLDebuggerCodeWidget||(typeof HLDebuggerCodeWidget=="undefined"?nil:HLDebuggerCodeWidget)} function $HLDebuggerCodeModel(){return globals.HLDebuggerCodeModel||(typeof HLDebuggerCodeModel=="undefined"?nil:HLDebuggerCodeModel)} return smalltalk.withContext(function($ctx1) { var $2,$3,$4,$6,$7,$8,$9,$5,$10,$1,$receiver; $2=self["@codeWidget"]; if(($receiver = $2) == null || $receiver.isNil){ $3=_st($HLDebuggerCodeWidget())._new(); $ctx1.sendIdx["new"]=1; $4=$3; $6=_st($HLDebuggerCodeModel())._new(); $7=$6; $8=self._model(); $ctx1.sendIdx["model"]=1; _st($7)._debuggerModel_($8); $9=_st($6)._yourself(); $ctx1.sendIdx["yourself"]=1; $5=$9; _st($4)._model_($5); _st($3)._browserModel_(self._model()); $10=_st($3)._yourself(); self["@codeWidget"]=$10; $1=self["@codeWidget"]; } else { $1=$2; }; return $1; }, function($ctx1) {$ctx1.fill(self,"codeWidget",{},globals.HLDebugger)})}, args: [], source: "codeWidget\x0a\x09^ codeWidget ifNil: [ codeWidget := HLDebuggerCodeWidget new\x0a\x09\x09model: (HLDebuggerCodeModel new\x0a\x09\x09\x09debuggerModel: self model;\x0a\x09\x09\x09yourself);\x0a\x09\x09browserModel: self model;\x0a\x09\x09yourself ]", messageSends: ["ifNil:", "model:", "new", "debuggerModel:", "model", "yourself", "browserModel:"], referencedClasses: ["HLDebuggerCodeWidget", "HLDebuggerCodeModel"] }), globals.HLDebugger); smalltalk.addMethod( smalltalk.method({ selector: "cssClass", protocol: 'accessing', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { var $2,$1; $2=($ctx1.supercall = true, globals.HLDebugger.superclass.fn.prototype._cssClass.apply(_st(self), [])); $ctx1.supercall = false; $1=_st($2).__comma(" hl_debugger"); return $1; }, function($ctx1) {$ctx1.fill(self,"cssClass",{},globals.HLDebugger)})}, args: [], source: "cssClass\x0a\x09^ super cssClass, ' hl_debugger'", messageSends: [",", "cssClass"], referencedClasses: [] }), globals.HLDebugger); smalltalk.addMethod( smalltalk.method({ selector: "focus", protocol: 'actions', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { _st(self._stackListWidget())._focus(); return self}, function($ctx1) {$ctx1.fill(self,"focus",{},globals.HLDebugger)})}, args: [], source: "focus\x0a\x09self stackListWidget focus", messageSends: ["focus", "stackListWidget"], referencedClasses: [] }), globals.HLDebugger); smalltalk.addMethod( smalltalk.method({ selector: "initializeFromError:", protocol: 'initialization', fn: function (anError){ var self=this; function $HLDebuggerModel(){return globals.HLDebuggerModel||(typeof HLDebuggerModel=="undefined"?nil:HLDebuggerModel)} return smalltalk.withContext(function($ctx1) { self["@model"]=_st($HLDebuggerModel())._on_(anError); self._observeModel(); return self}, function($ctx1) {$ctx1.fill(self,"initializeFromError:",{anError:anError},globals.HLDebugger)})}, args: ["anError"], source: "initializeFromError: anError\x0a\x09model := HLDebuggerModel on: anError.\x0a\x09self observeModel", messageSends: ["on:", "observeModel"], referencedClasses: ["HLDebuggerModel"] }), globals.HLDebugger); smalltalk.addMethod( smalltalk.method({ selector: "inspectorWidget", protocol: 'widgets', fn: function (){ var self=this; function $HLInspectorWidget(){return globals.HLInspectorWidget||(typeof HLInspectorWidget=="undefined"?nil:HLInspectorWidget)} return smalltalk.withContext(function($ctx1) { var $2,$1,$receiver; $2=self["@inspectorWidget"]; if(($receiver = $2) == null || $receiver.isNil){ self["@inspectorWidget"]=_st($HLInspectorWidget())._new(); $1=self["@inspectorWidget"]; } else { $1=$2; }; return $1; }, function($ctx1) {$ctx1.fill(self,"inspectorWidget",{},globals.HLDebugger)})}, args: [], source: "inspectorWidget\x0a\x09^ inspectorWidget ifNil: [ \x0a\x09\x09inspectorWidget := HLInspectorWidget new ]", messageSends: ["ifNil:", "new"], referencedClasses: ["HLInspectorWidget"] }), globals.HLDebugger); smalltalk.addMethod( smalltalk.method({ selector: "model", protocol: 'accessing', fn: function (){ var self=this; function $HLDebuggerModel(){return globals.HLDebuggerModel||(typeof HLDebuggerModel=="undefined"?nil:HLDebuggerModel)} return smalltalk.withContext(function($ctx1) { var $2,$1,$receiver; $2=self["@model"]; if(($receiver = $2) == null || $receiver.isNil){ self["@model"]=_st($HLDebuggerModel())._new(); $1=self["@model"]; } else { $1=$2; }; return $1; }, function($ctx1) {$ctx1.fill(self,"model",{},globals.HLDebugger)})}, args: [], source: "model\x0a\x09^ model ifNil: [ model := HLDebuggerModel new ]", messageSends: ["ifNil:", "new"], referencedClasses: ["HLDebuggerModel"] }), globals.HLDebugger); smalltalk.addMethod( smalltalk.method({ selector: "observeModel", protocol: 'actions', fn: function (){ var self=this; function $HLDebuggerContextSelected(){return globals.HLDebuggerContextSelected||(typeof HLDebuggerContextSelected=="undefined"?nil:HLDebuggerContextSelected)} function $HLDebuggerStepped(){return globals.HLDebuggerStepped||(typeof HLDebuggerStepped=="undefined"?nil:HLDebuggerStepped)} function $HLDebuggerProceeded(){return globals.HLDebuggerProceeded||(typeof HLDebuggerProceeded=="undefined"?nil:HLDebuggerProceeded)} return smalltalk.withContext(function($ctx1) { var $1,$2; $1=_st(self._model())._announcer(); _st($1)._on_send_to_($HLDebuggerContextSelected(),"onContextSelected:",self); $ctx1.sendIdx["on:send:to:"]=1; _st($1)._on_send_to_($HLDebuggerStepped(),"onDebuggerStepped:",self); $ctx1.sendIdx["on:send:to:"]=2; $2=_st($1)._on_send_to_($HLDebuggerProceeded(),"onDebuggerProceeded",self); return self}, function($ctx1) {$ctx1.fill(self,"observeModel",{},globals.HLDebugger)})}, args: [], source: "observeModel\x0a\x09self model announcer \x0a\x09\x09on: HLDebuggerContextSelected\x0a\x09\x09send: #onContextSelected:\x0a\x09\x09to: self;\x0a\x09\x09\x0a\x09\x09on: HLDebuggerStepped\x0a\x09\x09send: #onDebuggerStepped:\x0a\x09\x09to: self;\x0a\x09\x09\x0a\x09\x09on: HLDebuggerProceeded\x0a\x09\x09send: #onDebuggerProceeded\x0a\x09\x09to: self", messageSends: ["on:send:to:", "announcer", "model"], referencedClasses: ["HLDebuggerContextSelected", "HLDebuggerStepped", "HLDebuggerProceeded"] }), globals.HLDebugger); smalltalk.addMethod( smalltalk.method({ selector: "onContextSelected:", protocol: 'reactions', fn: function (anAnnouncement){ var self=this; function $HLContextInspectorDecorator(){return globals.HLContextInspectorDecorator||(typeof HLContextInspectorDecorator=="undefined"?nil:HLContextInspectorDecorator)} return smalltalk.withContext(function($ctx1) { _st(self._inspectorWidget())._inspect_(_st($HLContextInspectorDecorator())._on_(_st(anAnnouncement)._context())); return self}, function($ctx1) {$ctx1.fill(self,"onContextSelected:",{anAnnouncement:anAnnouncement},globals.HLDebugger)})}, args: ["anAnnouncement"], source: "onContextSelected: anAnnouncement\x0a\x09self inspectorWidget inspect: (HLContextInspectorDecorator on: anAnnouncement context)", messageSends: ["inspect:", "inspectorWidget", "on:", "context"], referencedClasses: ["HLContextInspectorDecorator"] }), globals.HLDebugger); smalltalk.addMethod( smalltalk.method({ selector: "onDebuggerProceeded", protocol: 'reactions', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { self._removeTab(); return self}, function($ctx1) {$ctx1.fill(self,"onDebuggerProceeded",{},globals.HLDebugger)})}, args: [], source: "onDebuggerProceeded\x0a\x09self removeTab", messageSends: ["removeTab"], referencedClasses: [] }), globals.HLDebugger); smalltalk.addMethod( smalltalk.method({ selector: "onDebuggerStepped:", protocol: 'reactions', fn: function (anAnnouncement){ var self=this; function $HLContextInspectorDecorator(){return globals.HLContextInspectorDecorator||(typeof HLContextInspectorDecorator=="undefined"?nil:HLContextInspectorDecorator)} return smalltalk.withContext(function($ctx1) { var $1; $1=_st(self._model())._atEnd(); if(smalltalk.assert($1)){ self._removeTab(); }; _st(self._inspectorWidget())._inspect_(_st($HLContextInspectorDecorator())._on_(_st(anAnnouncement)._context())); _st(self._stackListWidget())._refresh(); return self}, function($ctx1) {$ctx1.fill(self,"onDebuggerStepped:",{anAnnouncement:anAnnouncement},globals.HLDebugger)})}, args: ["anAnnouncement"], source: "onDebuggerStepped: anAnnouncement\x0a\x09self model atEnd ifTrue: [ self removeTab ].\x0a\x09\x0a\x09self inspectorWidget inspect: (HLContextInspectorDecorator on: anAnnouncement context).\x0a\x09self stackListWidget refresh", messageSends: ["ifTrue:", "atEnd", "model", "removeTab", "inspect:", "inspectorWidget", "on:", "context", "refresh", "stackListWidget"], referencedClasses: ["HLContextInspectorDecorator"] }), globals.HLDebugger); smalltalk.addMethod( smalltalk.method({ selector: "registerBindingsOn:", protocol: 'keybindings', fn: function (aBindingGroup){ var self=this; function $HLToolCommand(){return globals.HLToolCommand||(typeof HLToolCommand=="undefined"?nil:HLToolCommand)} return smalltalk.withContext(function($ctx1) { _st($HLToolCommand())._registerConcreteClassesOn_for_(aBindingGroup,self._model()); return self}, function($ctx1) {$ctx1.fill(self,"registerBindingsOn:",{aBindingGroup:aBindingGroup},globals.HLDebugger)})}, args: ["aBindingGroup"], source: "registerBindingsOn: aBindingGroup\x0a\x09HLToolCommand \x0a\x09\x09registerConcreteClassesOn: aBindingGroup \x0a\x09\x09for: self model", messageSends: ["registerConcreteClassesOn:for:", "model"], referencedClasses: ["HLToolCommand"] }), globals.HLDebugger); smalltalk.addMethod( smalltalk.method({ selector: "renderContentOn:", protocol: 'rendering', fn: function (html){ var self=this; function $HLContainer(){return globals.HLContainer||(typeof HLContainer=="undefined"?nil:HLContainer)} function $HLVerticalSplitter(){return globals.HLVerticalSplitter||(typeof HLVerticalSplitter=="undefined"?nil:HLVerticalSplitter)} function $HLHorizontalSplitter(){return globals.HLHorizontalSplitter||(typeof HLHorizontalSplitter=="undefined"?nil:HLHorizontalSplitter)} return smalltalk.withContext(function($ctx1) { var $2,$1; self._renderHeadOn_(html); $2=_st($HLVerticalSplitter())._with_with_(self._codeWidget(),_st($HLHorizontalSplitter())._with_with_(self._stackListWidget(),self._inspectorWidget())); $ctx1.sendIdx["with:with:"]=1; $1=_st($HLContainer())._with_($2); _st(html)._with_($1); $ctx1.sendIdx["with:"]=1; return self}, function($ctx1) {$ctx1.fill(self,"renderContentOn:",{html:html},globals.HLDebugger)})}, args: ["html"], source: "renderContentOn: html\x0a\x09self renderHeadOn: html.\x0a\x09html with: (HLContainer with: (HLVerticalSplitter\x0a\x09\x09with: self codeWidget\x0a\x09\x09with: (HLHorizontalSplitter\x0a\x09\x09\x09with: self stackListWidget\x0a\x09\x09\x09with: self inspectorWidget)))", messageSends: ["renderHeadOn:", "with:", "with:with:", "codeWidget", "stackListWidget", "inspectorWidget"], referencedClasses: ["HLContainer", "HLVerticalSplitter", "HLHorizontalSplitter"] }), globals.HLDebugger); smalltalk.addMethod( smalltalk.method({ selector: "renderHeadOn:", protocol: 'rendering', fn: function (html){ var self=this; return smalltalk.withContext(function($ctx1) { var $1,$2; $1=_st(html)._div(); _st($1)._class_("head"); $2=_st($1)._with_((function(){ return smalltalk.withContext(function($ctx2) { return _st(_st(html)._h2())._with_(_st(_st(self._model())._error())._messageText()); }, function($ctx2) {$ctx2.fillBlock({},$ctx1,1)})})); $ctx1.sendIdx["with:"]=1; return self}, function($ctx1) {$ctx1.fill(self,"renderHeadOn:",{html:html},globals.HLDebugger)})}, args: ["html"], source: "renderHeadOn: html\x0a\x09html div \x0a\x09\x09class: 'head'; \x0a\x09\x09with: [ html h2 with: self model error messageText ]", messageSends: ["class:", "div", "with:", "h2", "messageText", "error", "model"], referencedClasses: [] }), globals.HLDebugger); smalltalk.addMethod( smalltalk.method({ selector: "stackListWidget", protocol: 'widgets', fn: function (){ var self=this; function $HLStackListWidget(){return globals.HLStackListWidget||(typeof HLStackListWidget=="undefined"?nil:HLStackListWidget)} return smalltalk.withContext(function($ctx1) { var $2,$3,$4,$1,$receiver; $2=self["@stackListWidget"]; if(($receiver = $2) == null || $receiver.isNil){ $3=_st($HLStackListWidget())._on_(self._model()); _st($3)._next_(self._codeWidget()); $4=_st($3)._yourself(); self["@stackListWidget"]=$4; $1=self["@stackListWidget"]; } else { $1=$2; }; return $1; }, function($ctx1) {$ctx1.fill(self,"stackListWidget",{},globals.HLDebugger)})}, args: [], source: "stackListWidget\x0a\x09^ stackListWidget ifNil: [ \x0a\x09\x09stackListWidget := (HLStackListWidget on: self model)\x0a\x09\x09\x09next: self codeWidget;\x0a\x09\x09\x09yourself ]", messageSends: ["ifNil:", "next:", "on:", "model", "codeWidget", "yourself"], referencedClasses: ["HLStackListWidget"] }), globals.HLDebugger); smalltalk.addMethod( smalltalk.method({ selector: "unregister", protocol: 'actions', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { ($ctx1.supercall = true, globals.HLDebugger.superclass.fn.prototype._unregister.apply(_st(self), [])); $ctx1.supercall = false; $ctx1.sendIdx["unregister"]=1; _st(self._inspectorWidget())._unregister(); return self}, function($ctx1) {$ctx1.fill(self,"unregister",{},globals.HLDebugger)})}, args: [], source: "unregister\x0a\x09super unregister.\x0a\x09self inspectorWidget unregister", messageSends: ["unregister", "inspectorWidget"], referencedClasses: [] }), globals.HLDebugger); smalltalk.addMethod( smalltalk.method({ selector: "on:", protocol: 'instance creation', fn: function (anError){ var self=this; return smalltalk.withContext(function($ctx1) { var $2,$3,$1; $2=self._new(); _st($2)._initializeFromError_(anError); $3=_st($2)._yourself(); $1=$3; return $1; }, function($ctx1) {$ctx1.fill(self,"on:",{anError:anError},globals.HLDebugger.klass)})}, args: ["anError"], source: "on: anError\x0a\x09^ self new\x0a\x09\x09initializeFromError: anError;\x0a\x09\x09yourself", messageSends: ["initializeFromError:", "new", "yourself"], referencedClasses: [] }), globals.HLDebugger.klass); smalltalk.addMethod( smalltalk.method({ selector: "tabClass", protocol: 'accessing', fn: function (){ var self=this; return "debugger"; }, args: [], source: "tabClass\x0a\x09^ 'debugger'", messageSends: [], referencedClasses: [] }), globals.HLDebugger.klass); smalltalk.addMethod( smalltalk.method({ selector: "tabLabel", protocol: 'accessing', fn: function (){ var self=this; return "Debugger"; }, args: [], source: "tabLabel\x0a\x09^ 'Debugger'", messageSends: [], referencedClasses: [] }), globals.HLDebugger.klass); smalltalk.addClass('HLDebuggerCodeModel', globals.HLCodeModel, ['debuggerModel'], 'Helios-Debugger'); smalltalk.addMethod( smalltalk.method({ selector: "debuggerModel", protocol: 'accessing', fn: function (){ var self=this; var $1; $1=self["@debuggerModel"]; return $1; }, args: [], source: "debuggerModel\x0a\x09^ debuggerModel", messageSends: [], referencedClasses: [] }), globals.HLDebuggerCodeModel); smalltalk.addMethod( smalltalk.method({ selector: "debuggerModel:", protocol: 'accessing', fn: function (anObject){ var self=this; self["@debuggerModel"]=anObject; return self}, args: ["anObject"], source: "debuggerModel: anObject\x0a\x09debuggerModel := anObject", messageSends: [], referencedClasses: [] }), globals.HLDebuggerCodeModel); smalltalk.addMethod( smalltalk.method({ selector: "doIt:", protocol: 'actions', fn: function (aString){ var self=this; function $ErrorHandler(){return globals.ErrorHandler||(typeof ErrorHandler=="undefined"?nil:ErrorHandler)} return smalltalk.withContext(function($ctx1) { var $1; $1=_st((function(){ return smalltalk.withContext(function($ctx2) { return _st(self._debuggerModel())._evaluate_(aString); }, function($ctx2) {$ctx2.fillBlock({},$ctx1,1)})}))._tryCatch_((function(e){ return smalltalk.withContext(function($ctx2) { _st($ErrorHandler())._handleError_(e); return nil; }, function($ctx2) {$ctx2.fillBlock({e:e},$ctx1,2)})})); return $1; }, function($ctx1) {$ctx1.fill(self,"doIt:",{aString:aString},globals.HLDebuggerCodeModel)})}, args: ["aString"], source: "doIt: aString\x0a\x09^ [ self debuggerModel evaluate: aString ]\x0a\x09\x09tryCatch: [ :e | \x0a\x09\x09\x09ErrorHandler handleError: e.\x0a\x09\x09\x09nil ]", messageSends: ["tryCatch:", "evaluate:", "debuggerModel", "handleError:"], referencedClasses: ["ErrorHandler"] }), globals.HLDebuggerCodeModel); smalltalk.addClass('HLDebuggerCodeWidget', globals.HLBrowserCodeWidget, [], 'Helios-Debugger'); smalltalk.addMethod( smalltalk.method({ selector: "addStopAt:", protocol: 'actions', fn: function (anInteger){ var self=this; return smalltalk.withContext(function($ctx1) { _st(self["@editor"])._setGutterMarker_gutter_value_(anInteger,"stops",_st(_st("<div class=\x22stop\x22></stop>"._asJQuery())._toArray())._first()); return self}, function($ctx1) {$ctx1.fill(self,"addStopAt:",{anInteger:anInteger},globals.HLDebuggerCodeWidget)})}, args: ["anInteger"], source: "addStopAt: anInteger\x0a\x09editor\x0a\x09\x09setGutterMarker: anInteger\x0a\x09\x09gutter: 'stops'\x0a\x09\x09value: '<div class=\x22stop\x22></stop>' asJQuery toArray first", messageSends: ["setGutterMarker:gutter:value:", "first", "toArray", "asJQuery"], referencedClasses: [] }), globals.HLDebuggerCodeWidget); smalltalk.addMethod( smalltalk.method({ selector: "clearHighlight", protocol: 'actions', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { _st(self._editor())._clearGutter_("stops"); return self}, function($ctx1) {$ctx1.fill(self,"clearHighlight",{},globals.HLDebuggerCodeWidget)})}, args: [], source: "clearHighlight\x0a\x09self editor clearGutter: 'stops'", messageSends: ["clearGutter:", "editor"], referencedClasses: [] }), globals.HLDebuggerCodeWidget); smalltalk.addMethod( smalltalk.method({ selector: "contents:", protocol: 'accessing', fn: function (aString){ var self=this; return smalltalk.withContext(function($ctx1) { self._clearHighlight(); ($ctx1.supercall = true, globals.HLDebuggerCodeWidget.superclass.fn.prototype._contents_.apply(_st(self), [aString])); $ctx1.supercall = false; return self}, function($ctx1) {$ctx1.fill(self,"contents:",{aString:aString},globals.HLDebuggerCodeWidget)})}, args: ["aString"], source: "contents: aString\x0a\x09self clearHighlight.\x0a\x09super contents: aString", messageSends: ["clearHighlight", "contents:"], referencedClasses: [] }), globals.HLDebuggerCodeWidget); smalltalk.addMethod( smalltalk.method({ selector: "editorOptions", protocol: 'accessing', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { var $2,$3,$1; $2=($ctx1.supercall = true, globals.HLDebuggerCodeWidget.superclass.fn.prototype._editorOptions.apply(_st(self), [])); $ctx1.supercall = false; _st($2)._at_put_("gutters",["CodeMirror-linenumbers", "stops"]); $3=_st($2)._yourself(); $1=$3; return $1; }, function($ctx1) {$ctx1.fill(self,"editorOptions",{},globals.HLDebuggerCodeWidget)})}, args: [], source: "editorOptions\x0a\x09^ super editorOptions\x0a\x09\x09at: 'gutters' put: #('CodeMirror-linenumbers' 'stops');\x0a\x09\x09yourself", messageSends: ["at:put:", "editorOptions", "yourself"], referencedClasses: [] }), globals.HLDebuggerCodeWidget); smalltalk.addMethod( smalltalk.method({ selector: "highlight", protocol: 'actions', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { var $1,$receiver; $1=_st(self._browserModel())._nextNode(); if(($receiver = $1) == null || $receiver.isNil){ $1; } else { var node; node=$receiver; self._highlightNode_(node); }; return self}, function($ctx1) {$ctx1.fill(self,"highlight",{},globals.HLDebuggerCodeWidget)})}, args: [], source: "highlight\x0a\x09self browserModel nextNode ifNotNil: [ :node |\x0a\x09\x09self highlightNode: node ]", messageSends: ["ifNotNil:", "nextNode", "browserModel", "highlightNode:"], referencedClasses: [] }), globals.HLDebuggerCodeWidget); smalltalk.addMethod( smalltalk.method({ selector: "highlightNode:", protocol: 'actions', fn: function (aNode){ var self=this; var token; return smalltalk.withContext(function($ctx1) { var $4,$3,$2,$1,$5,$9,$8,$7,$11,$10,$6,$15,$14,$13,$12,$receiver; if(($receiver = aNode) == null || $receiver.isNil){ aNode; } else { self._clearHighlight(); $4=_st(aNode)._positionStart(); $ctx1.sendIdx["positionStart"]=1; $3=_st($4)._x(); $ctx1.sendIdx["x"]=1; $2=_st($3).__minus((1)); $ctx1.sendIdx["-"]=1; $1=self._addStopAt_($2); $1; $5=self._editor(); $9=_st(aNode)._positionStart(); $ctx1.sendIdx["positionStart"]=2; $8=_st($9)._x(); $ctx1.sendIdx["x"]=2; $7=_st($8).__minus((1)); $ctx1.sendIdx["-"]=2; $11=_st(_st(aNode)._positionStart())._y(); $ctx1.sendIdx["y"]=1; $10=_st($11).__minus((1)); $ctx1.sendIdx["-"]=3; $6=globals.HashedCollection._newFromPairs_(["line",$7,"ch",$10]); $15=_st(aNode)._positionEnd(); $ctx1.sendIdx["positionEnd"]=1; $14=_st($15)._x(); $13=_st($14).__minus((1)); $12=globals.HashedCollection._newFromPairs_(["line",$13,"ch",_st(_st(aNode)._positionEnd())._y()]); _st($5)._setSelection_to_($6,$12); }; return self}, function($ctx1) {$ctx1.fill(self,"highlightNode:",{aNode:aNode,token:token},globals.HLDebuggerCodeWidget)})}, args: ["aNode"], source: "highlightNode: aNode\x0a\x09| token |\x0a\x09\x0a\x09aNode ifNotNil: [\x0a\x09\x09self\x0a\x09\x09\x09clearHighlight;\x0a\x09\x09\x09addStopAt: aNode positionStart x - 1.\x0a\x0a\x09\x09self editor \x0a\x09\x09\x09setSelection: #{ 'line' -> (aNode positionStart x - 1). 'ch' -> (aNode positionStart y - 1) }\x0a\x09\x09\x09to: #{ 'line' -> (aNode positionEnd x - 1). 'ch' -> (aNode positionEnd y) } ]", messageSends: ["ifNotNil:", "clearHighlight", "addStopAt:", "-", "x", "positionStart", "setSelection:to:", "editor", "y", "positionEnd"], referencedClasses: [] }), globals.HLDebuggerCodeWidget); smalltalk.addMethod( smalltalk.method({ selector: "observeBrowserModel", protocol: 'actions', fn: function (){ var self=this; function $HLDebuggerContextSelected(){return globals.HLDebuggerContextSelected||(typeof HLDebuggerContextSelected=="undefined"?nil:HLDebuggerContextSelected)} function $HLDebuggerStepped(){return globals.HLDebuggerStepped||(typeof HLDebuggerStepped=="undefined"?nil:HLDebuggerStepped)} function $HLDebuggerWhere(){return globals.HLDebuggerWhere||(typeof HLDebuggerWhere=="undefined"?nil:HLDebuggerWhere)} return smalltalk.withContext(function($ctx1) { var $2,$1,$4,$3; ($ctx1.supercall = true, globals.HLDebuggerCodeWidget.superclass.fn.prototype._observeBrowserModel.apply(_st(self), [])); $ctx1.supercall = false; $2=self._browserModel(); $ctx1.sendIdx["browserModel"]=1; $1=_st($2)._announcer(); $ctx1.sendIdx["announcer"]=1; _st($1)._on_send_to_($HLDebuggerContextSelected(),"onContextSelected",self); $ctx1.sendIdx["on:send:to:"]=1; $4=self._browserModel(); $ctx1.sendIdx["browserModel"]=2; $3=_st($4)._announcer(); $ctx1.sendIdx["announcer"]=2; _st($3)._on_send_to_($HLDebuggerStepped(),"onContextSelected",self); $ctx1.sendIdx["on:send:to:"]=2; _st(_st(self._browserModel())._announcer())._on_send_to_($HLDebuggerWhere(),"onContextSelected",self); return self}, function($ctx1) {$ctx1.fill(self,"observeBrowserModel",{},globals.HLDebuggerCodeWidget)})}, args: [], source: "observeBrowserModel\x0a\x09super observeBrowserModel.\x0a\x09\x0a\x09self browserModel announcer \x0a\x09\x09on: HLDebuggerContextSelected\x0a\x09\x09send: #onContextSelected\x0a\x09\x09to: self.\x0a\x09\x0a\x09self browserModel announcer \x0a\x09\x09on: HLDebuggerStepped\x0a\x09\x09send: #onContextSelected\x0a\x09\x09to: self.\x0a\x09\x0a\x09self browserModel announcer \x0a\x09\x09on: HLDebuggerWhere\x0a\x09\x09send: #onContextSelected\x0a\x09\x09to: self", messageSends: ["observeBrowserModel", "on:send:to:", "announcer", "browserModel"], referencedClasses: ["HLDebuggerContextSelected", "HLDebuggerStepped", "HLDebuggerWhere"] }), globals.HLDebuggerCodeWidget); smalltalk.addMethod( smalltalk.method({ selector: "onContextSelected", protocol: 'reactions', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { self._highlight(); return self}, function($ctx1) {$ctx1.fill(self,"onContextSelected",{},globals.HLDebuggerCodeWidget)})}, args: [], source: "onContextSelected\x0a\x09self highlight", messageSends: ["highlight"], referencedClasses: [] }), globals.HLDebuggerCodeWidget); smalltalk.addMethod( smalltalk.method({ selector: "renderOn:", protocol: 'rendering', fn: function (html){ var self=this; return smalltalk.withContext(function($ctx1) { ($ctx1.supercall = true, globals.HLDebuggerCodeWidget.superclass.fn.prototype._renderOn_.apply(_st(self), [html])); $ctx1.supercall = false; self._contents_(_st(_st(self._browserModel())._selectedMethod())._source()); return self}, function($ctx1) {$ctx1.fill(self,"renderOn:",{html:html},globals.HLDebuggerCodeWidget)})}, args: ["html"], source: "renderOn: html\x0a\x09super renderOn: html.\x0a\x09self contents: self browserModel selectedMethod source", messageSends: ["renderOn:", "contents:", "source", "selectedMethod", "browserModel"], referencedClasses: [] }), globals.HLDebuggerCodeWidget); smalltalk.addClass('HLDebuggerModel', globals.HLToolModel, ['rootContext', 'debugger', 'error'], 'Helios-Debugger'); globals.HLDebuggerModel.comment="I am a model for debugging Amber code in Helios.\x0a\x0aMy instances hold a reference to an `ASTDebugger` instance, itself referencing the current `context`. The context should be the root of the context stack."; smalltalk.addMethod( smalltalk.method({ selector: "atEnd", protocol: 'testing', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { var $1; $1=_st(self._debugger())._atEnd(); return $1; }, function($ctx1) {$ctx1.fill(self,"atEnd",{},globals.HLDebuggerModel)})}, args: [], source: "atEnd\x0a\x09^ self debugger atEnd", messageSends: ["atEnd", "debugger"], referencedClasses: [] }), globals.HLDebuggerModel); smalltalk.addMethod( smalltalk.method({ selector: "contexts", protocol: 'accessing', fn: function (){ var self=this; var contexts,context; function $OrderedCollection(){return globals.OrderedCollection||(typeof OrderedCollection=="undefined"?nil:OrderedCollection)} return smalltalk.withContext(function($ctx1) { var $1; contexts=_st($OrderedCollection())._new(); context=self._rootContext(); _st((function(){ return smalltalk.withContext(function($ctx2) { return _st(context)._notNil(); }, function($ctx2) {$ctx2.fillBlock({},$ctx1,1)})}))._whileTrue_((function(){ return smalltalk.withContext(function($ctx2) { _st(contexts)._add_(context); context=_st(context)._outerContext(); return context; }, function($ctx2) {$ctx2.fillBlock({},$ctx1,2)})})); $1=contexts; return $1; }, function($ctx1) {$ctx1.fill(self,"contexts",{contexts:contexts,context:context},globals.HLDebuggerModel)})}, args: [], source: "contexts\x0a\x09| contexts context |\x0a\x09\x0a\x09contexts := OrderedCollection new.\x0a\x09context := self rootContext.\x0a\x09\x0a\x09[ context notNil ] whileTrue: [\x0a\x09\x09contexts add: context.\x0a\x09\x09context := context outerContext ].\x0a\x09\x09\x0a\x09^ contexts", messageSends: ["new", "rootContext", "whileTrue:", "notNil", "add:", "outerContext"], referencedClasses: ["OrderedCollection"] }), globals.HLDebuggerModel); smalltalk.addMethod( smalltalk.method({ selector: "currentContext", protocol: 'accessing', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { var $1; $1=_st(self._debugger())._context(); return $1; }, function($ctx1) {$ctx1.fill(self,"currentContext",{},globals.HLDebuggerModel)})}, args: [], source: "currentContext\x0a\x09^ self debugger context", messageSends: ["context", "debugger"], referencedClasses: [] }), globals.HLDebuggerModel); smalltalk.addMethod( smalltalk.method({ selector: "currentContext:", protocol: 'accessing', fn: function (aContext){ var self=this; function $HLDebuggerContextSelected(){return globals.HLDebuggerContextSelected||(typeof HLDebuggerContextSelected=="undefined"?nil:HLDebuggerContextSelected)} return smalltalk.withContext(function($ctx1) { var $1,$2; self._withChangesDo_((function(){ return smalltalk.withContext(function($ctx2) { self._selectedMethod_(_st(aContext)._method()); _st(self._debugger())._context_(aContext); $ctx2.sendIdx["context:"]=1; $1=_st($HLDebuggerContextSelected())._new(); _st($1)._context_(aContext); $2=_st($1)._yourself(); return _st(self._announcer())._announce_($2); }, function($ctx2) {$ctx2.fillBlock({},$ctx1,1)})})); return self}, function($ctx1) {$ctx1.fill(self,"currentContext:",{aContext:aContext},globals.HLDebuggerModel)})}, args: ["aContext"], source: "currentContext: aContext\x0a\x09self withChangesDo: [ \x0a\x09\x09self selectedMethod: aContext method.\x0a\x09\x09self debugger context: aContext.\x0a\x09\x09self announcer announce: (HLDebuggerContextSelected new\x0a\x09\x09\x09context: aContext;\x0a\x09\x09\x09yourself) ]", messageSends: ["withChangesDo:", "selectedMethod:", "method", "context:", "debugger", "announce:", "announcer", "new", "yourself"], referencedClasses: ["HLDebuggerContextSelected"] }), globals.HLDebuggerModel); smalltalk.addMethod( smalltalk.method({ selector: "debugger", protocol: 'accessing', fn: function (){ var self=this; function $ASTDebugger(){return globals.ASTDebugger||(typeof ASTDebugger=="undefined"?nil:ASTDebugger)} return smalltalk.withContext(function($ctx1) { var $2,$1,$receiver; $2=self["@debugger"]; if(($receiver = $2) == null || $receiver.isNil){ self["@debugger"]=_st($ASTDebugger())._new(); $1=self["@debugger"]; } else { $1=$2; }; return $1; }, function($ctx1) {$ctx1.fill(self,"debugger",{},globals.HLDebuggerModel)})}, args: [], source: "debugger\x0a\x09^ debugger ifNil: [ debugger := ASTDebugger new ]", messageSends: ["ifNil:", "new"], referencedClasses: ["ASTDebugger"] }), globals.HLDebuggerModel); smalltalk.addMethod( smalltalk.method({ selector: "error", protocol: 'accessing', fn: function (){ var self=this; var $1; $1=self["@error"]; return $1; }, args: [], source: "error\x0a\x09^ error", messageSends: [], referencedClasses: [] }), globals.HLDebuggerModel); smalltalk.addMethod( smalltalk.method({ selector: "evaluate:", protocol: 'evaluating', fn: function (aString){ var self=this; return smalltalk.withContext(function($ctx1) { var $1; $1=_st(self._environment())._evaluate_for_(aString,self._currentContext()); return $1; }, function($ctx1) {$ctx1.fill(self,"evaluate:",{aString:aString},globals.HLDebuggerModel)})}, args: ["aString"], source: "evaluate: aString\x0a\x09^ self environment \x0a\x09\x09evaluate: aString \x0a\x09\x09for: self currentContext", messageSends: ["evaluate:for:", "environment", "currentContext"], referencedClasses: [] }), globals.HLDebuggerModel); smalltalk.addMethod( smalltalk.method({ selector: "flushInnerContexts", protocol: 'private', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { var $1; $1=self._currentContext(); $ctx1.sendIdx["currentContext"]=1; _st($1)._innerContext_(nil); self["@rootContext"]=self._currentContext(); self._initializeContexts(); return self}, function($ctx1) {$ctx1.fill(self,"flushInnerContexts",{},globals.HLDebuggerModel)})}, args: [], source: "flushInnerContexts\x0a\x09\x22When stepping, the inner contexts are not relevent anymore,\x0a\x09and can be flushed\x22\x0a\x09\x0a\x09self currentContext innerContext: nil.\x0a\x09rootContext := self currentContext.\x0a\x09self initializeContexts", messageSends: ["innerContext:", "currentContext", "initializeContexts"], referencedClasses: [] }), globals.HLDebuggerModel); smalltalk.addMethod( smalltalk.method({ selector: "initializeFromError:", protocol: 'initialization', fn: function (anError){ var self=this; var errorContext; function $AIContext(){return globals.AIContext||(typeof AIContext=="undefined"?nil:AIContext)} return smalltalk.withContext(function($ctx1) { self["@error"]=anError; errorContext=_st($AIContext())._fromMethodContext_(_st(self["@error"])._context()); self["@rootContext"]=_st(self["@error"])._signalerContextFrom_(errorContext); self._selectedMethod_(_st(self["@rootContext"])._method()); return self}, function($ctx1) {$ctx1.fill(self,"initializeFromError:",{anError:anError,errorContext:errorContext},globals.HLDebuggerModel)})}, args: ["anError"], source: "initializeFromError: anError\x0a\x09| errorContext |\x0a\x09\x0a\x09error := anError.\x0a\x09errorContext := (AIContext fromMethodContext: error context).\x0a\x09rootContext := error signalerContextFrom: errorContext.\x0a\x09self selectedMethod: rootContext method", messageSends: ["fromMethodContext:", "context", "signalerContextFrom:", "selectedMethod:", "method"], referencedClasses: ["AIContext"] }), globals.HLDebuggerModel); smalltalk.addMethod( smalltalk.method({ selector: "nextNode", protocol: 'accessing', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { var $1; $1=_st(self._debugger())._node(); return $1; }, function($ctx1) {$ctx1.fill(self,"nextNode",{},globals.HLDebuggerModel)})}, args: [], source: "nextNode\x0a\x09^ self debugger node", messageSends: ["node", "debugger"], referencedClasses: [] }), globals.HLDebuggerModel); smalltalk.addMethod( smalltalk.method({ selector: "onStep", protocol: 'reactions', fn: function (){ var self=this; function $HLDebuggerContextSelected(){return globals.HLDebuggerContextSelected||(typeof HLDebuggerContextSelected=="undefined"?nil:HLDebuggerContextSelected)} return smalltalk.withContext(function($ctx1) { var $2,$1,$3,$4; self["@rootContext"]=self._currentContext(); $ctx1.sendIdx["currentContext"]=1; $2=self._currentContext(); $ctx1.sendIdx["currentContext"]=2; $1=_st($2)._method(); self._selectedMethod_($1); $3=_st($HLDebuggerContextSelected())._new(); _st($3)._context_(self._currentContext()); $4=_st($3)._yourself(); _st(self._announcer())._announce_($4); return self}, function($ctx1) {$ctx1.fill(self,"onStep",{},globals.HLDebuggerModel)})}, args: [], source: "onStep\x0a\x09rootContext := self currentContext.\x0a\x09\x0a\x09\x22Force a refresh of the context list and code widget\x22\x0a\x09self selectedMethod: self currentContext method.\x0a\x09self announcer announce: (HLDebuggerContextSelected new\x0a\x09\x09context: self currentContext;\x0a\x09\x09yourself)", messageSends: ["currentContext", "selectedMethod:", "method", "announce:", "announcer", "context:", "new", "yourself"], referencedClasses: ["HLDebuggerContextSelected"] }), globals.HLDebuggerModel); smalltalk.addMethod( smalltalk.method({ selector: "proceed", protocol: 'actions', fn: function (){ var self=this; function $HLDebuggerProceeded(){return globals.HLDebuggerProceeded||(typeof HLDebuggerProceeded=="undefined"?nil:HLDebuggerProceeded)} return smalltalk.withContext(function($ctx1) { _st(self._debugger())._proceed(); _st(self._announcer())._announce_(_st($HLDebuggerProceeded())._new()); return self}, function($ctx1) {$ctx1.fill(self,"proceed",{},globals.HLDebuggerModel)})}, args: [], source: "proceed\x0a\x09self debugger proceed.\x0a\x09\x0a\x09self announcer announce: HLDebuggerProceeded new", messageSends: ["proceed", "debugger", "announce:", "announcer", "new"], referencedClasses: ["HLDebuggerProceeded"] }), globals.HLDebuggerModel); smalltalk.addMethod( smalltalk.method({ selector: "restart", protocol: 'actions', fn: function (){ var self=this; function $HLDebuggerStepped(){return globals.HLDebuggerStepped||(typeof HLDebuggerStepped=="undefined"?nil:HLDebuggerStepped)} return smalltalk.withContext(function($ctx1) { var $1,$2; _st(self._debugger())._restart(); self._onStep(); $1=_st($HLDebuggerStepped())._new(); _st($1)._context_(self._currentContext()); $2=_st($1)._yourself(); _st(self._announcer())._announce_($2); return self}, function($ctx1) {$ctx1.fill(self,"restart",{},globals.HLDebuggerModel)})}, args: [], source: "restart\x0a\x09self debugger restart.\x0a\x09self onStep.\x0a\x09\x0a\x09self announcer announce: (HLDebuggerStepped new\x0a\x09\x09context: self currentContext;\x0a\x09\x09yourself)", messageSends: ["restart", "debugger", "onStep", "announce:", "announcer", "context:", "new", "currentContext", "yourself"], referencedClasses: ["HLDebuggerStepped"] }), globals.HLDebuggerModel); smalltalk.addMethod( smalltalk.method({ selector: "rootContext", protocol: 'accessing', fn: function (){ var self=this; var $1; $1=self["@rootContext"]; return $1; }, args: [], source: "rootContext\x0a\x09^ rootContext", messageSends: [], referencedClasses: [] }), globals.HLDebuggerModel); smalltalk.addMethod( smalltalk.method({ selector: "stepOver", protocol: 'actions', fn: function (){ var self=this; function $HLDebuggerStepped(){return globals.HLDebuggerStepped||(typeof HLDebuggerStepped=="undefined"?nil:HLDebuggerStepped)} return smalltalk.withContext(function($ctx1) { var $1,$2; _st(self._debugger())._stepOver(); self._onStep(); $1=_st($HLDebuggerStepped())._new(); _st($1)._context_(self._currentContext()); $2=_st($1)._yourself(); _st(self._announcer())._announce_($2); return self}, function($ctx1) {$ctx1.fill(self,"stepOver",{},globals.HLDebuggerModel)})}, args: [], source: "stepOver\x0a\x09self debugger stepOver.\x0a\x09self onStep.\x0a\x09\x0a\x09self announcer announce: (HLDebuggerStepped new\x0a\x09\x09context: self currentContext;\x0a\x09\x09yourself)", messageSends: ["stepOver", "debugger", "onStep", "announce:", "announcer", "context:", "new", "currentContext", "yourself"], referencedClasses: ["HLDebuggerStepped"] }), globals.HLDebuggerModel); smalltalk.addMethod( smalltalk.method({ selector: "where", protocol: 'actions', fn: function (){ var self=this; function $HLDebuggerWhere(){return globals.HLDebuggerWhere||(typeof HLDebuggerWhere=="undefined"?nil:HLDebuggerWhere)} return smalltalk.withContext(function($ctx1) { _st(self._announcer())._announce_(_st($HLDebuggerWhere())._new()); return self}, function($ctx1) {$ctx1.fill(self,"where",{},globals.HLDebuggerModel)})}, args: [], source: "where\x0a\x09self announcer announce: HLDebuggerWhere new", messageSends: ["announce:", "announcer", "new"], referencedClasses: ["HLDebuggerWhere"] }), globals.HLDebuggerModel); smalltalk.addMethod( smalltalk.method({ selector: "on:", protocol: 'instance creation', fn: function (anError){ var self=this; return smalltalk.withContext(function($ctx1) { var $2,$3,$1; $2=self._new(); _st($2)._initializeFromError_(anError); $3=_st($2)._yourself(); $1=$3; return $1; }, function($ctx1) {$ctx1.fill(self,"on:",{anError:anError},globals.HLDebuggerModel.klass)})}, args: ["anError"], source: "on: anError\x0a\x09^ self new\x0a\x09\x09initializeFromError: anError;\x0a\x09\x09yourself", messageSends: ["initializeFromError:", "new", "yourself"], referencedClasses: [] }), globals.HLDebuggerModel.klass); smalltalk.addClass('HLErrorHandler', globals.Object, [], 'Helios-Debugger'); smalltalk.addMethod( smalltalk.method({ selector: "confirmDebugError:", protocol: 'error handling', fn: function (anError){ var self=this; function $HLConfirmationWidget(){return globals.HLConfirmationWidget||(typeof HLConfirmationWidget=="undefined"?nil:HLConfirmationWidget)} return smalltalk.withContext(function($ctx1) { var $1,$2; $1=_st($HLConfirmationWidget())._new(); _st($1)._confirmationString_(_st(anError)._messageText()); _st($1)._actionBlock_((function(){ return smalltalk.withContext(function($ctx2) { return self._debugError_(anError); }, function($ctx2) {$ctx2.fillBlock({},$ctx1,1)})})); _st($1)._cancelButtonLabel_("Abandon"); _st($1)._confirmButtonLabel_("Debug"); $2=_st($1)._show(); return self}, function($ctx1) {$ctx1.fill(self,"confirmDebugError:",{anError:anError},globals.HLErrorHandler)})}, args: ["anError"], source: "confirmDebugError: anError\x0a\x09HLConfirmationWidget new\x0a\x09\x09confirmationString: anError messageText;\x0a\x09\x09actionBlock: [ self debugError: anError ];\x0a\x09\x09cancelButtonLabel: 'Abandon';\x0a\x09\x09confirmButtonLabel: 'Debug';\x0a\x09\x09show", messageSends: ["confirmationString:", "new", "messageText", "actionBlock:", "debugError:", "cancelButtonLabel:", "confirmButtonLabel:", "show"], referencedClasses: ["HLConfirmationWidget"] }), globals.HLErrorHandler); smalltalk.addMethod( smalltalk.method({ selector: "debugError:", protocol: 'error handling', fn: function (anError){ var self=this; function $HLDebugger(){return globals.HLDebugger||(typeof HLDebugger=="undefined"?nil:HLDebugger)} function $Error(){return globals.Error||(typeof Error=="undefined"?nil:Error)} function $ConsoleErrorHandler(){return globals.ConsoleErrorHandler||(typeof ConsoleErrorHandler=="undefined"?nil:ConsoleErrorHandler)} return smalltalk.withContext(function($ctx1) { _st((function(){ return smalltalk.withContext(function($ctx2) { return _st(_st($HLDebugger())._on_(anError))._openAsTab(); }, function($ctx2) {$ctx2.fillBlock({},$ctx1,1)})}))._on_do_($Error(),(function(error){ return smalltalk.withContext(function($ctx2) { return _st(_st($ConsoleErrorHandler())._new())._handleError_(error); }, function($ctx2) {$ctx2.fillBlock({error:error},$ctx1,2)})})); return self}, function($ctx1) {$ctx1.fill(self,"debugError:",{anError:anError},globals.HLErrorHandler)})}, args: ["anError"], source: "debugError: anError\x0a\x0a\x09[ \x0a\x09\x09(HLDebugger on: anError) openAsTab \x0a\x09] \x0a\x09\x09on: Error \x0a\x09\x09do: [ :error | ConsoleErrorHandler new handleError: error ]", messageSends: ["on:do:", "openAsTab", "on:", "handleError:", "new"], referencedClasses: ["HLDebugger", "Error", "ConsoleErrorHandler"] }), globals.HLErrorHandler); smalltalk.addMethod( smalltalk.method({ selector: "handleError:", protocol: 'error handling', fn: function (anError){ var self=this; return smalltalk.withContext(function($ctx1) { self._confirmDebugError_(anError); return self}, function($ctx1) {$ctx1.fill(self,"handleError:",{anError:anError},globals.HLErrorHandler)})}, args: ["anError"], source: "handleError: anError\x0a\x09self confirmDebugError: anError", messageSends: ["confirmDebugError:"], referencedClasses: [] }), globals.HLErrorHandler); smalltalk.addMethod( smalltalk.method({ selector: "onErrorHandled", protocol: 'error handling', fn: function (){ var self=this; function $HLProgressWidget(){return globals.HLProgressWidget||(typeof HLProgressWidget=="undefined"?nil:HLProgressWidget)} return smalltalk.withContext(function($ctx1) { var $1,$2; $1=_st($HLProgressWidget())._default(); _st($1)._flush(); $2=_st($1)._remove(); return self}, function($ctx1) {$ctx1.fill(self,"onErrorHandled",{},globals.HLErrorHandler)})}, args: [], source: "onErrorHandled\x0a\x09\x22when an error is handled, we need to make sure that\x0a\x09any progress bar widget gets removed. Because HLProgressBarWidget is asynchronous,\x0a\x09it has to be done here.\x22\x0a\x09\x0a\x09HLProgressWidget default \x0a\x09\x09flush; \x0a\x09\x09remove", messageSends: ["flush", "default", "remove"], referencedClasses: ["HLProgressWidget"] }), globals.HLErrorHandler); smalltalk.addClass('HLStackListWidget', globals.HLToolListWidget, [], 'Helios-Debugger'); smalltalk.addMethod( smalltalk.method({ selector: "items", protocol: 'accessing', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { var $1; $1=_st(self._model())._contexts(); return $1; }, function($ctx1) {$ctx1.fill(self,"items",{},globals.HLStackListWidget)})}, args: [], source: "items\x0a\x09^ self model contexts", messageSends: ["contexts", "model"], referencedClasses: [] }), globals.HLStackListWidget); smalltalk.addMethod( smalltalk.method({ selector: "label", protocol: 'accessing', fn: function (){ var self=this; return "Call stack"; }, args: [], source: "label\x0a\x09^ 'Call stack'", messageSends: [], referencedClasses: [] }), globals.HLStackListWidget); smalltalk.addMethod( smalltalk.method({ selector: "observeModel", protocol: 'actions', fn: function (){ var self=this; function $HLDebuggerStepped(){return globals.HLDebuggerStepped||(typeof HLDebuggerStepped=="undefined"?nil:HLDebuggerStepped)} return smalltalk.withContext(function($ctx1) { ($ctx1.supercall = true, globals.HLStackListWidget.superclass.fn.prototype._observeModel.apply(_st(self), [])); $ctx1.supercall = false; _st(_st(self._model())._announcer())._on_send_to_($HLDebuggerStepped(),"onDebuggerStepped:",self); return self}, function($ctx1) {$ctx1.fill(self,"observeModel",{},globals.HLStackListWidget)})}, args: [], source: "observeModel\x0a\x09super observeModel.\x0a\x09\x0a\x09self model announcer \x0a\x09\x09on: HLDebuggerStepped\x0a\x09\x09send: #onDebuggerStepped:\x0a\x09\x09to: self", messageSends: ["observeModel", "on:send:to:", "announcer", "model"], referencedClasses: ["HLDebuggerStepped"] }), globals.HLStackListWidget); smalltalk.addMethod( smalltalk.method({ selector: "onDebuggerStepped:", protocol: 'reactions', fn: function (anAnnouncement){ var self=this; return smalltalk.withContext(function($ctx1) { self["@items"]=nil; self._refresh(); return self}, function($ctx1) {$ctx1.fill(self,"onDebuggerStepped:",{anAnnouncement:anAnnouncement},globals.HLStackListWidget)})}, args: ["anAnnouncement"], source: "onDebuggerStepped: anAnnouncement\x0a\x09items := nil.\x0a\x09self refresh", messageSends: ["refresh"], referencedClasses: [] }), globals.HLStackListWidget); smalltalk.addMethod( smalltalk.method({ selector: "proceed", protocol: 'actions', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { _st(self._model())._proceed(); return self}, function($ctx1) {$ctx1.fill(self,"proceed",{},globals.HLStackListWidget)})}, args: [], source: "proceed\x0a\x09self model proceed", messageSends: ["proceed", "model"], referencedClasses: [] }), globals.HLStackListWidget); smalltalk.addMethod( smalltalk.method({ selector: "renderButtonsOn:", protocol: 'rendering', fn: function (html){ var self=this; return smalltalk.withContext(function($ctx1) { var $1,$3,$4,$5,$6,$7,$8,$9,$10,$2; $1=_st(html)._div(); _st($1)._class_("debugger_bar"); $ctx1.sendIdx["class:"]=1; $2=_st($1)._with_((function(){ return smalltalk.withContext(function($ctx2) { $3=_st(html)._button(); $ctx2.sendIdx["button"]=1; _st($3)._class_("btn restart"); $ctx2.sendIdx["class:"]=2; _st($3)._with_("Restart"); $ctx2.sendIdx["with:"]=2; $4=_st($3)._onClick_((function(){ return smalltalk.withContext(function($ctx3) { return self._restart(); }, function($ctx3) {$ctx3.fillBlock({},$ctx2,2)})})); $ctx2.sendIdx["onClick:"]=1; $4; $5=_st(html)._button(); $ctx2.sendIdx["button"]=2; _st($5)._class_("btn where"); $ctx2.sendIdx["class:"]=3; _st($5)._with_("Where"); $ctx2.sendIdx["with:"]=3; $6=_st($5)._onClick_((function(){ return smalltalk.withContext(function($ctx3) { return self._where(); }, function($ctx3) {$ctx3.fillBlock({},$ctx2,3)})})); $ctx2.sendIdx["onClick:"]=2; $6; $7=_st(html)._button(); $ctx2.sendIdx["button"]=3; _st($7)._class_("btn stepOver"); $ctx2.sendIdx["class:"]=4; _st($7)._with_("Step over"); $ctx2.sendIdx["with:"]=4; $8=_st($7)._onClick_((function(){ return smalltalk.withContext(function($ctx3) { return self._stepOver(); }, function($ctx3) {$ctx3.fillBlock({},$ctx2,4)})})); $ctx2.sendIdx["onClick:"]=3; $8; $9=_st(html)._button(); _st($9)._class_("btn proceed"); _st($9)._with_("Proceed"); $10=_st($9)._onClick_((function(){ return smalltalk.withContext(function($ctx3) { return self._proceed(); }, function($ctx3) {$ctx3.fillBlock({},$ctx2,5)})})); return $10; }, function($ctx2) {$ctx2.fillBlock({},$ctx1,1)})})); $ctx1.sendIdx["with:"]=1; return self}, function($ctx1) {$ctx1.fill(self,"renderButtonsOn:",{html:html},globals.HLStackListWidget)})}, args: ["html"], source: "renderButtonsOn: html\x0a\x09html div \x0a\x09\x09class: 'debugger_bar'; \x0a\x09\x09with: [\x0a\x09\x09\x09html button \x0a\x09\x09\x09\x09class: 'btn restart';\x0a\x09\x09\x09\x09with: 'Restart';\x0a\x09\x09\x09\x09onClick: [ self restart ].\x0a\x09\x09\x09html button \x0a\x09\x09\x09\x09class: 'btn where';\x0a\x09\x09\x09\x09with: 'Where';\x0a\x09\x09\x09\x09onClick: [ self where ].\x0a\x09\x09\x09html button \x0a\x09\x09\x09\x09class: 'btn stepOver';\x0a\x09\x09\x09\x09with: 'Step over';\x0a\x09\x09\x09\x09onClick: [ self stepOver ].\x0a\x09\x09\x09html button \x0a\x09\x09\x09\x09class: 'btn proceed';\x0a\x09\x09\x09\x09with: 'Proceed';\x0a\x09\x09\x09\x09onClick: [ self proceed ] ]", messageSends: ["class:", "div", "with:", "button", "onClick:", "restart", "where", "stepOver", "proceed"], referencedClasses: [] }), globals.HLStackListWidget); smalltalk.addMethod( smalltalk.method({ selector: "restart", protocol: 'actions', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { _st(self._model())._restart(); return self}, function($ctx1) {$ctx1.fill(self,"restart",{},globals.HLStackListWidget)})}, args: [], source: "restart\x0a\x09self model restart", messageSends: ["restart", "model"], referencedClasses: [] }), globals.HLStackListWidget); smalltalk.addMethod( smalltalk.method({ selector: "selectItem:", protocol: 'actions', fn: function (aContext){ var self=this; return smalltalk.withContext(function($ctx1) { _st(self._model())._currentContext_(aContext); ($ctx1.supercall = true, globals.HLStackListWidget.superclass.fn.prototype._selectItem_.apply(_st(self), [aContext])); $ctx1.supercall = false; return self}, function($ctx1) {$ctx1.fill(self,"selectItem:",{aContext:aContext},globals.HLStackListWidget)})}, args: ["aContext"], source: "selectItem: aContext\x0a \x09self model currentContext: aContext.\x0a\x09super selectItem: aContext", messageSends: ["currentContext:", "model", "selectItem:"], referencedClasses: [] }), globals.HLStackListWidget); smalltalk.addMethod( smalltalk.method({ selector: "selectedItem", protocol: 'actions', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { var $1; $1=_st(self._model())._currentContext(); return $1; }, function($ctx1) {$ctx1.fill(self,"selectedItem",{},globals.HLStackListWidget)})}, args: [], source: "selectedItem\x0a \x09^ self model currentContext", messageSends: ["currentContext", "model"], referencedClasses: [] }), globals.HLStackListWidget); smalltalk.addMethod( smalltalk.method({ selector: "stepOver", protocol: 'actions', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { _st(self._model())._stepOver(); return self}, function($ctx1) {$ctx1.fill(self,"stepOver",{},globals.HLStackListWidget)})}, args: [], source: "stepOver\x0a\x09self model stepOver", messageSends: ["stepOver", "model"], referencedClasses: [] }), globals.HLStackListWidget); smalltalk.addMethod( smalltalk.method({ selector: "where", protocol: 'actions', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { _st(self._model())._where(); return self}, function($ctx1) {$ctx1.fill(self,"where",{},globals.HLStackListWidget)})}, args: [], source: "where\x0a\x09self model where", messageSends: ["where", "model"], referencedClasses: [] }), globals.HLStackListWidget); });
Alexander-Remizov/SVG-Amber-Tools
bower_components/amber/support/helios/src/Helios-Debugger.js
JavaScript
mit
56,069
def calc(): h, l = input().split(' ') mapa = [] for i_row in range(int(h)): mapa.append(input().split(' ')) maior_num = 0 for row in mapa: for col in row: n = int(col) if (n > maior_num): maior_num = n qtd = [0 for i in range(maior_num + 1)] for row in mapa: for col in row: n = int(col) qtd[n] = qtd[n] + 1 menor = 1 for i in range(1, len(qtd)): if (qtd[i] <= qtd[menor]): menor = i print(menor) calc()
DestructHub/bcs-contest
2016/Main/L/Python/solution_1_wrong.py
Python
mit
471
/** * Error for services to through when they encounter a problem with the request. * Distinguishes between a bad service request and a general error */ function ServiceError(message) { this.name = "ServiceError"; this.message = (message || ""); } ServiceError.prototype = Object.create(Error.prototype, { constructor: {value: ServiceError} }); /** * Error for when an item is not found */ function NotFoundError(message) { this.name = "NotFoundError"; this.message = (message || "Not found"); } NotFoundError.prototype = Object.create(ServiceError.prototype, { constructor: { value: NotFoundError} }); exports.ServiceError = ServiceError; exports.NotFoundError = NotFoundError;
James-Tolley/Manny.js
src/services/errors.js
JavaScript
mit
692
require File.dirname(__FILE__) + '/spec' class Object class << self # Lookup missing generators using const_missing. This allows any # generator to reference another without having to know its location: # RubyGems, ~/.rubigen/generators, and APP_ROOT/generators. def lookup_missing_generator(class_id) if md = /(.+)Generator$/.match(class_id.to_s) name = md.captures.first.demodulize.underscore RubiGen::Base.active.lookup(name).klass else const_missing_before_generators(class_id) end end unless respond_to?(:const_missing_before_generators) alias_method :const_missing_before_generators, :const_missing alias_method :const_missing, :lookup_missing_generator end end end # User home directory lookup adapted from RubyGems. def Dir.user_home if ENV['HOME'] ENV['HOME'] elsif ENV['USERPROFILE'] ENV['USERPROFILE'] elsif ENV['HOMEDRIVE'] and ENV['HOMEPATH'] "#{ENV['HOMEDRIVE']}:#{ENV['HOMEPATH']}" else File.expand_path '~' end end module RubiGen # Generator lookup is managed by a list of sources which return specs # describing where to find and how to create generators. This module # provides class methods for manipulating the source list and looking up # generator specs, and an #instance wrapper for quickly instantiating # generators by name. # # A spec is not a generator: it's a description of where to find # the generator and how to create it. A source is anything that # yields generators from #each. PathSource and GemGeneratorSource are provided. module Lookup def self.included(base) base.extend(ClassMethods) # base.use_component_sources! # TODO is this required since it has no scope/source context end # Convenience method to instantiate another generator. def instance(generator_name, args, runtime_options = {}) self.class.active.instance(generator_name, args, runtime_options) end module ClassMethods # The list of sources where we look, in order, for generators. def sources if read_inheritable_attribute(:sources).blank? if superclass == RubiGen::Base superclass_sources = superclass.sources diff = superclass_sources.inject([]) do |mem, source| found = false application_sources.each { |app_source| found ||= true if app_source == source} mem << source unless found mem end write_inheritable_attribute(:sources, diff) end active.use_component_sources! if read_inheritable_attribute(:sources).blank? end read_inheritable_attribute(:sources) end # Add a source to the end of the list. def append_sources(*args) sources.concat(args.flatten) invalidate_cache! end # Add a source to the beginning of the list. def prepend_sources(*args) sources = self.sources reset_sources write_inheritable_array(:sources, args.flatten + sources) invalidate_cache! end # Reset the source list. def reset_sources write_inheritable_attribute(:sources, []) invalidate_cache! end # Use application generators (app, ?). def use_application_sources!(*filters) reset_sources write_inheritable_attribute(:sources, application_sources(filters)) end def application_sources(filters = []) filters.unshift 'app' app_sources = [] app_sources << PathSource.new(:builtin, File.join(File.dirname(__FILE__), %w[.. .. app_generators])) app_sources << filtered_sources(filters) app_sources.flatten end # Use component generators (test_unit, etc). # 1. Current application. If APP_ROOT is defined we know we're # generating in the context of this application, so search # APP_ROOT/generators. # 2. User home directory. Search ~/.rubigen/generators. # 3. RubyGems. Search for gems containing /{scope}_generators folder. # 4. Builtins. None currently. # # Search can be filtered by passing one or more prefixes. # e.g. use_component_sources!(:rubygems) means it will also search in the following # folders: # 5. User home directory. Search ~/.rubigen/rubygems_generators. # 6. RubyGems. Search for gems containing /rubygems_generators folder. def use_component_sources!(*filters) reset_sources new_sources = [] if defined? ::APP_ROOT new_sources << PathSource.new(:root, "#{::APP_ROOT}/generators") new_sources << PathSource.new(:vendor, "#{::APP_ROOT}/vendor/generators") new_sources << PathSource.new(:plugins, "#{::APP_ROOT}/vendor/plugins/*/**/generators") end new_sources << filtered_sources(filters) write_inheritable_attribute(:sources, new_sources.flatten) end def filtered_sources(filters) new_sources = [] new_sources << PathFilteredSource.new(:user, "#{Dir.user_home}/.rubigen/", *filters) if Object.const_defined?(:Gem) new_sources << GemPathSource.new(*filters) end new_sources end # Lookup knows how to find generators' Specs from a list of Sources. # Searches the sources, in order, for the first matching name. def lookup(generator_name) @found ||= {} generator_name = generator_name.to_s.downcase @found[generator_name] ||= cache.find { |spec| spec.name == generator_name } unless @found[generator_name] chars = generator_name.scan(/./).map{|c|"#{c}.*?"} rx = /^#{chars}$/ gns = cache.select {|spec| spec.name =~ rx } @found[generator_name] ||= gns.first if gns.length == 1 raise GeneratorError, "Pattern '#{generator_name}' matches more than one generator: #{gns.map{|sp|sp.name}.join(', ')}" if gns.length > 1 end @found[generator_name] or raise GeneratorError, "Couldn't find '#{generator_name}' generator" end # Convenience method to lookup and instantiate a generator. def instance(generator_name, args = [], runtime_options = {}) active.lookup(generator_name).klass.new(args, full_options(runtime_options)) end private # Lookup and cache every generator from the source list. def cache @cache ||= sources.inject([]) { |cache, source| cache + source.to_a } end # Clear the cache whenever the source list changes. def invalidate_cache! @cache = nil end end end # Sources enumerate (yield from #each) generator specs which describe # where to find and how to create generators. Enumerable is mixed in so, # for example, source.collect will retrieve every generator. # Sources may be assigned a label to distinguish them. class Source include Enumerable attr_reader :label def initialize(label) @label = label end # The each method must be implemented in subclasses. # The base implementation raises an error. def each raise NotImplementedError end # Return a convenient sorted list of all generator names. def names(filter = nil) inject([]) do |mem, spec| case filter when :visible mem << spec.name if spec.visible? end mem end.sort end end # PathSource looks for generators in a filesystem directory. class PathSource < Source attr_reader :path def initialize(label, path) super label @path = File.expand_path path end # Yield each eligible subdirectory. def each Dir["#{path}/[a-z]*"].each do |dir| if File.directory?(dir) yield Spec.new(File.basename(dir), dir, label) end end end def ==(source) self.class == source.class && path == source.path end end class PathFilteredSource < PathSource attr_reader :filters def initialize(label, path, *filters) super label, File.join(path, "#{filter_str(filters)}generators") end def filter_str(filters) @filters = filters.first.is_a?(Array) ? filters.first : filters return "" if @filters.blank? filter_str = @filters.map {|filter| "#{filter}_"}.join(",") filter_str += "," "{#{filter_str}}" end def ==(source) self.class == source.class && path == source.path && filters == source.filters && label == source.label end end class AbstractGemSource < Source def initialize super :RubyGems end end # GemPathSource looks for generators within any RubyGem's /{filter_}generators/**/<generator_name>_generator.rb file. class GemPathSource < AbstractGemSource attr_accessor :filters def initialize(*filters) super() @filters = filters end # Yield each generator within rails_generator subdirectories. def each generator_full_paths.each do |generator| yield Spec.new(File.basename(generator).sub(/_generator.rb$/, ''), File.dirname(generator), label) end end def ==(source) self.class == source.class && filters == source.filters end private def generator_full_paths @generator_full_paths ||= Gem::cache.inject({}) do |latest, name_gem| name, gem = name_gem hem = latest[gem.name] latest[gem.name] = gem if hem.nil? or gem.version > hem.version latest end.values.inject([]) do |mem, gem| Dir[gem.full_gem_path + "/#{filter_str}generators/**/*_generator.rb"].each do |generator| mem << generator end mem end.reverse end def filter_str @filters = filters.first.is_a?(Array) ? filters.first : filters return "" if filters.blank? filter_str = filters.map {|filter| "#{filter}_"}.join(",") filter_str += "," "{#{filter_str}}" end end end
cowboyd/rubigen
lib/rubigen/lookup.rb
Ruby
mit
10,194
import Ember from "ember"; export default Ember.Route.extend({ model: function() { return this.store.query('answer', {correct: true}); } });
dpatz/scroll-of-heroes-client
app/routes/application.js
JavaScript
mit
150
<?php /** * This file is part of the PHPMongo package. * * (c) Dmytro Sokil <dmytro.sokil@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sokil\Mongo\Validator; /** * Alphanumeric values validator * * @author Dmytro Sokil <dmytro.sokil@gmail.com> */ class AlphaNumericValidator extends \Sokil\Mongo\Validator { public function validateField(\Sokil\Mongo\Document $document, $fieldName, array $params) { if (!$document->get($fieldName)) { return; } if (preg_match('/^\w+$/', $document->get($fieldName))) { return; } if (!isset($params['message'])) { $params['message'] = 'Field "' . $fieldName . '" not alpha-numeric in model ' . get_called_class(); } $document->addError($fieldName, $this->getName(), $params['message']); } }
ngohuynhngockhanh/pyBearServer
vendor/sokil/php-mongo/src/Validator/AlphaNumericValidator.php
PHP
mit
961
<?php /** * swPagesAdmin actions. * * @package soleoweb * @subpackage swPagesAdmin * @author Your name here * @version SVN: $Id: actions.class.php 8507 2008-04-17 17:32:20Z fabien $ */ class baseSwBlogTagsAdminActions extends sfActions { public function executeIndex($request) { $this->sw_blog_tagList = new swBlogTagsDatagrid( $request->getParameter('filters', array()), array( 'page' => $request->getParameter('page'), 'per_page' => 10, ) ); } public function executeCreate() { $this->form = new swBlogTagForm(); $this->setTemplate('edit'); } public function executeEdit($request) { $this->form = $this->getswBlogTagForm($request->getParameter('id')); } public function executeUpdate($request) { $this->forward404Unless($request->isMethod('post')); $this->form = $this->getswBlogTagForm($request->getParameter('id')); $this->form->bind($request->getParameter('sw_blog_tag')); if ($this->form->isValid()) { $sw_blog_tag = $this->form->save(); $this->getUser()->setFlash('notice-ok', __('notice_your_change_has_been_saved', null, 'swToolbox')); $this->redirect('swBlogTagsAdmin/edit?id='.$sw_blog_tag['id']); } $this->getUser()->setFlash('notice-error', __('notice_an_error_occurred_while_saving', null, 'swToolbox')); $this->setTemplate('edit'); } public function executeDelete($request) { $this->forward404Unless($sw_blog_tag = $this->getswBlogTagById($request->getParameter('id'))); $sw_blog_tag->delete(); $this->getUser()->setFlash('notice-ok', __('notice_element_deleted', null, 'swToolbox')); $this->redirect('swBlogTagsAdmin/index'); } private function getswBlogTagTable() { return Doctrine::getTable('swBlogTag'); } private function getswBlogTagById($id) { return $this->getswBlogTagTable()->find($id); } private function getswBlogTagForm($id) { $sw_blog_tag = $this->getswBlogTagById($id); if ($sw_blog_tag instanceof swBlogTag) { return new swBlogTagForm($sw_blog_tag); } else { return new swBlogTagForm(); } } }
rande/swBlogPlugin
modules/swBlogTagsAdmin/lib/baseSwBlogTagsAdminActions.class.php
PHP
mit
2,201
//This file is automatically rebuilt by the Cesium build process. /*global define*/ define(function() { 'use strict'; return "/**\n\ * Converts an RGB color to HSB (hue, saturation, brightness)\n\ * HSB <-> RGB conversion with minimal branching: {@link http://lolengine.net/blog/2013/07/27/rgb-to-hsv-in-glsl}\n\ *\n\ * @name czm_RGBToHSB\n\ * @glslFunction\n\ * \n\ * @param {vec3} rgb The color in RGB.\n\ *\n\ * @returns {vec3} The color in HSB.\n\ *\n\ * @example\n\ * vec3 hsb = czm_RGBToHSB(rgb);\n\ * hsb.z *= 0.1;\n\ * rgb = czm_HSBToRGB(hsb);\n\ */\n\ \n\ const vec4 K_RGB2HSB = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);\n\ \n\ vec3 czm_RGBToHSB(vec3 rgb)\n\ {\n\ vec4 p = mix(vec4(rgb.bg, K_RGB2HSB.wz), vec4(rgb.gb, K_RGB2HSB.xy), step(rgb.b, rgb.g));\n\ vec4 q = mix(vec4(p.xyw, rgb.r), vec4(rgb.r, p.yzx), step(p.x, rgb.r));\n\ \n\ float d = q.x - min(q.w, q.y);\n\ return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + czm_epsilon7)), d / (q.x + czm_epsilon7), q.x);\n\ }\n\ "; });
coderFirework/app
js/Cesium-Tiles/Source/Shaders/Builtin/Functions/RGBToHSB.js
JavaScript
mit
1,025
/** * Demo App for TopcoatTouch */ $(document).ready(function() { <% if (kitchenSink) { if (mvc) { %> // Create the topcoatTouch object var tt = new TopcoatTouch({menu: [{id: 'help', name: 'Help'}, {id: 'info', name: 'Info'}, {id: 'about', name: 'About'}]}); tt.on(tt.EVENTS.MENU_ITEM_CLICKED, function(page, id) { if (id == 'help') { tt.goTo('help', 'slidedown', true); } else if (id == 'about') { tt.goTo('about', 'pop', true); } }); tt.createController('home'); tt.createController('about').addEvent('click', 'button', function() { tt.goBack(); }); tt.createController('info').addEvent('click', 'button', function() { tt.goBack(); }); tt.createController('help').addEvent('click', 'button', function() { tt.goBack(); }); tt.createController('buttonExample', { postrender: function($page) { // Show a message when anyone clicks on button of the test form... $page.find('.testForm').submit(function() { tt.showDialog('<h3>Button Clicked</h3>'); return false; }); } }); tt.createController('carouselExample', { postadd: function() { // When the page is loaded, run the following... // Setup iScroll.. this.carouselScroll = new IScroll('#carouselWrapper', { scrollX: true, scrollY: false, momentum: false, snap: true, snapSpeed: 400, keyBindings: true, indicators: { el: document.getElementById('carouselIndicator'), resize: false } }); }, pageend: function() { if (this.carouselScroll != null) { this.carouselScroll.destroy(); this.carouselScroll = null; } } }); tt.createController('checkRadioExample'); tt.createController('formExample'); tt.createController('galleryExample', { postrender: function($page) { $page.find('#changeButton').click(function() { createPlaceHolder($page, $('#gallery-picker').data('value')); }); createPlaceHolder($page, 'kittens'); } }); tt.createController('waitingDialogExample', { postadd: function() { // Show the loading message... $(document).on('click', '#showLoading', function() { tt.showLoading('10 seconds'); var count = 10; var interval = setInterval(function() { if (--count <= 0) { clearInterval(interval); tt.hideLoading(); } else { $('#topcoat-loading-message').text(count + ' seconds'); } },1000); }); // Show the dialog... $(document).on('click', '#showDialog', function() { tt.showDialog('This is a dialog', 'Example Dialog', {OK: function() { console.log('OK Pressed') } , Cancel: function() { console.log('Cancel Pressed')}}); }); } }); // First page we go to home... This could be done in code by setting the class to 'page page-center', but here is how to do it in code... tt.goTo('home'); function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1) + min); } // Create the placeholders in the gallery... function createPlaceHolder($page, type) { var placeHolders = { kittens : 'placekitten.com', bears: 'placebear.com', lorem: 'lorempixel.com', bacon: 'baconmockup.com', murray: 'www.fillmurray.com'}; var gallery = ''; for (var i = 0; i < getRandomInt(50,100); i++) { gallery += '<li class="photoClass" style="background:url(http://' + placeHolders[type] + '/' + getRandomInt(200,300) + '/' + getRandomInt(200,300) + ') 50% 50% no-repeat"></li>'; } $page.find('.photo-gallery').html(gallery); tt.refreshScroll(); // Refresh the scroller tt.scrollTo(0,0); // Move back to the top of the page... } <% // End If MVC KitchenSink } else { // Start SingleDocument KitchenSink %> // Create the topcoatTouch object var tt = new TopcoatTouch({menu: [{id: 'help', name: 'Help'}, {id: 'info', name: 'Info'}, {id: 'about', name: 'About'}]}); // First page we go to home... This could be done in code by setting the class to 'page page-center', but here is how to do it in code... tt.goTo('home'); var carouselScroll = null; tt.on(tt.EVENTS.MENU_ITEM_CLICKED, function(page, id) { if (id == 'help') { tt.goTo('help', 'slidedown', true); } else if (id == 'info') { tt.goTo('info', 'flip', true); } else if (id == 'about') { tt.goTo('about', 'pop', true); } }); tt.on('click', 'button', 'help about info', function() { tt.goBack(); }); // Show the loading message... $('#showLoading').click(function() { tt.showLoading('10 seconds'); var count = 10; var interval = setInterval(function() { if (--count <= 0) { clearInterval(interval); tt.hideLoading(); } else { $('#topcoat-loading-message').text(count + ' seconds'); } },1000); }); // Show the dialog... $('#showDialog').click(function() { tt.showDialog('This is a dialog', 'Example Dialog', {OK: function() { console.log('OK Pressed') } , Cancel: function() { console.log('Cancel Pressed')}}); }); tt.on(tt.EVENTS.PAGE_START, 'carouselExample', function() { // When the page is loaded, run the following... // Setup iScroll.. carouselScroll = new IScroll('#carouselWrapper', { scrollX: true, scrollY: false, momentum: false, snap: true, snapSpeed: 400, keyBindings: true, indicators: { el: document.getElementById('carouselIndicator'), resize: false } }); }).on(tt.EVENTS.PAGE_END, 'carouselExample', function() { // When the page is unloaded, run the following... if (carouselScroll != null) { carouselScroll.destroy(); carouselScroll = null; } }); // Show a message when anyone clicks on button of the test form... $('.testForm').submit(function() { tt.showDialog('<h3>Button Clicked</h3>'); return false; }); function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1) + min); } // Create the placeholders in the gallery... function createPlaceHolder(type) { var placeHolders = { kittens : 'placekitten.com', bears: 'placebear.com', lorem: 'lorempixel.com', bacon: 'baconmockup.com', murray: 'www.fillmurray.com'}; var gallery = ''; for (var i = 0; i < getRandomInt(50,100); i++) { gallery += '<li class="photoClass" style="background:url(http://' + placeHolders[type] + '/' + getRandomInt(200,300) + '/' + getRandomInt(200,300) + ') 50% 50% no-repeat"></li>'; } $('.photo-gallery').html(gallery); tt.refreshScroll(); // Refresh the scroller tt.scrollTo(0,0); // Move back to the top of the page... } $('#gallery-picker').change(function(e, id) { createPlaceHolder(id); }); createPlaceHolder('kittens'); <% } } else { %> // Create the topcoatTouch object var tt = new TopcoatTouch(); <% if (mvc) { %> tt.createController('home'); <% } else { %> // First page we go to home... This could be done in code by setting the class to 'page page-center', but here is how to do it in code... <% } %> tt.goTo('home'); <% } %> });
kriserickson/generator-topcoat-touch
app/templates/_app.js
JavaScript
mit
8,221
const sizeOf = { object: function () { return function (object) { let $start = 0 $start += 1 * object.array.length + 2 return $start } } () } const serializer = { all: { object: function () { return function (object, $buffer, $start) { let $i = [] for ($i[0] = 0; $i[0] < object.array.length; $i[0]++) { $buffer[$start++] = object.array[$i[0]] & 0xff } $buffer[$start++] = 0xd $buffer[$start++] = 0xa return { start: $start, serialize: null } } } () }, inc: { object: function () { return function (object, $step = 0, $i = []) { let $_, $bite return function $serialize ($buffer, $start, $end) { for (;;) { switch ($step) { case 0: $i[0] = 0 $step = 1 case 1: $bite = 0 $_ = object.array[$i[0]] case 2: while ($bite != -1) { if ($start == $end) { $step = 2 return { start: $start, serialize: $serialize } } $buffer[$start++] = $_ >>> $bite * 8 & 0xff $bite-- } if (++$i[0] != object.array.length) { $step = 1 continue } $step = 3 case 3: if ($start == $end) { $step = 3 return { start: $start, serialize: $serialize } } $buffer[$start++] = 0xd case 4: if ($start == $end) { $step = 4 return { start: $start, serialize: $serialize } } $buffer[$start++] = 0xa case 5: } break } return { start: $start, serialize: null } } } } () } } const parser = { all: { object: function () { return function ($buffer, $start) { let $i = [] let object = { array: [] } $i[0] = 0 for (;;) { if ( $buffer[$start] == 0xd && $buffer[$start + 1] == 0xa ) { $start += 2 break } object.array[$i[0]] = $buffer[$start++] $i[0]++ } return object } } () }, inc: { object: function () { return function (object, $step = 0, $i = []) { let $length = 0 return function $parse ($buffer, $start, $end) { for (;;) { switch ($step) { case 0: object = { array: [] } case 1: $i[0] = 0 case 2: $step = 2 if ($start == $end) { return { start: $start, object: null, parse: $parse } } if ($buffer[$start] != 0xd) { $step = 4 continue } $start++ $step = 3 case 3: $step = 3 if ($start == $end) { return { start: $start, object: null, parse: $parse } } if ($buffer[$start] != 0xa) { $step = 4 $parse(Buffer.from([ 0xd ]), 0, 1) continue } $start++ $step = 7 continue case 4: case 5: if ($start == $end) { $step = 5 return { start: $start, object: null, parse: $parse } } object.array[$i[0]] = $buffer[$start++] case 6: $i[0]++ $step = 2 continue case 7: } return { start: $start, object: object, parse: null } break } } } } () } } module.exports = { sizeOf: sizeOf, serializer: { all: serializer.all, inc: serializer.inc, bff: function ($incremental) { return { object: function () { return function (object) { return function ($buffer, $start, $end) { let $i = [] if ($end - $start < 2 + object.array.length * 1) { return $incremental.object(object, 0, $i)($buffer, $start, $end) } for ($i[0] = 0; $i[0] < object.array.length; $i[0]++) { $buffer[$start++] = object.array[$i[0]] & 0xff } $buffer[$start++] = 0xd $buffer[$start++] = 0xa return { start: $start, serialize: null } } } } () } } (serializer.inc) }, parser: { all: parser.all, inc: parser.inc, bff: function ($incremental) { return { object: function () { return function () { return function ($buffer, $start, $end) { let $i = [] let object = { array: [] } $i[0] = 0 for (;;) { if ($end - $start < 2) { return $incremental.object(object, 2, $i)($buffer, $start, $end) } if ( $buffer[$start] == 0xd && $buffer[$start + 1] == 0xa ) { $start += 2 break } if ($end - $start < 1) { return $incremental.object(object, 4, $i)($buffer, $start, $end) } object.array[$i[0]] = $buffer[$start++] $i[0]++ } return { start: $start, object: object, parse: null } } } () } } } (parser.inc) } }
bigeasy/packet
test/readme/terminated-multibyte.js
JavaScript
mit
8,252
<?php namespace Fannan\MembersModule\Member; use Anomaly\Streams\Platform\Database\Seeder\Seeder; class MemberSeeder extends Seeder { /** * Run the seeder. */ public function run() { // } }
fannan1991/pyrocms
addons/shared/fannan/members-module/src/Member/MemberSeeder.php
PHP
mit
227
import modelExtend from 'dva-model-extend' import { create, remove, update } from '../services/user' import * as usersService from '../services/users' import { pageModel } from './common' import { config } from 'utils' const { query } = usersService const { prefix } = config export default modelExtend(pageModel, { namespace: 'user', state: { currentItem: {}, modalVisible: false, modalType: 'create', selectedRowKeys: [], isMotion: localStorage.getItem(`${prefix}userIsMotion`) === 'true', }, subscriptions: { setup ({ dispatch, history }) { history.listen(location => { if (location.pathname === '/user') { dispatch({ type: 'query', payload: location.query, }) } }) }, }, effects: { *query ({ payload = {} }, { call, put }) { const data = yield call(query, payload) if (data) { yield put({ type: 'querySuccess', payload: { list: data.data, pagination: { current: Number(payload.page) || 1, pageSize: Number(payload.pageSize) || 10, total: data.total, }, }, }) } }, *'delete' ({ payload }, { call, put, select }) { const data = yield call(remove, { id: payload }) const { selectedRowKeys } = yield select(_ => _.user) if (data.success) { yield put({ type: 'updateState', payload: { selectedRowKeys: selectedRowKeys.filter(_ => _ !== payload) } }) yield put({ type: 'query' }) } else { throw data } }, *'multiDelete' ({ payload }, { call, put }) { const data = yield call(usersService.remove, payload) if (data.success) { yield put({ type: 'updateState', payload: { selectedRowKeys: [] } }) yield put({ type: 'query' }) } else { throw data } }, *create ({ payload }, { call, put }) { const data = yield call(create, payload) if (data.success) { yield put({ type: 'hideModal' }) yield put({ type: 'query' }) } else { throw data } }, *update ({ payload }, { select, call, put }) { const id = yield select(({ user }) => user.currentItem.id) const newUser = { ...payload, id } const data = yield call(update, newUser) if (data.success) { yield put({ type: 'hideModal' }) yield put({ type: 'query' }) } else { throw data } }, }, reducers: { showModal (state, { payload }) { return { ...state, ...payload, modalVisible: true } }, hideModal (state) { return { ...state, modalVisible: false } }, switchIsMotion (state) { localStorage.setItem(`${prefix}userIsMotion`, !state.isMotion) return { ...state, isMotion: !state.isMotion } }, }, })
shaohuawang2015/goldbeans-admin
src/models/user.js
JavaScript
mit
2,907