code
stringlengths 2
1.05M
| repo_name
stringlengths 5
101
| path
stringlengths 4
991
| language
stringclasses 3
values | license
stringclasses 5
values | size
int64 2
1.05M
|
|---|---|---|---|---|---|
# AUTOGENERATED FILE
FROM balenalib/fincm3-debian:stretch-run
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
ca-certificates \
curl \
\
# .NET Core dependencies
libc6 \
libgcc1 \
libgssapi-krb5-2 \
libicu57 \
libssl1.1 \
libstdc++6 \
zlib1g \
&& rm -rf /var/lib/apt/lists/*
# Configure web servers to bind to port 80 when present
ENV ASPNETCORE_URLS=http://+:80 \
# Enable detection of running in a container
DOTNET_RUNNING_IN_CONTAINER=true
# Install .NET Core
ENV DOTNET_VERSION 3.1.12
RUN curl -SL --output dotnet.tar.gz "https://dotnetcli.blob.core.windows.net/dotnet/Runtime/$DOTNET_VERSION/dotnet-runtime-$DOTNET_VERSION-linux-arm.tar.gz" \
&& dotnet_sha512='5d241663ef78720dacd4073f06150e0b1e085cda542436a9319beb3c14fb6dc19ade72caa738ce50d2bdd31e2936858d9f080a2f9ae43856587b165407b47314' \
&& echo "$dotnet_sha512 dotnet.tar.gz" | sha512sum -c - \
&& mkdir -p /usr/share/dotnet \
&& tar -zxf dotnet.tar.gz -C /usr/share/dotnet \
&& rm dotnet.tar.gz \
&& ln -s /usr/share/dotnet/dotnet /usr/bin/dotnet
ENV ASPNETCORE_VERSION 3.1.12
RUN curl -SL --output aspnetcore.tar.gz "https://dotnetcli.blob.core.windows.net/dotnet/aspnetcore/Runtime/$ASPNETCORE_VERSION/aspnetcore-runtime-$ASPNETCORE_VERSION-linux-arm.tar.gz" \
&& aspnetcore_sha512='656f95054ca2a40f12f993a7b2d0f734ab7952f52ced8bb52c4c2074a68b93f82fcbc191a215587306f0a7b82e7aec0bd1473de8bf2e8842fabab4d0a8809ead' \
&& echo "$aspnetcore_sha512 aspnetcore.tar.gz" | sha512sum -c - \
&& mkdir -p /usr/share/dotnet \
&& tar -zxf aspnetcore.tar.gz -C /usr/share/dotnet ./shared/Microsoft.AspNetCore.App \
&& rm aspnetcore.tar.gz
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@dotnet.sh" \
&& echo "Running test-stack@dotnet" \
&& chmod +x test-stack@dotnet.sh \
&& bash test-stack@dotnet.sh \
&& rm -rf test-stack@dotnet.sh
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Debian Stretch \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \ndotnet 3.1-aspnet \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh
|
nghiant2710/base-images
|
balena-base-images/dotnet/fincm3/debian/stretch/3.1-aspnet/run/Dockerfile
|
Dockerfile
|
apache-2.0
| 3,122
|
# AUTOGENERATED FILE
FROM balenalib/kitra520-ubuntu:xenial-build
# remove several traces of debian python
RUN apt-get purge -y python.*
# http://bugs.python.org/issue19846
# > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK.
ENV LANG C.UTF-8
# key 63C7CC90: public key "Simon McVittie <smcv@pseudorandom.co.uk>" imported
# key 3372DCFA: public key "Donald Stufft (dstufft) <donald@stufft.io>" imported
RUN gpg --keyserver keyring.debian.org --recv-keys 4DE8FF2A63C7CC90 \
&& gpg --keyserver keyserver.ubuntu.com --recv-key 6E3CBCE93372DCFA \
&& gpg --keyserver keyserver.ubuntu.com --recv-keys 0x52a43a1e4b77b059
ENV PYTHON_VERSION 3.5.10
# if this is called "PIP_VERSION", pip explodes with "ValueError: invalid truth value '<VERSION>'"
ENV PYTHON_PIP_VERSION 21.0.1
ENV SETUPTOOLS_VERSION 56.0.0
RUN set -x \
&& curl -SLO "http://resin-packages.s3.amazonaws.com/python/v$PYTHON_VERSION/Python-$PYTHON_VERSION.linux-armv7hf-openssl1.0.tar.gz" \
&& echo "351ffaa6dc7b44955f886ed42f9d228a268fe8b590f0e745c5434ce0620201dc Python-$PYTHON_VERSION.linux-armv7hf-openssl1.0.tar.gz" | sha256sum -c - \
&& tar -xzf "Python-$PYTHON_VERSION.linux-armv7hf-openssl1.0.tar.gz" --strip-components=1 \
&& rm -rf "Python-$PYTHON_VERSION.linux-armv7hf-openssl1.0.tar.gz" \
&& ldconfig \
&& if [ ! -e /usr/local/bin/pip3 ]; then : \
&& curl -SLO "https://raw.githubusercontent.com/pypa/get-pip/430ba37776ae2ad89f794c7a43b90dc23bac334c/get-pip.py" \
&& echo "19dae841a150c86e2a09d475b5eb0602861f2a5b7761ec268049a662dbd2bd0c get-pip.py" | sha256sum -c - \
&& python3 get-pip.py \
&& rm get-pip.py \
; fi \
&& pip3 install --no-cache-dir --upgrade --force-reinstall pip=="$PYTHON_PIP_VERSION" setuptools=="$SETUPTOOLS_VERSION" \
&& find /usr/local \
\( -type d -a -name test -o -name tests \) \
-o \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \
-exec rm -rf '{}' + \
&& cd / \
&& rm -rf /usr/src/python ~/.cache
# install "virtualenv", since the vast majority of users of this image will want it
RUN pip3 install --no-cache-dir virtualenv
ENV PYTHON_DBUS_VERSION 1.2.8
# install dbus-python dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
libdbus-1-dev \
libdbus-glib-1-dev \
&& rm -rf /var/lib/apt/lists/* \
&& apt-get -y autoremove
# install dbus-python
RUN set -x \
&& mkdir -p /usr/src/dbus-python \
&& curl -SL "http://dbus.freedesktop.org/releases/dbus-python/dbus-python-$PYTHON_DBUS_VERSION.tar.gz" -o dbus-python.tar.gz \
&& curl -SL "http://dbus.freedesktop.org/releases/dbus-python/dbus-python-$PYTHON_DBUS_VERSION.tar.gz.asc" -o dbus-python.tar.gz.asc \
&& gpg --verify dbus-python.tar.gz.asc \
&& tar -xzC /usr/src/dbus-python --strip-components=1 -f dbus-python.tar.gz \
&& rm dbus-python.tar.gz* \
&& cd /usr/src/dbus-python \
&& PYTHON_VERSION=$(expr match "$PYTHON_VERSION" '\([0-9]*\.[0-9]*\)') ./configure \
&& make -j$(nproc) \
&& make install -j$(nproc) \
&& cd / \
&& rm -rf /usr/src/dbus-python
# make some useful symlinks that are expected to exist
RUN cd /usr/local/bin \
&& ln -sf pip3 pip \
&& { [ -e easy_install ] || ln -s easy_install-* easy_install; } \
&& ln -sf idle3 idle \
&& ln -sf pydoc3 pydoc \
&& ln -sf python3 python \
&& ln -sf python3-config python-config
# set PYTHONPATH to point to dist-packages
ENV PYTHONPATH /usr/lib/python3/dist-packages:$PYTHONPATH
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@python.sh" \
&& echo "Running test-stack@python" \
&& chmod +x test-stack@python.sh \
&& bash test-stack@python.sh \
&& rm -rf test-stack@python.sh
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Ubuntu xenial \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nPython v3.5.10, Pip v21.0.1, Setuptools v56.0.0 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh
|
nghiant2710/base-images
|
balena-base-images/python/kitra520/ubuntu/xenial/3.5.10/build/Dockerfile
|
Dockerfile
|
apache-2.0
| 4,831
|
# AUTOGENERATED FILE
FROM balenalib/am571x-evm-debian:buster-run
ENV NODE_VERSION 10.24.0
ENV YARN_VERSION 1.22.4
RUN buildDeps='curl libatomic1' \
&& set -x \
&& for key in \
6A010C5166006599AA17F08146C2130DFD2497F5 \
; do \
gpg --batch --keyserver pgp.mit.edu --recv-keys "$key" || \
gpg --batch --keyserver keyserver.pgp.com --recv-keys "$key" || \
gpg --batch --keyserver ha.pool.sks-keyservers.net --recv-keys "$key" ; \
done \
&& apt-get update && apt-get install -y $buildDeps --no-install-recommends \
&& rm -rf /var/lib/apt/lists/* \
&& curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-armv7l.tar.gz" \
&& echo "02feb052d0e1eb77c9beea5cfe3b67b90d5209ab509797f4f6c892c75cc30fda node-v$NODE_VERSION-linux-armv7l.tar.gz" | sha256sum -c - \
&& tar -xzf "node-v$NODE_VERSION-linux-armv7l.tar.gz" -C /usr/local --strip-components=1 \
&& rm "node-v$NODE_VERSION-linux-armv7l.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \
&& gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& mkdir -p /opt/yarn \
&& tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \
&& rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& npm config set unsafe-perm true -g --unsafe-perm \
&& rm -rf /tmp/*
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@node.sh" \
&& echo "Running test-stack@node" \
&& chmod +x test-stack@node.sh \
&& bash test-stack@node.sh \
&& rm -rf test-stack@node.sh
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Debian Buster \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v10.24.0, Yarn v1.22.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh
|
nghiant2710/base-images
|
balena-base-images/node/am571x-evm/debian/buster/10.24.0/run/Dockerfile
|
Dockerfile
|
apache-2.0
| 2,942
|
# AUTOGENERATED FILE
FROM balenalib/artik533s-debian:buster-build
ENV NODE_VERSION 12.22.1
ENV YARN_VERSION 1.22.4
RUN for key in \
6A010C5166006599AA17F08146C2130DFD2497F5 \
; do \
gpg --batch --keyserver pgp.mit.edu --recv-keys "$key" || \
gpg --batch --keyserver keyserver.pgp.com --recv-keys "$key" || \
gpg --batch --keyserver ha.pool.sks-keyservers.net --recv-keys "$key" ; \
done \
&& curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-armv7l.tar.gz" \
&& echo "1bc056e1fef1c83059235d927edea2c1a2eee91ce654f45369a2af95c041e198 node-v$NODE_VERSION-linux-armv7l.tar.gz" | sha256sum -c - \
&& tar -xzf "node-v$NODE_VERSION-linux-armv7l.tar.gz" -C /usr/local --strip-components=1 \
&& rm "node-v$NODE_VERSION-linux-armv7l.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \
&& gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& mkdir -p /opt/yarn \
&& tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \
&& rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& npm config set unsafe-perm true -g --unsafe-perm \
&& rm -rf /tmp/*
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@node.sh" \
&& echo "Running test-stack@node" \
&& chmod +x test-stack@node.sh \
&& bash test-stack@node.sh \
&& rm -rf test-stack@node.sh
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Debian Buster \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v12.22.1, Yarn v1.22.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh
|
nghiant2710/base-images
|
balena-base-images/node/artik533s/debian/buster/12.22.1/build/Dockerfile
|
Dockerfile
|
apache-2.0
| 2,786
|
###
#
# Copyright 2017, Institute for Systems Biology
#
# 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.
#
###
# Dockerfile extending the generic Python image with application files for a
# single application.
FROM gcr.io/google_appengine/python
# Create a virtualenv for dependencies. This isolates these packages from
# system-level packages.
# Use -p python3 or -p python3.7 to select python version. Default is version 2.
RUN virtualenv /env -p python3
# Setting these environment variables are the same as running
# source /env/bin/activate.
ENV VIRTUAL_ENV /env
ENV PATH /env/bin:$PATH
RUN echo 'download mysql public build key'
RUN apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 467B942D3A79BD29
RUN apt-get update
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get install -y wget
RUN wget "http://repo.mysql.com/mysql-apt-config_0.8.9-1_all.deb" -P /tmp
# install lsb-release (a dependency of mysql-apt-config), since dpkg doesn't
# do dependency resolution
RUN apt-get install -y lsb-release
# add a debconf entry to select mysql-5.7 as the server version when we install
# the mysql config package
RUN echo "mysql-apt-config mysql-apt-config/select-server select mysql-5.7" | debconf-set-selections
# having 'selected' mysql-5.7 for 'server', install the mysql config package
RUN dpkg --install /tmp/mysql-apt-config_0.8.9-1_all.deb
# fetch the updated package metadata (in particular, mysql-server-5.7)
RUN apt-get update
# aaaand now let's install mysql-server
RUN apt-get install -y mysql-server
# Get pip3 installed
RUN curl --silent https://bootstrap.pypa.io/get-pip.py | python3
RUN apt-get -y install build-essential
RUN apt-get -y install --reinstall python-m2crypto python3-crypto
RUN apt-get -y install libxml2-dev libxmlsec1-dev swig
RUN pip3 install pexpect
RUN apt-get -y install unzip libffi-dev libssl-dev libmysqlclient-dev python3-mysqldb python3-dev libpython3-dev git ruby g++ curl
RUN easy_install -U distribute
ADD . /app
# We need to recompile some of the items because of differences in compiler versions
RUN pip3 install -r /app/requirements.txt -t /app/lib/ --upgrade
RUN pip3 install gunicorn==19.6.0
ENV PYTHONPATH=/app:/app/lib:/app/ISB-CGC-Common:${PYTHONPATH}
# Until we figure out a way to do it in CircleCI without whitelisting IPs this has to be done by a dev from
# ISB
# RUN python /app/manage.py migrate --noinput
#CMD gunicorn -c gunicorn.conf.py -b :$PORT isb_cgc.wsgi -w 3 -t 130
CMD gunicorn -c gunicorn.conf.py -b :$PORT isb_cgc.wsgi -w 3 -t 300
# increasing timeout to 5 mins
|
isb-cgc/ISB-CGC-Webapp
|
Dockerfile
|
Dockerfile
|
apache-2.0
| 3,046
|
# AUTOGENERATED FILE
FROM balenalib/edge-alpine:edge-run
ENV GO_VERSION 1.15.8
# set up nsswitch.conf for Go's "netgo" implementation
# - https://github.com/golang/go/blob/go1.9.1/src/net/conf.go#L194-L275
# - docker run --rm debian:stretch grep '^hosts:' /etc/nsswitch.conf
RUN [ ! -e /etc/nsswitch.conf ] && echo 'hosts: files dns' > /etc/nsswitch.conf
# gcc for cgo
RUN apk add --no-cache git gcc ca-certificates
RUN fetchDeps='curl' \
&& set -x \
&& apk add --no-cache $fetchDeps \
&& mkdir -p /usr/local/go \
&& curl -SLO "http://resin-packages.s3.amazonaws.com/golang/v$GO_VERSION/go$GO_VERSION.linux-alpine-amd64.tar.gz" \
&& echo "5237f65d18a7d139a13635a5ae2283c42b39cb68e7210b96a22d8958f04d12b7 go$GO_VERSION.linux-alpine-amd64.tar.gz" | sha256sum -c - \
&& tar -xzf "go$GO_VERSION.linux-alpine-amd64.tar.gz" -C /usr/local/go --strip-components=1 \
&& rm -f go$GO_VERSION.linux-alpine-amd64.tar.gz
ENV GOROOT /usr/local/go
ENV GOPATH /go
ENV PATH $GOPATH/bin:/usr/local/go/bin:$PATH
RUN mkdir -p "$GOPATH/src" "$GOPATH/bin" && chmod -R 777 "$GOPATH"
WORKDIR $GOPATH
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@golang.sh" \
&& echo "Running test-stack@golang" \
&& chmod +x test-stack@golang.sh \
&& bash test-stack@golang.sh \
&& rm -rf test-stack@golang.sh
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: Intel 64-bit (x86-64) \nOS: Alpine Linux edge \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nGo v1.15.8 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo $'#!/bin/bash\nbalena-info\nbusybox ln -sf /bin/busybox /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& ln -f /bin/sh /bin/sh.real \
&& ln -f /bin/sh-shim /bin/sh
|
nghiant2710/base-images
|
balena-base-images/golang/edge/alpine/edge/1.15.8/run/Dockerfile
|
Dockerfile
|
apache-2.0
| 2,468
|
Imports System
Imports System.Drawing
Imports System.Windows.Forms
Public Class PaintToolBar
'¦¹Ãþ§O©w¸qÃö©ó¤u¨ã¦C¥~Æ[¤Î¦æ¬°
Inherits PaintWithRegistry
Protected ToolBarCommand As Integer = 7 '¨Ï¥ÎªÌ¤u¨ã¦C©R¥O¿ï¾Ü
Protected LastCommand As Integer '¤W¤@Ó©R¥O
Protected pnToolbar As Panel '¤u¨ã¦C
Protected radbtnToolbar(15) As NoFocusRadbtn '¤u¨ã¦C¥\¯à
Sub New()
'¤u¨ã¦C«Øºc¤¸
Dim tx, coly, sy As Integer
If bToolbar Then tx = 60 Else tx = 0
If bColorbar Then coly = 50 Else coly = 0
If bStatusbar Then sy = 22 Else sy = 0
pnToolbar = New Panel
With pnToolbar
.Parent = Me
.BorderStyle = BorderStyle.None
.Location = New Point(0, 0)
.Size = New Size(60, ClientSize.Height - coly - sy)
End With
Dim TotTool As New ToolTip
Dim strTotTool() As String = {"¿ï¾Ü¥ô·N½d³ò", "¿ï¾Ü", "¾ó¥ÖÀ¿/±m¦â¾ó¥ÖÀ¿", "¶ñ¤J¦â±m", _
"¬D¿ïÃC¦â", "©ñ¤jÃè", "¹]µ§", "¯»¨ê", "¼Qºj", "¤å¦r", _
"ª½½u", "¦±½u", "¯x§Î", "¦hÃä§Î", "¾ò¶ê§Î", "¶ê¨¤¯x§Î"}
Dim i, cx As Integer
For i = 0 To 15
radbtnToolbar(i) = New NoFocusRadbtn
With radbtnToolbar(i)
.Name = (i + 1).ToString
.Parent = pnToolbar
.Appearance = Appearance.Button
.Size = New Size(26, 26)
.Image = New Bitmap(Me.GetType(), "toolbutton" & (i + 1).ToString & ".bmp")
If (i + 1) Mod 2 <> 0 Then cx = 3 Else cx = 29
.Location = New Point(cx, (i \ 2) * 26)
End With
TotTool.SetToolTip(radbtnToolbar(i), strTotTool(i))
AddHandler radbtnToolbar(i).MouseEnter, AddressOf ToolbarHelp
AddHandler radbtnToolbar(i).MouseLeave, AddressOf ToolbarHelpLeave
AddHandler radbtnToolbar(i).Click, AddressOf ToolbarRadbtnSelect
Next i
radbtnToolbar(6).Checked = True
pnWorkarea.Cursor = New Cursor(Me.GetType(), "Pen.cur")
End Sub
Protected Overrides Sub FormSizeChanged(ByVal obj As Object, ByVal ea As EventArgs)
'©w¸q¦]µøÄ±¤¸¥óÅܧó(¤u¨ã¦C,¦â¶ô°Ï)¤u¨ã¦C®y¼Ð°t¸m
MyBase.FormSizeChanged(obj, ea)
Dim tx, cy, sy As Integer
If bColorbar Then cy = 50 Else cy = 0
If bStatusbar Then sy = 22 Else sy = 0
pnToolbar.Size = New Size(60, ClientSize.Height - cy - sy)
End Sub
Protected Overridable Sub ToolbarHelp(ByVal obj As Object, ByVal ea As EventArgs)
'·í·Æ¹«²¾¦Ü¤u¨ã¦C¤¸¥ó¤W®É,Åã¥Ü¸Ó¤¸¥ó¦bª¬ºA¦Cªº¸ê°T.¥Ñ PaintStatusbar Âмg
End Sub
Protected Overridable Sub ToolbarHelpLeave(ByVal obj As Object, ByVal ea As EventArgs)
'·í·Æ¹«²¾¥X¤u¨ã¦C¤¸¥ó®É,Åã¥Ü¸Ó¤¸¥ó¦bª¬ºA¦Cªº¸ê°T.¥Ñ PaintStatusbar Âмg
End Sub
Protected Overridable Sub ToolbarRadbtnSelect(ByVal obj As Object, ByVal ea As EventArgs)
'©w¸q·í¨Ï¥ÎªÌ¿ï¾Ü¤u¨ã¦C¤¸¥ó®É,©Ò²£¥Íªº¦æ¬°
Dim radbtnSelect As NoFocusRadbtn = DirectCast(obj, NoFocusRadbtn)
LastCommand = ToolBarCommand '¨ú±o¤W¤@Ó¥\¯à
ToolBarCommand = CInt(radbtnSelect.Name) '¨ú±o¨Ï¥ÎªÌ©Ò¿ï¾Üªº¥\¯à
Dim CursorName As String
Select Case ToolBarCommand
Case 1, 2, 10, 11, 12, 13, 14, 15, 16
CursorName = "Cross.cur"
Case 3
CursorName = "Null.cur"
Case 4
CursorName = "FillColor.cur"
Case 5
CursorName = "Color.cur"
Case 6
CursorName = "ZoomSet.cur"
Case 7
CursorName = "Pen.cur"
Case 8
CursorName = "Brush.cur"
Case 9
CursorName = "Spray.cur"
End Select
pnWorkarea.Cursor = New Cursor(Me.GetType(), CursorName)
'³o¨ì¥Ø«e¬°¤î,¶È©w¸q¤F,¹ïÀ³©óø¹Ï¤u§@°Ïªº¹C¼ÐÅã¥Ü,¥Dnªº±±¨î¬yµ{,¥Ñ OverridesÂмg
End Sub
End Class
|
neville1/MSPaint
|
MsPaint Sub/PaintToolbar.vb
|
Visual Basic
|
mit
| 4,078
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:2.0.50727.1433
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
<Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "9.0.0.0"), _
Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Partial Friend NotInheritable Class MySettings
Inherits Global.System.Configuration.ApplicationSettingsBase
Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings),MySettings)
#Region "My.Settings Auto-Save Functionality"
#If _MyType = "WindowsForms" Then
Private Shared addedHandler As Boolean
Private Shared addedHandlerLockObject As New Object
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs)
If My.Application.SaveMySettingsOnExit Then
My.Settings.Save()
End If
End Sub
#End If
#End Region
Public Shared ReadOnly Property [Default]() As MySettings
Get
#If _MyType = "WindowsForms" Then
If Not addedHandler Then
SyncLock addedHandlerLockObject
If Not addedHandler Then
AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings
addedHandler = True
End If
End SyncLock
End If
#End If
Return defaultInstance
End Get
End Property
End Class
End Namespace
Namespace My
<Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _
Friend Module MySettingsProperty
<Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _
Friend ReadOnly Property Settings() As Global.pmDebug.My.MySettings
Get
Return Global.pmDebug.My.MySettings.Default
End Get
End Property
End Module
End Namespace
|
pmprog/pmScript
|
pmDebug/My Project/Settings.Designer.vb
|
Visual Basic
|
mit
| 2,900
|
'-------------------------------------------------------------------------------------------'
' Inicio del codigo
'-------------------------------------------------------------------------------------------'
' Importando librerias
'-------------------------------------------------------------------------------------------'
Imports System.Data
'-------------------------------------------------------------------------------------------'
' Inicio de clase "PAS_fNotas_Credito"
'-------------------------------------------------------------------------------------------'
Partial Class PAS_fNotas_Credito
Inherits vis2formularios.frmReporte
Dim loObjetoReporte As CrystalDecisions.CrystalReports.Engine.ReportDocument
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
Dim loConsulta As New StringBuilder()
loConsulta.AppendLine("SELECT Clientes.Nom_Cli,")
loConsulta.AppendLine(" Clientes.Rif,")
loConsulta.AppendLine(" Clientes.Nit,")
loConsulta.AppendLine(" Clientes.Dir_Fis,")
loConsulta.AppendLine(" Clientes.Telefonos,")
loConsulta.AppendLine(" Clientes.Fax,")
loConsulta.AppendLine(" Cuentas_Cobrar.Documento,")
loConsulta.AppendLine(" CASE WHEN DAY(Cuentas_Cobrar.Fec_Ini) < 10")
loConsulta.AppendLine(" THEN CONCAT('0', DAY(Cuentas_Cobrar.Fec_Ini))")
loConsulta.AppendLine(" ELSE DAY(Cuentas_Cobrar.Fec_Ini)")
loConsulta.AppendLine(" END AS Dia,")
loConsulta.AppendLine(" CASE WHEN MONTH(Cuentas_Cobrar.Fec_Ini) < 10 ")
loConsulta.AppendLine(" THEN CONCAT('0', MONTH(Cuentas_Cobrar.Fec_Ini))")
loConsulta.AppendLine(" ELSE MONTH(Cuentas_Cobrar.Fec_Ini)")
loConsulta.AppendLine(" END AS Mes,")
loConsulta.AppendLine(" YEAR(Cuentas_Cobrar.Fec_Ini) AS Anio,")
loConsulta.AppendLine(" Cuentas_Cobrar.Mon_Bru AS Mon_Bru, ")
loConsulta.AppendLine(" Cuentas_Cobrar.Mon_Imp1 AS Mon_Imp1, ")
loConsulta.AppendLine(" Cuentas_Cobrar.Por_Imp1 AS Por_Imp1, ")
loConsulta.AppendLine(" Cuentas_Cobrar.Mon_Net AS Mon_Net,")
loConsulta.AppendLine(" Cuentas_Cobrar.Mon_Sal AS Mon_Sal,")
loConsulta.AppendLine(" Cuentas_Cobrar.Por_Des AS Por_Des, ")
loConsulta.AppendLine(" Cuentas_Cobrar.Mon_Des AS Mon_Des, ")
loConsulta.AppendLine(" Cuentas_Cobrar.Comentario,")
loConsulta.AppendLine(" Cuentas_Cobrar.Referencia,")
loConsulta.AppendLine(" Renglones_Documentos.Can_Art,")
loConsulta.AppendLine(" Renglones_Documentos.Cod_Uni,")
loConsulta.AppendLine(" Renglones_Documentos.Precio1,")
loConsulta.AppendLine(" Renglones_Documentos.Precio2,")
loConsulta.AppendLine(" Renglones_Documentos.Mon_Net AS Neto,")
loConsulta.AppendLine(" Renglones_Documentos.Comentario AS Com_Renglon,")
loConsulta.AppendLine(" Renglones_Documentos.Notas,")
loConsulta.AppendLine(" Articulos.Nom_Art")
loConsulta.AppendLine("FROM Cuentas_Cobrar")
loConsulta.AppendLine(" JOIN Clientes ")
loConsulta.AppendLine(" ON Cuentas_Cobrar.Cod_Cli = Clientes.Cod_Cli")
loConsulta.AppendLine(" JOIN Renglones_Documentos ")
loConsulta.AppendLine(" ON Cuentas_Cobrar.Documento = Renglones_Documentos.Documento")
loConsulta.AppendLine(" AND Renglones_Documentos.Cod_Tip = 'N/CR'")
loConsulta.AppendLine(" JOIN Articulos ")
loConsulta.AppendLine(" ON Renglones_Documentos.Cod_Art = Articulos.Cod_Art")
loConsulta.AppendLine(" ")
loConsulta.AppendLine("WHERE " & cusAplicacion.goFormatos.pcCondicionPrincipal)
Dim loServicios As New cusDatos.goDatos()
' Me.mEscribirConsulta(loConsulta.ToString())
Dim laDatosReporte As DataSet = loServicios.mObtenerTodosSinEsquema(loConsulta.ToString(), "curReportes")
'Dim lcXml As String = "<impuesto></impuesto>"
'Dim lcPorcentajesImpueto As String
'Dim loImpuestos As New System.Xml.XmlDocument()
'lcPorcentajesImpueto = "("
''Recorre cada renglon de la tabla
'For lnNumeroFila As Integer = 0 To laDatosReporte.Tables(0).Rows.Count - 1
' lcXml = laDatosReporte.Tables(0).Rows(lnNumeroFila).Item("dis_imp")
' If String.IsNullOrEmpty(lcXml.Trim()) Then
' Continue For
' End If
' loImpuestos.LoadXml(lcXml)
' 'En cada renglón lee el contenido de la distribució de impuestos
' For Each loImpuesto As System.Xml.XmlNode In loImpuestos.SelectNodes("impuestos/impuesto")
' If lnNumeroFila = laDatosReporte.Tables(0).Rows.Count - 1 Then
' If CDec(loImpuesto.SelectSingleNode("porcentaje").InnerText) <> 0 Then
' lcPorcentajesImpueto = lcPorcentajesImpueto & ", " & CDec(loImpuesto.SelectSingleNode("porcentaje").InnerText) & "%"
' End If
' End If
' Next loImpuesto
'Next lnNumeroFila
'lcPorcentajesImpueto = lcPorcentajesImpueto & ")"
'lcPorcentajesImpueto = lcPorcentajesImpueto.Replace("(,", "(")
'--------------------------------------------------'
' Carga la imagen del logo en cusReportes '
'--------------------------------------------------'
Me.mCargarLogoEmpresa(laDatosReporte.Tables(0), "LogoEmpresa")
'-------------------------------------------------------------------------------------------------------
' Verificando si el select (tabla nº0) trae registros
'-------------------------------------------------------------------------------------------------------
If (laDatosReporte.Tables(0).Rows.Count <= 0) Then
Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Información", _
"No se Encontraron Registros para los Parámetros Especificados. ", _
vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Informacion, _
"350px", _
"200px")
End If
loObjetoReporte = cusAplicacion.goFormatos.mCargarInforme("PAS_fNotas_Credito", laDatosReporte)
'lcPorcentajesImpueto = lcPorcentajesImpueto.Replace(".", ",")
'CType(loObjetoReporte.ReportDefinition.ReportObjects("Text1"), CrystalDecisions.CrystalReports.Engine.TextObject).Text = lcPorcentajesImpueto.ToString
Me.mTraducirReporte(loObjetoReporte)
Me.mFormatearCamposReporte(loObjetoReporte)
Me.crvPAS_fNotas_Credito.ReportSource = loObjetoReporte
Catch loExcepcion As Exception
Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Error", _
"No se pudo Completar el Proceso: " & loExcepcion.Message, _
vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Error, _
"auto", _
"auto")
End Try
End Sub
Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
Try
loObjetoReporte.Close()
Catch loExcepcion As Exception
End Try
End Sub
End Class
'-------------------------------------------------------------------------------------------'
' Fin del codigo '
'-------------------------------------------------------------------------------------------'
' GMO: 16/08/08: Codigo inicial. '
'-------------------------------------------------------------------------------------------'
' JJD: 08/11/08: Ajustes al select. '
'-------------------------------------------------------------------------------------------'
' RJG: 01/09/09: Agregado código para mostrar unidad segundaria. '
'-------------------------------------------------------------------------------------------'
' CMS: 10/09/09: Se ajusto el nombre del articulo para los casos de aquellos articulos gen. '
'-------------------------------------------------------------------------------------------'
' JJD: 09/01/10: Se cambio para que leyera los datos genericos de la Factura cuando aplique.'
'-------------------------------------------------------------------------------------------'
' CMS: 18/03/10: Se aplicaron los metodos carga de imagen y validacion de registro cero. '
'-------------------------------------------------------------------------------------------'
' CMS: 19/03/10: Se a justo la logica para determinar el nombre del cliente '
' (Clientes.Generico = 0 ) a (Clientes.Generico = 0 AND Cuentas_Cobrar.Nom_Cli = '') '
'-------------------------------------------------------------------------------------------'
' MAT: 23/02/11: Se programo la distribución de impuestos para mostrarlo en el formato. '
'-------------------------------------------------------------------------------------------'
' MAT: 19/04/11 : Ajuste de la vista de diseño. '
'-------------------------------------------------------------------------------------------'
' RJG: 06/02/14 : Ajuste de la formato (comentario, indentación...) de código y SQL. '
'-------------------------------------------------------------------------------------------'
|
kodeitsolutions/ef-reports
|
PAS_fNotas_Credito.aspx.vb
|
Visual Basic
|
mit
| 10,260
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class LogoutBox
Inherits System.Windows.Forms.Form
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(LogoutBox))
Me.TableLayoutPanel1 = New System.Windows.Forms.TableLayoutPanel()
Me.OK_Button = New System.Windows.Forms.Button()
Me.Cancel_Button = New System.Windows.Forms.Button()
Me.lblLogout = New System.Windows.Forms.Label()
Me.Label1 = New System.Windows.Forms.Label()
Me.TableLayoutPanel1.SuspendLayout()
Me.SuspendLayout()
'
'TableLayoutPanel1
'
Me.TableLayoutPanel1.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.TableLayoutPanel1.ColumnCount = 2
Me.TableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50.0!))
Me.TableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50.0!))
Me.TableLayoutPanel1.Controls.Add(Me.OK_Button, 0, 0)
Me.TableLayoutPanel1.Controls.Add(Me.Cancel_Button, 1, 0)
Me.TableLayoutPanel1.Location = New System.Drawing.Point(115, 158)
Me.TableLayoutPanel1.Name = "TableLayoutPanel1"
Me.TableLayoutPanel1.RowCount = 1
Me.TableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50.0!))
Me.TableLayoutPanel1.Size = New System.Drawing.Size(221, 50)
Me.TableLayoutPanel1.TabIndex = 0
'
'OK_Button
'
Me.OK_Button.Anchor = System.Windows.Forms.AnchorStyles.None
Me.OK_Button.BackColor = System.Drawing.Color.White
Me.OK_Button.DialogResult = System.Windows.Forms.DialogResult.OK
Me.OK_Button.FlatStyle = System.Windows.Forms.FlatStyle.Flat
Me.OK_Button.Font = New System.Drawing.Font("Arial", 11.0!)
Me.OK_Button.Location = New System.Drawing.Point(3, 3)
Me.OK_Button.Name = "OK_Button"
Me.OK_Button.Size = New System.Drawing.Size(104, 44)
Me.OK_Button.TabIndex = 0
Me.OK_Button.Text = "Log out"
Me.OK_Button.UseVisualStyleBackColor = False
'
'Cancel_Button
'
Me.Cancel_Button.Anchor = System.Windows.Forms.AnchorStyles.None
Me.Cancel_Button.BackColor = System.Drawing.Color.White
Me.Cancel_Button.DialogResult = System.Windows.Forms.DialogResult.Cancel
Me.Cancel_Button.FlatStyle = System.Windows.Forms.FlatStyle.Flat
Me.Cancel_Button.Font = New System.Drawing.Font("Arial", 11.0!)
Me.Cancel_Button.Location = New System.Drawing.Point(113, 3)
Me.Cancel_Button.Name = "Cancel_Button"
Me.Cancel_Button.Size = New System.Drawing.Size(105, 44)
Me.Cancel_Button.TabIndex = 1
Me.Cancel_Button.Text = "Cancel"
Me.Cancel_Button.UseVisualStyleBackColor = False
'
'lblLogout
'
Me.lblLogout.AutoSize = True
Me.lblLogout.Font = New System.Drawing.Font("Arial", 18.0!)
Me.lblLogout.Location = New System.Drawing.Point(39, 36)
Me.lblLogout.Name = "lblLogout"
Me.lblLogout.Size = New System.Drawing.Size(373, 27)
Me.lblLogout.TabIndex = 1
Me.lblLogout.Text = "Are you sure you want to log out?"
'
'Label1
'
Me.Label1.AutoSize = True
Me.Label1.Font = New System.Drawing.Font("Arial", 11.0!)
Me.Label1.Location = New System.Drawing.Point(86, 103)
Me.Label1.Name = "Label1"
Me.Label1.Size = New System.Drawing.Size(278, 17)
Me.Label1.TabIndex = 2
Me.Label1.Text = "(You will be redirected to the login screen)"
'
'LogoutBox
'
Me.AcceptButton = Me.OK_Button
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None
Me.BackColor = System.Drawing.Color.Silver
Me.CancelButton = Me.Cancel_Button
Me.ClientSize = New System.Drawing.Size(450, 220)
Me.Controls.Add(Me.Label1)
Me.Controls.Add(Me.lblLogout)
Me.Controls.Add(Me.TableLayoutPanel1)
Me.Font = New System.Drawing.Font("Arial", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle
Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon)
Me.MaximizeBox = False
Me.MinimizeBox = False
Me.Name = "LogoutBox"
Me.ShowInTaskbar = False
Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
Me.Text = "Logout?"
Me.TableLayoutPanel1.ResumeLayout(False)
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Friend WithEvents TableLayoutPanel1 As System.Windows.Forms.TableLayoutPanel
Friend WithEvents OK_Button As System.Windows.Forms.Button
Friend WithEvents Cancel_Button As System.Windows.Forms.Button
Friend WithEvents lblLogout As Label
Friend WithEvents Label1 As Label
End Class
|
KameQuazi/Software-Major-Assignment-2k18
|
LampClient/DialogBoxes/LogoutBox.Designer.vb
|
Visual Basic
|
mit
| 6,027
|
Namespace Media
''' <summary></summary>
''' <autogenerated>Generated from a T4 template. Modifications will be lost, if applicable use a partial class instead.</autogenerated>
''' <generator-date>17/02/2014 16:03:03</generator-date>
''' <generator-functions>1</generator-functions>
''' <generator-source>Deimos\_Media\Enums\WMT_ATTR_DATATYPE.tt</generator-source>
''' <generator-version>1</generator-version>
<System.CodeDom.Compiler.GeneratedCode("Deimos\_Media\Enums\WMT_ATTR_DATATYPE.tt", "1")> _
Public Enum WMT_ATTR_DATATYPE As System.Int32
''' <summary>WMT_TYPE_DWORD</summary>
WMT_TYPE_DWORD = 0
''' <summary>WMT_TYPE_STRING</summary>
WMT_TYPE_STRING = 1
''' <summary>WMT_TYPE_BINARY</summary>
WMT_TYPE_BINARY = 2
''' <summary>WMT_TYPE_BOOL</summary>
WMT_TYPE_BOOL = 3
''' <summary>WMT_TYPE_QWORD</summary>
WMT_TYPE_QWORD = 4
''' <summary>WMT_TYPE_WORD</summary>
WMT_TYPE_WORD = 5
''' <summary>WMT_TYPE_GUID</summary>
WMT_TYPE_GUID = 6
End Enum
End Namespace
|
thiscouldbejd/Deimos
|
_Media/Enums/WMT_ATTR_DATATYPE.vb
|
Visual Basic
|
mit
| 1,012
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.239
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
<Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0"), _
Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Partial Friend NotInheritable Class MySettings
Inherits Global.System.Configuration.ApplicationSettingsBase
Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings()),MySettings)
#Region "My.Settings Auto-Save Functionality"
#If _MyType = "WindowsForms" Then
Private Shared addedHandler As Boolean
Private Shared addedHandlerLockObject As New Object
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs)
If My.Application.SaveMySettingsOnExit Then
My.Settings.Save()
End If
End Sub
#End If
#End Region
Public Shared ReadOnly Property [Default]() As MySettings
Get
#If _MyType = "WindowsForms" Then
If Not addedHandler Then
SyncLock addedHandlerLockObject
If Not addedHandler Then
AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings
addedHandler = True
End If
End SyncLock
End If
#End If
Return defaultInstance
End Get
End Property
End Class
End Namespace
Namespace My
<Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _
Friend Module MySettingsProperty
<Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _
Friend ReadOnly Property Settings() As Global.App.My.MySettings
Get
Return Global.App.My.MySettings.Default
End Get
End Property
End Module
End Namespace
|
WillSams/aspnet_mvc3_springnhibernate
|
src/web/My Project/Settings.Designer.vb
|
Visual Basic
|
apache-2.0
| 2,894
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.CodeGen
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic
Friend NotInheritable Class Rewriter
Public Shared Function LowerBodyOrInitializer(
method As MethodSymbol,
methodOrdinal As Integer,
body As BoundBlock,
previousSubmissionFields As SynthesizedSubmissionFields,
compilationState As TypeCompilationState,
diagnostics As DiagnosticBag,
ByRef lazyVariableSlotAllocator As VariableSlotAllocator,
lambdaDebugInfoBuilder As ArrayBuilder(Of LambdaDebugInfo),
closureDebugInfoBuilder As ArrayBuilder(Of ClosureDebugInfo),
ByRef delegateRelaxationIdDispenser As Integer,
<Out> ByRef stateMachineTypeOpt As StateMachineTypeSymbol,
allowOmissionOfConditionalCalls As Boolean,
isBodySynthesized As Boolean) As BoundBlock
Debug.Assert(Not body.HasErrors)
Debug.Assert(compilationState.ModuleBuilderOpt IsNot Nothing)
' performs node-specific lowering.
Dim sawLambdas As Boolean
Dim symbolsCapturedWithoutCopyCtor As ISet(Of Symbol) = Nothing
Dim rewrittenNodes As HashSet(Of BoundNode) = Nothing
Dim flags = If(allowOmissionOfConditionalCalls, LocalRewriter.RewritingFlags.AllowOmissionOfConditionalCalls, LocalRewriter.RewritingFlags.Default)
Dim loweredBody = LocalRewriter.Rewrite(body,
method,
compilationState,
previousSubmissionFields,
diagnostics,
rewrittenNodes,
sawLambdas,
symbolsCapturedWithoutCopyCtor,
flags,
currentMethod:=Nothing)
If loweredBody.HasErrors Then
Return loweredBody
End If
#If DEBUG Then
For Each node In rewrittenNodes.ToArray
If node.Kind = BoundKind.Literal Then
rewrittenNodes.Remove(node)
End If
Next
#End If
If lazyVariableSlotAllocator Is Nothing Then
' synthesized lambda methods are handled in LambdaRewriter.RewriteLambdaAsMethod
Debug.Assert(TypeOf method IsNot SynthesizedLambdaMethod)
lazyVariableSlotAllocator = compilationState.ModuleBuilderOpt.TryCreateVariableSlotAllocator(method, method)
End If
' Lowers lambda expressions into expressions that construct delegates.
Dim bodyWithoutLambdas = loweredBody
If sawLambdas Then
bodyWithoutLambdas = LambdaRewriter.Rewrite(loweredBody,
method,
methodOrdinal,
lambdaDebugInfoBuilder,
closureDebugInfoBuilder,
delegateRelaxationIdDispenser,
lazyVariableSlotAllocator,
compilationState,
If(symbolsCapturedWithoutCopyCtor, SpecializedCollections.EmptySet(Of Symbol)),
diagnostics,
rewrittenNodes)
End If
If bodyWithoutLambdas.HasErrors Then
Return bodyWithoutLambdas
End If
Return RewriteIteratorAndAsync(bodyWithoutLambdas, method, methodOrdinal, compilationState, diagnostics, lazyVariableSlotAllocator, stateMachineTypeOpt)
End Function
Friend Shared Function RewriteIteratorAndAsync(bodyWithoutLambdas As BoundBlock,
method As MethodSymbol,
methodOrdinal As Integer,
compilationState As TypeCompilationState,
diagnostics As DiagnosticBag,
slotAllocatorOpt As VariableSlotAllocator,
<Out> ByRef stateMachineTypeOpt As StateMachineTypeSymbol) As BoundBlock
Debug.Assert(compilationState.ModuleBuilderOpt IsNot Nothing)
Dim iteratorStateMachine As IteratorStateMachine = Nothing
Dim bodyWithoutIterators = IteratorRewriter.Rewrite(bodyWithoutLambdas,
method,
methodOrdinal,
slotAllocatorOpt,
compilationState,
diagnostics,
iteratorStateMachine)
If bodyWithoutIterators.HasErrors Then
Return bodyWithoutIterators
End If
Dim asyncStateMachine As AsyncStateMachine = Nothing
Dim bodyWithoutAsync = AsyncRewriter.Rewrite(bodyWithoutIterators,
method,
methodOrdinal,
slotAllocatorOpt,
compilationState,
diagnostics,
asyncStateMachine)
Debug.Assert(iteratorStateMachine Is Nothing OrElse asyncStateMachine Is Nothing)
stateMachineTypeOpt = If(iteratorStateMachine, DirectCast(asyncStateMachine, StateMachineTypeSymbol))
Return bodyWithoutAsync
End Function
End Class
End Namespace
|
paladique/roslyn
|
src/Compilers/VisualBasic/Portable/Lowering/Rewriter.vb
|
Visual Basic
|
apache-2.0
| 6,817
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Collections.Immutable
Imports System.Diagnostics
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend NotInheritable Class LocalRewriter
Private Function WrapInNullable(expr As BoundExpression, nullableType As TypeSymbol) As BoundExpression
Debug.Assert(nullableType.GetNullableUnderlyingType.IsSameTypeIgnoringAll(expr.Type))
Dim ctor = GetNullableMethod(expr.Syntax, nullableType, SpecialMember.System_Nullable_T__ctor)
If ctor IsNot Nothing Then
Return New BoundObjectCreationExpression(expr.Syntax,
ctor,
ImmutableArray.Create(expr),
Nothing,
nullableType)
End If
Return New BoundBadExpression(expr.Syntax, LookupResultKind.NotReferencable, ImmutableArray(Of Symbol).Empty, ImmutableArray.Create(expr), nullableType, hasErrors:=True)
End Function
''' <summary>
''' Splits nullable operand into a hasValueExpression and an expression that represents underlying value (returned).
'''
''' Underlying value can be called after calling hasValueExpr without duplicated side-effects.
''' Note that hasValueExpr is guaranteed to have NO SIDE-EFFECTS, while result value is
''' expected to be called exactly ONCE. That is the normal pattern in operator lifting.
'''
''' All necessary temps and side-effecting initializations are appended to temps and inits
''' </summary>
Private Function ProcessNullableOperand(operand As BoundExpression,
<Out> ByRef hasValueExpr As BoundExpression,
ByRef temps As ArrayBuilder(Of LocalSymbol),
ByRef inits As ArrayBuilder(Of BoundExpression),
doNotCaptureLocals As Boolean) As BoundExpression
Return ProcessNullableOperand(operand, hasValueExpr, temps, inits, doNotCaptureLocals, HasValue(operand))
End Function
Private Function ProcessNullableOperand(operand As BoundExpression,
<Out> ByRef hasValueExpr As BoundExpression,
ByRef temps As ArrayBuilder(Of LocalSymbol),
ByRef inits As ArrayBuilder(Of BoundExpression),
doNotCaptureLocals As Boolean,
operandHasValue As Boolean) As BoundExpression
Debug.Assert(Not HasNoValue(operand), "processing nullable operand when it is known to be null")
If operandHasValue Then
operand = NullableValueOrDefault(operand)
End If
Dim captured = CaptureNullableIfNeeded(operand, temps, inits, doNotCaptureLocals)
If operandHasValue Then
hasValueExpr = New BoundLiteral(operand.Syntax, ConstantValue.True, Me.GetSpecialType(SpecialType.System_Boolean))
Return captured
End If
hasValueExpr = NullableHasValue(captured)
Return NullableValueOrDefault(captured)
End Function
' Right operand could be a method that takes Left operand byref. Ex: " local And TakesArgByref(local) "
' So in general we must capture Left even if it is a local.
' however in many case we do not need that.
Private Function RightCanChangeLeftLocal(left As BoundExpression, right As BoundExpression) As Boolean
' TODO: in most cases right operand does not change value of the left one
' we could be smarter than this.
Return right.Kind = BoundKind.Local OrElse
right.Kind = BoundKind.Parameter
End Function
''' <summary>
''' Returns a NOT-SIDE-EFFECTING expression that represents results of the operand
''' If such transformation requires a temp, the temp and its initializing expression
''' are returned in temp/init
''' </summary>
Private Function CaptureNullableIfNeeded(operand As BoundExpression,
<Out> ByRef temp As SynthesizedLocal,
<Out> ByRef init As BoundExpression,
doNotCaptureLocals As Boolean) As BoundExpression
temp = Nothing
init = Nothing
If operand.IsConstant Then
Return operand
End If
If doNotCaptureLocals Then
If operand.Kind = BoundKind.Local AndAlso Not DirectCast(operand, BoundLocal).LocalSymbol.IsByRef Then
Return operand
End If
If operand.Kind = BoundKind.Parameter AndAlso Not DirectCast(operand, BoundParameter).ParameterSymbol.IsByRef Then
Return operand
End If
End If
' capture into local.
Return CaptureOperand(operand, temp, init)
End Function
Private Function CaptureOperand(operand As BoundExpression, <Out> ByRef temp As SynthesizedLocal, <Out> ByRef init As BoundExpression) As BoundExpression
temp = New SynthesizedLocal(Me._currentMethodOrLambda, operand.Type, SynthesizedLocalKind.LoweringTemp)
Dim localAccess = New BoundLocal(operand.Syntax, temp, True, temp.Type)
init = New BoundAssignmentOperator(operand.Syntax, localAccess, operand, True, operand.Type)
Return localAccess.MakeRValue
End Function
Private Function CaptureNullableIfNeeded(
operand As BoundExpression,
<[In], Out> ByRef temps As ArrayBuilder(Of LocalSymbol),
<[In], Out> ByRef inits As ArrayBuilder(Of BoundExpression),
doNotCaptureLocals As Boolean
) As BoundExpression
Dim temp As SynthesizedLocal = Nothing
Dim init As BoundExpression = Nothing
Dim captured = CaptureNullableIfNeeded(operand, temp, init, doNotCaptureLocals)
If temp IsNot Nothing Then
temps = If(temps, ArrayBuilder(Of LocalSymbol).GetInstance)
temps.Add(temp)
Debug.Assert(init IsNot Nothing)
inits = If(inits, ArrayBuilder(Of BoundExpression).GetInstance)
inits.Add(init)
Else
Debug.Assert(captured Is operand)
End If
Return captured
End Function
''' <summary>
''' Returns expression that -
''' a) evaluates the operand if needed
''' b) produces it's ValueOrDefault.
''' The helper is familiar with wrapping expressions and will go directly after the value
''' skipping wrap/unwrap steps.
''' </summary>
Private Function NullableValueOrDefault(expr As BoundExpression) As BoundExpression
Debug.Assert(expr.Type.IsNullableType)
' check if we are not getting value from freshly constructed nullable
' no need to wrap/unwrap it then.
If expr.Kind = BoundKind.ObjectCreationExpression Then
Dim objectCreation = DirectCast(expr, BoundObjectCreationExpression)
' passing one argument means we are calling New Nullable<T>(arg)
If objectCreation.Arguments.Length = 1 Then
Return objectCreation.Arguments(0)
End If
End If
Dim getValueOrDefaultMethod = GetNullableMethod(expr.Syntax, expr.Type, SpecialMember.System_Nullable_T_GetValueOrDefault)
If getValueOrDefaultMethod IsNot Nothing Then
Return New BoundCall(expr.Syntax,
getValueOrDefaultMethod,
Nothing,
expr,
ImmutableArray(Of BoundExpression).Empty,
Nothing,
isLValue:=False,
suppressObjectClone:=True,
type:=getValueOrDefaultMethod.ReturnType)
End If
Return New BoundBadExpression(expr.Syntax, LookupResultKind.NotReferencable, ImmutableArray(Of Symbol).Empty, ImmutableArray.Create(expr), expr.Type.GetNullableUnderlyingType(), hasErrors:=True)
End Function
Private Function NullableValue(expr As BoundExpression) As BoundExpression
Debug.Assert(expr.Type.IsNullableType)
If HasValue(expr) Then
Return NullableValueOrDefault(expr)
End If
Dim getValueMethod As MethodSymbol = GetNullableMethod(expr.Syntax, expr.Type, SpecialMember.System_Nullable_T_get_Value)
If getValueMethod IsNot Nothing Then
Return New BoundCall(expr.Syntax,
getValueMethod,
Nothing,
expr,
ImmutableArray(Of BoundExpression).Empty,
Nothing,
isLValue:=False,
suppressObjectClone:=True,
type:=getValueMethod.ReturnType)
End If
Return New BoundBadExpression(expr.Syntax, LookupResultKind.NotReferencable, ImmutableArray(Of Symbol).Empty, ImmutableArray.Create(expr), expr.Type.GetNullableUnderlyingType(), hasErrors:=True)
End Function
''' <summary>
''' Evaluates expr and calls HasValue on it.
''' </summary>
Private Function NullableHasValue(expr As BoundExpression) As BoundExpression
Debug.Assert(expr.Type.IsNullableType)
' when we statically know if expr HasValue we may skip
' evaluation depending on context.
Debug.Assert(Not HasValue(expr))
Debug.Assert(Not HasNoValue(expr))
Dim hasValueMethod As MethodSymbol = GetNullableMethod(expr.Syntax, expr.Type, SpecialMember.System_Nullable_T_get_HasValue)
If hasValueMethod IsNot Nothing Then
Return New BoundCall(expr.Syntax,
hasValueMethod,
Nothing,
expr,
ImmutableArray(Of BoundExpression).Empty,
Nothing,
isLValue:=False,
suppressObjectClone:=True,
type:=hasValueMethod.ReturnType)
End If
Return New BoundBadExpression(expr.Syntax, LookupResultKind.NotReferencable, ImmutableArray(Of Symbol).Empty, ImmutableArray.Create(expr),
Me.Compilation.GetSpecialType(SpecialType.System_Boolean), hasErrors:=True)
End Function
Private Shared Function NullableNull(syntax As SyntaxNode, nullableType As TypeSymbol) As BoundExpression
Debug.Assert(nullableType.IsNullableType)
Return New BoundObjectCreationExpression(syntax,
Nothing,
ImmutableArray(Of BoundExpression).Empty,
Nothing,
nullableType)
End Function
''' <summary>
''' Checks that candidate Null expression is a simple expression that produces Null of the desired type
''' (not a conversion or anything like that) and returns it.
''' Otherwise creates "New T?()" expression.
''' </summary>
Private Shared Function NullableNull(candidateNullExpression As BoundExpression,
type As TypeSymbol) As BoundExpression
Debug.Assert(HasNoValue(candidateNullExpression))
' in case if the expression is any more complicated than just creating a Null
' simplify it. This may happen if HasNoValue gets smarter and can
' detect situations other than "New T?()"
If (Not type.IsSameTypeIgnoringAll(candidateNullExpression.Type)) OrElse
candidateNullExpression.Kind <> BoundKind.ObjectCreationExpression Then
Return NullableNull(candidateNullExpression.Syntax, type)
End If
Return candidateNullExpression
End Function
Private Function NullableFalse(syntax As SyntaxNode, nullableOfBoolean As TypeSymbol) As BoundExpression
Debug.Assert(nullableOfBoolean.IsNullableOfBoolean)
Dim booleanType = nullableOfBoolean.GetNullableUnderlyingType
Return WrapInNullable(New BoundLiteral(syntax, ConstantValue.False, booleanType), nullableOfBoolean)
End Function
Private Function NullableTrue(syntax As SyntaxNode, nullableOfBoolean As TypeSymbol) As BoundExpression
Debug.Assert(nullableOfBoolean.IsNullableOfBoolean)
Dim booleanType = nullableOfBoolean.GetNullableUnderlyingType
Return WrapInNullable(New BoundLiteral(syntax, ConstantValue.True, booleanType), nullableOfBoolean)
End Function
Private Function GetNullableMethod(syntax As SyntaxNode, nullableType As TypeSymbol, member As SpecialMember) As MethodSymbol
Dim method As MethodSymbol = Nothing
If TryGetSpecialMember(method, member, syntax) Then
Dim substitutedType = DirectCast(nullableType, SubstitutedNamedType)
Return DirectCast(substitutedType.GetMemberForDefinition(method), MethodSymbol)
End If
Return Nothing
End Function
Private Function NullableOfBooleanValue(syntax As SyntaxNode, isTrue As Boolean, nullableOfBoolean As TypeSymbol) As BoundExpression
If isTrue Then
Return NullableTrue(syntax, nullableOfBoolean)
Else
Return NullableFalse(syntax, nullableOfBoolean)
End If
End Function
''' <summary>
''' returns true when expression has NO SIDE-EFFECTS and is known to produce nullable NULL
''' </summary>
Private Shared Function HasNoValue(expr As BoundExpression) As Boolean
Debug.Assert(expr.Type.IsNullableType)
If expr.Kind = BoundKind.ObjectCreationExpression Then
Dim objCreation = DirectCast(expr, BoundObjectCreationExpression)
' Nullable<T> has only one ctor with parameters and only that one sets hasValue = true
Return objCreation.Arguments.Length = 0
End If
' by default we do not know
Return False
End Function
''' <summary>
''' Returns true when expression is known to produce nullable NOT-NULL
''' NOTE: unlike HasNoValue case, HasValue expressions may have side-effects.
''' </summary>
Private Shared Function HasValue(expr As BoundExpression) As Boolean
Debug.Assert(expr.Type.IsNullableType)
If expr.Kind = BoundKind.ObjectCreationExpression Then
Dim objCreation = DirectCast(expr, BoundObjectCreationExpression)
' Nullable<T> has only one ctor with parameters and only that one sets hasValue = true
Return objCreation.Arguments.Length <> 0
End If
' by default we do not know
Return False
End Function
''' <summary>
''' Helper to generate binary expressions.
''' Performs some trivial constant folding.
''' TODO: Perhaps belong to a different file
''' </summary>
Private Function MakeBinaryExpression(syntax As SyntaxNode,
binaryOpKind As BinaryOperatorKind,
left As BoundExpression,
right As BoundExpression,
isChecked As Boolean,
resultType As TypeSymbol) As BoundExpression
Debug.Assert(Not left.Type.IsNullableType)
Debug.Assert(Not right.Type.IsNullableType)
Dim intOverflow As Boolean = False
Dim divideByZero As Boolean = False
Dim lengthOutOfLimit As Boolean = False
Dim constant = OverloadResolution.TryFoldConstantBinaryOperator(binaryOpKind, left, right, resultType, intOverflow, divideByZero, lengthOutOfLimit)
If constant IsNot Nothing AndAlso
Not divideByZero AndAlso
Not (intOverflow And isChecked) AndAlso
Not lengthOutOfLimit Then
Debug.Assert(Not constant.IsBad)
Return New BoundLiteral(syntax, constant, resultType)
End If
Select Case binaryOpKind
Case BinaryOperatorKind.Subtract
If right.IsDefaultValueConstant Then
Return left
End If
Case BinaryOperatorKind.Add,
BinaryOperatorKind.Or,
BinaryOperatorKind.OrElse
' if one of operands is trivial, return the other one
If left.IsDefaultValueConstant Then
Return right
End If
If right.IsDefaultValueConstant Then
Return left
End If
' if one of operands is True, evaluate the other and return the True one
If left.IsTrueConstant Then
Return MakeSequence(right, left)
End If
If right.IsTrueConstant Then
Return MakeSequence(left, right)
End If
Case BinaryOperatorKind.And,
BinaryOperatorKind.AndAlso,
BinaryOperatorKind.Multiply
' if one of operands is trivial, evaluate the other and return the trivial one
If left.IsDefaultValueConstant Then
Return MakeSequence(right, left)
End If
If right.IsDefaultValueConstant Then
Return MakeSequence(left, right)
End If
' if one of operands is True, return the other one
If left.IsTrueConstant Then
Return right
End If
If right.IsTrueConstant Then
Return left
End If
Case BinaryOperatorKind.Equals
If left.IsTrueConstant Then
Return right
End If
If right.IsTrueConstant Then
Return left
End If
Case BinaryOperatorKind.NotEquals
If left.IsFalseConstant Then
Return right
End If
If right.IsFalseConstant Then
Return left
End If
End Select
Return TransformRewrittenBinaryOperator(New BoundBinaryOperator(syntax, binaryOpKind, left, right, isChecked, resultType))
End Function
''' <summary>
''' Simpler helper for binary expressions.
''' When operand are boolean, the result type is same as operand's and is never checked
''' so do not need to pass that in.
''' </summary>
Private Function MakeBooleanBinaryExpression(syntax As SyntaxNode,
binaryOpKind As BinaryOperatorKind,
left As BoundExpression,
right As BoundExpression) As BoundExpression
Debug.Assert(TypeSymbol.Equals(left.Type, right.Type, TypeCompareKind.ConsiderEverything))
Debug.Assert(left.Type.IsBooleanType)
Return MakeBinaryExpression(syntax, binaryOpKind, left, right, False, left.Type)
End Function
Private Shared Function MakeNullLiteral(syntax As SyntaxNode, type As TypeSymbol) As BoundLiteral
Return New BoundLiteral(syntax, ConstantValue.Nothing, type)
End Function
''' <summary>
''' Takes two expressions and makes sequence.
''' </summary>
Private Shared Function MakeSequence(first As BoundExpression, second As BoundExpression) As BoundExpression
Return MakeSequence(second.Syntax, first, second)
End Function
''' <summary>
''' Takes two expressions and makes sequence.
''' </summary>
Private Shared Function MakeSequence(syntax As SyntaxNode,
first As BoundExpression,
second As BoundExpression) As BoundExpression
Dim sideeffects = GetSideeffects(first)
If sideeffects Is Nothing Then
Return second
End If
Return New BoundSequence(syntax,
ImmutableArray(Of LocalSymbol).Empty,
ImmutableArray.Create(sideeffects),
second,
second.Type)
End Function
''' <summary>
''' Takes two expressions and makes sequence.
''' </summary>
Private Function MakeTernaryConditionalExpression(syntax As SyntaxNode,
condition As BoundExpression,
whenTrue As BoundExpression,
whenFalse As BoundExpression) As BoundExpression
Debug.Assert(condition.Type.IsBooleanType, "ternary condition must be boolean")
Debug.Assert(whenTrue.Type.IsSameTypeIgnoringAll(whenFalse.Type), "ternary branches must have same types")
Dim ifConditionConst = condition.ConstantValueOpt
If ifConditionConst IsNot Nothing Then
Return MakeSequence(syntax, condition, If(ifConditionConst Is ConstantValue.True, whenTrue, whenFalse))
End If
Return TransformRewrittenTernaryConditionalExpression(New BoundTernaryConditionalExpression(syntax, condition, whenTrue, whenFalse, Nothing, whenTrue.Type))
End Function
''' <summary>
''' Returns an expression that can be used instead of the original one when
''' we want to run the expression for side-effects only (i.e. we intend to ignore result).
''' </summary>
Private Shared Function GetSideeffects(operand As BoundExpression) As BoundExpression
If operand.IsConstant Then
Return Nothing
End If
Select Case operand.Kind
Case BoundKind.Local,
BoundKind.Parameter
Return Nothing
Case BoundKind.ObjectCreationExpression
If operand.Type.IsNullableType Then
Dim objCreation = DirectCast(operand, BoundObjectCreationExpression)
Dim args = objCreation.Arguments
If args.Length = 0 Then
Return Nothing
Else
Return GetSideeffects(args(0))
End If
End If
End Select
Return operand
End Function
End Class
End Namespace
|
aelij/roslyn
|
src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_NullableHelpers.vb
|
Visual Basic
|
apache-2.0
| 24,667
|
Public Class mysqlSettings
Private Sub btnSalvar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSalvar.Click
'Guardamos en sus respectivas variables globales
_varglobal.ip = txtIp.Text
_varglobal.pass = txtPass.Text
_varglobal.user = txtUser.Text
'Cerramos el formulario
Me.Close()
End Sub
Private Sub mysqlSettings_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Guardamos los parámetros de conexión dentro de sus respectivas variables
_varglobal.ip = txtIp.Text
_varglobal.pass = txtPass.Text
_varglobal.user = txtUser.Text
End Sub
End Class
|
cecortes/Rekor
|
Vb/rekorRfidWebCam/rekorRfidWebCam/mysqlSettings.vb
|
Visual Basic
|
apache-2.0
| 714
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Scanning_keluar_Edit
Inherits System.Windows.Forms.Form
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.components = New System.ComponentModel.Container
Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(Scanning_keluar_Edit))
Me.LBLNama = New System.Windows.Forms.Label
Me.ListView1 = New System.Windows.Forms.ListView
Me.FileName = New System.Windows.Forms.ColumnHeader
Me.Lokasi = New System.Windows.Forms.ColumnHeader
Me.BTNScan = New System.Windows.Forms.Button
Me.GroupBox1 = New System.Windows.Forms.GroupBox
Me.BTNHapus = New System.Windows.Forms.Button
Me.BTNSImpan = New System.Windows.Forms.Button
Me.Label1 = New System.Windows.Forms.Label
Me._twain32 = New Saraff.Twain.Twain32(Me.components)
Me.Label12 = New System.Windows.Forms.Label
Me.Label23 = New System.Windows.Forms.Label
Me.GroupBox3 = New System.Windows.Forms.GroupBox
Me.BTNTutup = New System.Windows.Forms.Button
Me.picboxDeleteAll = New System.Windows.Forms.PictureBox
Me.picboxDelete = New System.Windows.Forms.PictureBox
Me.PictureBox1 = New System.Windows.Forms.PictureBox
Me.ToolTip1 = New System.Windows.Forms.ToolTip(Me.components)
Me.GroupBox1.SuspendLayout()
Me.GroupBox3.SuspendLayout()
CType(Me.picboxDeleteAll, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.picboxDelete, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.PictureBox1, System.ComponentModel.ISupportInitialize).BeginInit()
Me.SuspendLayout()
'
'LBLNama
'
Me.LBLNama.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
Me.LBLNama.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.LBLNama.Location = New System.Drawing.Point(94, 34)
Me.LBLNama.Name = "LBLNama"
Me.LBLNama.Size = New System.Drawing.Size(133, 23)
Me.LBLNama.TabIndex = 5
Me.ToolTip1.SetToolTip(Me.LBLNama, "Nama File")
'
'ListView1
'
Me.ListView1.Columns.AddRange(New System.Windows.Forms.ColumnHeader() {Me.FileName, Me.Lokasi})
Me.ListView1.Dock = System.Windows.Forms.DockStyle.Bottom
Me.ListView1.Location = New System.Drawing.Point(3, 19)
Me.ListView1.Name = "ListView1"
Me.ListView1.Size = New System.Drawing.Size(230, 151)
Me.ListView1.TabIndex = 0
Me.ListView1.UseCompatibleStateImageBehavior = False
Me.ListView1.View = System.Windows.Forms.View.Details
'
'FileName
'
Me.FileName.Text = "Nama File"
'
'Lokasi
'
Me.Lokasi.Text = "Lokasi"
'
'BTNScan
'
Me.BTNScan.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.BTNScan.Location = New System.Drawing.Point(65, 74)
Me.BTNScan.Name = "BTNScan"
Me.BTNScan.Size = New System.Drawing.Size(122, 43)
Me.BTNScan.TabIndex = 6
Me.BTNScan.Text = "Scan"
Me.ToolTip1.SetToolTip(Me.BTNScan, "Scan")
Me.BTNScan.UseVisualStyleBackColor = True
'
'GroupBox1
'
Me.GroupBox1.Controls.Add(Me.BTNScan)
Me.GroupBox1.Controls.Add(Me.BTNHapus)
Me.GroupBox1.Controls.Add(Me.LBLNama)
Me.GroupBox1.Controls.Add(Me.BTNSImpan)
Me.GroupBox1.Controls.Add(Me.Label1)
Me.GroupBox1.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.GroupBox1.Location = New System.Drawing.Point(347, 11)
Me.GroupBox1.Name = "GroupBox1"
Me.GroupBox1.Size = New System.Drawing.Size(236, 184)
Me.GroupBox1.TabIndex = 169
Me.GroupBox1.TabStop = False
Me.GroupBox1.Text = "Scanning"
'
'BTNHapus
'
Me.BTNHapus.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.BTNHapus.Location = New System.Drawing.Point(128, 136)
Me.BTNHapus.Name = "BTNHapus"
Me.BTNHapus.Size = New System.Drawing.Size(99, 31)
Me.BTNHapus.TabIndex = 7
Me.BTNHapus.Text = "Hapus"
Me.ToolTip1.SetToolTip(Me.BTNHapus, "Hapus Hasil Scan")
Me.BTNHapus.UseVisualStyleBackColor = True
'
'BTNSImpan
'
Me.BTNSImpan.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.BTNSImpan.Location = New System.Drawing.Point(21, 136)
Me.BTNSImpan.Name = "BTNSImpan"
Me.BTNSImpan.Size = New System.Drawing.Size(93, 31)
Me.BTNSImpan.TabIndex = 6
Me.BTNSImpan.Text = "Simpan"
Me.ToolTip1.SetToolTip(Me.BTNSImpan, "Simpan Hasil Scan")
Me.BTNSImpan.UseVisualStyleBackColor = True
'
'Label1
'
Me.Label1.AutoSize = True
Me.Label1.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label1.Location = New System.Drawing.Point(18, 38)
Me.Label1.Name = "Label1"
Me.Label1.Size = New System.Drawing.Size(70, 16)
Me.Label1.TabIndex = 4
Me.Label1.Text = "Nama File"
'
'_twain32
'
Me._twain32.AppProductName = "Saraff.Twain"
Me._twain32.Parent = Nothing
'
'Label12
'
Me.Label12.AutoSize = True
Me.Label12.BackColor = System.Drawing.Color.WhiteSmoke
Me.Label12.Font = New System.Drawing.Font("Segoe UI", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label12.Location = New System.Drawing.Point(363, 387)
Me.Label12.Margin = New System.Windows.Forms.Padding(4, 0, 4, 0)
Me.Label12.Name = "Label12"
Me.Label12.Size = New System.Drawing.Size(106, 15)
Me.Label12.TabIndex = 171
Me.Label12.Text = "Delete && Delete All"
'
'Label23
'
Me.Label23.AutoSize = True
Me.Label23.Location = New System.Drawing.Point(472, 198)
Me.Label23.Name = "Label23"
Me.Label23.Size = New System.Drawing.Size(45, 13)
Me.Label23.TabIndex = 174
Me.Label23.Text = "Label23"
Me.Label23.Visible = False
'
'GroupBox3
'
Me.GroupBox3.Controls.Add(Me.ListView1)
Me.GroupBox3.Location = New System.Drawing.Point(347, 211)
Me.GroupBox3.Name = "GroupBox3"
Me.GroupBox3.Size = New System.Drawing.Size(236, 173)
Me.GroupBox3.TabIndex = 170
Me.GroupBox3.TabStop = False
Me.GroupBox3.Text = "Daftar Gambar"
'
'BTNTutup
'
Me.BTNTutup.DialogResult = System.Windows.Forms.DialogResult.Cancel
Me.BTNTutup.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.BTNTutup.Location = New System.Drawing.Point(489, 405)
Me.BTNTutup.Name = "BTNTutup"
Me.BTNTutup.Size = New System.Drawing.Size(91, 34)
Me.BTNTutup.TabIndex = 168
Me.BTNTutup.Text = "Selesai"
Me.ToolTip1.SetToolTip(Me.BTNTutup, "Selesai")
Me.BTNTutup.UseVisualStyleBackColor = True
'
'picboxDeleteAll
'
Me.picboxDeleteAll.Image = Global.SIMARSIP.My.Resources.Resources.picboxDeleteAll_Leave
Me.picboxDeleteAll.Location = New System.Drawing.Point(412, 405)
Me.picboxDeleteAll.Name = "picboxDeleteAll"
Me.picboxDeleteAll.Size = New System.Drawing.Size(61, 36)
Me.picboxDeleteAll.TabIndex = 173
Me.picboxDeleteAll.TabStop = False
Me.picboxDeleteAll.Tag = "Delete All"
Me.ToolTip1.SetToolTip(Me.picboxDeleteAll, "Hapus Semua")
'
'picboxDelete
'
Me.picboxDelete.Image = Global.SIMARSIP.My.Resources.Resources.picboxDelete_Leave
Me.picboxDelete.Location = New System.Drawing.Point(353, 405)
Me.picboxDelete.Name = "picboxDelete"
Me.picboxDelete.Size = New System.Drawing.Size(60, 36)
Me.picboxDelete.TabIndex = 172
Me.picboxDelete.TabStop = False
Me.picboxDelete.Tag = "Delete Current Image"
Me.ToolTip1.SetToolTip(Me.picboxDelete, "Hapus")
'
'PictureBox1
'
Me.PictureBox1.BackColor = System.Drawing.SystemColors.ControlDark
Me.PictureBox1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
Me.PictureBox1.ImageLocation = ""
Me.PictureBox1.Location = New System.Drawing.Point(13, 13)
Me.PictureBox1.Name = "PictureBox1"
Me.PictureBox1.Size = New System.Drawing.Size(316, 429)
Me.PictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom
Me.PictureBox1.TabIndex = 167
Me.PictureBox1.TabStop = False
'
'Scanning_keluar_Edit
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink
Me.CancelButton = Me.BTNTutup
Me.ClientSize = New System.Drawing.Size(596, 452)
Me.ControlBox = False
Me.Controls.Add(Me.picboxDeleteAll)
Me.Controls.Add(Me.picboxDelete)
Me.Controls.Add(Me.PictureBox1)
Me.Controls.Add(Me.GroupBox1)
Me.Controls.Add(Me.Label12)
Me.Controls.Add(Me.Label23)
Me.Controls.Add(Me.GroupBox3)
Me.Controls.Add(Me.BTNTutup)
Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon)
Me.Name = "Scanning_keluar_Edit"
Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
Me.Text = "Scanning"
Me.GroupBox1.ResumeLayout(False)
Me.GroupBox1.PerformLayout()
Me.GroupBox3.ResumeLayout(False)
CType(Me.picboxDeleteAll, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.picboxDelete, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.PictureBox1, System.ComponentModel.ISupportInitialize).EndInit()
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Friend WithEvents LBLNama As System.Windows.Forms.Label
Private WithEvents picboxDeleteAll As System.Windows.Forms.PictureBox
Private WithEvents picboxDelete As System.Windows.Forms.PictureBox
Friend WithEvents PictureBox1 As System.Windows.Forms.PictureBox
Friend WithEvents ListView1 As System.Windows.Forms.ListView
Friend WithEvents FileName As System.Windows.Forms.ColumnHeader
Friend WithEvents Lokasi As System.Windows.Forms.ColumnHeader
Friend WithEvents BTNScan As System.Windows.Forms.Button
Friend WithEvents GroupBox1 As System.Windows.Forms.GroupBox
Friend WithEvents BTNHapus As System.Windows.Forms.Button
Friend WithEvents BTNSImpan As System.Windows.Forms.Button
Friend WithEvents Label1 As System.Windows.Forms.Label
Friend WithEvents _twain32 As Saraff.Twain.Twain32
Private WithEvents Label12 As System.Windows.Forms.Label
Friend WithEvents Label23 As System.Windows.Forms.Label
Friend WithEvents GroupBox3 As System.Windows.Forms.GroupBox
Friend WithEvents BTNTutup As System.Windows.Forms.Button
Friend WithEvents ToolTip1 As System.Windows.Forms.ToolTip
End Class
|
anakpantai/busus
|
SIMARSIP/Arsip Keluar/Scanning Keluar Edit.Designer.vb
|
Visual Basic
|
apache-2.0
| 12,990
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Form1
Inherits System.Windows.Forms.Form
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.Button1 = New System.Windows.Forms.Button()
Me.DataGridView1 = New System.Windows.Forms.DataGridView()
Me.Table1TableAdapter1 = New WindowsApplication1.Database1DataSetTableAdapters.Table1TableAdapter()
CType(Me.DataGridView1, System.ComponentModel.ISupportInitialize).BeginInit()
Me.SuspendLayout()
'
'Button1
'
Me.Button1.Location = New System.Drawing.Point(52, 218)
Me.Button1.Name = "Button1"
Me.Button1.Size = New System.Drawing.Size(75, 23)
Me.Button1.TabIndex = 1
Me.Button1.Text = "Button1"
Me.Button1.UseVisualStyleBackColor = True
'
'DataGridView1
'
Me.DataGridView1.AllowUserToOrderColumns = True
Me.DataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize
Me.DataGridView1.Location = New System.Drawing.Point(52, 25)
Me.DataGridView1.Name = "DataGridView1"
Me.DataGridView1.Size = New System.Drawing.Size(417, 162)
Me.DataGridView1.TabIndex = 2
'
'Table1TableAdapter1
'
Me.Table1TableAdapter1.ClearBeforeFill = True
'
'Form1
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(522, 344)
Me.Controls.Add(Me.DataGridView1)
Me.Controls.Add(Me.Button1)
Me.Name = "Form1"
Me.Text = "Form1"
CType(Me.DataGridView1, System.ComponentModel.ISupportInitialize).EndInit()
Me.ResumeLayout(False)
End Sub
Friend WithEvents Button1 As System.Windows.Forms.Button
Friend WithEvents DataGridView1 As System.Windows.Forms.DataGridView
Friend WithEvents Table1TableAdapter1 As WindowsApplication1.Database1DataSetTableAdapters.Table1TableAdapter
End Class
|
Joeordie/POS408Team
|
ContactManager/WindowsApplication1/Form1.Designer.vb
|
Visual Basic
|
bsd-2-clause
| 2,842
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.Rename.ConflictEngine
Imports Microsoft.CodeAnalysis.Simplification
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Simplification
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions
Friend Module ExpressionSyntaxExtensions
Public ReadOnly typeNameFormatWithGenerics As New SymbolDisplayFormat(
globalNamespaceStyle:=SymbolDisplayGlobalNamespaceStyle.Included,
genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters,
memberOptions:=SymbolDisplayMemberOptions.IncludeContainingType,
localOptions:=SymbolDisplayLocalOptions.IncludeType,
miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers,
typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces)
Public ReadOnly typeNameFormatWithoutGenerics As New SymbolDisplayFormat(
globalNamespaceStyle:=SymbolDisplayGlobalNamespaceStyle.Included,
genericsOptions:=SymbolDisplayGenericsOptions.None,
memberOptions:=SymbolDisplayMemberOptions.IncludeContainingType,
localOptions:=SymbolDisplayLocalOptions.IncludeType,
miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers,
typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces)
<Extension()>
Public Function WalkUpParentheses(expression As ExpressionSyntax) As ExpressionSyntax
While expression.IsParentKind(SyntaxKind.ParenthesizedExpression)
expression = DirectCast(expression.Parent, ExpressionSyntax)
End While
Return expression
End Function
<Extension()>
Public Function WalkDownParentheses(expression As ExpressionSyntax) As ExpressionSyntax
While expression.IsKind(SyntaxKind.ParenthesizedExpression)
expression = DirectCast(expression, ParenthesizedExpressionSyntax).Expression
End While
Return expression
End Function
<Extension()>
Public Function Parenthesize(expression As ExpressionSyntax) As ParenthesizedExpressionSyntax
Dim leadingTrivia = expression.GetLeadingTrivia()
Dim trailingTrivia = expression.GetTrailingTrivia()
Dim strippedExpression = expression.WithoutLeadingTrivia().WithoutTrailingTrivia()
Return SyntaxFactory.ParenthesizedExpression(strippedExpression) _
.WithLeadingTrivia(leadingTrivia) _
.WithTrailingTrivia(trailingTrivia) _
.WithAdditionalAnnotations(Simplifier.Annotation)
End Function
<Extension()>
Public Function IsAliasReplaceableExpression(expression As ExpressionSyntax) As Boolean
If expression.Kind = SyntaxKind.IdentifierName OrElse
expression.Kind = SyntaxKind.QualifiedName Then
Return True
End If
If expression.Kind = SyntaxKind.SimpleMemberAccessExpression Then
Dim memberAccess = DirectCast(expression, MemberAccessExpressionSyntax)
Return memberAccess.Expression IsNot Nothing AndAlso memberAccess.Expression.IsAliasReplaceableExpression()
End If
Return False
End Function
<Extension()>
Public Function IsMemberAccessExpressionName(expression As ExpressionSyntax) As Boolean
Return expression.IsParentKind(SyntaxKind.SimpleMemberAccessExpression) AndAlso
DirectCast(expression.Parent, MemberAccessExpressionSyntax).Name Is expression
End Function
<Extension()>
Public Function IsAnyMemberAccessExpressionName(expression As ExpressionSyntax) As Boolean
Return expression IsNot Nothing AndAlso
TypeOf expression.Parent Is MemberAccessExpressionSyntax AndAlso
DirectCast(expression.Parent, MemberAccessExpressionSyntax).Name Is expression
End Function
<Extension()>
Public Function IsRightSideOfDotOrBang(expression As ExpressionSyntax) As Boolean
Return expression.IsAnyMemberAccessExpressionName() OrElse expression.IsRightSideOfQualifiedName()
End Function
<Extension()>
Public Function IsRightSideOfDot(expression As ExpressionSyntax) As Boolean
Return expression.IsMemberAccessExpressionName() OrElse expression.IsRightSideOfQualifiedName()
End Function
<Extension()>
Public Function IsRightSideOfQualifiedName(expression As ExpressionSyntax) As Boolean
Return expression.IsParentKind(SyntaxKind.QualifiedName) AndAlso
DirectCast(expression.Parent, QualifiedNameSyntax).Right Is expression
End Function
<Extension()>
Public Function IsLeftSideOfQualifiedName(expression As ExpressionSyntax) As Boolean
Return expression.IsParentKind(SyntaxKind.QualifiedName) AndAlso
DirectCast(expression.Parent, QualifiedNameSyntax).Left Is expression
End Function
<Extension()>
Public Function IsAnyLiteralExpression(expression As ExpressionSyntax) As Boolean
Return expression.IsKind(SyntaxKind.CharacterLiteralExpression) OrElse
expression.IsKind(SyntaxKind.DateLiteralExpression) OrElse
expression.IsKind(SyntaxKind.FalseLiteralExpression) OrElse
expression.IsKind(SyntaxKind.NothingLiteralExpression) OrElse
expression.IsKind(SyntaxKind.NumericLiteralExpression) OrElse
expression.IsKind(SyntaxKind.StringLiteralExpression) OrElse
expression.IsKind(SyntaxKind.TrueLiteralExpression)
End Function
''' <summary>
''' Decompose a name or member access expression into its component parts.
''' </summary>
''' <param name="expression">The name or member access expression.</param>
''' <param name="qualifier">The qualifier (or left-hand-side) of the name expression. This may be null if there is no qualifier.</param>
''' <param name="name">The name of the expression.</param>
''' <param name="arity">The number of generic type parameters.</param>
<Extension()>
Public Sub DecomposeName(expression As ExpressionSyntax, ByRef qualifier As ExpressionSyntax, ByRef name As String, ByRef arity As Integer)
Select Case expression.Kind
Case SyntaxKind.SimpleMemberAccessExpression
Dim memberAccess = DirectCast(expression, MemberAccessExpressionSyntax)
qualifier = memberAccess.Expression
name = memberAccess.Name.Identifier.ValueText
arity = memberAccess.Name.Arity
Case SyntaxKind.QualifiedName
Dim qualifiedName = DirectCast(expression, QualifiedNameSyntax)
qualifier = qualifiedName.Left
name = qualifiedName.Right.Identifier.ValueText
arity = qualifiedName.Arity
Case SyntaxKind.GenericName
Dim genericName = DirectCast(expression, GenericNameSyntax)
qualifier = Nothing
name = genericName.Identifier.ValueText
arity = genericName.Arity
Case SyntaxKind.IdentifierName
Dim identifierName = DirectCast(expression, IdentifierNameSyntax)
qualifier = Nothing
name = identifierName.Identifier.ValueText
arity = 0
Case Else
qualifier = Nothing
name = Nothing
arity = 0
End Select
End Sub
<Extension()>
Public Function TryGetNameParts(expression As ExpressionSyntax, ByRef parts As IList(Of String)) As Boolean
Dim partsList = New List(Of String)
If Not expression.TryGetNameParts(partsList) Then
parts = Nothing
Return False
End If
parts = partsList
Return True
End Function
<Extension()>
Public Function TryGetNameParts(expression As ExpressionSyntax, parts As List(Of String)) As Boolean
If expression.IsKind(SyntaxKind.SimpleMemberAccessExpression) Then
Dim memberAccess = DirectCast(expression, MemberAccessExpressionSyntax)
If Not memberAccess.Name.TryGetNameParts(parts) Then
Return False
End If
Return AddSimpleName(memberAccess.Name, parts)
ElseIf expression.IsKind(SyntaxKind.QualifiedName) Then
Dim qualifiedName = DirectCast(expression, QualifiedNameSyntax)
If Not qualifiedName.Left.TryGetNameParts(parts) Then
Return False
End If
Return AddSimpleName(qualifiedName.Right, parts)
ElseIf TypeOf expression Is SimpleNameSyntax Then
Return AddSimpleName(DirectCast(expression, SimpleNameSyntax), parts)
Else
Return False
End If
End Function
Private Function AddSimpleName(simpleName As SimpleNameSyntax, parts As List(Of String)) As Boolean
If Not simpleName.IsKind(SyntaxKind.IdentifierName) Then
Return False
End If
parts.Add(simpleName.Identifier.ValueText)
Return True
End Function
<Extension()>
Public Function IsLeftSideOfDot(expression As ExpressionSyntax) As Boolean
Return _
(expression.IsParentKind(SyntaxKind.QualifiedName) AndAlso DirectCast(expression.Parent, QualifiedNameSyntax).Left Is expression) OrElse
(expression.IsParentKind(SyntaxKind.SimpleMemberAccessExpression) AndAlso DirectCast(expression.Parent, MemberAccessExpressionSyntax).Expression Is expression)
End Function
<Extension()>
Public Function Cast(
expression As ExpressionSyntax,
targetType As ITypeSymbol,
<Out> ByRef isResultPredefinedCast As Boolean) As ExpressionSyntax
' Parenthesize the expression, except for collection initializer where parenthesizing changes the semantics.
Dim parenthesized = If(expression.Kind = SyntaxKind.CollectionInitializer,
expression,
expression.Parenthesize())
Dim leadingTrivia = parenthesized.GetLeadingTrivia()
Dim trailingTrivia = parenthesized.GetTrailingTrivia()
Dim stripped = parenthesized.WithoutLeadingTrivia().WithoutTrailingTrivia()
Dim castKeyword = targetType.SpecialType.GetPredefinedCastKeyword()
If castKeyword = SyntaxKind.None Then
isResultPredefinedCast = False
Return SyntaxFactory.CTypeExpression(
expression:=stripped,
type:=targetType.GenerateTypeSyntax()) _
.WithLeadingTrivia(leadingTrivia) _
.WithTrailingTrivia(trailingTrivia) _
.WithAdditionalAnnotations(Simplifier.Annotation)
Else
isResultPredefinedCast = True
Return SyntaxFactory.PredefinedCastExpression(
keyword:=SyntaxFactory.Token(castKeyword),
expression:=stripped) _
.WithLeadingTrivia(leadingTrivia) _
.WithTrailingTrivia(trailingTrivia) _
.WithAdditionalAnnotations(Simplifier.Annotation)
End If
End Function
<Extension()>
Public Function CastIfPossible(
expression As ExpressionSyntax,
targetType As ITypeSymbol,
position As Integer,
semanticModel As SemanticModel,
<Out> ByRef wasCastAdded As Boolean
) As ExpressionSyntax
wasCastAdded = False
If targetType.ContainsAnonymousType() OrElse expression.IsParentKind(SyntaxKind.AsNewClause) Then
Return expression
End If
Dim typeSyntax = targetType.GenerateTypeSyntax()
Dim type = semanticModel.GetSpeculativeTypeInfo(
position,
typeSyntax,
SpeculativeBindingOption.BindAsTypeOrNamespace).Type
If Not targetType.Equals(type) Then
Return expression
End If
Dim isResultPredefinedCast As Boolean = False
Dim castExpression = expression.Cast(targetType, isResultPredefinedCast)
' Ensure that inserting the cast doesn't change the semantics.
Dim specAnalyzer = New SpeculationAnalyzer(expression, castExpression, semanticModel, CancellationToken.None)
Dim speculativeSemanticModel = specAnalyzer.SpeculativeSemanticModel
If speculativeSemanticModel Is Nothing Then
Return expression
End If
Dim speculatedCastExpression = specAnalyzer.ReplacedExpression
Dim speculatedCastInnerExpression = If(isResultPredefinedCast,
DirectCast(speculatedCastExpression, PredefinedCastExpressionSyntax).Expression,
DirectCast(speculatedCastExpression, CastExpressionSyntax).Expression)
If Not CastAnalyzer.IsUnnecessary(speculatedCastExpression, speculatedCastInnerExpression, speculativeSemanticModel, True, CancellationToken.None) Then
Return expression
End If
wasCastAdded = True
Return castExpression
End Function
<Extension()>
Public Function IsNewOnRightSideOfDotOrBang(expression As ExpressionSyntax) As Boolean
Dim identifierName = TryCast(expression, IdentifierNameSyntax)
If identifierName Is Nothing Then
Return False
End If
If String.Compare(identifierName.Identifier.ToString(), "New", StringComparison.OrdinalIgnoreCase) <> 0 Then
Return False
End If
Return identifierName.IsRightSideOfDotOrBang()
End Function
<Extension()>
Public Function IsObjectCreationWithoutArgumentList(expression As ExpressionSyntax) As Boolean
Return _
TypeOf expression Is ObjectCreationExpressionSyntax AndAlso
DirectCast(expression, ObjectCreationExpressionSyntax).ArgumentList Is Nothing
End Function
<Extension()>
Public Function IsInOutContext(expression As ExpressionSyntax, semanticModel As SemanticModel, cancellationToken As CancellationToken) As Boolean
' NOTE(cyrusn): VB has no concept of an out context. Even when a parameter has an
' '<Out>' attribute on it, it's still treated as ref by VB. So we always return false
' here.
Return False
End Function
<Extension()>
Public Function IsInRefContext(expression As ExpressionSyntax, semanticModel As SemanticModel, cancellationToken As CancellationToken) As Boolean
Dim simpleArgument = TryCast(expression.Parent, SimpleArgumentSyntax)
If simpleArgument Is Nothing Then
Return False
ElseIf simpleArgument.IsNamed Then
Dim info = semanticModel.GetSymbolInfo(simpleArgument.NameColonEquals.Name, cancellationToken)
Dim parameter = TryCast(info.GetAnySymbol(), IParameterSymbol)
Return parameter IsNot Nothing AndAlso parameter.RefKind <> RefKind.None
Else
Dim argumentList = TryCast(simpleArgument.Parent, ArgumentListSyntax)
If argumentList IsNot Nothing Then
Dim parent = argumentList.Parent
Dim index = argumentList.Arguments.IndexOf(simpleArgument)
Dim info = semanticModel.GetSymbolInfo(parent, cancellationToken)
Dim symbol = info.GetAnySymbol()
If TypeOf symbol Is IMethodSymbol Then
Dim method = DirectCast(symbol, IMethodSymbol)
If index < method.Parameters.Length Then
Return method.Parameters(index).RefKind <> RefKind.None
End If
ElseIf TypeOf symbol Is IPropertySymbol Then
Dim prop = DirectCast(symbol, IPropertySymbol)
If index < prop.Parameters.Length Then
Return prop.Parameters(index).RefKind <> RefKind.None
End If
End If
End If
End If
Return False
End Function
<Extension()>
Public Function IsOnlyWrittenTo(expression As ExpressionSyntax, semanticModel As SemanticModel, cancellationToken As CancellationToken) As Boolean
If expression.IsRightSideOfDot() Then
expression = TryCast(expression.Parent, ExpressionSyntax)
End If
If expression IsNot Nothing Then
If expression.IsInOutContext(semanticModel, cancellationToken) Then
Return True
End If
If expression.IsParentKind(SyntaxKind.SimpleAssignmentStatement) Then
Dim assignmentStatement = DirectCast(expression.Parent, AssignmentStatementSyntax)
If expression Is assignmentStatement.Left Then
Return True
End If
End If
If expression.IsChildNode(Of NamedFieldInitializerSyntax)(Function(n) n.Name) Then
Return True
End If
Return False
End If
Return False
End Function
<Extension()>
Public Function IsWrittenTo(expression As ExpressionSyntax, semanticModel As SemanticModel, cancellationToken As CancellationToken) As Boolean
If IsOnlyWrittenTo(expression, semanticModel, cancellationToken) Then
Return True
End If
If expression.IsRightSideOfDot() Then
expression = TryCast(expression.Parent, ExpressionSyntax)
End If
If expression IsNot Nothing Then
If expression.IsInRefContext(semanticModel, cancellationToken) Then
Return True
End If
If TypeOf expression.Parent Is AssignmentStatementSyntax Then
Dim assignmentStatement = DirectCast(expression.Parent, AssignmentStatementSyntax)
If expression Is assignmentStatement.Left Then
Return True
End If
End If
If expression.IsChildNode(Of NamedFieldInitializerSyntax)(Function(n) n.Name) Then
Return True
End If
Return False
End If
Return False
End Function
<Extension()>
Public Function IsMeMyBaseOrMyClass(expression As ExpressionSyntax) As Boolean
If expression Is Nothing Then
Return False
End If
Return expression.Kind = SyntaxKind.MeExpression OrElse
expression.Kind = SyntaxKind.MyBaseExpression OrElse
expression.Kind = SyntaxKind.MyClassExpression
End Function
<Extension()>
Public Function IsFirstStatementInCtor(expression As ExpressionSyntax) As Boolean
Dim statement = expression.FirstAncestorOrSelf(Of StatementSyntax)()
If statement Is Nothing Then
Return False
End If
If Not statement.IsParentKind(SyntaxKind.ConstructorBlock) Then
Return False
End If
Return DirectCast(statement.Parent, ConstructorBlockSyntax).Statements(0) Is statement
End Function
<Extension()>
Public Function IsNamedArgumentIdentifier(expression As ExpressionSyntax) As Boolean
Dim simpleArgument = TryCast(expression.Parent, SimpleArgumentSyntax)
Return simpleArgument IsNot Nothing AndAlso simpleArgument.NameColonEquals.Name Is expression
End Function
Private Function IsUnnecessaryCast(
castNode As ExpressionSyntax,
castExpressionNode As ExpressionSyntax,
semanticModel As SemanticModel,
assumeCallKeyword As Boolean,
cancellationToken As CancellationToken
) As Boolean
Return CastAnalyzer.IsUnnecessary(castNode, castExpressionNode, semanticModel, assumeCallKeyword, cancellationToken)
End Function
<Extension>
Public Function IsUnnecessaryCast(
node As CastExpressionSyntax,
semanticModel As SemanticModel,
cancellationToken As CancellationToken,
Optional assumeCallKeyword As Boolean = False
) As Boolean
Return IsUnnecessaryCast(node, node.Expression, semanticModel, assumeCallKeyword, cancellationToken)
End Function
<Extension>
Public Function IsUnnecessaryCast(
node As PredefinedCastExpressionSyntax,
semanticModel As SemanticModel,
cancellationToken As CancellationToken,
Optional assumeCallKeyword As Boolean = False
) As Boolean
Return IsUnnecessaryCast(node, node.Expression, semanticModel, assumeCallKeyword, cancellationToken)
End Function
Private Function CanReplace(symbol As ISymbol) As Boolean
Select Case symbol.Kind
Case SymbolKind.Field,
SymbolKind.Local,
SymbolKind.Method,
SymbolKind.Parameter,
SymbolKind.Property,
SymbolKind.RangeVariable
Return True
End Select
Return False
End Function
<Extension>
Public Function CanReplaceWithRValue(expression As ExpressionSyntax, semanticModel As SemanticModel, cancellationToken As CancellationToken) As Boolean
Return expression IsNot Nothing AndAlso
Not expression.IsWrittenTo(semanticModel, cancellationToken) AndAlso
expression.CanReplaceWithLValue(semanticModel, cancellationToken)
End Function
<Extension>
Public Function CanReplaceWithLValue(expression As ExpressionSyntax, semanticModel As SemanticModel, cancellationToken As CancellationToken) As Boolean
#If False Then
' Things that are definitely illegal to replace
If ContainsImplicitMemberAccess(expression) Then
Return False
End If
#End If
If expression.IsKind(SyntaxKind.MyBaseExpression) OrElse
expression.IsKind(SyntaxKind.MyClassExpression) Then
Return False
End If
If Not (TypeOf expression Is ObjectCreationExpressionSyntax) AndAlso
Not (TypeOf expression Is AnonymousObjectCreationExpressionSyntax) Then
Dim symbolInfo = semanticModel.GetSymbolInfo(expression, cancellationToken)
If Not symbolInfo.GetBestOrAllSymbols().All(AddressOf CanReplace) Then
' If the expression is actually a reference to a type, then it can't be replaced
' with an arbitrary expression.
Return False
End If
End If
' Technically, you could introduce an LValue for "Foo" in "Foo()" even if "Foo" binds
' to a method. (i.e. by assigning to a Func<...> type). However, this is so contrived
' and none of the features that use this extension consider this replacable.
If TypeOf expression.Parent Is InvocationExpressionSyntax Then
' If someting is being invoked, then it's either something like Foo(), Foo.Bar(), or
' SomeExpr() (i.e. Blah[1]()). In the first and second case, we only allow
' replacement if Foo and Foo.Bar didn't bind to a method. If we can't bind it, we'll
' assume it's a method and we don't allow it to be replaced either. However, if it's
' an arbitrary expression, we do allow replacement.
If expression.IsKind(SyntaxKind.IdentifierName) OrElse expression.IsKind(SyntaxKind.SimpleMemberAccessExpression) Then
Dim symbolInfo = semanticModel.GetSymbolInfo(expression, cancellationToken)
If Not symbolInfo.GetBestOrAllSymbols().Any() Then
Return False
End If
' don't allow it to be replaced if it is bound to an indexed property
Return Not symbolInfo.GetBestOrAllSymbols().OfType(Of IMethodSymbol)().Any() AndAlso
Not symbolInfo.GetBestOrAllSymbols().OfType(Of IPropertySymbol)().Any()
Else
Return True
End If
End If
' expression in next statement's control variables should match one in the head
Dim nextStatement = expression.FirstAncestorOrSelf(Of NextStatementSyntax)()
If nextStatement IsNot Nothing Then
Return False
End If
' Direct parent kind checks.
If expression.IsParentKind(SyntaxKind.EqualsValue) OrElse
expression.IsParentKind(SyntaxKind.ParenthesizedExpression) OrElse
expression.IsParentKind(SyntaxKind.SelectStatement) OrElse
expression.IsParentKind(SyntaxKind.SyncLockStatement) OrElse
expression.IsParentKind(SyntaxKind.CollectionInitializer) OrElse
expression.IsParentKind(SyntaxKind.InferredFieldInitializer) OrElse
expression.IsParentKind(SyntaxKind.BinaryConditionalExpression) OrElse
expression.IsParentKind(SyntaxKind.TernaryConditionalExpression) OrElse
expression.IsParentKind(SyntaxKind.ReturnStatement) OrElse
expression.IsParentKind(SyntaxKind.YieldStatement) OrElse
expression.IsParentKind(SyntaxKind.XmlEmbeddedExpression) OrElse
expression.IsParentKind(SyntaxKind.ThrowStatement) OrElse
expression.IsParentKind(SyntaxKind.IfStatement) OrElse
expression.IsParentKind(SyntaxKind.WhileStatement) OrElse
expression.IsParentKind(SyntaxKind.ElseIfStatement) OrElse
expression.IsParentKind(SyntaxKind.ForEachStatement) OrElse
expression.IsParentKind(SyntaxKind.ForStatement) OrElse
expression.IsParentKind(SyntaxKind.ConditionalAccessExpression) OrElse
expression.IsParentKind(SyntaxKind.TypeOfIsExpression) Then
Return True
End If
' Parent type checks
If TypeOf expression.Parent Is BinaryExpressionSyntax OrElse
TypeOf expression.Parent Is AssignmentStatementSyntax OrElse
TypeOf expression.Parent Is WhileOrUntilClauseSyntax OrElse
TypeOf expression.Parent Is SingleLineLambdaExpressionSyntax OrElse
TypeOf expression.Parent Is AwaitExpressionSyntax Then
Return True
End If
' Specific child checks.
If expression.CheckParent(Of NamedFieldInitializerSyntax)(Function(n) n.Expression Is expression) OrElse
expression.CheckParent(Of MemberAccessExpressionSyntax)(Function(m) m.Expression Is expression) OrElse
expression.CheckParent(Of TryCastExpressionSyntax)(Function(t) t.Expression Is expression) OrElse
expression.CheckParent(Of CatchFilterClauseSyntax)(Function(c) c.Filter Is expression) OrElse
expression.CheckParent(Of SimpleArgumentSyntax)(Function(n) n.Expression Is expression) OrElse
expression.CheckParent(Of DirectCastExpressionSyntax)(Function(d) d.Expression Is expression) OrElse
expression.CheckParent(Of FunctionAggregationSyntax)(Function(f) f.Argument Is expression) OrElse
expression.CheckParent(Of RangeArgumentSyntax)(Function(r) r.UpperBound Is expression) Then
Return True
End If
' Misc checks
If TypeOf expression.Parent Is ExpressionRangeVariableSyntax AndAlso
TypeOf expression.Parent.Parent Is QueryClauseSyntax Then
Dim rangeVariable = DirectCast(expression.Parent, ExpressionRangeVariableSyntax)
Dim selectClause = TryCast(rangeVariable.Parent, SelectClauseSyntax)
' Can't replace the expression in a select unless its the last select clause *or*
' it's a select of the form "select a = <expr>"
If selectClause IsNot Nothing Then
If rangeVariable.NameEquals IsNot Nothing Then
Return True
End If
Dim queryExpression = TryCast(selectClause.Parent, QueryExpressionSyntax)
If queryExpression IsNot Nothing Then
Return queryExpression.Clauses.Last() Is selectClause
End If
Dim aggregateClause = TryCast(selectClause.Parent, AggregateClauseSyntax)
If aggregateClause IsNot Nothing Then
Return aggregateClause.AdditionalQueryOperators().Last() Is selectClause
End If
Return False
End If
' Any other query type is ok. Note(cyrusn): This may be too broad.
Return True
End If
Return False
End Function
<Extension>
Public Function ContainsImplicitMemberAccess(expression As ExpressionSyntax) As Boolean
Return ContainsImplicitMemberAccessWorker(expression)
End Function
<Extension>
Public Function ContainsImplicitMemberAccess(statement As StatementSyntax) As Boolean
Return ContainsImplicitMemberAccessWorker(statement)
End Function
<Extension>
Public Function GetImplicitMemberAccessExpressions(expression As SyntaxNode, span As TextSpan) As IEnumerable(Of ExpressionSyntax)
' We don't want to allow a variable to be introduced if the expression contains an
' implicit member access. i.e. ".Blah.ToString()" as that .Blah refers to the containing
' object creation or anonymous type and we can't make a local for it. So we get all the
' descendents and we suppress ourselves.
' Note: if we hit a with block or an anonymous type, then we do not look deeper. Any
' implicit member accesses will refer to that thing and we *can* introduce a variable
Dim descendentExpressions = expression.DescendantNodesAndSelf().OfType(Of ExpressionSyntax).Where(Function(e) span.Contains(e.Span)).ToSet()
Return descendentExpressions.OfType(Of MemberAccessExpressionSyntax).
Select(Function(m) m.GetExpressionOfMemberAccessExpression()).
Where(Function(e) Not descendentExpressions.Contains(e))
End Function
<Extension>
Public Function GetImplicitMemberAccessExpressions(expression As SyntaxNode) As IEnumerable(Of ExpressionSyntax)
Return GetImplicitMemberAccessExpressions(expression, expression.FullSpan)
End Function
Private Function ContainsImplicitMemberAccessWorker(expression As SyntaxNode) As Boolean
Return GetImplicitMemberAccessExpressions(expression).Any()
End Function
<Extension>
Public Function GetOperatorPrecedence(expression As ExpressionSyntax) As OperatorPrecedence
Select Case expression.Kind
Case SyntaxKind.ExponentiateExpression
Return OperatorPrecedence.PrecedenceExponentiate
Case SyntaxKind.UnaryMinusExpression,
SyntaxKind.UnaryPlusExpression
Return OperatorPrecedence.PrecedenceNegate
Case SyntaxKind.MultiplyExpression,
SyntaxKind.DivideExpression
Return OperatorPrecedence.PrecedenceMultiply
Case SyntaxKind.IntegerDivideExpression
Return OperatorPrecedence.PrecedenceIntegerDivide
Case SyntaxKind.ModuloExpression
Return OperatorPrecedence.PrecedenceModulus
Case SyntaxKind.AddExpression,
SyntaxKind.SubtractExpression
Return OperatorPrecedence.PrecedenceAdd
Case SyntaxKind.ConcatenateExpression
Return OperatorPrecedence.PrecedenceConcatenate
Case SyntaxKind.LeftShiftExpression,
SyntaxKind.RightShiftExpression
Return OperatorPrecedence.PrecedenceShift
Case SyntaxKind.EqualsExpression,
SyntaxKind.NotEqualsExpression,
SyntaxKind.LessThanExpression,
SyntaxKind.GreaterThanExpression,
SyntaxKind.LessThanOrEqualExpression,
SyntaxKind.GreaterThanOrEqualExpression,
SyntaxKind.LikeExpression,
SyntaxKind.IsExpression,
SyntaxKind.IsNotExpression
Return OperatorPrecedence.PrecedenceRelational
Case SyntaxKind.NotExpression
Return OperatorPrecedence.PrecedenceNot
Case SyntaxKind.AndExpression,
SyntaxKind.AndAlsoExpression
Return OperatorPrecedence.PrecedenceAnd
Case SyntaxKind.OrExpression,
SyntaxKind.OrElseExpression
Return OperatorPrecedence.PrecedenceOr
Case SyntaxKind.ExclusiveOrExpression
Return OperatorPrecedence.PrecedenceXor
Case Else
Return OperatorPrecedence.PrecedenceNone
End Select
End Function
<Extension()>
Public Function DetermineType(expression As ExpressionSyntax,
semanticModel As SemanticModel,
cancellationToken As CancellationToken) As ITypeSymbol
' If a parameter appears to have a void return type, then just use 'object' instead.
If expression IsNot Nothing Then
Dim typeInfo = semanticModel.GetTypeInfo(expression, cancellationToken)
Dim symbolInfo = semanticModel.GetSymbolInfo(expression, cancellationToken)
If typeInfo.Type IsNot Nothing AndAlso typeInfo.Type.SpecialType = SpecialType.System_Void Then
Return semanticModel.Compilation.ObjectType
End If
Dim symbol = If(typeInfo.Type, symbolInfo.GetAnySymbol())
If symbol IsNot Nothing Then
Return symbol.ConvertToType(semanticModel.Compilation)
End If
If TypeOf expression Is CollectionInitializerSyntax Then
Dim collectionInitializer = DirectCast(expression, CollectionInitializerSyntax)
Return DetermineType(collectionInitializer, semanticModel, cancellationToken)
End If
End If
Return semanticModel.Compilation.ObjectType
End Function
<Extension()>
Private Function DetermineType(collectionInitializer As CollectionInitializerSyntax,
semanticModel As SemanticModel,
cancellationToken As CancellationToken) As ITypeSymbol
Dim rank = 1
While collectionInitializer.Initializers.Count > 0 AndAlso
collectionInitializer.Initializers(0).Kind = SyntaxKind.CollectionInitializer
rank += 1
collectionInitializer = DirectCast(collectionInitializer.Initializers(0), CollectionInitializerSyntax)
End While
Dim type = collectionInitializer.Initializers.FirstOrDefault().DetermineType(semanticModel, cancellationToken)
Return semanticModel.Compilation.CreateArrayTypeSymbol(type, rank)
End Function
<Extension()>
Public Function TryReduceVariableDeclaratorWithoutType(
variableDeclarator As VariableDeclaratorSyntax,
semanticModel As SemanticModel,
<Out()> ByRef replacementNode As SyntaxNode,
<Out()> ByRef issueSpan As TextSpan,
optionSet As OptionSet,
cancellationToken As CancellationToken
) As Boolean
replacementNode = Nothing
issueSpan = Nothing
' Failfast Conditions
If Not optionSet.GetOption(SimplificationOptions.PreferImplicitTypeInLocalDeclaration) OrElse
variableDeclarator.AsClause Is Nothing OrElse
Not variableDeclarator.Parent.IsKind(
SyntaxKind.LocalDeclarationStatement,
SyntaxKind.UsingStatement,
SyntaxKind.ForStatement,
SyntaxKind.ForEachStatement,
SyntaxKind.FieldDeclaration) Then
Return False
End If
If variableDeclarator.Names.Count <> 1 Then
Return False
End If
Dim parent = variableDeclarator.Parent
Dim modifiedIdentifier = variableDeclarator.Names.Single()
Dim simpleAsClause = TryCast(variableDeclarator.AsClause, SimpleAsClauseSyntax)
If simpleAsClause Is Nothing Then
Return False
End If
If (parent.IsKind(SyntaxKind.LocalDeclarationStatement, SyntaxKind.UsingStatement, SyntaxKind.FieldDeclaration) AndAlso
variableDeclarator.Initializer IsNot Nothing) Then
' Type Check
Dim declaredSymbolType As ITypeSymbol = Nothing
If Not HasValidDeclaredTypeSymbol(modifiedIdentifier, semanticModel, declaredSymbolType) Then
Return False
End If
Dim initializerType As ITypeSymbol = Nothing
If declaredSymbolType.IsArrayType() AndAlso variableDeclarator.Initializer.Value.Kind() = SyntaxKind.CollectionInitializer Then
' Get type of the array literal in context without the target type
initializerType = semanticModel.GetSpeculativeTypeInfo(variableDeclarator.Initializer.Value.SpanStart, variableDeclarator.Initializer.Value, SpeculativeBindingOption.BindAsExpression).ConvertedType
Else
initializerType = semanticModel.GetTypeInfo(variableDeclarator.Initializer.Value).Type
End If
If Not declaredSymbolType.Equals(initializerType) Then
Return False
End If
Dim newModifiedIdentifier = SyntaxFactory.ModifiedIdentifier(modifiedIdentifier.Identifier) ' LeadingTrivia is copied here
replacementNode = SyntaxFactory.VariableDeclarator(SyntaxFactory.SingletonSeparatedList(newModifiedIdentifier.WithTrailingTrivia(variableDeclarator.AsClause.GetTrailingTrivia())),
asClause:=Nothing,
initializer:=variableDeclarator.Initializer) 'TrailingTrivia is copied here
issueSpan = variableDeclarator.Span
Return True
End If
If (parent.IsKind(SyntaxKind.ForEachStatement, SyntaxKind.ForStatement)) Then
' Type Check for ForStatement
If parent.IsKind(SyntaxKind.ForStatement) Then
Dim declaredSymbolType As ITypeSymbol = Nothing
If Not HasValidDeclaredTypeSymbol(modifiedIdentifier, semanticModel, declaredSymbolType) Then
Return False
End If
Dim valueType = semanticModel.GetTypeInfo(DirectCast(parent, ForStatementSyntax).ToValue).Type
If Not valueType.Equals(declaredSymbolType) Then
Return False
End If
End If
If parent.IsKind(SyntaxKind.ForEachStatement) Then
Dim forEachStatementInfo = semanticModel.GetForEachStatementInfo(DirectCast(parent, ForEachStatementSyntax))
If Not forEachStatementInfo.ElementConversion.IsIdentity Then
Return False
End If
End If
Dim newIdentifierName = SyntaxFactory.IdentifierName(modifiedIdentifier.Identifier) ' Leading Trivia is copied here
replacementNode = newIdentifierName.WithTrailingTrivia(variableDeclarator.AsClause.GetTrailingTrivia()) ' Trailing Trivia is copied here
issueSpan = variableDeclarator.Span
Return True
End If
Return False
End Function
Private Function HasValidDeclaredTypeSymbol(
modifiedIdentifier As ModifiedIdentifierSyntax,
semanticModel As SemanticModel,
<Out()> ByRef typeSymbol As ITypeSymbol) As Boolean
Dim declaredSymbol = semanticModel.GetDeclaredSymbol(modifiedIdentifier)
If declaredSymbol Is Nothing OrElse
(Not TypeOf declaredSymbol Is ILocalSymbol AndAlso Not TypeOf declaredSymbol Is IFieldSymbol) Then
Return False
End If
Dim localSymbol = TryCast(declaredSymbol, ILocalSymbol)
If localSymbol IsNot Nothing AndAlso TypeOf localSymbol IsNot IErrorTypeSymbol AndAlso TypeOf localSymbol.Type IsNot IErrorTypeSymbol Then
typeSymbol = localSymbol.Type
Return True
End If
Dim fieldSymbol = TryCast(declaredSymbol, IFieldSymbol)
If fieldSymbol IsNot Nothing AndAlso TypeOf fieldSymbol IsNot IErrorTypeSymbol AndAlso TypeOf fieldSymbol.Type IsNot IErrorTypeSymbol Then
typeSymbol = fieldSymbol.Type
Return True
End If
Return False
End Function
<Extension()>
Public Function TryReduceOrSimplifyExplicitName(
expression As ExpressionSyntax,
semanticModel As SemanticModel,
<Out()> ByRef replacementNode As ExpressionSyntax,
<Out()> ByRef issueSpan As TextSpan,
optionSet As OptionSet,
cancellationToken As CancellationToken
) As Boolean
If expression.TryReduceExplicitName(semanticModel, replacementNode, issueSpan, optionSet, cancellationToken) Then
Return True
End If
Return expression.TrySimplify(semanticModel, optionSet, replacementNode, issueSpan)
End Function
<Extension()>
Public Function TryReduceExplicitName(
expression As ExpressionSyntax,
semanticModel As SemanticModel,
<Out()> ByRef replacementNode As ExpressionSyntax,
<Out()> ByRef issueSpan As TextSpan,
optionSet As OptionSet,
cancellationToken As CancellationToken
) As Boolean
replacementNode = Nothing
issueSpan = Nothing
If expression.Kind = SyntaxKind.SimpleMemberAccessExpression Then
Dim memberAccess = DirectCast(expression, MemberAccessExpressionSyntax)
Return memberAccess.TryReduce(semanticModel,
replacementNode,
issueSpan,
optionSet,
cancellationToken)
ElseIf TypeOf (expression) Is NameSyntax Then
Dim name = DirectCast(expression, NameSyntax)
Return name.TryReduce(semanticModel,
replacementNode,
issueSpan,
optionSet,
cancellationToken)
End If
Return False
End Function
<Extension()>
Private Function TryReduce(
memberAccess As MemberAccessExpressionSyntax,
semanticModel As SemanticModel,
<Out()> ByRef replacementNode As ExpressionSyntax,
<Out()> ByRef issueSpan As TextSpan,
optionSet As OptionSet,
cancellationToken As CancellationToken
) As Boolean
If memberAccess.Expression Is Nothing OrElse memberAccess.Name Is Nothing Then
Return False
End If
If optionSet.GetOption(SimplificationOptions.QualifyMemberAccessWithThisOrMe, semanticModel.Language) AndAlso
memberAccess.Expression.Kind() = SyntaxKind.MeExpression Then
Return False
End If
If memberAccess.HasAnnotations(SpecialTypeAnnotation.Kind) Then
replacementNode = SyntaxFactory.PredefinedType(
SyntaxFactory.Token(
GetPredefinedKeywordKind(SpecialTypeAnnotation.GetSpecialType(memberAccess.GetAnnotations(SpecialTypeAnnotation.Kind).First())))) _
.WithLeadingTrivia(memberAccess.GetLeadingTrivia())
issueSpan = memberAccess.Span
Return True
Else
If Not memberAccess.IsRightSideOfDot() Then
Dim aliasReplacement As IAliasSymbol = Nothing
If memberAccess.TryReplaceWithAlias(semanticModel, aliasReplacement, optionSet.GetOption(SimplificationOptions.PreferAliasToQualification)) Then
Dim identifierToken = SyntaxFactory.Identifier(
memberAccess.GetLeadingTrivia(),
aliasReplacement.Name,
memberAccess.GetTrailingTrivia())
identifierToken = VisualBasicSimplificationService.TryEscapeIdentifierToken(
identifierToken,
semanticModel)
replacementNode = SyntaxFactory.IdentifierName(identifierToken)
issueSpan = memberAccess.Span
' In case the alias name is the same as the last name of the alias target, we only include
' the left part of the name in the unnecessary span to Not confuse uses.
If memberAccess.Name.Identifier.ValueText = identifierToken.ValueText Then
issueSpan = memberAccess.Expression.Span
End If
Return True
End If
If PreferPredefinedTypeKeywordInMemberAccess(memberAccess, optionSet) Then
Dim symbol = semanticModel.GetSymbolInfo(memberAccess).Symbol
If (symbol IsNot Nothing AndAlso symbol.IsKind(SymbolKind.NamedType)) Then
Dim keywordKind = GetPredefinedKeywordKind(DirectCast(symbol, INamedTypeSymbol).SpecialType)
If keywordKind <> SyntaxKind.None Then
replacementNode = SyntaxFactory.PredefinedType(
SyntaxFactory.Token(
memberAccess.GetLeadingTrivia(),
keywordKind,
memberAccess.GetTrailingTrivia()))
issueSpan = memberAccess.Span
Return True
End If
End If
End If
End If
' a module name was inserted by the name expansion, so removing this should be tried first.
If memberAccess.HasAnnotation(SimplificationHelpers.SimplifyModuleNameAnnotation) Then
If TryOmitModuleName(memberAccess, semanticModel, replacementNode, issueSpan, cancellationToken) Then
Return True
End If
End If
replacementNode = memberAccess.Name
replacementNode = DirectCast(replacementNode, SimpleNameSyntax) _
.WithIdentifier(VisualBasicSimplificationService.TryEscapeIdentifierToken(
memberAccess.Name.Identifier,
semanticModel)) _
.WithLeadingTrivia(memberAccess.GetLeadingTriviaForSimplifiedMemberAccess()) _
.WithTrailingTrivia(memberAccess.GetTrailingTrivia())
issueSpan = memberAccess.Expression.Span
If memberAccess.CanReplaceWithReducedName(replacementNode, semanticModel, cancellationToken) Then
Return True
End If
If optionSet.GetOption(SimplificationOptions.PreferOmittingModuleNamesInQualification) Then
If TryOmitModuleName(memberAccess, semanticModel, replacementNode, issueSpan, cancellationToken) Then
Return True
End If
End If
End If
Return False
End Function
<Extension>
Private Function GetLeadingTriviaForSimplifiedMemberAccess(memberAccess As MemberAccessExpressionSyntax) As SyntaxTriviaList
' We want to include any user-typed trivia that may be present between the 'Expression', 'OperatorToken' and 'Identifier' of the MemberAccessExpression.
' However, we don't want to include any elastic trivia that may have been introduced by the expander in these locations. This is to avoid triggering
' aggressive formatting. Otherwise, formatter will see this elastic trivia added by the expander And use that as a cue to introduce unnecessary blank lines
' etc. around the user's original code.
Return memberAccess.GetLeadingTrivia().
AddRange(memberAccess.Expression.GetTrailingTrivia().WithoutElasticTrivia()).
AddRange(memberAccess.OperatorToken.LeadingTrivia.WithoutElasticTrivia()).
AddRange(memberAccess.OperatorToken.TrailingTrivia.WithoutElasticTrivia()).
AddRange(memberAccess.Name.GetLeadingTrivia().WithoutElasticTrivia())
End Function
<Extension>
Private Function WithoutElasticTrivia(list As IEnumerable(Of SyntaxTrivia)) As IEnumerable(Of SyntaxTrivia)
Return list.Where(Function(t) Not t.IsElastic())
End Function
Private Function InsideCrefReference(expr As ExpressionSyntax) As Boolean
Dim crefAttribute = expr.FirstAncestorOrSelf(Of XmlCrefAttributeSyntax)()
Return crefAttribute IsNot Nothing
End Function
Private Function InsideNameOfExpression(expr As ExpressionSyntax) As Boolean
Dim nameOfExpression = expr.FirstAncestorOrSelf(Of NameOfExpressionSyntax)()
Return nameOfExpression IsNot Nothing
End Function
Private Function PreferPredefinedTypeKeywordInMemberAccess(memberAccess As ExpressionSyntax, optionSet As OptionSet) As Boolean
Return (((memberAccess.Parent IsNot Nothing) AndAlso (TypeOf memberAccess.Parent Is MemberAccessExpressionSyntax)) OrElse
(InsideCrefReference(memberAccess) AndAlso Not memberAccess.IsLeftSideOfQualifiedName)) AndAlso ' Bug 1012713: Compiler has a bug due to which it doesn't support <PredefinedType>.Member inside crefs (i.e. Sytem.Int32.MaxValue is supported but Integer.MaxValue isn't). Until this bug is fixed, we don't support simplifying types names like System.Int32.MaxValue to Integer.MaxValue.
(Not InsideNameOfExpression(memberAccess)) AndAlso
optionSet.GetOption(SimplificationOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, LanguageNames.VisualBasic)
End Function
Private Function PreferPredefinedTypeKeywordInDeclarations(name As NameSyntax, optionSet As OptionSet) As Boolean
Return (name.Parent IsNot Nothing) AndAlso (TypeOf name.Parent IsNot MemberAccessExpressionSyntax) AndAlso (Not InsideCrefReference(name)) AndAlso
(Not InsideNameOfExpression(name)) AndAlso
optionSet.GetOption(SimplificationOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, LanguageNames.VisualBasic)
End Function
<Extension>
Public Function GetRightmostName(node As ExpressionSyntax) As NameSyntax
Dim memberAccess = TryCast(node, MemberAccessExpressionSyntax)
If memberAccess IsNot Nothing AndAlso memberAccess.Name IsNot Nothing Then
Return memberAccess.Name
End If
Dim qualified = TryCast(node, QualifiedNameSyntax)
If qualified IsNot Nothing AndAlso qualified.Right IsNot Nothing Then
Return qualified.Right
End If
Dim simple = TryCast(node, SimpleNameSyntax)
If simple IsNot Nothing Then
Return simple
End If
Return Nothing
End Function
Private Function TryOmitModuleName(memberAccess As MemberAccessExpressionSyntax, semanticModel As SemanticModel, <Out()> ByRef replacementNode As ExpressionSyntax, <Out()> ByRef issueSpan As TextSpan, cancellationToken As CancellationToken) As Boolean
If memberAccess.IsParentKind(SyntaxKind.SimpleMemberAccessExpression) Then
Dim symbolForMemberAccess = semanticModel.GetSymbolInfo(DirectCast(memberAccess.Parent, MemberAccessExpressionSyntax)).Symbol
If symbolForMemberAccess.IsModuleMember Then
replacementNode = memberAccess.Expression.WithLeadingTrivia(memberAccess.GetLeadingTrivia())
issueSpan = memberAccess.Name.Span
Dim parent = DirectCast(memberAccess.Parent, MemberAccessExpressionSyntax)
Dim parentReplacement = parent.ReplaceNode(parent.Expression, replacementNode)
If parent.CanReplaceWithReducedName(parentReplacement, semanticModel, cancellationToken) Then
Return True
End If
End If
End If
Return False
End Function
<Extension()>
Private Function CanReplaceWithReducedName(
memberAccess As MemberAccessExpressionSyntax,
reducedNode As ExpressionSyntax,
semanticModel As SemanticModel,
cancellationToken As CancellationToken
) As Boolean
If Not IsMeOrNamedTypeOrNamespace(memberAccess.Expression, semanticModel) Then
Return False
End If
' See if we can simplify a member access expression of the form E.M or E.M() to M or M()
Dim speculationAnalyzer = New SpeculationAnalyzer(memberAccess, reducedNode, semanticModel, cancellationToken)
If Not speculationAnalyzer.SymbolsForOriginalAndReplacedNodesAreCompatible() OrElse
speculationAnalyzer.ReplacementChangesSemantics() Then
Return False
End If
If memberAccess.Expression.IsKind(SyntaxKind.MyBaseExpression) Then
Dim enclosingNamedType = semanticModel.GetEnclosingNamedType(memberAccess.SpanStart, cancellationToken)
Dim symbol = semanticModel.GetSymbolInfo(memberAccess.Name).Symbol
If enclosingNamedType IsNot Nothing AndAlso
Not enclosingNamedType.IsSealed AndAlso
symbol IsNot Nothing AndAlso
symbol.IsOverridable() Then
Return False
End If
End If
Return True
End Function
<Extension()>
Private Function TryReduce(
name As NameSyntax,
semanticModel As SemanticModel,
<Out()> ByRef replacementNode As ExpressionSyntax,
<Out()> ByRef issueSpan As TextSpan,
optionSet As OptionSet,
cancellationToken As CancellationToken
) As Boolean
' do not simplify names of a namespace declaration
If IsPartOfNamespaceDeclarationName(name) Then
Return False
End If
' see whether binding the name binds to a symbol/type. if not, it is ambiguous and
' nothing we can do here.
Dim symbol = SimplificationHelpers.GetOriginalSymbolInfo(semanticModel, name)
If SimplificationHelpers.IsValidSymbolInfo(symbol) Then
If symbol.Kind = SymbolKind.Method AndAlso symbol.IsConstructor() Then
symbol = symbol.ContainingType
End If
If symbol.Kind = SymbolKind.Method AndAlso name.Kind = SyntaxKind.GenericName Then
If Not optionSet.GetOption(SimplificationOptions.PreferImplicitTypeInference) Then
Return False
End If
Dim genericName = DirectCast(name, GenericNameSyntax)
replacementNode = SyntaxFactory.IdentifierName(genericName.Identifier).WithLeadingTrivia(genericName.GetLeadingTrivia()).WithTrailingTrivia(genericName.GetTrailingTrivia())
issueSpan = name.Span
Return name.CanReplaceWithReducedName(replacementNode, semanticModel, cancellationToken)
End If
If Not TypeOf symbol Is INamespaceOrTypeSymbol Then
Return False
End If
Else
Return False
End If
If name.HasAnnotations(SpecialTypeAnnotation.Kind) Then
replacementNode = SyntaxFactory.PredefinedType(
SyntaxFactory.Token(name.GetLeadingTrivia(),
GetPredefinedKeywordKind(SpecialTypeAnnotation.GetSpecialType(name.GetAnnotations(SpecialTypeAnnotation.Kind).First())),
name.GetTrailingTrivia()))
issueSpan = name.Span
Return name.CanReplaceWithReducedNameInContext(replacementNode, semanticModel, cancellationToken)
Else
If Not name.IsRightSideOfDot() Then
Dim aliasReplacement As IAliasSymbol = Nothing
If name.TryReplaceWithAlias(semanticModel, aliasReplacement, optionSet.GetOption(SimplificationOptions.PreferAliasToQualification)) Then
Dim identifierToken = SyntaxFactory.Identifier(
name.GetLeadingTrivia(),
aliasReplacement.Name,
name.GetTrailingTrivia())
identifierToken = VisualBasicSimplificationService.TryEscapeIdentifierToken(
identifierToken,
semanticModel)
replacementNode = SyntaxFactory.IdentifierName(identifierToken)
Dim annotatedNodesOrTokens = name.GetAnnotatedNodesAndTokens(RenameAnnotation.Kind)
For Each annotatedNodeOrToken In annotatedNodesOrTokens
If annotatedNodeOrToken.IsToken Then
identifierToken = annotatedNodeOrToken.AsToken().CopyAnnotationsTo(identifierToken)
Else
replacementNode = annotatedNodeOrToken.AsNode().CopyAnnotationsTo(replacementNode)
End If
Next
annotatedNodesOrTokens = name.GetAnnotatedNodesAndTokens(AliasAnnotation.Kind)
For Each annotatedNodeOrToken In annotatedNodesOrTokens
If annotatedNodeOrToken.IsToken Then
identifierToken = annotatedNodeOrToken.AsToken().CopyAnnotationsTo(identifierToken)
Else
replacementNode = annotatedNodeOrToken.AsNode().CopyAnnotationsTo(replacementNode)
End If
Next
replacementNode = DirectCast(replacementNode, SimpleNameSyntax).WithIdentifier(identifierToken)
issueSpan = name.Span
' In case the alias name is the same as the last name of the alias target, we only include
' the left part of the name in the unnecessary span to Not confuse uses.
If name.Kind = SyntaxKind.QualifiedName Then
Dim qualifiedName As QualifiedNameSyntax = DirectCast(name, QualifiedNameSyntax)
If qualifiedName.Right.Identifier.ValueText = identifierToken.ValueText Then
issueSpan = qualifiedName.Left.Span
End If
End If
If name.CanReplaceWithReducedNameInContext(replacementNode, semanticModel, cancellationToken) Then
' check if the alias name ends with an Attribute suffic that can be omitted.
Dim replacementNodeWithoutAttributeSuffix As ExpressionSyntax = Nothing
Dim issueSpanWithoutAttributeSuffix As TextSpan = Nothing
If TryReduceAttributeSuffix(name, identifierToken, semanticModel, aliasReplacement IsNot Nothing, optionSet.GetOption(SimplificationOptions.PreferAliasToQualification), replacementNodeWithoutAttributeSuffix, issueSpanWithoutAttributeSuffix, cancellationToken) Then
If name.CanReplaceWithReducedName(replacementNodeWithoutAttributeSuffix, semanticModel, cancellationToken) Then
replacementNode = replacementNode.CopyAnnotationsTo(replacementNodeWithoutAttributeSuffix)
issueSpan = issueSpanWithoutAttributeSuffix
End If
End If
Return True
End If
Return False
End If
Dim nameHasNoAlias = False
If TypeOf name Is SimpleNameSyntax Then
Dim simpleName = DirectCast(name, SimpleNameSyntax)
If Not simpleName.Identifier.HasAnnotations(AliasAnnotation.Kind) Then
nameHasNoAlias = True
End If
End If
If TypeOf name Is QualifiedNameSyntax Then
Dim qualifiedNameSyntax = DirectCast(name, QualifiedNameSyntax)
If Not qualifiedNameSyntax.Right.Identifier.HasAnnotations(AliasAnnotation.Kind) Then
nameHasNoAlias = True
End If
End If
Dim aliasInfo = semanticModel.GetAliasInfo(name, cancellationToken)
If nameHasNoAlias AndAlso aliasInfo Is Nothing Then
If PreferPredefinedTypeKeywordInDeclarations(name, optionSet) OrElse
PreferPredefinedTypeKeywordInMemberAccess(name, optionSet) Then
Dim type = semanticModel.GetTypeInfo(name).Type
If type IsNot Nothing Then
Dim keywordKind = GetPredefinedKeywordKind(type.SpecialType)
If keywordKind <> SyntaxKind.None Then
replacementNode = SyntaxFactory.PredefinedType(
SyntaxFactory.Token(
name.GetLeadingTrivia(),
keywordKind,
name.GetTrailingTrivia()))
issueSpan = name.Span
Return name.CanReplaceWithReducedNameInContext(replacementNode, semanticModel, cancellationToken)
End If
End If
End If
End If
' Nullable rewrite: Nullable(Of Integer) -> Integer?
' Don't rewrite in the case where Nullable(Of Integer) is part of some qualified name like Nullable(Of Integer).Something
If (symbol.Kind = SymbolKind.NamedType) AndAlso (Not name.IsLeftSideOfQualifiedName) Then
Dim type = DirectCast(symbol, INamedTypeSymbol)
If aliasInfo Is Nothing AndAlso CanSimplifyNullable(type, name) Then
Dim genericName As GenericNameSyntax
If name.Kind = SyntaxKind.QualifiedName Then
genericName = DirectCast(DirectCast(name, QualifiedNameSyntax).Right, GenericNameSyntax)
Else
genericName = DirectCast(name, GenericNameSyntax)
End If
Dim oldType = genericName.TypeArgumentList.Arguments.First()
replacementNode = SyntaxFactory.NullableType(oldType).WithLeadingTrivia(name.GetLeadingTrivia())
issueSpan = name.Span
If name.CanReplaceWithReducedNameInContext(replacementNode, semanticModel, cancellationToken) Then
Return True
End If
End If
End If
End If
Select Case name.Kind
Case SyntaxKind.QualifiedName
' a module name was inserted by the name expansion, so removing this should be tried first.
Dim qualifiedName = DirectCast(name, QualifiedNameSyntax)
If qualifiedName.HasAnnotation(SimplificationHelpers.SimplifyModuleNameAnnotation) Then
If TryOmitModuleName(qualifiedName, semanticModel, replacementNode, issueSpan, cancellationToken) Then
Return True
End If
End If
replacementNode = qualifiedName.Right.WithLeadingTrivia(name.GetLeadingTrivia())
replacementNode = DirectCast(replacementNode, SimpleNameSyntax) _
.WithIdentifier(VisualBasicSimplificationService.TryEscapeIdentifierToken(
DirectCast(replacementNode, SimpleNameSyntax).Identifier,
semanticModel))
issueSpan = qualifiedName.Left.Span
If name.CanReplaceWithReducedName(replacementNode, semanticModel, cancellationToken) Then
Return True
End If
If optionSet.GetOption(SimplificationOptions.PreferOmittingModuleNamesInQualification) Then
If TryOmitModuleName(qualifiedName, semanticModel, replacementNode, issueSpan, cancellationToken) Then
Return True
End If
End If
Case SyntaxKind.IdentifierName
Dim identifier = DirectCast(name, IdentifierNameSyntax).Identifier
TryReduceAttributeSuffix(name, identifier, semanticModel, False, optionSet.GetOption(SimplificationOptions.PreferAliasToQualification), replacementNode, issueSpan, cancellationToken)
End Select
End If
If replacementNode Is Nothing Then
Return False
End If
Return name.CanReplaceWithReducedName(replacementNode, semanticModel, cancellationToken)
End Function
Private Function CanSimplifyNullable(type As INamedTypeSymbol, name As NameSyntax) As Boolean
If Not type.IsNullable Then
Return False
End If
If type.IsUnboundGenericType Then
' Don't simplify unbound generic type "Nullable(Of )".
Return False
End If
If Not InsideCrefReference(name) Then
' Nullable(Of T) can always be simplified to T? outside crefs.
Return True
End If
' Inside crefs, if the T in this Nullable(Of T) is being declared right here
' then this Nullable(Of T) is not a constructed generic type and we should
' not offer to simplify this to T?.
'
' For example, we should not offer the simplification in the following cases where
' T does not bind to an existing type / type parameter in the user's code.
' - <see cref="Nullable(Of T)"/>
' - <see cref="System.Nullable(Of T).Value"/>
'
' And we should offer the simplification in the following cases where SomeType and
' SomeMethod bind to a type and method declared elsewhere in the users code.
' - <see cref="SomeType.SomeMethod(Nullable(Of SomeType))"/>
If name.IsKind(SyntaxKind.GenericName) Then
If (name.IsParentKind(SyntaxKind.CrefReference)) OrElse ' cref="Nullable(Of T)"
(name.IsParentKind(SyntaxKind.QualifiedName) AndAlso name.Parent?.IsParentKind(SyntaxKind.CrefReference)) OrElse ' cref="System.Nullable(Of T)"
(name.IsParentKind(SyntaxKind.QualifiedName) AndAlso name.Parent?.IsParentKind(SyntaxKind.QualifiedName) AndAlso name.Parent?.Parent?.IsParentKind(SyntaxKind.CrefReference)) Then ' cref="System.Nullable(Of T).Value"
' Unfortunately, unlike in corresponding C# case, we need syntax based checking to detect these cases because of bugs in the VB SemanticModel.
' See https://github.com/dotnet/roslyn/issues/2196, https://github.com/dotnet/roslyn/issues/2197
Return False
End If
End If
Dim argument = type.TypeArguments.SingleOrDefault()
If argument Is Nothing OrElse argument.IsErrorType() Then
Return False
End If
Dim argumentDecl = argument.DeclaringSyntaxReferences.FirstOrDefault()
If argumentDecl Is Nothing Then
' The type argument is a type from metadata - so this is a constructed generic nullable type that can be simplified (e.g. Nullable(Of Integer)).
Return True
End If
Return Not name.Span.Contains(argumentDecl.Span)
End Function
Private Function TryReduceAttributeSuffix(
name As NameSyntax,
identifierToken As SyntaxToken,
semanticModel As SemanticModel,
isIdentifierNameFromAlias As Boolean,
preferAliasToQualification As Boolean,
<Out()> ByRef replacementNode As ExpressionSyntax,
<Out()> ByRef issueSpan As TextSpan,
cancellationToken As CancellationToken
) As Boolean
If SyntaxFacts.IsAttributeName(name) AndAlso Not isIdentifierNameFromAlias Then
' When the replacement is an Alias we don't want the "Attribute" Suffix to be removed because this will result in symbol change
Dim aliasSymbol = semanticModel.GetAliasInfo(name, cancellationToken)
If (aliasSymbol IsNot Nothing AndAlso preferAliasToQualification AndAlso
String.Compare(aliasSymbol.Name, identifierToken.ValueText, StringComparison.OrdinalIgnoreCase) = 0) Then
Return False
End If
If name.Parent.Kind = SyntaxKind.Attribute OrElse name.IsRightSideOfDot() Then
Dim newIdentifierText = String.Empty
' an attribute that should keep it (unnecessary "Attribute" suffix should be annotated with a DontSimplifyAnnotation
If identifierToken.HasAnnotation(SimplificationHelpers.DontSimplifyAnnotation) Then
newIdentifierText = identifierToken.ValueText + "Attribute"
ElseIf identifierToken.ValueText.TryReduceAttributeSuffix(newIdentifierText) Then
issueSpan = New TextSpan(name.Span.End - 9, 9)
Else
Return False
End If
' escape it (VB allows escaping even for abbreviated identifiers, C# does not!)
Dim newIdentifierToken = identifierToken.CopyAnnotationsTo(
SyntaxFactory.Identifier(
identifierToken.LeadingTrivia,
newIdentifierText,
identifierToken.TrailingTrivia))
newIdentifierToken = VisualBasicSimplificationService.TryEscapeIdentifierToken(newIdentifierToken, semanticModel)
replacementNode = SyntaxFactory.IdentifierName(newIdentifierToken).WithLeadingTrivia(name.GetLeadingTrivia())
Return True
End If
End If
Return False
End Function
''' <summary>
''' Checks if the SyntaxNode is a name of a namespace declaration. To be a namespace name, the syntax
''' must be parented by an namespace declaration and the node itself must be equal to the declaration's Name
''' property.
''' </summary>
Private Function IsPartOfNamespaceDeclarationName(node As SyntaxNode) As Boolean
Dim nextNode As SyntaxNode = node
Do While nextNode IsNot Nothing
Select Case nextNode.Kind
Case SyntaxKind.IdentifierName, SyntaxKind.QualifiedName
node = nextNode
nextNode = nextNode.Parent
Case SyntaxKind.NamespaceStatement
Dim namespaceStatement = DirectCast(nextNode, NamespaceStatementSyntax)
Return namespaceStatement.Name Is node
Case Else
Return False
End Select
Loop
Return False
End Function
Private Function TryOmitModuleName(name As QualifiedNameSyntax, semanticModel As SemanticModel, <Out()> ByRef replacementNode As ExpressionSyntax, <Out()> ByRef issueSpan As TextSpan, cancellationToken As CancellationToken) As Boolean
If name.IsParentKind(SyntaxKind.QualifiedName) Then
Dim symbolForName = semanticModel.GetSymbolInfo(DirectCast(name.Parent, QualifiedNameSyntax)).Symbol
' in case this QN is used in a "New NSName.ModuleName.MemberName()" expression
' the returned symbol is a constructor. Then we need to get the containing type.
If symbolForName.IsConstructor Then
symbolForName = symbolForName.ContainingType
End If
If symbolForName.IsModuleMember Then
replacementNode = name.Left.WithLeadingTrivia(name.GetLeadingTrivia())
issueSpan = name.Right.Span
Dim parent = DirectCast(name.Parent, QualifiedNameSyntax)
Dim parentReplacement = parent.ReplaceNode(parent.Left, replacementNode)
If parent.CanReplaceWithReducedName(parentReplacement, semanticModel, cancellationToken) Then
Return True
End If
End If
End If
Return False
End Function
<Extension()>
Private Function TrySimplify(
expression As ExpressionSyntax,
semanticModel As SemanticModel,
optionSet As OptionSet,
<Out()> ByRef replacementNode As ExpressionSyntax,
<Out()> ByRef issueSpan As TextSpan
) As Boolean
replacementNode = Nothing
issueSpan = Nothing
Select Case expression.Kind
Case SyntaxKind.SimpleMemberAccessExpression
If True Then
Dim memberAccess = DirectCast(expression, MemberAccessExpressionSyntax)
Dim newLeft As ExpressionSyntax = Nothing
If TrySimplifyMemberAccessOrQualifiedName(memberAccess.Expression, memberAccess.Name, semanticModel, optionSet, newLeft, issueSpan) Then
' replacement node might not be in it's simplest form, so add simplify annotation to it.
replacementNode = memberAccess.Update(memberAccess.Kind, newLeft, memberAccess.OperatorToken, memberAccess.Name).WithAdditionalAnnotations(Simplifier.Annotation)
' Ensure that replacement doesn't change semantics.
Return Not ReplacementChangesSemantics(memberAccess, replacementNode, semanticModel)
End If
Return False
End If
Case SyntaxKind.QualifiedName
If True Then
Dim qualifiedName = DirectCast(expression, QualifiedNameSyntax)
Dim newLeft As ExpressionSyntax = Nothing
If TrySimplifyMemberAccessOrQualifiedName(qualifiedName.Left, qualifiedName.Right, semanticModel, optionSet, newLeft, issueSpan) Then
If Not TypeOf newLeft Is NameSyntax Then
Contract.Fail("QualifiedName Left = " + qualifiedName.Left.ToString() + " and QualifiedName Right = " + qualifiedName.Right.ToString() + " . Left is tried to be replaced with the PredefinedType " + replacementNode.ToString())
End If
' replacement node might not be in it's simplest form, so add simplify annotation to it.
replacementNode = qualifiedName.Update(DirectCast(newLeft, NameSyntax), qualifiedName.DotToken, qualifiedName.Right).WithAdditionalAnnotations(Simplifier.Annotation)
' Ensure that replacement doesn't change semantics.
Return Not ReplacementChangesSemantics(qualifiedName, replacementNode, semanticModel)
End If
Return False
End If
End Select
Return False
End Function
Private Function ReplacementChangesSemantics(originalExpression As ExpressionSyntax, replacedExpression As ExpressionSyntax, semanticModel As SemanticModel) As Boolean
Dim speculationAnalyzer = New SpeculationAnalyzer(originalExpression, replacedExpression, semanticModel, CancellationToken.None)
Return speculationAnalyzer.ReplacementChangesSemantics()
End Function
' Note: The caller needs to verify that replacement doesn't change semantics of the original expression.
Private Function TrySimplifyMemberAccessOrQualifiedName(
left As ExpressionSyntax,
right As ExpressionSyntax,
semanticModel As SemanticModel,
optionSet As OptionSet,
<Out()> ByRef replacementNode As ExpressionSyntax,
<Out()> ByRef issueSpan As TextSpan
) As Boolean
replacementNode = Nothing
issueSpan = Nothing
If left IsNot Nothing AndAlso right IsNot Nothing Then
Dim leftSymbol = SimplificationHelpers.GetOriginalSymbolInfo(semanticModel, left)
If leftSymbol IsNot Nothing AndAlso leftSymbol.Kind = SymbolKind.NamedType Then
Dim rightSymbol = SimplificationHelpers.GetOriginalSymbolInfo(semanticModel, right)
If rightSymbol IsNot Nothing AndAlso (rightSymbol.IsStatic OrElse rightSymbol.Kind = SymbolKind.NamedType) Then
' Static member access or nested type member access.
Dim containingType As INamedTypeSymbol = rightSymbol.ContainingType
Dim isInCref = left.Ancestors(ascendOutOfTrivia:=True).OfType(Of CrefReferenceSyntax)().Any()
' Crefs in VB , irrespective of the expression are parsed as QualifiedName (no MemberAccessExpression)
' Hence the Left can never be a PredefinedType (or anything other than NameSyntax)
If isInCref AndAlso TypeOf rightSymbol Is IMethodSymbol AndAlso Not containingType.SpecialType = SpecialType.None Then
Return False
End If
If containingType IsNot Nothing AndAlso Not containingType.Equals(leftSymbol) Then
Dim namedType = TryCast(leftSymbol, INamedTypeSymbol)
If namedType IsNot Nothing Then
If ((namedType.GetBaseTypes().Contains(containingType) AndAlso
Not optionSet.GetOption(SimplificationOptions.AllowSimplificationToBaseType)) OrElse
(Not optionSet.GetOption(SimplificationOptions.AllowSimplificationToGenericType) AndAlso
containingType.TypeArguments.Count() <> 0)) Then
Return False
End If
End If
' We have a static member access or a nested type member access using a more derived type.
' Simplify syntax so as to use accessed member's most immediate containing type instead of the derived type.
replacementNode = containingType.GenerateTypeSyntax().WithLeadingTrivia(left.GetLeadingTrivia()).WithTrailingTrivia(left.GetTrailingTrivia()).WithAdditionalAnnotations(Simplifier.Annotation)
issueSpan = left.Span
Return True
End If
End If
End If
End If
Return False
End Function
<Extension>
Private Function TryReplaceWithAlias(
node As ExpressionSyntax,
semanticModel As SemanticModel,
<Out> ByRef aliasReplacement As IAliasSymbol,
Optional preferAliasToQualifiedName As Boolean = False) As Boolean
aliasReplacement = Nothing
If Not node.IsAliasReplaceableExpression() Then
Return False
End If
Dim symbol = semanticModel.GetSymbolInfo(node).Symbol
If (symbol.IsConstructor()) Then
symbol = symbol.ContainingType
End If
' The following condition checks if the user has used alias in the original code and
' if so the expression is replaced with the Alias
If TypeOf node Is QualifiedNameSyntax Then
Dim qualifiedNameNode = DirectCast(node, QualifiedNameSyntax)
If qualifiedNameNode.Right.Identifier.HasAnnotations(AliasAnnotation.Kind) Then
Dim aliasAnnotationInfo = qualifiedNameNode.Right.Identifier.GetAnnotations(AliasAnnotation.Kind).Single()
Dim aliasName = AliasAnnotation.GetAliasName(aliasAnnotationInfo)
Dim aliasIdentifier = SyntaxFactory.IdentifierName(aliasName)
Dim aliasTypeInfo = semanticModel.GetSpeculativeAliasInfo(node.SpanStart, aliasIdentifier, SpeculativeBindingOption.BindAsTypeOrNamespace)
If Not aliasTypeInfo Is Nothing Then
aliasReplacement = aliasTypeInfo
Return ValidateAliasForTarget(aliasReplacement, semanticModel, node, symbol)
End If
End If
End If
If node.Kind = SyntaxKind.IdentifierName AndAlso semanticModel.GetAliasInfo(DirectCast(node, IdentifierNameSyntax)) IsNot Nothing Then
Return False
End If
' an alias can only replace a type Or namespace
If symbol Is Nothing OrElse
(symbol.Kind <> SymbolKind.Namespace AndAlso symbol.Kind <> SymbolKind.NamedType) Then
Return False
End If
If symbol Is Nothing OrElse Not TypeOf (symbol) Is INamespaceOrTypeSymbol Then
Return False
End If
If TypeOf node Is QualifiedNameSyntax Then
Dim qualifiedName = DirectCast(node, QualifiedNameSyntax)
If Not qualifiedName.Right.HasAnnotation(Simplifier.SpecialTypeAnnotation) Then
Dim type = semanticModel.GetTypeInfo(node).Type
If Not type Is Nothing Then
Dim keywordKind = GetPredefinedKeywordKind(type.SpecialType)
If keywordKind <> SyntaxKind.None Then
preferAliasToQualifiedName = False
End If
End If
End If
End If
aliasReplacement = DirectCast(symbol, INamespaceOrTypeSymbol).GetAliasForSymbol(node, semanticModel)
If aliasReplacement IsNot Nothing And preferAliasToQualifiedName Then
Return ValidateAliasForTarget(aliasReplacement, semanticModel, node, symbol)
End If
Return False
End Function
' We must verify that the alias actually binds back to the thing it's aliasing.
' It's possible there is another symbol with the same name as the alias that binds first
Private Function ValidateAliasForTarget(aliasReplacement As IAliasSymbol, semanticModel As SemanticModel, node As ExpressionSyntax, symbol As ISymbol) As Boolean
Dim aliasName = aliasReplacement.Name
Dim boundSymbols = semanticModel.LookupNamespacesAndTypes(node.SpanStart, name:=aliasName)
If boundSymbols.Length = 1 Then
Dim boundAlias = TryCast(boundSymbols(0), IAliasSymbol)
If boundAlias IsNot Nothing And aliasReplacement.Target.Equals(symbol) Then
If symbol.IsAttribute Then
boundSymbols = semanticModel.LookupNamespacesAndTypes(node.Span.Start, name:=aliasName + "Attribute")
Return boundSymbols.IsEmpty
End If
Return True
End If
End If
Return False
End Function
<Extension()>
Private Function CanReplaceWithReducedName(
name As NameSyntax,
replacementNode As ExpressionSyntax,
semanticModel As SemanticModel,
cancellationToken As CancellationToken
) As Boolean
Dim speculationAnalyzer = New SpeculationAnalyzer(name, replacementNode, semanticModel, cancellationToken)
If speculationAnalyzer.ReplacementChangesSemantics() Then
Return False
End If
Return name.CanReplaceWithReducedNameInContext(replacementNode, semanticModel, cancellationToken)
End Function
<Extension>
Private Function CanReplaceWithReducedNameInContext(name As NameSyntax, replacementNode As ExpressionSyntax, semanticModel As SemanticModel, cancellationToken As CancellationToken) As Boolean
' Special case. if this new minimal name parses out to a predefined type, then we
' have to make sure that we're not in a using alias. That's the one place where the
' language doesn't allow predefined types. You have to use the fully qualified name
' instead.
Dim invalidTransformation1 = IsNonNameSyntaxInImportsDirective(name, replacementNode)
Dim invalidTransformation2 = IsReservedNameInAttribute(name, replacementNode)
Dim invalidTransformation3 = IsNullableTypeSyntaxLeftOfDotInMemberAccess(name, replacementNode)
Return Not (invalidTransformation1 OrElse invalidTransformation2 OrElse invalidTransformation3)
End Function
Private Function IsMeOrNamedTypeOrNamespace(expression As ExpressionSyntax, semanticModel As SemanticModel) As Boolean
If expression.Kind = SyntaxKind.MeExpression Then
Return True
End If
Dim expressionInfo = semanticModel.GetSymbolInfo(expression)
If SimplificationHelpers.IsValidSymbolInfo(expressionInfo.Symbol) Then
If TypeOf expressionInfo.Symbol Is INamespaceOrTypeSymbol Then
Return True
End If
If expressionInfo.Symbol.IsThisParameter() Then
Return True
End If
End If
Return False
End Function
''' <summary>
''' Returns the predefined keyword kind for a given special type.
''' </summary>
''' <param name="type">The specialtype of this type.</param>
''' <returns>The keyword kind for a given special type, or SyntaxKind.None if the type name is not a predefined type.</returns>
Private Function GetPredefinedKeywordKind(type As SpecialType) As SyntaxKind
Select Case type
Case SpecialType.System_Boolean
Return SyntaxKind.BooleanKeyword
Case SpecialType.System_Byte
Return SyntaxKind.ByteKeyword
Case SpecialType.System_SByte
Return SyntaxKind.SByteKeyword
Case SpecialType.System_Int32
Return SyntaxKind.IntegerKeyword
Case SpecialType.System_UInt32
Return SyntaxKind.UIntegerKeyword
Case SpecialType.System_Int16
Return SyntaxKind.ShortKeyword
Case SpecialType.System_UInt16
Return SyntaxKind.UShortKeyword
Case SpecialType.System_Int64
Return SyntaxKind.LongKeyword
Case SpecialType.System_UInt64
Return SyntaxKind.ULongKeyword
Case SpecialType.System_Single
Return SyntaxKind.SingleKeyword
Case SpecialType.System_Double
Return SyntaxKind.DoubleKeyword
Case SpecialType.System_Decimal
Return SyntaxKind.DecimalKeyword
Case SpecialType.System_String
Return SyntaxKind.StringKeyword
Case SpecialType.System_Char
Return SyntaxKind.CharKeyword
Case SpecialType.System_Object
Return SyntaxKind.ObjectKeyword
Case SpecialType.System_DateTime
Return SyntaxKind.DateKeyword
Case Else
Return SyntaxKind.None
End Select
End Function
Private Function IsNullableTypeSyntaxLeftOfDotInMemberAccess(expression As ExpressionSyntax, simplifiedNode As ExpressionSyntax) As Boolean
Return expression.IsParentKind(SyntaxKind.SimpleMemberAccessExpression) AndAlso
simplifiedNode.Kind = SyntaxKind.NullableType
End Function
Private Function IsNonNameSyntaxInImportsDirective(expression As ExpressionSyntax, simplifiedNode As ExpressionSyntax) As Boolean
Return TypeOf expression.Parent Is ImportsClauseSyntax AndAlso
Not TypeOf simplifiedNode Is NameSyntax
End Function
Public Function IsReservedNameInAttribute(originalName As NameSyntax, simplifiedNode As ExpressionSyntax) As Boolean
Dim attribute = originalName.GetAncestorOrThis(Of AttributeSyntax)()
If attribute Is Nothing Then
Return False
End If
Dim identifier As SimpleNameSyntax
If simplifiedNode.Kind = SyntaxKind.IdentifierName Then
identifier = DirectCast(simplifiedNode, SimpleNameSyntax)
ElseIf simplifiedNode.Kind = SyntaxKind.QualifiedName Then
identifier = DirectCast(DirectCast(simplifiedNode, QualifiedNameSyntax).Left, SimpleNameSyntax)
Else
Return False
End If
If identifier.Identifier.IsBracketed Then
Return False
End If
If attribute.Target Is Nothing Then
Dim identifierValue = SyntaxFacts.MakeHalfWidthIdentifier(identifier.Identifier.ValueText)
If CaseInsensitiveComparison.Equals(identifierValue, "Assembly") OrElse
CaseInsensitiveComparison.Equals(identifierValue, "Module") Then
Return True
End If
End If
Return False
End Function
End Module
End Namespace
|
marksantos/roslyn
|
src/Workspaces/VisualBasic/Portable/Extensions/ExpressionSyntaxExtensions.vb
|
Visual Basic
|
apache-2.0
| 95,473
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Threading
Imports System.Threading.Tasks
Imports System.Xml.Linq
Imports Microsoft.CodeAnalysis.Completion
Imports Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.Completion
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.VisualBasic.Completion.SuggestionMode
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Completion.CompletionProviders
Public Class SuggestionModeCompletionProviderTests
Inherits AbstractVisualBasicCompletionProviderTests
Public Sub New(workspaceFixture As VisualBasicTestWorkspaceFixture)
MyBase.New(workspaceFixture)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestFieldDeclaration1() As Task
Dim markup = <a>Class C
$$
End Class</a>
Await VerifyNotBuilderAsync(markup)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestFieldDeclaration2() As Task
Dim markup = <a>Class C
Public $$
End Class</a>
Await VerifyBuilderAsync(markup)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestFieldDeclaration3() As Task
Dim markup = <a>Module M
Public $$
End Module</a>
Await VerifyBuilderAsync(markup)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestFieldDeclaration4() As Task
Dim markup = <a>Structure S
Public $$
End Structure</a>
Await VerifyBuilderAsync(markup)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestFieldDeclaration5() As Task
Dim markup = <a>Class C
WithEvents $$
End Class</a>
Await VerifyBuilderAsync(markup)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestFieldDeclaration6() As Task
Dim markup = <a>Class C
Protected Friend $$
End Class</a>
Await VerifyBuilderAsync(markup)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestParameterDeclaration1() As Task
Dim markup = <a>Class C
Public Sub Bar($$
End Sub
End Class</a>
Await VerifyBuilderAsync(markup)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestParameterDeclaration2() As Task
Dim markup = <a>Class C
Public Sub Bar(Optional foo as Integer, $$
End Sub
End Class</a>
Await VerifyNotBuilderAsync(markup)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestParameterDeclaration3() As Task
Dim markup = <a>Class C
Public Sub Bar(Optional $$
End Sub
End Class</a>
Await VerifyBuilderAsync(markup)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestParameterDeclaration4() As Task
Dim markup = <a>Class C
Public Sub Bar(Optional x $$
End Sub
End Class</a>
Await VerifyNotBuilderAsync(markup)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestParameterDeclaration5() As Task
Dim markup = <a>Class C
Public Sub Bar(Optional x As $$
End Sub
End Class</a>
Await VerifyNotBuilderAsync(markup)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestParameterDeclaration6() As Task
Dim markup = <a>Class C
Public Sub Bar(Optional x As Integer $$
End Sub
End Class</a>
Await VerifyNotBuilderAsync(markup)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestParameterDeclaration7() As Task
Dim markup = <a>Class C
Public Sub Bar(ByVal $$
End Sub
End Class</a>
Await VerifyBuilderAsync(markup)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestParameterDeclaration8() As Task
Dim markup = <a>Class C
Public Sub Bar(ByVal x $$
End Sub
End Class</a>
Await VerifyNotBuilderAsync(markup)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestParameterDeclaration9() As Task
Dim markup = <a>Class C
Sub Foo $$
End Class</a>
Await VerifyNotBuilderAsync(markup)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestParameterDeclaration10() As Task
Dim markup = <a>Class C
Public Property SomeProp $$
End Class</a>
Await VerifyNotBuilderAsync(markup)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestSelectClause1() As Task
Dim markup = <a>Class z
Sub bar()
Dim a = New Integer(1, 2, 3) {}
Dim foo = From z In a
Select $$
End Sub
End Class</a>
Await VerifyBuilderAsync(markup)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestSelectClause2() As Task
Dim markup = <a>Class z
Sub bar()
Dim a = New Integer(1, 2, 3) {}
Dim foo = From z In a
Select 1, $$
End Sub
End Class</a>
Await VerifyBuilderAsync(markup)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestForStatement1() As Task
Dim markup = <a>Class z
Sub bar()
For $$
End Sub
End Class</a>
Await VerifyBuilderAsync(markup)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestForStatement2() As Task
Dim markup = <a>Class z
Sub bar()
For $$ = 1 To 10
Next
End Sub
End Class</a>
Await VerifyBuilderAsync(markup)
End Function
<WorkItem(545351, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545351")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestBuilderWhenOptionExplicitOff() As Task
Dim markup = <a>Option Explicit Off
Class C1
Sub M()
Console.WriteLine($$
End Sub
End Class
</a>
Await VerifyBuilderAsync(markup)
End Function
<WorkItem(546659, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546659")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestUsingStatement() As Task
Dim markup = <a>
Class C1
Sub M()
Using $$
End Sub
End Class
</a>
Await VerifyBuilderAsync(markup)
End Function
<WorkItem(734596, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/734596")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestOptionExplicitOffStatementLevel1() As Task
Dim markup = <a>
Option Explicit Off
Class C1
Sub M()
$$
End Sub
End Class
</a>
Await VerifyBuilderAsync(markup)
End Function
<WorkItem(734596, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/734596")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestOptionExplicitOffStatementLevel2() As Task
Dim markup = <a>
Option Explicit Off
Class C1
Sub M()
a = $$
End Sub
End Class
</a>
Await VerifyBuilderAsync(markup)
End Function
<WorkItem(960416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/960416")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestReadonlyField() As Task
Dim markup = <a>
Class C1
Readonly $$
Sub M()
End Sub
End Class
</a>
Await VerifyBuilderAsync(markup)
End Function
<WorkItem(1044441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1044441")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function BuilderInDebugger() As Task
Dim markup = <a>
Class C1
Sub Foo()
Dim __o = $$
End Sub
End Class
</a>
Await VerifyBuilderAsync(markup, CompletionTrigger.Default, useDebuggerOptions:=True)
End Function
<WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function NamespaceDeclarationName_Unqualified() As Task
Dim markup = <a>
Namespace $$
End Class
</a>
Await VerifyBuilderAsync(markup, CompletionTrigger.Default)
End Function
<WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function NamespaceDeclarationName_Qualified() As Task
Dim markup = <a>
Namespace A.$$
End Class
</a>
Await VerifyBuilderAsync(markup, CompletionTrigger.Default)
End Function
Private Function VerifyNotBuilderAsync(markup As XElement, Optional triggerInfo As CompletionTrigger? = Nothing, Optional useDebuggerOptions As Boolean = False) As Task
Return VerifySuggestionModeWorkerAsync(markup, isBuilder:=False, triggerInfo:=triggerInfo, useDebuggerOptions:=useDebuggerOptions)
End Function
Private Function VerifyBuilderAsync(markup As XElement, Optional triggerInfo As CompletionTrigger? = Nothing, Optional useDebuggerOptions As Boolean = False) As Task
Return VerifySuggestionModeWorkerAsync(markup, isBuilder:=True, triggerInfo:=triggerInfo, useDebuggerOptions:=useDebuggerOptions)
End Function
Private Async Function VerifySuggestionModeWorkerAsync(markup As XElement, isBuilder As Boolean, triggerInfo As CompletionTrigger?, Optional useDebuggerOptions As Boolean = False) As Task
Dim code As String = Nothing
Dim position As Integer = 0
MarkupTestFile.GetPosition(markup.NormalizedValue, code, position)
Using workspaceFixture = New VisualBasicTestWorkspaceFixture()
Dim options = If(useDebuggerOptions,
(Await workspaceFixture.GetWorkspaceAsync()).Options.WithDebuggerCompletionOptions(),
(Await workspaceFixture.GetWorkspaceAsync()).Options)
Dim document1 = Await workspaceFixture.UpdateDocumentAsync(code, SourceCodeKind.Regular)
Await CheckResultsAsync(document1, position, isBuilder, triggerInfo, options)
If Await CanUseSpeculativeSemanticModelAsync(document1, position) Then
Dim document2 = Await workspaceFixture.UpdateDocumentAsync(code, SourceCodeKind.Regular, cleanBeforeUpdate:=False)
Await CheckResultsAsync(document2, position, isBuilder, triggerInfo, options)
End If
End Using
End Function
Private Async Function CheckResultsAsync(document As Document, position As Integer, isBuilder As Boolean, triggerInfo As CompletionTrigger?, options As OptionSet) As Task
triggerInfo = If(triggerInfo, CompletionTrigger.CreateInsertionTrigger("a"c))
Dim service = GetCompletionService(document.Project.Solution.Workspace)
Dim context = Await service.GetContextAsync(
service.ExclusiveProviders?(0), document, position, triggerInfo.Value, options, CancellationToken.None)
If isBuilder Then
Assert.NotNull(context)
Assert.NotNull(context.SuggestionModeItem)
Else
If context IsNot Nothing Then
Assert.True(context.SuggestionModeItem Is Nothing, "group.Builder = " & If(context.SuggestionModeItem IsNot Nothing, context.SuggestionModeItem.DisplayText, "null"))
End If
End If
End Function
Friend Overrides Function CreateCompletionProvider() As CompletionProvider
Return New VisualBasicSuggestionModeCompletionProvider()
End Function
End Class
End Namespace
|
jaredpar/roslyn
|
src/EditorFeatures/VisualBasicTest/Completion/CompletionProviders/SuggestionModeCompletionProviderTests.vb
|
Visual Basic
|
apache-2.0
| 13,083
|
Imports System.Collections.Immutable
Imports System.Reflection
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.Collections
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Roslyn.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator
Friend Delegate Function GenerateMethodBody(method As EEMethodSymbol, diagnostics As DiagnosticBag) As BoundStatement
Friend NotInheritable Class EEMethodSymbol
Inherits MethodSymbol
Friend ReadOnly TypeMap As TypeSubstitution
Friend ReadOnly SubstitutedSourceMethod As MethodSymbol
Friend ReadOnly Locals As ImmutableArray(Of LocalSymbol)
Friend ReadOnly LocalsForBinding As ImmutableArray(Of LocalSymbol)
Private ReadOnly _compilation As VisualBasicCompilation
Private ReadOnly _container As EENamedTypeSymbol
Private ReadOnly _name As String
Private ReadOnly _locations As ImmutableArray(Of Location)
Private ReadOnly _typeParameters As ImmutableArray(Of TypeParameterSymbol)
Private ReadOnly _parameters As ImmutableArray(Of ParameterSymbol)
Private ReadOnly _meParameter As ParameterSymbol
Private ReadOnly _displayClassVariables As ImmutableDictionary(Of String, DisplayClassVariable)
Private ReadOnly _voidType As NamedTypeSymbol
''' <summary>
''' Invoked at most once to generate the method body.
''' (If the compilation has no errors, it will be invoked
''' exactly once, otherwise it may be skipped.)
''' </summary>
Private ReadOnly _generateMethodBody As GenerateMethodBody
Private _lazyReturnType As TypeSymbol
' NOTE: This is only used for asserts, so it could be conditional on DEBUG.
Private ReadOnly _allTypeParameters As ImmutableArray(Of TypeParameterSymbol)
Friend Sub New(
compilation As VisualBasicCompilation,
container As EENamedTypeSymbol,
name As String,
location As Location,
sourceMethod As MethodSymbol,
sourceLocals As ImmutableArray(Of LocalSymbol),
sourceLocalsForBinding As ImmutableArray(Of LocalSymbol),
sourceDisplayClassVariables As ImmutableDictionary(Of String, DisplayClassVariable),
voidType As NamedTypeSymbol,
generateMethodBody As GenerateMethodBody)
Debug.Assert(sourceMethod.IsDefinition)
Debug.Assert(sourceMethod.ContainingSymbol = container.SubstitutedSourceType.OriginalDefinition)
Debug.Assert(sourceLocals.All(Function(l) l.ContainingSymbol = sourceMethod))
_compilation = compilation
_container = container
_name = name
_locations = ImmutableArray.Create(location)
_voidType = voidType
' What we want is to map all original type parameters to the corresponding new type parameters
' (since the old ones have the wrong owners). Unfortunately, we have a circular dependency:
' 1) Each new type parameter requires the entire map in order to be able to construct its constraint list.
' 2) The map cannot be constructed until all new type parameters exist.
' Our solution is to pass each new type parameter a lazy reference to the type map. We then
' initialize the map as soon as the new type parameters are available - and before they are
' handed out - so that there is never a period where they can require the type map and find
' it uninitialized.
Dim sourceMethodTypeParameters = sourceMethod.TypeParameters
Dim allSourceTypeParameters = container.SourceTypeParameters.Concat(sourceMethodTypeParameters)
Dim getTypeMap As New Func(Of TypeSubstitution)(Function() TypeMap)
_typeParameters = sourceMethodTypeParameters.SelectAsArray(
Function(tp As TypeParameterSymbol, i As Integer, arg As Object) DirectCast(New EETypeParameterSymbol(Me, tp, i, getTypeMap), TypeParameterSymbol),
DirectCast(Nothing, Object))
_allTypeParameters = container.TypeParameters.Concat(_typeParameters)
Me.TypeMap = TypeSubstitution.Create(sourceMethod, allSourceTypeParameters, ImmutableArrayExtensions.Cast(Of TypeParameterSymbol, TypeSymbol)(_allTypeParameters))
EENamedTypeSymbol.VerifyTypeParameters(Me, _typeParameters)
Dim substitutedSourceType = container.SubstitutedSourceType
Me.SubstitutedSourceMethod = sourceMethod.AsMember(substitutedSourceType)
If _typeParameters.Any() Then
Me.SubstitutedSourceMethod = Me.SubstitutedSourceMethod.Construct(_typeParameters.As(Of TypeSymbol)())
End If
TypeParameterChecker.Check(Me.SubstitutedSourceMethod, _allTypeParameters)
' Create a map from original parameter to target parameter.
Dim parameterBuilder = ArrayBuilder(Of ParameterSymbol).GetInstance()
Dim substitutedSourceMeParameter = Me.SubstitutedSourceMethod.MeParameter
Dim subsitutedSourceHasMeParameter = substitutedSourceMeParameter IsNot Nothing
If subsitutedSourceHasMeParameter Then
_meParameter = MakeParameterSymbol(0, GeneratedNames.MakeStateMachineCapturedMeName(), substitutedSourceMeParameter) ' NOTE: Name doesn't actually matter.
Debug.Assert(_meParameter.Type = Me.SubstitutedSourceMethod.ContainingType)
parameterBuilder.Add(_meParameter)
End If
Dim ordinalOffset = If(subsitutedSourceHasMeParameter, 1, 0)
For Each substitutedSourceParameter In Me.SubstitutedSourceMethod.Parameters
Dim ordinal = substitutedSourceParameter.Ordinal + ordinalOffset
Debug.Assert(ordinal = parameterBuilder.Count)
Dim parameter = MakeParameterSymbol(ordinal, substitutedSourceParameter.Name, substitutedSourceParameter)
parameterBuilder.Add(parameter)
Next
_parameters = parameterBuilder.ToImmutableAndFree()
Dim localsBuilder = ArrayBuilder(Of LocalSymbol).GetInstance()
Dim localsMap = PooledDictionary(Of LocalSymbol, LocalSymbol).GetInstance()
For Each sourceLocal In sourceLocals
Dim local = sourceLocal.ToOtherMethod(Me, Me.TypeMap)
localsMap.Add(sourceLocal, local)
localsBuilder.Add(local)
Next
Me.Locals = localsBuilder.ToImmutableAndFree()
localsBuilder = ArrayBuilder(Of LocalSymbol).GetInstance()
For Each sourceLocal In sourceLocalsForBinding
Dim local As LocalSymbol = Nothing
If Not localsMap.TryGetValue(sourceLocal, local) Then
local = sourceLocal.ToOtherMethod(Me, Me.TypeMap)
localsMap.Add(sourceLocal, local)
End If
localsBuilder.Add(local)
Next
Me.LocalsForBinding = localsBuilder.ToImmutableAndFree()
' Create a map from variable name to display class field.
Dim displayClassVariables = PooledDictionary(Of String, DisplayClassVariable).GetInstance()
For Each pair In sourceDisplayClassVariables
Dim variable = pair.Value
Dim displayClassInstanceFromLocal = TryCast(variable.DisplayClassInstance, DisplayClassInstanceFromLocal)
Dim displayClassInstance = If(displayClassInstanceFromLocal Is Nothing,
DirectCast(New DisplayClassInstanceFromMe(Me.Parameters(0)), DisplayClassInstance),
New DisplayClassInstanceFromLocal(DirectCast(localsMap(displayClassInstanceFromLocal.Local), EELocalSymbol)))
variable = variable.SubstituteFields(displayClassInstance, Me.TypeMap)
displayClassVariables.Add(pair.Key, variable)
Next
_displayClassVariables = displayClassVariables.ToImmutableDictionary()
displayClassVariables.Free()
localsMap.Free()
_generateMethodBody = generateMethodBody
End Sub
Private Function MakeParameterSymbol(ordinal As Integer, name As String, sourceParameter As ParameterSymbol) As ParameterSymbol
Return New SynthesizedParameterSymbolWithCustomModifiers(
Me,
sourceParameter.Type,
ordinal,
sourceParameter.IsByRef,
name,
sourceParameter.CustomModifiers,
sourceParameter.HasByRefBeforeCustomModifiers)
End Function
Public Overrides ReadOnly Property MethodKind As MethodKind
Get
Return MethodKind.Ordinary
End Get
End Property
Public Overrides ReadOnly Property Name As String
Get
Return _name
End Get
End Property
Public Overrides ReadOnly Property Arity As Integer
Get
Return _typeParameters.Length
End Get
End Property
Public Overrides ReadOnly Property IsExtensionMethod As Boolean
Get
Return False
End Get
End Property
Friend Overrides ReadOnly Property HasSpecialName As Boolean
Get
Return True
End Get
End Property
Friend Overrides ReadOnly Property ImplementationAttributes As MethodImplAttributes
Get
Return Nothing
End Get
End Property
Friend Overrides ReadOnly Property HasDeclarativeSecurity As Boolean
Get
Return False
End Get
End Property
Public Overrides Function GetDllImportData() As DllImportData
Return Nothing
End Function
Friend Overrides Function GetSecurityInformation() As IEnumerable(Of Microsoft.Cci.SecurityAttribute)
Throw ExceptionUtilities.Unreachable
End Function
Friend Overrides ReadOnly Property ReturnTypeMarshallingInformation As MarshalPseudoCustomAttributeData
Get
Return Nothing
End Get
End Property
Friend Overrides Function TryGetMeParameter(<Out> ByRef meParameter As ParameterSymbol) As Boolean
meParameter = Nothing
Return True
End Function
Public Overrides ReadOnly Property IsVararg As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsSub As Boolean
Get
Return ReturnType.SpecialType = SpecialType.System_Void
End Get
End Property
Public Overrides ReadOnly Property IsAsync As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property ReturnType As TypeSymbol
Get
If _lazyReturnType Is Nothing Then
Throw New InvalidOperationException()
End If
Return _lazyReturnType
End Get
End Property
Public Overrides ReadOnly Property TypeArguments As ImmutableArray(Of TypeSymbol)
Get
Return ImmutableArrayExtensions.Cast(Of TypeParameterSymbol, TypeSymbol)(_typeParameters)
End Get
End Property
Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol)
Get
Return _typeParameters
End Get
End Property
Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol)
Get
Return _parameters
End Get
End Property
Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of MethodSymbol)
Get
Return ImmutableArray(Of MethodSymbol).Empty
End Get
End Property
Public Overrides ReadOnly Property ReturnTypeCustomModifiers As ImmutableArray(Of CustomModifier)
Get
Return ImmutableArray(Of CustomModifier).Empty
End Get
End Property
Public Overrides ReadOnly Property AssociatedSymbol As Symbol
Get
Return Nothing
End Get
End Property
Friend Overrides Function GetAppliedConditionalSymbols() As ImmutableArray(Of String)
Throw ExceptionUtilities.Unreachable
End Function
Friend Overrides ReadOnly Property CallingConvention As Cci.CallingConvention
Get
Debug.Assert(Me.IsShared)
Dim cc = Cci.CallingConvention.Default
If Me.IsVararg Then
cc = cc Or Cci.CallingConvention.ExtraArguments
End If
If Me.IsGenericMethod Then
cc = cc Or Cci.CallingConvention.Generic
End If
Return cc
End Get
End Property
Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property ContainingSymbol As Symbol
Get
Return _container
End Get
End Property
Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location)
Get
Return _locations
End Get
End Property
Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference)
Get
Throw ExceptionUtilities.Unreachable
End Get
End Property
Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility
Get
Return Accessibility.Internal
End Get
End Property
Public Overrides ReadOnly Property IsShared As Boolean
Get
Return True
End Get
End Property
Public Overrides ReadOnly Property IsOverridable As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsOverrides As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsMustOverride As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsNotOverridable As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsExternalMethod As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsIterator As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsOverloads As Boolean
Get
Return False
End Get
End Property
Friend Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData
Get
Throw ExceptionUtilities.Unreachable
End Get
End Property
Friend Overrides ReadOnly Property IsMethodKindBasedOnSyntax As Boolean
Get
Return False
End Get
End Property
Friend Overrides ReadOnly Property Syntax As VisualBasicSyntaxNode
Get
Return Nothing
End Get
End Property
#Disable Warning RS0010
''' <remarks>
''' The corresponding C# method,
''' <see cref="M:Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.EEMethodSymbol.GenerateMethodBody(Microsoft.CodeAnalysis.CSharp.TypeCompilationState,Microsoft.CodeAnalysis.DiagnosticBag)"/>,
''' invokes the <see cref="LocalRewriter"/> and the <see cref="LambdaRewriter"/> explicitly.
''' In VB, the caller (of this method) does that.
''' </remarks>
#Enable Warning RS0010
Friend Overrides Function GetBoundMethodBody(diagnostics As DiagnosticBag, <Out> ByRef Optional methodBodyBinder As Binder = Nothing) As BoundBlock
Dim body = _generateMethodBody(Me, diagnostics)
Debug.Assert(body IsNot Nothing)
_lazyReturnType = CalculateReturnType(body)
' Can't do this until the return type has been computed.
TypeParameterChecker.Check(Me, _allTypeParameters)
Dim syntax As VisualBasicSyntaxNode = body.Syntax
Dim statementsBuilder = ArrayBuilder(Of BoundStatement).GetInstance()
statementsBuilder.Add(body)
' Insert an implicit return statement if necessary.
If body.Kind <> BoundKind.ReturnStatement Then
statementsBuilder.Add(New BoundReturnStatement(syntax, Nothing, Nothing, Nothing))
End If
Dim originalLocalsBuilder = ArrayBuilder(Of LocalSymbol).GetInstance()
Dim originalLocalsSet = PooledHashSet(Of LocalSymbol).GetInstance()
For Each local In LocalsForBinding
Debug.Assert(Not originalLocalsSet.Contains(local))
originalLocalsBuilder.Add(local)
originalLocalsSet.Add(local)
Next
For Each local In Me.Locals
If Not originalLocalsSet.Contains(local) Then
originalLocalsBuilder.Add(local)
End If
Next
originalLocalsSet.Free()
Dim originalLocals = originalLocalsBuilder.ToImmutableAndFree()
Dim newBody = New BoundBlock(syntax, Nothing, originalLocals, statementsBuilder.ToImmutableAndFree())
If diagnostics.HasAnyErrors() Then
Return newBody
End If
DiagnosticsPass.IssueDiagnostics(newBody, diagnostics, Me)
If diagnostics.HasAnyErrors() Then
Return newBody
End If
' Check for use-site errors (e.g. missing types in the signature).
Dim useSiteInfo As DiagnosticInfo = Me.CalculateUseSiteErrorInfo()
If useSiteInfo IsNot Nothing Then
diagnostics.Add(useSiteInfo, _locations(0))
Return newBody
End If
Debug.Assert(Not newBody.HasErrors)
' NOTE: In C#, EE rewriting happens AFTER local rewriting. However, that order would be difficult
' to accommodate in VB, so we reverse it.
' Rewrite local declaration statement.
newBody = LocalDeclarationRewriter.Rewrite(_compilation, _container, newBody)
' Rewrite pseudo-variable references to helper method calls.
newBody = DirectCast(PlaceholderLocalRewriter.Rewrite(_compilation, _container, newBody), BoundBlock)
' Create a map from original local to target local.
Dim localMap = PooledDictionary(Of LocalSymbol, LocalSymbol).GetInstance()
Dim targetLocals = newBody.Locals
Debug.Assert(originalLocals.Length = targetLocals.Length)
For i = 0 To originalLocals.Length - 1
Dim originalLocal = originalLocals(i)
Dim targetLocal = targetLocals(i)
Debug.Assert(TypeOf originalLocal IsNot EELocalSymbol OrElse
DirectCast(originalLocal, EELocalSymbol).Ordinal = DirectCast(targetLocal, EELocalSymbol).Ordinal)
localMap.Add(originalLocal, targetLocal)
Next
' Variables may have been captured by lambdas in the original method
' or in the expression, and we need to preserve the existing values of
' those variables in the expression. This requires rewriting the variables
' in the expression based on the closure classes from both the original
' method and the expression, and generating a preamble that copies
' values into the expression closure classes.
'
' Consider the original method:
' Shared Sub M()
' Dim x, y, z as Integer
' ...
' F(Function() x + y)
' End Sub
' and the expression in the EE: "F(Function() x + z)".
'
' The expression is first rewritten using the closure class and local <1>
' from the original method: F(Function() <1>.x + z)
' Then lambda rewriting introduces a new closure class that includes
' the locals <1> and z, and a corresponding local <2>: F(Function() <2>.<1>.x + <2>.z)
' And a preamble is added to initialize the fields of <2>:
' <2> = New <>c__DisplayClass0()
' <2>.<1> = <1>
' <2>.z = z
' Create a map from variable name to display class field.
Dim displayClassVariables = PooledDictionary(Of String, DisplayClassVariable).GetInstance()
For Each pair In _displayClassVariables
Dim variable = pair.Value
Dim displayClassInstanceFromLocal = TryCast(variable.DisplayClassInstance, DisplayClassInstanceFromLocal)
Dim displayClassInstance = If(displayClassInstanceFromLocal Is Nothing,
DirectCast(New DisplayClassInstanceFromMe(Me.Parameters(0)), DisplayClassInstance),
New DisplayClassInstanceFromLocal(DirectCast(localMap(displayClassInstanceFromLocal.Local), EELocalSymbol)))
variable = New DisplayClassVariable(variable.Name, variable.Kind, displayClassInstance, variable.DisplayClassFields)
displayClassVariables.Add(pair.Key, variable)
Next
' Rewrite references to "Me" to refer to this method's "Me" parameter.
' Rewrite variables within body to reference existing display classes.
newBody = DirectCast(CapturedVariableRewriter.Rewrite(
If(Me.SubstitutedSourceMethod.IsShared, Nothing, Me.Parameters(0)),
displayClassVariables.ToImmutableDictionary(),
newBody,
diagnostics), BoundBlock)
displayClassVariables.Free()
If diagnostics.HasAnyErrors() Then
Return newBody
End If
' Insert locals from the original method, followed by any new locals.
Dim localBuilder = ArrayBuilder(Of LocalSymbol).GetInstance()
For Each originalLocal In Me.Locals
Dim targetLocal = localMap(originalLocal)
Debug.Assert(TypeOf targetLocal IsNot EELocalSymbol OrElse DirectCast(targetLocal, EELocalSymbol).Ordinal = localBuilder.Count)
localBuilder.Add(targetLocal)
Next
localMap.Free()
newBody = newBody.Update(newBody.StatementListSyntax, localBuilder.ToImmutableAndFree(), newBody.Statements)
TypeParameterChecker.Check(newBody, _allTypeParameters)
Return newBody
End Function
Private Function CalculateReturnType(body As BoundStatement) As TypeSymbol
Select Case body.Kind
Case BoundKind.ReturnStatement
Return DirectCast(body, BoundReturnStatement).ExpressionOpt.Type
Case BoundKind.ExpressionStatement,
BoundKind.RedimStatement
Return _voidType
Case Else
Throw ExceptionUtilities.UnexpectedValue(body.Kind)
End Select
End Function
Friend Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer
Throw ExceptionUtilities.Unreachable
End Function
End Class
End Namespace
|
DavidKarlas/roslyn
|
src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/EEMethodSymbol.vb
|
Visual Basic
|
apache-2.0
| 24,290
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Composition
Imports Microsoft.ApiDesignGuidelines.Analyzers
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.VisualBasic
Namespace Microsoft.ApiDesignGuidelines.VisualBasic.Analyzers
' <summary>
' CA1008: Enums should have zero value
' </summary>
<ExportCodeFixProvider(LanguageNames.VisualBasic), [Shared]>
Public Class BasicEnumsShouldHaveZeroValueFixer
Inherits EnumsShouldHaveZeroValueFixer
Protected Overrides Function GetParentNodeOrSelfToFix(nodeToFix As SyntaxNode) As SyntaxNode
If nodeToFix.IsKind(SyntaxKind.EnumStatement) And nodeToFix.Parent IsNot Nothing Then
Return nodeToFix.Parent
End If
Return nodeToFix
End Function
End Class
End Namespace
|
natidea/roslyn-analyzers
|
src/Microsoft.CodeQuality.Analyzers/VisualBasic/ApiDesignGuidelines/BasicEnumsShouldHaveZeroValue.Fixer.vb
|
Visual Basic
|
apache-2.0
| 995
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Threading
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic
Friend NotInheritable Class LazyObsoleteDiagnosticInfo
Inherits DiagnosticInfo
Private lazyActualObsoleteDiagnostic As DiagnosticInfo
Private ReadOnly m_symbol As Symbol
Private ReadOnly m_containingSymbol As Symbol
Friend Sub New(sym As Symbol, containingSymbol As Symbol)
MyBase.New(VisualBasic.MessageProvider.Instance, ERRID.Unknown)
Me.m_symbol = sym
Me.m_containingSymbol = containingSymbol
End Sub
Friend Overrides Function GetResolvedInfo() As DiagnosticInfo
If lazyActualObsoleteDiagnostic Is Nothing Then
' A symbol's Obsoleteness may not have been calculated yet if the symbol is coming
' from a different compilation's source. In that case, force completion of attributes.
m_symbol.ForceCompleteObsoleteAttribute()
If m_symbol.ObsoleteState = ThreeState.True Then
Dim inObsoleteContext = ObsoleteAttributeHelpers.GetObsoleteContextState(m_containingSymbol, forceComplete:=True)
Debug.Assert(inObsoleteContext <> ThreeState.Unknown)
If inObsoleteContext = ThreeState.False Then
Dim info As DiagnosticInfo = ObsoleteAttributeHelpers.CreateObsoleteDiagnostic(m_symbol)
If info IsNot Nothing Then
Interlocked.CompareExchange(Me.lazyActualObsoleteDiagnostic, info, Nothing)
Return Me.lazyActualObsoleteDiagnostic
End If
End If
End If
' If this symbol is not obsolete or is in an obsolete context, we don't want to report any diagnostics.
' Therefore make this a Void diagnostic.
Interlocked.CompareExchange(Me.lazyActualObsoleteDiagnostic, ErrorFactory.VoidDiagnosticInfo, Nothing)
End If
Return lazyActualObsoleteDiagnostic
End Function
End Class
End Namespace
|
DavidKarlas/roslyn
|
src/Compilers/VisualBasic/Portable/Errors/LazyObsoleteDiagnosticInfo.vb
|
Visual Basic
|
apache-2.0
| 2,344
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Collections.Immutable
Imports System.Diagnostics
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend NotInheritable Class LocalRewriter
Public Overrides Function VisitSyncLockStatement(node As BoundSyncLockStatement) As BoundNode
Dim statements = ArrayBuilder(Of BoundStatement).GetInstance
Dim syntaxNode = DirectCast(node.Syntax, SyncLockBlockSyntax)
' rewrite the lock expression.
Dim visitedLockExpression = VisitExpressionNode(node.LockExpression)
Dim objectType = GetSpecialType(SpecialType.System_Object)
Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing
Dim conversionKind = Conversions.ClassifyConversion(visitedLockExpression.Type, objectType, useSiteDiagnostics).Key
_diagnostics.Add(node, useSiteDiagnostics)
' when passing this boundlocal to Monitor.Enter and Monitor.Exit we need to pass a local of type object, because the parameter
' are of type object. We also do not want to have this conversion being shown in the semantic model, which is why we add it
' during rewriting. Because only reference types are allowed for synclock, this is always guaranteed to succeed.
' This also unboxes a type parameter, so that the same object is passed to both methods.
If Not Conversions.IsIdentityConversion(conversionKind) Then
Dim integerOverflow As Boolean
Dim constantResult = Conversions.TryFoldConstantConversion(
visitedLockExpression,
objectType,
integerOverflow)
visitedLockExpression = TransformRewrittenConversion(New BoundConversion(node.LockExpression.Syntax,
visitedLockExpression,
conversionKind,
False,
False,
constantResult,
objectType))
End If
' create a new temp local for the lock object
Dim tempLockObjectLocal As LocalSymbol = New SynthesizedLocal(Me._currentMethodOrLambda, objectType, SynthesizedLocalKind.Lock, syntaxNode.SyncLockStatement)
Dim boundLockObjectLocal = New BoundLocal(syntaxNode,
tempLockObjectLocal,
objectType)
Dim instrument As Boolean = Me.Instrument(node)
If instrument Then
' create a sequence point that contains the whole SyncLock statement as the first reachable sequence point
' of the SyncLock statement.
Dim prologue = _instrumenterOpt.CreateSyncLockStatementPrologue(node)
If prologue IsNot Nothing Then
statements.Add(prologue)
End If
End If
' assign the lock expression / object to it to avoid changes to it
Dim tempLockObjectAssignment As BoundStatement = New BoundAssignmentOperator(syntaxNode,
boundLockObjectLocal,
visitedLockExpression,
suppressObjectClone:=True,
type:=objectType).ToStatement
boundLockObjectLocal = boundLockObjectLocal.MakeRValue()
If ShouldGenerateUnstructuredExceptionHandlingResumeCode(node) Then
tempLockObjectAssignment = RegisterUnstructuredExceptionHandlingResumeTarget(syntaxNode, tempLockObjectAssignment, canThrow:=True)
End If
Dim saveState As UnstructuredExceptionHandlingContext = LeaveUnstructuredExceptionHandlingContext(node)
If instrument Then
tempLockObjectAssignment = _instrumenterOpt.InstrumentSyncLockObjectCapture(node, tempLockObjectAssignment)
End If
statements.Add(tempLockObjectAssignment)
' If the type of the lock object is System.Object we need to call the vb runtime helper
' Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.CheckForSyncLockOnValueType to ensure no value type is
' used. Note that we are checking type on original bound node for LockExpression because rewritten node will
' always have System.Object as its type due to conversion added above.
' If helper not available on this platform (/vbruntime*), don't call this helper and do not report errors.
Dim checkForSyncLockOnValueTypeMethod As MethodSymbol = Nothing
If node.LockExpression.Type.IsObjectType() AndAlso
TryGetWellknownMember(checkForSyncLockOnValueTypeMethod, WellKnownMember.Microsoft_VisualBasic_CompilerServices_ObjectFlowControl__CheckForSyncLockOnValueType, syntaxNode, isOptional:=True) Then
Dim boundHelperCall = New BoundCall(syntaxNode,
checkForSyncLockOnValueTypeMethod,
Nothing,
Nothing,
ImmutableArray.Create(Of BoundExpression)(boundLockObjectLocal),
Nothing,
checkForSyncLockOnValueTypeMethod.ReturnType,
suppressObjectClone:=True)
Dim boundHelperCallStatement = boundHelperCall.ToStatement
boundHelperCallStatement.SetWasCompilerGenerated() ' used to not create sequence points
statements.Add(boundHelperCallStatement)
End If
Dim locals As ImmutableArray(Of LocalSymbol)
Dim boundLockTakenLocal As BoundLocal = Nothing
Dim tempLockTakenAssignment As BoundStatement = Nothing
Dim tryStatements As ImmutableArray(Of BoundStatement)
Dim boundMonitorEnterCallStatement As BoundStatement = GenerateMonitorEnter(node.LockExpression.Syntax, boundLockObjectLocal, boundLockTakenLocal, tempLockTakenAssignment)
' the new Monitor.Enter call will be inside the try block, the old is outside
If boundLockTakenLocal IsNot Nothing Then
locals = ImmutableArray.Create(Of LocalSymbol)(tempLockObjectLocal, boundLockTakenLocal.LocalSymbol)
statements.Add(tempLockTakenAssignment)
tryStatements = ImmutableArray.Create(Of BoundStatement)(boundMonitorEnterCallStatement,
DirectCast(Visit(node.Body), BoundBlock))
Else
locals = ImmutableArray.Create(tempLockObjectLocal)
statements.Add(boundMonitorEnterCallStatement)
tryStatements = ImmutableArray.Create(Of BoundStatement)(DirectCast(Visit(node.Body), BoundBlock))
End If
' rewrite the SyncLock body
Dim tryBody As BoundBlock = New BoundBlock(syntaxNode,
Nothing,
ImmutableArray(Of LocalSymbol).Empty,
tryStatements)
Dim statementInFinally As BoundStatement = GenerateMonitorExit(syntaxNode, boundLockObjectLocal, boundLockTakenLocal)
Dim finallyBody As BoundBlock = New BoundBlock(syntaxNode,
Nothing,
ImmutableArray(Of LocalSymbol).Empty,
ImmutableArray.Create(Of BoundStatement)(statementInFinally))
If instrument Then
' Add a sequence point to highlight the "End SyncLock" syntax in case the body has thrown an exception
finallyBody = DirectCast(Concat(finallyBody, _instrumenterOpt.CreateSyncLockExitDueToExceptionEpilogue(node)), BoundBlock)
End If
Dim rewrittenSyncLock = RewriteTryStatement(syntaxNode, tryBody, ImmutableArray(Of BoundCatchBlock).Empty, finallyBody, Nothing)
statements.Add(rewrittenSyncLock)
If instrument Then
' Add a sequence point to highlight the "End SyncLock" syntax in case the body has been complete executed and
' exited normally
Dim epilogue = _instrumenterOpt.CreateSyncLockExitNormallyEpilogue(node)
If epilogue IsNot Nothing Then
statements.Add(epilogue)
End If
End If
RestoreUnstructuredExceptionHandlingContext(node, saveState)
Return New BoundBlock(syntaxNode,
Nothing,
locals,
statements.ToImmutableAndFree)
End Function
Private Function GenerateMonitorEnter(
syntaxNode As SyntaxNode,
boundLockObject As BoundExpression,
<Out> ByRef boundLockTakenLocal As BoundLocal,
<Out> ByRef boundLockTakenInitialization As BoundStatement
) As BoundStatement
boundLockTakenLocal = Nothing
boundLockTakenInitialization = Nothing
Dim parameters As ImmutableArray(Of BoundExpression)
' Figure out what Enter method to call from Monitor.
' In case the "new" Monitor.Enter(Object, ByRef Boolean) method is found, use that one,
' otherwise fall back to the Monitor.Enter() method.
Dim enterMethod As MethodSymbol = Nothing
If TryGetWellknownMember(enterMethod, WellKnownMember.System_Threading_Monitor__Enter2, syntaxNode, isOptional:=True) Then
' create local for the lockTaken boolean and initialize it with "False"
Dim tempLockTaken As LocalSymbol
If syntaxNode.Parent.Kind = SyntaxKind.SyncLockStatement Then
tempLockTaken = New SynthesizedLocal(Me._currentMethodOrLambda, enterMethod.Parameters(1).Type, SynthesizedLocalKind.LockTaken, DirectCast(syntaxNode.Parent, SyncLockStatementSyntax))
Else
tempLockTaken = New SynthesizedLocal(Me._currentMethodOrLambda, enterMethod.Parameters(1).Type, SynthesizedLocalKind.LoweringTemp)
End If
Debug.Assert(tempLockTaken.Type.IsBooleanType())
boundLockTakenLocal = New BoundLocal(syntaxNode, tempLockTaken, tempLockTaken.Type)
boundLockTakenInitialization = New BoundAssignmentOperator(syntaxNode,
boundLockTakenLocal,
New BoundLiteral(syntaxNode, ConstantValue.False, boundLockTakenLocal.Type),
suppressObjectClone:=True,
type:=boundLockTakenLocal.Type).ToStatement
boundLockTakenInitialization.SetWasCompilerGenerated() ' used to not create sequence points
parameters = ImmutableArray.Create(Of BoundExpression)(boundLockObject, boundLockTakenLocal)
boundLockTakenLocal = boundLockTakenLocal.MakeRValue()
Else
TryGetWellknownMember(enterMethod, WellKnownMember.System_Threading_Monitor__Enter, syntaxNode)
parameters = ImmutableArray.Create(Of BoundExpression)(boundLockObject)
End If
If enterMethod IsNot Nothing Then
' create a call to void Enter(object)
Dim boundMonitorEnterCall As BoundExpression
boundMonitorEnterCall = New BoundCall(syntaxNode,
enterMethod,
Nothing,
Nothing,
parameters,
Nothing,
enterMethod.ReturnType,
suppressObjectClone:=True)
Dim boundMonitorEnterCallStatement = boundMonitorEnterCall.ToStatement
boundMonitorEnterCallStatement.SetWasCompilerGenerated() ' used to not create sequence points
Return boundMonitorEnterCallStatement
End If
Return New BoundBadExpression(syntaxNode, LookupResultKind.NotReferencable, ImmutableArray(Of Symbol).Empty, parameters, ErrorTypeSymbol.UnknownResultType, hasErrors:=True).ToStatement()
End Function
Private Function GenerateMonitorExit(
syntaxNode As SyntaxNode,
boundLockObject As BoundExpression,
boundLockTakenLocal As BoundLocal
) As BoundStatement
Dim statementInFinally As BoundStatement
Dim boundMonitorExitCall As BoundExpression
Dim exitMethod As MethodSymbol = Nothing
If TryGetWellknownMember(exitMethod, WellKnownMember.System_Threading_Monitor__Exit, syntaxNode) Then
' create a call to void Monitor.Exit(object)
boundMonitorExitCall = New BoundCall(syntaxNode,
exitMethod,
Nothing,
Nothing,
ImmutableArray.Create(Of BoundExpression)(boundLockObject),
Nothing,
exitMethod.ReturnType,
suppressObjectClone:=True)
Else
boundMonitorExitCall = New BoundBadExpression(syntaxNode, LookupResultKind.NotReferencable, ImmutableArray(Of Symbol).Empty, ImmutableArray.Create(boundLockObject), ErrorTypeSymbol.UnknownResultType, hasErrors:=True)
End If
Dim boundMonitorExitCallStatement = boundMonitorExitCall.ToStatement
boundMonitorExitCallStatement.SetWasCompilerGenerated() ' used to not create sequence points
If boundLockTakenLocal IsNot Nothing Then
Debug.Assert(boundLockTakenLocal.Type.IsBooleanType())
' if the "new" enter method is used we need to check the temporary boolean to see if the lock was really taken.
' (maybe there was an exception after try and before the enter call).
Dim boundCondition = New BoundBinaryOperator(syntaxNode,
BinaryOperatorKind.Equals,
boundLockTakenLocal,
New BoundLiteral(syntaxNode, ConstantValue.True, boundLockTakenLocal.Type),
False,
boundLockTakenLocal.Type)
statementInFinally = RewriteIfStatement(syntaxNode, boundCondition, boundMonitorExitCallStatement, Nothing, instrumentationTargetOpt:=Nothing)
Else
statementInFinally = boundMonitorExitCallStatement
End If
Return statementInFinally
End Function
End Class
End Namespace
|
yeaicc/roslyn
|
src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_SyncLock.vb
|
Visual Basic
|
apache-2.0
| 16,832
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Namespace Microsoft.CodeAnalysis.PasteTracking
<UseExportProvider>
Public Class PasteTrackingServiceTests
Private Const Project1Name = "Proj1"
Private Const Project2Name = "Proj2"
Private Const Class1Name = "Class1.cs"
Private Const Class2Name = "Class2.cs"
Private Const PastedCode As String = "
public void Main(string[] args)
{
}"
Private Const UnformattedPastedCode As String = "
public void Main(string[] args)
{
}"
Private ReadOnly Property SingleFileCode As XElement =
<Workspace>
<Project Language="C#" CommonReferences="True" AssemblyName="Proj1">
<Document FilePath="Class1.cs">
public class Class1
{
$$
}
</Document>
</Project>
</Workspace>
Private ReadOnly Property MultiFileCode As XElement =
<Workspace>
<Project Language="C#" CommonReferences="True" AssemblyName=<%= Project1Name %>>
<Document FilePath=<%= Class1Name %>>
public class Class1
{
$$
}
</Document>
<Document FilePath=<%= Class2Name %>>
public class Class2
{
public const string Greeting = "Hello";
$$
}
</Document>
</Project>
<Project Language="C#" CommonReferences="True" AssemblyName=<%= Project2Name %>>
<Document IsLinkFile="True" LinkAssemblyName="Proj1" LinkFilePath=<%= Class1Name %>/>
</Project>
</Workspace>
<WpfFact>
<Trait(Traits.Feature, Traits.Features.PasteTracking)>
Public Async Function PasteTracking_MissingTextSpan_WhenNothingPasted() As Task
Using testState = New PasteTrackingTestState(SingleFileCode)
Dim class1Document = testState.OpenDocument(Project1Name, Class1Name)
Await testState.AssertMissingPastedTextSpanAsync(class1Document)
End Using
End Function
<WpfFact>
<Trait(Traits.Feature, Traits.Features.PasteTracking)>
Public Async Function PasteTracking_HasTextSpan_AfterPaste() As Task
Using testState = New PasteTrackingTestState(SingleFileCode)
Dim class1Document = testState.OpenDocument(Project1Name, Class1Name)
Dim expectedTextSpan = testState.SendPaste(class1Document, PastedCode)
Await testState.AssertHasPastedTextSpanAsync(class1Document, expectedTextSpan)
End Using
End Function
<WpfFact>
<Trait(Traits.Feature, Traits.Features.PasteTracking)>
Public Async Function PasteTracking_HasTextSpan_AfterFormattingPaste() As Task
Using testState = New PasteTrackingTestState(SingleFileCode)
Dim class1Document = testState.OpenDocument(Project1Name, Class1Name)
Dim expectedTextSpan = testState.SendPaste(class1Document, UnformattedPastedCode)
Await testState.AssertHasPastedTextSpanAsync(class1Document, expectedTextSpan)
End Using
End Function
<WpfFact>
<Trait(Traits.Feature, Traits.Features.PasteTracking)>
Public Async Function PasteTracking_HasTextSpan_AfterMultiplePastes() As Task
Using testState = New PasteTrackingTestState(SingleFileCode)
Dim class1Document = testState.OpenDocument(Project1Name, Class1Name)
Dim firstTextSpan = testState.SendPaste(class1Document, PastedCode)
Dim expectedTextSpan = testState.SendPaste(class1Document, PastedCode)
Assert.NotEqual(firstTextSpan, expectedTextSpan)
Await testState.AssertHasPastedTextSpanAsync(class1Document, expectedTextSpan)
End Using
End Function
<WpfFact>
<Trait(Traits.Feature, Traits.Features.PasteTracking)>
Public Async Function PasteTracking_MissingTextSpan_AfterPasteThenEdit() As Task
Using testState = New PasteTrackingTestState(SingleFileCode)
Dim class1Document = testState.OpenDocument(Project1Name, Class1Name)
testState.SendPaste(class1Document, PastedCode)
testState.InsertText(class1Document, "Foo")
Await testState.AssertMissingPastedTextSpanAsync(class1Document)
End Using
End Function
<WpfFact>
<Trait(Traits.Feature, Traits.Features.PasteTracking)>
Public Async Function PasteTracking_MissingTextSpan_AfterPasteThenClose() As Task
Using testState = New PasteTrackingTestState(SingleFileCode)
Dim class1Document = testState.OpenDocument(Project1Name, Class1Name)
testState.SendPaste(class1Document, PastedCode)
testState.CloseDocument(class1Document)
Await testState.AssertMissingPastedTextSpanAsync(class1Document)
End Using
End Function
<WpfFact>
<Trait(Traits.Feature, Traits.Features.PasteTracking)>
Public Async Function PasteTracking_MissingTextSpan_AfterPasteThenCloseThenOpen() As Task
Using testState = New PasteTrackingTestState(SingleFileCode)
Dim class1Document = testState.OpenDocument(Project1Name, Class1Name)
testState.SendPaste(class1Document, PastedCode)
testState.CloseDocument(class1Document)
testState.OpenDocument(class1Document)
Await testState.AssertMissingPastedTextSpanAsync(class1Document)
End Using
End Function
<WpfFact>
<Trait(Traits.Feature, Traits.Features.PasteTracking)>
Public Async Function PasteTracking_HasTextSpan_AfterPasteThenCloseThenOpenThenPaste() As Task
Using testState = New PasteTrackingTestState(SingleFileCode)
Dim class1Document = testState.OpenDocument(Project1Name, Class1Name)
testState.SendPaste(class1Document, PastedCode)
testState.CloseDocument(class1Document)
testState.OpenDocument(class1Document)
Dim expectedTextSpan = testState.SendPaste(class1Document, PastedCode)
Await testState.AssertHasPastedTextSpanAsync(class1Document, expectedTextSpan)
End Using
End Function
<WpfFact>
<Trait(Traits.Feature, Traits.Features.PasteTracking)>
Public Async Function PasteTracking_HasMultipleTextSpan_AfterPasteInMultipleFiles() As Task
Using testState = New PasteTrackingTestState(MultiFileCode)
Dim class1Document = testState.OpenDocument(Project1Name, Class1Name)
Dim class2Document = testState.OpenDocument(Project1Name, Class2Name)
Dim expectedClass1TextSpan = testState.SendPaste(class1Document, PastedCode)
Dim expectedClass2TextSpan = testState.SendPaste(class2Document, PastedCode)
Assert.NotEqual(expectedClass1TextSpan, expectedClass2TextSpan)
Await testState.AssertHasPastedTextSpanAsync(class1Document, expectedClass1TextSpan)
Await testState.AssertHasPastedTextSpanAsync(class2Document, expectedClass2TextSpan)
End Using
End Function
<WpfFact>
<Trait(Traits.Feature, Traits.Features.PasteTracking)>
Public Async Function PasteTracking_HasSingleTextSpan_AfterPasteInMultipleFilesThenOneClosed() As Task
Using testState = New PasteTrackingTestState(MultiFileCode)
Dim class1Document = testState.OpenDocument(Project1Name, Class1Name)
Dim class2Document = testState.OpenDocument(Project1Name, Class2Name)
testState.SendPaste(class1Document, PastedCode)
Dim expectedClass2TextSpan = testState.SendPaste(class2Document, PastedCode)
testState.CloseDocument(class1Document)
Await testState.AssertMissingPastedTextSpanAsync(class1Document)
Await testState.AssertHasPastedTextSpanAsync(class2Document, expectedClass2TextSpan)
End Using
End Function
<WpfFact>
<Trait(Traits.Feature, Traits.Features.PasteTracking)>
Public Async Function PasteTracking_MissingTextSpan_AfterPasteInMultipleFilesThenAllClosed() As Task
Using testState = New PasteTrackingTestState(MultiFileCode)
Dim class1Document = testState.OpenDocument(Project1Name, Class1Name)
Dim class2Document = testState.OpenDocument(Project1Name, Class2Name)
testState.SendPaste(class1Document, PastedCode)
testState.SendPaste(class2Document, PastedCode)
testState.CloseDocument(class1Document)
testState.CloseDocument(class2Document)
Await testState.AssertMissingPastedTextSpanAsync(class1Document)
Await testState.AssertMissingPastedTextSpanAsync(class2Document)
End Using
End Function
<WpfFact>
<Trait(Traits.Feature, Traits.Features.PasteTracking)>
Public Async Function PasteTracking_HasTextSpanInLinkedFile_AfterPaste() As Task
Using testState = New PasteTrackingTestState(MultiFileCode)
Dim class1Document = testState.OpenDocument(Project1Name, Class1Name)
Dim class1LinkedDocument = testState.OpenDocument(Project2Name, Class1Name)
Dim expectedClass1TextSpan = testState.SendPaste(class1Document, PastedCode)
Await testState.AssertHasPastedTextSpanAsync(class1LinkedDocument, expectedClass1TextSpan)
End Using
End Function
<WpfFact>
<Trait(Traits.Feature, Traits.Features.PasteTracking)>
Public Async Function PasteTracking_HasTextSpanInLinkedFile_AfterPasteThenClose() As Task
Using testState = New PasteTrackingTestState(MultiFileCode)
Dim class1Document = testState.OpenDocument(Project1Name, Class1Name)
Dim class1LinkedDocument = testState.OpenDocument(Project2Name, Class1Name)
Dim expectedClass1TextSpan = testState.SendPaste(class1Document, PastedCode)
testState.CloseDocument(class1Document)
Await testState.AssertHasPastedTextSpanAsync(class1LinkedDocument, expectedClass1TextSpan)
End Using
End Function
<WpfFact>
<Trait(Traits.Feature, Traits.Features.PasteTracking)>
Public Async Function PasteTracking_MissingTextSpanForLinkedFile_AfterPasteThenCloseAll() As Task
Using testState = New PasteTrackingTestState(MultiFileCode)
Dim class1Document = testState.OpenDocument(Project1Name, Class1Name)
Dim class1LinkedDocument = testState.OpenDocument(Project2Name, Class1Name)
testState.SendPaste(class1Document, PastedCode)
testState.CloseDocument(class1Document)
testState.CloseDocument(class1LinkedDocument)
Await testState.AssertMissingPastedTextSpanAsync(class1LinkedDocument)
End Using
End Function
<WpfFact>
<Trait(Traits.Feature, Traits.Features.PasteTracking)>
Public Async Function PasteTracking_MissingTextSpan_AfterPasteThenLinkedFileEdited() As Task
Using testState = New PasteTrackingTestState(MultiFileCode)
Dim class1Document = testState.OpenDocument(Project1Name, Class1Name)
Dim class1LinkedDocument = testState.OpenDocument(Project2Name, Class1Name)
testState.SendPaste(class1Document, PastedCode)
testState.InsertText(class1LinkedDocument, "Foo")
Await testState.AssertMissingPastedTextSpanAsync(class1Document)
Await testState.AssertMissingPastedTextSpanAsync(class1LinkedDocument)
End Using
End Function
<WpfFact>
<Trait(Traits.Feature, Traits.Features.PasteTracking)>
Public Async Function PasteTracking_HasTextSpanForLinkedFile_AfterPasteThenCloseAllThenOpenThenPaste() As Task
Using testState = New PasteTrackingTestState(MultiFileCode)
Dim class1Document = testState.OpenDocument(Project1Name, Class1Name)
Dim class1LinkedDocument = testState.OpenDocument(Project2Name, Class1Name)
testState.SendPaste(class1Document, PastedCode)
testState.CloseDocument(class1Document)
testState.CloseDocument(class1LinkedDocument)
Await testState.AssertMissingPastedTextSpanAsync(class1LinkedDocument)
testState.OpenDocument(class1LinkedDocument)
Dim expectedTextSpan = testState.SendPaste(class1LinkedDocument, PastedCode)
Await testState.AssertHasPastedTextSpanAsync(class1LinkedDocument, expectedTextSpan)
End Using
End Function
End Class
End Namespace
|
DustinCampbell/roslyn
|
src/EditorFeatures/Test2/PasteTracking/PasteTrackingServiceTests.vb
|
Visual Basic
|
apache-2.0
| 13,236
|
' 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.
Imports System.Collections.Immutable
Imports System.Diagnostics
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.CodeGen
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Utilities
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic
' Rewriting for select case statement.
'
' Select case statements can be rewritten as: Switch Table or an If list.
' There are certain restrictions and heuristics for determining which approach
' is being chosen for each select case statement. This determination
' is done in Binder.RecommendSwitchTable method and the result is stored in
' BoundSelectStatement.RecommendSwitchTable flag.
' For switch table based approach we have an option of completely rewriting the switch header
' and switch sections into simpler constructs, i.e. we can rewrite the select header
' using bound conditional goto statements and the rewrite the case blocks into
' bound labeled statements.
' However, all the logic for emitting the switch jump tables is language agnostic
' and includes IL optimizations. Hence we delay the switch jump table generation
' till the emit phase. This way we also get additional benefit of sharing this code
' between both VB and C# compilers.
' For integral type switch table based statements, we delay almost all the work
' to the emit phase.
' For string type switch table based statements, we need to determine if we are generating a hash
' table based jump table or a non hash jump table, i.e. linear string comparisons
' with each case clause string constant. We use the Dev10 C# compiler's heuristic to determine this
' (see SwitchStringJumpTableEmitter.ShouldGenerateHashTableSwitch() for details).
' If we are generating a hash table based jump table, we use a simple customizable
' hash function to hash the string constants corresponding to the case labels.
' See SwitchStringJumpTableEmitter.ComputeStringHash().
' We need to emit this function to compute the hash value into the compiler generated
' <PrivateImplementationDetails> class.
' If we have at least one string type select case statement in a module that needs a
' hash table based jump table, we generate a single public string hash synthesized method (SynthesizedStringSwitchHashMethod)
' that is shared across the module.
' CONSIDER: Ideally generating the SynthesizedStringSwitchHashMethod in <PrivateImplementationDetails>
' CONSIDER: class must be done during code generation, as the lowering does not mention or use
' CONSIDER: the hash function in any way.
' CONSIDER: However this would mean that <PrivateImplementationDetails> class can have
' CONSIDER: different sets of methods during the code generation phase,
' CONSIDER: which might be problematic if we want to make the emitter multithreaded?
Partial Friend NotInheritable Class LocalRewriter
Public Overrides Function VisitSelectStatement(node As BoundSelectStatement) As BoundNode
Return RewriteSelectStatement(node, node.Syntax, node.ExpressionStatement, node.ExprPlaceholderOpt, node.CaseBlocks, node.RecommendSwitchTable, node.ExitLabel)
End Function
Protected Function RewriteSelectStatement(
node As BoundSelectStatement,
syntaxNode As SyntaxNode,
selectExpressionStmt As BoundExpressionStatement,
exprPlaceholderOpt As BoundRValuePlaceholder,
caseBlocks As ImmutableArray(Of BoundCaseBlock),
recommendSwitchTable As Boolean,
exitLabel As LabelSymbol
) As BoundNode
Dim statementBuilder = ArrayBuilder(Of BoundStatement).GetInstance()
Dim instrument = Me.Instrument(node)
If instrument Then
' Add select case begin sequence point
Dim prologue As BoundStatement = _instrumenterOpt.CreateSelectStatementPrologue(node)
If prologue IsNot Nothing Then
statementBuilder.Add(prologue)
End If
End If
' Rewrite select expression
Dim rewrittenSelectExpression As BoundExpression = Nothing
Dim tempLocals As ImmutableArray(Of LocalSymbol) = Nothing
Dim endSelectResumeLabel As BoundLabelStatement = Nothing
Dim generateUnstructuredExceptionHandlingResumeCode As Boolean = ShouldGenerateUnstructuredExceptionHandlingResumeCode(node)
Dim rewrittenSelectExprStmt = RewriteSelectExpression(generateUnstructuredExceptionHandlingResumeCode,
selectExpressionStmt,
rewrittenSelectExpression,
tempLocals,
statementBuilder,
caseBlocks,
recommendSwitchTable,
endSelectResumeLabel)
' Add the select expression placeholder to placeholderReplacementMap
If exprPlaceholderOpt IsNot Nothing Then
AddPlaceholderReplacement(exprPlaceholderOpt, rewrittenSelectExpression)
Else
Debug.Assert(node.WasCompilerGenerated)
End If
' Rewrite select statement
If Not caseBlocks.Any() Then
' Add rewritten select expression statement.
statementBuilder.Add(rewrittenSelectExprStmt)
ElseIf recommendSwitchTable Then
If rewrittenSelectExpression.Type.IsStringType Then
' If we are emitting a hash table based string switch, then we need to create a
' SynthesizedStringSwitchHashMethod and add it to the compiler generated <PrivateImplementationDetails> class.
EnsureStringHashFunction(node)
End If
statementBuilder.Add(node.Update(rewrittenSelectExprStmt, exprPlaceholderOpt, VisitList(caseBlocks), recommendSwitchTable:=True, exitLabel:=exitLabel))
Else
' Rewrite select statement case blocks as IF List
Dim lazyConditionalBranchLocal As LocalSymbol = Nothing
statementBuilder.Add(RewriteCaseBlocksRecursive(node,
generateUnstructuredExceptionHandlingResumeCode,
caseBlocks,
startFrom:=0,
lazyConditionalBranchLocal:=lazyConditionalBranchLocal))
If lazyConditionalBranchLocal IsNot Nothing Then
tempLocals = tempLocals.Add(lazyConditionalBranchLocal)
End If
' Add label statement for exit label
statementBuilder.Add(New BoundLabelStatement(syntaxNode, exitLabel))
End If
If exprPlaceholderOpt IsNot Nothing Then
RemovePlaceholderReplacement(exprPlaceholderOpt)
End If
Dim epilogue As BoundStatement = endSelectResumeLabel
If instrument Then
' Add End Select sequence point
epilogue = _instrumenterOpt.InstrumentSelectStatementEpilogue(node, epilogue)
End If
If epilogue IsNot Nothing Then
statementBuilder.Add(epilogue)
End If
Return New BoundBlock(syntaxNode, Nothing, tempLocals, statementBuilder.ToImmutableAndFree()).MakeCompilerGenerated()
End Function
Private Sub EnsureStringHashFunction(node As BoundSelectStatement)
Dim selectCaseExpr = node.ExpressionStatement.Expression
' Prefer embedded version of the member if present
Dim embeddedOperatorsType As NamedTypeSymbol = Compilation.GetWellKnownType(WellKnownType.Microsoft_VisualBasic_CompilerServices_EmbeddedOperators)
Dim compareStringMember As WellKnownMember =
If(embeddedOperatorsType.IsErrorType AndAlso TypeOf embeddedOperatorsType Is MissingMetadataTypeSymbol,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__CompareStringStringStringBoolean,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_EmbeddedOperators__CompareStringStringStringBoolean)
Dim compareStringMethod = DirectCast(Compilation.GetWellKnownTypeMember(compareStringMember), MethodSymbol)
Me.ReportMissingOrBadRuntimeHelper(selectCaseExpr, compareStringMember, compareStringMethod)
Const stringCharsMember As SpecialMember = SpecialMember.System_String__Chars
Dim stringCharsMethod = DirectCast(ContainingAssembly.GetSpecialTypeMember(stringCharsMember), MethodSymbol)
Me.ReportMissingOrBadRuntimeHelper(selectCaseExpr, stringCharsMember, stringCharsMethod)
Me.ReportBadType(selectCaseExpr, Compilation.GetSpecialType(SpecialType.System_Int32))
Me.ReportBadType(selectCaseExpr, Compilation.GetSpecialType(SpecialType.System_UInt32))
Me.ReportBadType(selectCaseExpr, Compilation.GetSpecialType(SpecialType.System_String))
If _emitModule Is Nothing Then
Return
End If
If Not ShouldGenerateHashTableSwitch(_emitModule, node) Then
Return
End If
' If we have already generated this helper method, possibly for another select case
' or on another thread, we don't need to regenerate it.
Dim privateImplClass = _emitModule.GetPrivateImplClass(node.Syntax, _diagnostics)
If privateImplClass.GetMethod(PrivateImplementationDetails.SynthesizedStringHashFunctionName) IsNot Nothing Then
Return
End If
Dim method = New SynthesizedStringSwitchHashMethod(_emitModule.SourceModule, privateImplClass)
privateImplClass.TryAddSynthesizedMethod(method)
End Sub
Private Function RewriteSelectExpression(
generateUnstructuredExceptionHandlingResumeCode As Boolean,
selectExpressionStmt As BoundExpressionStatement,
<Out()> ByRef rewrittenSelectExpression As BoundExpression,
<Out()> ByRef tempLocals As ImmutableArray(Of LocalSymbol),
statementBuilder As ArrayBuilder(Of BoundStatement),
caseBlocks As ImmutableArray(Of BoundCaseBlock),
recommendSwitchTable As Boolean,
<Out()> ByRef endSelectResumeLabel As BoundLabelStatement
) As BoundExpressionStatement
Debug.Assert(statementBuilder IsNot Nothing)
Debug.Assert(Not caseBlocks.IsDefault)
Dim selectExprStmtSyntax = selectExpressionStmt.Syntax
If generateUnstructuredExceptionHandlingResumeCode Then
RegisterUnstructuredExceptionHandlingResumeTarget(selectExprStmtSyntax, canThrow:=True, statements:=statementBuilder)
' If the Select throws, a Resume Next should branch to the End Select.
endSelectResumeLabel = RegisterUnstructuredExceptionHandlingNonThrowingResumeTarget(selectExprStmtSyntax)
Else
endSelectResumeLabel = Nothing
End If
' Rewrite select expression
rewrittenSelectExpression = VisitExpressionNode(selectExpressionStmt.Expression)
' We will need to store the select case expression into a temporary local if we have at least one case block
' and one of the following is true:
' (1) We are generating If list based code.
' (2) We are generating switch table based code and the select expression is not a bound local expression.
' We need a local for this case because during codeGen we are going to perform a binary search with
' select expression result as the key and might need to load the key multiple times.
Dim needTempLocal = caseBlocks.Any() AndAlso (Not recommendSwitchTable OrElse rewrittenSelectExpression.Kind <> BoundKind.Local)
If needTempLocal Then
Dim selectExprType = rewrittenSelectExpression.Type
' Store the select expression result in a temp
Dim selectStatementSyntax = DirectCast(selectExprStmtSyntax.Parent, SelectBlockSyntax).SelectStatement
Dim tempLocal = New SynthesizedLocal(Me._currentMethodOrLambda, selectExprType, SynthesizedLocalKind.SelectCaseValue, selectStatementSyntax)
tempLocals = ImmutableArray.Create(Of LocalSymbol)(tempLocal)
Dim boundTemp = New BoundLocal(rewrittenSelectExpression.Syntax, tempLocal, selectExprType)
statementBuilder.Add(New BoundAssignmentOperator(syntax:=selectExprStmtSyntax,
left:=boundTemp,
right:=rewrittenSelectExpression,
suppressObjectClone:=True,
type:=selectExprType).ToStatement().MakeCompilerGenerated())
rewrittenSelectExpression = boundTemp.MakeRValue()
Else
tempLocals = ImmutableArray(Of LocalSymbol).Empty
End If
Return selectExpressionStmt.Update(rewrittenSelectExpression)
End Function
' Rewrite select statement case blocks as IF List
Private Function RewriteCaseBlocksRecursive(
selectStatement As BoundSelectStatement,
generateUnstructuredExceptionHandlingResumeCode As Boolean,
caseBlocks As ImmutableArray(Of BoundCaseBlock),
startFrom As Integer,
ByRef lazyConditionalBranchLocal As LocalSymbol
) As BoundStatement
Debug.Assert(startFrom <= caseBlocks.Length)
If startFrom = caseBlocks.Length Then
Return Nothing
End If
Dim rewrittenStatement As BoundStatement
Dim curCaseBlock = caseBlocks(startFrom)
Debug.Assert(generateUnstructuredExceptionHandlingResumeCode = ShouldGenerateUnstructuredExceptionHandlingResumeCode(curCaseBlock))
Dim unstructuredExceptionHandlingResumeTarget As ImmutableArray(Of BoundStatement) = Nothing
Dim rewrittenCaseCondition As BoundExpression = RewriteCaseStatement(generateUnstructuredExceptionHandlingResumeCode, curCaseBlock.CaseStatement, unstructuredExceptionHandlingResumeTarget)
Dim rewrittenBody = DirectCast(VisitBlock(curCaseBlock.Body), BoundBlock)
If generateUnstructuredExceptionHandlingResumeCode AndAlso startFrom < caseBlocks.Length - 1 Then
' Add a Resume entry to protect against fall-through to the next Case block.
rewrittenBody = AppendToBlock(rewrittenBody, RegisterUnstructuredExceptionHandlingNonThrowingResumeTarget(curCaseBlock.Syntax))
End If
Dim instrument = Me.Instrument(selectStatement)
If rewrittenCaseCondition Is Nothing Then
' This must be a Case Else Block
Debug.Assert(curCaseBlock.Syntax.Kind = SyntaxKind.CaseElseBlock)
Debug.Assert(Not curCaseBlock.CaseStatement.CaseClauses.Any())
' Only the last block can be a Case Else block
Debug.Assert(startFrom = caseBlocks.Length - 1)
' Case Else statement needs a sequence point
If instrument Then
rewrittenStatement = _instrumenterOpt.InstrumentCaseElseBlock(curCaseBlock, rewrittenBody)
Else
rewrittenStatement = rewrittenBody
End If
Else
Debug.Assert(curCaseBlock.Syntax.Kind = SyntaxKind.CaseBlock)
If instrument Then
rewrittenCaseCondition = _instrumenterOpt.InstrumentSelectStatementCaseCondition(selectStatement, rewrittenCaseCondition, _currentMethodOrLambda, lazyConditionalBranchLocal)
End If
' EnC: We need to insert a hidden sequence point to handle function remapping in case
' the containing method is edited while methods invoked in the condition are being executed.
rewrittenStatement = RewriteIfStatement(
syntaxNode:=curCaseBlock.Syntax,
rewrittenCondition:=rewrittenCaseCondition,
rewrittenConsequence:=rewrittenBody,
rewrittenAlternative:=RewriteCaseBlocksRecursive(selectStatement, generateUnstructuredExceptionHandlingResumeCode, caseBlocks, startFrom + 1, lazyConditionalBranchLocal),
unstructuredExceptionHandlingResumeTarget:=unstructuredExceptionHandlingResumeTarget,
instrumentationTargetOpt:=If(instrument, curCaseBlock, Nothing))
End If
Return rewrittenStatement
End Function
' Rewrite case statement as conditional expression
Private Function RewriteCaseStatement(
generateUnstructuredExceptionHandlingResumeCode As Boolean,
node As BoundCaseStatement,
<Out()> ByRef unstructuredExceptionHandlingResumeTarget As ImmutableArray(Of BoundStatement)
) As BoundExpression
If node.CaseClauses.Any() Then
' Case block
Debug.Assert(node.Syntax.Kind = SyntaxKind.CaseStatement)
Debug.Assert(node.ConditionOpt IsNot Nothing)
unstructuredExceptionHandlingResumeTarget = If(generateUnstructuredExceptionHandlingResumeCode,
RegisterUnstructuredExceptionHandlingResumeTarget(node.Syntax, canThrow:=True),
Nothing)
Return VisitExpressionNode(node.ConditionOpt)
Else
' Case Else block
Debug.Assert(node.Syntax.Kind = SyntaxKind.CaseElseStatement)
unstructuredExceptionHandlingResumeTarget = Nothing
Return Nothing
End If
End Function
' Checks whether we are generating a hash table based string switch
Private Shared Function ShouldGenerateHashTableSwitch([module] As Microsoft.CodeAnalysis.VisualBasic.Emit.PEModuleBuilder, node As BoundSelectStatement) As Boolean
Debug.Assert(Not node.HasErrors)
Debug.Assert(node.ExpressionStatement.Expression.Type.IsStringType)
Debug.Assert(node.RecommendSwitchTable)
If Not [module].SupportsPrivateImplClass Then
Return False
End If
' compute unique string constants from select clauses.
Dim uniqueStringConstants = New HashSet(Of ConstantValue)
For Each caseBlock In node.CaseBlocks
For Each caseClause In caseBlock.CaseStatement.CaseClauses
Dim constant As ConstantValue = Nothing
Select Case caseClause.Kind
Case BoundKind.SimpleCaseClause
Dim simpleCaseClause = DirectCast(caseClause, BoundSimpleCaseClause)
Debug.Assert(simpleCaseClause.ValueOpt IsNot Nothing)
Debug.Assert(simpleCaseClause.ConditionOpt Is Nothing)
constant = simpleCaseClause.ValueOpt.ConstantValueOpt
Case BoundKind.RelationalCaseClause
Dim relationalCaseClause = DirectCast(caseClause, BoundRelationalCaseClause)
Debug.Assert(relationalCaseClause.OperatorKind = BinaryOperatorKind.Equals)
Debug.Assert(relationalCaseClause.ValueOpt IsNot Nothing)
Debug.Assert(relationalCaseClause.ConditionOpt Is Nothing)
constant = relationalCaseClause.ValueOpt.ConstantValueOpt
Case Else
Throw ExceptionUtilities.UnexpectedValue(caseClause.Kind)
End Select
Debug.Assert(constant IsNot Nothing)
uniqueStringConstants.Add(constant)
Next
Next
Return SwitchStringJumpTableEmitter.ShouldGenerateHashTableSwitch([module], uniqueStringConstants.Count)
End Function
Public Overrides Function VisitCaseBlock(node As BoundCaseBlock) As BoundNode
Dim rewritten = DirectCast(MyBase.VisitCaseBlock(node), BoundCaseBlock)
Dim rewrittenBody = rewritten.Body
' Add a Resume entry to protect against fall-through to the next Case block.
If ShouldGenerateUnstructuredExceptionHandlingResumeCode(node) Then
rewrittenBody = AppendToBlock(rewrittenBody, RegisterUnstructuredExceptionHandlingNonThrowingResumeTarget(node.Syntax))
End If
Return rewritten.Update(rewritten.CaseStatement, rewrittenBody)
End Function
End Class
End Namespace
|
davkean/roslyn
|
src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_SelectCase.vb
|
Visual Basic
|
apache-2.0
| 22,052
|
' 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.
Imports System.Collections.ObjectModel
Imports Microsoft.CodeAnalysis.Editor.Implementation.InlineRename
Imports Microsoft.CodeAnalysis.Editor.Implementation.InlineRename.HighlightTags
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Text.Shared.Extensions
Imports Microsoft.VisualStudio.Text
Imports Microsoft.VisualStudio.Text.Editor
Imports Microsoft.VisualStudio.Text.Editor.Commanding.Commands
Imports Microsoft.VisualStudio.Text.Operations
Imports Microsoft.VisualStudio.Text.Tagging
Imports Roslyn.Utilities
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename
<[UseExportProvider]>
Public Class RenameTagProducerTests
Private Shared Function CreateCommandHandler(workspace As TestWorkspace) As RenameCommandHandler
Return workspace.ExportProvider.GetCommandHandler(Of RenameCommandHandler)(PredefinedCommandHandlerNames.Rename)
End Function
Private Shared Async Function VerifyEmptyTaggedSpans(tagType As TextMarkerTag, actualWorkspace As TestWorkspace, renameService As InlineRenameService) As Task
Await VerifyTaggedSpansCore(tagType, actualWorkspace, renameService, SpecializedCollections.EmptyEnumerable(Of Span))
End Function
Private Shared Async Function VerifyTaggedSpans(tagType As TextMarkerTag, actualWorkspace As TestWorkspace, renameService As InlineRenameService) As Task
Dim expectedSpans = actualWorkspace.Documents.Single(Function(d) d.SelectedSpans.Any()).SelectedSpans.Select(Function(ts) ts.ToSpan())
Await VerifyTaggedSpansCore(tagType, actualWorkspace, renameService, expectedSpans)
End Function
Private Shared Async Function VerifyTaggedSpans(tagType As TextMarkerTag, actualWorkspace As TestWorkspace, renameService As InlineRenameService, expectedTaggedWorkspace As TestWorkspace) As Task
Dim expectedSpans = expectedTaggedWorkspace.Documents.Single(Function(d) d.SelectedSpans.Any()).SelectedSpans.Select(Function(ts) ts.ToSpan())
Await VerifyTaggedSpansCore(tagType, actualWorkspace, renameService, expectedSpans)
End Function
Private Shared Async Function VerifyAnnotatedTaggedSpans(tagType As TextMarkerTag, annotationString As String, actualWorkspace As TestWorkspace, renameService As InlineRenameService, expectedTaggedWorkspace As TestWorkspace) As Task
Dim annotatedDocument = expectedTaggedWorkspace.Documents.SingleOrDefault(Function(d) d.AnnotatedSpans.Any())
Dim expectedSpans As IEnumerable(Of Span)
If annotatedDocument Is Nothing Then
expectedSpans = SpecializedCollections.EmptyEnumerable(Of Span)
Else
expectedSpans = GetAnnotatedSpans(annotationString, annotatedDocument)
End If
Await VerifyTaggedSpansCore(tagType, actualWorkspace, renameService, expectedSpans)
End Function
Private Shared Function GetAnnotatedSpans(annotationString As String, annotatedDocument As TestHostDocument) As IEnumerable(Of Span)
Return annotatedDocument.AnnotatedSpans.SelectMany(Function(kvp)
If kvp.Key = annotationString Then
Return kvp.Value.Select(Function(ts) ts.ToSpan())
End If
Return SpecializedCollections.EmptyEnumerable(Of Span)
End Function)
End Function
Private Shared Async Function VerifySpansBeforeConflictResolution(actualWorkspace As TestWorkspace, renameService As InlineRenameService) As Task
' Verify no fixup/resolved non-reference conflict span.
Await VerifyEmptyTaggedSpans(HighlightTags.RenameFixupTag.Instance, actualWorkspace, renameService)
' Verify valid reference tags.
Await VerifyTaggedSpans(HighlightTags.RenameFieldBackgroundAndBorderTag.Instance, actualWorkspace, renameService)
End Function
Private Shared Async Function VerifySpansAndBufferForConflictResolution(actualWorkspace As TestWorkspace, renameService As InlineRenameService, resolvedConflictWorkspace As TestWorkspace,
session As IInlineRenameSession, Optional sessionCommit As Boolean = False, Optional sessionCancel As Boolean = False) As System.Threading.Tasks.Task
Await WaitForRename(actualWorkspace)
' Verify fixup/resolved conflict spans.
Await VerifyAnnotatedTaggedSpans(HighlightTags.RenameFixupTag.Instance, "Complexified", actualWorkspace, renameService, resolvedConflictWorkspace)
' Verify valid reference tags.
Await VerifyTaggedSpans(HighlightTags.RenameFieldBackgroundAndBorderTag.Instance, actualWorkspace, renameService, resolvedConflictWorkspace)
VerifyBufferContentsInWorkspace(actualWorkspace, resolvedConflictWorkspace)
If sessionCommit Or sessionCancel Then
Assert.True(Not sessionCommit Or Not sessionCancel)
If sessionCancel Then
session.Cancel()
VerifyBufferContentsInWorkspace(actualWorkspace, actualWorkspace)
ElseIf sessionCommit Then
session.Commit()
VerifyBufferContentsInWorkspace(actualWorkspace, resolvedConflictWorkspace)
End If
End If
End Function
Private Shared Async Function VerifyTaggedSpansCore(tagType As TextMarkerTag, actualWorkspace As TestWorkspace, renameService As InlineRenameService, expectedSpans As IEnumerable(Of Span)) As Task
Dim taggedSpans = Await GetTagsOfType(tagType, actualWorkspace, renameService)
Assert.Equal(expectedSpans, taggedSpans)
End Function
Private Shared Sub VerifyBufferContentsInWorkspace(actualWorkspace As TestWorkspace, expectedWorkspace As TestWorkspace)
Dim actualDocs = actualWorkspace.Documents
Dim expectedDocs = expectedWorkspace.Documents
Assert.Equal(expectedDocs.Count, actualDocs.Count)
For i = 0 To actualDocs.Count - 1
Dim actualDocument = actualDocs(i)
Dim expectedDocument = expectedDocs(i)
Dim actualText = actualDocument.GetTextBuffer().CurrentSnapshot.GetText().Trim()
Dim expectedText = expectedDocument.GetTextBuffer().CurrentSnapshot.GetText().Trim()
Assert.Equal(expectedText, actualText)
Next
End Sub
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Async Function ValidTagsDuringSimpleRename(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class [|$$Goo|]
{
void Blah()
{
[|Goo|] f = new [|Goo|]();
}
}
</Document>
</Project>
</Workspace>, host)
Dim renameService = workspace.GetService(Of InlineRenameService)()
Dim session = StartSession(workspace)
Await VerifyTaggedSpans(HighlightTags.RenameFieldBackgroundAndBorderTag.Instance, workspace, renameService)
session.Cancel()
End Using
End Function
<WpfTheory>
<WorkItem(922197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/922197")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Async Function UnresolvableConflictInModifiedDocument(host As RenameTestHost) As System.Threading.Tasks.Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
static void Main(string[] {|conflict:args|}, int $$goo)
{
Goo(c => IsInt({|conflict:goo|}, c));
}
private static void Goo(Func<char, bool> p) { }
private static void Goo(Func<int, bool> p) { }
private static bool IsInt(int goo, char c) { }
}
</Document>
</Project>
</Workspace>, host)
Dim renameService = workspace.GetService(Of InlineRenameService)()
Dim document = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue)
Dim location = document.CursorPosition.Value
Dim session = StartSession(workspace)
document.GetTextBuffer().Replace(New Span(location, 3), "args")
Await WaitForRename(workspace)
Using renamedWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
static void Main(string[] {|conflict:args|}, int args)
{
Goo(c => IsInt({|conflict:args|}, c));
}
private static void Goo(Func<char, bool> p) { }
private static void Goo(Func<int, bool> p) { }
private static bool IsInt(int goo, char c) { }
}
</Document>
</Project>
</Workspace>, host)
Dim renamedDocument = renamedWorkspace.Documents.Single()
Dim expectedSpans = GetAnnotatedSpans("conflict", renamedDocument)
Dim taggedSpans = GetTagsOfType(RenameConflictTag.Instance, renameService, document.GetTextBuffer())
Assert.Equal(expectedSpans, taggedSpans)
End Using
End Using
End Function
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Async Function VerifyLinkedFiles_InterleavedResolvedConflicts(host As RenameTestHost) As System.Threading.Tasks.Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1">
<Document FilePath="C.cs">
public class Class1
{
#if Proj2
int fieldclash;
#endif
int field$$;
void M()
{
int fieldclash = 8;
#if Proj1
var a = [|field|];
#elif Proj2
var a = [|field|];
#elif Proj3
var a = field;
#endif
#if Proj1
var b = [|field|];
#elif Proj2
var b = [|field|];
#elif Proj3
var b = field;
#endif
}
}
</Document>
</Project>
<Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2">
<Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/>
</Project>
</Workspace>, host)
Dim renameService = workspace.GetService(Of InlineRenameService)()
Dim document = workspace.Documents.First(Function(d) d.CursorPosition.HasValue)
Dim location = document.CursorPosition.Value
Dim session = StartSession(workspace)
document.GetTextBuffer().Insert(location, "clash")
Await WaitForRename(workspace)
Using renamedWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1">
<Document FilePath="C.cs">
public class Class1
{
#if Proj2
int fieldclash;
#endif
int {|valid:fieldclash|};
void M()
{
int fieldclash = 8;
#if Proj1
{|resolved:var a = this.{|valid:fieldclash|};|}
#elif Proj2
var a = {|conflict:fieldclash|};
#elif Proj3
var a = field;
#endif
#if Proj1
{|resolved:var b = this.{|valid:fieldclash|};|}
#elif Proj2
var b = {|conflict:fieldclash|};
#elif Proj3
var b = field;
#endif
}
}
</Document>
</Project>
<Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2">
<Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/>
</Project>
</Workspace>, host)
Dim renamedDocument = renamedWorkspace.Documents.First()
Dim expectedSpans = GetAnnotatedSpans("resolved", renamedDocument)
Dim taggedSpans = GetTagsOfType(RenameFixupTag.Instance, renameService, document.GetTextBuffer())
Assert.Equal(expectedSpans, taggedSpans)
expectedSpans = GetAnnotatedSpans("conflict", renamedDocument)
taggedSpans = GetTagsOfType(RenameConflictTag.Instance, renameService, document.GetTextBuffer())
Assert.Equal(expectedSpans, taggedSpans)
expectedSpans = GetAnnotatedSpans("valid", renamedDocument)
taggedSpans = GetTagsOfType(RenameFieldBackgroundAndBorderTag.Instance, renameService, document.GetTextBuffer())
Assert.Equal(expectedSpans, taggedSpans)
End Using
End Using
End Function
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Async Function VerifyLinkedFiles_UnresolvableConflictComments(host As RenameTestHost) As Task
Dim originalDocument = "
public class Class1
{
#if Proj1
void Test(double x) { }
#elif Proj2
void Test(long x) { }
#endif
void Tes$$(int i) { }
void M()
{
Test(5);
}
}"
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1">
<Document FilePath="C.cs"><%= originalDocument %></Document>
</Project>
<Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2">
<Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/>
</Project>
</Workspace>, host)
Dim renameService = workspace.GetService(Of InlineRenameService)()
Dim document = workspace.Documents.First(Function(d) d.CursorPosition.HasValue)
Dim location = document.CursorPosition.Value
Dim session = StartSession(workspace)
document.GetTextBuffer().Insert(location, "t")
Await WaitForRename(workspace)
Dim expectedDocument = $"
public class Class1
{{
#if Proj1
void Test(double x) {{ }}
#elif Proj2
void Test(long x) {{ }}
#endif
void Test(int i) {{ }}
void M()
{{
{{|conflict:{{|conflict:/* {String.Format(WorkspacesResources.Unmerged_change_from_project_0, "CSharpAssembly1")}
{WorkspacesResources.Before_colon}
Test(5);
{WorkspacesResources.After_colon}
Test((long)5);
*|}}|}}/
Test((double)5);
}}
}}"
Using renamedWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1">
<Document FilePath="C.cs"><%= expectedDocument %></Document>
</Project>
<Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2">
<Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/>
</Project>
</Workspace>, host)
Dim renamedDocument = renamedWorkspace.Documents.First()
Dim expectedSpans = GetAnnotatedSpans("conflict", renamedDocument)
Dim taggedSpans = GetTagsOfType(RenameConflictTag.Instance, renameService, document.GetTextBuffer())
Assert.Equal(expectedSpans, taggedSpans)
End Using
End Using
End Function
<WpfTheory>
<WorkItem(922197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/922197")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Async Function UnresolvableConflictInUnmodifiedDocument(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class [|$$A|]
{
}
</Document>
<Document FilePath="B.cs">
class {|conflict:B|}
{
}
</Document>
</Project>
</Workspace>, host)
Dim renameService = workspace.GetService(Of InlineRenameService)()
Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Dim textBuffer = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).GetTextBuffer()
Dim session = StartSession(workspace)
textBuffer.Replace(New Span(location, 1), "B")
Await WaitForRename(workspace)
Dim conflictDocument = workspace.Documents.Single(Function(d) d.FilePath = "B.cs")
Dim expectedSpans = GetAnnotatedSpans("conflict", conflictDocument)
Dim taggedSpans = GetTagsOfType(RenameConflictTag.Instance, renameService, conflictDocument.GetTextBuffer())
Assert.Equal(expectedSpans, taggedSpans)
End Using
End Function
<WpfTheory>
<WorkItem(847467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/847467")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Async Function ValidStateWithEmptyReplacementTextAfterConflictResolution(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class [|$$T|]
{
}
</Document>
</Project>
</Workspace>, host)
Dim renameService = workspace.GetService(Of InlineRenameService)()
Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Dim textBuffer = workspace.Documents.Single().GetTextBuffer()
Dim session = StartSession(workspace)
textBuffer.Replace(New Span(location, 1), "this")
' Verify @ escaping
Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class @[|this|]
{
}
</Document>
</Project>
</Workspace>, host)
Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session)
End Using
textBuffer.Delete(New Span(location + 1, 4))
Await WaitForRename(workspace)
' Verify no escaping
Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class
{
}
</Document>
</Project>
</Workspace>, host)
VerifyBufferContentsInWorkspace(workspace, resolvedConflictWorkspace)
End Using
session.Commit()
Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class T
{
}
</Document>
</Project>
</Workspace>, host)
VerifyBufferContentsInWorkspace(workspace, resolvedConflictWorkspace)
End Using
End Using
End Function
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(812789, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/812789")>
Public Async Function RenamingEscapedIdentifiers(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void @$$as() { }
}
</Document>
</Project>
</Workspace>, host)
Dim renameService = workspace.GetService(Of InlineRenameService)()
Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Dim session = StartSession(workspace)
Dim textBuffer = workspace.Documents.Single().GetTextBuffer()
' Verify @ escaping is still present
Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void @[|as|]() { }
}
</Document>
</Project>
</Workspace>, host)
Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session)
End Using
textBuffer.Replace(New Span(location, 2), "bar")
' Verify @ escaping is removed
Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void [|bar|]() { }
}
</Document>
</Project>
</Workspace>, host)
Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session)
End Using
End Using
End Function
<WpfTheory>
<WorkItem(812795, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/812795")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Async Function BackspacingAfterConflictResolutionPreservesTrackingSpans(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void Method()
{
$$Bar(0);
}
void Goo(int i) { }
void Bar(double d) { }
}
</Document>
</Project>
</Workspace>, host)
Dim view = workspace.Documents.Single().GetTextView()
Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Dim textBuffer = workspace.Documents.Single().GetTextBuffer()
Dim renameService = workspace.GetService(Of InlineRenameService)()
Dim editorOperations = workspace.GetService(Of IEditorOperationsFactoryService).GetEditorOperations(view)
Dim commandHandler = CreateCommandHandler(workspace)
Dim session = StartSession(workspace)
textBuffer.Replace(New Span(location, 3), "Goo")
Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void Method()
{
{|Complexified:[|Goo|]((double)0);|}
}
void Goo(int i) { }
void [|Goo|](double d) { }
}
</Document>
</Project>
</Workspace>, host)
Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session)
End Using
' Delete Goo and type "as"
commandHandler.ExecuteCommand(New BackspaceKeyCommandArgs(view, view.TextBuffer), Sub() editorOperations.Backspace(), Utilities.TestCommandExecutionContext.Create())
commandHandler.ExecuteCommand(New BackspaceKeyCommandArgs(view, view.TextBuffer), Sub() editorOperations.Backspace(), Utilities.TestCommandExecutionContext.Create())
commandHandler.ExecuteCommand(New BackspaceKeyCommandArgs(view, view.TextBuffer), Sub() editorOperations.Backspace(), Utilities.TestCommandExecutionContext.Create())
commandHandler.ExecuteCommand(New TypeCharCommandArgs(view, view.TextBuffer, "a"c), Sub() editorOperations.InsertText("a"), Utilities.TestCommandExecutionContext.Create())
commandHandler.ExecuteCommand(New TypeCharCommandArgs(view, view.TextBuffer, "s"c), Sub() editorOperations.InsertText("s"), Utilities.TestCommandExecutionContext.Create())
Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void Method()
{
@[|as|](0);
}
void Goo(int i) { }
void @[|as|](double d) { }
}
</Document>
</Project>
</Workspace>, host)
Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session)
End Using
End Using
End Function
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Async Function CSharp_FixupSpanDuringResolvableConflict_NonReferenceConflict(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Goo
{
int bar;
void M(int [|$$goo|])
{
var x = [|goo|];
bar = 23;
}
}
</Document>
</Project>
</Workspace>, host)
Dim renameService = workspace.GetService(Of InlineRenameService)()
Dim session = StartSession(workspace)
Dim textBuffer = workspace.Documents.Single().GetTextBuffer()
Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Await VerifySpansBeforeConflictResolution(workspace, renameService)
' Apply edit so that we have a resolved non-reference conflict.
textBuffer.Replace(New Span(location, 3), "bar")
' Verify fixup/resolved non-reference conflict span.
Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Goo
{
int bar;
void M(int [|bar|])
{
var x = [|bar|];
{|Complexified:this.{|Resolved:bar|} = 23;|}
}
}
</Document>
</Project>
</Workspace>, host)
Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session)
End Using
' Make another edit so that we have no more conflicts.
location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
textBuffer.Replace(New Span(location, 3), "baR")
Using newWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Goo
{
int bar;
void M(int [|$$baR|])
{
var x = [|baR|];
bar = 23;
}
}
</Document>
</Project>
</Workspace>, host)
Await VerifySpansAndBufferForConflictResolution(workspace, renameService, newWorkspace, session, sessionCommit:=True)
End Using
End Using
End Function
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Async Function VisualBasic_FixupSpanDuringResolvableConflict_NonReferenceConflict(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Goo
Dim bar As Integer
Sub M([|$$goo|] As Integer)
Dim x = [|goo|]
BAR = 23
End Sub
End Class
</Document>
</Project>
</Workspace>, host)
Dim renameService = workspace.GetService(Of InlineRenameService)()
Dim session = StartSession(workspace)
Dim textBuffer = workspace.Documents.Single().GetTextBuffer()
Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Await VerifySpansBeforeConflictResolution(workspace, renameService)
' Apply edit so that we have a resolved non-reference conflict.
textBuffer.Replace(New Span(location, 3), "bar")
' Verify fixup/resolved non-reference conflict span.
Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Goo
Dim bar As Integer
Sub M([|bar|] As Integer)
Dim x = [|bar|]
{|Complexified:Me.{|Resolved:BAR|} = 23|}
End Sub
End Class
</Document>
</Project>
</Workspace>, host)
Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session)
End Using
' Make another edit so that we have no more conflicts.
location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
textBuffer.Replace(New Span(location, 3), "boo")
Using newWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Goo
Dim bar As Integer
Sub M([|$$boo|] As Integer)
Dim x = [|boo|]
BAR = 23
End Sub
End Class
</Document>
</Project>
</Workspace>, host)
Await VerifySpansAndBufferForConflictResolution(workspace, renameService, newWorkspace, session, sessionCommit:=True)
End Using
End Using
End Function
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Async Function CSharp_FixupSpanDuringResolvableConflict_ReferenceConflict(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Goo
{
int [|$$goo|];
void M(int bar)
{
[|goo|] = [|goo|] + bar;
}
}
</Document>
</Project>
</Workspace>, host)
Dim renameService = workspace.GetService(Of InlineRenameService)()
Dim session = StartSession(workspace)
Dim textBuffer = workspace.Documents.Single().GetTextBuffer()
Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Await VerifySpansBeforeConflictResolution(workspace, renameService)
' Apply edit so that we have a resolved reference conflict.
textBuffer.Replace(New Span(location, 3), "bar")
' Verify fixup/resolved conflict span.
Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Goo
{
int [|bar|];
void M(int bar)
{
{|Complexified:this.{|Resolved:[|bar|]|} = this.{|Resolved:[|bar|]|} + bar;|}
}
}
</Document>
</Project>
</Workspace>, host)
Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session)
End Using
textBuffer.Replace(New Span(location, 3), "ba")
Using newWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Goo
{
int [|$$ba|];
void M(int bar)
{
[|ba|] = [|ba|] + bar;
}
}
</Document>
</Project>
</Workspace>, host)
Await VerifySpansAndBufferForConflictResolution(workspace, renameService, newWorkspace, session, sessionCancel:=True)
End Using
End Using
End Function
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Async Function VisualBasic_FixupSpanDuringResolvableConflict_ReferenceConflict(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Goo
Dim [|$$goo|] As Integer
Sub M(bar As Integer)
[|goo|] = [|goo|] + bar
End Sub
End Class
</Document>
</Project>
</Workspace>, host)
Dim renameService = workspace.GetService(Of InlineRenameService)()
Dim session = StartSession(workspace)
Dim textBuffer = workspace.Documents.Single().GetTextBuffer()
Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Await VerifySpansBeforeConflictResolution(workspace, renameService)
' Apply edit so that we have a resolved reference conflict.
textBuffer.Replace(New Span(location, 3), "bar")
' Verify fixup/resolved conflict span.
Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Goo
Dim [|bar|] As Integer
Sub M(bar As Integer)
{|Complexified:Me.{|Resolved:[|bar|]|} = Me.{|Resolved:[|bar|]|} + bar|}
End Sub
End Class
</Document>
</Project>
</Workspace>, host)
Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session)
End Using
' Make another edit so that we have no more conflicts.
textBuffer.Replace(New Span(location, 3), "ba")
Using newWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Goo
Dim [|$$ba|] As Integer
Sub M(bar As Integer)
[|ba|] = [|ba|] + bar
End Sub
End Class
</Document>
</Project>
</Workspace>, host)
Await VerifySpansAndBufferForConflictResolution(workspace, renameService, newWorkspace, session, sessionCancel:=True)
End Using
End Using
End Function
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Async Function CSharp_FixupSpanDuringResolvableConflict_NeedsEscaping(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Goo
{
int @int;
void M(int [|$$goo|])
{
var x = [|goo|];
@int = 23;
}
}
</Document>
</Project>
</Workspace>, host)
Dim renameService = workspace.GetService(Of InlineRenameService)()
Dim session = StartSession(workspace)
Dim textBuffer = workspace.Documents.Single().GetTextBuffer()
Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Await VerifySpansBeforeConflictResolution(workspace, renameService)
' Apply edit so that we have a resolved escaping conflict.
textBuffer.Replace(New Span(location, 3), "int")
' Verify fixup/resolved conflict span.
Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Goo
{
int @int;
void M(int {|Resolved:@[|int|]|})
{
var x = {|Resolved:@[|int|]|};
{|Complexified:this.{|Resolved:@int|} = 23;|}
}
}
</Document>
</Project>
</Workspace>, host)
Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session)
End Using
' Make another edit to change "int" to "@in" so that we have no more conflicts, just escaping.
textBuffer.Replace(New Span(location + 1, 3), "in")
' Verify resolved escaping conflict spans.
Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Goo
{
int @int;
void M(int {|Resolved:@[|in|]|})
{
var x = {|Resolved:@[|in|]|};
@int = 23;
}
}
</Document>
</Project>
</Workspace>, host)
Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session, sessionCommit:=True)
End Using
End Using
End Function
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Async Function VisualBasic_FixupSpanDuringResolvableConflict_NeedsEscaping(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Goo
Dim [New] As Integer
Sub M([|$$goo|] As Integer)
Dim x = [|goo|]
[NEW] = 23
End Sub
End Class
</Document>
</Project>
</Workspace>, host)
Dim renameService = workspace.GetService(Of InlineRenameService)()
Dim session = StartSession(workspace)
Dim textBuffer = workspace.Documents.Single().GetTextBuffer()
Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Await VerifySpansBeforeConflictResolution(workspace, renameService)
' Apply edit so that we have a resolved escaping conflict.
textBuffer.Replace(New Span(location, 3), "New")
' Verify fixup/resolved conflict span.
Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Goo
Dim [New] As Integer
Sub M({|Resolved:[[|New|]]|} As Integer)
Dim x = {|Resolved:[[|New|]]|}
{|Complexified:Me.{|Resolved:[NEW]|} = 23|}
End Sub
End Class
</Document>
</Project>
</Workspace>, host)
Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session)
End Using
' Make another edit to change "New" to "[Do]" so that we have no more conflicts, just escaping.
textBuffer.Replace(New Span(location + 1, 3), "Do")
' Verify resolved escaping conflict spans.
Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Goo
Dim [New] As Integer
Sub M({|Resolved:[[|Do|]]|} As Integer)
Dim x = {|Resolved:[[|Do|]]|}
[NEW] = 23
End Sub
End Class
</Document>
</Project>
</Workspace>, host)
Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session, sessionCommit:=True)
End Using
End Using
End Function
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Async Function FixupSpanDuringResolvableConflict_VerifyCaret(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Goo
Sub [|N$$w|](goo As Integer)
End Sub
End Class
</Document>
</Project>
</Workspace>, host)
Dim view = workspace.Documents.Single().GetTextView()
Dim editorOperations = workspace.GetService(Of IEditorOperationsFactoryService).GetEditorOperations(view)
Dim commandHandler = CreateCommandHandler(workspace)
Dim textViewService = Assert.IsType(Of TextBufferAssociatedViewService)(workspace.ExportProvider.GetExportedValue(Of ITextBufferAssociatedViewService)())
Dim buffers = New Collection(Of ITextBuffer)
buffers.Add(view.TextBuffer)
DirectCast(textViewService, ITextViewConnectionListener).SubjectBuffersConnected(view, ConnectionReason.TextViewLifetime, buffers)
Dim renameService = workspace.GetService(Of InlineRenameService)()
Dim session = StartSession(workspace)
Await VerifySpansBeforeConflictResolution(workspace, renameService)
' Type first in the main identifier
view.Selection.Clear()
view.Caret.MoveTo(New SnapshotPoint(view.TextBuffer.CurrentSnapshot, workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value))
commandHandler.ExecuteCommand(New TypeCharCommandArgs(view, view.TextBuffer, "e"c),
Sub() editorOperations.InsertText("e"),
Utilities.TestCommandExecutionContext.Create())
' Verify fixup/resolved conflict span.
Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Goo
Sub [[|Ne$$w|]](goo As Integer)
End Sub
End Class
</Document>
</Project>
</Workspace>, host)
Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session)
Dim location = view.Caret.Position.BufferPosition.Position
Dim expectedLocation = resolvedConflictWorkspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Assert.Equal(expectedLocation, location)
End Using
' Make another edit to change "New" to "Nexw" so that we have no more conflicts or escaping.
commandHandler.ExecuteCommand(New TypeCharCommandArgs(view, view.TextBuffer, "x"c),
Sub() editorOperations.InsertText("x"),
Utilities.TestCommandExecutionContext.Create())
' Verify resolved escaping conflict spans.
Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Goo
Sub [|Nex$$w|](goo As Integer)
End Sub
End Class
</Document>
</Project>
</Workspace>, host)
Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session)
Dim location = view.Caret.Position.BufferPosition.Position
Dim expectedLocation = resolvedConflictWorkspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Assert.Equal(expectedLocation, location)
End Using
End Using
End Function
<WpfTheory>
<WorkItem(771743, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/771743")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Async Function VerifyNoSelectionAfterCommit(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Goo
Sub [|M$$ain|](goo As Integer)
End Sub
End Class
</Document>
</Project>
</Workspace>, host)
Dim view = workspace.Documents.Single().GetTextView()
Dim editorOperations = workspace.GetService(Of IEditorOperationsFactoryService).GetEditorOperations(view)
Dim commandHandler = CreateCommandHandler(workspace)
Dim textViewService = Assert.IsType(Of TextBufferAssociatedViewService)(workspace.ExportProvider.GetExportedValue(Of ITextBufferAssociatedViewService)())
Dim buffers = New Collection(Of ITextBuffer)
buffers.Add(view.TextBuffer)
DirectCast(textViewService, ITextViewConnectionListener).SubjectBuffersConnected(view, ConnectionReason.TextViewLifetime, buffers)
Dim location = view.Caret.Position.BufferPosition.Position
view.Selection.Select(New SnapshotSpan(view.Caret.Position.BufferPosition, 2), False)
Dim renameService = workspace.GetService(Of InlineRenameService)()
Dim session = StartSession(workspace)
Await VerifySpansBeforeConflictResolution(workspace, renameService)
' Type few characters.
view.Caret.MoveTo(New SnapshotPoint(view.TextBuffer.CurrentSnapshot, workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value))
commandHandler.ExecuteCommand(New TypeCharCommandArgs(view, view.TextBuffer, "e"c), Sub() editorOperations.InsertText("e"), Utilities.TestCommandExecutionContext.Create())
commandHandler.ExecuteCommand(New TypeCharCommandArgs(view, view.TextBuffer, "f"c), Sub() editorOperations.InsertText("f"), Utilities.TestCommandExecutionContext.Create())
commandHandler.ExecuteCommand(New TypeCharCommandArgs(view, view.TextBuffer, "g"c), Sub() editorOperations.InsertText("g"), Utilities.TestCommandExecutionContext.Create())
session.Commit()
Dim selectionLength = view.Selection.End.Position - view.Selection.Start.Position
Assert.Equal(0, selectionLength)
End Using
End Function
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Async Function CSharp_FixupSpanDuringResolvableConflict_ComplexificationOutsideConflict(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
static void Main(string[] args)
{
int x = [|$$Bar|](Goo([|Bar|](0)));
}
static int Goo(int i)
{
return 0;
}
static int [|Bar|](double d)
{
return 1;
}
}
</Document>
</Project>
</Workspace>, host)
Dim renameService = workspace.GetService(Of InlineRenameService)()
Dim session = StartSession(workspace)
Dim textBuffer = workspace.Documents.Single().GetTextBuffer()
Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Await VerifySpansBeforeConflictResolution(workspace, renameService)
' Apply edit so that we have a resolved reference conflict.
textBuffer.Replace(New Span(location, 3), "Goo")
' Verify fixup/resolved conflict span.
Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
static void Main(string[] args)
{
{|Complexified:int x = {|Resolved:[|Goo|]|}((double)Goo({|Resolved:[|Goo|]|}((double)0)));|}
}
static int Goo(int i)
{
return 0;
}
static int [|Goo|](double d)
{
return 1;
}
}
</Document>
</Project>
</Workspace>, host)
Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session)
End Using
' Make another edit so that we have no more conflicts.
textBuffer.Replace(New Span(location, 3), "GOO")
Using newWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
static void Main(string[] args)
{
int x = [|$$GOO|](Goo([|GOO|](0)));
}
static int Goo(int i)
{
return 0;
}
static int [|GOO|](double d)
{
return 1;
}
}
</Document>
</Project>
</Workspace>, host)
Await VerifySpansAndBufferForConflictResolution(workspace, renameService, newWorkspace, session, sessionCommit:=True)
End Using
End Using
End Function
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Async Function CSharp_FixupSpanDuringResolvableConflict_ContainedComplexifiedSpan(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
namespace N
{
class A<T>
{
public virtual void Goo(T x) { }
class B<S> : A<B<S>>
{
class [|$$C|]<U> : B<[|C|]<U>> // Rename C to A
{
public override void Goo(A<A<T>.B<S>>.B<A<T>.B<S>.[|C|]<U>> x) { }
}
}
}
}
]]>
</Document>
</Project>
</Workspace>, host)
Dim renameService = workspace.GetService(Of InlineRenameService)()
Dim session = StartSession(workspace)
Dim textBuffer = workspace.Documents.Single().GetTextBuffer()
Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Await VerifySpansBeforeConflictResolution(workspace, renameService)
' Apply edit so that we have a resolved reference conflict.
textBuffer.Replace(New Span(location, 1), "A")
' Verify fixup/resolved conflict span.
Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
namespace N
{
class A<T>
{
public virtual void Goo(T x) { }
class B<S> : A<B<S>>
{
class [|A|]<U> : B<[|A|]<U>> // Rename C to A
{
public override void Goo({|Complexified:N.{|Resolved:A|}<N.{|Resolved:A|}<T>.B<S>>|}.B<{|Complexified:N.{|Resolved:A|}<T>|}.B<S>.[|A|]<U>> x) { }
}
}
}
}
]]>
</Document>
</Project>
</Workspace>, host)
Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session, sessionCommit:=True)
End Using
End Using
End Function
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(8334, "https://github.com/dotnet/roslyn/issues/8334")>
Public Async Function CSharp_FixupSpanDuringResolvableConflict_ComplexificationReordersReferenceSpans(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
static class E
{
public static C [|$$Goo|](this C x, int tag) { return new C(); }
}
class C
{
C Bar(int tag)
{
return this.[|Goo|](1).[|Goo|](2);
}
}
</Document>
</Project>
</Workspace>, host)
Dim renameService = workspace.GetService(Of InlineRenameService)()
Dim session = StartSession(workspace)
Dim textBuffer = workspace.Documents.Single().GetTextBuffer()
Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Await VerifySpansBeforeConflictResolution(workspace, renameService)
' Apply edit so that we have a resolved reference conflict.
textBuffer.Replace(New Span(location, 3), "Bar")
' Verify fixup/resolved conflict span.
Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
static class E
{
public static C [|Bar|](this C x, int tag) { return new C(); }
}
class C
{
C Bar(int tag)
{
{|Complexified:return E.{|Resolved:[|Bar|]|}(E.{|Resolved:[|Bar|]|}(this, 1), 2);|}
}
}
</Document>
</Project>
</Workspace>, host)
Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session, sessionCommit:=True)
End Using
End Using
End Function
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Async Function CSharp_FixupSpanDuringResolvableConflict_WithinCrefs(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
using F = N;
namespace N
{
interface I
{
void Goo();
}
}
class C
{
class E : F.I
{
/// <summary>
/// This is a function <see cref="F.I.Goo"/>
/// </summary>
public void Goo() { }
}
class [|$$K|]
{
}
}
]]>
</Document>
</Project>
</Workspace>, host)
Dim renameService = workspace.GetService(Of InlineRenameService)()
Dim session = StartSession(workspace)
Dim textBuffer = workspace.Documents.Single().GetTextBuffer()
Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Await VerifySpansBeforeConflictResolution(workspace, renameService)
' Apply edit so that we have a resolved reference conflict.
textBuffer.Replace(New Span(location, 1), "F")
' Verify fixup/resolved conflict span.
Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
using F = N;
namespace N
{
interface I
{
void Goo();
}
}
class C
{
class E : {|Complexified:{|Resolved:N|}|}.I
{
/// <summary>
/// This is a function <see cref="{|Complexified:{|Resolved:N|}|}.I.Goo"/>
/// </summary>
public void Goo() { }
}
class [|$$F|]
{
}
}
]]>
</Document>
</Project>
</Workspace>, host)
Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session, sessionCommit:=True)
End Using
End Using
End Function
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Async Function CSharp_FixupSpanDuringResolvableConflict_OverLoadResolutionChangesInEnclosingInvocations(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
< { } // Rename Ex to Goo
}
]]>
</Document>
</Project>
</Workspace>, host)
Dim renameService = workspace.GetService(Of InlineRenameService)()
Dim session = StartSession(workspace)
Dim textBuffer = workspace.Documents.Single().GetTextBuffer()
Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Await VerifySpansBeforeConflictResolution(workspace, renameService)
' Apply edit so that we have a resolved reference conflict.
textBuffer.Replace(New Span(location, 2), "Goo")
' Verify fixup/resolved conflict span.
Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
< { } // Rename Ex to Goo
}
]]>
</Document>
</Project>
</Workspace>, host)
Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session, sessionCommit:=True)
End Using
End Using
End Function
<WpfTheory>
<WorkItem(530817, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530817")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Async Function CSharpShowDeclarationConflictsImmediately(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
static void Main(string[] args)
{
const int {|valid:$$V|} = 5;
int {|conflict:V|} = 99;
}
}
</Document>
</Project>
</Workspace>, host)
Dim renameService = workspace.GetService(Of InlineRenameService)()
Dim session = StartSession(workspace)
Dim validTaggedSpans = Await GetTagsOfType(HighlightTags.RenameFieldBackgroundAndBorderTag.Instance, workspace, renameService)
Dim validExpectedSpans = workspace.Documents.Single(Function(d) d.AnnotatedSpans.Count > 0).AnnotatedSpans("valid").Select(Function(ts) ts.ToSpan())
Dim conflictTaggedSpans = Await GetTagsOfType(RenameConflictTag.Instance, workspace, renameService)
Dim conflictExpectedSpans = workspace.Documents.Single(Function(d) d.AnnotatedSpans.Count > 0).AnnotatedSpans("conflict").Select(Function(ts) ts.ToSpan())
session.Cancel()
AssertEx.Equal(validExpectedSpans, validTaggedSpans)
AssertEx.Equal(conflictExpectedSpans, conflictTaggedSpans)
End Using
End Function
<WpfTheory>
<WorkItem(530817, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530817")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Async Function VBShowDeclarationConflictsImmediately(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Goo
Sub Bar()
Dim {|valid:$$V|} as Integer
Dim {|conflict:V|} as String
End Sub
End Class
</Document>
</Project>
</Workspace>, host)
Dim renameService = workspace.GetService(Of InlineRenameService)()
Dim session = StartSession(workspace)
Dim validTaggedSpans = Await GetTagsOfType(HighlightTags.RenameFieldBackgroundAndBorderTag.Instance, workspace, renameService)
Dim validExpectedSpans = workspace.Documents.Single(Function(d) d.AnnotatedSpans.Count > 0).AnnotatedSpans("valid").Select(Function(ts) ts.ToSpan())
Dim conflictTaggedSpans = Await GetTagsOfType(RenameConflictTag.Instance, workspace, renameService)
Dim conflictExpectedSpans = workspace.Documents.Single(Function(d) d.AnnotatedSpans.Count > 0).AnnotatedSpans("conflict").Select(Function(ts) ts.ToSpan())
session.Cancel()
AssertEx.Equal(validExpectedSpans, validTaggedSpans)
AssertEx.Equal(conflictExpectedSpans, conflictTaggedSpans)
End Using
End Function
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Async Function ActiveSpanInSecondaryView(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class [|$$Goo|]
End Class
</Document>
<Document>
' [|Goo|]
</Document>
</Project>
</Workspace>, host)
Dim renameService = workspace.GetService(Of InlineRenameService)()
Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Dim textBuffer = workspace.Documents(0).GetTextBuffer()
Dim session = StartSession(workspace)
session.RefreshRenameSessionWithOptionsChanged(CodeAnalysis.Rename.RenameOptions.RenameInComments, newValue:=True)
Await WaitForRename(workspace)
session.RefreshRenameSessionWithOptionsChanged(CodeAnalysis.Rename.RenameOptions.RenameInComments, newValue:=False)
Await WaitForRename(workspace)
textBuffer.Replace(New Span(location, 3), "Bar")
Await WaitForRename(workspace)
End Using
End Function
Private Shared Async Function GetTagsOfType(expectedTagType As ITextMarkerTag, workspace As TestWorkspace, renameService As InlineRenameService) As Task(Of IEnumerable(Of Span))
Dim textBuffer = workspace.Documents.Single().GetTextBuffer()
Await WaitForRename(workspace)
Return GetTagsOfType(expectedTagType, renameService, textBuffer)
End Function
Private Shared Function GetTagsOfType(expectedTagType As ITextMarkerTag, renameService As InlineRenameService, textBuffer As ITextBuffer) As IEnumerable(Of Span)
Dim tagger = New RenameTagger(textBuffer, renameService)
Dim tags = tagger.GetTags(textBuffer.CurrentSnapshot.GetSnapshotSpanCollection())
Return (From tag In tags
Where tag.Tag Is expectedTagType
Order By tag.Span.Start
Select tag.Span.Span).ToList()
End Function
End Class
End Namespace
|
AmadeusW/roslyn
|
src/EditorFeatures/Test2/Rename/RenameTagProducerTests.vb
|
Visual Basic
|
apache-2.0
| 73,739
|
Namespace Microsoft.CodeAnalysis.VisualBasic
Friend Partial Module ErrorFacts
Public Function IsWarning(code as ERRID) As Boolean
Select Case code
Case ERRID.WRN_BadSwitch,
ERRID.WRN_NoConfigInResponseFile,
ERRID.WRN_IgnoreModuleManifest,
ERRID.WRN_BadUILang,
ERRID.WRN_UseOfObsoleteSymbol2,
ERRID.WRN_InvalidOverrideDueToTupleNames2,
ERRID.WRN_MustOverloadBase4,
ERRID.WRN_OverrideType5,
ERRID.WRN_MustOverride2,
ERRID.WRN_DefaultnessShadowed4,
ERRID.WRN_UseOfObsoleteSymbolNoMessage1,
ERRID.WRN_AssemblyGeneration0,
ERRID.WRN_AssemblyGeneration1,
ERRID.WRN_ComClassNoMembers1,
ERRID.WRN_SynthMemberShadowsMember5,
ERRID.WRN_MemberShadowsSynthMember6,
ERRID.WRN_SynthMemberShadowsSynthMember7,
ERRID.WRN_UseOfObsoletePropertyAccessor3,
ERRID.WRN_UseOfObsoletePropertyAccessor2,
ERRID.WRN_FieldNotCLSCompliant1,
ERRID.WRN_BaseClassNotCLSCompliant2,
ERRID.WRN_ProcTypeNotCLSCompliant1,
ERRID.WRN_ParamNotCLSCompliant1,
ERRID.WRN_InheritedInterfaceNotCLSCompliant2,
ERRID.WRN_CLSMemberInNonCLSType3,
ERRID.WRN_NameNotCLSCompliant1,
ERRID.WRN_EnumUnderlyingTypeNotCLS1,
ERRID.WRN_NonCLSMemberInCLSInterface1,
ERRID.WRN_NonCLSMustOverrideInCLSType1,
ERRID.WRN_ArrayOverloadsNonCLS2,
ERRID.WRN_RootNamespaceNotCLSCompliant1,
ERRID.WRN_RootNamespaceNotCLSCompliant2,
ERRID.WRN_GenericConstraintNotCLSCompliant1,
ERRID.WRN_TypeNotCLSCompliant1,
ERRID.WRN_OptionalValueNotCLSCompliant1,
ERRID.WRN_CLSAttrInvalidOnGetSet,
ERRID.WRN_TypeConflictButMerged6,
ERRID.WRN_ShadowingGenericParamWithParam1,
ERRID.WRN_CannotFindStandardLibrary1,
ERRID.WRN_EventDelegateTypeNotCLSCompliant2,
ERRID.WRN_DebuggerHiddenIgnoredOnProperties,
ERRID.WRN_SelectCaseInvalidRange,
ERRID.WRN_CLSEventMethodInNonCLSType3,
ERRID.WRN_ExpectedInitComponentCall2,
ERRID.WRN_NamespaceCaseMismatch3,
ERRID.WRN_UndefinedOrEmptyNamespaceOrClass1,
ERRID.WRN_UndefinedOrEmptyProjectNamespaceOrClass1,
ERRID.WRN_IndirectRefToLinkedAssembly2,
ERRID.WRN_DelaySignButNoKey,
ERRID.WRN_UnimplementedCommandLineSwitch,
ERRID.WRN_NoNonObsoleteConstructorOnBase3,
ERRID.WRN_NoNonObsoleteConstructorOnBase4,
ERRID.WRN_RequiredNonObsoleteNewCall3,
ERRID.WRN_RequiredNonObsoleteNewCall4,
ERRID.WRN_MissingAsClauseinOperator,
ERRID.WRN_ConstraintsFailedForInferredArgs2,
ERRID.WRN_ConditionalNotValidOnFunction,
ERRID.WRN_UseSwitchInsteadOfAttribute,
ERRID.WRN_TupleLiteralNameMismatch,
ERRID.WRN_ReferencedAssemblyDoesNotHaveStrongName,
ERRID.WRN_RecursiveAddHandlerCall,
ERRID.WRN_ImplicitConversionCopyBack,
ERRID.WRN_MustShadowOnMultipleInheritance2,
ERRID.WRN_RecursiveOperatorCall,
ERRID.WRN_ImplicitConversionSubst1,
ERRID.WRN_LateBindingResolution,
ERRID.WRN_ObjectMath1,
ERRID.WRN_ObjectMath2,
ERRID.WRN_ObjectAssumedVar1,
ERRID.WRN_ObjectAssumed1,
ERRID.WRN_ObjectAssumedProperty1,
ERRID.WRN_UnusedLocal,
ERRID.WRN_SharedMemberThroughInstance,
ERRID.WRN_RecursivePropertyCall,
ERRID.WRN_OverlappingCatch,
ERRID.WRN_DefAsgUseNullRefByRef,
ERRID.WRN_DuplicateCatch,
ERRID.WRN_ObjectMath1Not,
ERRID.WRN_BadChecksumValExtChecksum,
ERRID.WRN_MultipleDeclFileExtChecksum,
ERRID.WRN_BadGUIDFormatExtChecksum,
ERRID.WRN_ObjectMathSelectCase,
ERRID.WRN_EqualToLiteralNothing,
ERRID.WRN_NotEqualToLiteralNothing,
ERRID.WRN_UnusedLocalConst,
ERRID.WRN_ComClassInterfaceShadows5,
ERRID.WRN_ComClassPropertySetObject1,
ERRID.WRN_DefAsgUseNullRef,
ERRID.WRN_DefAsgNoRetValFuncRef1,
ERRID.WRN_DefAsgNoRetValOpRef1,
ERRID.WRN_DefAsgNoRetValPropRef1,
ERRID.WRN_DefAsgUseNullRefByRefStr,
ERRID.WRN_DefAsgUseNullRefStr,
ERRID.WRN_StaticLocalNoInference,
ERRID.WRN_InvalidAssemblyName,
ERRID.WRN_XMLDocBadXMLLine,
ERRID.WRN_XMLDocMoreThanOneCommentBlock,
ERRID.WRN_XMLDocNotFirstOnLine,
ERRID.WRN_XMLDocInsideMethod,
ERRID.WRN_XMLDocParseError1,
ERRID.WRN_XMLDocDuplicateXMLNode1,
ERRID.WRN_XMLDocIllegalTagOnElement2,
ERRID.WRN_XMLDocBadParamTag2,
ERRID.WRN_XMLDocParamTagWithoutName,
ERRID.WRN_XMLDocCrefAttributeNotFound1,
ERRID.WRN_XMLMissingFileOrPathAttribute1,
ERRID.WRN_XMLCannotWriteToXMLDocFile2,
ERRID.WRN_XMLDocWithoutLanguageElement,
ERRID.WRN_XMLDocReturnsOnWriteOnlyProperty,
ERRID.WRN_XMLDocOnAPartialType,
ERRID.WRN_XMLDocReturnsOnADeclareSub,
ERRID.WRN_XMLDocStartTagWithNoEndTag,
ERRID.WRN_XMLDocBadGenericParamTag2,
ERRID.WRN_XMLDocGenericParamTagWithoutName,
ERRID.WRN_XMLDocExceptionTagWithoutCRef,
ERRID.WRN_XMLDocInvalidXMLFragment,
ERRID.WRN_XMLDocBadFormedXML,
ERRID.WRN_InterfaceConversion2,
ERRID.WRN_LiftControlVariableLambda,
ERRID.WRN_LambdaPassedToRemoveHandler,
ERRID.WRN_LiftControlVariableQuery,
ERRID.WRN_RelDelegatePassedToRemoveHandler,
ERRID.WRN_AmbiguousCastConversion2,
ERRID.WRN_VarianceDeclarationAmbiguous3,
ERRID.WRN_ArrayInitNoTypeObjectAssumed,
ERRID.WRN_TypeInferenceAssumed3,
ERRID.WRN_VarianceConversionFailedOut6,
ERRID.WRN_VarianceConversionFailedIn6,
ERRID.WRN_VarianceIEnumerableSuggestion3,
ERRID.WRN_VarianceConversionFailedTryOut4,
ERRID.WRN_VarianceConversionFailedTryIn4,
ERRID.WRN_IfNoTypeObjectAssumed,
ERRID.WRN_IfTooManyTypesObjectAssumed,
ERRID.WRN_ArrayInitTooManyTypesObjectAssumed,
ERRID.WRN_LambdaNoTypeObjectAssumed,
ERRID.WRN_LambdaTooManyTypesObjectAssumed,
ERRID.WRN_MissingAsClauseinVarDecl,
ERRID.WRN_MissingAsClauseinFunction,
ERRID.WRN_MissingAsClauseinProperty,
ERRID.WRN_ObsoleteIdentityDirectCastForValueType,
ERRID.WRN_ImplicitConversion2,
ERRID.WRN_MutableStructureInUsing,
ERRID.WRN_MutableGenericStructureInUsing,
ERRID.WRN_DefAsgNoRetValFuncVal1,
ERRID.WRN_DefAsgNoRetValOpVal1,
ERRID.WRN_DefAsgNoRetValPropVal1,
ERRID.WRN_AsyncLacksAwaits,
ERRID.WRN_AsyncSubCouldBeFunction,
ERRID.WRN_UnobservedAwaitableExpression,
ERRID.WRN_UnobservedAwaitableDelegate,
ERRID.WRN_PrefixAndXmlnsLocalName,
ERRID.WRN_UseValueForXmlExpression3,
ERRID.WRN_ReturnTypeAttributeOnWriteOnlyProperty,
ERRID.WRN_InvalidVersionFormat,
ERRID.WRN_MainIgnored,
ERRID.WRN_EmptyPrefixAndXmlnsLocalName,
ERRID.WRN_DefAsgNoRetValWinRtEventVal1,
ERRID.WRN_AssemblyAttributeFromModuleIsOverridden,
ERRID.WRN_RefCultureMismatch,
ERRID.WRN_ConflictingMachineAssembly,
ERRID.WRN_PdbLocalNameTooLong,
ERRID.WRN_PdbUsingNameTooLong,
ERRID.WRN_XMLDocCrefToTypeParameter,
ERRID.WRN_AnalyzerCannotBeCreated,
ERRID.WRN_NoAnalyzerInAssembly,
ERRID.WRN_UnableToLoadAnalyzer,
ERRID.WRN_AttributeIgnoredWhenPublicSigning,
ERRID.WRN_Experimental
Return True
Case Else
Return False
End Select
End Function
Public Function IsFatal(code as ERRID) As Boolean
Select Case code
Case ERRID.FTL_InvalidInputFileName
Return True
Case Else
Return False
End Select
End Function
Public Function IsInfo(code as ERRID) As Boolean
Select Case code
Case ERRID.INF_UnableToLoadSomeTypesInAnalyzer
Return True
Case Else
Return False
End Select
End Function
Public Function IsHidden(code as ERRID) As Boolean
Select Case code
Case ERRID.HDN_UnusedImportClause,
ERRID.HDN_UnusedImportStatement
Return True
Case Else
Return False
End Select
End Function
End Module
End Namespace
|
VSadov/roslyn
|
src/Compilers/VisualBasic/Portable/Generated/ErrorFacts.Generated.vb
|
Visual Basic
|
apache-2.0
| 10,820
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.KeywordHighlighting
Public Class WhileBlockHighlighterTests
Inherits AbstractVisualBasicKeywordHighlighterTests
Friend Overrides Function CreateHighlighter() As IHighlighter
Return New WhileBlockHighlighter()
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)>
Public Async Function TestWhileBlock1() As Task
Await TestAsync(<Text>
Class C
Sub M()
{|Cursor:[|While|]|} True
If x Then
[|Exit While|]
Else
[|Continue While|]
End If
[|End While|]
End Sub
End Class</Text>)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)>
Public Async Function TestWhileBlock2() As Task
Await TestAsync(<Text>
Class C
Sub M()
[|While|] True
If x Then
{|Cursor:[|Exit While|]|}
Else
[|Continue While|]
End If
[|End While|]
End Sub
End Class</Text>)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)>
Public Async Function TestWhileBlock3() As Task
Await TestAsync(<Text>
Class C
Sub M()
[|While|] True
If x Then
[|Exit While|]
Else
{|Cursor:[|Continue While|]|}
End If
[|End While|]
End Sub
End Class</Text>)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)>
Public Async Function TestWhileBlock4() As Task
Await TestAsync(<Text>
Class C
Sub M()
[|While|] True
If x Then
[|Exit While|]
Else
[|Continue While|]
End If
{|Cursor:[|End While|]|}
End Sub
End Class</Text>)
End Function
End Class
End Namespace
|
bbarry/roslyn
|
src/EditorFeatures/VisualBasicTest/KeywordHighlighting/WhileBlockHighlighterTests.vb
|
Visual Basic
|
apache-2.0
| 2,001
|
' 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.
Imports System
Imports System.Collections.Immutable
Imports System.Reflection.Metadata
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
Imports Microsoft.CodeAnalysis.ExpressionEvaluator
Imports Microsoft.CodeAnalysis.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator
Friend NotInheritable Class VisualBasicEESymbolProvider
Inherits EESymbolProvider(Of TypeSymbol, LocalSymbol)
Private ReadOnly _metadataDecoder As MetadataDecoder
Private ReadOnly _method As PEMethodSymbol
Public Sub New([module] As PEModuleSymbol, method As PEMethodSymbol)
_metadataDecoder = New MetadataDecoder([module], method)
_method = method
End Sub
Public Overrides Function GetLocalVariable(
name As String,
slotIndex As Integer,
info As LocalInfo(Of TypeSymbol),
dynamicFlagsOpt As ImmutableArray(Of Boolean),
tupleElementNamesOpt As ImmutableArray(Of String)) As LocalSymbol
' Custom modifiers can be dropped since binding ignores custom
' modifiers from locals and since we only need to preserve
' the type of the original local in the generated method.
Dim kind = If(name = _method.Name, LocalDeclarationKind.FunctionValue, LocalDeclarationKind.Variable)
Dim type = IncludeTupleElementNamesIfAny(info.Type, tupleElementNamesOpt)
Return New EELocalSymbol(_method, EELocalSymbol.NoLocations, name, slotIndex, kind, type, info.IsByRef, info.IsPinned, canScheduleToStack:=False)
End Function
Public Overrides Function GetLocalConstant(
name As String,
type As TypeSymbol,
value As ConstantValue,
dynamicFlagsOpt As ImmutableArray(Of Boolean),
tupleElementNamesOpt As ImmutableArray(Of String)) As LocalSymbol
type = IncludeTupleElementNamesIfAny(type, tupleElementNamesOpt)
Return New EELocalConstantSymbol(_method, name, type, value)
End Function
''' <exception cref="BadImageFormatException"></exception>
''' <exception cref="UnsupportedSignatureContent"></exception>
Public Overrides Function DecodeLocalVariableType(signature As ImmutableArray(Of Byte)) As TypeSymbol
Return _metadataDecoder.DecodeLocalVariableTypeOrThrow(signature)
End Function
Public Overrides Function GetTypeSymbolForSerializedType(typeName As String) As TypeSymbol
Return _metadataDecoder.GetTypeSymbolForSerializedType(typeName)
End Function
''' <exception cref="BadImageFormatException"></exception>
''' <exception cref="UnsupportedSignatureContent"></exception>
Public Overrides Sub DecodeLocalConstant(ByRef reader As BlobReader, ByRef type As TypeSymbol, ByRef value As ConstantValue)
_metadataDecoder.DecodeLocalConstantBlobOrThrow(reader, type, value)
End Sub
''' <exception cref="BadImageFormatException"></exception>
Public Overrides Function GetReferencedAssembly(handle As AssemblyReferenceHandle) As IAssemblySymbolInternal
Dim index As Integer = _metadataDecoder.Module.GetAssemblyReferenceIndexOrThrow(handle)
Dim assembly = _metadataDecoder.ModuleSymbol.GetReferencedAssemblySymbol(index)
' GetReferencedAssemblySymbol should not return Nothing since this method is
' only used for import aliases in the PDB which are not supported from VB.
Return assembly
End Function
''' <exception cref="UnsupportedSignatureContent"></exception>
Public Overrides Function [GetType](handle As EntityHandle) As TypeSymbol
Dim isNoPiaLocalType As Boolean
Return _metadataDecoder.GetSymbolForTypeHandleOrThrow(handle, isNoPiaLocalType, allowTypeSpec:=True, requireShortForm:=False)
End Function
Private Function IncludeTupleElementNamesIfAny(type As TypeSymbol, tupleElementNamesOpt As ImmutableArray(Of String)) As TypeSymbol
Return TupleTypeDecoder.DecodeTupleTypesIfApplicable(type, tupleElementNamesOpt)
End Function
End Class
End Namespace
|
AlekseyTs/roslyn
|
src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/VisualBasicEESymbolProvider.vb
|
Visual Basic
|
mit
| 4,500
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.KeywordHighlighting
Public Class MultiLineIfBlockHighlighterTests
Inherits AbstractVisualBasicKeywordHighlighterTests
Friend Overrides Function CreateHighlighter() As IHighlighter
Return New MultiLineIfBlockHighlighter()
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)>
Public Sub TestMultilineIf1()
Test(<Text><![CDATA[
Class C
Sub M()
{|Cursor:[|If|]|} a < b [|Then|]
a = b
[|ElseIf|] DateTime.Now.Ticks Mod 2 = 0
Throw New RandomException
[|Else|]
If a < b Then a = b Else b = a
[|End If|]
End Sub
End Class]]></Text>)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)>
Public Sub TestMultilineIf2()
Test(<Text><![CDATA[
Class C
Sub M()
[|If|] a < b {|Cursor:[|Then|]|}
a = b
[|ElseIf|] DateTime.Now.Ticks Mod 2 = 0
Throw New RandomException
[|Else|]
If a < b Then a = b Else b = a
[|End If|]
End Sub
End Class]]></Text>)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)>
Public Sub TestMultilineIf3()
Test(<Text><![CDATA[
Class C
Sub M()
[|If|] a < b [|Then|]
a = b
{|Cursor:[|ElseIf|]|} DateTime.Now.Ticks Mod 2 = 0
Throw New RandomException
[|Else|]
If a < b Then a = b Else b = a
[|End If|]
End Sub
End Class]]></Text>)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)>
Public Sub TestMultilineIf4()
Test(<Text><![CDATA[
Class C
Sub M()
[|If|] a < b [|Then|]
a = b
[|ElseIf|] DateTime.Now.Ticks Mod 2 = 0
Throw New RandomException
[|{|Cursor:Else|}|]
If a < b Then a = b Else b = a
[|End If|]
End Sub
End Class]]></Text>)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)>
Public Sub TestMultilineIf5()
Test(<Text><![CDATA[
Class C
Sub M()
[|If|] a < b [|Then|]
a = b
[|ElseIf|] DateTime.Now.Ticks Mod 2 = 0
Throw New RandomException
[|Else|]
If a < b Then a = b Else b = a
{|Cursor:[|End If|]|}
End Sub
End Class]]></Text>)
End Sub
<WorkItem(542614)>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)>
Public Sub TestMultilineIf6()
Test(<Text><![CDATA[
Imports System
Module M
Sub C()
Dim x As Integer = 5
[|If|] x < 0 [|Then|]
{|Cursor:[|Else If|]|}
[|End If|]
End Sub
End Module]]></Text>)
End Sub
End Class
End Namespace
|
droyad/roslyn
|
src/EditorFeatures/VisualBasicTest/KeywordHighlighting/MultiLineIfBlockHighlighterTests.vb
|
Visual Basic
|
apache-2.0
| 2,847
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.42000
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
<Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0"), _
Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Partial Friend NotInheritable Class MySettings
Inherits Global.System.Configuration.ApplicationSettingsBase
Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings), MySettings)
#Region "My.Settings Auto-Save Functionality"
#If _MyType = "WindowsForms" Then
Private Shared addedHandler As Boolean
Private Shared addedHandlerLockObject As New Object
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs)
If My.Application.SaveMySettingsOnExit Then
My.Settings.Save()
End If
End Sub
#End If
#End Region
Public Shared ReadOnly Property [Default]() As MySettings
Get
#If _MyType = "WindowsForms" Then
If Not addedHandler Then
SyncLock addedHandlerLockObject
If Not addedHandler Then
AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings
addedHandler = True
End If
End SyncLock
End If
#End If
Return defaultInstance
End Get
End Property
End Class
End Namespace
Namespace My
<Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _
Friend Module MySettingsProperty
<Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _
Friend ReadOnly Property Settings() As Global.Rodriguez_GuessingGame.My.MySettings
Get
Return Global.Rodriguez_GuessingGame.My.MySettings.Default
End Get
End Property
End Module
End Namespace
|
miguel2192/CSC-162
|
Rodriguez_GuessingGame/Rodriguez_GuessingGame/My Project/Settings.Designer.vb
|
Visual Basic
|
mit
| 2,950
|
Imports System.Xml.Serialization
Friend Class SerializerCache
Private Shared hash As New Hashtable()
''' <summary>
'''
''' </summary>
''' <param name="type"></param>
''' <returns></returns>
Friend Shared Function GetSerializer(ByVal type As Type) As XmlSerializer
Dim res As XmlSerializer = Nothing
SyncLock hash
res = TryCast(hash(type.FullName), XmlSerializer)
If res Is Nothing Then
res = New XmlSerializer(type)
hash(type.FullName) = res
End If
End SyncLock
Return res
End Function
End Class
|
skitsanos/WDK10
|
WDK.XML.Utils/SerializerCache.vb
|
Visual Basic
|
mit
| 633
|
Imports System.Configuration
Imports System.Data.Common
Imports log4net
Public Class DatabaseTestBase
Inherits TestBase
Private Shared ReadOnly Log As ILog = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod.DeclaringType)
Protected Overrides Sub SetUp()
MyBase.SetUp()
DeleteRecords()
End Sub
Protected Overridable Sub DeleteRecords()
Dim connectionString As ConnectionStringSettings = ConfigurationManager.ConnectionStrings("SiphonTests")
Dim factory As DbProviderFactory = DbProviderFactories.GetFactory(connectionString.ProviderName)
Using connection As IDbConnection = factory.CreateConnection
connection.ConnectionString = connectionString.ConnectionString
Using command As IDbCommand = factory.CreateCommand
command.CommandText = "Delete From DatabaseMonitor"
command.CommandType = CommandType.Text
command.Connection = connection
connection.Open()
command.ExecuteNonQuery()
connection.Close()
End Using
End Using
End Sub
Protected Overridable Function GetRecords() As DataTable
Dim connectionString As ConnectionStringSettings = ConfigurationManager.ConnectionStrings("SiphonTests")
Dim factory As DbProviderFactory = DbProviderFactories.GetFactory(connectionString.ProviderName)
Dim adapter As DbDataAdapter = factory.CreateDataAdapter
Dim table As New DataTable
Using connection As IDbConnection = factory.CreateConnection
connection.ConnectionString = connectionString.ConnectionString
Using command As IDbCommand = factory.CreateCommand
command.CommandText = "Select * From DatabaseMonitor"
command.CommandType = CommandType.Text
command.Connection = connection
adapter.SelectCommand = command
adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey
connection.Open()
adapter.Fill(table)
connection.Close()
End Using
End Using
Return table
End Function
Protected Overridable Sub CreateRecord(ByVal record As Dictionary(Of String, Object))
Dim connectionString As ConnectionStringSettings = ConfigurationManager.ConnectionStrings("SiphonTests")
Dim factory As DbProviderFactory = DbProviderFactories.GetFactory(connectionString.ProviderName)
Using connection As IDbConnection = factory.CreateConnection
connection.ConnectionString = connectionString.ConnectionString
Using command As IDbCommand = factory.CreateCommand
command.CommandText = String.Format("Insert Into DatabaseMonitor ({0}) Values (@{1});", String.Join(",", record.Keys.ToArray), String.Join(", @", record.Keys.ToArray))
command.CommandType = CommandType.Text
command.Connection = connection
For Each column As String In record.Keys
Dim parameter As IDbDataParameter = factory.CreateParameter
parameter.ParameterName = String.Format("@{0}", column)
parameter.Value = record(column)
command.Parameters.Add(parameter)
Next
connection.Open()
command.ExecuteNonQuery()
connection.Close()
End Using
End Using
End Sub
Protected Overridable Sub CreateSuccessRecord(Optional ByVal name As String = "SUCCESS")
Dim row As New Dictionary(Of String, Object)
row("Name") = name
CreateRecord(row)
End Sub
Protected Overridable Sub CreateFailureRecord(Optional ByVal name As String = "FAILURE")
Dim row As New Dictionary(Of String, Object)
row("Name") = name
CreateRecord(row)
End Sub
Protected Overridable Sub CreateExceptionRecord(Optional ByVal name As String = "EXCEPTION")
Dim row As New Dictionary(Of String, Object)
row("Name") = name
CreateRecord(row)
End Sub
End Class
|
claco/siphon
|
SiphonTests/DatabaseTestBase.vb
|
Visual Basic
|
mit
| 4,200
|
Friend Module Config
Public Property useXkey As Boolean = False
Public Property MainForm As Main
Public Property ConfigForm As ConfigForm
Public Property AppSwither As AppSwither
End Module
|
ErikV88/AppSwitcherPlussPluss
|
AppSwitcher++/Config.vb
|
Visual Basic
|
mit
| 210
|
' This file was generated by CSLA Object Generator - CslaGenFork v4.5
'
' Filename: DocType
' ObjectType: DocType
' CSLAType: EditableRoot
Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports Csla
Imports Csla.Data
Imports DocStore.Business.Util
Imports Csla.Rules
Imports Csla.Rules.CommonRules
Imports DocStore.Business.Security
Namespace DocStore.Business
''' <summary>
''' Document type (editable root object).<br/>
''' This is a generated base class of <see cref="DocType"/> business object.
''' </summary>
<Serializable>
Public Partial Class DocType
Inherits BusinessBase(Of DocType)
#Region " Static Fields "
Private Shared _lastId As Integer
#End Region
#Region " Business Properties "
''' <summary>
''' Maintains metadata about <see cref="DocTypeID"/> property.
''' </summary>
<NotUndoable>
Public Shared ReadOnly DocTypeIDProperty As PropertyInfo(Of Integer) = RegisterProperty(Of Integer)(Function(p) p.DocTypeID, "Doc Type ID")
''' <summary>
''' Gets the Doc Type ID.
''' </summary>
''' <value>The Doc Type ID.</value>
Public ReadOnly Property DocTypeID As Integer
Get
Return GetProperty(DocTypeIDProperty)
End Get
End Property
''' <summary>
''' Maintains metadata about <see cref="DocTypeName"/> property.
''' </summary>
Public Shared ReadOnly DocTypeNameProperty As PropertyInfo(Of String) = RegisterProperty(Of String)(Function(p) p.DocTypeName, "Doc Type Name")
''' <summary>
''' Gets or sets the Doc Type Name.
''' </summary>
''' <value>The Doc Type Name.</value>
Public Property DocTypeName As String
Get
Return GetProperty(DocTypeNameProperty)
End Get
Set(ByVal value As String)
SetProperty(DocTypeNameProperty, value)
End Set
End Property
''' <summary>
''' Maintains metadata about <see cref="CreateDate"/> property.
''' </summary>
Public Shared ReadOnly CreateDateProperty As PropertyInfo(Of SmartDate) = RegisterProperty(Of SmartDate)(Function(p) p.CreateDate, "Create Date")
''' <summary>
''' Gets the Create Date.
''' </summary>
''' <value>The Create Date.</value>
Public ReadOnly Property CreateDate As SmartDate
Get
Return GetProperty(CreateDateProperty)
End Get
End Property
''' <summary>
''' Maintains metadata about <see cref="CreateUserID"/> property.
''' </summary>
Public Shared ReadOnly CreateUserIDProperty As PropertyInfo(Of Integer) = RegisterProperty(Of Integer)(Function(p) p.CreateUserID, "Create User ID")
''' <summary>
''' Gets the Create User ID.
''' </summary>
''' <value>The Create User ID.</value>
Public ReadOnly Property CreateUserID As Integer
Get
Return GetProperty(CreateUserIDProperty)
End Get
End Property
''' <summary>
''' Maintains metadata about <see cref="ChangeDate"/> property.
''' </summary>
Public Shared ReadOnly ChangeDateProperty As PropertyInfo(Of SmartDate) = RegisterProperty(Of SmartDate)(Function(p) p.ChangeDate, "Change Date")
''' <summary>
''' Gets the Change Date.
''' </summary>
''' <value>The Change Date.</value>
Public ReadOnly Property ChangeDate As SmartDate
Get
Return GetProperty(ChangeDateProperty)
End Get
End Property
''' <summary>
''' Maintains metadata about <see cref="ChangeUserID"/> property.
''' </summary>
Public Shared ReadOnly ChangeUserIDProperty As PropertyInfo(Of Integer) = RegisterProperty(Of Integer)(Function(p) p.ChangeUserID, "Change User ID")
''' <summary>
''' Gets the Change User ID.
''' </summary>
''' <value>The Change User ID.</value>
Public ReadOnly Property ChangeUserID As Integer
Get
Return GetProperty(ChangeUserIDProperty)
End Get
End Property
''' <summary>
''' Maintains metadata about <see cref="RowVersion"/> property.
''' </summary>
<NotUndoable>
Public Shared ReadOnly RowVersionProperty As PropertyInfo(Of Byte()) = RegisterProperty(Of Byte())(Function(p) p.RowVersion, "Row Version")
''' <summary>
''' Gets the Row Version.
''' </summary>
''' <value>The Row Version.</value>
Public ReadOnly Property RowVersion As Byte()
Get
Return GetProperty(RowVersionProperty)
End Get
End Property
''' <summary>
''' Gets the Create User Name.
''' </summary>
''' <value>The Create User Name.</value>
Public ReadOnly Property CreateUserName As String
Get
Dim result = String.Empty
If Admin.UserNVL.GetUserNVL().ContainsKey(CreateUserID) Then
result = Admin.UserNVL.GetUserNVL().GetItemByKey(CreateUserID).Value
End If
Return result
End Get
End Property
''' <summary>
''' Gets the Change User Name.
''' </summary>
''' <value>The Change User Name.</value>
Public ReadOnly Property ChangeUserName As String
Get
Dim result = String.Empty
If Admin.UserNVL.GetUserNVL().ContainsKey(ChangeUserID) Then
result = Admin.UserNVL.GetUserNVL().GetItemByKey(ChangeUserID).Value
End If
Return result
End Get
End Property
#End Region
#Region " BusinessBase(Of T) Overrides "
''' <summary>
''' Returns a string that represents the current <see cref="DocType"/>
''' </summary>
''' <returns>A <see cref="System.String"/> that represents this instance.</returns>
Public Overrides Function ToString() As String
' Return the Primary Key as a string
Return DocTypeName.ToString()
End Function
#End Region
#Region " Factory Methods "
''' <summary>
''' Factory method. Creates a new <see cref="DocType"/> object.
''' </summary>
''' <returns>A reference to the created <see cref="DocType"/> object.</returns>
Public Shared Function NewDocType() As DocType
Return DataPortal.Create(Of DocType)()
End Function
''' <summary>
''' Factory method. Loads a <see cref="DocType"/> object, based on given parameters.
''' </summary>
''' <param name="docTypeID">The DocTypeID parameter of the DocType to fetch.</param>
''' <returns>A reference to the fetched <see cref="DocType"/> object.</returns>
Public Shared Function GetDocType(docTypeID As Integer) As DocType
Return DataPortal.Fetch(Of DocType)(docTypeID)
End Function
''' <summary>
''' Factory method. Deletes a <see cref="DocType"/> object, based on given parameters.
''' </summary>
''' <param name="docTypeID">The DocTypeID of the DocType to delete.</param>
Public Shared Sub DeleteDocType(docTypeID As Integer)
DataPortal.Delete(Of DocType)(docTypeID)
End Sub
''' <summary>
''' Factory method. Asynchronously creates a new <see cref="DocType"/> object.
''' </summary>
''' <param name="callback">The completion callback method.</param>
Public Shared Sub NewDocType(callback As EventHandler(Of DataPortalResult(Of DocType)))
DataPortal.BeginCreate(Of DocType)(callback)
End Sub
''' <summary>
''' Factory method. Asynchronously loads a <see cref="DocType"/> object, based on given parameters.
''' </summary>
''' <param name="docTypeID">The DocTypeID parameter of the DocType to fetch.</param>
''' <param name="callback">The completion callback method.</param>
Public Shared Sub GetDocType(docTypeID As Integer, ByVal callback As EventHandler(Of DataPortalResult(Of DocType)))
DataPortal.BeginFetch(Of DocType)(docTypeID, callback)
End Sub
''' <summary>
''' Factory method. Asynchronously deletes a <see cref="DocType"/> object, based on given parameters.
''' </summary>
''' <param name="docTypeID">The DocTypeID of the DocType to delete.</param>
''' <param name="callback">The completion callback method.</param>
Public Shared Sub DeleteDocType(docTypeID As Integer, callback As EventHandler(Of DataPortalResult(Of DocType)))
DataPortal.BeginDelete(Of DocType)(docTypeID, callback)
End Sub
#End Region
#Region " Constructor "
''' <summary>
''' Initializes a new instance of the <see cref="DocType"/> class.
''' </summary>
''' <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
<System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)>
Public Sub New()
' Use factory methods and do not use direct creation.
End Sub
#End Region
#Region " Object Authorization "
''' <summary>
''' Adds the object authorization rules.
''' </summary>
Protected Shared Sub AddObjectAuthorizationRules()
BusinessRules.AddRule(GetType(DocType), New IsInRole(AuthorizationActions.CreateObject, "Manager"))
BusinessRules.AddRule(GetType(DocType), New IsInRole(AuthorizationActions.GetObject, "User"))
BusinessRules.AddRule(GetType(DocType), New IsInRole(AuthorizationActions.EditObject, "Manager"))
BusinessRules.AddRule(GetType(DocType), New IsInRole(AuthorizationActions.DeleteObject, "Admin"))
AddObjectAuthorizationRulesExtend()
End Sub
''' <summary>
''' Allows the set up of custom object authorization rules.
''' </summary>
Partial Private Shared Sub AddObjectAuthorizationRulesExtend()
End Sub
''' <summary>
''' Checks if the current user can create a new DocType object.
''' </summary>
''' <returns><c>True</c> if the user can create a new object; otherwise, <c>false</c>.</returns>
Public Overloads Shared Function CanAddObject() As Boolean
Return BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.CreateObject, GetType(DocType))
End Function
''' <summary>
''' Checks if the current user can retrieve DocType's properties.
''' </summary>
''' <returns><c>True</c> if the user can read the object; otherwise, <c>false</c>.</returns>
Public Overloads Shared Function CanGetObject() As Boolean
Return BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.GetObject, GetType(DocType))
End Function
''' <summary>
''' Checks if the current user can change DocType's properties.
''' </summary>
''' <returns><c>True</c> if the user can update the object; otherwise, <c>false</c>.</returns>
Public Overloads Shared Function CanEditObject() As Boolean
Return BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.EditObject, GetType(DocType))
End Function
''' <summary>
''' Checks if the current user can delete a DocType object.
''' </summary>
''' <returns><c>True</c> if the user can delete the object; otherwise, <c>false</c>.</returns>
Public Overloads Shared Function CanDeleteObject() As Boolean
Return BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.DeleteObject, GetType(DocType))
End Function
#End Region
#Region " Data Access "
''' <summary>
''' Loads default values for the <see cref="DocType"/> object properties.
''' </summary>
<RunLocal>
Protected Overrides Sub DataPortal_Create()
LoadProperty(DocTypeIDProperty, System.Threading.Interlocked.Decrement(_lastId))
LoadProperty(CreateDateProperty, new SmartDate(Date.Now))
LoadProperty(CreateUserIDProperty, UserInformation.UserId)
LoadProperty(ChangeDateProperty, ReadProperty(CreateDateProperty))
LoadProperty(ChangeUserIDProperty, ReadProperty(CreateUserIDProperty))
Dim args As New DataPortalHookArgs()
OnCreate(args)
MyBase.DataPortal_Create()
End Sub
''' <summary>
''' Loads a <see cref="DocType"/> object from the database, based on given criteria.
''' </summary>
''' <param name="docTypeID">The Doc Type ID.</param>
Protected Sub DataPortal_Fetch(docTypeID As Integer)
Using ctx = ConnectionManager(Of SqlConnection).GetManager(Database.DocStoreConnection, False)
Using cmd = New SqlCommand("GetDocType", ctx.Connection)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("@DocTypeID", docTypeID).DbType = DbType.Int32
Dim args As New DataPortalHookArgs(cmd, docTypeID)
OnFetchPre(args)
Fetch(cmd)
OnFetchPost(args)
End Using
End Using
' check all object rules and property rules
BusinessRules.CheckRules()
End Sub
Private Sub Fetch(cmd As SqlCommand)
Using dr As New SafeDataReader(cmd.ExecuteReader())
If dr.Read() Then
Fetch(dr)
End If
End Using
End Sub
''' <summary>
''' Loads a <see cref="DocType"/> object from the given SafeDataReader.
''' </summary>
''' <param name="dr">The SafeDataReader to use.</param>
Private Sub Fetch(dr As SafeDataReader)
' Value properties
LoadProperty(DocTypeIDProperty, dr.GetInt32("DocTypeID"))
LoadProperty(DocTypeNameProperty, dr.GetString("DocTypeName"))
LoadProperty(CreateDateProperty, dr.GetSmartDate("CreateDate", True))
LoadProperty(CreateUserIDProperty, dr.GetInt32("CreateUserID"))
LoadProperty(ChangeDateProperty, dr.GetSmartDate("ChangeDate", True))
LoadProperty(ChangeUserIDProperty, dr.GetInt32("ChangeUserID"))
LoadProperty(RowVersionProperty, TryCast(dr.GetValue("RowVersion"), Byte()))
Dim args As New DataPortalHookArgs(dr)
OnFetchRead(args)
End Sub
''' <summary>
''' Inserts a new <see cref="DocType"/> object in the database.
''' </summary>
Protected Overrides Sub DataPortal_Insert()
SimpleAuditTrail()
Using ctx = TransactionManager(Of SqlConnection, SqlTransaction).GetManager(Database.DocStoreConnection, False)
Using cmd = New SqlCommand("AddDocType", ctx.Connection)
cmd.Transaction = ctx.Transaction
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("@DocTypeID", ReadProperty(DocTypeIDProperty)).Direction = ParameterDirection.Output
cmd.Parameters.AddWithValue("@DocTypeName", ReadProperty(DocTypeNameProperty)).DbType = DbType.String
cmd.Parameters.AddWithValue("@CreateDate", ReadProperty(CreateDateProperty).DBValue).DbType = DbType.DateTime2
cmd.Parameters.AddWithValue("@CreateUserID", ReadProperty(CreateUserIDProperty)).DbType = DbType.Int32
cmd.Parameters.AddWithValue("@ChangeDate", ReadProperty(ChangeDateProperty).DBValue).DbType = DbType.DateTime2
cmd.Parameters.AddWithValue("@ChangeUserID", ReadProperty(ChangeUserIDProperty)).DbType = DbType.Int32
cmd.Parameters.Add("@NewRowVersion", SqlDbType.Timestamp).Direction = ParameterDirection.Output
Dim args As New DataPortalHookArgs(cmd)
OnInsertPre(args)
cmd.ExecuteNonQuery()
OnInsertPost(args)
LoadProperty(DocTypeIDProperty, DirectCast(cmd.Parameters("@DocTypeID").Value, Integer))
LoadProperty(RowVersionProperty, DirectCast(cmd.Parameters("@NewRowVersion").Value, Byte()))
End Using
ctx.Commit()
End Using
End Sub
''' <summary>
''' Updates in the database all changes made to the <see cref="DocType"/> object.
''' </summary>
Protected Overrides Sub DataPortal_Update()
SimpleAuditTrail()
Using ctx = TransactionManager(Of SqlConnection, SqlTransaction).GetManager(Database.DocStoreConnection, False)
Using cmd = New SqlCommand("UpdateDocType", ctx.Connection)
cmd.Transaction = ctx.Transaction
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("@DocTypeID", ReadProperty(DocTypeIDProperty)).DbType = DbType.Int32
cmd.Parameters.AddWithValue("@DocTypeName", ReadProperty(DocTypeNameProperty)).DbType = DbType.String
cmd.Parameters.AddWithValue("@ChangeDate", ReadProperty(ChangeDateProperty).DBValue).DbType = DbType.DateTime2
cmd.Parameters.AddWithValue("@ChangeUserID", ReadProperty(ChangeUserIDProperty)).DbType = DbType.Int32
cmd.Parameters.AddWithValue("@RowVersion", ReadProperty(RowVersionProperty)).DbType = DbType.Binary
cmd.Parameters.Add("@NewRowVersion", SqlDbType.Timestamp).Direction = ParameterDirection.Output
Dim args As New DataPortalHookArgs(cmd)
OnUpdatePre(args)
cmd.ExecuteNonQuery()
OnUpdatePost(args)
LoadProperty(RowVersionProperty, DirectCast(cmd.Parameters("@NewRowVersion").Value, Byte()))
End Using
ctx.Commit()
End Using
End Sub
Private Sub SimpleAuditTrail()
LoadProperty(ChangeDateProperty, Date.Now)
LoadProperty(ChangeUserIDProperty, UserInformation.UserId)
OnPropertyChanged("ChangeUserName")
If IsNew Then
LoadProperty(CreateDateProperty, ReadProperty(ChangeDateProperty))
LoadProperty(CreateUserIDProperty, ReadProperty(ChangeUserIDProperty))
OnPropertyChanged("CreateUserName")
End If
End Sub
''' <summary>
''' Self deletes the <see cref="DocType"/> object.
''' </summary>
Protected Overrides Sub DataPortal_DeleteSelf()
DataPortal_Delete(DocTypeID)
End Sub
''' <summary>
''' Deletes the <see cref="DocType"/> object from database.
''' </summary>
''' <param name="docTypeID">The delete criteria.</param>
Protected Sub DataPortal_Delete(docTypeID As Integer)
' audit the object, just in case soft delete is used on this object
SimpleAuditTrail()
Using ctx = TransactionManager(Of SqlConnection, SqlTransaction).GetManager(Database.DocStoreConnection, False)
Using cmd = New SqlCommand("DeleteDocType", ctx.Connection)
cmd.Transaction = ctx.Transaction
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("@DocTypeID", docTypeID).DbType = DbType.Int32
Dim args As New DataPortalHookArgs(cmd, docTypeID)
OnDeletePre(args)
cmd.ExecuteNonQuery()
OnDeletePost(args)
End Using
ctx.Commit()
End Using
End Sub
#End Region
#Region " DataPortal Hooks "
''' <summary>
''' Occurs after setting all defaults for object creation.
''' </summary>
Partial Private Sub OnCreate(args As DataPortalHookArgs)
End Sub
''' <summary>
''' Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
''' </summary>
Partial Private Sub OnDeletePre(args As DataPortalHookArgs)
End Sub
''' <summary>
''' Occurs in DataPortal_Delete, after the delete operation, before Commit().
''' </summary>
Partial Private Sub OnDeletePost(args As DataPortalHookArgs)
End Sub
''' <summary>
''' Occurs after setting query parameters and before the fetch operation.
''' </summary>
Partial Private Sub OnFetchPre(args As DataPortalHookArgs)
End Sub
''' <summary>
''' Occurs after the fetch operation (object or collection is fully loaded and set up).
''' </summary>
Partial Private Sub OnFetchPost(args As DataPortalHookArgs)
End Sub
''' <summary>
''' Occurs after the low level fetch operation, before the data reader is destroyed.
''' </summary>
Partial Private Sub OnFetchRead(args As DataPortalHookArgs)
End Sub
''' <summary>
''' Occurs after setting query parameters and before the update operation.
''' </summary>
Partial Private Sub OnUpdatePre(args As DataPortalHookArgs)
End Sub
''' <summary>
''' Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
''' </summary>
Partial Private Sub OnUpdatePost(args As DataPortalHookArgs)
End Sub
''' <summary>
''' Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
''' </summary>
Partial Private Sub OnInsertPre(args As DataPortalHookArgs)
End Sub
''' <summary>
''' Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
''' </summary>
Partial Private Sub OnInsertPost(args As DataPortalHookArgs)
End Sub
#End Region
End Class
End Namespace
|
CslaGenFork/CslaGenFork
|
trunk/CoverageTest/Plain/Plain-WIN-VB/DocStore.Business/DocType.Designer.vb
|
Visual Basic
|
mit
| 23,207
|
' 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.
Imports System.Runtime.CompilerServices
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions
Friend Module ObjectCreationExpressionExtensions
<Extension>
Public Function CanRemoveEmptyArgumentList(objectCreationExpression As ObjectCreationExpressionSyntax, semanticModel As SemanticModel) As Boolean
If objectCreationExpression.ArgumentList Is Nothing Then
Return False
End If
If objectCreationExpression.ArgumentList.Arguments.Count > 0 Then
Return False
End If
Dim nextToken = objectCreationExpression.GetLastToken.GetNextToken()
If nextToken.IsKindOrHasMatchingText(SyntaxKind.OpenParenToken) Then
Return False
End If
If nextToken.IsKindOrHasMatchingText(SyntaxKind.DotToken) Then
If Not TypeOf objectCreationExpression.Type Is PredefinedTypeSyntax Then
Return False
End If
End If
Return True
End Function
End Module
End Namespace
|
reaction1989/roslyn
|
src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/Extensions/ObjectCreationExpressionExtensions.vb
|
Visual Basic
|
apache-2.0
| 1,351
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.42000
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
<Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.4.0.0"), _
Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Partial Friend NotInheritable Class MySettings
Inherits Global.System.Configuration.ApplicationSettingsBase
Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings()),MySettings)
#Region "My.Settings Auto-Save Functionality"
#If _MyType = "WindowsForms" Then
Private Shared addedHandler As Boolean
Private Shared addedHandlerLockObject As New Object
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Private Shared Sub AutoSaveSettings(sender As Global.System.Object, e As Global.System.EventArgs)
If My.Application.SaveMySettingsOnExit Then
My.Settings.Save()
End If
End Sub
#End If
#End Region
Public Shared ReadOnly Property [Default]() As MySettings
Get
#If _MyType = "WindowsForms" Then
If Not addedHandler Then
SyncLock addedHandlerLockObject
If Not addedHandler Then
AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings
addedHandler = True
End If
End SyncLock
End If
#End If
Return defaultInstance
End Get
End Property
End Class
End Namespace
Namespace My
<Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _
Friend Module MySettingsProperty
<Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _
Friend ReadOnly Property Settings() As Global.WindowsDesktop_VB.NET_WinForms_Example.My.MySettings
Get
Return Global.WindowsDesktop_VB.NET_WinForms_Example.My.MySettings.Default
End Get
End Property
End Module
End Namespace
|
panthernet/GraphX
|
Examples/WindowsDesktop_VB.NET_WinForms_Example/My Project/Settings.Designer.vb
|
Visual Basic
|
apache-2.0
| 2,954
|
Public Partial Class TimerPickerTest
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
tpTimeIn.SelectedTime = Now.TimeOfDay
End Sub
Protected Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim i = 0
End Sub
End Class
|
Micmaz/DTIControls
|
JqueryUIControls/JqueryUIControlsTest/TimerPickerTest.aspx.vb
|
Visual Basic
|
mit
| 379
|
Option Strict Off
Option Explicit On
Imports Sooda
Imports Sooda.UnitTests.BaseObjects
Imports System
Imports System.Collections
Imports System.Data
Imports System.Diagnostics
Namespace Sooda.UnitTests.VBObjects
Public Class PKString
Inherits Sooda.UnitTests.VBObjects.Stubs.PKString_Stub
Public Sub New(ByVal c As SoodaConstructor)
MyBase.New(c)
'Do not modify this constructor.
End Sub
Public Sub New(ByVal transaction As SoodaTransaction)
MyBase.New(transaction)
'
'TODO: Add construction logic here.
'
End Sub
Public Sub New()
Me.New(SoodaTransaction.ActiveTransaction)
'Do not modify this constructor.
End Sub
End Class
End Namespace
|
pfusik/sooda
|
tests/VBUnitTestObjects/PKString.vb
|
Visual Basic
|
bsd-2-clause
| 830
|
Imports Microsoft.VisualBasic
Imports System.Reflection
Imports System.Resources
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Imports System.Windows
' 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("WpfGlassDemo")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyConfiguration("")>
<Assembly: AssemblyCompany("Microsoft")>
<Assembly: AssemblyProduct("WpfGlassDemo")>
<Assembly: AssemblyCopyright("Copyright © Microsoft 2009")>
<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)>
'In order to begin building localizable applications, set
'<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
'inside a <PropertyGroup>. For example, if you are using US english
'in your source files, set the <UICulture> to en-US. Then uncomment
'the NeutralResourceLanguage attribute below. Update the "en-US" in
'the line below to match the UICulture setting in the project file.
'[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
'(used if a resource is not found in the page,
' or application resource dictionaries)
'(used if a resource is not found in the page,
' app, or any theme specific resource dictionaries)
<Assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)>
' 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")>
|
devkimchi/Windows-API-Code-Pack-1.1
|
source/Samples/AeroGlass/VB/WpfGlassDemo/My Project/AssemblyInfo.vb
|
Visual Basic
|
mit
| 2,129
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Collections.Immutable
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.CodeGen
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend NotInheritable Class IteratorRewriter
Inherits StateMachineRewriter(Of FieldSymbol)
Private ReadOnly elementType As TypeSymbol
Private ReadOnly isEnumerable As Boolean
Private currentField As FieldSymbol
Private initialThreadIdField As FieldSymbol
Public Sub New(body As BoundStatement,
method As MethodSymbol,
isEnumerable As Boolean,
stateMachineType As IteratorStateMachine,
slotAllocatorOpt As VariableSlotAllocator,
compilationState As TypeCompilationState,
diagnostics As DiagnosticBag)
MyBase.New(body, method, stateMachineType, slotAllocatorOpt, compilationState, diagnostics)
Me.isEnumerable = isEnumerable
Dim methodReturnType = method.ReturnType
If methodReturnType.GetArity = 0 Then
Me.elementType = method.ContainingAssembly.GetSpecialType(SpecialType.System_Object)
Else
' the element type may contain method type parameters, which are now alpha-renamed into type parameters of the generated class
Me.elementType = DirectCast(methodReturnType, NamedTypeSymbol).TypeArgumentsNoUseSiteDiagnostics().Single().InternalSubstituteTypeParameters(Me.TypeMap)
End If
End Sub
''' <summary>
''' Rewrite an iterator method into a state machine class.
''' </summary>
Friend Overloads Shared Function Rewrite(body As BoundBlock,
method As MethodSymbol,
methodOrdinal As Integer,
slotAllocatorOpt As VariableSlotAllocator,
compilationState As TypeCompilationState,
diagnostics As DiagnosticBag,
<Out> ByRef stateMachineType As IteratorStateMachine) As BoundBlock
If body.HasErrors Or Not method.IsIterator Then
Return body
End If
Dim methodReturnType As TypeSymbol = method.ReturnType
Dim retSpecialType = method.ReturnType.OriginalDefinition.SpecialType
Dim isEnumerable As Boolean = retSpecialType = SpecialType.System_Collections_Generic_IEnumerable_T OrElse
retSpecialType = SpecialType.System_Collections_IEnumerable
Dim elementType As TypeSymbol
If method.ReturnType.IsDefinition Then
elementType = method.ContainingAssembly.GetSpecialType(SpecialType.System_Object)
Else
elementType = DirectCast(methodReturnType, NamedTypeSymbol).TypeArgumentsNoUseSiteDiagnostics(0)
End If
stateMachineType = New IteratorStateMachine(slotAllocatorOpt, compilationState, method, methodOrdinal, elementType, isEnumerable)
If compilationState.ModuleBuilderOpt IsNot Nothing Then
compilationState.ModuleBuilderOpt.CompilationState.SetStateMachineType(method, stateMachineType)
End If
Dim rewriter As New IteratorRewriter(body, method, isEnumerable, stateMachineType, slotAllocatorOpt, compilationState, diagnostics)
' check if we have all the types we need
If rewriter.EnsureAllSymbolsAndSignature() Then
Return body
End If
Return rewriter.Rewrite()
End Function
Friend Overrides Function EnsureAllSymbolsAndSignature() As Boolean
Dim hasErrors As Boolean = MyBase.EnsureAllSymbolsAndSignature
If Me.Method.IsSub OrElse Me.elementType.IsErrorType Then
hasErrors = True
End If
' NOTE: in current implementation these attributes must exist
' TODO: change to "don't use if not found"
EnsureWellKnownMember(Of MethodSymbol)(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor, hasErrors)
EnsureWellKnownMember(Of MethodSymbol)(WellKnownMember.System_Diagnostics_DebuggerNonUserCodeAttribute__ctor, hasErrors)
' NOTE: We don't ensure DebuggerStepThroughAttribute, it is just not emitted if not found
' EnsureWellKnownMember(Of MethodSymbol)(WellKnownMember.System_Diagnostics_DebuggerStepThroughAttribute__ctor, hasErrors)
' TODO: do we need these here? They are used on the actual iterator method.
' EnsureWellKnownMember(Of MethodSymbol)(WellKnownMember.System_Runtime_CompilerServices_IteratorStateMachine__ctor, hasErrors)
EnsureSpecialType(SpecialType.System_Object, hasErrors)
EnsureSpecialType(SpecialType.System_Boolean, hasErrors)
EnsureSpecialType(SpecialType.System_Int32, hasErrors)
If Me.Method.ReturnType.IsDefinition Then
If Me.isEnumerable Then
EnsureSpecialType(SpecialType.System_Collections_IEnumerator, hasErrors)
End If
Else
If Me.isEnumerable Then
EnsureSpecialType(SpecialType.System_Collections_Generic_IEnumerator_T, hasErrors)
EnsureSpecialType(SpecialType.System_Collections_IEnumerable, hasErrors)
End If
EnsureSpecialType(SpecialType.System_Collections_IEnumerator, hasErrors)
End If
EnsureSpecialType(SpecialType.System_IDisposable, hasErrors)
Return hasErrors
End Function
Protected Overrides Sub GenerateControlFields()
' Add a field: int _state
Me.StateField = Me.F.StateMachineField(Me.F.SpecialType(SpecialType.System_Int32), Me.Method, GeneratedNames.MakeStateMachineStateFieldName(), Accessibility.Public)
' Add a field: T current
currentField = F.StateMachineField(elementType, Me.Method, GeneratedNames.MakeIteratorCurrentFieldName(), Accessibility.Public)
' if it is an Enumerable, add a field: initialThreadId As Integer
initialThreadIdField = If(isEnumerable,
F.StateMachineField(F.SpecialType(SpecialType.System_Int32), Me.Method, GeneratedNames.MakeIteratorInitialThreadIdName(), Accessibility.Public),
Nothing)
End Sub
Protected Overrides Sub GenerateMethodImplementations()
Dim managedThreadId As BoundExpression = Nothing ' Thread.CurrentThread.ManagedThreadId
' Add bool IEnumerator.MoveNext() and void IDisposable.Dispose()
Dim disposeMethod = Me.OpenMethodImplementation(SpecialMember.System_IDisposable__Dispose,
"Dispose",
DebugAttributes.DebuggerNonUserCodeAttribute,
Accessibility.Private,
generateDebugInfo:=False,
hasMethodBodyDependency:=True)
Dim debuggerHidden = IsDebuggerHidden(Me.Method)
Dim moveNextAttrs As DebugAttributes = DebugAttributes.CompilerGeneratedAttribute
If debuggerHidden Then moveNextAttrs = moveNextAttrs Or DebugAttributes.DebuggerHiddenAttribute
Dim moveNextMethod = Me.OpenMethodImplementation(SpecialMember.System_Collections_IEnumerator__MoveNext,
"MoveNext",
moveNextAttrs,
Accessibility.Private,
generateDebugInfo:=True,
hasMethodBodyDependency:=True)
GenerateMoveNextAndDispose(moveNextMethod, disposeMethod)
F.CurrentMethod = moveNextMethod
If isEnumerable Then
' generate the code for GetEnumerator()
' IEnumerable<elementType> result;
' if (this.initialThreadId == Thread.CurrentThread.ManagedThreadId && this.state == -2)
' {
' this.state = 0;
' result = this;
' }
' else
' {
' result = new Ints0_Impl(0);
' }
' result.parameter = this.parameterProxy; ' copy all of the parameter proxies
' Add IEnumerator<int> IEnumerable<int>.GetEnumerator()
Dim getEnumeratorGeneric = Me.OpenMethodImplementation(F.SpecialType(SpecialType.System_Collections_Generic_IEnumerable_T).Construct(elementType),
SpecialMember.System_Collections_Generic_IEnumerable_T__GetEnumerator,
"GetEnumerator",
DebugAttributes.DebuggerNonUserCodeAttribute,
Accessibility.Private,
generateDebugInfo:=False,
hasMethodBodyDependency:=False)
Dim bodyBuilder = ArrayBuilder(Of BoundStatement).GetInstance()
Dim resultVariable = F.SynthesizedLocal(StateMachineType) ' iteratorClass result;
Dim currentManagedThreadIdMethod As MethodSymbol = Nothing
Dim currentManagedThreadIdProperty As PropertySymbol = F.WellKnownMember(Of PropertySymbol)(WellKnownMember.System_Environment__CurrentManagedThreadId, isOptional:=True)
If (currentManagedThreadIdProperty IsNot Nothing) Then
currentManagedThreadIdMethod = currentManagedThreadIdProperty.GetMethod()
End If
If (currentManagedThreadIdMethod IsNot Nothing) Then
managedThreadId = F.Call(Nothing, currentManagedThreadIdMethod)
Else
managedThreadId = F.Property(F.Property(WellKnownMember.System_Threading_Thread__CurrentThread), WellKnownMember.System_Threading_Thread__ManagedThreadId)
End If
' if (this.state == -2 && this.initialThreadId == Thread.CurrentThread.ManagedThreadId)
' this.state = 0;
' result = this;
' goto thisInitialized
' else
' result = new IteratorClass(0)
' ' initialize [Me] if needed
' thisInitialized:
' ' initialize other fields
Dim thisInitialized = F.GenerateLabel("thisInitialized")
bodyBuilder.Add(
F.If(
condition:=
F.LogicalAndAlso(
F.IntEqual(F.Field(F.Me, StateField, False), F.Literal(StateMachineStates.FinishedStateMachine)),
F.IntEqual(F.Field(F.Me, initialThreadIdField, False), managedThreadId)),
thenClause:=
F.Block(
F.Assignment(F.Field(F.Me, StateField, True), F.Literal(StateMachineStates.FirstUnusedState)),
F.Assignment(F.Local(resultVariable, True), F.Me),
If(Method.IsShared OrElse Method.MeParameter.Type.IsReferenceType,
F.Goto(thisInitialized),
DirectCast(F.Block(), BoundStatement))
),
elseClause:=
F.Assignment(F.Local(resultVariable, True), F.[New](StateMachineType.Constructor, F.Literal(0)))
))
' Initialize all the parameter copies
Dim copySrc = InitialParameters
Dim copyDest = nonReusableLocalProxies
If Not Method.IsShared Then
' starting with "this"
Dim proxy As FieldSymbol = Nothing
If (copyDest.TryGetValue(Method.MeParameter, proxy)) Then
bodyBuilder.Add(
F.Assignment(
F.Field(F.Local(resultVariable, True), proxy.AsMember(StateMachineType), True),
F.Field(F.Me, copySrc(Method.MeParameter).AsMember(F.CurrentType), False)))
End If
End If
bodyBuilder.Add(F.Label(thisInitialized))
For Each parameter In Method.Parameters
Dim proxy As FieldSymbol = Nothing
If (copyDest.TryGetValue(parameter, proxy)) Then
bodyBuilder.Add(
F.Assignment(
F.Field(F.Local(resultVariable, True), proxy.AsMember(StateMachineType), True),
F.Field(F.Me, copySrc(parameter).AsMember(F.CurrentType), False)))
End If
Next
bodyBuilder.Add(F.Return(F.Local(resultVariable, False)))
F.CloseMethod(F.Block(ImmutableArray.Create(resultVariable), bodyBuilder.ToImmutableAndFree()))
' Generate IEnumerable.GetEnumerator
' NOTE: this is a private implementing method. Its name is irrelevant
' but must be different from another GetEnumerator. Dev11 uses GetEnumerator0 here.
' IEnumerable.GetEnumerator seems better -
' it is clear why we have the property, and "Current" suffix will be shared in metadata with another Current.
' It is also consistent with the naming of IEnumerable.Current (see below).
Me.OpenMethodImplementation(SpecialMember.System_Collections_IEnumerable__GetEnumerator,
"IEnumerable.GetEnumerator",
DebugAttributes.DebuggerNonUserCodeAttribute,
Accessibility.Private,
generateDebugInfo:=False,
hasMethodBodyDependency:=False)
F.CloseMethod(F.Return(F.Call(F.Me, getEnumeratorGeneric)))
End If
' Add T IEnumerator<T>.Current
Me.OpenPropertyImplementation(F.SpecialType(SpecialType.System_Collections_Generic_IEnumerator_T).Construct(elementType),
SpecialMember.System_Collections_Generic_IEnumerator_T__Current,
"Current",
DebugAttributes.DebuggerNonUserCodeAttribute,
Accessibility.Private,
False)
F.CloseMethod(F.Return(F.Field(F.Me, currentField, False)))
' Add void IEnumerator.Reset()
Me.OpenMethodImplementation(SpecialMember.System_Collections_IEnumerator__Reset,
"Reset",
DebugAttributes.DebuggerNonUserCodeAttribute,
Accessibility.Private,
generateDebugInfo:=False,
hasMethodBodyDependency:=False)
F.CloseMethod(F.Throw(F.[New](F.WellKnownType(WellKnownType.System_NotSupportedException))))
' Add object IEnumerator.Current
' NOTE: this is a private implementing property. Its name is irrelevant
' but must be different from another Current.
' Dev11 uses fully qualified and substituted name here (System.Collections.Generic.IEnumerator(Of Object).Current),
' It may be an overkill and may lead to metadata bloat.
' IEnumerable.Current seems better -
' it is clear why we have the property, and "Current" suffix will be shared in metadata with another Current.
Me.OpenPropertyImplementation(SpecialMember.System_Collections_IEnumerator__Current,
"IEnumerator.Current",
DebugAttributes.DebuggerNonUserCodeAttribute,
Accessibility.Private,
False)
F.CloseMethod(F.Return(F.Field(F.Me, currentField, False)))
' Add a body for the constructor
If True Then
F.CurrentMethod = StateMachineType.Constructor
Dim bodyBuilder = ArrayBuilder(Of BoundStatement).GetInstance()
bodyBuilder.Add(F.BaseInitialization())
bodyBuilder.Add(F.Assignment(F.Field(F.Me, StateField, True), F.Parameter(F.CurrentMethod.Parameters(0)).MakeRValue)) ' this.state = state
If isEnumerable Then
' this.initialThreadId = Thread.CurrentThread.ManagedThreadId;
bodyBuilder.Add(F.Assignment(F.Field(F.Me, initialThreadIdField, True), managedThreadId))
End If
bodyBuilder.Add(F.Return())
F.CloseMethod(F.Block(bodyBuilder.ToImmutableAndFree()))
bodyBuilder = Nothing
End If
End Sub
Protected Overrides Function GenerateStateMachineCreation(stateMachineVariable As LocalSymbol, frameType As NamedTypeSymbol) As BoundStatement
Return F.Return(F.Local(stateMachineVariable, False))
End Function
Protected Overrides Sub InitializeStateMachine(bodyBuilder As ArrayBuilder(Of BoundStatement), frameType As NamedTypeSymbol, stateMachineLocal As LocalSymbol)
' Dim stateMachineLocal As new IteratorImplementationClass(N)
' where N is either 0 (if we're producing an enumerator) or -2 (if we're producing an enumerable)
Dim initialState = If(isEnumerable, StateMachineStates.FinishedStateMachine, StateMachineStates.FirstUnusedState)
bodyBuilder.Add(
F.Assignment(
F.Local(stateMachineLocal, True),
F.[New](StateMachineType.Constructor.AsMember(frameType), F.Literal(initialState))))
End Sub
Protected Overrides ReadOnly Property PreserveInitialParameterValues As Boolean
Get
Return Me.isEnumerable
End Get
End Property
Friend Overrides ReadOnly Property TypeMap As TypeSubstitution
Get
Return StateMachineType.TypeSubstitution
End Get
End Property
Private Sub GenerateMoveNextAndDispose(moveNextMethod As SynthesizedStateMachineMethod, disposeMethod As SynthesizedStateMachineMethod)
Dim rewriter = New IteratorMethodToClassRewriter(method:=Me.Method,
F:=Me.F,
state:=Me.StateField,
current:=Me.currentField,
HoistedVariables:=Me.hoistedVariables,
localProxies:=Me.nonReusableLocalProxies,
SynthesizedLocalOrdinals:=Me.SynthesizedLocalOrdinals,
slotAllocatorOpt:=Me.SlotAllocatorOpt,
nextFreeHoistedLocalSlot:=Me.nextFreeHoistedLocalSlot,
diagnostics:=Diagnostics)
rewriter.GenerateMoveNextAndDispose(Body, moveNextMethod, disposeMethod)
End Sub
Protected Overrides Function CreateByValLocalCapture(field As FieldSymbol, local As LocalSymbol) As FieldSymbol
Return field
End Function
Protected Overrides Function CreateParameterCapture(field As FieldSymbol, parameter As ParameterSymbol) As FieldSymbol
Return field
End Function
Protected Overrides Sub InitializeParameterWithProxy(parameter As ParameterSymbol, proxy As FieldSymbol, stateMachineVariable As LocalSymbol, initializers As ArrayBuilder(Of BoundExpression))
Debug.Assert(proxy IsNot Nothing)
Dim frameType As NamedTypeSymbol = If(Me.Method.IsGenericMethod,
Me.StateMachineType.Construct(Me.Method.TypeArguments),
Me.StateMachineType)
Dim expression As BoundExpression = If(parameter.IsMe,
DirectCast(Me.F.Me, BoundExpression),
Me.F.Parameter(parameter).MakeRValue())
initializers.Add(
Me.F.AssignmentExpression(
Me.F.Field(
Me.F.Local(stateMachineVariable, True),
proxy.AsMember(frameType),
True),
expression))
End Sub
End Class
End Namespace
|
DavidKarlas/roslyn
|
src/Compilers/VisualBasic/Portable/Lowering/IteratorRewriter/IteratorRewriter.vb
|
Visual Basic
|
apache-2.0
| 22,193
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Option Strict Off
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.Simplification
Imports Microsoft.CodeAnalysis.VisualBasic.CodeFixes.GenerateType
Imports Microsoft.CodeAnalysis.VisualBasic.Diagnostics
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.GenerateType
Public Class GenerateTypeTests
Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, CodeFixProvider)
Return New Tuple(Of DiagnosticAnalyzer, CodeFixProvider)(Nothing, New GenerateTypeCodeFixProvider())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestGenerateTypeParameterFromArgumentInferT()
Test(
NewLines("Module Program \n Sub Main() \n Dim f As [|Foo(Of Integer)|] \n End Sub \n End Module"),
NewLines("Module Program \n Sub Main() \n Dim f As Foo(Of Integer) \n End Sub \n End Module \n Friend Class Foo(Of T) \n End Class"),
index:=1)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestGenerateClassFromTypeParameter()
Test(
NewLines("Class C \n Dim emp As List(Of [|Employee|]) \n End Class"),
NewLines("Class C \n Dim emp As List(Of Employee) \n Private Class Employee \n End Class \n End Class"),
index:=2)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestGenerateClassFromFieldDeclarationIntoSameType()
Test(
NewLines("Class C \n dim f as [|Foo|] \n End Class"),
NewLines("Class C \n dim f as Foo \n Private Class Foo \n End Class \n End Class"),
index:=2)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestGenerateClassFromFieldDeclarationIntoSameNamespace()
Test(
NewLines("Class C \n dim f as [|Foo|] \n End Class"),
NewLines("Class C \n dim f as Foo \n End Class \n Friend Class Foo \n End Class"),
index:=1)
End Sub
<WorkItem(539716)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestGenerateClassFromFullyQualifiedFieldIntoSameNamespace()
Test(
NewLines("Namespace NS \n Class Foo \n Private x As New NS.[|Bar|] \n End Class \n End Namespace"),
NewLines("Namespace NS \n Class Foo \n Private x As New NS.Bar \n End Class \n Friend Class Bar \n End Class \n End Namespace"),
index:=1,
parseOptions:=Nothing) ' Namespaces not supported in script
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestGenerateClassWithCtorFromObjectCreation()
Test(
NewLines("Class C \n Dim f As Foo = New [|Foo|]() \n End Class"),
NewLines("Class C \n Dim f As Foo = New Foo() \n Private Class Foo \n Public Sub New() \n End Sub \n End Class \n End Class"),
index:=2)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestCreateException()
Test(
NewLines("Imports System \n Imports System.Collections.Generic \n Imports System.Linq \n Module Program \n Sub Main(args As String()) \n Throw New [|Foo|]() \n End Sub \n End Module"),
NewLines("Imports System \n Imports System.Collections.Generic \n Imports System.Linq \n Imports System.Runtime.Serialization \n Module Program \n Sub Main(args As String()) \n Throw New Foo() \n End Sub \n End Module \n <Serializable> Friend Class Foo \n Inherits Exception \n Public Sub New() \n End Sub \n Public Sub New(message As String) \n MyBase.New(message) \n End Sub \n Public Sub New(message As String, innerException As Exception) \n MyBase.New(message, innerException) \n End Sub \n Protected Sub New(info As SerializationInfo, context As StreamingContext) \n MyBase.New(info, context) \n End Sub \n End Class"),
index:=1)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestCreateFieldDelegatingConstructor()
Test(
NewLines("Imports System \n Imports System.Collections.Generic \n Imports System.Linq \n Module Program \n Sub Main(args As String()) \n Call New [|Foo|](1, ""blah"") \n End Sub \n End Module"),
NewLines("Imports System \n Imports System.Collections.Generic \n Imports System.Linq \n Module Program \n Sub Main(args As String()) \n Call New Foo(1, ""blah"") \n End Sub \n End Module \n Friend Class Foo \n Private v1 As Integer \n Private v2 As String \n Public Sub New(v1 As Integer, v2 As String) \n Me.v1 = v1 \n Me.v2 = v2 \n End Sub \n End Class"),
index:=1)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestCreateBaseDelegatingConstructor()
Test(
NewLines("Imports System \n Imports System.Collections.Generic \n Imports System.Linq \n Module Program \n Sub Main(args As String()) \n Dim d As B = New [|D|](4) \n End Sub \n End Module \n Class B \n Protected Sub New(value As Integer) \n End Sub \n End Class"),
NewLines("Imports System \n Imports System.Collections.Generic \n Imports System.Linq \n Module Program \n Sub Main(args As String()) \n Dim d As B = New D(4) \n End Sub \n End Module \n Friend Class D \n Inherits B \n Public Sub New(value As Integer) \n MyBase.New(value) \n End Sub \n End Class \n Class B \n Protected Sub New(value As Integer) \n End Sub \n End Class"),
index:=1)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestGenerateIntoNamespace()
Test(
NewLines("Imports System \n Imports System.Collections.Generic \n Imports System.Linq \n Namespace Outer \n Module Program \n Sub Main(args As String()) \n Call New [|Blah|]() \n End Sub \n End Module \n End Namespace"),
NewLines("Imports System \n Imports System.Collections.Generic \n Imports System.Linq \n Namespace Outer \n Module Program \n Sub Main(args As String()) \n Call New Blah() \n End Sub \n End Module \n Friend Class Blah \n Public Sub New() \n End Sub \n End Class \n End Namespace"),
index:=1)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestGenerateAssignmentToBaseField()
Test(
NewLines("Imports System \n Imports System.Collections.Generic \n Imports System.Linq \n Module Program \n Sub Main(i As Integer) \n Dim d As B = New [|D|](i) \n End Sub \n End Module \n Class B \n Protected i As Integer \n End Class"),
NewLines("Imports System \n Imports System.Collections.Generic \n Imports System.Linq \n Module Program \n Sub Main(i As Integer) \n Dim d As B = New D(i) \n End Sub \n End Module \n Friend Class D \n Inherits B \n Public Sub New(i As Integer) \n Me.i = i \n End Sub \n End Class \n Class B \n Protected i As Integer \n End Class"),
index:=1)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestGenerateGenericType()
Test(
NewLines("Imports System \n Imports System.Collections.Generic \n Imports System.Linq \n Class Outer(Of M) \n Sub Main(i As Integer) \n Call New [|Foo(Of M)|] \n End Sub \n End Class"),
NewLines("Imports System \n Imports System.Collections.Generic \n Imports System.Linq \n Class Outer(Of M) \n Sub Main(i As Integer) \n Call New Foo(Of M) \n End Sub \n End Class \n Friend Class Foo(Of M) \n End Class"),
index:=1)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestGenerateIntoClass()
Test(
NewLines("Imports System \n Imports System.Collections.Generic \n Imports System.Linq \n Class Outer(Of M) \n Sub Main(i As Integer) \n Call New [|Foo(Of M)|] \n End Sub \n End Class"),
NewLines("Imports System \n Imports System.Collections.Generic \n Imports System.Linq \n Class Outer(Of M) \n Sub Main(i As Integer) \n Call New Foo(Of M) \n End Sub \n Private Class Foo(Of M) \n End Class \n End Class"),
index:=2)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestGenerateIntoClassFromFullyQualifiedInvocation()
Test(
NewLines("Class Program \n Sub Test() \n Dim d = New [|Program.Foo|]() \n End Sub \n End Class"),
NewLines("Class Program \n Sub Test() \n Dim d = New Program.Foo() \n End Sub \n Private Class Foo \n Public Sub New() \n End Sub \n End Class \n End Class"))
End Sub
<WorkItem(5776, "DevDiv_Projects/Roslyn")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestGenerateIntoNamespaceFromFullyQualifiedInvocation()
Test(
NewLines("Namespace Foo \n Class Program \n Sub Test() \n Dim d = New [|Foo.Bar|]() \n End Sub \n End Class \n End Namespace"),
NewLines("Namespace Foo \n Class Program \n Sub Test() \n Dim d = New Foo.Bar() \n End Sub \n End Class \n Friend Class Bar \n Public Sub New() \n End Sub \n End Class \n End Namespace"),
index:=1,
parseOptions:=Nothing) ' Namespaces not supported in script
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestInSecondConstraintClause()
Test(
NewLines("Imports System \n Imports System.Collections.Generic \n Imports System.Linq \n Class Program(Of T As {Foo, [|IBar|]}) \n End Class"),
NewLines("Imports System \n Imports System.Collections.Generic \n Imports System.Linq \n Class Program(Of T As {Foo, IBar}) \n End Class \n Friend Interface IBar \n End Interface"),
index:=1)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestGenerateIntoNewNamespace()
TestAddDocument(
NewLines("Imports System \n Imports System.Collections.Generic \n Imports System.Linq \n Class Program \n Sub Main() \n Call New Foo.[|Bar|]() \n End Sub \n End Class"),
NewLines("Namespace Foo \n Friend Class Bar \n Public Sub New() \n End Sub \n End Class \n End Namespace"),
expectedContainers:={"Foo"},
expectedDocumentName:="Bar.vb")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestGenerateIntoGlobalNamespaceNewFile()
TestAddDocument(
NewLines("Imports System \n Imports System.Collections.Generic \n Imports System.Linq \n Module Program \n Sub Main(args As String()) \n Dim x As New [|Foo|] \n End Sub \n End Module"),
NewLines("Friend Class Foo \n End Class"),
expectedContainers:=Array.Empty(Of String)(),
expectedDocumentName:="Foo.vb")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestGenerateTypeThatImplementsInterface1()
Test(
NewLines("Imports System \n Imports System.Collections.Generic \n Imports System.Linq \n Module Program \n Sub Main(args As String()) \n Dim d As [|IFoo|] = New Foo() \n End Sub \n End Module"),
NewLines("Imports System \n Imports System.Collections.Generic \n Imports System.Linq \n Module Program \n Sub Main(args As String()) \n Dim d As IFoo = New Foo() \n End Sub \n End Module \n Friend Interface IFoo \n End Interface"),
index:=1)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestGenerateTypeThatImplementsInterface2()
Test(
NewLines("Imports System \n Imports System.Collections.Generic \n Imports System.Linq \n Module Program \n Sub Main(args As String()) \n Dim d As IFoo = New [|Foo|]() \n End Sub \n End Module \n Friend Interface IFoo \n End Interface"),
NewLines("Imports System \n Imports System.Collections.Generic \n Imports System.Linq \n Module Program \n Sub Main(args As String()) \n Dim d As IFoo = New Foo() \n End Sub \n End Module \n Friend Class Foo \n Implements IFoo \n End Class \n Friend Interface IFoo \n End Interface"),
index:=1)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestGenerateTypeWithNamedArguments()
Test(
NewLines("Class Program \n Sub Test() \n Dim x = New [|Bar|](value:=7) \n End Sub \n End Class"),
NewLines("Class Program \n Sub Test() \n Dim x = New Bar(value:=7) \n End Sub \n End Class \n Friend Class Bar \n Private value As Integer \n Public Sub New(value As Integer) \n Me.value = value \n End Sub \n End Class"),
index:=1)
End Sub
<WorkItem(539730)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestNotIntoType()
TestActionCount(
NewLines("Class Program \n Inherits [|Temp|] \n Sub Test() \n End Sub \n End Class"),
count:=3)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestGenerateClassFromReturnType()
Test(
NewLines("Class Foo \n Function F() As [|Bar|] \n End Function \n End Class"),
NewLines("Class Foo \n Function F() As Bar \n End Function \n End Class \n Public Class Bar \n End Class"),
index:=1)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestGenerateClassWhereKeywordBecomesTypeName()
Test(
NewLines("Class Foo \n Dim x As New [|[Class]|] \n End Class"),
NewLines("Class Foo \n Dim x As New [Class] \n End Class \n Friend Class [Class] \n End Class"),
index:=1)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub NegativeTestGenerateClassFromEscapedType()
Test(
NewLines("Class Foo \n Dim x as New [|[Bar]|] \n End Class"),
NewLines("Class Foo \n Dim x as New [Bar] \n End Class \n Friend Class Bar \n End Class"),
index:=1)
End Sub
<WorkItem(539716)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestGenerateTypeIntoContainingNamespace()
Test(
NewLines("Namespace NS \n Class Foo \n Dim x As New NS.[|Bar|] \n End Class \n End Namespace"),
NewLines("Namespace NS \n Class Foo \n Dim x As New NS.Bar \n End Class \n Friend Class Bar \n End Class \n End Namespace"),
index:=1,
parseOptions:=Nothing) ' Namespaces not supported in script
End Sub
<WorkItem(539736)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestGenerateTypeIntoContainingModule()
Test(
NewLines("Module M \n Dim x As [|C|] \n End Module"),
NewLines("Module M \n Dim x As C \n Private Class C \n End Class \n End Module"),
index:=2)
End Sub
<WorkItem(539737)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestGenerateInterfaceInImplementsStatement()
Test(
NewLines("Class C \n Implements [|D|] \n End Class"),
NewLines("Class C \n Implements D \n End Class \n Friend Interface D \n End Interface"),
index:=1)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestAbsenceOfGenerateIntoInvokingTypeForConstraintList()
TestActionCount(
NewLines("Class EmployeeList(Of T As [|Employee|]) \n End Class"),
count:=3,
parseOptions:=TestOptions.Regular)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestMissingOnImportsDirective()
TestMissing(
NewLines("Imports [|System|]"))
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestNoContainersInNewType()
TestAddDocument(
NewLines("Class Base \n Sub Main \n Dim p = New [|Derived|]() \n End Sub \n End Class"),
NewLines("Friend Class Derived \n Public Sub New() \n End Sub \n End Class"),
expectedContainers:=Array.Empty(Of String)(),
expectedDocumentName:="Derived.vb")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestNotOfferedInsideBinaryExpressions()
TestMissing(
NewLines("Class Base \n Sub Main \n Dim a = 1 + [|Foo|] \n End Sub \n End Class"))
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestNotOfferedIfLeftSideOfDotIsNotAName()
TestMissing(
NewLines("Module Program \n Sub Main(args As String()) \n Call 1.[|T|] \n End Sub \n End Module"))
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestNotOfferedIfLeftFromDotIsNotAName()
TestMissing(
NewLines("Class C1 \n Sub Foo \n Me.[|Foo|] = 3 \n End Sub \n End Class"))
End Sub
<WorkItem(539786)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestMissingOnAssignedVariable()
TestMissing(
NewLines("Imports System \n Imports System.Collections.Generic \n Imports System.Linq \n Module Program \n Sub Main(args As String()) \n [|B|] = 10 \n End Sub \n End Module"))
End Sub
<WorkItem(539757)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestArrayInference1()
Test(
NewLines("Class Base \n Sub Main \n Dim p() As Base = New [|Derived|](10) {} \n End Sub \n End Class"),
NewLines("Class Base \n Sub Main \n Dim p() As Base = New Derived(10) {} \n End Sub \n End Class \n Friend Class Derived \n Inherits Base \n End Class"),
index:=1)
End Sub
<WorkItem(539757)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestArrayInference2()
Test(
NewLines("Class Base \n Sub Main \n Dim p As Base() = New [|Derived|](10) {} \n End Sub \n End Class"),
NewLines("Class Base \n Sub Main \n Dim p As Base() = New Derived(10) {} \n End Sub \n End Class \n Friend Class Derived \n Inherits Base \n End Class"),
index:=1)
End Sub
<WorkItem(539757)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestArrayInference3()
Test(
NewLines("Class Base \n Sub Main \n Dim p As Base = New [|Derived|](10) {} \n End Sub \n End Class"),
NewLines("Class Base \n Sub Main \n Dim p As Base = New Derived(10) {} \n End Sub \n End Class \n Friend Class Derived \n End Class"),
index:=1)
End Sub
<WorkItem(539749)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestMatchWithDifferentArity()
Test(
NewLines("Class Program \n Private Sub Main() \n Dim f As [|Foo(Of Integer)|] \n End Sub \n End Class \n Class Foo \n End Class"),
NewLines("Class Program \n Private Sub Main() \n Dim f As Foo(Of Integer) \n End Sub \n End Class \n Friend Class Foo(Of T) \n End Class \n Class Foo \n End Class"),
index:=1)
End Sub
<WorkItem(540504)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestNoUnavailableTypeParameters1()
Test(
NewLines("Class C(Of T1, T2) \n Sub M(x As T1, y As T2) \n Dim a As Test = New [|Test|](x, y) \n End Sub \n End Class"),
NewLines("Class C(Of T1, T2) \n Sub M(x As T1, y As T2) \n Dim a As Test = New Test(x, y) \n End Sub \n End Class \n Friend Class Test \n Private x As Object \n Private y As Object \n Public Sub New(x As Object, y As Object) \n Me.x = x \n Me.y = y \n End Sub \n End Class"),
index:=1)
End Sub
<WorkItem(540534)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestMultipleTypeParamsInConstructor1()
Test(
NewLines("Class C(Of T1, T2) \n Sub M(x As T1, y As T2) \n Dim a As Test(Of T1, T2) = New [|Test(Of T1, T2)|](x, y) \n End Sub \n End Class"),
NewLines("Class C(Of T1, T2) \n Sub M(x As T1, y As T2) \n Dim a As Test(Of T1, T2) = New Test(Of T1, T2)(x, y) \n End Sub \n End Class \n Friend Class Test(Of T1, T2) \n Private x As T1 \n Private y As T2 \n Public Sub New(x As T1, y As T2) \n Me.x = x \n Me.y = y \n End Sub \n End Class"),
index:=1)
End Sub
<WorkItem(540644)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestGenerateWithVoidArg()
Test(
NewLines("Module Program \n Sub Main(args As String()) \n Dim x As C = New [|C|](M()) \n End Sub \n Sub M() \n End Sub \n End Module"),
NewLines("Module Program \n Sub Main(args As String()) \n Dim x As C = New C(M()) \n End Sub \n Sub M() \n End Sub \n End Module \n Friend Class C \n Private v As Object \n Public Sub New(v As Object) \n Me.v = v \n End Sub \n End Class"),
index:=1)
End Sub
<WorkItem(539735)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestInAsClause()
Test(
NewLines("Class D \n Sub M() \n Dim x As New [|C|](4) \n End Sub \n End Class"),
NewLines("Class D \n Sub M() \n Dim x As New C(4) \n End Sub \n End Class \n Friend Class C \n Private v As Integer \n Public Sub New(v As Integer) \n Me.v = v \n End Sub \n End Class"),
index:=1)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestNotOnConstructorToActualType()
TestMissing(
NewLines("Class C \n Sub Test() \n Dim x As Integer = 1 \n Dim obj As New [|C|](x) \n End Sub \n End Class"))
End Sub
<WorkItem(540986)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestGenerateAttribute1()
Test(
NewLines("<[|AttClass|]()> \n Class C \n End Class"),
NewLines("Imports System \n <AttClass()> \n Class C \n End Class \n Friend Class AttClassAttribute \n Inherits Attribute \n End Class"),
index:=1)
End Sub
<WorkItem(540986)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestGenerateAttribute2()
Test(
NewLines("Imports System \n <[|AttClass|]()> \n Class C \n End Class"),
NewLines("Imports System \n <AttClass()> \n Class C \n End Class \n Friend Class AttClassAttribute \n Inherits Attribute \n End Class"),
index:=1)
End Sub
<WorkItem(541607)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestNotOnDictionaryAccess()
TestMissing(
NewLines("Imports System \n Imports System.Collections \n Imports System.Collections.Generic \n Public Class A \n Public Sub Foo() \n Dim Table As Hashtable = New Hashtable() \n Table![|Orange|] = ""A fruit"" \n Table(""Broccoli"") = ""A vegetable"" \n Console.WriteLine(Table!Orange) \n End Sub \n End Class"))
End Sub
<WorkItem(542392)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestAccessibilityConstraint1()
Test(
NewLines("Imports System.Runtime.CompilerServices \n Module StringExtensions \n <Extension()> \n Public Sub Print(ByVal aString As String, x As [|C|]) \n Console.WriteLine(aString) \n End Sub \n End Module"),
NewLines("Imports System.Runtime.CompilerServices \n Module StringExtensions \n <Extension()> \n Public Sub Print(ByVal aString As String, x As C) \n Console.WriteLine(aString) \n End Sub \n Public Class C \n End Class \n End Module"),
index:=2)
End Sub
<WorkItem(542836)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestNewLineAfterNestedType()
Test(
<Text>Class A
Sub Main()
Dim x As A()() = New [|HERE|]()
End Sub
End Class</Text>.NormalizedValue,
<Text>Class A
Sub Main()
Dim x As A()() = New HERE()
End Sub
Private Class HERE
Public Sub New()
End Sub
End Class
End Class</Text>.NormalizedValue,
index:=2,
compareTokens:=False)
End Sub
<WorkItem(543290)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestNestedType()
Test(
NewLines("Option Explicit Off \n Module Program \n Sub Main(args As String()) \n Dim i = 2 \n Dim r As New i.[|Extension|] \n End Sub \n Public Class i \n End Class \n End Module"),
NewLines("Option Explicit Off \n Module Program \n Sub Main(args As String()) \n Dim i = 2 \n Dim r As New i.Extension \n End Sub \n Public Class i \n Friend Class Extension \n End Class \n End Class \n End Module"))
End Sub
<WorkItem(543397)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestNewModule()
TestMissing(
NewLines("Module Program \n Sub Main \n Dim f As New [|Program|] \n End Sub \n End Module"))
End Sub
<WorkItem(545363)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestInHiddenNamespace1()
TestExactActionSetOffered(
<text>
#ExternalSource ("Default.aspx", 1)
Class Program
Sub Main(args As String())
Dim f As New [|Foo|]()
End Sub
End Class
#End ExternalSource
</text>.NormalizedValue,
{String.Format(FeaturesResources.GenerateForInNewFile, "class", "Foo", FeaturesResources.GlobalNamespace), String.Format(FeaturesResources.GenerateForIn, "class", "Foo", "Program"), FeaturesResources.GenerateNewType})
End Sub
<WorkItem(545363)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestInHiddenNamespace2()
TestExactActionSetOffered(
<text>
#ExternalSource ("Default.aspx", 1)
Class Program
Sub Main(args As String())
Dim f As New [|Foo|]()
End Sub
End Class
Class Bar
End Class
#End ExternalSource
</text>.NormalizedValue,
{String.Format(FeaturesResources.GenerateForInNewFile, "class", "Foo", FeaturesResources.GlobalNamespace), String.Format(FeaturesResources.GenerateForIn, "class", "Foo", FeaturesResources.GlobalNamespace), String.Format(FeaturesResources.GenerateForIn, "class", "Foo", "Program"), FeaturesResources.GenerateNewType})
End Sub
<WorkItem(545363)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestInHiddenNamespace3()
Test(
<text>
#ExternalSource ("Default.aspx", 1)
Class Program
Sub Main(args As String())
Dim f As New [|Foo|]()
End Sub
End Class
Class Bar
End Class
#End ExternalSource
</text>.NormalizedValue,
<text>
#ExternalSource ("Default.aspx", 1)
Class Program
Sub Main(args As String())
Dim f As New Foo()
End Sub
End Class
Friend Class Foo
Public Sub New()
End Sub
End Class
Class Bar
End Class
#End ExternalSource
</text>.NormalizedValue,
index:=1)
End Sub
<WorkItem(546852)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestAnonymousMethodArgument()
Test(
NewLines("Module Program \n Sub Main() \n Dim c = New [|C|](Function() x) \n End Sub \n End Module"),
NewLines("Imports System \n Module Program \n Sub Main() \n Dim c = New C(Function() x) \n End Sub \n End Module \n Friend Class C \n Private p As Func(Of Object) \n Public Sub New(p As Func(Of Object)) \n Me.p = p \n End Sub \n End Class"),
index:=1)
End Sub
<WorkItem(546851)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestOmittedArguments()
Test(
NewLines("Imports System \n Module Program \n Sub Main() \n Dim x = New [|C|](,) \n End Sub \n End Module"),
NewLines("Imports System \n Module Program \n Sub Main() \n Dim x = New C(,) \n End Sub \n End Module \n Friend Class C \n Private p1 As Object \n Private p2 As Object \n Public Sub New(p1 As Object, p2 As Object) \n Me.p1 = p1 \n Me.p2 = p2 \n End Sub \n End Class"),
index:=1)
End Sub
<WorkItem(1003618)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub GenerateTypeThatBindsToNamespace()
Test(
NewLines("Imports System \n [|<System>|] \n Module Program \n Sub Main() \n End Sub \n End Module"),
NewLines("Imports System \n <System> \n Module Program \n Sub Main() \n End Sub \n End Module \n Friend Class SystemAttribute \n Inherits Attribute \n End Class"),
index:=1)
End Sub
<WorkItem(821277)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestTooFewTypeArgument()
Test(
<text>
Class Program
Sub Main(args As String())
Dim f As [|AA|]
End Sub
End Class
Class AA(Of T)
End Class
</text>.NormalizedValue,
<text>
Class Program
Sub Main(args As String())
Dim f As AA
End Sub
End Class
Friend Class AA
End Class
Class AA(Of T)
End Class
</text>.NormalizedValue,
index:=1,
compareTokens:=False)
End Sub
<WorkItem(821277)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestTooMoreTypeArgument()
Test(
<text>
Class Program
Sub Main(args As String())
Dim f As [|AA(Of Integer, Integer)|]
End Sub
End Class
Class AA(Of T)
End Class
</text>.NormalizedValue,
<text>
Class Program
Sub Main(args As String())
Dim f As AA(Of Integer, Integer)
End Sub
End Class
Friend Class AA(Of T1, T2)
End Class
Class AA(Of T)
End Class
</text>.NormalizedValue,
index:=1,
compareTokens:=False)
End Sub
<WorkItem(942568)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub GenerateTypeWithPreferIntrinsicPredefinedKeywordFalse()
Test(
<text>
Class Program
Sub M(args As Integer)
Dim f = new [|T(args)|]
End Sub
End Class
</text>.NormalizedValue,
<text>
Class Program
Sub M(args As Integer)
Dim f = new T(args)
End Sub
End Class
Friend Class T
Private args As System.Int32
Public Sub New(args As System.Int32)
Me.args = args
End Sub
End Class
</text>.NormalizedValue,
index:=1,
compareTokens:=False,
options:=New Dictionary(Of OptionKey, Object) From {{New OptionKey(SimplificationOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, LanguageNames.VisualBasic), False}})
End Sub
<WorkItem(869506)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestGenerateTypeOutsideCurrentProject()
Dim initial = <Workspace>
<Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true">
<ProjectReference>Assembly2</ProjectReference>
<Document FilePath="Test1.vb">
Class Program
Sub Main()
Dim f As [|A.B.C$$|].D
End Sub
End Class
Namespace A
End Namespace</Document>
</Project>
<Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true">
<Document FilePath="Test2.cs">
Namespace A
Public Class B
End Class
End Namespace</Document>
</Project>
</Workspace>.ToString()
Dim expected = <Text>
Namespace A
Public Class B
Public Class C
End Class
End Class
End Namespace</Text>.NormalizedValue
Test(initial, expected, compareTokens:=False, isLine:=False)
End Sub
<WorkItem(940003)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestWithProperties1()
Test(
NewLines("Imports System \n Module Program \n Sub Main() \n Dim c As New [|Customer|](x:=1, y:=""Hello"") With {.Name = ""John"", .Age = Date.Today} \n End Sub \n End Module"),
NewLines("Imports System \n Module Program \n Sub Main() \n Dim c As New [|Customer|](x:=1, y:=""Hello"") With {.Name = ""John"", .Age = Date.Today} \n End Sub \n End Module \n Friend Class Customer \n Private x As Integer \n Private y As String \n Public Sub New(x As Integer, y As String) \n Me.x = x \n Me.y = y \n End Sub \n Public Property Age As Date \n Public Property Name As String \n End Class"),
index:=1)
End Sub
<WorkItem(940003)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestWithProperties2()
Test(
NewLines("Imports System \n Module Program \n Sub Main() \n Dim c As New [|Customer|](x:=1, y:=""Hello"") With {.Name = Nothing, .Age = Date.Today} \n End Sub \n End Module"),
NewLines("Imports System \n Module Program \n Sub Main() \n Dim c As New [|Customer|](x:=1, y:=""Hello"") With {.Name = Nothing, .Age = Date.Today} \n End Sub \n End Module \n Friend Class Customer \n Private x As Integer \n Private y As String \n Public Sub New(x As Integer, y As String) \n Me.x = x \n Me.y = y \n End Sub \n Public Property Age As Date \n Public Property Name As Object \n End Class"),
index:=1)
End Sub
<WorkItem(940003)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestWithProperties3()
Test(
NewLines("Imports System \n Module Program \n Sub Main() \n Dim c As New [|Customer|](x:=1, y:=""Hello"") With {.Name = Foo, .Age = Date.Today} \n End Sub \n End Module"),
NewLines("Imports System \n Module Program \n Sub Main() \n Dim c As New [|Customer|](x:=1, y:=""Hello"") With {.Name = Foo, .Age = Date.Today} \n End Sub \n End Module \n Friend Class Customer \n Private x As Integer \n Private y As String \n Public Sub New(x As Integer, y As String) \n Me.x = x \n Me.y = y \n End Sub \n Public Property Age As Date \n Public Property Name As Object \n End Class"),
index:=1)
End Sub
<WorkItem(1082031)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestWithProperties4()
Test(
NewLines("Imports System \n Module Program \n Sub Main() \n Dim c As New [|Customer|] With {.Name = ""John"", .Age = Date.Today} \n End Sub \n End Module"),
NewLines("Imports System \n Module Program \n Sub Main() \n Dim c As New [|Customer|] With {.Name = ""John"", .Age = Date.Today} \n End Sub \n End Module \n Friend Class Customer \n Public Property Age As Date \n Public Property Name As String \n End Class"),
index:=1)
End Sub
<WorkItem(1032176)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestWithNameOf()
Test(
NewLines("Imports System \n Module Program \n Sub Main() \n Dim x = nameof([|Z|]) \n End Sub \n End Module"),
NewLines("Imports System \n Module Program \n Sub Main() \n Dim x = nameof([|Z|]) \n End Sub \n End Module \n Friend Class Z \n End Class"),
index:=1)
End Sub
<WorkItem(1032176)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestWithNameOf2()
Test(
NewLines("Imports System \n Class Program \n Sub Main() \n Dim x = nameof([|Z|]) \n End Sub \n End Class"),
NewLines("Imports System \n Class Program \n Sub Main() \n Dim x = nameof([|Z|]) \n End Sub \n Private Class Z \n End Class \n End Class "),
index:=2)
End Sub
<WorkItem(1032176)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestWithNameOf3()
Test(
NewLines("Imports System \n Class Program \n Sub Main() \n Dim x = nameof([|Program.Z|]) \n End Sub \n End Class"),
NewLines("Imports System \n Class Program \n Sub Main() \n Dim x = nameof([|Program.Z|]) \n End Sub \n Private Class Z \n End Class \n End Class "),
index:=0)
End Sub
<WorkItem(1065647)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestAccesiblityForNestedType()
Test(
NewLines("Public Interface I \n Sub Foo(a As [|X.Y.Z|]) \n End Interface \n Public Class X \n End Class"),
NewLines("Public Interface I \n Sub Foo(a As X.Y.Z) \n End Interface \n Public Class X \n Public Class Y \n End Class \n End Class"),
index:=0)
End Sub
<WorkItem(1130905)>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestGenerateTypeInImports()
Test(
NewLines("Imports [|Fizz|]"),
NewLines("Friend Class Fizz\nEnd Class\n"), isAddedDocument:=True)
End Sub
<WorkItem(1130905)>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestGenerateTypeInImports2()
Test(
NewLines("Imports [|Fizz|]"),
NewLines("Imports Fizz \n Friend Class Fizz \n End Class"),
index:=1)
End Sub
<WorkItem(1107929)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestAccesiblityForPublicFields()
Test(
NewLines("Public Class A \n Public B As New [|B|]() \n End Class"),
NewLines("Public Class B \n Public Sub New() \n End Sub \n End Class"),
index:=0,
isAddedDocument:=True)
End Sub
<WorkItem(1107929)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestAccesiblityForPublicFields2()
Test(
NewLines("Public Class A \n Public B As New [|B|]() \n End Class"),
NewLines("Public Class A \n Public B As New B() \n End Class \n\n Public Class B \n Public Sub New() \n End Sub \n End Class"),
index:=1)
End Sub
<WorkItem(1107929)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestAccesiblityForPublicFields3()
Test(
NewLines("Public Class A \n Public B As New [|B|]() \n End Class"),
NewLines("Public Class A \n Public B As New B() \n Public Class B \n Public Sub New() \n End Sub \n End Class \n End Class"),
index:=2)
End Sub
<WorkItem(1107929)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestAccesiblityForPublicFields4()
Test(
NewLines("Public Class A \n Public B As New [|B|] \n End Class"),
NewLines("Public Class B \n End Class"),
index:=0,
isAddedDocument:=True)
End Sub
<WorkItem(1107929)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestAccesiblityForPublicFields5()
Test(
NewLines("Public Class A \n Public B As New [|B|] \n End Class"),
NewLines("Public Class A \n Public B As New B \n End Class \n\n Public Class B \n End Class"),
index:=1)
End Sub
<WorkItem(1107929)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestAccesiblityForPublicFields6()
Test(
NewLines("Public Class A \n Public B As New [|B|] \n End Class"),
NewLines("Public Class A \n Public B As New B \n Public Class B \n End Class \n End Class"),
index:=2)
End Sub
<WorkItem(1107929)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestAccesiblityForPublicFields7()
Test(
NewLines("Public Class A \n Public B As New [|B(Of Integer)|] \n End Class"),
NewLines("Public Class B(Of T) \n End Class"),
index:=0,
isAddedDocument:=True)
End Sub
<WorkItem(1107929)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestAccesiblityForPublicFields8()
Test(
NewLines("Public Class A \n Public B As New [|B(Of Integer)|] \n End Class"),
NewLines("Public Class A \n Public B As New B(Of Integer) \n End Class \n\n Public Class B(Of T) \n End Class"),
index:=1)
End Sub
<WorkItem(1107929)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Sub TestAccesiblityForPublicFields9()
Test(
NewLines("Public Class A \n Public B As New [|B(Of Integer)|] \n End Class"),
NewLines("Public Class A \n Public B As New B(Of Integer) \n Public Class B(Of T) \n End Class \n End Class"),
index:=2)
End Sub
Public Class AddImportTestsWithAddImportDiagnosticProvider
Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, CodeFixProvider)
Return Tuple.Create(Of DiagnosticAnalyzer, CodeFixProvider)(
New VisualBasicUnboundIdentifiersDiagnosticAnalyzer(),
New GenerateTypeCodeFixProvider())
End Function
<WorkItem(829970)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)>
Public Sub TestUnknownIdentifierInAttributeSyntaxWithoutTarget()
Test(
NewLines("Module Program \n <[|Extension|]> \n End Module"),
NewLines("Imports System \n Module Program \n <Extension> \n End Module \n Friend Class ExtensionAttribute \n Inherits Attribute \n End Class"),
index:=1)
End Sub
End Class
End Class
End Namespace
|
furesoft/roslyn
|
src/EditorFeatures/VisualBasicTest/Diagnostics/GenerateType/GenerateTypeTests.vb
|
Visual Basic
|
apache-2.0
| 41,641
|
' 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.
Imports System.Collections.Immutable
Imports System.Composition
Imports System.Threading
Imports Microsoft.CodeAnalysis.Completion
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.Snippets
Imports Microsoft.CodeAnalysis.Tags
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.Snippets
Imports Microsoft.VisualStudio.Text
Imports Microsoft.VisualStudio.Text.Projection
Imports Roslyn.Utilities
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense
<[UseExportProvider]>
Public Class VisualBasicCompletionCommandHandlerTests
<WorkItem(546208, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546208")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function MultiWordKeywordCommitBehavior() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>
Class C
Sub M()
$$
End Sub
End Class
</Document>)
state.SendTypeChars("on")
Await state.AssertSelectedCompletionItem("On Error GoTo", description:=String.Format(FeaturesResources._0_Keyword, "On Error GoTo") + vbCrLf + VBFeaturesResources.Enables_the_error_handling_routine_that_starts_at_the_line_specified_in_the_line_argument_The_specified_line_must_be_in_the_same_procedure_as_the_On_Error_statement_On_Error_GoTo_bracket_label_0_1_bracket)
state.SendTypeChars(" ")
Await state.AssertSelectedCompletionItem("On Error GoTo", description:=String.Format(FeaturesResources._0_Keyword, "On Error GoTo") + vbCrLf + VBFeaturesResources.Enables_the_error_handling_routine_that_starts_at_the_line_specified_in_the_line_argument_The_specified_line_must_be_in_the_same_procedure_as_the_On_Error_statement_On_Error_GoTo_bracket_label_0_1_bracket)
End Using
End Function
<WorkItem(546208, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546208")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function MultiWordKeywordCommitBehavior2() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>
Class C
Sub M()
$$
End Sub
End Class
</Document>)
state.SendTypeChars("next")
Await state.AssertSelectedCompletionItem("On Error Resume Next", description:=String.Format(FeaturesResources._0_Keyword, "On Error Resume Next") + vbCrLf + VBFeaturesResources.When_a_run_time_error_occurs_execution_transfers_to_the_statement_following_the_statement_or_procedure_call_that_resulted_in_the_error)
state.SendTypeChars(" ")
Await state.AssertNoCompletionSession()
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CompletionNotShownWhenBackspacingThroughWhitespace() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>
Module M
Sub Goo()
If True Then $$Console.WriteLine()
End Sub
End Module
</Document>)
state.SendBackspace()
Await state.AssertNoCompletionSession()
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion), WorkItem(541032, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541032")>
Public Async Function CompletionNotShownWhenBackspacingThroughNewline() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>
Module Program
Sub Main()
If True And
$$False Then
End If
End Sub
End Module
</Document>)
state.SendBackspace()
Await state.AssertNoCompletionSession()
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CompletionAdjustInsertionText_CommitsOnOpenParens1() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<document>
Module M
Sub FogBar()
End Sub
Sub test()
$$
End Sub
End Module
</document>)
state.SendTypeChars("Fog(")
Await state.AssertCompletionSession()
Assert.Contains(" FogBar(", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CompletionUpAfterDot() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<document>
Class Program
Sub Main(args As String())
Program$$
End Sub
End Class
</document>)
Await state.AssertNoCompletionSession()
state.SendTypeChars(".")
Await state.AssertCompletionSession()
End Using
End Function
<WorkItem(546432, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546432")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Sub ImplementsCompletionFaultTolerance()
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>
Imports System
Class C
Sub Goo() Implements ICloneable$$
End Module
</Document>)
state.SendTypeChars(".")
End Using
End Sub
<WorkItem(5487, "https://github.com/dotnet/roslyn/issues/5487")>
<WpfFact(Skip:="https://github.com/dotnet/roslyn/issues/48870"), Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestCommitCharTypedAtTheBeginingOfTheFilterSpan() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
Public Fuction F() As Boolean
If $$
End Function
End Class
]]></Document>)
state.SendTypeChars("tru")
Await state.AssertCompletionSession()
state.SendLeftKey()
state.SendLeftKey()
state.SendLeftKey()
Await state.AssertSelectedCompletionItem(isSoftSelected:=True)
state.SendTypeChars("(")
Assert.Equal("If (tru", state.GetLineTextFromCaretPosition().Trim())
Assert.Equal("t", state.GetCaretPoint().BufferPosition.GetChar())
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CompletionAdjustInsertionText_CommitsOnOpenParens2() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<document>
Module M
Sub FogBar(Of T)()
End Sub
Sub test()
$$
End Sub
End Module
</document>)
state.SendTypeChars("Fog(")
Await state.AssertCompletionSession()
Assert.Contains(" FogBar(", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WorkItem(543497, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543497")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CompletionDismissedAfterEscape1() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<document>
Class Program
Sub Main(args As String())
Program$$
End Sub
End Class
</document>)
Await state.AssertNoCompletionSession()
state.SendTypeChars(".")
Await state.AssertCompletionSession()
state.SendEscape()
Await state.AssertNoCompletionSession()
End Using
End Function
<WorkItem(543497, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543497")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestEnterOnSoftSelection1() As Task
' Code must be left-aligned because of https://github.com/dotnet/roslyn/issues/27988
Using state = TestStateFactory.CreateVisualBasicTestState(
<document>
Class Program
Shared Sub Main(args As String())
Program.$$
End Sub
End Class
</document>)
state.SendInvokeCompletionList()
Await state.AssertSelectedCompletionItem("Equals", isSoftSelected:=True)
Dim caretPos = state.GetCaretPoint().BufferPosition.Position
state.SendReturn()
state.Workspace.Documents.First().GetTextView().Caret.MoveTo(New SnapshotPoint(state.Workspace.Documents.First().GetTextBuffer().CurrentSnapshot, caretPos))
Assert.Contains("Program." + vbCrLf, state.GetLineFromCurrentCaretPosition().GetTextIncludingLineBreak(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CompletionTestTab1() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<document>
Module M
Sub FogBar()
End Sub
Sub test()
$$
End Sub
End Module
</document>)
state.SendTypeChars("Fog")
state.SendTab()
Await state.AssertNoCompletionSession()
Assert.Contains(" FogBar", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function DotIsInserted() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<document>
Class Program
Sub Main(args As String())
$$
End Sub
End Class
</document>)
state.SendTypeChars("Progra.")
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem(displayText:="Equals", isSoftSelected:=True)
Assert.Contains("Program.", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestReturn1() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<document>
Class Program
Sub Main(args As String())
$$
End Sub
End Class
</document>)
state.SendTypeChars("Progra")
state.SendReturn()
Await state.AssertNoCompletionSession()
Assert.Contains(<text>
Sub Main(args As String())
Program
End Sub</text>.NormalizedValue, state.GetDocumentText(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestDown1() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<document>
Namespace N
Class A
End Class
Class B
End Class
Class C
End Class
End Namespace
Class Program
Sub Main(args As String())
N$$
End Sub
End Class
</document>)
state.SendTypeChars(".A")
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem(displayText:="A", isHardSelected:=True)
state.SendDownKey()
Await state.AssertSelectedCompletionItem(displayText:="B", isHardSelected:=True)
state.SendDownKey()
Await state.AssertSelectedCompletionItem(displayText:="C", isHardSelected:=True)
state.SendDownKey()
Await state.AssertSelectedCompletionItem(displayText:="C", isHardSelected:=True)
state.SendPageUp()
Await state.AssertSelectedCompletionItem(displayText:="A", isHardSelected:=True)
state.SendUpKey()
Await state.AssertSelectedCompletionItem(displayText:="A", isHardSelected:=True)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestFirstCharacterDoesNotFilter1() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<document>
Namespace N
Class A
End Class
Class B
End Class
Class C
End Class
End Namespace
Class Program
Sub Main(args As String())
N$$
End Sub
End Class
</document>)
state.SendTypeChars(".A")
Await state.AssertCompletionSession()
Assert.Equal(3, state.GetCompletionItems().Count)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestSecondCharacterDoesFilter1() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<document>
Namespace N
Class AAA
End Class
Class AAB
End Class
Class BB
End Class
Class CC
End Class
End Namespace
Class Program
Sub Main(args As String())
N$$
End Sub
End Class
</document>)
state.SendTypeChars(".A")
Await state.AssertCompletionSession()
Assert.Equal(4, state.GetCompletionItems().Count)
state.SendTypeChars("A")
Await state.AssertCompletionSession()
Assert.Equal(2, state.GetCompletionItems().Count)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNavigateSoftToHard() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<document>
Class Program
Shared Sub Main(args As String())
Program.$$
End Sub
End Class
</document>)
state.SendInvokeCompletionList()
Await state.AssertSelectedCompletionItem(displayText:="Equals", isSoftSelected:=True)
state.SendUpKey()
Await state.AssertSelectedCompletionItem(displayText:="Equals", isHardSelected:=True)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestBackspaceBeforeCompletedComputation() As Task
' Simulate a very slow completionImplementation provider.
Using state = TestStateFactory.CreateVisualBasicTestState(
<document>
Class Program
Shared Sub Main(args As String())
Program$$
End Sub
End Class
</document>,
extraExportedTypes:={GetType(TriggeredCompletionProvider)}.ToList())
Dim completionService = DirectCast(state.Workspace.Services.GetLanguageServices(LanguageNames.VisualBasic).GetRequiredService(Of CompletionService)(), CompletionServiceWithProviders)
Dim provider = completionService.GetTestAccessor().GetAllProviders(ImmutableHashSet(Of String).Empty).OfType(Of TriggeredCompletionProvider)().Single()
Await state.AssertNoCompletionSession()
state.SendTypeChars(".M")
' We should not have a session now. Note: do not block as this will just deadlock things
' since the provider will not return.
state.AssertNoCompletionSessionWithNoBlock()
' Now, navigate back.
state.SendBackspace()
' allow the provider to continue
provider.e.Set()
' At this point, completionImplementation will be available since the caret is still within the model's span.
Await state.AssertCompletionSession()
' Now, navigate back again. Completion should be dismissed
state.SendBackspace()
Await state.AssertNoCompletionSession()
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNavigationBeforeCompletedComputation() As Task
' Simulate a very slow completionImplementation provider.
Using state = TestStateFactory.CreateVisualBasicTestState(
<document>
Class Program
Shared Sub Main(args As String())
Program$$
End Sub
End Class
</document>,
extraExportedTypes:={GetType(TriggeredCompletionProvider)}.ToList())
Dim completionService = DirectCast(state.Workspace.Services.GetLanguageServices(LanguageNames.VisualBasic).GetRequiredService(Of CompletionService)(), CompletionServiceWithProviders)
Dim provider = completionService.GetTestAccessor().GetAllProviders(ImmutableHashSet(Of String).Empty).OfType(Of TriggeredCompletionProvider)().Single()
Await state.AssertNoCompletionSession()
state.SendTypeChars(".Ma")
' We should not have a session now. Note: do not block as this will just deadlock things
' since the provider will not return.
state.AssertNoCompletionSessionWithNoBlock()
' Now, navigate using the caret.
state.SendMoveToPreviousCharacter()
' allow the provider to continue
provider.e.Set()
' Async provider can handle keys pressed while waiting for providers.
Await state.AssertCompletionSession()
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNavigationOutBeforeCompletedComputation() As Task
' Simulate a very slow completionImplementation provider.
Using state = TestStateFactory.CreateVisualBasicTestState(
<document>
Class Program
Shared Sub Main(args As String())
Program$$
End Sub
End Class
</document>,
extraExportedTypes:={GetType(TriggeredCompletionProvider)}.ToList())
Dim completionService = DirectCast(state.Workspace.Services.GetLanguageServices(LanguageNames.VisualBasic).GetRequiredService(Of CompletionService)(), CompletionServiceWithProviders)
Dim provider = completionService.GetTestAccessor().GetAllProviders(ImmutableHashSet(Of String).Empty).OfType(Of TriggeredCompletionProvider)().Single()
Await state.AssertNoCompletionSession()
state.SendTypeChars(".Ma")
' We should not have a session now. Note: do not block as this will just deadlock things
' since the provider will not return.
state.AssertNoCompletionSessionWithNoBlock()
' Now, navigate using the caret.
state.SendDownKey()
' allow the provider to continue
provider.e.Set()
' Caret was intended to be moved out of the span.
' Therefore, we should cancel the completion And move the caret.
Await state.AssertNoCompletionSession()
Assert.Contains(" End Sub", state.GetLineFromCurrentCaretPosition().GetText(), StringComparison.Ordinal)
End Using
End Function
<WpfFact(Skip:="https://github.com/dotnet/roslyn/issues/48870")>
<Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNavigateOutOfItemChangeSpan() As Task
' Code must be left-aligned because of https://github.com/dotnet/roslyn/issues/27988
Using state = TestStateFactory.CreateVisualBasicTestState(
<document>
Class Program
Shared Sub Main(args As String())
Program$$
End Sub
End Class
</document>)
Await state.AssertNoCompletionSession()
state.SendTypeChars(".Ma")
Await state.AssertCompletionSession()
state.SendMoveToPreviousCharacter()
Await state.AssertCompletionSession()
state.SendMoveToPreviousCharacter()
Await state.AssertCompletionSession()
state.SendMoveToPreviousCharacter()
Await state.AssertNoCompletionSession()
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestUndo1() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<document>
Class Program
Shared Sub Main(args As String())
Program$$
End Sub
End Class
</document>)
Await state.AssertNoCompletionSession()
state.SendTypeChars(".Ma(")
Await state.AssertCompletionSession()
Assert.Contains(".Main(", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
state.SendUndo()
Assert.Contains(".Ma(", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestCommitAfterNavigation() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<document>
Namespace N
Class A
End Class
Class B
End Class
Class C
End Class
End Namespace
Class Program
Sub Main(args As String())
N$$
End Sub
End Class
</document>)
state.SendTypeChars(".A")
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem(displayText:="A", isHardSelected:=True)
state.SendDownKey()
Await state.AssertSelectedCompletionItem(displayText:="B", isHardSelected:=True)
state.SendTab()
Assert.Contains(".B", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestFiltering1() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<document>
Imports System
Class c
Sub Main
$$
End Sub
End Class</document>)
state.SendTypeChars("Sy")
Await state.AssertCompletionItemsContainAll("OperatingSystem", "System")
Await state.AssertCompletionItemsDoNotContainAny("Exception", "Activator")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestMSCorLibTypes() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<document>
Imports System
Class c
Inherits$$
End Class</document>)
state.SendTypeChars(" ")
Await state.AssertCompletionItemsContainAll("Attribute", "Exception")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestDescription1() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<document>
<![CDATA[Imports System
''' <summary>
''' TestDoc
''' </summary>
Class TestException
Inherits Exception
End Class
Class MyException
Inherits $$
End Class]]></document>)
state.SendTypeChars("TestEx")
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem(description:="Class TestException" & vbCrLf & "TestDoc")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestObjectCreationPreselection1() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
Dim x As List(Of Integer) = New$$
End Sub
End Module]]></Document>)
state.SendTypeChars(" ")
Await state.AssertSelectedCompletionItem(displayText:="List(Of Integer)", isHardSelected:=True)
Await state.AssertCompletionItemsContainAll("LinkedList", "List", "System")
state.SendTypeChars("Li")
Await state.AssertSelectedCompletionItem(displayText:="List(Of Integer)", isHardSelected:=True)
Await state.AssertCompletionItemsContainAll("LinkedList", "List")
Await state.AssertCompletionItemsDoNotContainAny("System")
state.SendTypeChars("n")
Await state.AssertSelectedCompletionItem(displayText:="LinkedList", displayTextSuffix:="(Of " & ChrW(&H2026) & ")", isHardSelected:=True)
state.SendBackspace()
Await state.AssertSelectedCompletionItem(displayText:="List(Of Integer)", isHardSelected:=True)
state.SendTab()
Assert.Contains("New List(Of Integer)", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WorkItem(287, "https://github.com/dotnet/roslyn/issues/287")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NotEnumPreselectionAfterBackspace() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Enum E
Bat
End Enum
Class C
Sub Test(param As E)
Dim b As E
Test(b.$$)
End Sub
End Class]]></Document>)
state.SendBackspace()
Await state.AssertSelectedCompletionItem(displayText:="b", isHardSelected:=True)
End Using
End Function
<WorkItem(543496, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543496")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNumericLiteralWithNoMatch() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>
Imports System
Module Program
Sub Main(args As String())
Dim i =$$
End Sub
End Module</Document>)
state.SendTypeChars(" 0")
Await state.AssertNoCompletionSession()
state.SendReturn()
Await state.AssertNoCompletionSession()
Assert.Equal(<Document>
Imports System
Module Program
Sub Main(args As String())
Dim i = 0
End Sub
End Module</Document>.NormalizedValue, state.GetDocumentText())
End Using
End Function
<WorkItem(543496, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543496")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNumericLiteralWithPartialMatch() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>
Imports System
Module Program
Sub Main(args As String())
Dim i =$$
End Sub
End Module</Document>)
' Could match Int32
' kayleh 1/17/2013, but we decided to have #s always dismiss the list in bug 547287
state.SendTypeChars(" 3")
Await state.AssertNoCompletionSession()
state.SendReturn()
Await state.AssertNoCompletionSession()
Assert.Equal(<Document>
Imports System
Module Program
Sub Main(args As String())
Dim i = 3
End Sub
End Module</Document>.NormalizedValue, state.GetDocumentText())
End Using
End Function
<WorkItem(543496, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543496")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNumbersAfterLetters() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>
Imports System
Module Program
Sub Main(args As String())
Dim i =$$
End Sub
End Module</Document>)
' Could match Int32
state.SendTypeChars(" I3")
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem(displayText:="Int32", isHardSelected:=True)
state.SendReturn()
Await state.AssertNoCompletionSession()
Assert.Equal(<Document>
Imports System
Module Program
Sub Main(args As String())
Dim i = Int32
End Sub
End Module</Document>.NormalizedValue, state.GetDocumentText())
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNotAfterTypingDotAfterIntegerLiteral() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>
class c
sub M()
WriteLine(3$$
end sub
end class
</Document>)
state.SendTypeChars(".")
Await state.AssertNoCompletionSession()
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestAfterExplicitInvokeAfterDotAfterIntegerLiteral() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>
class c
sub M()
WriteLine(3.$$
end sub
end class
</Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionItemsContainAll("ToString")
End Using
End Function
<WorkItem(543669, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543669")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestDeleteWordToLeft() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>
class c
sub M()
$$
end sub
end class
</Document>)
state.SendTypeChars("Dim i =")
Await state.AssertCompletionSession()
state.SendDeleteWordToLeft()
Await state.AssertNoCompletionSession()
End Using
End Function
<WorkItem(543617, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543617")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestCompletionGenericWithOpenParen() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>
class c
sub Goo(Of X)()
$$
end sub
end class
</Document>)
state.SendTypeChars("Go(")
Await state.AssertCompletionSession()
Assert.Equal(" Goo(", state.GetLineTextFromCaretPosition())
Assert.DoesNotContain("Goo(Of", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WorkItem(543617, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543617")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestCompletionGenericWithSpace() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>
class c
sub Goo(Of X)()
$$
end sub
end class
</Document>)
state.SendTypeChars("Go ")
Await state.AssertCompletionSession()
Assert.Equal(" Goo(Of ", state.GetLineTextFromCaretPosition())
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitForImportsStatement1() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>
$$
</Document>)
state.SendTypeChars("Imports Sys")
Await state.AssertSelectedCompletionItem(displayText:="System", isHardSelected:=True)
state.SendTypeChars("(")
Await state.AssertNoCompletionSession()
Assert.Contains("Imports Sys(", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitForImportsStatement2() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>
$$
</Document>)
state.SendTypeChars("Imports Sys")
Await state.AssertSelectedCompletionItem(displayText:="System", isHardSelected:=True)
state.SendTypeChars(".")
Await state.AssertCompletionSession()
Assert.Contains("Imports System.", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitForImportsStatement3() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>
$$
</Document>)
state.SendTypeChars("Imports Sys")
Await state.AssertSelectedCompletionItem(displayText:="System", isHardSelected:=True)
state.SendTypeChars(" ")
Await state.AssertNoCompletionSession()
Assert.Contains("Imports Sys ", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WorkItem(544190, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544190")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function DoNotInsertEqualsForNamedParameterCommitWithColon() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>
Class Class1
Sub Method()
Test($$
End Sub
Sub Test(Optional x As Integer = 42)
End Sub
End Class
</Document>)
state.SendTypeChars("x:")
Await state.AssertNoCompletionSession()
Assert.DoesNotContain(":=", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WorkItem(544190, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544190")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function DoInsertEqualsForNamedParameterCommitWithSpace() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>
Class Class1
Sub Method()
Test($$
End Sub
Sub Test(Optional x As Integer = 42)
End Sub
End Class
</Document>)
state.SendTypeChars("x")
state.SendTab()
Await state.AssertNoCompletionSession()
Assert.Contains(":=", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WorkItem(544150, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544150")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function ConsumeHashForPreprocessorCompletion() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>
$$
</Document>)
state.SendTypeChars("#re")
state.SendTab()
Await state.AssertNoCompletionSession()
Assert.Equal("#Region", state.GetLineTextFromCaretPosition())
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function EnumCompletionTriggeredOnSpace() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>
Enum Numeros
Uno
Dos
End Enum
Class Goo
Sub Bar(a As Integer, n As Numeros)
End Sub
Sub Baz()
Bar(0$$
End Sub
End Class
</Document>)
state.SendTypeChars(", ")
Await state.AssertSelectedCompletionItem(displayText:="Numeros.Dos", isSoftSelected:=True)
End Using
End Function
<ExportCompletionProvider(NameOf(TriggeredCompletionProvider), LanguageNames.VisualBasic)>
<[Shared]>
<PartNotDiscoverable>
Friend Class TriggeredCompletionProvider
Inherits MockCompletionProvider
Public ReadOnly e As ManualResetEvent = New ManualResetEvent(False)
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
MyBase.New(getItems:=Function(t, p, c)
Return Nothing
End Function,
isTriggerCharacter:=Function(t, p) True)
End Sub
Public Overrides Function ProvideCompletionsAsync(context As CompletionContext) As Task
e.WaitOne()
Return MyBase.ProvideCompletionsAsync(context)
End Function
End Class
<WorkItem(544297, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544297")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestVerbatimNamedIdentifierFiltering() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>
Class Class1
Private Sub Test([string] As String)
Test($$
End Sub
End Class
</Document>)
state.SendTypeChars("s")
Await state.AssertCompletionSession()
Await state.AssertCompletionItemsContain("string", ":=")
state.SendTypeChars("t")
Await state.AssertCompletionSession()
Await state.AssertCompletionItemsContain("string", ":=")
End Using
End Function
<WorkItem(544299, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544299")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestExclusiveNamedParameterCompletion() As Task
Using state = TestStateFactory.CreateTestStateFromWorkspace(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true" LanguageVersion="15">
<Document>
Class Class1
Private Sub Test()
Goo(bool:=False,$$
End Sub
Private Sub Goo(str As String, character As Char)
End Sub
Private Sub Goo(str As String, bool As Boolean)
End Sub
End Class
</Document>
</Project>
</Workspace>)
state.SendTypeChars(" ")
Await state.AssertCompletionSession()
Assert.Equal(1, state.GetCompletionItems().Count)
Await state.AssertCompletionItemsContain("str", ":=")
End Using
End Function
<WorkItem(544299, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544299")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestExclusiveNamedParameterCompletion2() As Task
Using state = TestStateFactory.CreateTestStateFromWorkspace(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true" LanguageVersion="15">
<Document>
Class Goo
Private Sub Test()
Dim m As Object = Nothing
Method(obj:=m, $$
End Sub
Private Sub Method(obj As Object, num As Integer, str As String)
End Sub
Private Sub Method(dbl As Double, str As String)
End Sub
Private Sub Method(num As Integer, b As Boolean, str As String)
End Sub
Private Sub Method(obj As Object, b As Boolean, str As String)
End Sub
End Class
</Document>
</Project>
</Workspace>)
state.SendTypeChars(" ")
Await state.AssertCompletionSession()
Assert.Equal(3, state.GetCompletionItems().Count)
Await state.AssertCompletionItemsContain("b", ":=")
Await state.AssertCompletionItemsContain("num", ":=")
Await state.AssertCompletionItemsContain("str", ":=")
Assert.False(state.GetCompletionItems().Any(Function(i) i.DisplayText = "dbl" AndAlso i.DisplayTextSuffix = ":="))
End Using
End Function
<WorkItem(544471, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544471")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestDontCrashOnEmptyParameterList() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>
<Obsolete()$$>
</Document>)
state.SendTypeChars(" ")
Await state.AssertNoCompletionSession()
End Using
End Function
<WorkItem(544628, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544628")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function OnlyMatchOnLowercaseIfPrefixWordMatch() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>
Module Program
$$
End Module
</Document>)
state.SendTypeChars("z")
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem("#Const", isSoftSelected:=True)
End Using
End Function
<WorkItem(544989, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544989")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function MyBaseFinalize() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>
Class C
Protected Overrides Sub Finalize()
MyBase.Finalize$$
End Sub
End Class
</Document>)
state.SendTypeChars("(")
Await state.AssertSignatureHelpSession()
Await state.AssertSignatureHelpItemsContainAll({"Object.Finalize()"})
End Using
End Function
<WorkItem(551117, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/551117")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNamedParameterSortOrder() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>
Imports System
Module Program
Sub Main(args As String())
Main($$
End Sub
End Module
</Document>)
state.SendTypeChars("a")
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem("args", isHardSelected:=True)
state.SendDownKey()
Await state.AssertSelectedCompletionItem("args", displayTextSuffix:=":=", isHardSelected:=True)
End Using
End Function
<WorkItem(546810, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546810")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestLineContinuationCharacter() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>
Imports System
Module Program
Sub Main()
Dim x = New $$
End Sub
End Module
</Document>)
state.SendTypeChars("_")
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem("_AppDomain", isHardSelected:=False)
End Using
End Function
<WorkItem(547287, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547287")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNumberDismissesCompletion() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>
Imports System
Module Program
Sub Main()
Console.WriteLine$$
End Sub
End Module
</Document>)
state.SendTypeChars("(")
Await state.AssertCompletionSession()
state.SendTypeChars(".")
Await state.AssertNoCompletionSession()
state.SendBackspace()
state.SendBackspace()
state.SendTypeChars("(")
Await state.AssertCompletionSession()
state.SendTypeChars("-")
Await state.AssertNoCompletionSession()
state.SendBackspace()
state.SendBackspace()
state.SendTypeChars("(")
Await state.AssertCompletionSession()
state.SendTypeChars("1")
Await state.AssertNoCompletionSession()
End Using
End Function
<WpfFact(Skip:="https://github.com/dotnet/roslyn/issues/27446"), Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestProjections() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>
{|S1:
Imports System
Module Program
Sub Main(arg As String)
Dim bbb = 234
Console.WriteLine$$
End Sub
End Module|} </Document>)
Dim subjectDocument = state.Workspace.Documents.First()
Dim firstProjection = state.Workspace.CreateProjectionBufferDocument(
<Document>
{|S1:|}
{|S2: some text that's mapped to the surface buffer |}
</Document>.NormalizedValue, {subjectDocument}, options:=ProjectionBufferOptions.WritableLiteralSpans)
Dim topProjectionBuffer = state.Workspace.CreateProjectionBufferDocument(
<Document>
{|S1:|}
{|S2:|}
</Document>.NormalizedValue, {firstProjection}, options:=ProjectionBufferOptions.WritableLiteralSpans)
' Test a view that has a subject buffer with multiple projection buffers in between
Dim view = topProjectionBuffer.GetTextView()
Dim subjectBuffer = subjectDocument.GetTextBuffer()
state.SendTypeCharsToSpecificViewAndBuffer("(", view, subjectBuffer)
Await state.AssertCompletionSession(view)
state.SendTypeCharsToSpecificViewAndBuffer("a", view, subjectBuffer)
Await state.AssertSelectedCompletionItem(displayText:="arg", projectionsView:=view)
Dim text = view.TextSnapshot.GetText()
Dim projection = DirectCast(topProjectionBuffer.GetTextBuffer(), IProjectionBuffer)
Dim sourceSpans = projection.CurrentSnapshot.GetSourceSpans()
' unmap our source spans without changing the top buffer
projection.ReplaceSpans(0, sourceSpans.Count, {subjectBuffer.CurrentSnapshot.CreateTrackingSpan(0, subjectBuffer.CurrentSnapshot.Length, SpanTrackingMode.EdgeInclusive)}, EditOptions.DefaultMinimalChange, editTag:=Nothing)
state.SendBackspace()
state.SendTypeChars("b")
Await state.AssertSelectedCompletionItem(displayText:="bbb")
' prepare to remap our subject buffer
Dim subjectBufferText = subjectDocument.GetTextBuffer().CurrentSnapshot.GetText()
Using edit = subjectDocument.GetTextBuffer().CreateEdit(EditOptions.DefaultMinimalChange, reiteratedVersionNumber:=Nothing, editTag:=Nothing)
edit.Replace(New Span(0, subjectBufferText.Length), subjectBufferText.Replace("Console.WriteLine(a", "Console.WriteLine(b"))
edit.Apply()
End Using
Dim replacementSpans = sourceSpans.Select(Function(ss)
If ss.Snapshot.TextBuffer.ContentType.TypeName = "inert" Then
Return DirectCast(ss.Snapshot.GetText(ss.Span), Object)
Else
Return DirectCast(ss.Snapshot.CreateTrackingSpan(ss.Span, SpanTrackingMode.EdgeExclusive), Object)
End If
End Function).ToList()
projection.ReplaceSpans(0, 1, replacementSpans, EditOptions.DefaultMinimalChange, editTag:=Nothing)
' the same completionImplementation session should still be active after the remapping.
Await state.AssertSelectedCompletionItem(displayText:="bbb", projectionsView:=view)
state.SendTypeCharsToSpecificViewAndBuffer("b", view, subjectBuffer)
Await state.AssertSelectedCompletionItem(displayText:="bbb", projectionsView:=view)
' verify we can commit even when unmapped
projection.ReplaceSpans(0, projection.CurrentSnapshot.GetSourceSpans.Count, {projection.CurrentSnapshot.GetText()}, EditOptions.DefaultMinimalChange, editTag:=Nothing)
Await state.SendCommitUniqueCompletionListItemAsync()
Assert.Contains(<text>
Imports System
Module Program
Sub Main(arg As String)
Dim bbb = 234
Console.WriteLine(bbb
End Sub
End Module </text>.NormalizedValue, state.GetDocumentText(), StringComparison.Ordinal)
End Using
End Function
<WorkItem(622957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/622957")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestBangFiltersInDocComment() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
''' $$
Public Class TestClass
End Class
]]></Document>)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("!")
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem("!--")
End Using
End Function
<WpfFact(Skip:="https://github.com/dotnet/roslyn/issues/48870")>
<Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CompletionUpAfterBackSpacetoWord() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>
Public E$$
</Document>)
state.SendBackspace()
Await state.AssertCompletionSession()
state.SendBackspace()
Await state.AssertNoCompletionSession()
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function NoCompletionAfterBackspaceInStringLiteral() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>
Sub Goo()
Dim z = "aa$$"
End Sub
</Document>)
state.SendBackspace()
Await state.AssertNoCompletionSession()
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CompletionUpAfterDeleteDot() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>
Sub Goo()
Dim z = "a"
z.$$ToString()
End Sub
</Document>)
state.SendBackspace()
Await state.AssertCompletionSession()
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function NotCompletionUpAfterDeleteRParen() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>
Sub Goo()
"a".ToString()$$
End Sub
</Document>)
state.SendBackspace()
Await state.AssertNoCompletionSession()
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function NotCompletionUpAfterDeleteLParen() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>
Sub Goo()
"a".ToString($$
End Sub
</Document>)
state.SendBackspace()
Await state.AssertNoCompletionSession()
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function NotCompletionUpAfterDeleteComma() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>
Sub Goo(x as Integer, y as Integer)
Goo(1,$$)
End Sub
</Document>)
state.SendBackspace()
Await state.AssertNoCompletionSession()
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CompletionAfterDeleteKeyword() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>
Sub Goo(x as Integer, y as Integer)
Goo(1,2)
End$$ Sub
</Document>)
state.SendBackspace()
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem("End", description:=String.Format(FeaturesResources._0_Keyword, "End") + vbCrLf + VBFeaturesResources.Stops_execution_immediately)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function NoCompletionOnBackspaceAtBeginningOfFile() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>$$</Document>)
state.SendBackspace()
Await state.AssertNoCompletionSession()
End Using
End Function
<WpfFact(), Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CompletionUpAfterLeftCurlyBrace() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<document>
Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
Dim l As New List(Of Integer) From $$
End Sub
End Module
</document>)
Await state.AssertNoCompletionSession()
state.SendTypeChars("{")
Await state.AssertCompletionSession()
End Using
End Function
<WpfFact(), Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CompletionUpAfterLeftAngleBracket() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<document>
$$
Module Program
Sub Main(args As String())
End Sub
End Module
</document>)
Await state.AssertNoCompletionSession()
state.SendTypeChars("<")
Await state.AssertCompletionSession()
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeCompletionDoesNotFilter() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Imports System
Class G
Sub goo()
Dim x as String$$
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertSelectedCompletionItem("String")
Await state.AssertCompletionItemsContainAll("Integer", "G")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeCompletionSelectsWithoutRegardToCaretPosition() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Imports System
Class G
Sub goo()
Dim x as Str$$ing
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertSelectedCompletionItem("String")
Await state.AssertCompletionItemsContainAll("Integer", "G")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeCompletionBeforeWordDoesNotSelect() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Imports System
Class G
Sub goo()
Dim x as $$String
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertSelectedCompletionItem("AccessViolationException")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function BackspaceCompletionInvokedSelectedAndUnfiltered() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Imports System
Class G
Sub goo()
Dim x as String$$
End Sub
End Class
]]></Document>)
state.SendBackspace()
Await state.AssertSelectedCompletionItem("String")
Await state.AssertCompletionItemsContainAll("Integer", "G")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function ListDismissedIfNoMatches() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Imports System
Class G
Sub goo()
Dim x as $$
End Sub
End Class
]]></Document>)
state.SendTypeChars("str")
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem("String", isHardSelected:=True)
state.SendTypeChars("gg")
Await state.AssertNoCompletionSession()
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeCompletionComesUpEvenIfNoMatches() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Imports System
Class G
Sub goo()
Dim x as gggg$$
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
End Using
End Function
<WorkItem(674422, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/674422")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function BackspaceInvokeCompletionComesUpEvenIfNoMatches() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Imports System
Class G
Sub goo()
Dim x as gggg$$
End Sub
End Class
]]></Document>)
state.SendBackspace()
Await state.AssertCompletionSession()
state.SendBackspace()
Await state.AssertCompletionSession()
End Using
End Function
<WorkItem(674366, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/674366")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function BackspaceCompletionSelects() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Imports System
Class G
Sub goo()
Dim x as Integrr$$
End Sub
End Class
]]></Document>)
state.SendBackspace()
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem("Integer")
End Using
End Function
<WorkItem(675555, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/675555")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function BackspaceCompletionNeverFilters() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Imports System
Class G
Sub goo()
Dim x as String$$
End Sub
End Class
]]></Document>)
state.SendBackspace()
Await state.AssertCompletionSession()
Await state.AssertCompletionItemsContainAll("AccessViolationException")
state.SendBackspace()
Await state.AssertCompletionSession()
Await state.AssertCompletionItemsContainAll("AccessViolationException")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Sub TabAfterQuestionMarkInEmptyLine()
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Imports System
Class G
Sub goo()
?$$
End Sub
End Class
]]></Document>)
state.SendTab()
Assert.Equal(state.GetLineTextFromCaretPosition(), " ?" + vbTab)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Sub TabAfterTextFollowedByQuestionMark()
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Imports System
Class G
Sub goo()
a?$$
End Sub
End Class
]]></Document>)
state.SendTab()
Assert.Equal(state.GetLineTextFromCaretPosition(), " a")
End Using
End Sub
<WorkItem(669942, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/669942")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function DistinguishItemsWithDifferentGlyphs() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Imports System
Imports System.Linq
Class Test
Sub [Select]()
End Sub
Sub Goo()
Dim k As Integer = 1
$$
End Sub
End Class
]]></Document>)
state.SendTypeChars("selec")
Await state.AssertCompletionSession()
Assert.Equal(state.GetCompletionItems().Count, 2)
End Using
End Function
<WorkItem(670149, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/670149")>
<WpfFact(), Trait(Traits.Feature, Traits.Features.Completion)>
Public Sub TabAfterNullableFollowedByQuestionMark()
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Imports System
Class G
Dim a As Integer?$$
End Class
]]></Document>)
state.SendTab()
Assert.Equal(state.GetLineTextFromCaretPosition(), " Dim a As Integer?" + vbTab)
End Using
End Sub
<WorkItem(672474, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/672474")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestInvokeSnippetCommandDismissesCompletion() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>$$</Document>)
state.SendTypeChars("Imp")
Await state.AssertCompletionSession()
state.SendInsertSnippetCommand()
Await state.AssertNoCompletionSession()
End Using
End Function
<WorkItem(672474, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/672474")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestSurroundWithCommandDismissesCompletion() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>$$</Document>)
state.SendTypeChars("Imp")
Await state.AssertCompletionSession()
state.SendSurroundWithCommand()
Await state.AssertNoCompletionSession()
End Using
End Function
<WorkItem(716117, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/716117")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function XmlCompletionNotTriggeredOnBackspaceInText() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
''' <summary>
''' text$$
''' </summary>
Class G
Dim a As Integer?
End Class]]></Document>)
state.SendBackspace()
Await state.AssertNoCompletionSession()
End Using
End Function
<WorkItem(716117, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/716117")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function XmlCompletionNotTriggeredOnBackspaceInTag() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
''' <summary$$>
''' text
''' </summary>
Class G
Dim a As Integer?
End Class]]></Document>)
state.SendBackspace()
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem("summary")
End Using
End Function
<WorkItem(674415, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/674415")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function BackspacingLastCharacterDismisses() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>$$</Document>)
state.SendTypeChars("A")
Await state.AssertCompletionSession()
state.SendBackspace()
Await state.AssertNoCompletionSession()
End Using
End Function
<WorkItem(719977, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/719977")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function HardSelectionWithBuilderAndOneExactMatch() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>Module M
Public $$
End Module</Document>)
state.SendTypeChars("sub")
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem("Sub")
Assert.True(state.HasSuggestedItem())
End Using
End Function
<WorkItem(828603, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/828603")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function SoftSelectionWithBuilderAndNoExactMatch() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>Module M
Public $$
End Module</Document>)
state.SendTypeChars("prop")
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem("Property", isSoftSelected:=True)
Assert.True(state.HasSuggestedItem())
End Using
End Function
' The test verifies the CommitCommandHandler isolated behavior which does not add '()' after 'Main'.
' The integrated VS behavior for the case is to get 'Main()'.
<WorkItem(792569, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/792569")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Sub CommitOnEnter()
Dim expected = <Document>Module M
Sub Main()
Main
End Sub
End Module</Document>.Value.Replace(vbLf, vbCrLf)
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>Module M
Sub Main()
Ma$$i
End Sub
End Module</Document>)
state.SendInvokeCompletionList()
state.SendReturn()
Assert.Equal(expected, state.GetDocumentText())
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Sub TestEnterIsConsumedWithAfterFullyTypedWordOption_NotFullyTyped()
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>
Class Class1
Sub Main(args As String())
$$
End Sub
End Class
</Document>)
Dim workspace = state.Workspace
workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _
.WithChangedOption(CompletionOptions.EnterKeyBehavior, LanguageNames.VisualBasic, EnterKeyRule.AfterFullyTypedWord)))
state.SendTypeChars("System.TimeSpan.FromMin")
state.SendReturn()
Assert.Equal(<text>
Class Class1
Sub Main(args As String())
System.TimeSpan.FromMinutes
End Sub
End Class
</text>.NormalizedValue, state.GetDocumentText())
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Sub TestEnterIsConsumedWithAfterFullyTypedWordOption_FullyTyped()
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>
Class Class1
Sub Main(args As String())
$$
End Sub
End Class
</Document>)
Dim workspace = state.Workspace
workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _
.WithChangedOption(CompletionOptions.EnterKeyBehavior, LanguageNames.VisualBasic, EnterKeyRule.AfterFullyTypedWord)))
state.SendTypeChars("System.TimeSpan.FromMinutes")
state.SendReturn()
Assert.Equal(<text>
Class Class1
Sub Main(args As String())
System.TimeSpan.FromMinutes
End Sub
End Class
</text>.NormalizedValue, state.GetDocumentText())
End Using
End Sub
<WorkItem(546208, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546208")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function SelectKeywordFirst() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>
Class C
Sub M()
$$
End Sub
Sub GetType()
End Sub
End Class
</Document>)
state.SendTypeChars("GetType")
Await state.AssertSelectedCompletionItem(
displayText:="GetType",
displayTextSuffix:=String.Empty,
description:=VBFeaturesResources.GetType_function + vbCrLf +
VBWorkspaceResources.Returns_a_System_Type_object_for_the_specified_type_name + vbCrLf +
$"GetType({VBWorkspaceResources.typeName}) As Type")
End Using
End Function
<WorkItem(828392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/828392")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function ConstructorFiltersAsNew() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>
Public Class Base
Public Sub New(x As Integer)
End Sub
End Class
Public Class Derived
Inherits Base
Public Sub New(x As Integer)
MyBase.$$
End Sub
End Class
</Document>)
state.SendTypeChars("New")
Await state.AssertSelectedCompletionItem("New", isHardSelected:=True)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function NoUnmentionableTypeInObjectCreation() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>
Public Class C
Sub Goo()
Dim a = new$$
End Sub
End Class
</Document>)
state.SendTypeChars(" ")
Await state.AssertSelectedCompletionItem("AccessViolationException", isSoftSelected:=True)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function FilterPreferEnum() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>
Enum E
Goo
Bar
End Enum
Class Goo
End Class
Public Class C
Sub Goo()
E e = $$
End Sub
End Class</Document>)
state.SendTypeChars("g")
Await state.AssertSelectedCompletionItem("E.Goo", isHardSelected:=True)
End Using
End Function
<WorkItem(883295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/883295")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InsertOfOnSpace() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>
Imports System.Threading.Tasks
Public Class C
Sub Goo()
Dim a as $$
End Sub
End Class
</Document>)
state.SendTypeChars("Task")
Await state.WaitForUIRenderedAsync()
state.SendDownKey()
state.SendTypeChars(" ")
Assert.Equal(" Dim a as Task(Of ", state.GetLineTextFromCaretPosition())
End Using
End Function
<WorkItem(883295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/883295")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Sub DoNotInsertOfOnTab()
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>
Imports System.Threading.Tasks
Public Class C
Sub Goo()
Dim a as $$
End Sub
End Class
</Document>)
state.SendTypeChars("Task")
state.SendTab()
Assert.Equal(state.GetLineTextFromCaretPosition(), " Dim a as Task")
End Using
End Sub
<WorkItem(899414, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899414")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function NotInPartialMethodDeclaration() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>
Module Module1
Sub Main()
End Sub
End Module
Public Class Class2
Partial Private Sub PartialMethod(ByVal x As Integer)
$$
End Sub
End Class</Document>)
state.SendInvokeCompletionList()
Await state.AssertNoCompletionSession()
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestCompletionInLinkedFiles() As Task
Using state = TestStateFactory.CreateTestStateFromWorkspace(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBProj" PreprocessorSymbols="Thing2=True">
<Document FilePath="C.vb">
Class C
Sub M()
$$
End Sub
#If Thing1 Then
Sub Thing1()
End Sub
#End If
#If Thing2 Then
Sub Thing2()
End Sub
#End If
End Class
</Document>
</Project>
<Project Language="Visual Basic" CommonReferences="true" PreprocessorSymbols="Thing1=True">
<Document IsLinkFile="true" LinkAssemblyName="VBProj" LinkFilePath="C.vb"/>
</Project>
</Workspace>)
Dim documents = state.Workspace.Documents
Dim linkDocument = documents.Single(Function(d) d.IsLinkFile)
state.SendTypeChars("Thi")
Await state.AssertSelectedCompletionItem("Thing1")
state.SendBackspace()
state.SendBackspace()
state.SendBackspace()
state.Workspace.SetDocumentContext(linkDocument.Id)
state.SendTypeChars("Thi")
Await state.AssertSelectedCompletionItem("Thing1")
End Using
End Function
<WorkItem(916452, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916452")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function SoftSelectedWithNoFilterText() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>
Imports System
Class C
Public Sub M(day As DayOfWeek)
M$$
End Sub
End Class</Document>)
state.SendTypeChars("(")
Await state.AssertCompletionSession()
Assert.True(state.IsSoftSelected())
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function EnumSortingOrder() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>
Imports System
Class C
Public Sub M(day As DayOfWeek)
M$$
End Sub
End Class</Document>)
state.SendTypeChars("(")
Await state.AssertCompletionSession()
' DayOfWeek.Monday should immediately follow DayOfWeek.Friday
Dim friday = state.GetCompletionItems().First(Function(i) i.DisplayText = "DayOfWeek.Friday")
Dim monday = state.GetCompletionItems().First(Function(i) i.DisplayText = "DayOfWeek.Monday")
Assert.True(state.GetCompletionItems().IndexOf(friday) = state.GetCompletionItems().IndexOf(monday) - 1)
End Using
End Function
<WorkItem(951726, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/951726")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function DismissUponSave() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
$$
End Class]]></Document>)
state.SendTypeChars("Su")
Await state.AssertSelectedCompletionItem("Sub")
state.SendSave()
Await state.AssertNoCompletionSession()
state.AssertMatchesTextStartingAtLine(2, " Su")
End Using
End Function
<WorkItem(969794, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/969794")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function DeleteCompletionInvokedSelectedAndUnfiltered() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Imports System
Class G
Sub goo()
Dim x as Stri$$ng
End Sub
End Class
]]></Document>)
state.SendDelete()
Await state.AssertSelectedCompletionItem("String")
End Using
End Function
<WorkItem(871755, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/871755")>
<WorkItem(954556, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/954556")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function FilterPrefixOnlyOnBackspace1() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Imports System
Class G
Public Re$$
End Class
]]></Document>)
state.SendBackspace()
Await state.AssertSelectedCompletionItem("ReadOnly")
state.SendTypeChars("a")
Await state.AssertNoCompletionSession()
End Using
End Function
<WorkItem(969040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/969040")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function BackspaceTriggerOnlyIfOptionEnabled() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Imports System
Class G
Public Re$$
End Class
]]></Document>)
Dim workspace = state.Workspace
workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _
.WithChangedOption(CompletionOptions.TriggerOnTyping, LanguageNames.VisualBasic, False)))
state.SendBackspace()
Await state.AssertNoCompletionSession()
End Using
End Function
<WorkItem(957450, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/957450")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function KeywordsForIntrinsicsDeduplicated() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Imports System
Class G
Sub Goo()
$$
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
' Should only have one item called 'Double' and it should have a keyword glyph
Dim doubleItem = state.GetCompletionItems().Single(Function(c) c.DisplayText = "Double")
Assert.True(doubleItem.Tags.Contains(WellKnownTags.Keyword))
End Using
End Function
<WorkItem(957450, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/957450")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function KeywordDeduplicationLeavesEscapedIdentifiers() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Imports System
Class [Double]
Sub Goo()
Dim x as $$
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
' We should have gotten the item corresponding to [Double] and the item for the Double keyword
Dim doubleItems = state.GetCompletionItems().Where(Function(c) c.DisplayText = "Double")
Assert.Equal(2, doubleItems.Count())
Assert.True(doubleItems.Any(Function(c) c.Tags.Contains(WellKnownTags.Keyword)))
Assert.True(doubleItems.Any(Function(c) c.Tags.Contains(WellKnownTags.Class) AndAlso c.Tags.Contains(WellKnownTags.Internal)))
End Using
End Function
<WorkItem(957450, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/957450")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestEscapedItemCommittedWithCloseBracket() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Imports System
Class [Interface]
Sub Goo()
Dim x As $$
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("Interf]")
state.AssertMatchesTextStartingAtLine(4, "Dim x As [Interface]")
End Using
End Function
<WorkItem(1075298, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1075298")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Sub CommitOnQuestionMarkForConditionalAccess()
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Imports System
Class G
Sub Goo()
Dim x = String.$$
End Sub
End Class
]]></Document>)
state.SendTypeChars("emp?")
state.AssertMatchesTextStartingAtLine(4, "Dim x = String.Empty?")
End Using
End Sub
<WorkItem(1659, "https://github.com/dotnet/roslyn/issues/1659")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function DismissOnSelectAllCommand() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
Sub goo()
$$]]></Document>)
' Note: the caret is at the file, so the Select All command's movement
' of the caret to the end of the selection isn't responsible for
' dismissing the session.
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendSelectAll()
Await state.AssertNoCompletionSession()
End Using
End Function
<WorkItem(3088, "https://github.com/dotnet/roslyn/issues/3088")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function DoNotPreferParameterNames() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Module Program
Sub Main(args As String())
Dim Table As Integer
goo(table$$)
End Sub
Sub goo(table As String)
End Sub
End Module]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertSelectedCompletionItem("Table")
End Using
End Function
<WorkItem(4892, "https://github.com/dotnet/roslyn/issues/4892")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function BooleanPreselection1() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Module Program
Sub Main(args As String())
Dim x as boolean = $$
End Sub
End Module]]></Document>)
state.SendTypeChars("f")
Await state.AssertSelectedCompletionItem("False")
state.SendBackspace()
state.SendTypeChars("t")
Await state.AssertSelectedCompletionItem("True")
End Using
End Function
<WorkItem(4892, "https://github.com/dotnet/roslyn/issues/4892")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function BooleanPreselection2() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Module Program
Sub Main(args As String())
foot($$
End Sub
Sub foot(x as boolean)
End Sub
End Module]]></Document>)
state.SendTypeChars("f")
Await state.AssertSelectedCompletionItem("False")
state.SendBackspace()
state.SendTypeChars("t")
Await state.AssertSelectedCompletionItem("True")
End Using
End Function
<WorkItem(4892, "https://github.com/dotnet/roslyn/issues/4892")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function BooleanPreselection3() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Module Program
Class F
End Class
Class T
End Class
Sub Main(args As String())
$$
End Sub
End Module]]></Document>)
state.SendTypeChars("f")
Await state.AssertSelectedCompletionItem("F")
state.SendBackspace()
state.SendTypeChars("t")
Await state.AssertSelectedCompletionItem("T")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TargetTypePreselection1() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Imports System.Threading
Module Program
Sub Cancel(x As Integer, cancellationToken As CancellationToken)
Cancel(x + 1, $$)
End Sub
End Module]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertSelectedCompletionItem("cancellationToken").ConfigureAwait(True)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TargetTypePreselection2() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Module Program
Sub Main(args As String())
Dim aaz As Integer
args = $$
End Sub
End Module]]></Document>)
state.SendTypeChars("a")
Await state.AssertSelectedCompletionItem("args").ConfigureAwait(True)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TargetTypePreselection3() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class D
End Class
Class Program
Sub Main(string() args)
Dim cw = 7
Dim cx as D = new D()
Dim cx2 as D = $$
End Sub
End Class
]]></Document>)
state.SendTypeChars("c")
Await state.AssertSelectedCompletionItem("cx", isHardSelected:=True).ConfigureAwait(True)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TargetTypePreselectionLocalsOverType() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class A
End Class
Class Program
Sub Main(string() args)
Dim cx = new A()
Dim cx2 as A = $$
End Sub
End Class
]]></Document>)
state.SendTypeChars("c")
Await state.AssertSelectedCompletionItem("cx", isHardSelected:=True).ConfigureAwait(True)
End Using
End Function
<WpfFact(Skip:="https://github.com/dotnet/roslyn/issues/6942"), Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TargetTypePreselectionConvertibility1() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Mustinherit Class C
End Class
Class D
inherits C
End Class
Class Program
Sub Main(string() args)
Dim cx = new D()
Dim cx2 as C = $$
End Sub
End Class
]]></Document>)
state.SendTypeChars("c")
Await state.AssertSelectedCompletionItem("cx", isHardSelected:=True).ConfigureAwait(True)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TargetTypePreselectionParamsArray() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class Program
Sub Main(string() args)
Dim azc as integer
M2(a$$
End Sub
Sub M2(params int() yx)
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertSelectedCompletionItem("azc", isHardSelected:=True).ConfigureAwait(True)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TargetTypePreselectionSetterValue() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class Program
Private Async As Integer
Public Property NewProperty() As Integer
Get
Return Async
End Get
Set(ByVal value As Integer)
Async = $$
End Set
End Property
End Class]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertSelectedCompletionItem("value", isHardSelected:=False, isSoftSelected:=True).ConfigureAwait(True)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(12530, "https://github.com/dotnet/roslyn/issues/12530")>
Public Async Function TestAnonymousTypeDescription() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Imports System.Linq
Public Class Class1
Sub Method()
Dim x = {New With {.x = 1}}.ToArr$$
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertSelectedCompletionItem(description:=
$"<{ VBFeaturesResources.Extension }> Function IEnumerable(Of 'a).ToArray() As 'a()
{ FeaturesResources.Anonymous_Types_colon }
'a { FeaturesResources.is_ } New With {{ .x As Integer }}")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(12530, "https://github.com/dotnet/roslyn/issues/12530")>
Public Async Function TestAnonymousTypeDescription2() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Imports System.Linq
Public Class Class1
Sub Method()
Dim x = {New With { Key .x = 1}}.ToArr$$
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertSelectedCompletionItem(description:=
$"<{ VBFeaturesResources.Extension }> Function IEnumerable(Of 'a).ToArray() As 'a()
{ FeaturesResources.Anonymous_Types_colon }
'a { FeaturesResources.is_ } New With {{ Key .x As Integer }}")
End Using
End Function
<WorkItem(11812, "https://github.com/dotnet/roslyn/issues/11812")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestObjectCreationQualifiedName() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class A
Sub Test()
Dim b As B.C(Of Integer) = New$$
End Sub
End Class
Namespace B
Class C(Of T)
End Class
End Namespace]]></Document>)
state.SendTypeChars(" ")
Await state.AssertCompletionSession()
state.SendTypeChars("(")
state.AssertMatchesTextStartingAtLine(3, "Dim b As B.C(Of Integer) = New B.C(Of Integer)(")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNonTrailingNamedArgumentInVB15_3() As Task
Using state = TestStateFactory.CreateTestStateFromWorkspace(
<Workspace>
<Project Language="Visual Basic" LanguageVersion="15.3" CommonReferences="true" AssemblyName="VBProj">
<Document FilePath="C.vb">
Class C
Sub M()
Dim better As Integer = 2
M(a:=1, $$)
End Sub
Sub M(a As Integer, bar As Integer, c As Integer)
End Sub
End Class
</Document>
</Project>
</Workspace>)
state.SendTypeChars("b")
Await state.AssertSelectedCompletionItem(displayText:="bar", displayTextSuffix:=":=", isHardSelected:=True)
state.SendTypeChars("e")
Await state.AssertNoCompletionSession()
End Using
End Function
<WpfFact>
Public Async Function TestNonTrailingNamedArgumentInVB15_5() As Task
Using state = TestStateFactory.CreateTestStateFromWorkspace(
<Workspace>
<Project Language="Visual Basic" LanguageVersion="15.5" CommonReferences="true" AssemblyName="VBProj">
<Document FilePath="C.vb">
Class C
Sub M()
Dim better As Integer = 2
M(a:=1, $$)
End Sub
Sub M(a As Integer, bar As Integer, c As Integer)
End Sub
End Class
</Document>
</Project>
</Workspace>)
state.SendTypeChars("bar")
Await state.AssertSelectedCompletionItem(displayText:="bar", displayTextSuffix:=":=", isHardSelected:=True)
state.SendBackspace()
state.SendBackspace()
state.SendTypeChars("et")
Await state.AssertSelectedCompletionItem(displayText:="better", isHardSelected:=True)
state.SendTypeChars(", ")
Assert.Contains("M(a:=1, better,", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestSymbolInTupleLiteral() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
Public Sub Goo()
Dim t = ($$)
End Sub
End Class
}]]></Document>)
state.SendTypeChars("Go")
Await state.AssertSelectedCompletionItem(displayText:="Goo", isHardSelected:=True)
state.SendTypeChars(":")
Assert.Contains("(Go:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestSymbolInTupleLiteralAfterComma() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
Public Sub Goo()
Dim t = (1, $$)
End Sub
End Class
]]></Document>)
state.SendTypeChars("Go")
Await state.AssertSelectedCompletionItem(displayText:="Goo", isHardSelected:=True)
state.SendTypeChars(":")
Assert.Contains("(1, Go:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestSnippetInTupleLiteral() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
Public Sub Goo()
Dim t = ($$)
End Sub
End Class
}]]></Document>,
extraExportedTypes:={GetType(MockSnippetInfoService), GetType(SnippetCompletionProvider), GetType(StubVsEditorAdaptersFactoryService)}.ToList())
Dim workspace = state.Workspace
workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _
.WithChangedOption(CompletionOptions.SnippetsBehavior, LanguageNames.VisualBasic, SnippetsRule.AlwaysInclude)))
state.SendTypeChars("Shortcu")
Await state.AssertSelectedCompletionItem(displayText:="Shortcut", isHardSelected:=True)
state.SendTypeChars(":")
Assert.Contains("(Shortcu:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestSnippetInTupleLiteralAfterComma() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
Public Sub Goo()
Dim t = (1, $$)
End Sub
End Class
}]]></Document>,
extraExportedTypes:={GetType(MockSnippetInfoService), GetType(SnippetCompletionProvider), GetType(StubVsEditorAdaptersFactoryService)}.ToList())
Dim workspace = state.Workspace
workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _
.WithChangedOption(CompletionOptions.SnippetsBehavior, LanguageNames.VisualBasic, SnippetsRule.AlwaysInclude)))
state.SendTypeChars("Shortcu")
Await state.AssertSelectedCompletionItem(displayText:="Shortcut", isHardSelected:=True)
state.SendTypeChars(":")
Assert.Contains("(1, Shortcu:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestSnippetsNotExclusiveWhenAlwaysShowing() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
Public Sub Goo()
Dim x as Integer = 3
Dim t = $$
End Sub
End Class
}]]></Document>,
extraExportedTypes:={GetType(MockSnippetInfoService), GetType(SnippetCompletionProvider), GetType(StubVsEditorAdaptersFactoryService)}.ToList())
Dim workspace = state.Workspace
workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _
.WithChangedOption(CompletionOptions.SnippetsBehavior, LanguageNames.VisualBasic, SnippetsRule.AlwaysInclude)))
state.SendInvokeCompletionList()
Await state.AssertCompletionItemsContainAll("x", "Shortcut")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestBuiltInTypesKeywordInTupleLiteral() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
Public Sub Goo()
Dim t = ($$)
End Sub
End Class
}]]></Document>)
state.SendTypeChars("Intege")
Await state.AssertSelectedCompletionItem(displayText:="Integer", isHardSelected:=True)
state.SendTypeChars(":")
Assert.Contains("(Intege:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestBuiltInTypesKeywordInTupleLiteralAfterComma() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
Public Sub Goo()
Dim t = (1, $$)
End Sub
End Class
}]]></Document>)
state.SendTypeChars("Intege")
Await state.AssertSelectedCompletionItem(displayText:="Integer", isHardSelected:=True)
state.SendTypeChars(":")
Assert.Contains("(1, Intege:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestFunctionKeywordInTupleLiteral() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
Public Sub Goo()
Dim t = ($$)
End Sub
End Class
}]]></Document>)
state.SendTypeChars("Functio")
Await state.AssertSelectedCompletionItem(displayText:="Function", isHardSelected:=True)
state.SendTypeChars(":")
Assert.Contains("(Functio:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestFunctionKeywordInTupleLiteralAfterComma() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
Public Sub Goo()
Dim t = (1, $$)
End Sub
End Class
}]]></Document>)
state.SendTypeChars("Functio")
Await state.AssertSelectedCompletionItem(displayText:="Function", isHardSelected:=True)
state.SendTypeChars(":")
Assert.Contains("(1, Functio:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestSymbolInTupleType() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
Public Sub Goo()
Dim t As ($$)
End Sub
End Class
]]></Document>)
state.SendTypeChars("Integ")
Await state.AssertSelectedCompletionItem(displayText:="Integer", isHardSelected:=True)
state.SendTypeChars(",")
Assert.Contains("(Integer,", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestInvocationExpression() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
Public Sub Goo(Alice As Integer)
Goo($$)
End Sub
End Class
]]></Document>)
state.SendTypeChars("Alic")
Await state.AssertSelectedCompletionItem(displayText:="Alice", isHardSelected:=True)
state.SendTypeChars(":")
Assert.Contains("Goo(Alice:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestInvocationExpressionAfterComma() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
Public Sub Goo(Alice As Integer, Bob As Integer)
Goo(1, $$)
End Sub
End Class
]]></Document>)
state.SendTypeChars("B")
Await state.AssertSelectedCompletionItem(displayText:="Bob", isHardSelected:=True)
state.SendTypeChars(":")
Assert.Contains("Goo(1, Bob:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WorkItem(13161, "https://github.com/dotnet/roslyn/issues/13161")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Sub CommitGenericDoesNotInsertEllipsis()
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Interface Goo(Of T)
End Interface
Class Bar
Implements $$
End Class]]></Document>)
Dim unicodeEllipsis = ChrW(&H2026).ToString()
state.SendTypeChars("Goo")
state.SendTab()
Assert.Equal("Implements Goo(Of", state.GetLineTextFromCaretPosition().Trim())
Assert.DoesNotContain(unicodeEllipsis, state.GetLineTextFromCaretPosition())
End Using
End Sub
<WorkItem(13161, "https://github.com/dotnet/roslyn/issues/13161")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Sub CommitGenericDoesNotInsertEllipsisCommitOnParen()
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Interface Goo(Of T)
End Interface
Class Bar
Implements $$
End Class]]></Document>)
Dim unicodeEllipsis = ChrW(&H2026).ToString()
state.SendTypeChars("Goo(")
Assert.Equal("Implements Goo(", state.GetLineTextFromCaretPosition().Trim())
Assert.DoesNotContain(unicodeEllipsis, state.GetLineTextFromCaretPosition())
End Using
End Sub
<WorkItem(13161, "https://github.com/dotnet/roslyn/issues/13161")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Sub CommitGenericItemDoesNotInsertEllipsisCommitOnTab()
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Interface Goo(Of T)
End Interface
Class Bar
Dim x as $$
End Class]]></Document>)
Dim unicodeEllipsis = ChrW(&H2026).ToString()
state.SendTypeChars("Goo")
state.SendTab()
Assert.Equal("Dim x as Goo(Of", state.GetLineTextFromCaretPosition().Trim())
Assert.DoesNotContain(unicodeEllipsis, state.GetLineTextFromCaretPosition())
End Using
End Sub
<WorkItem(15011, "https://github.com/dotnet/roslyn/issues/15011")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function SymbolAndObjectPreselectionUnification() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Module Module1
Sub Main()
Dim x As ProcessStartInfo = New $$
End Sub
End Module
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
Dim psi = state.GetCompletionItems().Where(Function(i) i.DisplayText.Contains("ProcessStartInfo")).ToArray()
Assert.Equal(1, psi.Length)
End Using
End Function
<WorkItem(394863, "https://devdiv.visualstudio.com/DevDiv/_workitems?_a=edit&id=394863&triage=true")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function ImplementsClause() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Partial Class TestClass
Implements IComparable(Of TestClass)
Public Function CompareTo(other As TestClass) As Integer Implements I$$
End Function
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTab()
Assert.Contains("IComparable(Of TestClass)", state.GetLineTextFromCaretPosition())
End Using
End Function
<WorkItem(18785, "https://github.com/dotnet/roslyn/issues/18785")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function BackspaceSoftSelectionIfNotPrefixMatch() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
Sub Do()
Dim x = new System.Collections.Generic.List(Of String)()
x.$$Add("stuff")
End Sub
End Class
]]></Document>)
state.SendBackspace()
Await state.AssertSelectedCompletionItem("x", isSoftSelected:=True)
state.SendTypeChars(".")
Assert.Contains("x.Add", state.GetLineTextFromCaretPosition())
End Using
End Function
<WorkItem(28767, "https://github.com/dotnet/roslyn/issues/28767")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CompletionDoesNotRemoveBracketsOnEnum() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>
Class C
Sub S
[$$]
End Sub
End Class
</Document>)
Await state.AssertNoCompletionSession()
state.SendTypeChars("Enu")
Await state.AssertSelectedCompletionItem(displayText:="Enum", isHardSelected:=True)
state.SendTab()
Assert.Contains("[Enum]", state.GetDocumentText(), StringComparison.Ordinal)
End Using
End Function
<WorkItem(30097, "https://github.com/dotnet/roslyn/issues/30097")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestMRUKeepsTwoRecentlyUsedItems() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>
Class C
Public Sub Ma(m As Double)
End Sub
Public Sub Test()
$$
End Sub
End Class
</Document>)
state.SendTypeChars("M(M(M(M(")
Await state.AssertCompletionSession()
Assert.Equal(" Ma(m:=(Ma(m:=(", state.GetLineTextFromCaretPosition())
End Using
End Function
<WorkItem(36546, "https://github.com/dotnet/roslyn/issues/36546")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestDoNotDismissIfEmptyOnBackspaceIfStartedWithBackspace() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>
Imports System
Class C
Public Sub M()
Console.W$$
End Sub
End Class
</Document>)
state.SendBackspace()
Await state.AssertCompletionItemsContainAll("WriteLine")
End Using
End Function
<WorkItem(36546, "https://github.com/dotnet/roslyn/issues/36546")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestDoNotDismissIfEmptyOnMultipleBackspaceIfStartedInvoke() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document>
Imports System
Class C
Public Sub M()
Console.Wr$$
End Sub
End Class
</Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendBackspace()
state.SendBackspace()
Await state.AssertCompletionSession()
End Using
End Function
<WorkItem(588, "https://github.com/dotnet/roslyn/issues/588")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestMatchWithTurkishIWorkaround1() As Task
Using New CultureContext(New Globalization.CultureInfo("tr-TR", useUserOverride:=False))
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
Sub goo(x As Integer)
String.$$
]]></Document>)
state.SendTypeChars("is")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem("IsInterned")
End Using
End Using
End Function
<WorkItem(588, "https://github.com/dotnet/roslyn/issues/588")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestMatchWithTurkishIWorkaround2() As Task
Using New CultureContext(New Globalization.CultureInfo("tr-TR", useUserOverride:=False))
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
Sub goo(x As Integer)
String.$$]]></Document>)
state.SendTypeChars("ı")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem()
End Using
End Using
End Function
<WorkItem(29938, "https://github.com/dotnet/roslyn/issues/29938")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestMatchWithTurkishIWorkaround3() As Task
Using New CultureContext(New Globalization.CultureInfo("tr-TR", useUserOverride:=False))
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class TARIFE
End Class
Class C
Sub goo(x As Integer)
Dim t As $$
]]></Document>)
state.SendTypeChars("tarif")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem("TARIFE")
End Using
End Using
End Function
<WorkItem(29938, "https://github.com/dotnet/roslyn/issues/29938")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestMatchWithTurkishIWorkaround4() As Task
Using New CultureContext(New Globalization.CultureInfo("tr-TR", useUserOverride:=False))
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class IFADE
End Class
Class ifTest
End Class
Class C
Sub goo(x As Integer)
Dim ifade As IFADE
$$]]></Document>)
state.SendTypeChars("if")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem("If")
End Using
End Using
End Function
<WorkItem(29938, "https://github.com/dotnet/roslyn/issues/29938")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestMatchWithTurkishIWorkaround5() As Task
Using New CultureContext(New Globalization.CultureInfo("tr-TR", useUserOverride:=False))
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class İFADE
End Class
Class ifTest
End Class
Class C
Sub goo(x As Integer)
Dim ifade As İFADE
$$
]]></Document>)
state.SendTypeChars("if")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem("If")
End Using
End Using
End Function
<WorkItem(29938, "https://github.com/dotnet/roslyn/issues/29938")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestMatchWithTurkishIWorkaround6() As Task
Using New CultureContext(New Globalization.CultureInfo("tr-TR", useUserOverride:=False))
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class TARİFE
End Class
Class C
Sub goo(x As Integer)
Dim obj As $$
]]></Document>)
state.SendTypeChars("tarif")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem("TARİFE")
End Using
End Using
End Function
<WorkItem(29938, "https://github.com/dotnet/roslyn/issues/29938")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestMatchWithTurkishIWorkaround7() As Task
Using New CultureContext(New Globalization.CultureInfo("tr-TR", useUserOverride:=False))
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class İFADE
End Class
Class ifTest
End Class
Class C
Sub goo(x As Integer)
Dim obj As $$
]]></Document>)
state.SendTypeChars("ifad")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem("İFADE")
End Using
End Using
End Function
<WorkItem(29938, "https://github.com/dotnet/roslyn/issues/29938")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestMatchWithTurkishIWorkaround8() As Task
Using New CultureContext(New Globalization.CultureInfo("tr-TR", useUserOverride:=False))
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class IFADE
End Class
Class ifTest
End Class
Class C
Sub goo(x As Integer)
Dim obj As $$
]]></Document>)
state.SendTypeChars("ifad")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem("IFADE")
End Using
End Using
End Function
<WorkItem(29938, "https://github.com/dotnet/roslyn/issues/29938")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestMatchWithTurkishIWorkaround9() As Task
Using New CultureContext(New Globalization.CultureInfo("tr-TR", useUserOverride:=False))
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class IFADE
End Class
Class ifTest
End Class
Class C
Sub goo(x As Integer)
Dim ifade_ As İFADE
$$]]></Document>)
state.SendTypeChars("IF")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem("If")
End Using
End Using
End Function
<WorkItem(29938, "https://github.com/dotnet/roslyn/issues/29938")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestMatchWithTurkishIWorkaround10() As Task
Using New CultureContext(New Globalization.CultureInfo("tr-TR", useUserOverride:=False))
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class İFADE
End Class
Class ifTest
End Class
Class C
Sub goo(x As Integer)
Dim ifade As İFADE
$$
]]></Document>)
state.SendTypeChars("IF")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem("If")
End Using
End Using
End Function
<WpfTheory, CombinatorialData>
<Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CompletionInPreprocessorIf(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateTestStateFromWorkspace(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true" PreprocessorSymbols="Goo=1,Bar=2,Baz=3">
<Document>
#if $$
</Document>
</Project>
</Workspace>,
showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendInvokeCompletionList()
Await state.AssertCompletionItemsContainAll({"Goo", "Bar", "Baz", "True", "False"})
state.SendTypeChars("Go")
state.SendTab()
Await state.AssertNoCompletionSession()
Assert.Contains("#if Goo", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfTheory, CombinatorialData>
<Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CompletionInPreprocessorElseIf(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateTestStateFromWorkspace(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true" PreprocessorSymbols="Goo=1,Bar=2,Baz=3">
<Document>
#if false
#elseif $$
</Document>
</Project>
</Workspace>,
showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendInvokeCompletionList()
Await state.AssertCompletionItemsContainAll({"Goo", "Bar", "Baz", "True", "False"})
state.SendTypeChars("Go")
state.SendTab()
Await state.AssertNoCompletionSession()
Assert.Contains("#elseif Goo", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfTheory, CombinatorialData>
<Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CompletionNotInPreprocessorElse(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateTestStateFromWorkspace(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true" PreprocessorSymbols="Goo=1,Bar=2,Baz=3">
<Document>
#if false
#elseif false
#else $$
</Document>
</Project>
</Workspace>,
showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendInvokeCompletionList()
Await state.AssertNoCompletionSession()
End Using
End Function
<WpfTheory, CombinatorialData>
<Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CompletionInPreprocessorParenthesized(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateTestStateFromWorkspace(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true" PreprocessorSymbols="Goo=1,Bar=2,Baz=3">
<Document>
#if ($$
</Document>
</Project>
</Workspace>,
showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendInvokeCompletionList()
Await state.AssertCompletionItemsContainAll({"Goo", "Bar", "Baz", "True", "False"})
state.SendTypeChars("Go")
state.SendTab()
Await state.AssertNoCompletionSession()
Assert.Contains("#if (Goo", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfTheory, CombinatorialData>
<Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CompletionInPreprocessorNot(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateTestStateFromWorkspace(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true" PreprocessorSymbols="Goo=1,Bar=2,Baz=3">
<Document>
#if not $$
</Document>
</Project>
</Workspace>,
showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendInvokeCompletionList()
Await state.AssertCompletionItemsContainAll({"Goo", "Bar", "Baz", "True", "False"})
state.SendTypeChars("Go")
state.SendTab()
Await state.AssertNoCompletionSession()
Assert.Contains("#if not Goo", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfTheory, CombinatorialData>
<Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CompletionInPreprocessorAnd(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateTestStateFromWorkspace(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true" PreprocessorSymbols="Goo=1,Bar=2,Baz=3">
<Document>
#if true and $$
</Document>
</Project>
</Workspace>,
showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendInvokeCompletionList()
Await state.AssertCompletionItemsContainAll({"Goo", "Bar", "Baz", "True", "False"})
state.SendTypeChars("Go")
state.SendTab()
Await state.AssertNoCompletionSession()
Assert.Contains("#if true and Goo", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfTheory, CombinatorialData>
<Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CompletionInPreprocessorAndAlso(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateTestStateFromWorkspace(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true" PreprocessorSymbols="Goo=1,Bar=2,Baz=3">
<Document>
#if true andalso $$
</Document>
</Project>
</Workspace>,
showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendInvokeCompletionList()
Await state.AssertCompletionItemsContainAll({"Goo", "Bar", "Baz", "True", "False"})
state.SendTypeChars("Go")
state.SendTab()
Await state.AssertNoCompletionSession()
Assert.Contains("#if true andalso Goo", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfTheory, CombinatorialData>
<Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CompletionInPreprocessorOr(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateTestStateFromWorkspace(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true" PreprocessorSymbols="Goo=1,Bar=2,Baz=3">
<Document>
#if true or $$
</Document>
</Project>
</Workspace>,
showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendInvokeCompletionList()
Await state.AssertCompletionItemsContainAll({"Goo", "Bar", "Baz", "True", "False"})
state.SendTypeChars("Go")
state.SendTab()
Await state.AssertNoCompletionSession()
Assert.Contains("#if true or Goo", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfTheory, CombinatorialData>
<Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CompletionInPreprocessorOrElse(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateTestStateFromWorkspace(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true" PreprocessorSymbols="Goo=1,Bar=2,Baz=3">
<Document>
#if true orelse $$
</Document>
</Project>
</Workspace>,
showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendInvokeCompletionList()
Await state.AssertCompletionItemsContainAll({"Goo", "Bar", "Baz", "True", "False"})
state.SendTypeChars("Go")
state.SendTab()
Await state.AssertNoCompletionSession()
Assert.Contains("#if true orelse Goo", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfTheory, CombinatorialData>
<Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CompletionInPreprocessorCasingDifference(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateTestStateFromWorkspace(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true" PreprocessorSymbols="Goo=1,Bar=2,BAR=2,Baz=3">
<Document>
#if $$
</Document>
</Project>
</Workspace>,
showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendInvokeCompletionList()
Await state.AssertCompletionItemsContainAll({"Goo", "Bar", "Baz", "True", "False"})
state.SendTypeChars("Go")
state.SendTab()
Await state.AssertNoCompletionSession()
Assert.Contains("#if Goo", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<ExportLanguageService(GetType(ISnippetInfoService), LanguageNames.VisualBasic, ServiceLayer.Test), [Shared], PartNotDiscoverable>
Friend Class MockSnippetInfoService
Implements ISnippetInfoService
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Public Function GetSnippetsAsync_NonBlocking() As IEnumerable(Of SnippetInfo) Implements ISnippetInfoService.GetSnippetsIfAvailable
Return SpecializedCollections.SingletonEnumerable(New SnippetInfo("Shortcut", "Title", "Description", "Path"))
End Function
Public Function ShouldFormatSnippet(snippetInfo As SnippetInfo) As Boolean Implements ISnippetInfoService.ShouldFormatSnippet
Return False
End Function
Public Function SnippetShortcutExists_NonBlocking(shortcut As String) As Boolean Implements ISnippetInfoService.SnippetShortcutExists_NonBlocking
Return shortcut = "Shortcut"
End Function
End Class
End Class
End Namespace
|
ErikSchierboom/roslyn
|
src/EditorFeatures/Test2/IntelliSense/VisualBasicCompletionCommandHandlerTests.vb
|
Visual Basic
|
apache-2.0
| 141,466
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Statements
Public Class CaseKeywordRecommenderTests
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function CaseAfterSelectTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>Select |</MethodBody>, "Case")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function NoCaseAfterQuerySelectTest() As Task
Await VerifyRecommendationsMissingAsync(<MethodBody>Dim q = From x in "abc" Select |</MethodBody>, "Case")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function NoCaseElseAfterQuerySelectTest() As Task
Await VerifyRecommendationsMissingAsync(<MethodBody>Dim q = From x in "abc" Select |</MethodBody>, "Case Else")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function CaseNotByItselfTest() As Task
Await VerifyRecommendationsMissingAsync(<MethodBody>|</MethodBody>, "Case")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function CaseInSelectBlockTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>
Select Case foo
|
End Select</MethodBody>, "Case")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function CaseElseInSelectBlockTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>
Select Case foo
|
End Select</MethodBody>, "Case Else")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function CaseElseNotInSelectBlockThatAlreadyHasCaseElseTest() As Task
Await VerifyRecommendationsMissingAsync(<MethodBody>
Select Case foo
Case Else
|
End Select</MethodBody>, "Case Else")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function CaseElseNotInSelectBlockIfBeforeCaseTest() As Task
Await VerifyRecommendationsMissingAsync(<MethodBody>
Select Case foo
|
Case
End Select</MethodBody>, "Case Else")
End Function
<Fact>
<WorkItem(543384, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543384")>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function NoCaseInSelectBlockIfAfterCaseElseTest() As Task
Await VerifyRecommendationsMissingAsync(<MethodBody>
Select Case foo
Case Else
Dim i = 3
|
End Select</MethodBody>, "Case")
End Function
<Fact>
<WorkItem(543384, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543384")>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function CaseInSelectBlockBeforeCaseElseTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>
Select Case foo
|
Case Else
Dim i = 3
End Select</MethodBody>, "Case")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function NoCaseIsInSelectBlockTest() As Task
Await VerifyRecommendationsMissingAsync(<MethodBody>
Select Case foo
|
End Select</MethodBody>, "Case Is")
End Function
End Class
End Namespace
|
Pvlerick/roslyn
|
src/EditorFeatures/VisualBasicTest/Recommendations/Statements/CaseKeywordRecommenderTests.vb
|
Visual Basic
|
apache-2.0
| 3,792
|
Namespace Security.SystemOptions_Applications
Public Class ApplicationDrivers
Inherits SecurityItemBase
Public Sub New()
_ConceptItemName = "Application Drivers"
_ConceptName = "System Options_Applications"
_Description = "Allow access to 'Application Driver's Tab"
_IsEnterprise = True
_IsSmallBusiness = True
_IsViewer = False
_IsWeb = False
_IsWebPlus = False
End Sub
End Class
End Namespace
|
nublet/DMS
|
DMS.Forms.Shared/Security/Items/SystemOptions/Applications/ApplicationDrivers.vb
|
Visual Basic
|
mit
| 532
|
Imports System
Imports Aspose.Cells
Imports Aspose.Cells.Drawing
Namespace Articles
Public Class ShadowEffectOfShape
Public Shared Sub Run()
' ExStart:ShadowEffectOfShape
' The path to the documents directory.
Dim dataDir As String = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
' Load your source excel file
Dim wb As New Workbook(dataDir & Convert.ToString("sample.xlsx"))
' Access first worksheet
Dim ws As Worksheet = wb.Worksheets(0)
' Access first shape
Dim sh As Shape = ws.Shapes(0)
' Set the shadow effect of the shape, Set its Angle, Blur, Distance and Transparency properties
Dim se As ShadowEffect = sh.ShadowEffect
se.Angle = 150
se.Blur = 4
se.Distance = 45
se.Transparency = 0.3
' Save the workbook in xlsx format
wb.Save(dataDir & Convert.ToString("output_out.xlsx"))
' ExEnd:ShadowEffectOfShape
End Sub
End Class
End Namespace
|
maria-shahid-aspose/Aspose.Cells-for-.NET
|
Examples/VisualBasic/Articles/ShadowEffectOfShape.vb
|
Visual Basic
|
mit
| 1,133
|
Imports System
Imports System.Collections.Specialized
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Namespace Authentication
Public Class Status
Implements System.Web.IHttpHandler
#Region " IHttpHandler Implementation "
Public ReadOnly Property IsReusable() As Boolean _
Implements System.Web.IHttpHandler.IsReusable
Get
Return True
End Get
End Property
Public Sub ProcessRequest( _
ByVal context As System.Web.HttpContext _
) Implements System.Web.IHttpHandler.ProcessRequest
Dim SV = New Hermes.Authentication.Server()
Dim auth_Builder As New System.Text.StringBuilder()
auth_Builder.AppendLine("<div>")
If SV.Authenticated Then
auth_Builder.AppendLine(String.Format("<h3>{0}</h3>", "Hermes Authenticated"))
auth_Builder.AppendLine("<ul>")
auth_Builder.AppendLine(String.Format("<li>{0}: {1}</li>", "Username", SV.Username))
auth_Builder.AppendLine(String.Format("<li>{0}: {1}</li>", "Details", SV.Details))
auth_Builder.AppendLine(String.Format("<li>{0}: {1}</li>", "Expires", SV.Expires.ToString()))
auth_Builder.AppendLine(String.Format("<li>{0}: {1}</li>", "Email", SV.Email_Address))
Dim role_Index As Integer = 0
For Each role As String In SV.Roles
role_Index += 1
auth_Builder.AppendLine(String.Format("<li>Role {0}: {1}</li>", role_Index, role))
Next
auth_Builder.AppendLine("</ul>")
Else
auth_Builder.AppendLine(String.Format("<h3>{0}</h3>", "Hermes NOT Authenticated"))
End If
auth_Builder.AppendLine("</div>")
context.Response.Write(auth_Builder.ToString())
For i As Integer = 0 To context.Request.Cookies.Count - 1
Dim cookie_Builder As New System.Text.StringBuilder()
cookie_Builder.AppendLine("<div>")
cookie_Builder.AppendLine(String.Format("<h3>{0}</h3>", context.Request.Cookies(i).Name))
cookie_Builder.AppendLine("<ul>")
cookie_Builder.AppendLine(String.Format("<li>{0}: {1}</li>", "Domain", context.Request.Cookies(i).Domain))
cookie_Builder.AppendLine(String.Format("<li>{0}: {1}</li>", "Path", context.Request.Cookies(i).Path))
cookie_Builder.AppendLine(String.Format("<li>{0}: {1}</li>", "Expires", context.Request.Cookies(i).Expires))
cookie_Builder.AppendLine(String.Format("<li>{0}: {1}</li>", "Secure", context.Request.Cookies(i).Secure))
cookie_Builder.AppendLine(String.Format("<li>{0}: {1}</li>", "HttpOnly", context.Request.Cookies(i).HttpOnly))
cookie_Builder.AppendLine(String.Format("<li>{0}: {1}</li>", "HasKeys", context.Request.Cookies(i).HasKeys))
cookie_Builder.AppendLine(String.Format("<li>{0}: {1}</li>", "Value", context.Request.Cookies(i).Value))
If context.Request.Cookies(i).HasKeys AndAlso Not context.Request.Cookies(i).Values Is Nothing AndAlso context.Request.Cookies(i).Values.Count > 0 Then
cookie_Builder.AppendLine("<li>")
cookie_Builder.AppendLine(String.Format("<h3>{0}</h3>", "Values"))
cookie_Builder.AppendLine("<ul>")
Dim cookie_Values As New NameValueCollection(context.Request.Cookies(i).Values)
For Each name As String In cookie_Values.AllKeys
Dim values As String() = cookie_Values.GetValues(name)
For k As Integer = 0 To values.Length - 1
cookie_Builder.AppendLine(String.Format("<li>{0} [Value {1}]: {2}</li>", name, (k + 1), values(k)))
Next
Next
cookie_Builder.AppendLine("</ul>")
cookie_Builder.AppendLine("</li>")
End If
cookie_Builder.AppendLine("</ul>")
cookie_Builder.AppendLine("</div>")
context.Response.Write(cookie_Builder.ToString())
Next
context.Response.Flush
context.Response.End
End Sub
#End Region
End Class
End Namespace
|
thiscouldbejd/Hermes
|
_Authentication/Partials/Status.vb
|
Visual Basic
|
mit
| 3,792
|
Imports Microsoft.VisualBasic
Imports System.IO
Imports Aspose.Cells
Namespace Articles
Public Class MoveRangeOfCells
Public Shared Sub Run()
' ExStart:1
' The path to the documents directory.
Dim dataDir As String = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
' Instantiate the workbook object
' Open the Excel file
Dim workbook As New Workbook(dataDir & "book1.xls")
Dim cells As Global.Aspose.Cells.Cells = workbook.Worksheets(0).Cells
' Create Cell' S area
Dim ca As New CellArea()
ca.StartColumn = 0
ca.EndColumn = 1
ca.StartRow = 0
ca.EndRow = 4
' Move Range
cells.MoveRange(ca, 0, 2)
' Save the resultant file
workbook.Save(dataDir & "output.xls")
' ExEnd:1
End Sub
End Class
End Namespace
|
maria-shahid-aspose/Aspose.Cells-for-.NET
|
Examples/VisualBasic/Articles/MoveRangeOfCells.vb
|
Visual Basic
|
mit
| 984
|
Imports System.IO
Imports System.Net
Imports System.Net.NetworkInformation
Imports System.Text
Imports Newtonsoft.Json.Linq
Public Class loadman
Public Loggedin As Boolean = False
Dim checkstat As Boolean = False
Dim something As Integer = 0
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
If Loggedin = True Then
If Environment.CommandLine.Contains("hidden") Then
Log("Background Mode GUI Load Up")
NotifyIcon1.Visible = True
Me.Hide()
Timer1.Stop()
If Environment.CommandLine.Contains("lostnet") Then
Log("Starting Background Network Monitor")
Dim recheckaccess1 As New Threading.Thread(AddressOf RecheckAccess)
recheckaccess1.IsBackground = True
recheckaccess1.SetApartmentState(Threading.ApartmentState.STA)
recheckaccess1.Start()
End If
Else
Log("Normal Mode GUI Load Up")
Dim newman As New Form1
newman.Show()
Me.Close()
Timer1.Stop()
End If
End If
If openlogin = True Then
openlogin = False
Dim logina As New login
logina.Show()
End If
If My.Application.OpenForms.OfType(Of login).Count = 0 And something > 20 Then
Application.Restart()
ElseIf My.Application.OpenForms.OfType(Of login).Count = 1 Then
Else
something += 1
End If
End Sub
Private Sub wait(ByVal interval As Integer)
Dim sw As New Stopwatch
sw.Start()
Do While sw.ElapsedMilliseconds < interval
Application.DoEvents()
Loop
sw.Stop()
End Sub
Private Sub Browser_NewWindow(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles browser.NewWindow
e.Cancel = True
End Sub
Private WithEvents browser As WebBrowser
Dim openlogin As Boolean = False
Dim openmain As Boolean = False
Public Shared Function GetUnixTimestamp() As Double
Dim val = (DateTime.Now - New DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds
Dim rep As String = Math.Round(val, 3)
rep = rep.Replace(".", "")
Return rep
End Function
Private Sub CheckLogin(username As String, password As String, secondary As Boolean)
SetProgress(10, MetroProgressBar1)
browser = New WebBrowser
browser.ScriptErrorsSuppressed = True
browser.Navigate("http://172.16.0.30:8090/httpclient.html")
SetProgress(30, MetroProgressBar1)
Dim counterman As Integer = 0
abc:
If browser.ReadyState = WebBrowserReadyState.Complete Then
Try
SetProgress(40, MetroProgressBar1)
browser.Document.GetElementById("username").SetAttribute("value", username)
browser.Document.GetElementById("password").SetAttribute("value", password)
browser.Document.GetElementById("btnSubmit").InvokeMember("click")
wait(500)
SetProgress(50, MetroProgressBar1)
Catch ex As Exception
If Environment.CommandLine.Contains("lostnet") Then
Log("Unable to connect. Switching to Standby Mode")
Me.Hide()
Timer1.Stop()
Timer2.Stop()
Log("See you in " & 60 * 1000 * 2 & " milliseconds")
For i As Integer = 0 To 120
Threading.Thread.Sleep(1000)
Next
Denotify()
Process.Start(Application.ExecutablePath, "-hidden -lostnet")
End
Else
Log("Cannot Connect to Cyberoam")
MsgBox("Couldn't Connect to Cyberoam. Either Cyberoam is down or your not connected to a Cyberoam Network.", MsgBoxStyle.Exclamation, "Cyberoam Connection Failure")
Denotify()
End
End If
End Try
Else
If counterman <> 10 Then
wait(500)
counterman += 1
GoTo abc
Else
Log("Cannot Connect to Cyberoam")
MsgBox("Couldn't Connect to Cyberoam. Either Cyberoam is down or your not connected to a Cyberoam Network.", MsgBoxStyle.Exclamation, "Cyberoam Connection Failure")
Denotify()
End
End If
End If
def:
SetProgress(80, MetroProgressBar1)
If browser.ReadyState = WebBrowserReadyState.Complete Then
If browser.Document.Body.InnerText.Contains("You have successfully logged in") Then
Log("Logged in")
SetProgress(100, MetroProgressBar1)
CheckUpdates()
Loggedin = True
If Environment.CommandLine.Contains("-lostnet") Then
Log("Restored Net")
'GenerateNotification("Net has been restored. :)", EventType.Warning, 5000)
End If
If Environment.CommandLine.Contains("-logout") Then
SetProgress(90, MetroProgressBar1)
Log("Logging off")
browser.Document.GetElementById("btnSubmit").InvokeMember("click")
wait(500)
If browser.Document.Body.InnerText.Contains("You have successfully logged off") Then
Log("Logged off")
NotifyIcon1.Visible = False
NotifyIcon1.Dispose()
Denotify()
End
End If
End If
ElseIf browser.Document.Body.InnerText.Contains("Your data transfer has been exceeded, Please contact the administrator") Then
Log("Data Transfer Exceeded")
'GenerateNotification("Your data transfer has exceeded. :(", EventType.Warning, 5000)
openlogin = True
Exit Sub
ElseIf browser.Document.Body.InnerText.Contains("The system could not log you on. Make sure your password is correct") Then
Log("Incorrect Credentials")
'GenerateNotification("Your credentials were incorrect. Retry again.", EventType.Warning, 5000)
openlogin = True
Exit Sub
Else
Log("Server Crashed")
GenerateNotification2("Server is not responding. Please try again later", EventType.Warning, 5000)
End If
Else GoTo def
End If
End Sub
Private Sub CheckUpdates()
Log("Checking Updates")
If Environment.CommandLine.Contains("hidden") Then
Try
Dim webman As New WebClient
Dim stringman As String = webman.DownloadString("https://raw.githubusercontent.com/Nischay-Pro/Bits-Internet-Accessibility-Supervisor/master/Bits%20Internet%20Accessibility%20Supervisor/bin/Release/version.txt")
stringman = stringman.Substring(0, My.Application.Info.Version.ToString.Length)
If stringman = My.Application.Info.Version.ToString Then
Log("No New Updates")
Else
Log("New Updates")
If Not Environment.CommandLine.Contains("-lostnet") Then
If MessageBox.Show("A newer update is available. Would you like to download?", "Newer Update Available", MessageBoxButtons.YesNo, MessageBoxIcon.Information) = DialogResult.Yes Then
Process.Start("https://github.com/Nischay-Pro/Bits-Internet-Accessibility-Supervisor/releases")
End If
End If
End If
Catch ex As Exception
Log(ex.Message)
End Try
End If
Log("Checked for updates")
End Sub
Private Sub loadman_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Log("Started Application")
Log("Application Version : " & My.Application.Info.Version.ToString)
Log("Parameters Loaded")
Log(Environment.CommandLine)
My.Computer.FileSystem.WriteAllText(My.Application.Info.DirectoryPath & "\version.txt", My.Application.Info.Version.ToString, False)
Dim threada As New Threading.Thread(AddressOf Check)
threada.SetApartmentState(Threading.ApartmentState.STA)
threada.IsBackground = True
threada.Start()
MetroProgressBar1.Visible = True
End Sub
Private Sub Check()
Try
Log("Logging in")
Dim username As String = Nothing
Dim password As String = Nothing
Dim ini As New IniFile
If My.Computer.FileSystem.FileExists(My.Application.Info.DirectoryPath & "\config.ini") Then
ini.Load(My.Application.Info.DirectoryPath & "\config.ini")
username = ini.GetKeyValue("Authentication", "Username")
Try
'password = DecryptString(getMD5Hash(GetMotherBoardID() & GetProcessorId() & GetVolumeSerial()), ini.GetKeyValue("Authentication", "Password"))
password = ini.GetKeyValue("Authentication", "Password")
Catch ex As Exception
openlogin = True
Exit Sub
End Try
Else
openlogin = True
Exit Sub
End If
CheckLogin(username, password, False)
Catch ex As Exception
Log(ex.Message)
GenerateNotification2("Something wrong happened. :(", EventType.Critical, 5000)
wait(5000)
End
End Try
End Sub
Public Function IsConnectionAvailable() As Boolean
Dim objUrl As New System.Uri("https://www.google.com")
Dim objWebReq As System.Net.WebRequest
objWebReq = System.Net.WebRequest.Create(objUrl)
objWebReq.Proxy = Nothing
Dim objResp As System.Net.WebResponse
Try
objResp = objWebReq.GetResponse
objResp.Close()
objWebReq = Nothing
Return True
Catch ex As Exception
objResp = Nothing
objResp.Close()
objWebReq = Nothing
Return False
End Try
End Function
Private Sub LoadfromSecondary()
Dim Data As String = Nothing
If My.Computer.FileSystem.FileExists(My.Application.Info.DirectoryPath & "\accounts.json") Then
Data = My.Computer.FileSystem.ReadAllText(My.Application.Info.DirectoryPath & "\accounts.json")
End If
Dim parsed As JObject = JObject.Parse(Data)
Dim JArrayman As JArray = parsed("accounts")
For Each Item As JObject In JArrayman
If Item("status") = "Not Verified" Then
CheckLogin(Item("username"), Item("password"), True)
End If
Next
End Sub
Private Sub UpdateSecondary(username As String)
Dim Data As String = Nothing
If My.Computer.FileSystem.FileExists(My.Application.Info.DirectoryPath & "\accounts.json") Then
Data = My.Computer.FileSystem.ReadAllText(My.Application.Info.DirectoryPath & "\accounts.json")
End If
Dim parsed As JObject = JObject.Parse(Data)
Dim JArrayman As JArray = parsed("accounts")
For Each Item As JObject In JArrayman
If Item("username") = username Then
Item("status") = "Currently Active"
Dim milliseconds = CLng(DateTime.UtcNow.Subtract(New DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds)
Item("timestamp") = milliseconds
ElseIf Item("status") = "Not Verified" Then
Else
Item("status") = "Not Active"
End If
Next
End Sub
Private Sub LimitSecondary(username As String)
Dim Data As String = Nothing
If My.Computer.FileSystem.FileExists(My.Application.Info.DirectoryPath & "\accounts.json") Then
Data = My.Computer.FileSystem.ReadAllText(My.Application.Info.DirectoryPath & "\accounts.json")
End If
Dim parsed As JObject = JObject.Parse(Data)
Dim JArrayman As JArray = parsed("accounts")
For Each Item As JObject In JArrayman
If Item("username") = username Then
Item("status") = "Data Exceeded"
Dim milliseconds = CLng(DateTime.UtcNow.Subtract(New DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds)
Item("timestamp") = milliseconds
End If
Next
End Sub
Private Sub InvalidSecondary(username As String)
Dim Data As String = Nothing
If My.Computer.FileSystem.FileExists(My.Application.Info.DirectoryPath & "\accounts.json") Then
Data = My.Computer.FileSystem.ReadAllText(My.Application.Info.DirectoryPath & "\accounts.json")
End If
Dim parsed As JObject = JObject.Parse(Data)
Dim JArrayman As JArray = parsed("accounts")
For Each Item As JObject In JArrayman
If Item("username") = username Then
Item("status") = "Invalid Credentials"
Dim milliseconds = CLng(DateTime.UtcNow.Subtract(New DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds)
Item("timestamp") = milliseconds
End If
Next
End Sub
Private Sub Denotify()
NotifyIcon1.Visible = False
NotifyIcon1.Icon = Nothing
NotifyIcon1.Dispose()
NotifyIcon1 = Nothing
End Sub
Private Sub NotifyIcon1_MouseDoubleClick(sender As Object, e As MouseEventArgs) Handles NotifyIcon1.MouseDoubleClick
NotifyIcon1.Visible = False
Dim newman As New Form1
newman.Show()
Close()
End Sub
Private Sub NotifyIcon1_MouseClick(sender As Object, e As MouseEventArgs) Handles NotifyIcon1.MouseClick
NotifyIcon1.Visible = False
Dim newman As New Form1
newman.Show()
Close()
End Sub
Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
If LostInternet = True Then
threshold += 1
Log("Threshold now at " & threshold)
If threshold = 5 Then
Log("Reached Threshold Limit. Restoring Network Access.")
Denotify()
Process.Start(Application.ExecutablePath, "-hidden -lostnet")
End
End If
End If
End Sub
Dim threshold As Integer = 0
Dim LostInternet As Boolean = False
Private Sub RecheckAccess()
startman:
Log("Checking Network Access")
Try
Dim request As WebRequest = WebRequest.Create("http://www.google.com")
request.Credentials = CredentialCache.DefaultCredentials
request.Timeout = 7 * 1000
Dim response As WebResponse = request.GetResponse()
Console.WriteLine(CType(response, HttpWebResponse).StatusDescription)
Dim dataStream As Stream = response.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
reader.Close()
response.Close()
If responseFromServer.Contains("http://172.16.0.30:8090/httpclient.html") Then
LostInternet = True
Else
Log("Threshold Set to 0")
threshold = 0
End If
Threading.Thread.Sleep(2500)
Catch ex As Exception
LostInternet = True
End Try
GoTo startman
End Sub
End Class
|
Nischay-Pro/Bits-Internet-Accessibility-Supervisor
|
Bits Internet Accessibility Supervisor/load.vb
|
Visual Basic
|
mit
| 16,010
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
<CompilerTrait(CompilerFeature.Tuples)>
Public Class CodeGenTuples
Inherits BasicTestBase
<Fact()>
Public Sub TupleTypeBinding()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim t as (Integer, Integer)
console.writeline(t)
End Sub
End Module
Namespace System
Structure ValueTuple(Of T1, T2)
Public Overrides Function ToString() As String
Return "hello"
End Function
End Structure
End Namespace
</file>
</compilation>, expectedOutput:=<![CDATA[
hello
]]>)
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 12 (0xc)
.maxstack 1
.locals init (System.ValueTuple(Of Integer, Integer) V_0) //t
IL_0000: ldloc.0
IL_0001: box "System.ValueTuple(Of Integer, Integer)"
IL_0006: call "Sub System.Console.WriteLine(Object)"
IL_000b: ret
}
]]>)
End Sub
<Fact()>
Public Sub TupleTypeBindingNoTuple()
Dim comp = CreateCompilationWithMscorlibAndVBRuntime(
<compilation name="NoTuples">
<file name="a.vb"><![CDATA[
Imports System
Module C
Sub Main()
Dim t as (Integer, Integer)
console.writeline(t)
console.writeline(t.Item1)
Dim t1 as (A As Integer, B As Integer)
console.writeline(t1)
console.writeline(t1.Item1)
console.writeline(t1.A)
End Sub
End Module
]]></file>
</compilation>)
comp.AssertTheseDiagnostics(
<errors>
BC31091: Import of type 'ValueTuple(Of ,)' from assembly or module 'NoTuples.dll' failed.
Dim t as (Integer, Integer)
~~~~~~~~~~~~~~~~~~
BC31091: Import of type 'ValueTuple(Of ,)' from assembly or module 'NoTuples.dll' failed.
Dim t as (Integer, Integer)
~~~~~~~~~~~~~~~~~~
BC30389: '(Integer, Integer).Item1' is not accessible in this context because it is 'Private'.
console.writeline(t.Item1)
~~~~~~~
BC31091: Import of type 'ValueTuple(Of ,)' from assembly or module 'NoTuples.dll' failed.
Dim t1 as (A As Integer, B As Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC31091: Import of type 'ValueTuple(Of ,)' from assembly or module 'NoTuples.dll' failed.
Dim t1 as (A As Integer, B As Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30389: '(A As Integer, B As Integer).Item1' is not accessible in this context because it is 'Private'.
console.writeline(t1.Item1)
~~~~~~~~
BC30389: '(A As Integer, B As Integer).A' is not accessible in this context because it is 'Private'.
console.writeline(t1.A)
~~~~
</errors>)
End Sub
<Fact()>
Public Sub DataFlow()
Dim comp = CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module C
Sub Main()
dim initialized as Object = Nothing
dim baseline_literal = (initialized, initialized)
dim uninitialized as Object
dim literal = (uninitialized, uninitialized)
dim uninitialized1 as Exception
dim identity_literal as (Alice As Exception, Bob As Exception) = (uninitialized1, uninitialized1)
dim uninitialized2 as Exception
dim converted_literal as (Object, Object) = (uninitialized2, uninitialized2)
End Sub
End Module
]]></file>
</compilation>, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef})
comp.AssertTheseDiagnostics(
<errors>
BC42104: Variable 'uninitialized' is used before it has been assigned a value. A null reference exception could result at runtime.
dim literal = (uninitialized, uninitialized)
~~~~~~~~~~~~~
BC42104: Variable 'uninitialized1' is used before it has been assigned a value. A null reference exception could result at runtime.
dim identity_literal as (Alice As Exception, Bob As Exception) = (uninitialized1, uninitialized1)
~~~~~~~~~~~~~~
BC42104: Variable 'uninitialized2' is used before it has been assigned a value. A null reference exception could result at runtime.
dim converted_literal as (Object, Object) = (uninitialized2, uninitialized2)
~~~~~~~~~~~~~~
</errors>)
End Sub
<Fact()>
Public Sub TupleFieldBinding()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim t as (Integer, Integer)
t.Item1 = 42
t.Item2 = t.Item1
console.writeline(t.Item2)
End Sub
End Module
Namespace System
Structure ValueTuple(Of T1, T2)
Public Item1 As T1
Public Item2 As T2
End Structure
End Namespace
</file>
</compilation>, expectedOutput:=<![CDATA[
42
]]>)
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 34 (0x22)
.maxstack 2
.locals init (System.ValueTuple(Of Integer, Integer) V_0) //t
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.s 42
IL_0004: stfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer"
IL_0009: ldloca.s V_0
IL_000b: ldloc.0
IL_000c: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer"
IL_0011: stfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer"
IL_0016: ldloc.0
IL_0017: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer"
IL_001c: call "Sub System.Console.WriteLine(Integer)"
IL_0021: ret
}
]]>)
End Sub
<Fact()>
Public Sub TupleFieldBinding01()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim vt as ValueTuple(Of Integer, Integer) = M1(2,3)
console.writeline(vt.Item2)
End Sub
Function M1(x As Integer, y As Integer) As ValueTuple(Of Integer, Integer)
Return New ValueTuple(Of Integer, Integer)(x, y)
End Function
End Module
</file>
</compilation>, expectedOutput:=<![CDATA[
3
]]>, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef})
verifier.VerifyIL("C.M1", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)"
IL_0007: ret
}
]]>)
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 18 (0x12)
.maxstack 2
IL_0000: ldc.i4.2
IL_0001: ldc.i4.3
IL_0002: call "Function C.M1(Integer, Integer) As (Integer, Integer)"
IL_0007: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer"
IL_000c: call "Sub System.Console.WriteLine(Integer)"
IL_0011: ret
}
]]>)
End Sub
<Fact()>
Public Sub TupleFieldBindingLong()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim t as (Integer, Integer, Integer, integer, integer, integer, integer, integer, integer, Integer, Integer, String, integer, integer, integer, integer, String, integer)
t.Item17 = "hello"
t.Item12 = t.Item17
console.writeline(t.Item12)
End Sub
End Module
</file>
</compilation>, expectedOutput:=<![CDATA[
hello
]]>, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef})
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 67 (0x43)
.maxstack 2
.locals init (System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer, String, Integer, Integer, Integer, Integer, String, Integer)) V_0) //t
IL_0000: ldloca.s V_0
IL_0002: ldflda "System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer, String, Integer, Integer, Integer, Integer, String, Integer)).Rest As (Integer, Integer, Integer, Integer, String, Integer, Integer, Integer, Integer, String, Integer)"
IL_0007: ldflda "System.ValueTuple(Of Integer, Integer, Integer, Integer, String, Integer, Integer, (Integer, Integer, String, Integer)).Rest As (Integer, Integer, String, Integer)"
IL_000c: ldstr "hello"
IL_0011: stfld "System.ValueTuple(Of Integer, Integer, String, Integer).Item3 As String"
IL_0016: ldloca.s V_0
IL_0018: ldflda "System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer, String, Integer, Integer, Integer, Integer, String, Integer)).Rest As (Integer, Integer, Integer, Integer, String, Integer, Integer, Integer, Integer, String, Integer)"
IL_001d: ldloc.0
IL_001e: ldfld "System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer, String, Integer, Integer, Integer, Integer, String, Integer)).Rest As (Integer, Integer, Integer, Integer, String, Integer, Integer, Integer, Integer, String, Integer)"
IL_0023: ldfld "System.ValueTuple(Of Integer, Integer, Integer, Integer, String, Integer, Integer, (Integer, Integer, String, Integer)).Rest As (Integer, Integer, String, Integer)"
IL_0028: ldfld "System.ValueTuple(Of Integer, Integer, String, Integer).Item3 As String"
IL_002d: stfld "System.ValueTuple(Of Integer, Integer, Integer, Integer, String, Integer, Integer, (Integer, Integer, String, Integer)).Item5 As String"
IL_0032: ldloc.0
IL_0033: ldfld "System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer, String, Integer, Integer, Integer, Integer, String, Integer)).Rest As (Integer, Integer, Integer, Integer, String, Integer, Integer, Integer, Integer, String, Integer)"
IL_0038: ldfld "System.ValueTuple(Of Integer, Integer, Integer, Integer, String, Integer, Integer, (Integer, Integer, String, Integer)).Item5 As String"
IL_003d: call "Sub System.Console.WriteLine(String)"
IL_0042: ret
}
]]>)
End Sub
<Fact()>
Public Sub TupleNamedFieldBinding()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim t As (a As Integer, b As Integer)
t.a = 42
t.b = t.a
Console.WriteLine(t.b)
End Sub
End Module
Namespace System
Structure ValueTuple(Of T1, T2)
Public Item1 As T1
Public Item2 As T2
End Structure
End Namespace
</file>
</compilation>, expectedOutput:=<![CDATA[
42
]]>)
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 34 (0x22)
.maxstack 2
.locals init (System.ValueTuple(Of Integer, Integer) V_0) //t
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.s 42
IL_0004: stfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer"
IL_0009: ldloca.s V_0
IL_000b: ldloc.0
IL_000c: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer"
IL_0011: stfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer"
IL_0016: ldloc.0
IL_0017: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer"
IL_001c: call "Sub System.Console.WriteLine(Integer)"
IL_0021: ret
}
]]>)
End Sub
<Fact()>
Public Sub TupleDefaultFieldBinding()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Dim t As (Integer, Integer) = nothing
t.Item1 = 42
t.Item2 = t.Item1
Console.WriteLine(t.Item2)
Dim t1 = (A:=1, B:=123)
Console.WriteLine(t1.B)
End Sub
End Module
</file>
</compilation>, expectedOutput:=<![CDATA[
42
123
]]>, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef})
verifier.VerifyIL("Module1.Main", <![CDATA[
{
// Code size 60 (0x3c)
.maxstack 2
.locals init (System.ValueTuple(Of Integer, Integer) V_0) //t
IL_0000: ldloca.s V_0
IL_0002: initobj "System.ValueTuple(Of Integer, Integer)"
IL_0008: ldloca.s V_0
IL_000a: ldc.i4.s 42
IL_000c: stfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer"
IL_0011: ldloca.s V_0
IL_0013: ldloc.0
IL_0014: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer"
IL_0019: stfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer"
IL_001e: ldloc.0
IL_001f: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer"
IL_0024: call "Sub System.Console.WriteLine(Integer)"
IL_0029: ldc.i4.1
IL_002a: ldc.i4.s 123
IL_002c: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)"
IL_0031: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer"
IL_0036: call "Sub System.Console.WriteLine(Integer)"
IL_003b: ret
}
]]>)
End Sub
<Fact()>
Public Sub TupleNamedFieldBindingLong()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim t as (a1 as Integer, a2 as Integer, a3 as Integer, a4 as integer,
a5 as integer, a6 as integer, a7 as integer, a8 as integer,
a9 as integer, a10 as Integer, a11 as Integer, a12 as Integer,
a13 as integer, a14 as integer, a15 as integer, a16 as integer,
a17 as integer, a18 as integer)
t.a17 = 42
t.a12 = t.a17
console.writeline(t.a12)
End Sub
End Module
</file>
</compilation>, expectedOutput:=<![CDATA[
42
]]>, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef})
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 64 (0x40)
.maxstack 2
.locals init (System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)) V_0) //t
IL_0000: ldloca.s V_0
IL_0002: ldflda "System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)).Rest As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)"
IL_0007: ldflda "System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer)).Rest As (Integer, Integer, Integer, Integer)"
IL_000c: ldc.i4.s 42
IL_000e: stfld "System.ValueTuple(Of Integer, Integer, Integer, Integer).Item3 As Integer"
IL_0013: ldloca.s V_0
IL_0015: ldflda "System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)).Rest As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)"
IL_001a: ldloc.0
IL_001b: ldfld "System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)).Rest As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)"
IL_0020: ldfld "System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer)).Rest As (Integer, Integer, Integer, Integer)"
IL_0025: ldfld "System.ValueTuple(Of Integer, Integer, Integer, Integer).Item3 As Integer"
IL_002a: stfld "System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer)).Item5 As Integer"
IL_002f: ldloc.0
IL_0030: ldfld "System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)).Rest As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)"
IL_0035: ldfld "System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer)).Item5 As Integer"
IL_003a: call "Sub System.Console.WriteLine(Integer)"
IL_003f: ret
}
]]>)
End Sub
<Fact()>
Public Sub TupleLiteralBinding()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim t as (Integer, Integer) = (1, 2)
console.writeline(t)
End Sub
End Module
</file>
</compilation>, expectedOutput:=<![CDATA[
(1, 2)
]]>, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef})
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 18 (0x12)
.maxstack 2
IL_0000: ldc.i4.1
IL_0001: ldc.i4.2
IL_0002: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)"
IL_0007: box "System.ValueTuple(Of Integer, Integer)"
IL_000c: call "Sub System.Console.WriteLine(Object)"
IL_0011: ret
}
]]>)
End Sub
<Fact()>
Public Sub TupleLiteralBindingNamed()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim t = (A := 1, B := "hello")
console.writeline(t.B)
End Sub
End Module
</file>
</compilation>, expectedOutput:=<![CDATA[
hello
]]>, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef})
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 22 (0x16)
.maxstack 2
IL_0000: ldc.i4.1
IL_0001: ldstr "hello"
IL_0006: newobj "Sub System.ValueTuple(Of Integer, String)..ctor(Integer, String)"
IL_000b: ldfld "System.ValueTuple(Of Integer, String).Item2 As String"
IL_0010: call "Sub System.Console.WriteLine(String)"
IL_0015: ret
}
]]>)
End Sub
<Fact()>
Public Sub TupleLiteralSample()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Collections.Generic
Imports System.Threading.Tasks
Module Module1
Sub Main()
Dim t As (Integer, Integer) = Nothing
t.Item1 = 42
t.Item2 = t.Item1
Console.WriteLine(t.Item2)
Dim t1 = (A:=1, B:=123)
Console.WriteLine(t1.B)
Dim numbers = {1, 2, 3, 4}
Dim t2 = Tally(numbers).Result
System.Console.WriteLine($"Sum: {t2.Sum}, Count: {t2.Count}")
End Sub
Public Async Function Tally(values As IEnumerable(Of Integer)) As Task(Of (Sum As Integer, Count As Integer))
Dim s = 0, c = 0
For Each n In values
s += n
c += 1
Next
'Await Task.Yield()
Return (Sum:=s, Count:=c)
End Function
End Module
Namespace System
Structure ValueTuple(Of T1, T2)
Public Item1 As T1
Public Item2 As T2
Sub New(item1 as T1, item2 as T2)
Me.Item1 = item1
Me.Item2 = item2
End Sub
End Structure
End Namespace
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="42
123
Sum: 10, Count: 4")
End Sub
<Fact()>
Public Sub Overloading001()
Dim comp = CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Module m1
Sub Test(x as (a as integer, b as Integer))
End Sub
Sub Test(x as (c as integer, d as Integer))
End Sub
End module
]]></file>
</compilation>, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef})
comp.AssertTheseDiagnostics(
<errors>
BC30269: 'Public Sub Test(x As (a As Integer, b As Integer))' has multiple definitions with identical signatures.
Sub Test(x as (a as integer, b as Integer))
~~~~
</errors>)
End Sub
<Fact()>
Public Sub Overloading002()
Dim comp = CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Module m1
Sub Test(x as (integer,Integer))
End Sub
Sub Test(x as (a as integer, b as Integer))
End Sub
End module
]]></file>
</compilation>, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef})
comp.AssertTheseDiagnostics(
<errors>
BC30269: 'Public Sub Test(x As (Integer, Integer))' has multiple definitions with identical signatures.
Sub Test(x as (integer,Integer))
~~~~
</errors>)
End Sub
<Fact()>
Public Sub SimpleTupleTargetTyped001()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim x as (String, String) = (Nothing, Nothing)
System.Console.WriteLine(x.ToString())
End Sub
End Module
</file>
</compilation>, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef}, expectedOutput:=<![CDATA[
(, )
]]>)
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 28 (0x1c)
.maxstack 3
.locals init (System.ValueTuple(Of String, String) V_0) //x
IL_0000: ldloca.s V_0
IL_0002: ldnull
IL_0003: ldnull
IL_0004: call "Sub System.ValueTuple(Of String, String)..ctor(String, String)"
IL_0009: ldloca.s V_0
IL_000b: constrained. "System.ValueTuple(Of String, String)"
IL_0011: callvirt "Function Object.ToString() As String"
IL_0016: call "Sub System.Console.WriteLine(String)"
IL_001b: ret
}
]]>)
Dim comp = verifier.Compilation
Dim tree = comp.SyntaxTrees(0)
Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False)
Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes()
Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single()
Assert.Equal("(Nothing, Nothing)", node.ToString())
Assert.Null(model.GetTypeInfo(node).Type)
Assert.Equal("(System.String, System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.WideningTuple, model.GetConversion(node).Kind)
End Sub
<Fact()>
Public Sub SimpleTupleTargetTyped001Err()
Dim comp = CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module C
Sub Main()
Dim x as (A as String, B as String) = (C:=Nothing, D:=Nothing, E:=Nothing)
System.Console.WriteLine(x.ToString())
End Sub
End Module
]]></file>
</compilation>, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef})
comp.AssertTheseDiagnostics(
<errors>
BC30491: Expression does not produce a value.
Dim x as (A as String, B as String) = (C:=Nothing, D:=Nothing, E:=Nothing)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</errors>)
End Sub
<Fact()>
Public Sub SimpleTupleTargetTyped002()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim x as (Func(Of integer), Func(of String)) = (Function() 42, Function() "hi")
System.Console.WriteLine((x.Item1(), x.Item2()).ToString())
End Sub
End Module
</file>
</compilation>, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef}, expectedOutput:=<![CDATA[
(42, hi)
]]>)
End Sub
<Fact()>
Public Sub SimpleTupleTargetTyped002a()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim x as (Func(Of integer), Func(of String)) = (Function() 42, Function() Nothing)
System.Console.WriteLine((x.Item1(), x.Item2()).ToString())
End Sub
End Module
</file>
</compilation>, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef}, expectedOutput:=<![CDATA[
(42, )
]]>)
End Sub
<Fact()>
Public Sub SimpleTupleTargetTyped003()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim x = CType((Nothing, 1),(String, Byte))
System.Console.WriteLine(x.ToString())
End Sub
End Module
</file>
</compilation>, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef}, expectedOutput:=<![CDATA[
(, 1)
]]>)
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 28 (0x1c)
.maxstack 3
.locals init (System.ValueTuple(Of String, Byte) V_0) //x
IL_0000: ldloca.s V_0
IL_0002: ldnull
IL_0003: ldc.i4.1
IL_0004: call "Sub System.ValueTuple(Of String, Byte)..ctor(String, Byte)"
IL_0009: ldloca.s V_0
IL_000b: constrained. "System.ValueTuple(Of String, Byte)"
IL_0011: callvirt "Function Object.ToString() As String"
IL_0016: call "Sub System.Console.WriteLine(String)"
IL_001b: ret
}
]]>)
End Sub
<Fact()>
Public Sub SimpleTupleTargetTyped004()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim x = DirectCast((Nothing, 1),(String, String))
System.Console.WriteLine(x.ToString())
End Sub
End Module
</file>
</compilation>, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef}, expectedOutput:=<![CDATA[
(, 1)
]]>)
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 33 (0x21)
.maxstack 3
.locals init (System.ValueTuple(Of String, String) V_0) //x
IL_0000: ldloca.s V_0
IL_0002: ldnull
IL_0003: ldc.i4.1
IL_0004: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToString(Integer) As String"
IL_0009: call "Sub System.ValueTuple(Of String, String)..ctor(String, String)"
IL_000e: ldloca.s V_0
IL_0010: constrained. "System.ValueTuple(Of String, String)"
IL_0016: callvirt "Function Object.ToString() As String"
IL_001b: call "Sub System.Console.WriteLine(String)"
IL_0020: ret
}
]]>)
End Sub
<Fact()>
Public Sub SimpleTupleTargetTyped005()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim i as integer = 100
Dim x = CType((Nothing, i),(String, byte))
System.Console.WriteLine(x.ToString())
End Sub
End Module
</file>
</compilation>, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef}, expectedOutput:=<![CDATA[
(, 100)
]]>)
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 32 (0x20)
.maxstack 3
.locals init (Integer V_0, //i
System.ValueTuple(Of String, Byte) V_1) //x
IL_0000: ldc.i4.s 100
IL_0002: stloc.0
IL_0003: ldloca.s V_1
IL_0005: ldnull
IL_0006: ldloc.0
IL_0007: conv.ovf.u1
IL_0008: call "Sub System.ValueTuple(Of String, Byte)..ctor(String, Byte)"
IL_000d: ldloca.s V_1
IL_000f: constrained. "System.ValueTuple(Of String, Byte)"
IL_0015: callvirt "Function Object.ToString() As String"
IL_001a: call "Sub System.Console.WriteLine(String)"
IL_001f: ret
}
]]>)
End Sub
<Fact()>
Public Sub SimpleTupleTargetTyped006()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim i as integer = 100
Dim x = DirectCast((Nothing, i),(String, byte))
System.Console.WriteLine(x.ToString())
End Sub
End Module
</file>
</compilation>, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef}, expectedOutput:=<![CDATA[
(, 100)
]]>)
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 32 (0x20)
.maxstack 3
.locals init (Integer V_0, //i
System.ValueTuple(Of String, Byte) V_1) //x
IL_0000: ldc.i4.s 100
IL_0002: stloc.0
IL_0003: ldloca.s V_1
IL_0005: ldnull
IL_0006: ldloc.0
IL_0007: conv.ovf.u1
IL_0008: call "Sub System.ValueTuple(Of String, Byte)..ctor(String, Byte)"
IL_000d: ldloca.s V_1
IL_000f: constrained. "System.ValueTuple(Of String, Byte)"
IL_0015: callvirt "Function Object.ToString() As String"
IL_001a: call "Sub System.Console.WriteLine(String)"
IL_001f: ret
}
]]>)
End Sub
<Fact()>
Public Sub SimpleTupleTargetTyped007()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim i as integer = 100
Dim x = TryCast((Nothing, i),(String, byte))
System.Console.WriteLine(x.ToString())
End Sub
End Module
</file>
</compilation>, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef}, expectedOutput:=<![CDATA[
(, 100)
]]>)
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 32 (0x20)
.maxstack 3
.locals init (Integer V_0, //i
System.ValueTuple(Of String, Byte) V_1) //x
IL_0000: ldc.i4.s 100
IL_0002: stloc.0
IL_0003: ldloca.s V_1
IL_0005: ldnull
IL_0006: ldloc.0
IL_0007: conv.ovf.u1
IL_0008: call "Sub System.ValueTuple(Of String, Byte)..ctor(String, Byte)"
IL_000d: ldloca.s V_1
IL_000f: constrained. "System.ValueTuple(Of String, Byte)"
IL_0015: callvirt "Function Object.ToString() As String"
IL_001a: call "Sub System.Console.WriteLine(String)"
IL_001f: ret
}
]]>)
End Sub
<Fact()>
Public Sub TupleConversionWidening()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim i as (x as byte, y as byte) = (a:=100, b:=100)
Dim x as (integer, double) = i
System.Console.WriteLine(x.ToString())
End Sub
End Module
</file>
</compilation>, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef}, expectedOutput:=<![CDATA[
(100, 100)
]]>)
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 48 (0x30)
.maxstack 2
.locals init (System.ValueTuple(Of Integer, Double) V_0, //x
System.ValueTuple(Of Byte, Byte) V_1)
IL_0000: ldc.i4.s 100
IL_0002: ldc.i4.s 100
IL_0004: newobj "Sub System.ValueTuple(Of Byte, Byte)..ctor(Byte, Byte)"
IL_0009: stloc.1
IL_000a: ldloc.1
IL_000b: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte"
IL_0010: ldloc.1
IL_0011: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte"
IL_0016: conv.r8
IL_0017: newobj "Sub System.ValueTuple(Of Integer, Double)..ctor(Integer, Double)"
IL_001c: stloc.0
IL_001d: ldloca.s V_0
IL_001f: constrained. "System.ValueTuple(Of Integer, Double)"
IL_0025: callvirt "Function Object.ToString() As String"
IL_002a: call "Sub System.Console.WriteLine(String)"
IL_002f: ret
}
]]>)
Dim comp = verifier.Compilation
Dim tree = comp.SyntaxTrees(0)
Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False)
Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes()
Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single()
Assert.Equal("(a:=100, b:=100)", node.ToString())
Assert.Equal("(a As Integer, b As Integer)", model.GetTypeInfo(node).Type.ToDisplayString())
Assert.Equal("(x As System.Byte, y As System.Byte)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.WideningTuple, model.GetConversion(node).Kind)
End Sub
<Fact()>
Public Sub TupleConversionNarrowing()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim i as (Integer, String) = (100, 100)
Dim x as (Byte, Byte) = i
System.Console.WriteLine(x.ToString())
End Sub
End Module
</file>
</compilation>, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef}, expectedOutput:=<![CDATA[
(100, 100)
]]>)
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 58 (0x3a)
.maxstack 2
.locals init (System.ValueTuple(Of Byte, Byte) V_0, //x
System.ValueTuple(Of Integer, String) V_1)
IL_0000: ldc.i4.s 100
IL_0002: ldc.i4.s 100
IL_0004: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToString(Integer) As String"
IL_0009: newobj "Sub System.ValueTuple(Of Integer, String)..ctor(Integer, String)"
IL_000e: stloc.1
IL_000f: ldloc.1
IL_0010: ldfld "System.ValueTuple(Of Integer, String).Item1 As Integer"
IL_0015: conv.ovf.u1
IL_0016: ldloc.1
IL_0017: ldfld "System.ValueTuple(Of Integer, String).Item2 As String"
IL_001c: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToByte(String) As Byte"
IL_0021: newobj "Sub System.ValueTuple(Of Byte, Byte)..ctor(Byte, Byte)"
IL_0026: stloc.0
IL_0027: ldloca.s V_0
IL_0029: constrained. "System.ValueTuple(Of Byte, Byte)"
IL_002f: callvirt "Function Object.ToString() As String"
IL_0034: call "Sub System.Console.WriteLine(String)"
IL_0039: ret
}
]]>)
Dim comp = verifier.Compilation
Dim tree = comp.SyntaxTrees(0)
Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False)
Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes()
Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single()
Assert.Equal("(100, 100)", node.ToString())
Assert.Equal("(Integer, Integer)", model.GetTypeInfo(node).Type.ToDisplayString())
Assert.Equal("(System.Int32, System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString())
Assert.Equal(ConversionKind.NarrowingTuple, model.GetConversion(node).Kind)
End Sub
<Fact()>
Public Sub TupleConversionNarrowingUnchecked()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim i as (Integer, String) = (100, 100)
Dim x as (Byte, Byte) = i
System.Console.WriteLine(x.ToString())
End Sub
End Module
</file>
</compilation>, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef}, options:=TestOptions.ReleaseExe.WithOverflowChecks(False), expectedOutput:=<![CDATA[
(100, 100)
]]>)
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 58 (0x3a)
.maxstack 2
.locals init (System.ValueTuple(Of Byte, Byte) V_0, //x
System.ValueTuple(Of Integer, String) V_1)
IL_0000: ldc.i4.s 100
IL_0002: ldc.i4.s 100
IL_0004: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToString(Integer) As String"
IL_0009: newobj "Sub System.ValueTuple(Of Integer, String)..ctor(Integer, String)"
IL_000e: stloc.1
IL_000f: ldloc.1
IL_0010: ldfld "System.ValueTuple(Of Integer, String).Item1 As Integer"
IL_0015: conv.u1
IL_0016: ldloc.1
IL_0017: ldfld "System.ValueTuple(Of Integer, String).Item2 As String"
IL_001c: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToByte(String) As Byte"
IL_0021: newobj "Sub System.ValueTuple(Of Byte, Byte)..ctor(Byte, Byte)"
IL_0026: stloc.0
IL_0027: ldloca.s V_0
IL_0029: constrained. "System.ValueTuple(Of Byte, Byte)"
IL_002f: callvirt "Function Object.ToString() As String"
IL_0034: call "Sub System.Console.WriteLine(String)"
IL_0039: ret
}
]]>)
End Sub
<Fact()>
Public Sub TupleConversionObject()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim i as (object, object) = (1, (2,3))
Dim x as (integer, (integer, integer)) = ctype(i, (integer, (integer, integer)))
System.Console.WriteLine(x.ToString())
End Sub
End Module
</file>
</compilation>, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef}, expectedOutput:=<![CDATA[
(1, (2, 3))
]]>)
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 86 (0x56)
.maxstack 3
.locals init (System.ValueTuple(Of Integer, (Integer, Integer)) V_0, //x
System.ValueTuple(Of Object, Object) V_1,
System.ValueTuple(Of Integer, Integer) V_2)
IL_0000: ldc.i4.1
IL_0001: box "Integer"
IL_0006: ldc.i4.2
IL_0007: ldc.i4.3
IL_0008: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)"
IL_000d: box "System.ValueTuple(Of Integer, Integer)"
IL_0012: newobj "Sub System.ValueTuple(Of Object, Object)..ctor(Object, Object)"
IL_0017: stloc.1
IL_0018: ldloc.1
IL_0019: ldfld "System.ValueTuple(Of Object, Object).Item1 As Object"
IL_001e: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(Object) As Integer"
IL_0023: ldloc.1
IL_0024: ldfld "System.ValueTuple(Of Object, Object).Item2 As Object"
IL_0029: dup
IL_002a: brtrue.s IL_0038
IL_002c: pop
IL_002d: ldloca.s V_2
IL_002f: initobj "System.ValueTuple(Of Integer, Integer)"
IL_0035: ldloc.2
IL_0036: br.s IL_003d
IL_0038: unbox.any "System.ValueTuple(Of Integer, Integer)"
IL_003d: newobj "Sub System.ValueTuple(Of Integer, (Integer, Integer))..ctor(Integer, (Integer, Integer))"
IL_0042: stloc.0
IL_0043: ldloca.s V_0
IL_0045: constrained. "System.ValueTuple(Of Integer, (Integer, Integer))"
IL_004b: callvirt "Function Object.ToString() As String"
IL_0050: call "Sub System.Console.WriteLine(String)"
IL_0055: ret
}
]]>)
End Sub
<Fact()>
Public Sub TupleConversionOverloadResolution()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim b as (byte, byte) = (100, 100)
Test(b)
Dim i as (integer, integer) = b
Test(i)
Dim l as (Long, integer) = b
Test(l)
End Sub
Sub Test(x as (integer, integer))
System.Console.Writeline("integer")
End SUb
Sub Test(x as (Long, Long))
System.Console.Writeline("long")
End SUb
End Module
</file>
</compilation>, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef}, expectedOutput:=<![CDATA[
integer
integer
long ]]>)
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 101 (0x65)
.maxstack 3
.locals init (System.ValueTuple(Of Byte, Byte) V_0,
System.ValueTuple(Of Long, Integer) V_1)
IL_0000: ldc.i4.s 100
IL_0002: ldc.i4.s 100
IL_0004: newobj "Sub System.ValueTuple(Of Byte, Byte)..ctor(Byte, Byte)"
IL_0009: dup
IL_000a: stloc.0
IL_000b: ldloc.0
IL_000c: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte"
IL_0011: ldloc.0
IL_0012: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte"
IL_0017: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)"
IL_001c: call "Sub C.Test((Integer, Integer))"
IL_0021: dup
IL_0022: stloc.0
IL_0023: ldloc.0
IL_0024: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte"
IL_0029: ldloc.0
IL_002a: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte"
IL_002f: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)"
IL_0034: call "Sub C.Test((Integer, Integer))"
IL_0039: stloc.0
IL_003a: ldloc.0
IL_003b: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte"
IL_0040: conv.u8
IL_0041: ldloc.0
IL_0042: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte"
IL_0047: newobj "Sub System.ValueTuple(Of Long, Integer)..ctor(Long, Integer)"
IL_004c: stloc.1
IL_004d: ldloc.1
IL_004e: ldfld "System.ValueTuple(Of Long, Integer).Item1 As Long"
IL_0053: ldloc.1
IL_0054: ldfld "System.ValueTuple(Of Long, Integer).Item2 As Integer"
IL_0059: conv.i8
IL_005a: newobj "Sub System.ValueTuple(Of Long, Long)..ctor(Long, Long)"
IL_005f: call "Sub C.Test((Long, Long))"
IL_0064: ret
}
]]>)
End Sub
<Fact()>
Public Sub TupleConversionNullable001()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim i as (x as byte, y as byte)? = (a:=100, b:=100)
Dim x as (integer, double) = CType(i, (integer, double))
System.Console.WriteLine(x.ToString())
End Sub
End Module
</file>
</compilation>, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef}, expectedOutput:=<![CDATA[
(100, 100)
]]>)
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 62 (0x3e)
.maxstack 3
.locals init ((x As Byte, y As Byte)? V_0, //i
System.ValueTuple(Of Integer, Double) V_1, //x
System.ValueTuple(Of Byte, Byte) V_2)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.s 100
IL_0004: ldc.i4.s 100
IL_0006: newobj "Sub System.ValueTuple(Of Byte, Byte)..ctor(Byte, Byte)"
IL_000b: call "Sub (x As Byte, y As Byte)?..ctor((x As Byte, y As Byte))"
IL_0010: ldloca.s V_0
IL_0012: call "Function (x As Byte, y As Byte)?.get_Value() As (x As Byte, y As Byte)"
IL_0017: stloc.2
IL_0018: ldloc.2
IL_0019: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte"
IL_001e: ldloc.2
IL_001f: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte"
IL_0024: conv.r8
IL_0025: newobj "Sub System.ValueTuple(Of Integer, Double)..ctor(Integer, Double)"
IL_002a: stloc.1
IL_002b: ldloca.s V_1
IL_002d: constrained. "System.ValueTuple(Of Integer, Double)"
IL_0033: callvirt "Function Object.ToString() As String"
IL_0038: call "Sub System.Console.WriteLine(String)"
IL_003d: ret
}
]]>)
End Sub
<Fact()>
Public Sub TupleConversionNullable002()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim i as (x as byte, y as byte) = (a:=100, b:=100)
Dim x as (integer, double)? = CType(i, (integer, double))
System.Console.WriteLine(x.ToString())
End Sub
End Module
</file>
</compilation>, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef}, expectedOutput:=<![CDATA[
(100, 100)
]]>)
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 57 (0x39)
.maxstack 3
.locals init (System.ValueTuple(Of Byte, Byte) V_0, //i
(Integer, Double)? V_1, //x
System.ValueTuple(Of Byte, Byte) V_2)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.s 100
IL_0004: ldc.i4.s 100
IL_0006: call "Sub System.ValueTuple(Of Byte, Byte)..ctor(Byte, Byte)"
IL_000b: ldloca.s V_1
IL_000d: ldloc.0
IL_000e: stloc.2
IL_000f: ldloc.2
IL_0010: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte"
IL_0015: ldloc.2
IL_0016: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte"
IL_001b: conv.r8
IL_001c: newobj "Sub System.ValueTuple(Of Integer, Double)..ctor(Integer, Double)"
IL_0021: call "Sub (Integer, Double)?..ctor((Integer, Double))"
IL_0026: ldloca.s V_1
IL_0028: constrained. "(Integer, Double)?"
IL_002e: callvirt "Function Object.ToString() As String"
IL_0033: call "Sub System.Console.WriteLine(String)"
IL_0038: ret
}
]]>)
End Sub
<Fact()>
Public Sub TupleConversionNullable003()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim i as (x as byte, y as byte)? = (a:=100, b:=100)
Dim x = CType(i, (integer, double)?)
System.Console.WriteLine(x.ToString())
End Sub
End Module
</file>
</compilation>, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef}, expectedOutput:=<![CDATA[
(100, 100)
]]>)
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 87 (0x57)
.maxstack 3
.locals init ((x As Byte, y As Byte)? V_0, //i
(Integer, Double)? V_1, //x
(Integer, Double)? V_2,
System.ValueTuple(Of Byte, Byte) V_3)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.s 100
IL_0004: ldc.i4.s 100
IL_0006: newobj "Sub System.ValueTuple(Of Byte, Byte)..ctor(Byte, Byte)"
IL_000b: call "Sub (x As Byte, y As Byte)?..ctor((x As Byte, y As Byte))"
IL_0010: ldloca.s V_0
IL_0012: call "Function (x As Byte, y As Byte)?.get_HasValue() As Boolean"
IL_0017: brtrue.s IL_0024
IL_0019: ldloca.s V_2
IL_001b: initobj "(Integer, Double)?"
IL_0021: ldloc.2
IL_0022: br.s IL_0043
IL_0024: ldloca.s V_0
IL_0026: call "Function (x As Byte, y As Byte)?.GetValueOrDefault() As (x As Byte, y As Byte)"
IL_002b: stloc.3
IL_002c: ldloc.3
IL_002d: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte"
IL_0032: ldloc.3
IL_0033: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte"
IL_0038: conv.r8
IL_0039: newobj "Sub System.ValueTuple(Of Integer, Double)..ctor(Integer, Double)"
IL_003e: newobj "Sub (Integer, Double)?..ctor((Integer, Double))"
IL_0043: stloc.1
IL_0044: ldloca.s V_1
IL_0046: constrained. "(Integer, Double)?"
IL_004c: callvirt "Function Object.ToString() As String"
IL_0051: call "Sub System.Console.WriteLine(String)"
IL_0056: ret
}
]]>)
End Sub
<Fact()>
Public Sub TupleConversionNullable004()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim i as ValueTuple(of byte, byte)? = (a:=100, b:=100)
Dim x = CType(i, ValueTuple(of integer, double)?)
System.Console.WriteLine(x.ToString())
End Sub
End Module
</file>
</compilation>, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef}, expectedOutput:=<![CDATA[
(100, 100)
]]>)
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 87 (0x57)
.maxstack 3
.locals init ((Byte, Byte)? V_0, //i
(Integer, Double)? V_1, //x
(Integer, Double)? V_2,
System.ValueTuple(Of Byte, Byte) V_3)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.s 100
IL_0004: ldc.i4.s 100
IL_0006: newobj "Sub System.ValueTuple(Of Byte, Byte)..ctor(Byte, Byte)"
IL_000b: call "Sub (Byte, Byte)?..ctor((Byte, Byte))"
IL_0010: ldloca.s V_0
IL_0012: call "Function (Byte, Byte)?.get_HasValue() As Boolean"
IL_0017: brtrue.s IL_0024
IL_0019: ldloca.s V_2
IL_001b: initobj "(Integer, Double)?"
IL_0021: ldloc.2
IL_0022: br.s IL_0043
IL_0024: ldloca.s V_0
IL_0026: call "Function (Byte, Byte)?.GetValueOrDefault() As (Byte, Byte)"
IL_002b: stloc.3
IL_002c: ldloc.3
IL_002d: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte"
IL_0032: ldloc.3
IL_0033: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte"
IL_0038: conv.r8
IL_0039: newobj "Sub System.ValueTuple(Of Integer, Double)..ctor(Integer, Double)"
IL_003e: newobj "Sub (Integer, Double)?..ctor((Integer, Double))"
IL_0043: stloc.1
IL_0044: ldloca.s V_1
IL_0046: constrained. "(Integer, Double)?"
IL_004c: callvirt "Function Object.ToString() As String"
IL_0051: call "Sub System.Console.WriteLine(String)"
IL_0056: ret
}
]]>)
End Sub
<Fact()>
Public Sub ImplicitConversions02()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim x = (a:=1, b:=1)
Dim y As C1 = x
x = y
System.Console.WriteLine(x)
x = CType(CType(x, C1), (integer, integer))
System.Console.WriteLine(x)
End Sub
End Module
Class C1
Public Shared Widening Operator CType(arg as (long, long)) as C1
return new C1()
End Operator
Public Shared Widening Operator CType(arg as C1) as (c As Byte, d as Byte)
return (2, 2)
End Operator
End Class
</file>
</compilation>, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef}, expectedOutput:=<![CDATA[
(2, 2)
(2, 2)
]]>)
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 125 (0x7d)
.maxstack 2
.locals init (System.ValueTuple(Of Integer, Integer) V_0,
System.ValueTuple(Of Byte, Byte) V_1)
IL_0000: ldc.i4.1
IL_0001: ldc.i4.1
IL_0002: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)"
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer"
IL_000e: conv.i8
IL_000f: ldloc.0
IL_0010: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer"
IL_0015: conv.i8
IL_0016: newobj "Sub System.ValueTuple(Of Long, Long)..ctor(Long, Long)"
IL_001b: call "Function C1.op_Implicit((Long, Long)) As C1"
IL_0020: call "Function C1.op_Implicit(C1) As (c As Byte, d As Byte)"
IL_0025: stloc.1
IL_0026: ldloc.1
IL_0027: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte"
IL_002c: ldloc.1
IL_002d: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte"
IL_0032: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)"
IL_0037: dup
IL_0038: box "System.ValueTuple(Of Integer, Integer)"
IL_003d: call "Sub System.Console.WriteLine(Object)"
IL_0042: stloc.0
IL_0043: ldloc.0
IL_0044: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer"
IL_0049: conv.i8
IL_004a: ldloc.0
IL_004b: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer"
IL_0050: conv.i8
IL_0051: newobj "Sub System.ValueTuple(Of Long, Long)..ctor(Long, Long)"
IL_0056: call "Function C1.op_Implicit((Long, Long)) As C1"
IL_005b: call "Function C1.op_Implicit(C1) As (c As Byte, d As Byte)"
IL_0060: stloc.1
IL_0061: ldloc.1
IL_0062: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte"
IL_0067: ldloc.1
IL_0068: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte"
IL_006d: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)"
IL_0072: box "System.ValueTuple(Of Integer, Integer)"
IL_0077: call "Sub System.Console.WriteLine(Object)"
IL_007c: ret
}
]]>)
End Sub
<Fact()>
Public Sub ExplicitConversions02()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim x = (a:=1, b:=1)
Dim y As C1 = CType(x, C1)
x = CTYpe(y, (integer, integer))
System.Console.WriteLine(x)
x = CType(CType(x, C1), (integer, integer))
System.Console.WriteLine(x)
End Sub
End Module
Class C1
Public Shared Narrowing Operator CType(arg as (long, long)) as C1
return new C1()
End Operator
Public Shared Narrowing Operator CType(arg as C1) as (c As Byte, d as Byte)
return (2, 2)
End Operator
End Class
</file>
</compilation>, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef}, expectedOutput:=<![CDATA[
(2, 2)
(2, 2)
]]>)
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 125 (0x7d)
.maxstack 2
.locals init (System.ValueTuple(Of Integer, Integer) V_0,
System.ValueTuple(Of Byte, Byte) V_1)
IL_0000: ldc.i4.1
IL_0001: ldc.i4.1
IL_0002: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)"
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer"
IL_000e: conv.i8
IL_000f: ldloc.0
IL_0010: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer"
IL_0015: conv.i8
IL_0016: newobj "Sub System.ValueTuple(Of Long, Long)..ctor(Long, Long)"
IL_001b: call "Function C1.op_Explicit((Long, Long)) As C1"
IL_0020: call "Function C1.op_Explicit(C1) As (c As Byte, d As Byte)"
IL_0025: stloc.1
IL_0026: ldloc.1
IL_0027: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte"
IL_002c: ldloc.1
IL_002d: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte"
IL_0032: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)"
IL_0037: dup
IL_0038: box "System.ValueTuple(Of Integer, Integer)"
IL_003d: call "Sub System.Console.WriteLine(Object)"
IL_0042: stloc.0
IL_0043: ldloc.0
IL_0044: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer"
IL_0049: conv.i8
IL_004a: ldloc.0
IL_004b: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer"
IL_0050: conv.i8
IL_0051: newobj "Sub System.ValueTuple(Of Long, Long)..ctor(Long, Long)"
IL_0056: call "Function C1.op_Explicit((Long, Long)) As C1"
IL_005b: call "Function C1.op_Explicit(C1) As (c As Byte, d As Byte)"
IL_0060: stloc.1
IL_0061: ldloc.1
IL_0062: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte"
IL_0067: ldloc.1
IL_0068: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte"
IL_006d: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)"
IL_0072: box "System.ValueTuple(Of Integer, Integer)"
IL_0077: call "Sub System.Console.WriteLine(Object)"
IL_007c: ret
}
]]>)
End Sub
<Fact()>
Public Sub ImplicitConversions03()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim x = (a:=1, b:=1)
Dim y As C1 = x
Dim x1 as (integer, integer)? = y
System.Console.WriteLine(x1)
x1 = CType(CType(x, C1), (integer, integer)?)
System.Console.WriteLine(x1)
End Sub
End Module
Class C1
Public Shared Widening Operator CType(arg as (long, long)) as C1
return new C1()
End Operator
Public Shared Widening Operator CType(arg as C1) as (c As Byte, d as Byte)
return (2, 2)
End Operator
End Class
</file>
</compilation>, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef}, expectedOutput:=<![CDATA[
(2, 2)
(2, 2)
]]>)
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 140 (0x8c)
.maxstack 3
.locals init (System.ValueTuple(Of Integer, Integer) V_0, //x
C1 V_1, //y
System.ValueTuple(Of Integer, Integer) V_2,
System.ValueTuple(Of Byte, Byte) V_3)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.1
IL_0003: ldc.i4.1
IL_0004: call "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)"
IL_0009: ldloc.0
IL_000a: stloc.2
IL_000b: ldloc.2
IL_000c: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer"
IL_0011: conv.i8
IL_0012: ldloc.2
IL_0013: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer"
IL_0018: conv.i8
IL_0019: newobj "Sub System.ValueTuple(Of Long, Long)..ctor(Long, Long)"
IL_001e: call "Function C1.op_Implicit((Long, Long)) As C1"
IL_0023: stloc.1
IL_0024: ldloc.1
IL_0025: call "Function C1.op_Implicit(C1) As (c As Byte, d As Byte)"
IL_002a: stloc.3
IL_002b: ldloc.3
IL_002c: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte"
IL_0031: ldloc.3
IL_0032: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte"
IL_0037: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)"
IL_003c: newobj "Sub (Integer, Integer)?..ctor((Integer, Integer))"
IL_0041: box "(Integer, Integer)?"
IL_0046: call "Sub System.Console.WriteLine(Object)"
IL_004b: ldloc.0
IL_004c: stloc.2
IL_004d: ldloc.2
IL_004e: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer"
IL_0053: conv.i8
IL_0054: ldloc.2
IL_0055: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer"
IL_005a: conv.i8
IL_005b: newobj "Sub System.ValueTuple(Of Long, Long)..ctor(Long, Long)"
IL_0060: call "Function C1.op_Implicit((Long, Long)) As C1"
IL_0065: call "Function C1.op_Implicit(C1) As (c As Byte, d As Byte)"
IL_006a: stloc.3
IL_006b: ldloc.3
IL_006c: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte"
IL_0071: ldloc.3
IL_0072: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte"
IL_0077: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)"
IL_007c: newobj "Sub (Integer, Integer)?..ctor((Integer, Integer))"
IL_0081: box "(Integer, Integer)?"
IL_0086: call "Sub System.Console.WriteLine(Object)"
IL_008b: ret
}
]]>)
End Sub
<Fact()>
Public Sub ImplicitConversions04()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim x = (1, (1, (1, (1, (1, (1, 1))))))
Dim y as C1 = x
Dim x2 as (integer, integer) = y
System.Console.WriteLine(x2)
Dim x3 as (integer, (integer, integer)) = y
System.Console.WriteLine(x3)
Dim x12 as (Integer, (Integer, (Integer, (Integer, (Integer, (Integer, (Integer, (Integer, (Integer, (Integer, (Integer, Integer))))))))))) = y
System.Console.WriteLine(x12)
End Sub
End Module
Class C1
Private x as Byte
Public Shared Widening Operator CType(arg as (long, C1)) as C1
Dim result = new C1()
result.x = arg.Item2.x
return result
End Operator
Public Shared Widening Operator CType(arg as (long, long)) as C1
Dim result = new C1()
result.x = CByte(arg.Item2)
return result
End Operator
Public Shared Widening Operator CType(arg as C1) as (c As Byte, d as C1)
Dim t = arg.x
arg.x += 1
return (CByte(t), arg)
End Operator
Public Shared Widening Operator CType(arg as C1) as (c As Byte, d as Byte)
Dim t1 = arg.x
arg.x += 1
Dim t2 = arg.x
arg.x += 1
return (CByte(t1), CByte(t2))
End Operator
End Class
</file>
</compilation>, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef}, expectedOutput:=<![CDATA[
(1, 2)
(3, (4, 5))
(6, (7, (8, (9, (10, (11, (12, (13, (14, (15, (16, 17)))))))))))
]]>)
End Sub
<Fact()>
Public Sub ExplicitConversions04()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim x = (1, (1, (1, (1, (1, (1, 1))))))
Dim y as C1 = x
Dim x2 as (integer, integer) = y
System.Console.WriteLine(x2)
Dim x3 as (integer, (integer, integer)) = y
System.Console.WriteLine(x3)
Dim x12 as (Integer, (Integer, (Integer, (Integer, (Integer, (Integer, (Integer, (Integer, (Integer, (Integer, (Integer, Integer))))))))))) = y
System.Console.WriteLine(x12)
End Sub
End Module
Class C1
Private x as Byte
Public Shared Narrowing Operator CType(arg as (long, C1)) as C1
Dim result = new C1()
result.x = arg.Item2.x
return result
End Operator
Public Shared Narrowing Operator CType(arg as (long, long)) as C1
Dim result = new C1()
result.x = CByte(arg.Item2)
return result
End Operator
Public Shared Narrowing Operator CType(arg as C1) as (c As Byte, d as C1)
Dim t = arg.x
arg.x += 1
return (CByte(t), arg)
End Operator
Public Shared Narrowing Operator CType(arg as C1) as (c As Byte, d as Byte)
Dim t1 = arg.x
arg.x += 1
Dim t2 = arg.x
arg.x += 1
return (CByte(t1), CByte(t2))
End Operator
End Class
</file>
</compilation>, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef}, expectedOutput:=<![CDATA[
(1, 2)
(3, (4, 5))
(6, (7, (8, (9, (10, (11, (12, (13, (14, (15, (16, 17)))))))))))
]]>)
End Sub
<Fact()>
Public Sub MethodTypeInference001()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
System.Console.WriteLine(Test((1,"q")))
End Sub
Function Test(of T1, T2)(x as (T1, T2)) as (T1, T2)
Console.WriteLine(Gettype(T1))
Console.WriteLine(Gettype(T2))
return x
End Function
End Module
</file>
</compilation>, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef}, expectedOutput:=<![CDATA[
System.Int32
System.String
(1, q)
]]>)
End Sub
<Fact()>
Public Sub MethodTypeInference002()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim v = (new Object(),"q")
Test(v)
System.Console.WriteLine(v)
End Sub
Function Test(of T)(x as (T, T)) as (T, T)
Console.WriteLine(Gettype(T))
return x
End Function
End Module
</file>
</compilation>, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef}, expectedOutput:=<![CDATA[
System.Object
(System.Object, q)
]]>)
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 51 (0x33)
.maxstack 3
.locals init (System.ValueTuple(Of Object, String) V_0)
IL_0000: newobj "Sub Object..ctor()"
IL_0005: ldstr "q"
IL_000a: newobj "Sub System.ValueTuple(Of Object, String)..ctor(Object, String)"
IL_000f: dup
IL_0010: stloc.0
IL_0011: ldloc.0
IL_0012: ldfld "System.ValueTuple(Of Object, String).Item1 As Object"
IL_0017: ldloc.0
IL_0018: ldfld "System.ValueTuple(Of Object, String).Item2 As String"
IL_001d: newobj "Sub System.ValueTuple(Of Object, Object)..ctor(Object, Object)"
IL_0022: call "Function C.Test(Of Object)((Object, Object)) As (Object, Object)"
IL_0027: pop
IL_0028: box "System.ValueTuple(Of Object, String)"
IL_002d: call "Sub System.Console.WriteLine(Object)"
IL_0032: ret
}
]]>)
End Sub
<Fact()>
Public Sub MethodTypeInference002Err()
Dim comp = CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module C
Sub Main()
Dim v = (new Object(),"q")
Test(v)
System.Console.WriteLine(v)
TestRef(v)
System.Console.WriteLine(v)
End Sub
Function Test(of T)(x as (T, T)) as (T, T)
Console.WriteLine(Gettype(T))
return x
End Function
Function TestRef(of T)(ByRef x as (T, T)) as (T, T)
Console.WriteLine(Gettype(T))
x.Item1 = x.Item2
return x
End Function
End Module
]]></file>
</compilation>, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef})
comp.AssertTheseDiagnostics(
<errors>
BC36651: Data type(s) of the type parameter(s) in method 'Public Function TestRef(Of T)(ByRef x As (T, T)) As (T, T)' cannot be inferred from these arguments because more than one type is possible. Specifying the data type(s) explicitly might correct this error.
TestRef(v)
~~~~~~~
</errors>)
End Sub
<Fact()>
Public Sub MethodTypeInference003()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
System.Console.WriteLine(Test((Nothing,"q")))
End Sub
Function Test(of T)(x as (T, T)) as (T, T)
Console.WriteLine(Gettype(T))
return x
End Function
End Module
</file>
</compilation>, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef}, expectedOutput:=<![CDATA[
System.String
(, q)
]]>)
End Sub
<Fact()>
Public Sub MethodTypeInference004()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module C
Sub Main()
System.Console.WriteLine(Test((new Object(),"q")))
System.Console.WriteLine(Test1((new Object(),"q")))
End Sub
Function Test(of T)(x as (T, T)) as (T, T)
Console.WriteLine(Gettype(T))
return x
End Function
Function Test1(of T)(x as T) as T
Console.WriteLine(Gettype(T))
return x
End Function
End Module
</file>
</compilation>, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef}, expectedOutput:=<![CDATA[
System.Object
(System.Object, q)
System.ValueTuple`2[System.Object,System.String]
(System.Object, q)
]]>)
End Sub
<Fact()>
Public Sub MethodTypeInference004Err()
Dim comp = CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module C
Sub Main()
Dim q = "q"
Dim a as object = "a"
System.Console.WriteLine(Test((q, a)))
System.Console.WriteLine(q)
System.Console.WriteLine(a)
End Sub
Function Test(of T)(byref x as (T, T)) as (T, T)
Console.WriteLine(Gettype(T))
x.Item1 = x.Item2
return x
End Function
End Module
]]></file>
</compilation>, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef})
comp.AssertTheseDiagnostics(
<errors>
BC36651: Data type(s) of the type parameter(s) in method 'Public Function Test(Of T)(ByRef x As (T, T)) As (T, T)' cannot be inferred from these arguments because more than one type is possible. Specifying the data type(s) explicitly might correct this error.
System.Console.WriteLine(Test((q, a)))
~~~~
</errors>)
End Sub
<Fact()>
Public Sub MethodTypeInference005()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Collections.Generic
Module Module1
Sub Main()
Dim ie As IEnumerable(Of String) = {1, 2}
Dim t = (ie, ie)
Test(t, New Object)
Test((ie, ie), New Object)
End Sub
Sub Test(Of T)(a1 As (IEnumerable(Of T), IEnumerable(Of T)), a2 As T)
System.Console.WriteLine(GetType(T))
End Sub
End Module
</file>
</compilation>, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef}, expectedOutput:=<![CDATA[
System.Object
System.Object
]]>)
End Sub
<Fact()>
Public Sub MethodTypeInference006()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Collections.Generic
Module Module1
Sub Main()
Dim ie As IEnumerable(Of Integer) = {1, 2}
Dim t = (ie, ie)
Test(t)
Test((1, 1))
End Sub
Sub Test(Of T)(f1 As IComparable(Of (T, T)))
System.Console.WriteLine(GetType(T))
End Sub
End Module
</file>
</compilation>, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef}, expectedOutput:=<![CDATA[
System.Collections.Generic.IEnumerable`1[System.Int32]
System.Int32
]]>)
End Sub
<Fact()>
Public Sub MethodTypeInference007()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Collections.Generic
Module Module1
Sub Main()
Dim ie As IEnumerable(Of Integer) = {1, 2}
Dim t = (ie, ie)
Test(t)
Test((1, 1))
End Sub
Sub Test(Of T)(f1 As IComparable(Of (T, T)))
System.Console.WriteLine(GetType(T))
End Sub
End Module
</file>
</compilation>, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef}, expectedOutput:=<![CDATA[
System.Collections.Generic.IEnumerable`1[System.Int32]
System.Int32
]]>)
End Sub
<Fact()>
Public Sub MethodTypeInference008()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Collections.Generic
Module Module1
Sub Main()
Dim t = (1, 1L)
' these are valid
Test1(t)
Test1((1, 1L))
End Sub
Sub Test1(Of T)(f1 As (T, T))
System.Console.WriteLine(GetType(T))
End Sub
End Module
</file>
</compilation>, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef}, expectedOutput:=<![CDATA[
System.Int64
System.Int64
]]>)
End Sub
<Fact()>
Public Sub MethodTypeInference008Err()
Dim comp = CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Collections.Generic
Module Module1
Sub Main()
Dim t = (1, 1L)
' these are valid
Test1(t)
Test1((1, 1L))
' these are not
Test2(t)
Test2((1, 1L))
End Sub
Sub Test1(Of T)(f1 As (T, T))
System.Console.WriteLine(GetType(T))
End Sub
Sub Test2(Of T)(f1 As IComparable(Of (T, T)))
System.Console.WriteLine(GetType(T))
End Sub
End Module
]]></file>
</compilation>, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef})
comp.AssertTheseDiagnostics(
<errors>
BC36657: Data type(s) of the type parameter(s) in method 'Public Sub Test2(Of T)(f1 As IComparable(Of (T, T)))' cannot be inferred from these arguments because they do not convert to the same type. Specifying the data type(s) explicitly might correct this error.
Test2(t)
~~~~~
BC36657: Data type(s) of the type parameter(s) in method 'Public Sub Test2(Of T)(f1 As IComparable(Of (T, T)))' cannot be inferred from these arguments because they do not convert to the same type. Specifying the data type(s) explicitly might correct this error.
Test2((1, 1L))
~~~~~
</errors>)
End Sub
<Fact()>
Public Sub Inference04()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Test( Function(x)x.y )
Test( Function(x)x.bob )
End Sub
Sub Test(of T)(x as Func(of (x as Byte, y As Byte), T))
System.Console.WriteLine("first")
System.Console.WriteLine(x((2,3)).ToString())
End Sub
Sub Test(of T)(x as Func(of (alice as integer, bob as integer), T))
System.Console.WriteLine("second")
System.Console.WriteLine(x((4,5)).ToString())
End Sub
End Module
</file>
</compilation>, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef}, expectedOutput:=<![CDATA[
first
3
second
5
]]>)
End Sub
<Fact()>
Public Sub Inference07()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Test(Function(x)(x, x), Function(t)1)
Test1(Function(x)(x, x), Function(t)1)
Test2((a:= 1, b:= 2), Function(t)(t.a, t.b))
End Sub
Sub Test(Of U)(f1 as Func(of Integer, ValueTuple(Of U, U)), f2 as Func(Of ValueTuple(Of U, U), Integer))
System.Console.WriteLine(f2(f1(1)))
End Sub
Sub Test1(of U)(f1 As Func(of integer, (U, U)), f2 as Func(Of (U, U), integer))
System.Console.WriteLine(f2(f1(1)))
End Sub
Sub Test2(of U, T)(f1 as U , f2 As Func(Of U, (x as T, y As T)))
System.Console.WriteLine(f2(f1).y)
End Sub
End Module
</file>
</compilation>, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef}, expectedOutput:=<![CDATA[
1
1
2
]]>)
End Sub
<Fact()>
Public Sub InferenceChain001()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Test(Function(x As (Integer, Integer)) (x, x), Function(t) (t, t))
End Sub
Sub Test(Of T, U, V)(f1 As Func(Of (T,T), (U,U)), f2 As Func(Of (U,U), (V,V)))
System.Console.WriteLine(f2(f1(Nothing)))
System.Console.WriteLine(GetType(T))
System.Console.WriteLine(GetType(U))
System.Console.WriteLine(GetType(V))
End Sub
End Module
</file>
</compilation>, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef}, expectedOutput:=<![CDATA[
(((0, 0), (0, 0)), ((0, 0), (0, 0)))
System.Int32
System.ValueTuple`2[System.Int32,System.Int32]
System.ValueTuple`2[System.ValueTuple`2[System.Int32,System.Int32],System.ValueTuple`2[System.Int32,System.Int32]]
]]>)
End Sub
<Fact()>
Public Sub InferenceChain002()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Test(Function(x As (Integer, Object)) (x, x), Function(t) (t, t))
End Sub
Sub Test(Of T, U, V)(ByRef f1 As Func(Of (T, T), (U, U)), ByRef f2 As Func(Of (U, U), (V, V)))
System.Console.WriteLine(f2(f1(Nothing)))
System.Console.WriteLine(GetType(T))
System.Console.WriteLine(GetType(U))
System.Console.WriteLine(GetType(V))
End Sub
End Module
</file>
</compilation>, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef}, expectedOutput:=<![CDATA[
(((0, ), (0, )), ((0, ), (0, )))
System.Object
System.ValueTuple`2[System.Int32,System.Object]
System.ValueTuple`2[System.ValueTuple`2[System.Int32,System.Object],System.ValueTuple`2[System.Int32,System.Object]]
]]>)
End Sub
End Class
End Namespace
|
KiloBravoLima/roslyn
|
src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenTuples.vb
|
Visual Basic
|
apache-2.0
| 75,104
|
'*******************************************************************************************'
' '
' Download Free Evaluation Version From: https://bytescout.com/download/web-installer '
' '
' Also available as Web API! Get free API Key https://app.pdf.co/signup '
' '
' Copyright © 2017-2020 ByteScout, Inc. All rights reserved. '
' https://www.bytescout.com '
' https://www.pdf.co '
'*******************************************************************************************'
Imports Bytescout.PDFExtractor
Class Program
Friend Shared Sub Main(args As String())
' Create Bytescout.PDFExtractor.CSVExtractor instance
Dim jsonExtractor As New JSONExtractor()
jsonExtractor.RegistrationName = "demo"
jsonExtractor.RegistrationKey = "demo"
' Create Bytescout.PDFExtractor.TableDetector instance
Dim tableDetector As New TableDetector()
tableDetector.RegistrationName = "demo"
tableDetector.RegistrationKey = "demo"
' We should define what kind of tables we should detect.
' So we set min required number of columns to 3 ...
tableDetector.DetectionMinNumberOfColumns = 3
' ... and we set min required number of rows to 3
tableDetector.DetectionMinNumberOfRows = 3
' Set table detection mode to "bordered tables" - best for tables with closed solid borders.
tableDetector.ColumnDetectionMode = ColumnDetectionMode.BorderedTables
' Load sample PDF document
jsonExtractor.LoadDocumentFromFile(".\sample3.pdf")
tableDetector.LoadDocumentFromFile(".\sample3.pdf")
' Get page count
Dim pageCount As Integer = tableDetector.GetPageCount()
' Iterate through pages
For i As Integer = 0 To pageCount - 1
Dim t As Integer = 1
' Find first table and continue if found
If (tableDetector.FindTable(i)) Then
Do
' Set extraction area for JSON extractor to rectangle received from the table detector
jsonExtractor.SetExtractionArea(tableDetector.FoundTableLocation)
' Export the table to JSON file
jsonExtractor.SaveJSONToFile(i, "page-" + i.ToString() + "-table-" + t.ToString() + ".json")
t = t + 1
Loop While tableDetector.FindNextTable()
End If
Next
' Cleanup
jsonExtractor.Dispose()
tableDetector.Dispose()
' Open first output file in default associated application (for demo purposes)
System.Diagnostics.Process.Start("page-0-table-1.json")
End Sub
End Class
|
bytescout/ByteScout-SDK-SourceCode
|
PDF Extractor SDK/VB.NET/Find Table in PDF And Extract As JSON/Program.vb
|
Visual Basic
|
apache-2.0
| 3,174
|
Imports System
Imports Microsoft.SPOT
Imports Toolbox.NETMF
Imports Toolbox.NETMF.NET
' Copyright 2012-2014 Stefan Thoolen (http://www.netmftoolbox.com/)
'
' 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.
Namespace Programs
Public Module Ntp
''' <summary>
''' Binds to the Shell Core
''' </summary>
''' <param name="Shell">The ShellCore object</param>
Public Sub Bind(Shell As ShellCore)
AddHandler Shell.OnCommandReceived, AddressOf Shell_OnCommandReceived
End Sub
''' <summary>
''' Unbinds from the Shell Core
''' </summary>
''' <param name="Shell">The ShellCore object</param>
Public Sub Unbind(Shell As ShellCore)
RemoveHandler Shell.OnCommandReceived, AddressOf Shell_OnCommandReceived
End Sub
''' <summary>
''' Triggered when a command has been given
''' </summary>
''' <param name="Shell">Reference to the shell</param>
''' <param name="Arguments">Command line arguments</param>
''' <param name="SuspressError">Set to 'true' if you could do anything with the command</param>
''' <param name="Time">Current timestamp</param>
Private Sub Shell_OnCommandReceived(Shell As ShellCore, Arguments() As String, ByRef SuspressError As Boolean, Time As DateTime)
Select Case Arguments(0).ToUpper()
Case "NTPSYNC"
If Arguments.Length <> 2 Then
Throw New ArgumentException("Need 1 parameter, see HELP NTPSYNC for more info.")
Else
Ntp.Sync(Shell.Telnetserver, Arguments(1))
End If
SuspressError = True
Case "HELP"
Dim PageFound As Boolean = False
If Arguments.Length = 1 Then
PageFound = Ntp.DoHelp(Shell.Telnetserver, "")
Else
PageFound = Ntp.DoHelp(Shell.Telnetserver, Arguments(1).ToUpper())
End If
If PageFound Then SuspressError = True
End Select
End Sub
''' <summary>
''' Shows a specific help page
''' </summary>
''' <param name="Server">The telnet server object</param>
''' <param name="Page">The page</param>
''' <returns>True when the page exists</returns>
Private Function DoHelp(Server As TelnetServer, Page As String) As Boolean
Select Case Page
Case ""
Server.Print("NTPSYNC [HOSTNAME] Synchronizes with a timeserver")
Return True
Case "NTPSYNC"
Server.Print("NTPSYNC [HOSTNAME] Synchronizes with a timeserver")
Server.Print("- [HOSTNAME] The hostname of an NTP-server (example: pool.ntp.org)")
Return True
Case Else
Return False
End Select
End Function
''' <summary>
''' Synchronizes with an NTP-server
''' </summary>
''' <param name="Server">The telnet server object</param>
''' <param name="NtpServer">Hostname of the NTP server</param>
Private Sub Sync(Server As TelnetServer, NtpServer As String)
Dim Client As SNTP_Client = New SNTP_Client(New IntegratedSocket(NtpServer, 123))
Client.Synchronize()
Server.Print("Current time: " + DateTime.Now.ToString())
End Sub
End Module
End Namespace
|
JakeLardinois/NetMF.Toolbox
|
Samples/Visual Basic/Terminal Server/Programs/Ntp.vb
|
Visual Basic
|
apache-2.0
| 4,129
|
Imports BVSoftware.Bvc5.Core
Imports System.Data
Imports System.Collections.ObjectModel
Partial Class BVModules_ContentBlocks_Order_Activity_view
Inherits Content.BVModule
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
LoadOrders()
End If
End Sub
Private Sub LoadOrders()
Dim s As String = String.Empty
s = SettingsManager.GetSetting("Status")
Select Case s
Case "Payment"
LoadPaymentStatus()
Case "Shipping"
LoadShippingStatus()
Case "Other"
LoadOtherStatus()
End Select
End Sub
Public Sub LoadPaymentStatus()
Dim c As New Orders.OrderSearchCriteria
Dim v As String = String.Empty
v = SettingsManager.GetSetting("Value")
Me.Title.Text = "Last 10 Orders with Payment Status: " & v.ToString
Select Case v
Case "Unknown"
c.PaymentStatus = Orders.OrderPaymentStatus.Unknown
Case "Unpaid"
c.PaymentStatus = Orders.OrderPaymentStatus.Unpaid
Case "PartiallyPaid"
c.PaymentStatus = Orders.OrderPaymentStatus.PartiallyPaid
Case "Paid"
c.PaymentStatus = Orders.OrderPaymentStatus.Paid
Case "Overpaid"
c.PaymentStatus = Orders.OrderPaymentStatus.Overpaid
End Select
Dim found As New Collection(Of Orders.Order)
found = Orders.Order.FindByCriteria(c)
Dim newFound As New Collection(Of Orders.Order)
Dim i As Integer = 0
If found.Count > 10 Then
While i < 10
newFound.Add(found.Item(i))
i += 1
End While
Else
Dim f As Integer = 0
While f < found.Count
newFound.Add(found.Item(f))
f += 1
End While
End If
Me.OrderActivityDataList.DataSource = newFound
Me.OrderActivityDataList.DataBind()
Me.OrderActivityDataList.RepeatDirection = SettingsManager.GetIntegerSetting("DisplayTypeRad")
If SettingsManager.GetIntegerSetting("DisplayTypeRad") = 1 Then
Me.OrderActivityDataList.RepeatColumns = 1
Else
Me.OrderActivityDataList.RepeatColumns = SettingsManager.GetIntegerSetting("GridColumnsField")
End If
End Sub
Public Sub LoadShippingStatus()
Dim c As New Orders.OrderSearchCriteria
Dim v As String = String.Empty
v = SettingsManager.GetSetting("Value")
Me.Title.Text = "Last 10 Orders with Shipping Status: " & v.ToString
Select Case v
Case "Unknown"
c.ShippingStatus = Orders.OrderShippingStatus.Unknown
Case "Unshipped"
c.ShippingStatus = Orders.OrderShippingStatus.Unshipped
Case "PartiallyShipped"
c.ShippingStatus = Orders.OrderShippingStatus.PartiallyShipped
Case "FullyShipped"
c.ShippingStatus = Orders.OrderShippingStatus.FullyShipped
Case "NonShipping"
c.ShippingStatus = Orders.OrderShippingStatus.NonShipping
End Select
Dim found As New Collection(Of Orders.Order)
found = Orders.Order.FindByCriteria(c)
Dim newFound As New Collection(Of Orders.Order)
Dim i As Integer = 0
If found.Count > 10 Then
While i < 10
newFound.Add(found.Item(i))
i += 1
End While
Else
Dim f As Integer = 0
While f < found.Count
newFound.Add(found.Item(f))
f += 1
End While
End If
Me.OrderActivityDataList.DataSource = newFound
Me.OrderActivityDataList.DataBind()
Me.OrderActivityDataList.RepeatDirection = SettingsManager.GetIntegerSetting("DisplayTypeRad")
If SettingsManager.GetIntegerSetting("DisplayTypeRad") = 1 Then
Me.OrderActivityDataList.RepeatColumns = 1
Else
Me.OrderActivityDataList.RepeatColumns = SettingsManager.GetIntegerSetting("GridColumnsField")
End If
End Sub
Public Sub LoadOtherStatus()
Dim c As New Orders.OrderSearchCriteria
Dim v As String = SettingsManager.GetSetting("OtherStatusBvin")
Dim o As Orders.OrderStatusCode = Orders.OrderStatusCode.FindByBvin(v)
c.StatusCode = v
Dim found As New Collection(Of Orders.Order)
found = Orders.Order.FindByCriteria(c)
If found.Count = 0 Then
Me.Title.Text = "No Orders Found"
Else
Me.Title.Text = "Last 10 Orders with Status: " & o.StatusName
Dim newFound As New Collection(Of Orders.Order)
Dim i As Integer = 0
If found.Count > 10 Then
While i < 10
newFound.Add(found.Item(i))
i += 1
End While
Else
Dim f As Integer = 0
While f < found.Count
newFound.Add(found.Item(f))
f += 1
End While
End If
Me.OrderActivityDataList.DataSource = newFound
Me.OrderActivityDataList.DataBind()
Me.OrderActivityDataList.RepeatDirection = SettingsManager.GetIntegerSetting("DisplayTypeRad")
If SettingsManager.GetIntegerSetting("DisplayTypeRad") = 1 Then
Me.OrderActivityDataList.RepeatColumns = 1
Else
Me.OrderActivityDataList.RepeatColumns = SettingsManager.GetIntegerSetting("GridColumnsField")
End If
End If
End Sub
Protected Sub OrderActivityDataList_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataListCommandEventArgs) Handles OrderActivityDataList.ItemCommand
If e.CommandName = "Go" Then
Dim OrderID As String = e.CommandArgument.ToString
Response.Redirect("~/BVAdmin/Orders/ViewOrder.aspx?id=" & OrderID & "")
End If
End Sub
End Class
|
ajaydex/Scopelist_2015
|
BVModules/ContentBlocks/Order Activity/view.ascx.vb
|
Visual Basic
|
apache-2.0
| 6,248
|
Imports System.ComponentModel
Imports System.Dynamic
Namespace ActiveRecord
Partial Public MustInherit Class Entity
Inherits DynamicObject
Public Shared Function GetCount(Of TValue)(
conditionSqlStatement As String,
sqlParams As Dictionary(Of String, Object),
connection As Connection
) As Long
Return connection.GetProviderResource().GetCount(
conditionSqlStatement, sqlParams, connection,
MetaDescriptor.GetClassDescription(GetType(TValue))
)
End Function
Public Shared Function GetCount(Of TValue)(
conditionSqlStatement As String,
sqlParams As Dictionary(Of String, Object),
transaction As Transaction
) As Long
Return transaction.ConnectionWrapper.GetProviderResource().GetCount(
conditionSqlStatement, sqlParams, transaction,
MetaDescriptor.GetClassDescription(GetType(TValue))
)
End Function
Public Shared Function GetCount(Of TValue)(
conditionSqlStatement As String,
sqlParams As Dictionary(Of String, Object),
Optional connectionIndex As Integer? = Nothing
) As Long
Return Entity.GetCount(Of TValue)(
conditionSqlStatement, sqlParams, Connection.Get(If(
connectionIndex.HasValue,
connectionIndex.Value,
Tools.GetConnectionIndexByClassAttr(GetType(TValue), True)
))
)
End Function
Public Shared Function GetCount(Of TValue)(
conditionSqlStatement As String,
sqlParams As Object,
connection As Connection
) As Long
Return connection.GetProviderResource().GetCount(
conditionSqlStatement, sqlParams, connection,
MetaDescriptor.GetClassDescription(GetType(TValue))
)
End Function
Public Shared Function GetCount(Of TValue)(
conditionSqlStatement As String,
sqlParams As Object,
transaction As Transaction
) As Long
Return transaction.ConnectionWrapper.GetProviderResource().GetCount(
conditionSqlStatement, sqlParams, transaction,
MetaDescriptor.GetClassDescription(GetType(TValue))
)
End Function
Public Shared Function GetCount(Of TValue)(
Optional conditionSqlStatement As String = "",
Optional sqlParams As Object = Nothing,
Optional connectionIndex As Integer? = Nothing
) As Long
Return Entity.GetCount(Of TValue)(
conditionSqlStatement, sqlParams,
Connection.Get(If(
connectionIndex.HasValue,
connectionIndex.Value,
Tools.GetConnectionIndexByClassAttr(GetType(TValue), True)
))
)
End Function
End Class
End Namespace
|
databasic-net/databasic-core
|
ActiveRecord/Entity/DatabaseGetters/GetCount.vb
|
Visual Basic
|
bsd-3-clause
| 2,453
|
' 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.
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Queries
Public Class EqualsKeywordRecommenderTests
<WorkItem(543136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543136")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub EqualsAfterJoinInOnIdentifierTest()
Dim method = <MethodBody>
Dim arr = New Integer() {4, 5}
Dim q2 = From num In arr Join n1 In arr On num |
</MethodBody>
VerifyRecommendationsAreExactly(method, "Equals")
End Sub
<WorkItem(543136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543136")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub EqualsAfterJoinInOnBinaryExpressionTest()
Dim method = <MethodBody>
Dim arr = New Integer() {4, 5}
Dim q2 = From num In arr Join n1 In arr On num + 5L |
</MethodBody>
VerifyRecommendationsAreExactly(method, "Equals")
End Sub
End Class
End Namespace
|
physhi/roslyn
|
src/EditorFeatures/VisualBasicTest/Recommendations/Queries/EqualsKeywordRecommenderTests.vb
|
Visual Basic
|
apache-2.0
| 1,407
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Threading
Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Editor.VisualBasic
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.EndConstructGeneration
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.VisualStudio.Text
Imports Microsoft.VisualStudio.Text.Editor
Imports Microsoft.VisualStudio.Text.Operations
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EndConstructGeneration
Public Class MiscellaneousTests
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Async Function DoesNothingOnEmptyFile() As Tasks.Task
Await VerifyStatementEndConstructNotAppliedAsync(
text:="",
caret:={0, -1})
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Async Function DoesNothingOnFileWithNoStatement() As Tasks.Task
Await VerifyStatementEndConstructNotAppliedAsync(
text:="'Foo
",
caret:={0, -1})
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Async Function VerifyLineContinuationMark() As Tasks.Task
Await VerifyStatementEndConstructNotAppliedAsync(
text:="Class C
function f(byval x as Integer,
byref y as string) as string
for i = 1 to 10 _
return y
End Function
End Class",
caret:={3, -1})
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Async Function VerifyImplicitLineContinuation() As Tasks.Task
Await VerifyStatementEndConstructNotAppliedAsync(
text:="Class C
function f() as string
While 1 +
return y
End Function
End Class",
caret:={2, -1})
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Async Function TestVerifyNestedDo() As Task
Await VerifyStatementEndConstructAppliedAsync(
before:="Class C
function f() as string
for i = 1 to 10",
beforeCaret:={2, -1},
after:="Class C
function f() as string
for i = 1 to 10
Next",
afterCaret:={3, -1})
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Async Function TestVerifyMultilinesChar() As Task
Await VerifyStatementEndConstructAppliedAsync(
before:="Class C
sub s
do :do
Loop
End sub
End Class",
beforeCaret:={2, -1},
after:="Class C
sub s
do :do
Loop
Loop
End sub
End Class",
afterCaret:={3, -1})
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Async Function TestVerifyInlineComments() As Task
Await VerifyStatementEndConstructAppliedAsync(
before:="Class C
sub s
If true then 'here
End sub
End Class",
beforeCaret:={2, -1},
after:="Class C
sub s
If true then 'here
End If
End sub
End Class",
afterCaret:={3, -1})
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Async Function VerifyNotAppliedWithJunkAtEndOfLine() As Tasks.Task
' Try this without a newline at the end of the file
Await VerifyStatementEndConstructNotAppliedAsync(
text:="Class C End Class",
caret:={0, "Class C".Length})
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Async Function VerifyNotAppliedWithJunkAtEndOfLine2() As Tasks.Task
' Try this with a newline at the end of the file
Await VerifyStatementEndConstructNotAppliedAsync(
text:="Class C End Class
",
caret:={0, "Class C".Length})
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
<WorkItem(539727, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539727")>
Public Async Function DeletesSelectedText() As Tasks.Task
Using workspace = Await TestWorkspace.CreateVisualBasicAsync("Interface IFoo ~~")
Dim textView = workspace.Documents.Single().GetTextView()
Dim subjectBuffer = workspace.Documents.First().GetTextBuffer()
' Select the ~~ backwards, so the caret location is at the start
Dim startPoint = New SnapshotPoint(textView.TextSnapshot, textView.TextSnapshot.Length - 2)
textView.TryMoveCaretToAndEnsureVisible(startPoint)
textView.SetSelection(New SnapshotSpan(startPoint, length:=2))
Dim endConstructService As New VisualBasicEndConstructService(
workspace.GetService(Of ISmartIndentationService),
workspace.GetService(Of ITextUndoHistoryRegistry),
workspace.GetService(Of IEditorOperationsFactoryService),
workspace.GetService(Of IEditorOptionsFactoryService))
Assert.True(endConstructService.TryDoEndConstructForEnterKey(textView, textView.TextSnapshot.TextBuffer, CancellationToken.None))
Assert.Equal("End Interface", textView.TextSnapshot.Lines.Last().GetText())
End Using
End Function
End Class
End Namespace
|
ericfe-ms/roslyn
|
src/EditorFeatures/VisualBasicTest/EndConstructGeneration/MiscellaneousTests.vb
|
Visual Basic
|
apache-2.0
| 6,017
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System
Imports System.Collections.Generic
Imports System.Collections.Immutable
Imports System.Reflection
Imports System.Runtime.InteropServices
Imports System.Text
Imports System.Threading
Imports Microsoft.CodeAnalysis.CodeGen
Imports Microsoft.CodeAnalysis.Collections
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' Represents an attribute applied to a Symbol.
''' </summary>
Friend MustInherit Class VisualBasicAttributeData
Inherits AttributeData
Private _lazyIsSecurityAttribute As ThreeState = ThreeState.Unknown
''' <summary>
''' Gets the attribute class being applied.
''' </summary>
Public MustOverride Shadows ReadOnly Property AttributeClass As NamedTypeSymbol
''' <summary>
''' Gets the constructor used in this application of the attribute.
''' </summary>
Public MustOverride Shadows ReadOnly Property AttributeConstructor As MethodSymbol
''' <summary>
''' Gets a reference to the source for this application of the attribute. Returns null for applications of attributes on metadata Symbols.
''' </summary>
Public MustOverride Shadows ReadOnly Property ApplicationSyntaxReference As SyntaxReference
''' <summary>
''' Gets the list of constructor arguments specified by this application of the attribute. This list contains both positional arguments
''' and named arguments that are formal parameters to the constructor.
''' </summary>
Public Shadows ReadOnly Property ConstructorArguments As IEnumerable(Of TypedConstant)
Get
Return Me.CommonConstructorArguments
End Get
End Property
''' <summary>
''' Gets the list of named field or property value arguments specified by this application of the attribute.
''' </summary>
Public Shadows ReadOnly Property NamedArguments As IEnumerable(Of KeyValuePair(Of String, TypedConstant))
Get
Return Me.CommonNamedArguments
End Get
End Property
''' <summary>
''' Compares the namespace and type name with the attribute's namespace and type name. Returns true if they are the same.
''' </summary>
Friend Overridable Function IsTargetAttribute(
namespaceName As String,
typeName As String,
Optional ignoreCase As Boolean = False
) As Boolean
If AttributeClass.IsErrorType() AndAlso Not TypeOf AttributeClass Is MissingMetadataTypeSymbol Then
' Can't guarantee complete name information.
Return False
End If
Dim options As StringComparison = If(ignoreCase, StringComparison.OrdinalIgnoreCase, StringComparison.Ordinal)
Return AttributeClass.HasNameQualifier(namespaceName, options) AndAlso
AttributeClass.Name.Equals(typeName, options)
End Function
Friend Function IsTargetAttribute(targetSymbol As Symbol, description As AttributeDescription) As Boolean
Return GetTargetAttributeSignatureIndex(targetSymbol, description) <> -1
End Function
Friend MustOverride Function GetTargetAttributeSignatureIndex(targetSymbol As Symbol, description As AttributeDescription) As Integer
''' <summary>
''' Checks if an applied attribute with the given attributeType matches the namespace name and type name of the given early attribute's description
''' and the attribute description has a signature with parameter count equal to the given attribute syntax's argument list count.
''' NOTE: We don't allow early decoded attributes to have optional parameters.
''' </summary>
Friend Overloads Shared Function IsTargetEarlyAttribute(attributeType As NamedTypeSymbol, attributeSyntax As AttributeSyntax, description As AttributeDescription) As Boolean
Debug.Assert(Not attributeType.IsErrorType())
Dim argumentCount As Integer = If(attributeSyntax.ArgumentList IsNot Nothing,
attributeSyntax.ArgumentList.Arguments.Where(Function(arg) arg.Kind = SyntaxKind.SimpleArgument AndAlso Not arg.IsNamed).Count,
0)
Return AttributeData.IsTargetEarlyAttribute(attributeType, argumentCount, description)
End Function
''' <summary>
''' Returns the <see cref="System.String"/> that represents the current AttributeData.
''' </summary>
''' <returns>A <see cref="System.String"/> that represents the current AttributeData.</returns>
Public Overrides Function ToString() As String
If Me.AttributeClass IsNot Nothing Then
Dim className As String = Me.AttributeClass.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat)
If Not Me.CommonConstructorArguments.Any() And Not Me.CommonNamedArguments.Any() Then
Return className
End If
Dim pooledStrbuilder = PooledStringBuilder.GetInstance()
Dim stringBuilder As StringBuilder = pooledStrbuilder.Builder
stringBuilder.Append(className)
stringBuilder.Append("(")
Dim first As Boolean = True
For Each constructorArgument In Me.CommonConstructorArguments
If Not first Then
stringBuilder.Append(", ")
End If
stringBuilder.Append(constructorArgument.ToVisualBasicString())
first = False
Next
For Each namedArgument In Me.CommonNamedArguments
If Not first Then
stringBuilder.Append(", ")
End If
stringBuilder.Append(namedArgument.Key)
stringBuilder.Append(":=")
stringBuilder.Append(namedArgument.Value.ToVisualBasicString())
first = False
Next
stringBuilder.Append(")")
Return pooledStrbuilder.ToStringAndFree()
End If
Return MyBase.ToString()
End Function
#Region "AttributeData Implementation"
''' <summary>
''' Gets the attribute class being applied as an <see cref="INamedTypeSymbol"/>
''' </summary>
Protected Overrides ReadOnly Property CommonAttributeClass As INamedTypeSymbol
Get
Return AttributeClass()
End Get
End Property
''' <summary>
''' Gets the constructor used in this application of the attribute as an <see cref="IMethodSymbol"/>.
''' </summary>
Protected Overrides ReadOnly Property CommonAttributeConstructor As IMethodSymbol
Get
Return AttributeConstructor()
End Get
End Property
''' <summary>
''' Gets a reference to the source for this application of the attribute. Returns null for applications of attributes on metadata Symbols.
''' </summary>
Protected Overrides ReadOnly Property CommonApplicationSyntaxReference As SyntaxReference
Get
Return ApplicationSyntaxReference()
End Get
End Property
#End Region
#Region "Attribute Decoding"
Friend Function IsSecurityAttribute(comp As VisualBasicCompilation) As Boolean
' CLI spec (Partition II Metadata), section 21.11 "DeclSecurity : 0x0E" states:
' SPEC: If the attribute's type is derived (directly or indirectly) from System.Security.Permissions.SecurityAttribute then
' SPEC: it is a security custom attribute and requires special treatment.
If _lazyIsSecurityAttribute = ThreeState.Unknown Then
_lazyIsSecurityAttribute = Me.AttributeClass.IsOrDerivedFromWellKnownClass(WellKnownType.System_Security_Permissions_SecurityAttribute, comp, useSiteDiagnostics:=Nothing).ToThreeState()
End If
Return _lazyIsSecurityAttribute.Value
End Function
Friend Sub DecodeSecurityAttribute(Of T As {WellKnownAttributeData, ISecurityAttributeTarget, New})(targetSymbol As Symbol, compilation As VisualBasicCompilation, ByRef arguments As DecodeWellKnownAttributeArguments(Of AttributeSyntax, VisualBasicAttributeData, AttributeLocation))
Dim hasErrors As Boolean = False
Dim action As DeclarativeSecurityAction = Me.DecodeSecurityAttributeAction(targetSymbol, compilation, arguments.AttributeSyntaxOpt, hasErrors, arguments.Diagnostics)
If Not hasErrors Then
Dim data As T = arguments.GetOrCreateData(Of T)()
Dim securityData As SecurityWellKnownAttributeData = data.GetOrCreateData()
securityData.SetSecurityAttribute(arguments.Index, action, arguments.AttributesCount)
If Me.IsTargetAttribute(targetSymbol, AttributeDescription.PermissionSetAttribute) Then
Dim resolvedPathForFixup As String = Me.DecodePermissionSetAttribute(compilation, arguments)
If resolvedPathForFixup IsNot Nothing Then
securityData.SetPathForPermissionSetAttributeFixup(arguments.Index, resolvedPathForFixup, arguments.AttributesCount)
End If
End If
End If
End Sub
Private Function DecodeSecurityAttributeAction(
targetSymbol As Symbol,
compilation As VisualBasicCompilation,
nodeOpt As AttributeSyntax,
ByRef hasErrors As Boolean,
diagnostics As DiagnosticBag
) As DeclarativeSecurityAction
Debug.Assert(Not hasErrors)
Debug.Assert(Me.IsSecurityAttribute(compilation))
Debug.Assert(targetSymbol.Kind = SymbolKind.Assembly OrElse targetSymbol.Kind = SymbolKind.NamedType OrElse targetSymbol.Kind = SymbolKind.Method)
If Me.AttributeConstructor.ParameterCount = 0 Then
' NOTE: Security custom attributes must have a valid SecurityAction as its first argument, we have none here.
' NOTE: Ideally, we should always generate 'BC31205: First argument to a security attribute must be a valid SecurityAction' for this case.
' NOTE: However, native compiler allows applying System.Security.Permissions.HostProtectionAttribute attribute without any argument and uses
' NOTE: SecurityAction.LinkDemand as the default SecurityAction in this case. We maintain compatibility with the native compiler for this case.
' BREAKING CHANGE: Even though the native compiler intends to allow only HostProtectionAttribute to be applied without any arguments,
' it doesn't quite do this correctly
' The implementation issue leads to the native compiler allowing any user defined security attribute with a parameterless constructor and a named property argument as the first
' attribute argument to have the above mentioned behavior, even though the comment clearly mentions that this behavior was intended only for the HostProtectionAttribute.
' We currently allow this case only for the HostProtectionAttribute. In future if need arises, we can exactly match native compiler's behavior.
If Me.IsTargetAttribute(targetSymbol, AttributeDescription.HostProtectionAttribute) Then
Return DeclarativeSecurityAction.LinkDemand
End If
Else
Dim firstArg As TypedConstant = Me.CommonConstructorArguments.FirstOrDefault()
Dim firstArgType = DirectCast(firstArg.Type, TypeSymbol)
Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing
If firstArgType IsNot Nothing AndAlso firstArgType.IsOrDerivedFromWellKnownClass(WellKnownType.System_Security_Permissions_SecurityAction, compilation, useSiteDiagnostics) Then
Return ValidateSecurityAction(firstArg, targetSymbol, nodeOpt, diagnostics, hasErrors)
End If
diagnostics.Add(If(nodeOpt IsNot Nothing, nodeOpt.Name.GetLocation, NoLocation.Singleton), useSiteDiagnostics)
End If
' BC31205: First argument to a security attribute must be a valid SecurityAction
diagnostics.Add(ErrorFactory.ErrorInfo(ERRID.ERR_SecurityAttributeMissingAction,
Me.AttributeClass),
If(nodeOpt IsNot Nothing, nodeOpt.Name.GetLocation, NoLocation.Singleton))
hasErrors = True
Return Nothing
End Function
Private Function ValidateSecurityAction(
typedValue As TypedConstant,
targetSymbol As Symbol,
nodeOpt As AttributeSyntax,
diagnostics As DiagnosticBag,
<Out> ByRef hasErrors As Boolean
) As DeclarativeSecurityAction
Debug.Assert(targetSymbol.Kind = SymbolKind.Assembly OrElse targetSymbol.Kind = SymbolKind.NamedType OrElse targetSymbol.Kind = SymbolKind.Method)
Dim securityAction As Integer = CInt(typedValue.Value)
hasErrors = False
Dim isPermissionRequestAction As Boolean
Select Case securityAction
Case DeclarativeSecurityAction.InheritanceDemand,
DeclarativeSecurityAction.LinkDemand
If Me.IsTargetAttribute(targetSymbol, AttributeDescription.PrincipalPermissionAttribute) Then
' BC31209: SecurityAction value '{0}' is invalid for PrincipalPermission attribute
diagnostics.Add(ERRID.ERR_PrincipalPermissionInvalidAction,
If(nodeOpt IsNot Nothing, nodeOpt.ArgumentList.Arguments(0).GetLocation(), NoLocation.Singleton),
If(nodeOpt IsNot Nothing, nodeOpt.ArgumentList.Arguments(0).ToString(), ""))
hasErrors = True
Return DeclarativeSecurityAction.None
End If
isPermissionRequestAction = False
Case 1
' Native compiler allows security action value 1 even though there is no corresponding field in
' System.Security.Permissions.SecurityAction enum.
' We will maintain compatibility.
Case DeclarativeSecurityAction.Assert,
DeclarativeSecurityAction.Demand,
DeclarativeSecurityAction.PermitOnly,
DeclarativeSecurityAction.Deny
isPermissionRequestAction = False
Case DeclarativeSecurityAction.RequestMinimum,
DeclarativeSecurityAction.RequestOptional,
DeclarativeSecurityAction.RequestRefuse
isPermissionRequestAction = True
Case Else
' BC31206: Security attribute '{0}' has an invalid SecurityAction value '{1}'
diagnostics.Add(ERRID.ERR_SecurityAttributeInvalidActionTypeOrMethod,
If(nodeOpt IsNot Nothing, nodeOpt.ArgumentList.Arguments(0).GetLocation(), NoLocation.Singleton),
If(nodeOpt IsNot Nothing, nodeOpt.Name.ToString, ""),
If(nodeOpt IsNot Nothing, nodeOpt.ArgumentList.Arguments(0).ToString(), ""))
hasErrors = True
Return DeclarativeSecurityAction.None
End Select
If isPermissionRequestAction Then
If targetSymbol.Kind = SymbolKind.NamedType OrElse targetSymbol.Kind = SymbolKind.Method Then
' Types and methods cannot take permission requests.
' BC31208: SecurityAction value '{0}' is invalid for security attributes applied to a type or a method
diagnostics.Add(ERRID.ERR_SecurityAttributeInvalidActionTypeOrMethod,
If(nodeOpt IsNot Nothing, nodeOpt.ArgumentList.Arguments(0).GetLocation, NoLocation.Singleton),
If(nodeOpt IsNot Nothing, nodeOpt.ArgumentList.Arguments(0).ToString(), ""))
hasErrors = True
Return DeclarativeSecurityAction.None
End If
ElseIf targetSymbol.Kind = SymbolKind.Assembly Then
' Assemblies cannot take declarative security.
' BC31207: SecurityAction value '{0}' is invalid for security attributes applied to an assembly
diagnostics.Add(ERRID.ERR_SecurityAttributeInvalidActionAssembly,
If(nodeOpt IsNot Nothing, nodeOpt.ArgumentList.Arguments(0).GetLocation, NoLocation.Singleton),
If(nodeOpt IsNot Nothing, nodeOpt.ArgumentList.Arguments(0).ToString(), ""))
hasErrors = True
Return DeclarativeSecurityAction.None
End If
Return CType(securityAction, DeclarativeSecurityAction)
End Function
''' <summary>
''' Decodes PermissionSetAttribute applied in source to determine if it needs any fixup during codegen.
''' </summary>
''' <remarks>
''' PermissionSetAttribute needs fixup when it contains an assignment to the 'File' property as a single named attribute argument.
''' Fixup performed is ported from SecurityAttributes::FixUpPermissionSetAttribute.
''' It involves following steps:
''' 1) Verifying that the specified file name resolves to a valid path.
''' 2) Reading the contents of the file into a byte array.
''' 3) Convert each byte in the file content into two bytes containing hexa-decimal characters.
''' 4) Replacing the 'File = fileName' named argument with 'Hex = hexFileContent' argument, where hexFileContent is the converted output from step 3) above.
'''
''' Step 1) is performed in this method, i.e. during binding.
''' Remaining steps are performed during serialization as we want to avoid retaining the entire file contents throughout the binding/codegen pass.
''' See <see cref="Microsoft.CodeAnalysis.CodeGen.PermissionSetAttributeWithFileReference"/> for remaining fixup steps.
''' </remarks>
''' <returns>String containing the resolved file path if PermissionSetAttribute needs fixup during codegen, null otherwise.</returns>
Friend Function DecodePermissionSetAttribute(compilation As VisualBasicCompilation, ByRef arguments As DecodeWellKnownAttributeArguments(Of AttributeSyntax, VisualBasicAttributeData, AttributeLocation)) As String
Dim resolvedFilePath As String = Nothing
Dim namedArgs = Me.CommonNamedArguments
If namedArgs.Length = 1 Then
Dim namedArg = namedArgs(0)
Dim attrType As NamedTypeSymbol = Me.AttributeClass
Dim filePropName As String = PermissionSetAttributeWithFileReference.FilePropertyName
Dim hexPropName As String = PermissionSetAttributeWithFileReference.HexPropertyName
If namedArg.Key = filePropName AndAlso
PermissionSetAttributeTypeHasRequiredProperty(attrType, filePropName) Then
' resolve file prop path
Dim fileName = DirectCast(namedArg.Value.Value, String)
Dim resolver = compilation.Options.XmlReferenceResolver
resolvedFilePath = If(resolver IsNot Nothing, resolver.ResolveReference(fileName, baseFilePath:=Nothing), Nothing)
If resolvedFilePath Is Nothing Then
' BC31210: Unable to resolve file path '{0}' specified for the named argument '{1}' for PermissionSet attribute
Dim argSyntaxLocation As Location = If(arguments.AttributeSyntaxOpt IsNot Nothing,
arguments.AttributeSyntaxOpt.ArgumentList.Arguments(1).GetLocation(),
NoLocation.Singleton)
arguments.Diagnostics.Add(ERRID.ERR_PermissionSetAttributeInvalidFile, argSyntaxLocation, If(fileName, "<empty>"), filePropName)
ElseIf (Not PermissionSetAttributeTypeHasRequiredProperty(attrType, hexPropName)) Then
' PermissionSetAttribute was defined in user source, but doesn't have the required Hex property.
' Native compiler still emits the file content as named assignment to 'Hex' property, but this leads to a runtime exception.
' We instead skip the fixup and emit the file property.
' CONSIDER: We may want to consider taking a breaking change and generating an error here.
Return Nothing
End If
End If
End If
Return resolvedFilePath
End Function
' This method checks if the given PermissionSetAttribute type has a property member with the given propName which is
' writable, non-generic, public and of string type.
Private Shared Function PermissionSetAttributeTypeHasRequiredProperty(permissionSetType As NamedTypeSymbol, propName As String) As Boolean
Dim members = permissionSetType.GetMembers(propName)
If members.Length = 1 AndAlso members(0).Kind = SymbolKind.Property Then
Dim [property] = DirectCast(members(0), PropertySymbol)
If [property].Type IsNot Nothing AndAlso [property].Type.SpecialType = SpecialType.System_String AndAlso
[property].DeclaredAccessibility = Accessibility.Public AndAlso [property].GetArity() = 0 AndAlso
[property].HasSet AndAlso [property].SetMethod.DeclaredAccessibility = Accessibility.Public Then
Return True
End If
End If
Return False
End Function
Friend Sub DecodeClassInterfaceAttribute(nodeOpt As AttributeSyntax, diagnostics As DiagnosticBag)
Debug.Assert(Not Me.HasErrors)
Dim ctorArgument As TypedConstant = Me.CommonConstructorArguments(0)
Debug.Assert(ctorArgument.Kind = TypedConstantKind.Enum OrElse ctorArgument.Kind = TypedConstantKind.Primitive)
Dim interfaceType As ClassInterfaceType = If(ctorArgument.Kind = TypedConstantKind.Enum,
ctorArgument.DecodeValue(Of ClassInterfaceType)(SpecialType.System_Enum),
CType(ctorArgument.DecodeValue(Of Short)(SpecialType.System_Int16), ClassInterfaceType))
Select Case interfaceType
Case ClassInterfaceType.None, ClassInterfaceType.AutoDispatch, ClassInterfaceType.AutoDual
Exit Select
Case Else
diagnostics.Add(ERRID.ERR_BadAttribute1, If(nodeOpt IsNot Nothing, nodeOpt.ArgumentList.Arguments(0).GetLocation(), NoLocation.Singleton), Me.AttributeClass)
End Select
End Sub
Friend Sub DecodeInterfaceTypeAttribute(node As AttributeSyntax, diagnostics As DiagnosticBag)
Dim discarded As ComInterfaceType = Nothing
If Not DecodeInterfaceTypeAttribute(discarded) Then
diagnostics.Add(ERRID.ERR_BadAttribute1, node.ArgumentList.Arguments(0).GetLocation(), Me.AttributeClass)
End If
End Sub
Friend Function DecodeInterfaceTypeAttribute(<Out> ByRef interfaceType As ComInterfaceType) As Boolean
Debug.Assert(Not Me.HasErrors)
Dim ctorArgument As TypedConstant = Me.CommonConstructorArguments(0)
Debug.Assert(ctorArgument.Kind = TypedConstantKind.Enum OrElse ctorArgument.Kind = TypedConstantKind.Primitive)
interfaceType = If(ctorArgument.Kind = TypedConstantKind.Enum,
ctorArgument.DecodeValue(Of ComInterfaceType)(SpecialType.System_Enum),
CType(ctorArgument.DecodeValue(Of Short)(SpecialType.System_Int16), ComInterfaceType))
Select Case interfaceType
Case ComInterfaceType.InterfaceIsDual, ComInterfaceType.InterfaceIsIDispatch, ComInterfaceType.InterfaceIsIInspectable, ComInterfaceType.InterfaceIsIUnknown
Return True
Case Else
Return False
End Select
End Function
Friend Function DecodeTypeLibTypeAttribute() As Cci.TypeLibTypeFlags
Debug.Assert(Not Me.HasErrors)
Dim ctorArgument As TypedConstant = Me.CommonConstructorArguments(0)
Debug.Assert(ctorArgument.Kind = TypedConstantKind.Enum OrElse ctorArgument.Kind = TypedConstantKind.Primitive)
Return If(ctorArgument.Kind = TypedConstantKind.Enum,
ctorArgument.DecodeValue(Of Cci.TypeLibTypeFlags)(SpecialType.System_Enum),
CType(ctorArgument.DecodeValue(Of Short)(SpecialType.System_Int16), Cci.TypeLibTypeFlags))
End Function
Friend Sub DecodeGuidAttribute(nodeOpt As AttributeSyntax, diagnostics As DiagnosticBag)
Debug.Assert(Not Me.HasErrors)
Dim guidString As String = Me.GetConstructorArgument(Of String)(0, SpecialType.System_String)
' Native compiler allows only a specific GUID format: "D" format (32 digits separated by hyphens)
Dim guidVal As Guid
If Not Guid.TryParseExact(guidString, "D", guidVal) Then
diagnostics.Add(ERRID.ERR_BadAttributeUuid2,
If(nodeOpt IsNot Nothing, nodeOpt.ArgumentList.Arguments(0).GetLocation(), NoLocation.Singleton),
Me.AttributeClass, If(guidString, ObjectDisplay.NullLiteral))
End If
End Sub
Friend Function DecodeDefaultMemberAttribute() As String
Debug.Assert(Not Me.HasErrors)
Return Me.GetConstructorArgument(Of String)(0, SpecialType.System_String)
End Function
#End Region
''' <summary>
''' This method determines if an applied attribute must be emitted.
''' Some attributes appear in symbol model to reflect the source code, but should not be emitted.
''' </summary>
Friend Function ShouldEmitAttribute(target As Symbol, isReturnType As Boolean, emittingAssemblyAttributesInNetModule As Boolean) As Boolean
Debug.Assert(TypeOf target Is SourceAssemblySymbol OrElse TypeOf target.ContainingAssembly Is SourceAssemblySymbol)
If HasErrors Then
Throw ExceptionUtilities.Unreachable
End If
' Attribute type is conditionally omitted if both the following are true:
' (a) It has at least one applied conditional attribute AND
' (b) None of conditional symbols are true at the attribute source location.
If Me.IsConditionallyOmitted Then
Return False
End If
' // UNDONE:harishk - spec. issue
' // how to deal with CLS Compliant attributes present on both Modules and Assemblies ?
' // Also this might be a issue for other well known attributes too ?
' //
' // For CLSCompliance - Ignore Module attributes for Assemblies and vice-versa
Select Case target.Kind
Case SymbolKind.Assembly
If (Not emittingAssemblyAttributesInNetModule AndAlso
(IsTargetAttribute(target, AttributeDescription.AssemblyCultureAttribute) OrElse
IsTargetAttribute(target, AttributeDescription.AssemblyVersionAttribute) OrElse
IsTargetAttribute(target, AttributeDescription.AssemblyFlagsAttribute) OrElse
IsTargetAttribute(target, AttributeDescription.AssemblyAlgorithmIdAttribute))) OrElse
(IsTargetAttribute(target, AttributeDescription.CLSCompliantAttribute) AndAlso
target.DeclaringCompilation.Options.OutputKind = OutputKind.NetModule) OrElse
IsTargetAttribute(target, AttributeDescription.TypeForwardedToAttribute) OrElse
Me.IsSecurityAttribute(target.DeclaringCompilation) Then
Return False
End If
Case SymbolKind.Event
If IsTargetAttribute(target, AttributeDescription.SpecialNameAttribute) OrElse
IsTargetAttribute(target, AttributeDescription.NonSerializedAttribute) Then
Return False
End If
Case SymbolKind.Field
If IsTargetAttribute(target, AttributeDescription.SpecialNameAttribute) OrElse
IsTargetAttribute(target, AttributeDescription.NonSerializedAttribute) OrElse
IsTargetAttribute(target, AttributeDescription.FieldOffsetAttribute) OrElse
IsTargetAttribute(target, AttributeDescription.MarshalAsAttribute) Then
Return False
End If
Case SymbolKind.Method
If isReturnType Then
If IsTargetAttribute(target, AttributeDescription.MarshalAsAttribute) Then
Return False
End If
Else
If IsTargetAttribute(target, AttributeDescription.SpecialNameAttribute) OrElse
IsTargetAttribute(target, AttributeDescription.MethodImplAttribute) OrElse
IsTargetAttribute(target, AttributeDescription.DllImportAttribute) OrElse
IsTargetAttribute(target, AttributeDescription.PreserveSigAttribute) OrElse
Me.IsSecurityAttribute(target.DeclaringCompilation) Then
Return False
End If
End If
Case SymbolKind.NetModule
If (IsTargetAttribute(target, AttributeDescription.CLSCompliantAttribute) AndAlso
target.DeclaringCompilation.Options.OutputKind <> OutputKind.NetModule) Then
Return False
End If
Case SymbolKind.NamedType
If IsTargetAttribute(target, AttributeDescription.SpecialNameAttribute) OrElse
IsTargetAttribute(target, AttributeDescription.ComImportAttribute) OrElse
IsTargetAttribute(target, AttributeDescription.SerializableAttribute) OrElse
IsTargetAttribute(target, AttributeDescription.StructLayoutAttribute) OrElse
IsTargetAttribute(target, AttributeDescription.WindowsRuntimeImportAttribute) OrElse
Me.IsSecurityAttribute(target.DeclaringCompilation) Then
Return False
End If
Case SymbolKind.Parameter
If IsTargetAttribute(target, AttributeDescription.OptionalAttribute) OrElse
IsTargetAttribute(target, AttributeDescription.MarshalAsAttribute) OrElse
IsTargetAttribute(target, AttributeDescription.InAttribute) OrElse
IsTargetAttribute(target, AttributeDescription.OutAttribute) Then
Return False
End If
Case SymbolKind.Property
If IsTargetAttribute(target, AttributeDescription.SpecialNameAttribute) Then
Return False
End If
End Select
Return True
End Function
End Class
Friend Module AttributeDataExtensions
<System.Runtime.CompilerServices.Extension()>
Public Function IndexOfAttribute(attributes As ImmutableArray(Of VisualBasicAttributeData), targetSymbol As Symbol, description As AttributeDescription) As Integer
For i As Integer = 0 To attributes.Length - 1
If attributes(i).IsTargetAttribute(targetSymbol, description) Then
Return i
End If
Next
Return -1
End Function
End Module
End Namespace
|
VPashkov/roslyn
|
src/Compilers/VisualBasic/Portable/Symbols/Attributes/AttributeData.vb
|
Visual Basic
|
apache-2.0
| 33,294
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.VisualBasic.CodeFixes.CorrectNextControlVariable
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.CorrectNextControlVariable
Public Class CorrectNextControlVariableTests
Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, CodeFixProvider)
Return New Tuple(Of DiagnosticAnalyzer, CodeFixProvider)(
Nothing, New CorrectNextControlVariableCodeFixProvider)
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsCorrectNextControlVariable)>
Public Sub TestForLoopBoundIdentifier()
Test(
NewLines("Module M1 \n Sub Main() \n Dim y As Integer \n For x = 1 To 10 \n Next [|y|] \n End Sub \n End Module"),
NewLines("Module M1 \n Sub Main() \n Dim y As Integer \n For x = 1 To 10 \n Next x \n End Sub \n End Module"))
End Sub
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsCorrectNextControlVariable)>
Public Sub TestForLoopUnboundIdentifier()
Test(
NewLines("Module M1 \n Sub Main() \n For x = 1 To 10 \n Next [|y|] \n End Sub \n End Module"),
NewLines("Module M1 \n Sub Main() \n For x = 1 To 10 \n Next x \n End Sub \n End Module"))
End Sub
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsCorrectNextControlVariable)>
Public Sub TestForEachLoopBoundIdentifier()
Test(
NewLines("Module M1 \n Sub Main() \n Dim y As Integer \n For Each x In {1, 2, 3} \n Next [|y|] \n End Sub \n End Module"),
NewLines("Module M1 \n Sub Main() \n Dim y As Integer \n For Each x In {1, 2, 3} \n Next x \n End Sub \n End Module"))
End Sub
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsCorrectNextControlVariable)>
Public Sub TestForEachLoopUnboundIdentifier()
Test(
NewLines("Module M1 \n Sub Main() \n For Each x In {1, 2, 3} \n Next [|y|] \n End Sub \n End Module"),
NewLines("Module M1 \n Sub Main() \n For Each x In {1, 2, 3} \n Next x \n End Sub \n End Module"))
End Sub
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsCorrectNextControlVariable)>
Public Sub TestForEachNested()
Test(
NewLines("Module M1 \n Sub Main() \n For Each x In {1, 2, 3} \n For Each y In {1, 2, 3} \n Next [|x|] \n Next x \n End Sub \n End Module"),
NewLines("Module M1 \n Sub Main() \n For Each x In {1, 2, 3} \n For Each y In {1, 2, 3} \n Next y \n Next x \n End Sub \n End Module"))
End Sub
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsCorrectNextControlVariable)>
Public Sub TestForEachNestedOuter()
Test(
NewLines("Module M1 \n Sub Main() \n For Each x In {1, 2, 3} \n For Each y In {1, 2, 3} \n Next y \n Next [|y|] \n End Sub \n End Module"),
NewLines("Module M1 \n Sub Main() \n For Each x In {1, 2, 3} \n For Each y In {1, 2, 3} \n Next y \n Next x \n End Sub \n End Module"))
End Sub
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsCorrectNextControlVariable)>
Public Sub TestForLoopWithDeclarator()
Test(
NewLines("Module M1 \n Sub Main() \n Dim y As Integer \n For x As Integer = 1 To 10 \n Next [|y|] \n End Sub \n End Module"),
NewLines("Module M1 \n Sub Main() \n Dim y As Integer \n For x As Integer = 1 To 10 \n Next x \n End Sub \n End Module"))
End Sub
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsCorrectNextControlVariable)>
Public Sub TestForEachLoopWithDeclarator()
Test(
NewLines("Module M1 \n Sub Main() \n For Each x As Integer In {1, 2, 4} \n Next [|y|] \n End Sub \n End Module"),
NewLines("Module M1 \n Sub Main() \n For Each x As Integer In {1, 2, 4} \n Next x \n End Sub \n End Module"))
End Sub
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsCorrectNextControlVariable)>
Public Sub TestMultipleControl1()
Test(
NewLines("Module M1 \n Sub Main() \n For Each x As Integer In {1, 2, 4} \n For Each y In {1, 2, 3} \n Next [|x|], y \n End Sub \n End Module"),
NewLines("Module M1 \n Sub Main() \n For Each x As Integer In {1, 2, 4} \n For Each y In {1, 2, 3} \n Next y, y \n End Sub \n End Module"))
End Sub
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsCorrectNextControlVariable)>
Public Sub TestMultipleControl2()
Test(
NewLines("Module M1 \n Sub Main() \n For Each x As Integer In {1, 2, 4} \n For Each y In {1, 2, 3} \n Next x, [|y|] \n End Sub \n End Module"),
NewLines("Module M1 \n Sub Main() \n For Each x As Integer In {1, 2, 4} \n For Each y In {1, 2, 3} \n Next x, x \n End Sub \n End Module"))
End Sub
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsCorrectNextControlVariable)>
Public Sub TestMixedNestedLoop()
Test(
NewLines("Module M1 \n Sub Main() \n For Each x As Integer In {1, 2, 4} \n For y = 1 To 10 \n Next y, [|y|] \n End Sub \n End Module"),
NewLines("Module M1 \n Sub Main() \n For Each x As Integer In {1, 2, 4} \n For y = 1 To 10 \n Next y, x \n End Sub \n End Module"))
End Sub
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsCorrectNextControlVariable)>
Public Sub TestThreeLevels()
Test(
NewLines("Module M1 \n Sub Main() \n For Each x As Integer In {1, 2, 4} \n For y = 1 To 10 \n For Each z As Integer In {1, 2, 3} \n Next z \n Next y, [|z|] \n End Sub \n End Module"),
NewLines("Module M1 \n Sub Main() \n For Each x As Integer In {1, 2, 4} \n For y = 1 To 10 \n For Each z As Integer In {1, 2, 3} \n Next z \n Next y, x \n End Sub \n End Module"))
End Sub
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsCorrectNextControlVariable)>
Public Sub TestExtraVariable()
Test(
NewLines("Module M1 \n Sub Main() \n For Each x As Integer In {1, 2, 4} \n For y = 1 To 10 \n Next y, [|z|], x \n End Sub \n End Module"),
NewLines("Module M1 \n Sub Main() \n For Each x As Integer In {1, 2, 4} \n For y = 1 To 10 \n Next y, x, x \n End Sub \n End Module"))
End Sub
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsCorrectNextControlVariable)>
Public Sub TestMethodCall()
Test(
NewLines("Module M1 \n Sub Main() \n For Each x As Integer In {1, 2, 4} \n For y = 1 To 10 \n Next y \n Next [|y|]() \n End Sub \n End Module"),
NewLines("Module M1 \n Sub Main() \n For Each x As Integer In {1, 2, 4} \n For y = 1 To 10 \n Next y \n Next x \n End Sub \n End Module"))
End Sub
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsCorrectNextControlVariable)>
Public Sub TestLongExpressions()
Test(
NewLines("Module M1 \n Sub Main() \n For Each x As Integer In {1, 2, 4} \n For y = 1 To 10 \n Next [|x + 10 + 11|], x \n End Sub \n End Module"),
NewLines("Module M1 \n Sub Main() \n For Each x As Integer In {1, 2, 4} \n For y = 1 To 10 \n Next y, x \n End Sub \n End Module"))
End Sub
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsCorrectNextControlVariable)>
Public Sub TestNoLoop()
TestMissing(
NewLines("Module M1 \n Sub Main() \n Next [|y|] \n End Sub \n End Module"))
End Sub
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsCorrectNextControlVariable)>
Public Sub TestMissingNesting()
TestMissing(
NewLines("Module M1 \n Sub Main() \n For Each x In {1, 2, 3} \n Next x, [|y|] \n End Sub \n End Module"))
End Sub
End Class
End Namespace
|
droyad/roslyn
|
src/EditorFeatures/VisualBasicTest/Diagnostics/CorrectNextControlVariable/CorrectNextControlVariableTests.vb
|
Visual Basic
|
apache-2.0
| 7,943
|
'
' News Articles for DotNetNuke - http://www.dotnetnuke.com
' Copyright (c) 2005-2012
' by Ventrian ( sales@ventrian.com ) ( http://www.ventrian.com )
'
Imports DotNetNuke.Common
Imports DotNetNuke.Common.Utilities
Imports DotNetNuke.Services.Exceptions
Imports DotNetNuke.Services.Localization
Imports Ventrian.NewsArticles.Base
Namespace Ventrian.NewsArticles
Partial Public Class ucMyArticles
Inherits NewsArticleModuleBase
Private Enum StatusType
Draft = 1
Unapproved = 2
Approved = 3
End Enum
Private _status As StatusType = StatusType.Draft
#Region " Private Properties "
Private ReadOnly Property CurrentPage() As Integer
Get
If (Request("Page") = Null.NullString And Request("CurrentPage") = Null.NullString) Then
Return 1
Else
Try
If (Request("Page") <> Null.NullString) Then
Return Convert.ToInt32(Request("Page"))
Else
Return Convert.ToInt32(Request("CurrentPage"))
End If
Catch
Return 1
End Try
End If
End Get
End Property
#End Region
#Region " Private Methods "
Private Sub ReadQueryString()
If (Request("Status") <> "") Then
Select Case Request("Status").ToLower()
Case "2"
_status = StatusType.Unapproved
Exit Select
Case "3"
_status = StatusType.Approved
Exit Select
End Select
End If
End Sub
Private Sub BindSelection()
If (ArticleSettings.IsApprover Or ArticleSettings.IsAdmin) Then
If (Request("ShowAll") <> "") Then
chkShowAll.Checked = True
End If
Else
chkShowAll.Visible = False
End If
End Sub
Private Sub BindArticles()
Dim objArticleController As ArticleController = New ArticleController
Localization.LocalizeDataGrid(grdMyArticles, Me.LocalResourceFile)
Dim count As Integer = 0
Dim authorID As Integer = Me.UserId
If (chkShowAll.Checked) Then
authorID = Null.NullInteger
End If
grdMyArticles.DataSource = objArticleController.GetArticleList(Me.ModuleId, Null.NullDate, Null.NullDate, Nothing, Null.NullBoolean, Nothing, Null.NullInteger, CurrentPage, 10, ArticleSettings.SortBy, ArticleSettings.SortDirection, False, True, Null.NullString, authorID, True, True, Null.NullBoolean, Null.NullBoolean, False, False, Null.NullString, Nothing, False, Null.NullString, Null.NullInteger, Null.NullString, Null.NullString, count)
Select Case _status
Case StatusType.Draft
grdMyArticles.DataSource = objArticleController.GetArticleList(Me.ModuleId, Null.NullDate, Null.NullDate, Nothing, Null.NullBoolean, Nothing, Null.NullInteger, CurrentPage, 10, ArticleSettings.SortBy, ArticleSettings.SortDirection, False, True, Null.NullString, authorID, True, True, Null.NullBoolean, Null.NullBoolean, False, False, Null.NullString, Nothing, False, Null.NullString, Null.NullInteger, Null.NullString, Null.NullString, count)
Exit Select
Case StatusType.Unapproved
grdMyArticles.DataSource = objArticleController.GetArticleList(Me.ModuleId, Null.NullDate, Null.NullDate, Nothing, Null.NullBoolean, Nothing, Null.NullInteger, CurrentPage, 10, ArticleSettings.SortBy, ArticleSettings.SortDirection, False, False, Null.NullString, authorID, True, True, Null.NullBoolean, Null.NullBoolean, False, False, Null.NullString, Nothing, False, Null.NullString, Null.NullInteger, Null.NullString, Null.NullString, count)
Exit Select
Case StatusType.Approved
grdMyArticles.DataSource = objArticleController.GetArticleList(Me.ModuleId, Null.NullDate, Null.NullDate, Nothing, Null.NullBoolean, Nothing, Null.NullInteger, CurrentPage, 10, ArticleSettings.SortBy, ArticleSettings.SortDirection, True, False, Null.NullString, authorID, True, True, Null.NullBoolean, Null.NullBoolean, False, False, Null.NullString, Nothing, False, Null.NullString, Null.NullInteger, Null.NullString, Null.NullString, count)
Exit Select
End Select
grdMyArticles.DataBind()
If (grdMyArticles.Items.Count = 0) Then
phNoArticles.Visible = True
grdMyArticles.Visible = False
ctlPagingControl.Visible = False
Else
phNoArticles.Visible = False
grdMyArticles.Visible = True
If (count > 10) Then
ctlPagingControl.Visible = True
ctlPagingControl.TotalRecords = count
ctlPagingControl.PageSize = 10
ctlPagingControl.CurrentPage = CurrentPage
ctlPagingControl.QuerystringParams = GetParams()
ctlPagingControl.TabID = TabId
ctlPagingControl.EnableViewState = False
End If
grdMyArticles.Columns(0).Visible = IsEditable
End If
End Sub
Private Sub CheckSecurity()
If (ArticleSettings.IsSubmitter = False) Then
Response.Redirect(NavigateURL(), True)
End If
If (Request("ShowAll") <> "") Then
If ((ArticleSettings.IsApprover Or ArticleSettings.IsAdmin) = False) Then
Response.Redirect(NavigateURL(), True)
End If
End If
End Sub
Private Function GetParams() As String
Dim params As String = ""
If (Request("ctl") <> "") Then
If (Request("ctl").ToLower() = "myarticles") Then
params += "ctl=" & Request("ctl") & "&mid=" & ModuleId.ToString()
End If
End If
If (Request("articleType") <> "") Then
If (Request("articleType").ToString().ToLower() = "myarticles") Then
params += "articleType=" & Request("articleType")
End If
End If
If (Request("Status") <> "") Then
params += "&Status=" & Convert.ToInt32(_status).ToString()
End If
If (Request("ShowAll") <> "") Then
params += "&ShowAll=" & Request("ShowAll")
End If
Return params
End Function
#End Region
#Region " Protected Methods "
Protected Function GetAdjustedCreateDate(ByVal objItem As Object) As String
Dim objArticle As ArticleInfo = CType(objItem, ArticleInfo)
Return objArticle.CreatedDate.ToString("d") & " " & objArticle.CreatedDate.ToString("t")
End Function
Protected Function GetAdjustedPublishDate(ByVal objItem As Object) As String
Dim objArticle As ArticleInfo = CType(objItem, ArticleInfo)
Return objArticle.StartDate.ToString("d") & " " & objArticle.StartDate.ToString("t")
End Function
Protected Function GetArticleLink(ByVal objItem As Object) As String
Dim objArticle As ArticleInfo = CType(objItem, ArticleInfo)
Return Common.GetArticleLink(objArticle, PortalSettings.ActiveTab, ArticleSettings, False)
End Function
Protected Function GetEditUrl(ByVal articleID As String) As String
If (ArticleSettings.LaunchLinks) Then
Return Common.GetModuleLink(Me.TabId, Me.ModuleId, "Edit", ArticleSettings, "ArticleID=" & articleID)
Else
Return Common.GetModuleLink(Me.TabId, Me.ModuleId, "SubmitNews", ArticleSettings, "ArticleID=" & articleID)
End If
End Function
Protected Function GetModuleLink(ByVal key As String, ByVal status As Integer) As String
If (status = 1) Then
Return Common.GetModuleLink(TabId, ModuleId, "MyArticles", ArticleSettings)
Else
Return Common.GetModuleLink(TabId, ModuleId, "MyArticles", ArticleSettings, "Status=" & status.ToString())
End If
End Function
Public Shadows ReadOnly Property IsEditable() As Boolean
Get
If (_status = StatusType.Draft) Then
Return True
Else
If (ArticleSettings.IsApprover Or ArticleSettings.IsAutoApprover) Then
Return True
End If
End If
End Get
End Property
Protected Function IsSelected(ByVal status As Integer)
If (status = _status) Then
Return "ui-tabs-selected ui-state-active"
Else
Return ""
End If
End Function
#End Region
#Region " Event Handlers "
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Try
CheckSecurity()
ReadQueryString()
If (IsPostBack = False) Then
BindSelection()
BindArticles()
End If
Catch exc As Exception 'Module failed to load
ProcessModuleLoadException(Me, exc)
End Try
End Sub
Protected Sub chkShowAll_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs) Handles chkShowAll.CheckedChanged
Try
If (chkShowAll.Checked) Then
If (_status <> StatusType.Draft) Then
Response.Redirect(Common.GetModuleLink(Me.TabId, Me.ModuleId, "MyArticles", ArticleSettings, "ShowAll=1", "Status=" & Convert.ToInt32(_status).ToString()), True)
Else
Response.Redirect(Common.GetModuleLink(Me.TabId, Me.ModuleId, "MyArticles", ArticleSettings, "ShowAll=1"), True)
End If
Else
If (_status <> StatusType.Draft) Then
Response.Redirect(Common.GetModuleLink(Me.TabId, Me.ModuleId, "MyArticles", ArticleSettings, "Status=" & Convert.ToInt32(_status).ToString()), True)
Else
Response.Redirect(Common.GetModuleLink(Me.TabId, Me.ModuleId, "MyArticles", ArticleSettings), True)
End If
End If
Catch exc As Exception 'Module failed to load
ProcessModuleLoadException(Me, exc)
End Try
End Sub
#End Region
End Class
End Namespace
|
ventrian/News-Articles
|
ucMyArticles.ascx.vb
|
Visual Basic
|
mit
| 11,335
|
Imports System.Windows.Forms
Public Class EnterNewSignal
Public inplayer As Integer = 0
Public outKeyCode As Integer = 0
Private Sub OK_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK_Button.Click
Me.DialogResult = System.Windows.Forms.DialogResult.OK
Me.Close()
End Sub
Private Sub Cancel_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cancel_Button.Click
Me.DialogResult = System.Windows.Forms.DialogResult.Cancel
Me.Close()
End Sub
Private Sub EnterNewSignal_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Label1.Text = "Please press the key to use" & vbCrLf & "for player " & inplayer
Me.KeyPreview = True
End Sub
Public Sub HandleKeyStroke(ByVal sender As Object, ByVal e As KeyEventArgs) Handles Me.KeyDown
Label1.Text = "New Key Code" & vbCrLf & "for player " & inplayer & vbCrLf & "is " & e.KeyCode & "(" & Asc(e.KeyCode) & ")"
outKeyCode = e.KeyCode
End Sub
End Class
|
mankowitz/jeppardy
|
Jeopardy/EnterNewSignal.vb
|
Visual Basic
|
mit
| 1,095
|
'------------------------------------------------------------------------------
' <auto-generated>
' Этот код создан программой.
' Исполняемая версия:4.0.30319.42000
'
' Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
' повторной генерации кода.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
<Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "14.0.0.0"), _
Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Partial Friend NotInheritable Class MySettings
Inherits Global.System.Configuration.ApplicationSettingsBase
Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings()),MySettings)
#Region "Функциональные возможности автосохранения My.Settings"
#If _MyType = "WindowsForms" Then
Private Shared addedHandler As Boolean
Private Shared addedHandlerLockObject As New Object
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs)
If My.Application.SaveMySettingsOnExit Then
My.Settings.Save()
End If
End Sub
#End If
#End Region
Public Shared ReadOnly Property [Default]() As MySettings
Get
#If _MyType = "WindowsForms" Then
If Not addedHandler Then
SyncLock addedHandlerLockObject
If Not addedHandler Then
AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings
addedHandler = True
End If
End SyncLock
End If
#End If
Return defaultInstance
End Get
End Property
End Class
Namespace My
<Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _
Friend Module MySettingsProperty
<Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _
Friend ReadOnly Property Settings() As Global.IPromptTestVB.MySettings
Get
Return Global.IPromptTestVB.MySettings.Default
End Get
End Property
End Module
End Namespace
|
ramer/IPrompt
|
IPromptTestVB/My Project/Settings.Designer.vb
|
Visual Basic
|
mit
| 3,019
|
Partial Class JhSerializer
Private Shared Sub SkipWhiteSpace(ByVal s As String, ByRef pos As Integer)
While pos < s.Length
Select Case AscW(s(pos))
Case 32, 9, 10, 13, 12
pos += 1
Case Else
Exit Sub
End Select
End While
End Sub
Public Class JsonParsePassedEndException
Inherits Exception
End Class
Public Class JsonParseInvalidDataException
Inherits Exception
Public ReadOnly AtCharacter As Integer
Public Sub New(ByVal AtCharacter As Integer)
Me.AtCharacter = AtCharacter
End Sub
End Class
Partial Class JhsValue
Public MustOverride Function EncodeJson(pretty As Boolean, Optional indentLevel As Integer = 0) As String
Public Shared Function TryParseJson(ByVal s As String, ByRef v As JhsValue) As Boolean
Try
v = ParseJson(s)
Return True
Catch
Return False
End Try
End Function
Public Shared Function ParseJson(ByVal s As String, Optional ByRef fromIndex As Integer = 0) As JhsValue
SkipWhiteSpace(s, fromIndex)
Dim dl = s.Length - fromIndex
If dl <= 0 Then Throw New JsonParsePassedEndException
If s(fromIndex) = "{"c Then
fromIndex += 1
Return ParseJsonObject(s, fromIndex)
ElseIf s(fromIndex) = "["c Then
fromIndex += 1
Return ParseJsonArray(s, fromIndex)
ElseIf s(fromIndex) = """"c Then
fromIndex += 1
Return ParseJsonString(s, fromIndex)
ElseIf dl >= 4 AndAlso String.Compare(s.Substring(fromIndex, 4), "true", StringComparison.InvariantCultureIgnoreCase) = 0 Then
fromIndex += 4
Return New JhsBoolean(True)
ElseIf dl >= 5 AndAlso String.Compare(s.Substring(fromIndex, 5), "false", StringComparison.InvariantCultureIgnoreCase) = 0 Then
fromIndex += 5
Return New JhsBoolean(False)
ElseIf dl >= 4 AndAlso String.Compare(s.Substring(fromIndex, 4), "null", StringComparison.InvariantCultureIgnoreCase) = 0 Then
fromIndex += 4
Return JhsNull.Value
Else
Return ParseJsonNumber(s, fromIndex)
End If
End Function
Private Shared Function ParseJsonObject(ByVal s As String, ByRef pos As Integer) As JhsObject
Dim oName As String
Dim oVal As JhsValue
Dim rv As New JhsObject
SkipWhiteSpace(s, pos)
If pos >= s.Length Then Throw New JsonParsePassedEndException
If s(pos) = "}"c Then pos += 1 : Return rv
Do
If s(pos) <> """"c Then Throw New JsonParseInvalidDataException(pos)
pos += 1
oName = ParseJsonString(s, pos).Value
SkipWhiteSpace(s, pos)
If pos >= s.Length Then Throw New JsonParsePassedEndException
If s(pos) <> ":"c Then Throw New JsonParseInvalidDataException(pos)
pos += 1
SkipWhiteSpace(s, pos)
If pos >= s.Length Then Throw New JsonParsePassedEndException
oVal = ParseJson(s, pos)
rv.Members.Add(oName, oVal)
SkipWhiteSpace(s, pos)
If pos >= s.Length Then Throw New JsonParsePassedEndException
If s(pos) = "}"c Then pos += 1 : Return rv
If s(pos) <> ","c Then Throw New JsonParseInvalidDataException(pos)
pos += 1
JhSerializer.SkipWhiteSpace(s, pos)
If pos >= s.Length Then Throw New JsonParsePassedEndException
Loop
End Function
Private Shared Function ParseJsonArray(ByVal s As String, ByRef pos As Integer) As JhsArray
JhSerializer.SkipWhiteSpace(s, pos)
If pos >= s.Length Then Throw New JsonParsePassedEndException
Dim rv As New JhsArray
If s(pos) = "]"c Then pos += 1 : Return rv
Do
rv.Elements.Add(JhSerializer.JhsValue.ParseJson(s, pos))
SkipWhiteSpace(s, pos)
If pos >= s.Length Then Throw New JsonParsePassedEndException
If s(pos) = "]"c Then pos += 1 : Return rv
If s(pos) <> ","c Then Throw New JsonParseInvalidDataException(pos)
pos += 1
SkipWhiteSpace(s, pos)
Loop
End Function
Private Shared Function ParseJsonString(ByVal s As String, ByRef pos As Integer) As JhsString
Dim sb As New System.Text.StringBuilder
Dim c As Char
Do
If pos >= s.Length Then Throw New JsonParsePassedEndException
c = s(pos)
If c = """"c Then pos += 1 : Return New JhsString(sb.ToString)
If c <> "\"c Then sb.Append(c) : pos += 1 : Continue Do
pos += 1
If pos >= s.Length Then Throw New JsonParsePassedEndException
Select Case s(pos)
Case "b"c 'backspace (BS)
sb.Append(ChrW(8))
Case "t"c 'tab (TAB)
sb.Append(ChrW(9))
Case "n"c 'new line (LF)
sb.Append(ChrW(10))
Case "f"c 'form feed (FF)
sb.Append(ChrW(12))
Case "r"c 'return (CR)
sb.Append(ChrW(13))
Case "u"c ' "0"c To "9"c, "a"c To "f"c, "A"c To "F"c '4 digit hex
If pos + 4 >= s.Length Then Throw New JsonParsePassedEndException
sb.Append(ChrW(Convert.ToInt32(s.Substring(pos + 1, 4), 16)))
pos += 4 '+1 after End Select
Case Else ' everything else including ", \, /
sb.Append(s(pos))
End Select
pos += 1
Loop
End Function
Private Shared Function ParseJsonNumber(ByVal s As String, ByRef pos As Integer) As JhsValue
If pos >= s.Length Then Throw New JsonParsePassedEndException
Dim sp = pos
Dim FloatFlag = False
If s(pos) = "-"c Then pos += 1
If pos >= s.Length Then Throw New JsonParsePassedEndException
If SkipDigits(s, pos) = 0 Then Throw New JsonParseInvalidDataException(pos)
If pos >= s.Length Then GoTo markDone
REM look for decimal point
If s(pos) = "."c Then
FloatFlag = True
pos += 1
If SkipDigits(s, pos) = 0 Then Throw New JsonParseInvalidDataException(pos)
End If
REM look for e/E
If Char.ToLowerInvariant(s(pos)) <> "e"c Then GoTo markDone
FloatFlag = True
pos += 1
If pos >= s.Length Then Throw New JsonParsePassedEndException
If s(pos) = "-" Or s(pos) = "+" Then pos += 1
If pos >= s.Length Then Throw New JsonParsePassedEndException
If SkipDigits(s, pos) = 0 Then Throw New JsonParseInvalidDataException(pos)
markDone:
If FloatFlag Then
Return New JhsFloat(Double.Parse(s.Substring(sp, pos - sp), System.Globalization.NumberFormatInfo.InvariantInfo))
Else
Return New JhsInteger(Int64.Parse(s.Substring(sp, pos - sp), System.Globalization.NumberFormatInfo.InvariantInfo))
End If
End Function
Private Shared Function SkipDigits(ByVal s As String, ByRef pos As Integer) As Integer
Dim skipCt = 0
Do
If pos >= s.Length OrElse s(pos) < "0"c OrElse s(pos) > "9"c Then Return skipCt
pos += 1
skipCt += 1
Loop
End Function
End Class
Partial Class JhsObject
Public Overrides Function EncodeJson(pretty As Boolean, Optional indentLevel As Integer = 0) As String
If Members.Count = 0 Then Return "{}"
Dim sb As New System.Text.StringBuilder
sb.Append("{"c)
If pretty Then sb.Append(vbCrLf)
Dim firstM = True
For Each m In Members
If Not firstM Then
sb.Append(","c)
If pretty Then sb.Append(vbCrLf)
End If
If pretty Then sb.Append(New String(" "c, (indentLevel + 1) * 2))
sb.Append((New JhsString(m.Key)).EncodeJson(pretty, indentLevel + 1))
If pretty Then sb.Append(" : ") Else sb.Append(":"c)
sb.Append(m.Value.EncodeJson(pretty, indentLevel + 1))
firstM = False
Next
If pretty Then sb.Append(vbCrLf & New String(" "c, indentLevel * 2))
sb.Append("}"c)
Return sb.ToString
End Function
End Class
Partial Class JhsArray
Public Overrides Function EncodeJson(pretty As Boolean, Optional indentLevel As Integer = 0) As String
If Elements.Count = 0 Then Return "[]"
Dim sb As New System.Text.StringBuilder
sb.Append("["c)
If pretty Then sb.Append(vbCrLf)
Dim firstE = True
For Each m In Elements
If Not firstE Then
sb.Append(","c)
If pretty Then sb.Append(vbCrLf)
End If
If pretty Then sb.Append(New String(" "c, (indentLevel + 1) * 2))
sb.Append(m.EncodeJson(pretty, indentLevel + 1))
firstE = False
Next
If pretty Then sb.Append(vbCrLf & New String(" "c, indentLevel * 2))
sb.Append("]"c)
Return sb.ToString
End Function
End Class
Partial Class JhsString
Public Overrides Function EncodeJson(pretty As Boolean, Optional indentLevel As Integer = 0) As String
If Value Is Nothing Then Return "null"
Dim sb As New System.Text.StringBuilder
sb.Append(""""c)
For i = 0 To Value.Length - 1
Select Case AscW(Value(i))
Case 8 'backspace (BS)
sb.Append("\b")
Case 9 'horizontal tab (TAB)
sb.Append("\t")
Case 10 ' newline (LF)
sb.Append("\n")
Case 12 'formfeed (FF)
sb.Append("\f")
Case 13 'carriage return (CR)
sb.Append("\r")
Case 34 ' "
sb.Append("\""")
Case 92 ' \
sb.Append("\\")
Case Is < 32, 127 ' control chars
sb.Append("\" & Hex(AscW(Value(i))).PadLeft(4, "0"c))
Case Else
sb.Append(Value(i))
End Select
Next
sb.Append(""""c)
Return sb.ToString
End Function
End Class
Partial Class JhsDateTime
Public Overloads Overrides Function EncodeJson(pretty As Boolean, Optional indentLevel As Integer = 0) As String
Return """" & Value.ToString("yyyy-MM-ddTHH:mm:ss") & """"
End Function
End Class
Partial Class JhsInteger
Public Overrides Function EncodeJson(pretty As Boolean, Optional indentLevel As Integer = 0) As String
Return Value.ToString(System.Globalization.NumberFormatInfo.InvariantInfo)
End Function
End Class
Partial Class JhsFloat
Public Overrides Function EncodeJson(pretty As Boolean, Optional indentLevel As Integer = 0) As String
Return Value.ToString(System.Globalization.NumberFormatInfo.InvariantInfo)
End Function
End Class
Partial Class JhsBoolean
Public Overrides Function EncodeJson(pretty As Boolean, Optional indentLevel As Integer = 0) As String
Return If(Value, "true", "false")
End Function
End Class
Partial Class JhsNull
Public Overrides Function EncodeJson(pretty As Boolean, Optional indentLevel As Integer = 0) As String
Return "null"
End Function
End Class
Partial Class JhsBinary
Public Overloads Overrides Function EncodeJson(pretty As Boolean, Optional indentLevel As Integer = 0) As String
Return """" & System.Convert.ToBase64String(Value) & """"
End Function
End Class
End Class
|
jesperhoy/GitHubBackup
|
GitHubBackup/JHSerializer-JSON.vb
|
Visual Basic
|
mit
| 11,003
|
'-------------------------------------------------------------------------------------------'
' Inicio del codigo
'-------------------------------------------------------------------------------------------'
' Importando librerias
'-------------------------------------------------------------------------------------------'
Imports System.Data
'-------------------------------------------------------------------------------------------'
' Inicio de clase "rRVentas_CBancarias"
'-------------------------------------------------------------------------------------------'
Partial Class rRVentas_CBancarias
Inherits vis2Formularios.frmReporte
Dim loObjetoReporte As CrystalDecisions.CrystalReports.Engine.ReportDocument
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim lcParametro0Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(0),goServicios.enuOpcionesRedondeo.KN_FechaInicioDelDia)
Dim lcParametro0Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(0),goServicios.enuOpcionesRedondeo.KN_FechaFinDelDia)
Dim lcOrdenamiento As String = cusAplicacion.goReportes.pcOrden
Try
Dim loComandoSeleccionar As New StringBuilder()
'-------------------------------------------------------------------------------------------'
' 1 - Select de Cobros
'-------------------------------------------------------------------------------------------'
loComandoSeleccionar.AppendLine(" SELECT CONVERT(NCHAR(10), Cobros.Fec_Ini, 103) AS Fec_Ini, ")
loComandoSeleccionar.AppendLine(" CONVERT(NCHAR(10), Cobros.Fec_Ini, 112) AS Fecha2, ")
loComandoSeleccionar.AppendLine(" Detalles_Cobros.Tip_Ope AS Tip_Ope, ")
loComandoSeleccionar.AppendLine(" Detalles_Cobros.Num_Doc AS Num_Doc, ")
loComandoSeleccionar.AppendLine(" Detalles_Cobros.Mon_Net AS Mon_Net, ")
loComandoSeleccionar.AppendLine(" 0.00 AS CMon_Com, ")
loComandoSeleccionar.AppendLine(" 0.00 AS CMon_Ret ")
loComandoSeleccionar.AppendLine(" INTO #TablaTemporalCobrosNoTarjetas1 ")
loComandoSeleccionar.AppendLine(" FROM Cobros, Detalles_Cobros ")
loComandoSeleccionar.AppendLine(" WHERE Cobros.Documento = Detalles_Cobros.Documento ")
loComandoSeleccionar.AppendLine(" AND Detalles_Cobros.Tip_Ope <> 'Tarjeta' ")
loComandoSeleccionar.AppendLine(" AND Cobros.Fec_Ini BETWEEN " & lcParametro0Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro0Hasta)
loComandoSeleccionar.AppendLine(" AND Cobros.Status <> 'Anulado'")
loComandoSeleccionar.AppendLine(" SELECT CONVERT(NCHAR(10), Cobros.Fec_Ini, 103) AS Fec_Ini, ")
loComandoSeleccionar.AppendLine(" CONVERT(NCHAR(10), Cobros.Fec_Ini, 112) AS Fecha2, ")
loComandoSeleccionar.AppendLine(" Detalles_Cobros.Tip_Ope AS Tip_Ope, ")
loComandoSeleccionar.AppendLine(" Detalles_Cobros.Num_Doc AS Num_Doc, ")
loComandoSeleccionar.AppendLine(" Detalles_Cobros.Mon_Net AS Mon_Net, ")
loComandoSeleccionar.AppendLine(" ((Detalles_Cobros.Mon_Net * Tarjetas.Por_Com) / 100) AS CMon_Com, ")
loComandoSeleccionar.AppendLine(" ((Detalles_Cobros.Mon_Net * Tarjetas.Por_Ret) / 100) AS CMon_Ret ")
loComandoSeleccionar.AppendLine(" INTO #TablaTemporalCobrosTarjetas1 ")
loComandoSeleccionar.AppendLine(" FROM Cobros, Detalles_Cobros, Tarjetas ")
loComandoSeleccionar.AppendLine(" WHERE Cobros.Documento = Detalles_Cobros.Documento ")
loComandoSeleccionar.AppendLine(" AND Tarjetas.Cod_Tar = Detalles_Cobros.Cod_Tar ")
loComandoSeleccionar.AppendLine(" AND Detalles_Cobros.Tip_Ope = 'Tarjeta' ")
loComandoSeleccionar.AppendLine(" AND Cobros.Fec_Ini BETWEEN " & lcParametro0Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro0Hasta)
loComandoSeleccionar.AppendLine(" AND Cobros.Status <> 'Anulado'")
loComandoSeleccionar.AppendLine(" SELECT Fec_Ini AS Fec_Ini, ")
loComandoSeleccionar.AppendLine(" Fecha2 AS Fecha2, ")
loComandoSeleccionar.AppendLine(" Tip_Ope AS Tip_Ope, ")
loComandoSeleccionar.AppendLine(" COUNT(Mon_Net) AS Cuantas, ")
loComandoSeleccionar.AppendLine(" SUM(Mon_Net) AS Monto, ")
loComandoSeleccionar.AppendLine(" SUM(CMon_Com) AS CMon_Com, ")
loComandoSeleccionar.AppendLine(" SUM(CMon_Ret) AS CMon_Ret ")
loComandoSeleccionar.AppendLine(" INTO #TablaTemporalCobros1 ")
loComandoSeleccionar.AppendLine(" FROM #TablaTemporalCobrosNoTarjetas1 ")
loComandoSeleccionar.AppendLine(" GROUP BY Fecha2, Fec_Ini, Tip_Ope ")
loComandoSeleccionar.AppendLine(" UNION ALL ")
loComandoSeleccionar.AppendLine(" SELECT Fec_Ini AS Fec_Ini, ")
loComandoSeleccionar.AppendLine(" Fecha2 AS Fecha2, ")
loComandoSeleccionar.AppendLine(" Tip_Ope AS Tip_Ope, ")
loComandoSeleccionar.AppendLine(" COUNT(Mon_Net) AS Cuantas, ")
loComandoSeleccionar.AppendLine(" SUM(Mon_Net) AS Monto, ")
loComandoSeleccionar.AppendLine(" SUM(CMon_Com) AS CMon_Com, ")
loComandoSeleccionar.AppendLine(" SUM(CMon_Ret) AS CMon_Ret ")
loComandoSeleccionar.AppendLine(" FROM #TablaTemporalCobrosTarjetas1 ")
loComandoSeleccionar.AppendLine(" GROUP BY Fecha2, Fec_Ini, Tip_Ope ")
loComandoSeleccionar.AppendLine(" ORDER BY 1, 2, 5 ")
'-------------------------------------------------------------------------------------------'
' 2 - Select de las Ventas
'-------------------------------------------------------------------------------------------'
loComandoSeleccionar.AppendLine(" SELECT Tip_Doc AS Tip_Doc, ")
loComandoSeleccionar.AppendLine(" Cod_Tip AS Cod_Tip, ")
loComandoSeleccionar.AppendLine(" CONVERT(NCHAR(10), Cuentas_Cobrar.Fec_Ini, 103) AS Fecha1, ")
loComandoSeleccionar.AppendLine(" CONVERT(NCHAR(10), Cuentas_Cobrar.Fec_Ini, 112) AS Fecha2, ")
loComandoSeleccionar.AppendLine(" (CASE WHEN Cod_Tip = 'FACT' THEN Cuentas_Cobrar.Documento ELSE SPACE(10) END) AS Documento, ")
loComandoSeleccionar.AppendLine(" Cuentas_Cobrar.Status AS Status, ")
loComandoSeleccionar.AppendLine(" Cuentas_Cobrar.Mon_Bru AS Mon_Bru, ")
loComandoSeleccionar.AppendLine(" (Cuentas_Cobrar.Mon_Imp1 + Cuentas_Cobrar.Mon_Imp2 + Cuentas_Cobrar.Mon_Imp3) AS Mon_Imp, ")
loComandoSeleccionar.AppendLine(" Cuentas_Cobrar.Mon_Net AS Mon_Net ")
loComandoSeleccionar.AppendLine(" INTO #TablaTemporalDocumentos1 ")
loComandoSeleccionar.AppendLine(" FROM Cuentas_Cobrar ")
loComandoSeleccionar.AppendLine(" WHERE (Cuentas_Cobrar.Cod_Tip = 'FACT' ")
loComandoSeleccionar.AppendLine(" OR Cuentas_Cobrar.Cod_Tip = 'N/CR') ")
loComandoSeleccionar.AppendLine(" AND Cuentas_Cobrar.Status <> 'Anulado' ")
loComandoSeleccionar.AppendLine(" AND Cuentas_Cobrar.Fec_Ini BETWEEN " & lcParametro0Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro0Hasta)
loComandoSeleccionar.AppendLine(" SELECT Fecha1 AS Fecha1, ")
loComandoSeleccionar.AppendLine(" Fecha2 AS Fecha2, ")
loComandoSeleccionar.AppendLine(" SUM(CASE WHEN Tip_Doc = 'Debito' THEN 1 ELSE 0 END) AS Can_Fac, ")
loComandoSeleccionar.AppendLine(" SUM(CASE WHEN Tip_Doc <> 'Debito' THEN 0 ELSE 1 END) AS Can_NCR, ")
loComandoSeleccionar.AppendLine(" SUM(CASE WHEN Cod_Tip = 'FACT' THEN Mon_Bru ELSE 0.00 END) AS Mon_BruF, ")
loComandoSeleccionar.AppendLine(" SUM(CASE WHEN Cod_Tip <> 'FACT' THEN Mon_Bru ELSE 0.00 END) AS Mon_BruNC, ")
loComandoSeleccionar.AppendLine(" SUM(CASE WHEN Cod_Tip = 'FACT' THEN Mon_Imp ELSE 0.00 END) AS Mon_ImpF, ")
loComandoSeleccionar.AppendLine(" SUM(CASE WHEN Cod_Tip <> 'FACT' THEN Mon_Imp ELSE 0.00 END) AS Mon_ImpNC, ")
loComandoSeleccionar.AppendLine(" SUM(CASE WHEN Cod_Tip = 'FACT' THEN Mon_Net ELSE 0.00 END) AS Mon_NetF, ")
loComandoSeleccionar.AppendLine(" SUM(CASE WHEN Cod_Tip <> 'FACT' THEN Mon_Net ELSE 0.00 END) AS Mon_NetNC, ")
loComandoSeleccionar.AppendLine(" MIN((CASE WHEN Cod_Tip = 'FACT' THEN Documento END)) AS Doc_Ini, ")
loComandoSeleccionar.AppendLine(" MAX(Documento) AS Doc_Fin ")
loComandoSeleccionar.AppendLine(" INTO #TablaTemporalFacturas1 ")
loComandoSeleccionar.AppendLine(" FROM #TablaTemporalDocumentos1 ")
loComandoSeleccionar.AppendLine(" GROUP BY Fecha2, Fecha1 ")
loComandoSeleccionar.AppendLine(" SELECT Fecha1 AS VenFecha1, ")
loComandoSeleccionar.AppendLine(" Fecha2 AS VenFecha2, ")
loComandoSeleccionar.AppendLine(" Can_Fac AS VenCan_Doc, ")
loComandoSeleccionar.AppendLine(" Mon_BruF AS VenMon_BruF, ")
loComandoSeleccionar.AppendLine(" 0.00 AS VenMon_BruNC, ")
loComandoSeleccionar.AppendLine(" Mon_ImpF AS VenMon_ImpF, ")
loComandoSeleccionar.AppendLine(" 0.00 AS VenMon_ImpNC, ")
loComandoSeleccionar.AppendLine(" Mon_NetF AS VenMon_NetF, ")
loComandoSeleccionar.AppendLine(" 0.00 AS VenMon_NetNC, ")
loComandoSeleccionar.AppendLine(" (Mon_BruF - Mon_BruNC) AS VenMon_Bru, ")
loComandoSeleccionar.AppendLine(" (Mon_ImpF - Mon_ImpNC) AS VenMon_Imp, ")
loComandoSeleccionar.AppendLine(" (Mon_NetF - Mon_NetNC) AS VenMon_Net, ")
loComandoSeleccionar.AppendLine(" Doc_Ini AS VenDoc_Ini, ")
loComandoSeleccionar.AppendLine(" Doc_Fin AS VenDoc_Fin ")
loComandoSeleccionar.AppendLine(" INTO #TablaTemporalFacturas2 ")
loComandoSeleccionar.AppendLine(" FROM #TablaTemporalFacturas1 ")
loComandoSeleccionar.AppendLine(" SELECT Fecha1 AS VenFecha1, ")
loComandoSeleccionar.AppendLine(" Fecha2 AS VenFecha2, ")
loComandoSeleccionar.AppendLine(" SUM(CASE WHEN Tip_Doc <> 'Debito' THEN 1 ELSE 0 END) AS VenCan_Doc, ")
loComandoSeleccionar.AppendLine(" 0.00 AS VenMon_BruF, ")
loComandoSeleccionar.AppendLine(" SUM(CASE WHEN Tip_Doc <> 'Debito' THEN Mon_Bru ELSE 0.00 END) AS VenMon_BruNC, ")
loComandoSeleccionar.AppendLine(" 0.00 AS VenMon_ImpF, ")
loComandoSeleccionar.AppendLine(" SUM(CASE WHEN Tip_Doc <> 'Debito' THEN Mon_Imp ELSE 0.00 END) AS VenMon_ImpNC, ")
loComandoSeleccionar.AppendLine(" 0.00 AS VenMon_NetF, ")
loComandoSeleccionar.AppendLine(" SUM(CASE WHEN Tip_Doc <> 'Debito' THEN Mon_Net ELSE 0.00 END) AS VenMon_NetNC, ")
loComandoSeleccionar.AppendLine(" 0.00 AS VenMon_Bru, ")
loComandoSeleccionar.AppendLine(" 0.00 AS VenMon_Imp, ")
loComandoSeleccionar.AppendLine(" 0.00 AS VenMon_Net, ")
loComandoSeleccionar.AppendLine(" SPACE(10) AS VenDoc_Ini, ")
loComandoSeleccionar.AppendLine(" SPACE(10) AS VenDoc_Fin ")
loComandoSeleccionar.AppendLine(" INTO #TablaTemporalNotasCredito1 ")
loComandoSeleccionar.AppendLine(" FROM #TablaTemporalDocumentos1 ")
loComandoSeleccionar.AppendLine(" GROUP BY Fecha2, Fecha1 ")
loComandoSeleccionar.AppendLine(" SELECT 'Facturas' AS VenTip_Doc, ")
loComandoSeleccionar.AppendLine(" #TablaTemporalFacturas2.* ")
loComandoSeleccionar.AppendLine(" INTO #TablaTemporalVentas1 ")
loComandoSeleccionar.AppendLine(" FROM #TablaTemporalFacturas2 ")
loComandoSeleccionar.AppendLine(" UNION ALL ")
loComandoSeleccionar.AppendLine(" SELECT 'NCredito' AS VenTip_Doc, ")
loComandoSeleccionar.AppendLine(" #TablaTemporalNotasCredito1.* ")
loComandoSeleccionar.AppendLine(" FROM #TablaTemporalNotasCredito1 ")
'-------------------------------------------------------------------------------------------'
' 3 - Select de las Relaciones de Descuentos por Facturas
'-------------------------------------------------------------------------------------------'
loComandoSeleccionar.AppendLine(" SELECT CONVERT(NCHAR(10), Cuentas_Cobrar.Fec_Ini, 103) AS DscFec_Ini, ")
loComandoSeleccionar.AppendLine(" CONVERT(NCHAR(10), Cuentas_Cobrar.Fec_Ini, 112) AS DscFecha2, ")
loComandoSeleccionar.AppendLine(" Cuentas_Cobrar.Documento AS DscDocumento, ")
loComandoSeleccionar.AppendLine(" Cuentas_Cobrar.Por_Des AS DscPor_Des, ")
loComandoSeleccionar.AppendLine(" Cuentas_Cobrar.Mon_Des AS DscMon_Des, ")
loComandoSeleccionar.AppendLine(" Cuentas_Cobrar.Mon_Bru AS DscMon_Bru, ")
loComandoSeleccionar.AppendLine(" Cuentas_Cobrar.Mon_Net AS DscMon_Net ")
loComandoSeleccionar.AppendLine(" INTO #TablaTemporalDescuentos1 ")
loComandoSeleccionar.AppendLine(" FROM Cuentas_Cobrar ")
loComandoSeleccionar.AppendLine(" WHERE Cuentas_Cobrar.Cod_Tip = 'FACT' ")
loComandoSeleccionar.AppendLine(" AND Cuentas_Cobrar.Por_Des > 0.00 ")
loComandoSeleccionar.AppendLine(" AND Cuentas_Cobrar.Status <> 'Anulado' ")
loComandoSeleccionar.AppendLine(" AND Cuentas_Cobrar.Fec_Ini Between " & lcParametro0Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro0Hasta)
loComandoSeleccionar.AppendLine(" ORDER BY Cuentas_Cobrar.Fec_Ini ")
'-------------------------------------------------------------------------------------------'
' 4 - Select de las Relaciones de Cheques
'-------------------------------------------------------------------------------------------'
loComandoSeleccionar.AppendLine(" SELECT CONVERT(NCHAR(10), Cobros.Fec_Ini, 103) AS ChFec_Ini, ")
loComandoSeleccionar.AppendLine(" CONVERT(NCHAR(10), Cobros.Fec_Ini, 112) AS ChFecha2, ")
loComandoSeleccionar.AppendLine(" Detalles_Cobros.Documento AS ChDocumento, ")
loComandoSeleccionar.AppendLine(" Detalles_Cobros.Num_Doc AS ChNum_Doc, ")
loComandoSeleccionar.AppendLine(" Detalles_Cobros.Mon_Net AS ChMon_Net, ")
loComandoSeleccionar.AppendLine(" Bancos.Nom_Ban AS ChNom_Ban ")
loComandoSeleccionar.AppendLine(" INTO #TablaTemporalCheques1 ")
loComandoSeleccionar.AppendLine(" FROM Cobros INNER JOIN Detalles_Cobros ")
loComandoSeleccionar.AppendLine(" ON Cobros.Documento = Detalles_Cobros.Documento, ")
loComandoSeleccionar.AppendLine(" Bancos ")
loComandoSeleccionar.AppendLine(" WHERE Detalles_Cobros.Cod_Ban = Bancos.Cod_Ban ")
loComandoSeleccionar.AppendLine(" AND Detalles_Cobros.Tip_Ope = 'Cheque' ")
loComandoSeleccionar.AppendLine(" AND Cobros.Fec_Ini Between " & lcParametro0Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro0Hasta)
loComandoSeleccionar.AppendLine(" AND Cobros.status <> 'Anulado'")
loComandoSeleccionar.AppendLine(" ORDER BY Cobros.Fec_Ini ")
'-------------------------------------------------------------------------------------------'
' 5 - Select de las Tarjetas
'-------------------------------------------------------------------------------------------'
loComandoSeleccionar.AppendLine(" SELECT Cobros.Documento AS TDocumento, ")
loComandoSeleccionar.AppendLine(" CONVERT(NCHAR(10), Cobros.Fec_Ini, 103) AS TFec_Ini, ")
loComandoSeleccionar.AppendLine(" CONVERT(NCHAR(10), Cobros.Fec_Ini, 112) AS TFecha2, ")
loComandoSeleccionar.AppendLine(" Cobros.Cod_Ven AS TCod_Ven, ")
loComandoSeleccionar.AppendLine(" Detalles_Cobros.Cod_Tar AS TCod_Tar, ")
loComandoSeleccionar.AppendLine(" Detalles_Cobros.Num_Doc AS TNum_Doc, ")
loComandoSeleccionar.AppendLine(" Detalles_Cobros.Mon_Net AS TMon_Net, ")
loComandoSeleccionar.AppendLine(" Tarjetas.Por_Com AS TPor_Com, ")
loComandoSeleccionar.AppendLine(" (Detalles_Cobros.Mon_Net * (Tarjetas.Por_Com / 100)) AS TMon_Com, ")
loComandoSeleccionar.AppendLine(" Tarjetas.Por_Ret AS TPor_Ret, ")
loComandoSeleccionar.AppendLine(" (Detalles_Cobros.Mon_Net * (Tarjetas.Por_Ret / 100)) AS TMon_Ret, ")
loComandoSeleccionar.AppendLine(" Tarjetas.Cod_Tip AS TCod_Tip ")
loComandoSeleccionar.AppendLine(" INTO #TablaTemporalTarjetas1 ")
loComandoSeleccionar.AppendLine(" FROM Cobros INNER JOIN Detalles_Cobros ")
loComandoSeleccionar.AppendLine(" ON Cobros.Documento = Detalles_Cobros.Documento, ")
loComandoSeleccionar.AppendLine(" Tarjetas ")
loComandoSeleccionar.AppendLine(" WHERE Tarjetas.Cod_Tar = Detalles_Cobros.Cod_Tar ")
loComandoSeleccionar.AppendLine(" AND Cobros.Fec_Ini Between " & lcParametro0Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro0Hasta)
loComandoSeleccionar.AppendLine(" AND Cobros.status <> 'Anulado'")
loComandoSeleccionar.AppendLine(" ORDER BY Cobros.Fec_Ini ")
'-------------------------------------------------------------------------------------------'
' 6 - Select de Comisiones
'-------------------------------------------------------------------------------------------'
loComandoSeleccionar.AppendLine(" SELECT CONVERT(NCHAR(10), Facturas.Fec_Ini, 103) AS Fec_Ini, ")
loComandoSeleccionar.AppendLine(" CONVERT(NCHAR(10), Facturas.Fec_Ini, 112) AS Fecha2, ")
loComandoSeleccionar.AppendLine(" Facturas.Cod_Ven AS Cod_Ven, ")
loComandoSeleccionar.AppendLine(" Vendedores.Nom_Ven AS Nom_Ven, ")
loComandoSeleccionar.AppendLine(" Vendedores.Por_Ven AS Por_Ven, ")
loComandoSeleccionar.AppendLine(" (Renglones_Facturas.Mon_Bru) AS Mon_Bru, ")
loComandoSeleccionar.AppendLine(" (Renglones_Facturas.Mon_Net + Renglones_Facturas.Mon_Imp1) AS Mon_Net, ")
loComandoSeleccionar.AppendLine(" (Renglones_Facturas.Can_Art1) AS Pares ")
loComandoSeleccionar.AppendLine(" INTO #TablaTemporalComisiones1 ")
loComandoSeleccionar.AppendLine(" FROM Facturas, ")
loComandoSeleccionar.AppendLine(" Renglones_Facturas, ")
loComandoSeleccionar.AppendLine(" Vendedores ")
loComandoSeleccionar.AppendLine(" WHERE Facturas.Documento = Renglones_Facturas.Documento ")
loComandoSeleccionar.AppendLine(" AND Facturas.Status <> 'Anulado' ")
loComandoSeleccionar.AppendLine(" AND Facturas.Cod_Ven = Vendedores.Cod_Ven ")
loComandoSeleccionar.AppendLine(" AND Facturas.Fec_Ini Between " & lcParametro0Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro0Hasta)
loComandoSeleccionar.AppendLine(" SELECT Fec_Ini AS Fec_Ini, ")
loComandoSeleccionar.AppendLine(" Fecha2 AS Fecha2, ")
loComandoSeleccionar.AppendLine(" Cod_Ven AS Cod_Ven, ")
loComandoSeleccionar.AppendLine(" Nom_Ven AS Nom_Ven, ")
loComandoSeleccionar.AppendLine(" Por_Ven AS Por_Ven, ")
loComandoSeleccionar.AppendLine(" COUNT(*) AS Cuantos, ")
loComandoSeleccionar.AppendLine(" SUM(Mon_Bru) AS Mon_Bru, ")
loComandoSeleccionar.AppendLine(" SUM(Mon_Net) AS Mon_Net, ")
loComandoSeleccionar.AppendLine(" SUM(Mon_Bru * (Por_Ven / 100)) AS Mon_Com, ")
loComandoSeleccionar.AppendLine(" SUM(Pares) AS Pares ")
loComandoSeleccionar.AppendLine(" INTO #TablaTemporalComisiones2 ")
loComandoSeleccionar.AppendLine(" FROM #TablaTemporalComisiones1 ")
loComandoSeleccionar.AppendLine(" GROUP BY Fecha2, Fec_Ini, Cod_Ven, Nom_Ven, Por_Ven ")
loComandoSeleccionar.AppendLine(" ORDER BY Fecha2, Cod_Ven, Nom_Ven, Por_Ven; ")
'-------------------------------------------------------------------------------------------'
' Union de las tablas involucradas
'-------------------------------------------------------------------------------------------'
loComandoSeleccionar.AppendLine(" WITH curTemporal AS ( ")
loComandoSeleccionar.AppendLine(" SELECT 1 AS Orden, ")
loComandoSeleccionar.AppendLine(" 'RelCob' AS Tipo, ")
loComandoSeleccionar.AppendLine(" Fec_Ini AS Fec_Ini,")
loComandoSeleccionar.AppendLine(" Fecha2 AS Fecha2,")
loComandoSeleccionar.AppendLine(" Tip_Ope AS Tip_Ope, ")
loComandoSeleccionar.AppendLine(" Cuantas AS Cuantas, ")
loComandoSeleccionar.AppendLine(" Monto AS Monto, ")
loComandoSeleccionar.AppendLine(" CMon_Com AS CMon_Com, ")
loComandoSeleccionar.AppendLine(" CMon_Ret AS CMon_Ret, ")
loComandoSeleccionar.AppendLine(" SPACE(30) AS Cod_Ven, ")
loComandoSeleccionar.AppendLine(" SPACE(30) AS Nom_Ven, ")
loComandoSeleccionar.AppendLine(" 0.00 AS Por_Ven, ")
loComandoSeleccionar.AppendLine(" 0.00 AS Cuantos, ")
loComandoSeleccionar.AppendLine(" 0.00 AS Mon_Bru, ")
loComandoSeleccionar.AppendLine(" 0.00 AS Mon_Net, ")
loComandoSeleccionar.AppendLine(" 0.00 AS Mon_Com, ")
loComandoSeleccionar.AppendLine(" 0.00 AS Pares, ")
loComandoSeleccionar.AppendLine(" SPACE(10) AS TDocumento, ")
loComandoSeleccionar.AppendLine(" Fec_Ini AS TFec_Ini, ")
loComandoSeleccionar.AppendLine(" SPACE(30) AS TCod_Ven, ")
loComandoSeleccionar.AppendLine(" SPACE(30) AS TCod_Tar, ")
loComandoSeleccionar.AppendLine(" SPACE(30) AS TNum_Doc, ")
loComandoSeleccionar.AppendLine(" 0.00 AS TMon_Net, ")
loComandoSeleccionar.AppendLine(" 0.00 AS TPor_Com, ")
loComandoSeleccionar.AppendLine(" 0.00 AS TMon_Com, ")
loComandoSeleccionar.AppendLine(" 0.00 AS TPor_Ret, ")
loComandoSeleccionar.AppendLine(" 0.00 AS TMon_Ret, ")
loComandoSeleccionar.AppendLine(" SPACE(10) AS TCod_Tip, ")
loComandoSeleccionar.AppendLine(" SPACE(10) AS Doc_Ini, ")
loComandoSeleccionar.AppendLine(" SPACE(10) AS Doc_Fin, ")
loComandoSeleccionar.AppendLine(" 0.00 AS ChMon_Net, ")
loComandoSeleccionar.AppendLine(" SPACE(10) AS ChDocumento, ")
loComandoSeleccionar.AppendLine(" SPACE(20) AS ChNum_Doc, ")
loComandoSeleccionar.AppendLine(" SPACE(30) AS ChNom_Ban, ")
loComandoSeleccionar.AppendLine(" SPACE(10) AS DscDocumento, ")
loComandoSeleccionar.AppendLine(" 0.00 AS DscPor_Des, ")
loComandoSeleccionar.AppendLine(" 0.00 AS DscMon_Des, ")
loComandoSeleccionar.AppendLine(" 0.00 AS DscMon_Bru, ")
loComandoSeleccionar.AppendLine(" 0.00 AS DscMon_Net, ")
loComandoSeleccionar.AppendLine(" 0.00 AS VenCan_Doc, ")
loComandoSeleccionar.AppendLine(" SPACE(10) AS VenTip_Doc, ")
loComandoSeleccionar.AppendLine(" 0.00 AS VenMon_Bru, ")
loComandoSeleccionar.AppendLine(" 0.00 AS VenMon_BruF, ")
loComandoSeleccionar.AppendLine(" 0.00 AS VenMon_BruNC, ")
loComandoSeleccionar.AppendLine(" SPACE(10) AS VenDoc_Ini, ")
loComandoSeleccionar.AppendLine(" SPACE(10) AS VenDoc_Fin ")
loComandoSeleccionar.AppendLine(" FROM #TablaTemporalCobros1 ")
loComandoSeleccionar.AppendLine(" UNION ALL ")
loComandoSeleccionar.AppendLine(" SELECT 2 AS Orden, ")
loComandoSeleccionar.AppendLine(" 'RelVen' AS Tipo, ")
loComandoSeleccionar.AppendLine(" VenFecha1 AS Fec_Ini,")
loComandoSeleccionar.AppendLine(" VenFecha2 AS Fecha2,")
loComandoSeleccionar.AppendLine(" SPACE(10) AS Tip_Ope, ")
loComandoSeleccionar.AppendLine(" 0.00 AS Cuantas, ")
loComandoSeleccionar.AppendLine(" 0.00 AS Monto, ")
loComandoSeleccionar.AppendLine(" 0.00 AS CMon_Com, ")
loComandoSeleccionar.AppendLine(" 0.00 AS CMon_Ret, ")
loComandoSeleccionar.AppendLine(" SPACE(30) AS Cod_Ven, ")
loComandoSeleccionar.AppendLine(" SPACE(30) AS Nom_Ven, ")
loComandoSeleccionar.AppendLine(" 0.00 AS Por_Ven, ")
loComandoSeleccionar.AppendLine(" 0.00 AS Cuantos, ")
loComandoSeleccionar.AppendLine(" 0.00 AS Mon_Bru, ")
loComandoSeleccionar.AppendLine(" 0.00 AS Mon_Net, ")
loComandoSeleccionar.AppendLine(" 0.00 AS Mon_Com, ")
loComandoSeleccionar.AppendLine(" 0.00 AS Pares, ")
loComandoSeleccionar.AppendLine(" SPACE(10) AS TDocumento, ")
loComandoSeleccionar.AppendLine(" VenFecha1 AS TFec_Ini, ")
loComandoSeleccionar.AppendLine(" SPACE(30) AS TCod_Ven, ")
loComandoSeleccionar.AppendLine(" SPACE(30) AS TCod_Tar, ")
loComandoSeleccionar.AppendLine(" SPACE(30) AS TNum_Doc, ")
loComandoSeleccionar.AppendLine(" 0.00 AS TMon_Net, ")
loComandoSeleccionar.AppendLine(" 0.00 AS TPor_Com, ")
loComandoSeleccionar.AppendLine(" 0.00 AS TMon_Com, ")
loComandoSeleccionar.AppendLine(" 0.00 AS TPor_Ret, ")
loComandoSeleccionar.AppendLine(" 0.00 AS TMon_Ret, ")
loComandoSeleccionar.AppendLine(" SPACE(10) AS TCod_Tip, ")
loComandoSeleccionar.AppendLine(" SPACE(10) AS Doc_Ini, ")
loComandoSeleccionar.AppendLine(" SPACE(10) AS Doc_Fin, ")
loComandoSeleccionar.AppendLine(" 0.00 AS ChMon_Net, ")
loComandoSeleccionar.AppendLine(" SPACE(10) AS ChDocumento, ")
loComandoSeleccionar.AppendLine(" SPACE(20) AS ChNum_Doc, ")
loComandoSeleccionar.AppendLine(" SPACE(30) AS ChNom_Ban, ")
loComandoSeleccionar.AppendLine(" SPACE(10) AS DscDocumento, ")
loComandoSeleccionar.AppendLine(" 0.00 AS DscPor_Des, ")
loComandoSeleccionar.AppendLine(" 0.00 AS DscMon_Des, ")
loComandoSeleccionar.AppendLine(" 0.00 AS DscMon_Bru, ")
loComandoSeleccionar.AppendLine(" 0.00 AS DscMon_Net, ")
loComandoSeleccionar.AppendLine(" VenCan_Doc AS VenCan_Doc, ")
loComandoSeleccionar.AppendLine(" VenTip_Doc AS VenTip_Doc, ")
loComandoSeleccionar.AppendLine(" VenMon_Bru AS VenMon_Bru, ")
loComandoSeleccionar.AppendLine(" VenMon_BruF AS VenMon_BruF, ")
loComandoSeleccionar.AppendLine(" VenMon_BruNC AS VenMon_BruNC, ")
loComandoSeleccionar.AppendLine(" VenDoc_Ini AS VenDoc_Ini, ")
loComandoSeleccionar.AppendLine(" VenDoc_Fin AS VenDoc_Fin ")
loComandoSeleccionar.AppendLine(" FROM #TablaTemporalVentas1 ")
loComandoSeleccionar.AppendLine(" UNION ALL ")
loComandoSeleccionar.AppendLine(" SELECT 3 AS Orden, ")
loComandoSeleccionar.AppendLine(" 'RelDes' AS Tipo, ")
loComandoSeleccionar.AppendLine(" DscFec_Ini AS Fec_Ini,")
loComandoSeleccionar.AppendLine(" DscFecha2 AS Fecha2,")
loComandoSeleccionar.AppendLine(" SPACE(10) AS Tip_Ope, ")
loComandoSeleccionar.AppendLine(" 0.00 AS Cuantas, ")
loComandoSeleccionar.AppendLine(" 0.00 AS Monto, ")
loComandoSeleccionar.AppendLine(" 0.00 AS CMon_Com, ")
loComandoSeleccionar.AppendLine(" 0.00 AS CMon_Ret, ")
loComandoSeleccionar.AppendLine(" SPACE(30) AS Cod_Ven, ")
loComandoSeleccionar.AppendLine(" SPACE(30) AS Nom_Ven, ")
loComandoSeleccionar.AppendLine(" 0.00 AS Por_Ven, ")
loComandoSeleccionar.AppendLine(" 0.00 AS Cuantos, ")
loComandoSeleccionar.AppendLine(" 0.00 AS Mon_Bru, ")
loComandoSeleccionar.AppendLine(" 0.00 AS Mon_Net, ")
loComandoSeleccionar.AppendLine(" 0.00 AS Mon_Com, ")
loComandoSeleccionar.AppendLine(" 0.00 AS Pares, ")
loComandoSeleccionar.AppendLine(" SPACE(10) AS TDocumento, ")
loComandoSeleccionar.AppendLine(" DscFec_Ini AS TFec_Ini, ")
loComandoSeleccionar.AppendLine(" SPACE(30) AS TCod_Ven, ")
loComandoSeleccionar.AppendLine(" SPACE(30) AS TCod_Tar, ")
loComandoSeleccionar.AppendLine(" SPACE(30) AS TNum_Doc, ")
loComandoSeleccionar.AppendLine(" 0.00 AS TMon_Net, ")
loComandoSeleccionar.AppendLine(" 0.00 AS TPor_Com, ")
loComandoSeleccionar.AppendLine(" 0.00 AS TMon_Com, ")
loComandoSeleccionar.AppendLine(" 0.00 AS TPor_Ret, ")
loComandoSeleccionar.AppendLine(" 0.00 AS TMon_Ret, ")
loComandoSeleccionar.AppendLine(" SPACE(10) AS TCod_Tip, ")
loComandoSeleccionar.AppendLine(" SPACE(10) AS Doc_Ini, ")
loComandoSeleccionar.AppendLine(" SPACE(10) AS Doc_Fin, ")
loComandoSeleccionar.AppendLine(" 0.00 AS ChMon_Net, ")
loComandoSeleccionar.AppendLine(" SPACE(10) AS ChDocumento, ")
loComandoSeleccionar.AppendLine(" SPACE(20) AS ChNum_Doc, ")
loComandoSeleccionar.AppendLine(" SPACE(30) AS ChNom_Ban, ")
loComandoSeleccionar.AppendLine(" DscDocumento AS DscDocumento, ")
loComandoSeleccionar.AppendLine(" DscPor_Des AS DscPor_Des, ")
loComandoSeleccionar.AppendLine(" DscMon_Des AS DscMon_Des, ")
loComandoSeleccionar.AppendLine(" DscMon_Bru AS DscMon_Bru, ")
loComandoSeleccionar.AppendLine(" DscMon_Net AS DscMon_Net, ")
loComandoSeleccionar.AppendLine(" 0.00 AS VenCan_Doc, ")
loComandoSeleccionar.AppendLine(" SPACE(10) AS VenTip_Doc, ")
loComandoSeleccionar.AppendLine(" 0.00 AS VenMon_Bru, ")
loComandoSeleccionar.AppendLine(" 0.00 AS VenMon_BruF, ")
loComandoSeleccionar.AppendLine(" 0.00 AS VenMon_BruNC, ")
loComandoSeleccionar.AppendLine(" SPACE(10) AS VenDoc_Ini, ")
loComandoSeleccionar.AppendLine(" SPACE(10) AS VenDoc_Fin ")
loComandoSeleccionar.AppendLine(" FROM #TablaTemporalDescuentos1 ")
loComandoSeleccionar.AppendLine(" UNION ALL ")
loComandoSeleccionar.AppendLine(" SELECT 4 AS Orden, ")
loComandoSeleccionar.AppendLine(" 'RelChe' AS Tipo, ")
loComandoSeleccionar.AppendLine(" ChFec_Ini AS Fec_Ini,")
loComandoSeleccionar.AppendLine(" ChFecha2 AS Fecha2,")
loComandoSeleccionar.AppendLine(" SPACE(10) AS Tip_Ope, ")
loComandoSeleccionar.AppendLine(" 0.00 AS Cuantas, ")
loComandoSeleccionar.AppendLine(" 0.00 AS Monto, ")
loComandoSeleccionar.AppendLine(" 0.00 AS CMon_Com, ")
loComandoSeleccionar.AppendLine(" 0.00 AS CMon_Ret, ")
loComandoSeleccionar.AppendLine(" SPACE(30) AS Cod_Ven, ")
loComandoSeleccionar.AppendLine(" SPACE(30) AS Nom_Ven, ")
loComandoSeleccionar.AppendLine(" 0.00 AS Por_Ven, ")
loComandoSeleccionar.AppendLine(" 0.00 AS Cuantos, ")
loComandoSeleccionar.AppendLine(" 0.00 AS Mon_Bru, ")
loComandoSeleccionar.AppendLine(" 0.00 AS Mon_Net, ")
loComandoSeleccionar.AppendLine(" 0.00 AS Mon_Com, ")
loComandoSeleccionar.AppendLine(" 0.00 AS Pares, ")
loComandoSeleccionar.AppendLine(" SPACE(10) AS TDocumento, ")
loComandoSeleccionar.AppendLine(" ChFec_Ini AS TFec_Ini, ")
loComandoSeleccionar.AppendLine(" SPACE(30) AS TCod_Ven, ")
loComandoSeleccionar.AppendLine(" SPACE(30) AS TCod_Tar, ")
loComandoSeleccionar.AppendLine(" SPACE(30) AS TNum_Doc, ")
loComandoSeleccionar.AppendLine(" 0.00 AS TMon_Net, ")
loComandoSeleccionar.AppendLine(" 0.00 AS TPor_Com, ")
loComandoSeleccionar.AppendLine(" 0.00 AS TMon_Com, ")
loComandoSeleccionar.AppendLine(" 0.00 AS TPor_Ret, ")
loComandoSeleccionar.AppendLine(" 0.00 AS TMon_Ret, ")
loComandoSeleccionar.AppendLine(" SPACE(10) AS TCod_Tip, ")
loComandoSeleccionar.AppendLine(" SPACE(10) AS Doc_Ini, ")
loComandoSeleccionar.AppendLine(" SPACE(10) AS Doc_Fin, ")
loComandoSeleccionar.AppendLine(" ChMon_Net AS ChMon_Net, ")
loComandoSeleccionar.AppendLine(" ChDocumento AS ChDocumento, ")
loComandoSeleccionar.AppendLine(" ChNum_Doc AS ChNum_Doc, ")
loComandoSeleccionar.AppendLine(" ChNom_Ban AS ChNom_Ban, ")
loComandoSeleccionar.AppendLine(" SPACE(10) AS DscDocumento, ")
loComandoSeleccionar.AppendLine(" 0.00 AS DscPor_Des, ")
loComandoSeleccionar.AppendLine(" 0.00 AS DscMon_Des, ")
loComandoSeleccionar.AppendLine(" 0.00 AS DscMon_Bru, ")
loComandoSeleccionar.AppendLine(" 0.00 AS DscMon_Net, ")
loComandoSeleccionar.AppendLine(" 0.00 AS VenCan_Doc, ")
loComandoSeleccionar.AppendLine(" SPACE(10) AS VenTip_Doc, ")
loComandoSeleccionar.AppendLine(" 0.00 AS VenMon_Bru, ")
loComandoSeleccionar.AppendLine(" 0.00 AS VenMon_BruF, ")
loComandoSeleccionar.AppendLine(" 0.00 AS VenMon_BruNC, ")
loComandoSeleccionar.AppendLine(" SPACE(10) AS VenDoc_Ini, ")
loComandoSeleccionar.AppendLine(" SPACE(10) AS VenDoc_Fin ")
loComandoSeleccionar.AppendLine(" FROM #TablaTemporalCheques1 ")
loComandoSeleccionar.AppendLine(" UNION ALL ")
loComandoSeleccionar.AppendLine(" SELECT 5 AS Orden, ")
loComandoSeleccionar.AppendLine(" 'RelTar' AS Tipo, ")
loComandoSeleccionar.AppendLine(" TFec_Ini AS Fec_Ini, ")
loComandoSeleccionar.AppendLine(" TFecha2 AS Fecha2,")
loComandoSeleccionar.AppendLine(" SPACE(20) AS Tip_Ope, ")
loComandoSeleccionar.AppendLine(" 0.00 AS Cuantas, ")
loComandoSeleccionar.AppendLine(" 0.00 AS Monto, ")
loComandoSeleccionar.AppendLine(" 0.00 AS CMon_Com, ")
loComandoSeleccionar.AppendLine(" 0.00 AS CMon_Ret, ")
loComandoSeleccionar.AppendLine(" SPACE(30) AS Cod_Ven, ")
loComandoSeleccionar.AppendLine(" SPACE(30) AS Nom_Ven, ")
loComandoSeleccionar.AppendLine(" 0.00 AS Por_Ven, ")
loComandoSeleccionar.AppendLine(" 0.00 AS Cuantos, ")
loComandoSeleccionar.AppendLine(" 0.00 AS Mon_Bru, ")
loComandoSeleccionar.AppendLine(" 0.00 AS Mon_Net, ")
loComandoSeleccionar.AppendLine(" 0.00 AS Mon_Com, ")
loComandoSeleccionar.AppendLine(" 0.00 AS Pares, ")
loComandoSeleccionar.AppendLine(" TDocumento AS TDocumento, ")
loComandoSeleccionar.AppendLine(" TFec_Ini AS TFec_Ini, ")
loComandoSeleccionar.AppendLine(" TCod_Ven AS TCod_Ven, ")
loComandoSeleccionar.AppendLine(" TCod_Tar AS TCod_Tar, ")
loComandoSeleccionar.AppendLine(" TNum_Doc AS TNum_Doc, ")
loComandoSeleccionar.AppendLine(" TMon_Net AS TMon_Net, ")
loComandoSeleccionar.AppendLine(" TPor_Com AS TPor_Com, ")
loComandoSeleccionar.AppendLine(" TMon_Com AS TMon_Com, ")
loComandoSeleccionar.AppendLine(" TPor_Ret AS TPor_Ret, ")
loComandoSeleccionar.AppendLine(" TMon_Ret AS TMon_Ret, ")
loComandoSeleccionar.AppendLine(" TCod_Tip AS TCod_Tip, ")
loComandoSeleccionar.AppendLine(" SPACE(10) AS Doc_Ini, ")
loComandoSeleccionar.AppendLine(" SPACE(10) AS Doc_Fin, ")
loComandoSeleccionar.AppendLine(" 0.00 AS ChMon_Net, ")
loComandoSeleccionar.AppendLine(" SPACE(10) AS ChDocumento, ")
loComandoSeleccionar.AppendLine(" SPACE(20) AS ChNum_Doc, ")
loComandoSeleccionar.AppendLine(" SPACE(30) AS ChNom_Ban, ")
loComandoSeleccionar.AppendLine(" SPACE(10) AS DscDocumento, ")
loComandoSeleccionar.AppendLine(" 0.00 AS DscPor_Des, ")
loComandoSeleccionar.AppendLine(" 0.00 AS DscMon_Des, ")
loComandoSeleccionar.AppendLine(" 0.00 AS DscMon_Bru, ")
loComandoSeleccionar.AppendLine(" 0.00 AS DscMon_Net, ")
loComandoSeleccionar.AppendLine(" 0.00 AS VenCan_Doc, ")
loComandoSeleccionar.AppendLine(" SPACE(10) AS VenTip_Doc, ")
loComandoSeleccionar.AppendLine(" 0.00 AS VenMon_Bru, ")
loComandoSeleccionar.AppendLine(" 0.00 AS VenMon_BruF, ")
loComandoSeleccionar.AppendLine(" 0.00 AS VenMon_BruNC, ")
loComandoSeleccionar.AppendLine(" SPACE(10) AS VenDoc_Ini, ")
loComandoSeleccionar.AppendLine(" SPACE(10) AS VenDoc_Fin ")
loComandoSeleccionar.AppendLine(" FROM #TablaTemporalTarjetas1 ")
loComandoSeleccionar.AppendLine(" UNION ALL ")
loComandoSeleccionar.AppendLine(" SELECT 6 AS Orden,")
loComandoSeleccionar.AppendLine(" 'RelCom' AS Tipo,")
loComandoSeleccionar.AppendLine(" Fec_Ini AS Fec_Ini, ")
loComandoSeleccionar.AppendLine(" Fecha2 AS Fecha2,")
loComandoSeleccionar.AppendLine(" SPACE(20) AS Tip_Ope, ")
loComandoSeleccionar.AppendLine(" 0.00 AS Cuantas, ")
loComandoSeleccionar.AppendLine(" 0.00 AS Monto, ")
loComandoSeleccionar.AppendLine(" 0.00 AS CMon_Com, ")
loComandoSeleccionar.AppendLine(" 0.00 AS CMon_Ret, ")
loComandoSeleccionar.AppendLine(" Cod_Ven AS Cod_Ven, ")
loComandoSeleccionar.AppendLine(" Nom_Ven AS Nom_Ven, ")
loComandoSeleccionar.AppendLine(" Por_Ven AS Por_Ven, ")
loComandoSeleccionar.AppendLine(" Cuantos AS Cuantos, ")
loComandoSeleccionar.AppendLine(" Mon_Bru AS Mon_Bru, ")
loComandoSeleccionar.AppendLine(" Mon_Net AS Mon_Net, ")
loComandoSeleccionar.AppendLine(" Mon_Com AS Mon_Com, ")
loComandoSeleccionar.AppendLine(" Pares AS Pares, ")
loComandoSeleccionar.AppendLine(" SPACE(10) AS TDocumento, ")
loComandoSeleccionar.AppendLine(" Fec_Ini AS TFec_Ini, ")
loComandoSeleccionar.AppendLine(" SPACE(30) AS TCod_Ven, ")
loComandoSeleccionar.AppendLine(" SPACE(30) AS TCod_Tar, ")
loComandoSeleccionar.AppendLine(" SPACE(30) AS TNum_Doc, ")
loComandoSeleccionar.AppendLine(" 0.00 AS TMon_Net, ")
loComandoSeleccionar.AppendLine(" 0.00 AS TPor_Com, ")
loComandoSeleccionar.AppendLine(" 0.00 AS TMon_Com, ")
loComandoSeleccionar.AppendLine(" 0.00 AS TPor_Ret, ")
loComandoSeleccionar.AppendLine(" 0.00 AS TMon_Ret, ")
loComandoSeleccionar.AppendLine(" SPACE(10) AS TCod_Tip, ")
loComandoSeleccionar.AppendLine(" SPACE(10) AS Doc_Ini, ")
loComandoSeleccionar.AppendLine(" SPACE(10) AS Doc_Fin, ")
loComandoSeleccionar.AppendLine(" 0.00 AS ChMon_Net, ")
loComandoSeleccionar.AppendLine(" SPACE(10) AS ChDocumento, ")
loComandoSeleccionar.AppendLine(" SPACE(20) AS ChNum_Doc, ")
loComandoSeleccionar.AppendLine(" SPACE(30) AS ChNom_Ban, ")
loComandoSeleccionar.AppendLine(" SPACE(10) AS DscDocumento, ")
loComandoSeleccionar.AppendLine(" 0.00 AS DscPor_Des, ")
loComandoSeleccionar.AppendLine(" 0.00 AS DscMon_Des, ")
loComandoSeleccionar.AppendLine(" 0.00 AS DscMon_Bru, ")
loComandoSeleccionar.AppendLine(" 0.00 AS DscMon_Net, ")
loComandoSeleccionar.AppendLine(" 0.00 AS VenCan_Doc, ")
loComandoSeleccionar.AppendLine(" SPACE(10) AS VenTip_Doc, ")
loComandoSeleccionar.AppendLine(" 0.00 AS VenMon_Bru, ")
loComandoSeleccionar.AppendLine(" 0.00 AS VenMon_BruF, ")
loComandoSeleccionar.AppendLine(" 0.00 AS VenMon_BruNC, ")
loComandoSeleccionar.AppendLine(" SPACE(10) AS VenDoc_Ini, ")
loComandoSeleccionar.AppendLine(" SPACE(10) AS VenDoc_Fin ")
loComandoSeleccionar.AppendLine(" FROM #TablaTemporalComisiones2 ")
loComandoSeleccionar.AppendLine(" ) ")
loComandoSeleccionar.AppendLine(" SELECT Orden, ")
loComandoSeleccionar.AppendLine(" Tipo, ")
loComandoSeleccionar.AppendLine(" Fec_Ini,")
loComandoSeleccionar.AppendLine(" Tip_Ope, ")
loComandoSeleccionar.AppendLine(" Cuantas, ")
loComandoSeleccionar.AppendLine(" Monto, ")
loComandoSeleccionar.AppendLine(" CMon_Com, ")
loComandoSeleccionar.AppendLine(" CMon_Ret, ")
loComandoSeleccionar.AppendLine(" Cod_Ven, ")
loComandoSeleccionar.AppendLine(" Nom_Ven, ")
loComandoSeleccionar.AppendLine(" Por_Ven, ")
loComandoSeleccionar.AppendLine(" Cuantos, ")
loComandoSeleccionar.AppendLine(" Mon_Bru, ")
loComandoSeleccionar.AppendLine(" Mon_Net, ")
loComandoSeleccionar.AppendLine(" Mon_Com, ")
loComandoSeleccionar.AppendLine(" Pares, ")
loComandoSeleccionar.AppendLine(" TDocumento, ")
loComandoSeleccionar.AppendLine(" TFec_Ini, ")
loComandoSeleccionar.AppendLine(" TCod_Ven, ")
loComandoSeleccionar.AppendLine(" TCod_Tar, ")
loComandoSeleccionar.AppendLine(" TNum_Doc, ")
loComandoSeleccionar.AppendLine(" TMon_Net, ")
loComandoSeleccionar.AppendLine(" TPor_Com, ")
loComandoSeleccionar.AppendLine(" TMon_Com, ")
loComandoSeleccionar.AppendLine(" TPor_Ret, ")
loComandoSeleccionar.AppendLine(" TMon_Ret, ")
loComandoSeleccionar.AppendLine(" TCod_Tip, ")
loComandoSeleccionar.AppendLine(" Doc_Ini, ")
loComandoSeleccionar.AppendLine(" Doc_Fin, ")
loComandoSeleccionar.AppendLine(" ChMon_Net, ")
loComandoSeleccionar.AppendLine(" ChDocumento, ")
loComandoSeleccionar.AppendLine(" ChNum_Doc, ")
loComandoSeleccionar.AppendLine(" ChNom_Ban, ")
loComandoSeleccionar.AppendLine(" DscDocumento, ")
loComandoSeleccionar.AppendLine(" DscPor_Des, ")
loComandoSeleccionar.AppendLine(" DscMon_Des, ")
loComandoSeleccionar.AppendLine(" DscMon_Bru, ")
loComandoSeleccionar.AppendLine(" DscMon_Net, ")
loComandoSeleccionar.AppendLine(" VenCan_Doc, ")
loComandoSeleccionar.AppendLine(" VenTip_Doc, ")
loComandoSeleccionar.AppendLine(" VenMon_Bru, ")
loComandoSeleccionar.AppendLine(" VenMon_BruF, ")
loComandoSeleccionar.AppendLine(" VenMon_BruNC, ")
loComandoSeleccionar.AppendLine(" VenDoc_Ini, ")
loComandoSeleccionar.AppendLine(" VenDoc_Fin ")
loComandoSeleccionar.AppendLine(" FROM curTemporal ")
'loComandoSeleccionar.AppendLine(" ORDER BY Fecha2 ASC, Orden ")
loComandoSeleccionar.AppendLine("ORDER BY " & lcOrdenamiento & ", Orden")
Dim loServicios As New cusDatos.goDatos
Dim laDatosReporte As DataSet = loServicios.mObtenerTodosSinEsquema(loComandoSeleccionar.ToString, "curReportes")
'-------------------------------------------------------------------------------------------------------
' Verificando si el select (tabla nº0) trae registros
'-------------------------------------------------------------------------------------------------------
If (laDatosReporte.Tables(0).Rows.Count <= 0) Then
Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Información", _
"No se Encontraron Registros para los Parámetros Especificados. ", _
vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Informacion, _
"350px", _
"200px")
End If
loObjetoReporte = cusAplicacion.goReportes.mCargarReporte("rRVentas_CBancarias", laDatosReporte)
Me.mTraducirReporte(loObjetoReporte)
Me.mFormatearCamposReporte(loObjetoReporte)
Me.crvrRVentas_CBancarias.ReportSource = loObjetoReporte
Catch loExcepcion As Exception
Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Error", _
"No se pudo Completar el Proceso: " & loExcepcion.Message, _
vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Error, _
"auto", _
"auto")
End Try
End Sub
Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
Try
loObjetoReporte.Close()
Catch loExcepcion As Exception
End Try
End Sub
End Class
'-------------------------------------------------------------------------------------------'
' Fin del codigo
'-------------------------------------------------------------------------------------------'
' JJD: 29/07/08: Codigo inicial
'-------------------------------------------------------------------------------------------'
' JJD: 30/07/08: Ajustes a los campos que se traia el reporte
'-------------------------------------------------------------------------------------------'
' JJD: 10/10/08: Adecuacion segun los parametros del reporte original
'-------------------------------------------------------------------------------------------'
' JJD: 11/10/08: Continuacion de la adecuacion segun los parametros del reporte original
'-------------------------------------------------------------------------------------------'
' JJD: 13/10/08: Continuacion de la adecuacion segun los parametros del reporte original
'-------------------------------------------------------------------------------------------'
' JJD: 25/10/08: Ajustes a la busqueda de los cheques y las tarjetas
'-------------------------------------------------------------------------------------------'
' CMS: 14/08/09: Metodo de ordenamiento, verificacionde registros
'-------------------------------------------------------------------------------------------'
|
kodeitsolutions/ef-reports
|
rRVentas_CBancarias.aspx.vb
|
Visual Basic
|
mit
| 51,847
|
Namespace Extensions
Public Module System_Data_SqlClient_SqlCommand
<System.Runtime.CompilerServices.Extension()> Public Sub AddParameters(cmd As System.Data.SqlClient.SqlCommand, parameters As IDictionary(Of String, Object))
If cmd Is Nothing Then
Return
End If
If parameters Is Nothing Then
Return
End If
If parameters.Count <= 0 Then
Return
End If
cmd.Parameters.AddRange(parameters.Select(Function(o) New System.Data.SqlClient.SqlParameter(o.Key, Data.GetDBParameter(o.Value))).ToArray())
End Sub
End Module
End Namespace
|
nublet/APRBase
|
APRBase/Extensions/System_Data_SqlClient_SqlCommand.vb
|
Visual Basic
|
mit
| 688
|
Imports Transporter_AEHF.BurchfieldPositionerControl
Imports Transporter_AEHF.Objects.Enumerations
Imports Transporter_AEHF.Objects.Positioners
Imports NLog
Public Class PositionerConnectionForm
Private _addressType As PumaEnums.ConnectionType
Private _positionerModel As PumaEnums.PositionerModel
Private _main As Main
Private _positioner As Object
Private Const EthernetHeader = ""
Private Const EthernetFooter = ""
Private Const UsbHeader = ""
Private _log As Logger = LogManager.GetCurrentClassLogger
Private _loggerSelection As String
Sub New(ByVal aMain As Main)
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
_loggerSelection = aMain.LoggerSelection
_main = aMain
End Sub
Private Sub cmboBoxConnectionType_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmboBoxConnectionType.SelectedIndexChanged
If cmboBoxConnectionType.SelectedIndex = 0 Then 'if user selects ethernet
lblConnectionAddress.Text = "Enter IP Adress"
txtBoxConnectionAddress.Text = "192.168.100.179" '"TCPIP0::192.168.100.179::80::SOCKET" '169.254.117.216::INSTR"
lblPort.Text = "Enter Port"
txtBoxConnectionPort.Text = "4000"
txtBoxConnectionAddress.Enabled = True
txtBoxConnectionPort.Enabled = True
_addressType = PumaEnums.ConnectionType.Ip
ElseIf cmboBoxConnectionType.SelectedIndex = 1 Then 'if user selects com
lblConnectionAddress.Text = "Com"
txtBoxConnectionAddress.Text = "COM"
lblPort.Text = "Enter Port"
txtBoxConnectionPort.Text = "4"
txtBoxConnectionPort.Enabled = True
_addressType = PumaEnums.ConnectionType.Com
End If
End Sub
Private Sub btnConnectPositioner_Click(sender As Object, e As EventArgs) Handles btnConnectPositioner.Click
Dim address = Trim(txtBoxConnectionAddress.Text)
Dim port = Trim(txtBoxConnectionPort.Text)
'check the type of connection
If _addressType = PumaEnums.ConnectionType.Ip Then 'if ethernet then use visa session
'check the positioner type
If _positionerModel = PumaEnums.PositionerModel.Burchfield Then 'if ethernet and Burchfield
'try to establish a session
'session should be managed with positioner object
Try
'establish positioner object
_positioner = New BurchfieldUnit()
_positioner.connect(address, port, _addressType, _loggerSelection)
'send positioner object to positioner form
Dim posForm = New BurchfieldPositionerForm(_positioner, _loggerSelection)
posForm.Show()
Close()
Catch ex As Exception
ErrorMessageFormat("Error trying to connect.", ex)
If _positioner IsNot Nothing Then
_positioner.dispose()
End If
End Try
ElseIf _positionerModel = PumaEnums.PositionerModel.DirectedPerception Then 'if ethernet and direct perception
MsgBox("We do not currently support ethernet connections to direct perception positioners. Try USB/Serial connection.")
End If
ElseIf _addressType = PumaEnums.ConnectionType.Com Then 'if usb then use serial session
'check positioner type
If _positionerModel = PumaEnums.PositionerModel.Burchfield Then 'if serial and Burchfield
MsgBox("We do not currently support serial connections to Burchfield positioners. Try Ethernet connection.")
ElseIf _positionerModel = PumaEnums.PositionerModel.DirectedPerception Then 'if serial and direct perception
Try
_positioner = New FlirUnit()
_positioner.connect(address & port)
Dim posForm = New FlirPositionerForm(_main, _positioner)
posForm.Show()
Me.Close()
Catch ex As Exception
ErrorMessageFormat("Error trying to connect.", ex)
_positioner.dispose()
End Try
End If
End If
End Sub
Private Sub cmboBoxPositionerType_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmboBoxPositionerType.SelectedIndexChanged
If cmboBoxPositionerType.SelectedIndex = 0 Then 'if Burchfield selected
_positionerModel = PumaEnums.PositionerModel.Burchfield
cmboBoxConnectionType.Enabled = True
ElseIf cmboBoxPositionerType.SelectedIndex = 1 Then 'if direct perception selected
_positionerModel = PumaEnums.PositionerModel.DirectedPerception
cmboBoxConnectionType.Enabled = True
End If
End Sub
Private Sub btnPositionConnectCancel_Click(sender As Object, e As EventArgs) Handles btnPositionConnectCancel.Click
Me.Dispose()
Me.Close()
End Sub
Private Sub ErrorMessageFormat(ByVal message As String, ByVal ex As Exception)
If ex.InnerException IsNot Nothing Then
MsgBox(message & vbNewLine & "Message:" & vbNewLine & ex.Message & vbNewLine & "Inner Exception" & vbNewLine & _
ex.InnerException.Message, vbMsgBoxSetForeground)
Else
MsgBox(message & vbNewLine & "Message:" & vbNewLine & ex.Message, vbMsgBoxSetForeground)
End If
End Sub
End Class
|
wboxx1/85-EIS-PUMA
|
puma/src/Supporting Forms/Positioners/PositionerConnectionForm.vb
|
Visual Basic
|
mit
| 5,690
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class MainWindow
Inherits MetroFramework.Forms.MetroForm
'Form remplace la méthode Dispose pour nettoyer la liste des composants.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
'Requise par le Concepteur Windows Form
Private components As System.ComponentModel.IContainer
'REMARQUE : la procédure suivante est requise par le Concepteur Windows Form
'Elle peut être modifiée à l'aide du Concepteur Windows Form.
'Ne la modifiez pas à l'aide de l'éditeur de code.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.mainPanel = New MetroFramework.Controls.MetroPanel()
Me.tlpContent = New System.Windows.Forms.TableLayoutPanel()
Me.dgvSounds = New System.Windows.Forms.DataGridView()
Me.colSoundLink = New IlshiPlay.SoundColumn()
Me.colPlayButton = New IlshiPlay.KeyColumn()
Me.cbMicrophone = New MetroFramework.Controls.MetroComboBox()
Me.tlpButtons = New System.Windows.Forms.TableLayoutPanel()
Me.btnSave = New MetroFramework.Controls.MetroButton()
Me.btnImport = New MetroFramework.Controls.MetroButton()
Me.TableLayoutPanel1 = New System.Windows.Forms.TableLayoutPanel()
Me.tbVolume = New MetroFramework.Controls.MetroTrackBar()
Me.lblVolume = New MetroFramework.Controls.MetroLabel()
Me.TableLayoutPanel2 = New System.Windows.Forms.TableLayoutPanel()
Me.btnToggleKey = New MetroFramework.Controls.MetroLabel()
Me.cbUserOutput = New MetroFramework.Controls.MetroCheckBox()
Me.linkAbout = New MetroFramework.Controls.MetroLink()
Me.bgwPlayer = New System.ComponentModel.BackgroundWorker()
Me.lblPlayingSong = New MetroFramework.Controls.MetroLabel()
Me.KeyColumn1 = New IlshiPlay.KeyColumn()
Me.KeyComboBoxColumn1 = New IlshiPlay.KeyColumn()
Me.mainPanel.SuspendLayout()
Me.tlpContent.SuspendLayout()
CType(Me.dgvSounds, System.ComponentModel.ISupportInitialize).BeginInit()
Me.tlpButtons.SuspendLayout()
Me.TableLayoutPanel1.SuspendLayout()
Me.TableLayoutPanel2.SuspendLayout()
Me.SuspendLayout()
'
'mainPanel
'
Me.mainPanel.Controls.Add(Me.tlpContent)
Me.mainPanel.Dock = System.Windows.Forms.DockStyle.Fill
Me.mainPanel.HorizontalScrollbarBarColor = True
Me.mainPanel.HorizontalScrollbarHighlightOnWheel = False
Me.mainPanel.HorizontalScrollbarSize = 8
Me.mainPanel.Location = New System.Drawing.Point(15, 60)
Me.mainPanel.Margin = New System.Windows.Forms.Padding(2)
Me.mainPanel.Name = "mainPanel"
Me.mainPanel.Size = New System.Drawing.Size(270, 265)
Me.mainPanel.TabIndex = 0
Me.mainPanel.VerticalScrollbarBarColor = True
Me.mainPanel.VerticalScrollbarHighlightOnWheel = False
Me.mainPanel.VerticalScrollbarSize = 8
'
'tlpContent
'
Me.tlpContent.ColumnCount = 1
Me.tlpContent.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100.0!))
Me.tlpContent.Controls.Add(Me.dgvSounds, 0, 3)
Me.tlpContent.Controls.Add(Me.cbMicrophone, 0, 0)
Me.tlpContent.Controls.Add(Me.tlpButtons, 0, 4)
Me.tlpContent.Controls.Add(Me.TableLayoutPanel1, 0, 1)
Me.tlpContent.Controls.Add(Me.TableLayoutPanel2, 0, 2)
Me.tlpContent.Dock = System.Windows.Forms.DockStyle.Fill
Me.tlpContent.Location = New System.Drawing.Point(0, 0)
Me.tlpContent.Margin = New System.Windows.Forms.Padding(2)
Me.tlpContent.Name = "tlpContent"
Me.tlpContent.RowCount = 5
Me.tlpContent.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 29.0!))
Me.tlpContent.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 29.0!))
Me.tlpContent.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 29.0!))
Me.tlpContent.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100.0!))
Me.tlpContent.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 29.0!))
Me.tlpContent.Size = New System.Drawing.Size(270, 265)
Me.tlpContent.TabIndex = 2
'
'dgvSounds
'
Me.dgvSounds.BackgroundColor = System.Drawing.Color.Azure
Me.dgvSounds.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize
Me.dgvSounds.Columns.AddRange(New System.Windows.Forms.DataGridViewColumn() {Me.colSoundLink, Me.colPlayButton})
Me.dgvSounds.Dock = System.Windows.Forms.DockStyle.Fill
Me.dgvSounds.Location = New System.Drawing.Point(2, 89)
Me.dgvSounds.Margin = New System.Windows.Forms.Padding(2)
Me.dgvSounds.Name = "dgvSounds"
Me.dgvSounds.RowTemplate.Height = 24
Me.dgvSounds.Size = New System.Drawing.Size(266, 145)
Me.dgvSounds.TabIndex = 1
'
'colSoundLink
'
Me.colSoundLink.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill
Me.colSoundLink.HeaderText = "Path"
Me.colSoundLink.Name = "colSoundLink"
Me.colSoundLink.ReadOnly = True
Me.colSoundLink.Resizable = System.Windows.Forms.DataGridViewTriState.[True]
'
'colPlayButton
'
Me.colPlayButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat
Me.colPlayButton.HeaderText = "Key"
Me.colPlayButton.Items.AddRange(New Object() {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"})
Me.colPlayButton.Name = "colPlayButton"
Me.colPlayButton.Resizable = System.Windows.Forms.DataGridViewTriState.[True]
Me.colPlayButton.Width = 50
'
'cbMicrophone
'
Me.cbMicrophone.Dock = System.Windows.Forms.DockStyle.Fill
Me.cbMicrophone.FormattingEnabled = True
Me.cbMicrophone.ItemHeight = 23
Me.cbMicrophone.Location = New System.Drawing.Point(2, 2)
Me.cbMicrophone.Margin = New System.Windows.Forms.Padding(2)
Me.cbMicrophone.Name = "cbMicrophone"
Me.cbMicrophone.Size = New System.Drawing.Size(266, 29)
Me.cbMicrophone.TabIndex = 2
Me.cbMicrophone.UseSelectable = True
'
'tlpButtons
'
Me.tlpButtons.ColumnCount = 2
Me.tlpButtons.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50.0!))
Me.tlpButtons.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50.0!))
Me.tlpButtons.Controls.Add(Me.btnSave, 1, 0)
Me.tlpButtons.Controls.Add(Me.btnImport, 0, 0)
Me.tlpButtons.Dock = System.Windows.Forms.DockStyle.Fill
Me.tlpButtons.Location = New System.Drawing.Point(2, 238)
Me.tlpButtons.Margin = New System.Windows.Forms.Padding(2)
Me.tlpButtons.Name = "tlpButtons"
Me.tlpButtons.RowCount = 1
Me.tlpButtons.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50.0!))
Me.tlpButtons.Size = New System.Drawing.Size(266, 25)
Me.tlpButtons.TabIndex = 3
'
'btnSave
'
Me.btnSave.Dock = System.Windows.Forms.DockStyle.Fill
Me.btnSave.Location = New System.Drawing.Point(135, 2)
Me.btnSave.Margin = New System.Windows.Forms.Padding(2)
Me.btnSave.Name = "btnSave"
Me.btnSave.Size = New System.Drawing.Size(129, 21)
Me.btnSave.TabIndex = 3
Me.btnSave.Text = "Save ..."
Me.btnSave.UseSelectable = True
'
'btnImport
'
Me.btnImport.Dock = System.Windows.Forms.DockStyle.Fill
Me.btnImport.Location = New System.Drawing.Point(2, 2)
Me.btnImport.Margin = New System.Windows.Forms.Padding(2)
Me.btnImport.Name = "btnImport"
Me.btnImport.Size = New System.Drawing.Size(129, 21)
Me.btnImport.TabIndex = 0
Me.btnImport.Text = "Import ..."
Me.btnImport.UseSelectable = True
'
'TableLayoutPanel1
'
Me.TableLayoutPanel1.ColumnCount = 2
Me.TableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 85.0!))
Me.TableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 15.0!))
Me.TableLayoutPanel1.Controls.Add(Me.tbVolume, 0, 0)
Me.TableLayoutPanel1.Controls.Add(Me.lblVolume, 1, 0)
Me.TableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill
Me.TableLayoutPanel1.Location = New System.Drawing.Point(2, 31)
Me.TableLayoutPanel1.Margin = New System.Windows.Forms.Padding(2)
Me.TableLayoutPanel1.Name = "TableLayoutPanel1"
Me.TableLayoutPanel1.RowCount = 1
Me.TableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100.0!))
Me.TableLayoutPanel1.Size = New System.Drawing.Size(266, 25)
Me.TableLayoutPanel1.TabIndex = 5
'
'tbVolume
'
Me.tbVolume.BackColor = System.Drawing.Color.Transparent
Me.tbVolume.Dock = System.Windows.Forms.DockStyle.Fill
Me.tbVolume.Location = New System.Drawing.Point(2, 2)
Me.tbVolume.Margin = New System.Windows.Forms.Padding(2)
Me.tbVolume.Name = "tbVolume"
Me.tbVolume.Size = New System.Drawing.Size(222, 21)
Me.tbVolume.Style = MetroFramework.MetroColorStyle.Blue
Me.tbVolume.TabIndex = 5
'
'lblVolume
'
Me.lblVolume.Dock = System.Windows.Forms.DockStyle.Fill
Me.lblVolume.Location = New System.Drawing.Point(228, 0)
Me.lblVolume.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0)
Me.lblVolume.Name = "lblVolume"
Me.lblVolume.Size = New System.Drawing.Size(36, 25)
Me.lblVolume.TabIndex = 6
Me.lblVolume.Text = "0.0"
Me.lblVolume.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
'
'TableLayoutPanel2
'
Me.TableLayoutPanel2.ColumnCount = 2
Me.TableLayoutPanel2.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 69.14498!))
Me.TableLayoutPanel2.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 30.85502!))
Me.TableLayoutPanel2.Controls.Add(Me.btnToggleKey, 1, 0)
Me.TableLayoutPanel2.Controls.Add(Me.cbUserOutput, 0, 0)
Me.TableLayoutPanel2.Dock = System.Windows.Forms.DockStyle.Fill
Me.TableLayoutPanel2.Location = New System.Drawing.Point(2, 60)
Me.TableLayoutPanel2.Margin = New System.Windows.Forms.Padding(2)
Me.TableLayoutPanel2.Name = "TableLayoutPanel2"
Me.TableLayoutPanel2.RowCount = 1
Me.TableLayoutPanel2.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50.0!))
Me.TableLayoutPanel2.Size = New System.Drawing.Size(266, 25)
Me.TableLayoutPanel2.TabIndex = 6
'
'btnToggleKey
'
Me.btnToggleKey.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
Me.btnToggleKey.Dock = System.Windows.Forms.DockStyle.Fill
Me.btnToggleKey.Location = New System.Drawing.Point(186, 0)
Me.btnToggleKey.Name = "btnToggleKey"
Me.btnToggleKey.Size = New System.Drawing.Size(77, 25)
Me.btnToggleKey.Style = MetroFramework.MetroColorStyle.Black
Me.btnToggleKey.TabIndex = 3
Me.btnToggleKey.Text = "<toggle>"
Me.btnToggleKey.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
Me.btnToggleKey.UseStyleColors = True
'
'cbUserOutput
'
Me.cbUserOutput.Dock = System.Windows.Forms.DockStyle.Fill
Me.cbUserOutput.Location = New System.Drawing.Point(2, 2)
Me.cbUserOutput.Margin = New System.Windows.Forms.Padding(2)
Me.cbUserOutput.Name = "cbUserOutput"
Me.cbUserOutput.Size = New System.Drawing.Size(179, 21)
Me.cbUserOutput.TabIndex = 4
Me.cbUserOutput.Text = "Hear on main headphones"
Me.cbUserOutput.UseSelectable = True
'
'linkAbout
'
Me.linkAbout.Anchor = CType((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.linkAbout.Location = New System.Drawing.Point(227, 37)
Me.linkAbout.Margin = New System.Windows.Forms.Padding(2)
Me.linkAbout.Name = "linkAbout"
Me.linkAbout.Size = New System.Drawing.Size(56, 19)
Me.linkAbout.TabIndex = 1
Me.linkAbout.Text = "About ..."
Me.linkAbout.TextAlign = System.Drawing.ContentAlignment.MiddleRight
Me.linkAbout.UseSelectable = True
'
'bgwPlayer
'
'
'lblPlayingSong
'
Me.lblPlayingSong.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Left), System.Windows.Forms.AnchorStyles)
Me.lblPlayingSong.AutoSize = True
Me.lblPlayingSong.Location = New System.Drawing.Point(17, 325)
Me.lblPlayingSong.Margin = New System.Windows.Forms.Padding(2, 0, 2, 0)
Me.lblPlayingSong.Name = "lblPlayingSong"
Me.lblPlayingSong.Size = New System.Drawing.Size(64, 19)
Me.lblPlayingSong.TabIndex = 2
Me.lblPlayingSong.Text = "Playing ..."
Me.lblPlayingSong.Visible = False
'
'KeyColumn1
'
Me.KeyColumn1.FlatStyle = System.Windows.Forms.FlatStyle.Flat
Me.KeyColumn1.HeaderText = ""
Me.KeyColumn1.Items.AddRange(New Object() {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"})
Me.KeyColumn1.Name = "KeyColumn1"
Me.KeyColumn1.Resizable = System.Windows.Forms.DataGridViewTriState.[True]
Me.KeyColumn1.Width = 50
'
'KeyComboBoxColumn1
'
Me.KeyComboBoxColumn1.FlatStyle = System.Windows.Forms.FlatStyle.Flat
Me.KeyComboBoxColumn1.HeaderText = ""
Me.KeyComboBoxColumn1.Items.AddRange(New Object() {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"})
Me.KeyComboBoxColumn1.Name = "KeyComboBoxColumn1"
Me.KeyComboBoxColumn1.Resizable = System.Windows.Forms.DataGridViewTriState.[True]
Me.KeyComboBoxColumn1.Width = 50
'
'MainWindow
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(300, 341)
Me.Controls.Add(Me.lblPlayingSong)
Me.Controls.Add(Me.linkAbout)
Me.Controls.Add(Me.mainPanel)
Me.Margin = New System.Windows.Forms.Padding(2)
Me.MaximizeBox = False
Me.MaximumSize = New System.Drawing.Size(300, 650)
Me.MinimumSize = New System.Drawing.Size(300, 341)
Me.Name = "MainWindow"
Me.Padding = New System.Windows.Forms.Padding(15, 60, 15, 16)
Me.Text = "IlshiPlay"
Me.mainPanel.ResumeLayout(False)
Me.tlpContent.ResumeLayout(False)
CType(Me.dgvSounds, System.ComponentModel.ISupportInitialize).EndInit()
Me.tlpButtons.ResumeLayout(False)
Me.TableLayoutPanel1.ResumeLayout(False)
Me.TableLayoutPanel2.ResumeLayout(False)
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Private WithEvents bgwPlayer As System.ComponentModel.BackgroundWorker
Private WithEvents lblPlayingSong As MetroFramework.Controls.MetroLabel
Private WithEvents mainPanel As MetroFramework.Controls.MetroPanel
Private WithEvents tlpContent As System.Windows.Forms.TableLayoutPanel
Private WithEvents btnImport As MetroFramework.Controls.MetroButton
Private WithEvents linkAbout As MetroFramework.Controls.MetroLink
Private WithEvents dgvSounds As System.Windows.Forms.DataGridView
Private WithEvents cbMicrophone As MetroFramework.Controls.MetroComboBox
Private WithEvents btnSave As MetroFramework.Controls.MetroButton
Private WithEvents KeyComboBoxColumn1 As IlshiPlay.KeyColumn
Private WithEvents tlpButtons As System.Windows.Forms.TableLayoutPanel
Private WithEvents cbUserOutput As MetroFramework.Controls.MetroCheckBox
Private WithEvents KeyColumn1 As IlshiPlay.KeyColumn
Private WithEvents colSoundLink As IlshiPlay.SoundColumn
Private WithEvents colPlayButton As IlshiPlay.KeyColumn
Private WithEvents tbVolume As MetroFramework.Controls.MetroTrackBar
Private WithEvents TableLayoutPanel1 As System.Windows.Forms.TableLayoutPanel
Private WithEvents lblVolume As MetroFramework.Controls.MetroLabel
Private WithEvents TableLayoutPanel2 As System.Windows.Forms.TableLayoutPanel
Friend WithEvents btnToggleKey As MetroFramework.Controls.MetroLabel
End Class
|
Ilshidur/IlshiPlay
|
IlshiPlay/MainWindow.Designer.vb
|
Visual Basic
|
mit
| 16,047
|
Namespace Security.SystemOptions_Accounts
Public Class Open
Inherits SecurityItemBase
Public Sub New()
_ConceptItemName = "Open"
_ConceptName = "System Options_Accounts"
_Description = "Allow access to 'Account Settings' Tab"
_IsEnterprise = True
_IsSmallBusiness = True
_IsViewer = False
_IsWeb = False
_IsWebPlus = False
End Sub
End Class
End Namespace
|
nublet/DMS
|
DMS.Forms.Shared/Security/Items/SystemOptions/Accounts/Open.vb
|
Visual Basic
|
mit
| 492
|
Imports System
Imports System.Reflection
Imports 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.
' Review the values of the assembly attributes
<Assembly: AssemblyTitle("CompressionBoss")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("")>
<Assembly: AssemblyProduct("CompressionBoss")>
<Assembly: AssemblyCopyright("Copyright © 2014")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("d044c858-0fbf-4d1a-8f40-adf2051c06a2")>
' 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")>
|
waystoskinacat/compBoss
|
src/My Project/AssemblyInfo.vb
|
Visual Basic
|
apache-2.0
| 1,148
|
' 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.
Imports System.Collections.Immutable
Imports System.Runtime.CompilerServices
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles
Imports Microsoft.CodeAnalysis.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices
Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions
Partial Friend Module SemanticModelExtensions
Private Const DefaultParameterName = "p"
<Extension()>
Public Function GenerateParameterNames(semanticModel As SemanticModel,
arguments As ArgumentListSyntax,
reservedNames As IEnumerable(Of String),
cancellationToken As CancellationToken) As ImmutableArray(Of ParameterName)
If arguments Is Nothing Then
Return ImmutableArray(Of ParameterName).Empty
End If
Return GenerateParameterNames(
semanticModel, arguments.Arguments.ToList(),
reservedNames, cancellationToken)
End Function
<Extension()>
Public Function GenerateParameterNames(semanticModel As SemanticModel,
arguments As IList(Of ArgumentSyntax),
reservedNames As IEnumerable(Of String),
cancellationToken As CancellationToken) As ImmutableArray(Of ParameterName)
reservedNames = If(reservedNames, SpecializedCollections.EmptyEnumerable(Of String))
Return semanticModel.GenerateParameterNames(
arguments,
Function(s) Not reservedNames.Any(Function(n) CaseInsensitiveComparison.Equals(s, n)),
cancellationToken)
End Function
<Extension()>
Public Function GenerateParameterNames(semanticModel As SemanticModel,
arguments As IList(Of ArgumentSyntax),
reservedNames As IEnumerable(Of String),
parameterNamingRule As NamingRule,
cancellationToken As CancellationToken) As ImmutableArray(Of ParameterName)
reservedNames = If(reservedNames, SpecializedCollections.EmptyEnumerable(Of String))
Return semanticModel.GenerateParameterNames(
arguments,
Function(s) Not reservedNames.Any(Function(n) CaseInsensitiveComparison.Equals(s, n)),
parameterNamingRule,
cancellationToken)
End Function
<Extension()>
Public Function GenerateParameterNames(semanticModel As SemanticModel,
arguments As IList(Of ArgumentSyntax),
canUse As Func(Of String, Boolean),
cancellationToken As CancellationToken) As ImmutableArray(Of ParameterName)
If arguments.Count = 0 Then
Return ImmutableArray(Of ParameterName).Empty
End If
' We can't change the names of named parameters. Any other names we're flexible on.
Dim isFixed = Aggregate arg In arguments
Select arg = TryCast(arg, SimpleArgumentSyntax)
Select arg IsNot Nothing AndAlso arg.NameColonEquals IsNot Nothing
Into ToImmutableArray()
Dim parameterNames = arguments.Select(Function(a) semanticModel.GenerateNameForArgument(a, cancellationToken)).ToImmutableArray()
Return NameGenerator.EnsureUniqueness(parameterNames, isFixed, canUse).
Select(Function(name, index) New ParameterName(name, isFixed(index))).
ToImmutableArray()
End Function
<Extension()>
Public Function GenerateParameterNames(semanticModel As SemanticModel,
arguments As IList(Of ArgumentSyntax),
canUse As Func(Of String, Boolean),
parameterNamingRule As NamingRule,
cancellationToken As CancellationToken) As ImmutableArray(Of ParameterName)
If arguments.Count = 0 Then
Return ImmutableArray(Of ParameterName).Empty
End If
' We can't change the names of named parameters. Any other names we're flexible on.
Dim isFixed = Aggregate arg In arguments
Select arg = TryCast(arg, SimpleArgumentSyntax)
Select arg IsNot Nothing AndAlso arg.NameColonEquals IsNot Nothing
Into ToImmutableArray()
Dim parameterNames = arguments.Select(Function(a) semanticModel.GenerateNameForArgument(a, cancellationToken)).ToImmutableArray()
Return NameGenerator.EnsureUniqueness(parameterNames, isFixed, canUse).
Select(Function(name, index) New ParameterName(name, isFixed(index), parameterNamingRule)).
ToImmutableArray()
End Function
<Extension()>
Public Function GenerateNameForArgument(semanticModel As SemanticModel,
argument As ArgumentSyntax,
cancellationToken As CancellationToken) As String
Dim result = GenerateNameForArgumentWorker(semanticModel, argument, cancellationToken)
Return If(String.IsNullOrWhiteSpace(result), DefaultParameterName, result)
End Function
Private Function GenerateNameForArgumentWorker(semanticModel As SemanticModel,
argument As ArgumentSyntax,
cancellationToken As CancellationToken) As String
If argument.IsNamed Then
Return DirectCast(argument, SimpleArgumentSyntax).NameColonEquals.Name.Identifier.ValueText
ElseIf Not argument.IsOmitted Then
Return semanticModel.GenerateNameForExpression(
argument.GetExpression(), capitalize:=False, cancellationToken:=cancellationToken)
Else
Return DefaultParameterName
End If
End Function
''' <summary>
''' Given an expression node, tries to generate an appropriate name that can be used for
''' that expression.
''' </summary>
<Extension()>
Public Function GenerateNameForExpression(semanticModel As SemanticModel,
expression As ExpressionSyntax,
capitalize As Boolean,
cancellationToken As CancellationToken) As String
' Try to find a usable name node that we can use to name the
' parameter. If we have an expression that has a name as part of it
' then we try to use that part.
Dim current = expression
While True
current = current.WalkDownParentheses()
If current.Kind = SyntaxKind.IdentifierName Then
Return (DirectCast(current, IdentifierNameSyntax)).Identifier.ValueText.ToCamelCase()
ElseIf TypeOf current Is MemberAccessExpressionSyntax Then
Return (DirectCast(current, MemberAccessExpressionSyntax)).Name.Identifier.ValueText.ToCamelCase()
ElseIf TypeOf current Is CastExpressionSyntax Then
current = (DirectCast(current, CastExpressionSyntax)).Expression
Else
Exit While
End If
End While
' there was nothing in the expression to signify a name. If we're in an argument
' location, then try to choose a name based on the argument name.
Dim argumentName = TryGenerateNameForArgumentExpression(
semanticModel, expression, cancellationToken)
If argumentName IsNot Nothing Then
Return If(capitalize, argumentName.ToPascalCase(), argumentName.ToCamelCase())
End If
' Otherwise, figure out the type of the expression and generate a name from that
' instead.
Dim info = semanticModel.GetTypeInfo(expression, cancellationToken)
If info.Type Is Nothing Then
Return DefaultParameterName
End If
Return semanticModel.GenerateNameFromType(info.Type, VisualBasicSyntaxFacts.Instance, capitalize)
End Function
Private Function TryGenerateNameForArgumentExpression(semanticModel As SemanticModel, expression As ExpressionSyntax, cancellationToken As CancellationToken) As String
Dim topExpression = expression.WalkUpParentheses()
If TypeOf topExpression.Parent Is ArgumentSyntax Then
Dim argument = DirectCast(topExpression.Parent, ArgumentSyntax)
Dim simpleArgument = TryCast(argument, SimpleArgumentSyntax)
If simpleArgument?.NameColonEquals IsNot Nothing Then
Return simpleArgument.NameColonEquals.Name.Identifier.ValueText
End If
Dim argumentList = TryCast(argument.Parent, ArgumentListSyntax)
If argumentList IsNot Nothing Then
Dim index = argumentList.Arguments.IndexOf(argument)
Dim member = TryCast(semanticModel.GetSymbolInfo(argumentList.Parent, cancellationToken).Symbol, IMethodSymbol)
If member IsNot Nothing AndAlso index < member.Parameters.Length Then
Dim parameter = member.Parameters(index)
If parameter.Type.TypeKind <> TypeKind.TypeParameter Then
Return parameter.Name
End If
End If
End If
End If
Return Nothing
End Function
End Module
End Namespace
|
brettfo/roslyn
|
src/Workspaces/VisualBasic/Portable/Extensions/SemanticModelExtensions.vb
|
Visual Basic
|
apache-2.0
| 10,698
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Collections.Immutable
Imports System.Composition
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editing
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Simplification
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
<ExportLanguageService(GetType(SyntaxGenerator), LanguageNames.VisualBasic), [Shared]>
Friend Class VisualBasicSyntaxGenerator
Inherits SyntaxGenerator
Public Shared ReadOnly Instance As SyntaxGenerator = New VisualBasicSyntaxGenerator()
<ImportingConstructor>
Public Sub New()
End Sub
Friend Overrides ReadOnly Property ElasticCarriageReturnLineFeed As SyntaxTrivia = SyntaxFactory.ElasticCarriageReturnLineFeed
Friend Overrides ReadOnly Property CarriageReturnLineFeed As SyntaxTrivia = SyntaxFactory.CarriageReturnLineFeed
Friend Overrides ReadOnly Property RequiresExplicitImplementationForInterfaceMembers As Boolean = True
Friend Overrides ReadOnly Property SyntaxFacts As ISyntaxFactsService = VisualBasicSyntaxFactsService.Instance
Friend Overrides Function EndOfLine(text As String) As SyntaxTrivia
Return SyntaxFactory.EndOfLine(text)
End Function
Friend Overrides Function Whitespace(text As String) As SyntaxTrivia
Return SyntaxFactory.Whitespace(text)
End Function
Friend Overrides Function SeparatedList(Of TElement As SyntaxNode)(list As SyntaxNodeOrTokenList) As SeparatedSyntaxList(Of TElement)
Return SyntaxFactory.SeparatedList(Of TElement)(list)
End Function
#Region "Expressions and Statements"
Public Overrides Function AddEventHandler([event] As SyntaxNode, handler As SyntaxNode) As SyntaxNode
Return SyntaxFactory.AddHandlerStatement(CType([event], ExpressionSyntax), CType(handler, ExpressionSyntax))
End Function
Public Overrides Function RemoveEventHandler([event] As SyntaxNode, handler As SyntaxNode) As SyntaxNode
Return SyntaxFactory.RemoveHandlerStatement(CType([event], ExpressionSyntax), CType(handler, ExpressionSyntax))
End Function
Public Overrides Function AwaitExpression(expression As SyntaxNode) As SyntaxNode
Return SyntaxFactory.AwaitExpression(DirectCast(expression, ExpressionSyntax))
End Function
Public Overrides Function NameOfExpression(expression As SyntaxNode) As SyntaxNode
Return SyntaxFactory.NameOfExpression(DirectCast(expression, ExpressionSyntax))
End Function
Public Overrides Function TupleExpression(arguments As IEnumerable(Of SyntaxNode)) As SyntaxNode
Return SyntaxFactory.TupleExpression(SyntaxFactory.SeparatedList(arguments.Select(AddressOf AsSimpleArgument)))
End Function
Friend Overrides Function AddParentheses(expression As SyntaxNode) As SyntaxNode
Return Parenthesize(expression)
End Function
Private Function Parenthesize(expression As SyntaxNode) As ParenthesizedExpressionSyntax
Return DirectCast(expression, ExpressionSyntax).Parenthesize()
End Function
Public Overrides Function AddExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode
Return SyntaxFactory.AddExpression(Parenthesize(left), Parenthesize(right))
End Function
Public Overloads Overrides Function Argument(name As String, refKind As RefKind, expression As SyntaxNode) As SyntaxNode
If name Is Nothing Then
Return SyntaxFactory.SimpleArgument(DirectCast(expression, ExpressionSyntax))
Else
Return SyntaxFactory.SimpleArgument(SyntaxFactory.NameColonEquals(name.ToIdentifierName()), DirectCast(expression, ExpressionSyntax))
End If
End Function
Public Overrides Function TryCastExpression(expression As SyntaxNode, type As SyntaxNode) As SyntaxNode
Return SyntaxFactory.TryCastExpression(DirectCast(expression, ExpressionSyntax), DirectCast(type, TypeSyntax))
End Function
Public Overrides Function AssignmentStatement(left As SyntaxNode, right As SyntaxNode) As SyntaxNode
Return SyntaxFactory.SimpleAssignmentStatement(
DirectCast(left, ExpressionSyntax),
SyntaxFactory.Token(SyntaxKind.EqualsToken),
DirectCast(right, ExpressionSyntax))
End Function
Public Overrides Function BaseExpression() As SyntaxNode
Return SyntaxFactory.MyBaseExpression()
End Function
Public Overrides Function BitwiseAndExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode
Return SyntaxFactory.AndExpression(Parenthesize(left), Parenthesize(right))
End Function
Public Overrides Function BitwiseOrExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode
Return SyntaxFactory.OrExpression(Parenthesize(left), Parenthesize(right))
End Function
Public Overrides Function CastExpression(type As SyntaxNode, expression As SyntaxNode) As SyntaxNode
Return SyntaxFactory.DirectCastExpression(DirectCast(expression, ExpressionSyntax), DirectCast(type, TypeSyntax)).WithAdditionalAnnotations(Simplifier.Annotation)
End Function
Public Overrides Function ConvertExpression(type As SyntaxNode, expression As SyntaxNode) As SyntaxNode
Return SyntaxFactory.CTypeExpression(DirectCast(expression, ExpressionSyntax), DirectCast(type, TypeSyntax)).WithAdditionalAnnotations(Simplifier.Annotation)
End Function
Public Overrides Function ConditionalExpression(condition As SyntaxNode, whenTrue As SyntaxNode, whenFalse As SyntaxNode) As SyntaxNode
Return SyntaxFactory.TernaryConditionalExpression(
DirectCast(condition, ExpressionSyntax),
DirectCast(whenTrue, ExpressionSyntax),
DirectCast(whenFalse, ExpressionSyntax))
End Function
Public Overrides Function LiteralExpression(value As Object) As SyntaxNode
Return ExpressionGenerator.GenerateNonEnumValueExpression(Nothing, value, canUseFieldReference:=True)
End Function
Public Overrides Function TypedConstantExpression(value As TypedConstant) As SyntaxNode
Return ExpressionGenerator.GenerateExpression(value)
End Function
Friend Overrides Function InterpolatedStringExpression(startToken As SyntaxToken, content As IEnumerable(Of SyntaxNode), endToken As SyntaxToken) As SyntaxNode
Return SyntaxFactory.InterpolatedStringExpression(
startToken, SyntaxFactory.List(content.Cast(Of InterpolatedStringContentSyntax)), endToken)
End Function
Friend Overrides Function InterpolatedStringText(textToken As SyntaxToken) As SyntaxNode
Return SyntaxFactory.InterpolatedStringText(textToken)
End Function
Friend Overrides Function InterpolatedStringTextToken(content As String) As SyntaxToken
Return SyntaxFactory.InterpolatedStringTextToken(content, "")
End Function
Friend Overrides Function Interpolation(syntaxNode As SyntaxNode) As SyntaxNode
Return SyntaxFactory.Interpolation(DirectCast(syntaxNode, ExpressionSyntax))
End Function
Friend Overrides Function NumericLiteralToken(text As String, value As ULong) As SyntaxToken
Return SyntaxFactory.Literal(text, value)
End Function
Public Overrides Function DefaultExpression(type As ITypeSymbol) As SyntaxNode
Return SyntaxFactory.NothingLiteralExpression(SyntaxFactory.Token(SyntaxKind.NothingKeyword))
End Function
Public Overrides Function DefaultExpression(type As SyntaxNode) As SyntaxNode
Return SyntaxFactory.NothingLiteralExpression(SyntaxFactory.Token(SyntaxKind.NothingKeyword))
End Function
Public Overloads Overrides Function ElementAccessExpression(expression As SyntaxNode, arguments As IEnumerable(Of SyntaxNode)) As SyntaxNode
Return SyntaxFactory.InvocationExpression(ParenthesizeLeft(expression), CreateArgumentList(arguments))
End Function
Public Overrides Function ExpressionStatement(expression As SyntaxNode) As SyntaxNode
If TypeOf expression Is StatementSyntax Then
Return expression
End If
Return SyntaxFactory.ExpressionStatement(DirectCast(expression, ExpressionSyntax))
End Function
Public Overloads Overrides Function GenericName(identifier As String, typeArguments As IEnumerable(Of SyntaxNode)) As SyntaxNode
Return GenericName(identifier.ToIdentifierToken(), typeArguments)
End Function
Friend Overrides Function GenericName(identifier As SyntaxToken, typeArguments As IEnumerable(Of SyntaxNode)) As SyntaxNode
Return SyntaxFactory.GenericName(
identifier,
SyntaxFactory.TypeArgumentList(
SyntaxFactory.SeparatedList(typeArguments.Cast(Of TypeSyntax)()))).WithAdditionalAnnotations(Simplifier.Annotation)
End Function
Public Overrides Function IdentifierName(identifier As String) As SyntaxNode
Return identifier.ToIdentifierName()
End Function
Public Overrides Function IfStatement(condition As SyntaxNode, trueStatements As IEnumerable(Of SyntaxNode), Optional falseStatements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode
Dim ifStmt = SyntaxFactory.IfStatement(SyntaxFactory.Token(SyntaxKind.IfKeyword),
DirectCast(condition, ExpressionSyntax),
SyntaxFactory.Token(SyntaxKind.ThenKeyword))
If falseStatements Is Nothing Then
Return SyntaxFactory.MultiLineIfBlock(
ifStmt,
GetStatementList(trueStatements),
Nothing,
Nothing
)
End If
' convert nested if-blocks into else-if parts
Dim statements = falseStatements.ToList()
If statements.Count = 1 AndAlso TypeOf statements(0) Is MultiLineIfBlockSyntax Then
Dim mifBlock = DirectCast(statements(0), MultiLineIfBlockSyntax)
' insert block's if-part onto head of elseIf-parts
Dim elseIfBlocks = mifBlock.ElseIfBlocks.Insert(0,
SyntaxFactory.ElseIfBlock(
SyntaxFactory.ElseIfStatement(SyntaxFactory.Token(SyntaxKind.ElseIfKeyword), mifBlock.IfStatement.Condition, SyntaxFactory.Token(SyntaxKind.ThenKeyword)),
mifBlock.Statements)
)
Return SyntaxFactory.MultiLineIfBlock(
ifStmt,
GetStatementList(trueStatements),
elseIfBlocks,
mifBlock.ElseBlock
)
End If
Return SyntaxFactory.MultiLineIfBlock(
ifStmt,
GetStatementList(trueStatements),
Nothing,
SyntaxFactory.ElseBlock(GetStatementList(falseStatements))
)
End Function
Private Function GetStatementList(nodes As IEnumerable(Of SyntaxNode)) As SyntaxList(Of StatementSyntax)
If nodes Is Nothing Then
Return Nothing
Else
Return SyntaxFactory.List(nodes.Select(AddressOf AsStatement))
End If
End Function
Private Function AsStatement(node As SyntaxNode) As StatementSyntax
Dim expr = TryCast(node, ExpressionSyntax)
If expr IsNot Nothing Then
Return SyntaxFactory.ExpressionStatement(expr)
Else
Return DirectCast(node, StatementSyntax)
End If
End Function
Public Overloads Overrides Function InvocationExpression(expression As SyntaxNode, arguments As IEnumerable(Of SyntaxNode)) As SyntaxNode
Return SyntaxFactory.InvocationExpression(ParenthesizeLeft(expression), CreateArgumentList(arguments))
End Function
Public Overrides Function IsTypeExpression(expression As SyntaxNode, type As SyntaxNode) As SyntaxNode
Return SyntaxFactory.TypeOfIsExpression(Parenthesize(expression), DirectCast(type, TypeSyntax))
End Function
Public Overrides Function TypeOfExpression(type As SyntaxNode) As SyntaxNode
Return SyntaxFactory.GetTypeExpression(DirectCast(type, TypeSyntax))
End Function
Public Overrides Function LogicalAndExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode
Return SyntaxFactory.AndAlsoExpression(Parenthesize(left), Parenthesize(right))
End Function
Public Overrides Function LogicalNotExpression(expression As SyntaxNode) As SyntaxNode
Return SyntaxFactory.NotExpression(Parenthesize(expression))
End Function
Public Overrides Function LogicalOrExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode
Return SyntaxFactory.OrElseExpression(Parenthesize(left), Parenthesize(right))
End Function
Friend Overrides Function MemberAccessExpressionWorker(expression As SyntaxNode, simpleName As SyntaxNode) As SyntaxNode
Return SyntaxFactory.SimpleMemberAccessExpression(
ParenthesizeLeft(expression),
SyntaxFactory.Token(SyntaxKind.DotToken),
DirectCast(simpleName, SimpleNameSyntax))
End Function
Friend Overrides Function ConditionalAccessExpression(expression As SyntaxNode, whenNotNull As SyntaxNode) As SyntaxNode
Return SyntaxFactory.ConditionalAccessExpression(
DirectCast(expression, ExpressionSyntax),
DirectCast(whenNotNull, ExpressionSyntax))
End Function
Friend Overrides Function MemberBindingExpression(name As SyntaxNode) As SyntaxNode
Return SyntaxFactory.SimpleMemberAccessExpression(DirectCast(name, SimpleNameSyntax))
End Function
Friend Overrides Function ElementBindingExpression(argumentList As SyntaxNode) As SyntaxNode
Return SyntaxFactory.InvocationExpression(expression:=Nothing,
argumentList:=DirectCast(argumentList, ArgumentListSyntax))
End Function
' parenthesize the left-side of a dot or target of an invocation if not unnecessary
Private Function ParenthesizeLeft(expression As SyntaxNode) As ExpressionSyntax
Dim expressionSyntax = DirectCast(expression, ExpressionSyntax)
If TypeOf expressionSyntax Is TypeSyntax _
OrElse expressionSyntax.IsMeMyBaseOrMyClass() _
OrElse expressionSyntax.IsKind(SyntaxKind.ParenthesizedExpression) _
OrElse expressionSyntax.IsKind(SyntaxKind.InvocationExpression) _
OrElse expressionSyntax.IsKind(SyntaxKind.SimpleMemberAccessExpression) Then
Return expressionSyntax
Else
Return expressionSyntax.Parenthesize()
End If
End Function
Public Overrides Function MultiplyExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode
Return SyntaxFactory.MultiplyExpression(Parenthesize(left), Parenthesize(right))
End Function
Public Overrides Function NegateExpression(expression As SyntaxNode) As SyntaxNode
Return SyntaxFactory.UnaryMinusExpression(Parenthesize(expression))
End Function
Private Function AsExpressionList(expressions As IEnumerable(Of SyntaxNode)) As SeparatedSyntaxList(Of ExpressionSyntax)
Return SyntaxFactory.SeparatedList(Of ExpressionSyntax)(expressions.OfType(Of ExpressionSyntax)())
End Function
Public Overrides Function ArrayCreationExpression(elementType As SyntaxNode, size As SyntaxNode) As SyntaxNode
Dim sizes = SyntaxFactory.ArgumentList(SyntaxFactory.SingletonSeparatedList(AsArgument(size)))
Dim initializer = SyntaxFactory.CollectionInitializer()
Return SyntaxFactory.ArrayCreationExpression(Nothing, DirectCast(elementType, TypeSyntax), sizes, initializer)
End Function
Public Overrides Function ArrayCreationExpression(elementType As SyntaxNode, elements As IEnumerable(Of SyntaxNode)) As SyntaxNode
Dim sizes = SyntaxFactory.ArgumentList()
Dim initializer = SyntaxFactory.CollectionInitializer(AsExpressionList(elements))
Return SyntaxFactory.ArrayCreationExpression(Nothing, DirectCast(elementType, TypeSyntax), sizes, initializer)
End Function
Public Overloads Overrides Function ObjectCreationExpression(typeName As SyntaxNode, arguments As IEnumerable(Of SyntaxNode)) As SyntaxNode
Return SyntaxFactory.ObjectCreationExpression(
Nothing,
DirectCast(typeName, TypeSyntax),
CreateArgumentList(arguments),
Nothing)
End Function
Public Overrides Function QualifiedName(left As SyntaxNode, right As SyntaxNode) As SyntaxNode
Return SyntaxFactory.QualifiedName(DirectCast(left, NameSyntax), DirectCast(right, SimpleNameSyntax))
End Function
Friend Overrides Function GlobalAliasedName(name As SyntaxNode) As SyntaxNode
Return QualifiedName(SyntaxFactory.GlobalName(), name)
End Function
Public Overrides Function ReferenceEqualsExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode
Return SyntaxFactory.IsExpression(Parenthesize(left), Parenthesize(right))
End Function
Public Overrides Function ReferenceNotEqualsExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode
Return SyntaxFactory.IsNotExpression(Parenthesize(left), Parenthesize(right))
End Function
Public Overrides Function ReturnStatement(Optional expressionOpt As SyntaxNode = Nothing) As SyntaxNode
Return SyntaxFactory.ReturnStatement(DirectCast(expressionOpt, ExpressionSyntax))
End Function
Friend Overrides Function YieldReturnStatement(expression As SyntaxNode) As SyntaxNode
Return SyntaxFactory.YieldStatement(DirectCast(expression, ExpressionSyntax))
End Function
Public Overrides Function ThisExpression() As SyntaxNode
Return SyntaxFactory.MeExpression()
End Function
Public Overrides Function ThrowStatement(Optional expressionOpt As SyntaxNode = Nothing) As SyntaxNode
Return SyntaxFactory.ThrowStatement(DirectCast(expressionOpt, ExpressionSyntax))
End Function
Public Overrides Function ThrowExpression(expression As SyntaxNode) As SyntaxNode
Throw New NotSupportedException("ThrowExpressions are not supported in Visual Basic")
End Function
Friend Overrides Function SupportsThrowExpression() As Boolean
Return False
End Function
Public Overrides Function NameExpression(namespaceOrTypeSymbol As INamespaceOrTypeSymbol) As SyntaxNode
Return namespaceOrTypeSymbol.GenerateTypeSyntax()
End Function
Public Overrides Function TypeExpression(typeSymbol As ITypeSymbol) As SyntaxNode
Return typeSymbol.GenerateTypeSyntax()
End Function
Public Overrides Function TypeExpression(specialType As SpecialType) As SyntaxNode
Select Case specialType
Case specialType.System_Boolean
Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.BooleanKeyword))
Case specialType.System_Byte
Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ByteKeyword))
Case specialType.System_Char
Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.CharKeyword))
Case specialType.System_Decimal
Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.DecimalKeyword))
Case specialType.System_Double
Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.DoubleKeyword))
Case specialType.System_Int16
Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ShortKeyword))
Case specialType.System_Int32
Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.IntegerKeyword))
Case specialType.System_Int64
Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.LongKeyword))
Case specialType.System_Object
Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ObjectKeyword))
Case specialType.System_SByte
Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.SByteKeyword))
Case specialType.System_Single
Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.SingleKeyword))
Case specialType.System_String
Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.StringKeyword))
Case specialType.System_UInt16
Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.UShortKeyword))
Case specialType.System_UInt32
Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.UIntegerKeyword))
Case specialType.System_UInt64
Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ULongKeyword))
Case specialType.System_DateTime
Return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.DateKeyword))
Case Else
Throw New NotSupportedException("Unsupported SpecialType")
End Select
End Function
Public Overloads Overrides Function UsingStatement(type As SyntaxNode, identifier As String, expression As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode
Return SyntaxFactory.UsingBlock(
SyntaxFactory.UsingStatement(
expression:=Nothing,
variables:=SyntaxFactory.SingletonSeparatedList(VariableDeclarator(type, identifier.ToModifiedIdentifier, expression))),
GetStatementList(statements))
End Function
Public Overloads Overrides Function UsingStatement(expression As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode
Return SyntaxFactory.UsingBlock(
SyntaxFactory.UsingStatement(
expression:=DirectCast(expression, ExpressionSyntax),
variables:=Nothing),
GetStatementList(statements))
End Function
Public Overrides Function LockStatement(expression As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode
Return SyntaxFactory.SyncLockBlock(
SyntaxFactory.SyncLockStatement(
expression:=DirectCast(expression, ExpressionSyntax)),
GetStatementList(statements))
End Function
Public Overrides Function ValueEqualsExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode
Return SyntaxFactory.EqualsExpression(Parenthesize(left), Parenthesize(right))
End Function
Public Overrides Function ValueNotEqualsExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode
Return SyntaxFactory.NotEqualsExpression(Parenthesize(left), Parenthesize(right))
End Function
Private Function CreateArgumentList(arguments As IEnumerable(Of SyntaxNode)) As ArgumentListSyntax
Return SyntaxFactory.ArgumentList(CreateArguments(arguments))
End Function
Private Function CreateArguments(arguments As IEnumerable(Of SyntaxNode)) As SeparatedSyntaxList(Of ArgumentSyntax)
Return SyntaxFactory.SeparatedList(arguments.Select(AddressOf AsArgument))
End Function
Private Function AsArgument(argOrExpression As SyntaxNode) As ArgumentSyntax
Return If(TryCast(argOrExpression, ArgumentSyntax),
SyntaxFactory.SimpleArgument(DirectCast(argOrExpression, ExpressionSyntax)))
End Function
Private Function AsSimpleArgument(argOrExpression As SyntaxNode) As SimpleArgumentSyntax
Return If(TryCast(argOrExpression, SimpleArgumentSyntax),
SyntaxFactory.SimpleArgument(DirectCast(argOrExpression, ExpressionSyntax)))
End Function
Public Overloads Overrides Function LocalDeclarationStatement(type As SyntaxNode, identifier As String, Optional initializer As SyntaxNode = Nothing, Optional isConst As Boolean = False) As SyntaxNode
Return LocalDeclarationStatement(type, identifier.ToIdentifierToken, initializer, isConst)
End Function
Friend Overloads Overrides Function LocalDeclarationStatement(type As SyntaxNode, identifier As SyntaxToken, Optional initializer As SyntaxNode = Nothing, Optional isConst As Boolean = False) As SyntaxNode
Return SyntaxFactory.LocalDeclarationStatement(
SyntaxFactory.TokenList(SyntaxFactory.Token(If(isConst, SyntaxKind.ConstKeyword, SyntaxKind.DimKeyword))),
SyntaxFactory.SingletonSeparatedList(VariableDeclarator(type, SyntaxFactory.ModifiedIdentifier(identifier), initializer)))
End Function
Friend Overrides Function WithInitializer(variableDeclarator As SyntaxNode, initializer As SyntaxNode) As SyntaxNode
Return DirectCast(variableDeclarator, VariableDeclaratorSyntax).WithInitializer(DirectCast(initializer, EqualsValueSyntax))
End Function
Friend Overrides Function EqualsValueClause(operatorToken As SyntaxToken, value As SyntaxNode) As SyntaxNode
Return SyntaxFactory.EqualsValue(operatorToken, DirectCast(value, ExpressionSyntax))
End Function
Private Function VariableDeclarator(type As SyntaxNode, name As ModifiedIdentifierSyntax, Optional expression As SyntaxNode = Nothing) As VariableDeclaratorSyntax
Return SyntaxFactory.VariableDeclarator(
SyntaxFactory.SingletonSeparatedList(name),
If(type Is Nothing, Nothing, SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax))),
If(expression Is Nothing,
Nothing,
SyntaxFactory.EqualsValue(DirectCast(expression, ExpressionSyntax))))
End Function
Public Overloads Overrides Function SwitchStatement(expression As SyntaxNode, caseClauses As IEnumerable(Of SyntaxNode)) As SyntaxNode
Return SyntaxFactory.SelectBlock(
SyntaxFactory.SelectStatement(DirectCast(expression, ExpressionSyntax)),
SyntaxFactory.List(caseClauses.Cast(Of CaseBlockSyntax)))
End Function
Public Overloads Overrides Function SwitchSection(expressions As IEnumerable(Of SyntaxNode), statements As IEnumerable(Of SyntaxNode)) As SyntaxNode
Return SyntaxFactory.CaseBlock(
SyntaxFactory.CaseStatement(GetCaseClauses(expressions)),
GetStatementList(statements))
End Function
Friend Overrides Function SwitchSectionFromLabels(labels As IEnumerable(Of SyntaxNode), statements As IEnumerable(Of SyntaxNode)) As SyntaxNode
Return SyntaxFactory.CaseBlock(
SyntaxFactory.CaseStatement(SyntaxFactory.SeparatedList(labels.Cast(Of CaseClauseSyntax))),
GetStatementList(statements))
End Function
Public Overrides Function DefaultSwitchSection(statements As IEnumerable(Of SyntaxNode)) As SyntaxNode
Return SyntaxFactory.CaseElseBlock(
SyntaxFactory.CaseElseStatement(SyntaxFactory.ElseCaseClause()),
GetStatementList(statements))
End Function
Private Function GetCaseClauses(expressions As IEnumerable(Of SyntaxNode)) As SeparatedSyntaxList(Of CaseClauseSyntax)
Dim cases = SyntaxFactory.SeparatedList(Of CaseClauseSyntax)
If expressions IsNot Nothing Then
cases = cases.AddRange(expressions.Select(Function(e) SyntaxFactory.SimpleCaseClause(DirectCast(e, ExpressionSyntax))))
End If
Return cases
End Function
Private Function AsCaseClause(expression As SyntaxNode) As CaseClauseSyntax
Return SyntaxFactory.SimpleCaseClause(DirectCast(expression, ExpressionSyntax))
End Function
Public Overrides Function ExitSwitchStatement() As SyntaxNode
Return SyntaxFactory.ExitSelectStatement()
End Function
Public Overloads Overrides Function ValueReturningLambdaExpression(parameters As IEnumerable(Of SyntaxNode), expression As SyntaxNode) As SyntaxNode
Return SyntaxFactory.SingleLineFunctionLambdaExpression(
SyntaxFactory.FunctionLambdaHeader().WithParameterList(GetParameterList(parameters)),
DirectCast(expression, ExpressionSyntax))
End Function
Public Overrides Function VoidReturningLambdaExpression(lambdaParameters As IEnumerable(Of SyntaxNode), expression As SyntaxNode) As SyntaxNode
Return SyntaxFactory.SingleLineSubLambdaExpression(
SyntaxFactory.SubLambdaHeader().WithParameterList(GetParameterList(lambdaParameters)),
AsStatement(expression))
End Function
Public Overloads Overrides Function ValueReturningLambdaExpression(lambdaParameters As IEnumerable(Of SyntaxNode), statements As IEnumerable(Of SyntaxNode)) As SyntaxNode
Return SyntaxFactory.MultiLineFunctionLambdaExpression(
SyntaxFactory.FunctionLambdaHeader().WithParameterList(GetParameterList(lambdaParameters)),
GetStatementList(statements),
SyntaxFactory.EndFunctionStatement())
End Function
Public Overrides Function VoidReturningLambdaExpression(lambdaParameters As IEnumerable(Of SyntaxNode), statements As IEnumerable(Of SyntaxNode)) As SyntaxNode
Return SyntaxFactory.MultiLineSubLambdaExpression(
SyntaxFactory.SubLambdaHeader().WithParameterList(GetParameterList(lambdaParameters)),
GetStatementList(statements),
SyntaxFactory.EndSubStatement())
End Function
Public Overrides Function LambdaParameter(identifier As String, Optional type As SyntaxNode = Nothing) As SyntaxNode
Return ParameterDeclaration(identifier, type)
End Function
Public Overrides Function ArrayTypeExpression(type As SyntaxNode) As SyntaxNode
Dim arrayType = TryCast(type, ArrayTypeSyntax)
If arrayType IsNot Nothing Then
Return arrayType.WithRankSpecifiers(arrayType.RankSpecifiers.Add(SyntaxFactory.ArrayRankSpecifier()))
Else
Return SyntaxFactory.ArrayType(DirectCast(type, TypeSyntax), SyntaxFactory.SingletonList(SyntaxFactory.ArrayRankSpecifier()))
End If
End Function
Public Overrides Function NullableTypeExpression(type As SyntaxNode) As SyntaxNode
Dim nullableType = TryCast(type, NullableTypeSyntax)
If nullableType IsNot Nothing Then
Return nullableType
Else
Return SyntaxFactory.NullableType(DirectCast(type, TypeSyntax))
End If
End Function
Friend Overrides Function CreateTupleType(elements As IEnumerable(Of SyntaxNode)) As SyntaxNode
Return SyntaxFactory.TupleType(SyntaxFactory.SeparatedList(elements.Cast(Of TupleElementSyntax)()))
End Function
Public Overrides Function TupleElementExpression(type As SyntaxNode, Optional name As String = Nothing) As SyntaxNode
If name Is Nothing Then
Return SyntaxFactory.TypedTupleElement(DirectCast(type, TypeSyntax))
Else
Return SyntaxFactory.NamedTupleElement(name.ToIdentifierToken(), SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax)))
End If
End Function
Public Overrides Function WithTypeArguments(name As SyntaxNode, typeArguments As IEnumerable(Of SyntaxNode)) As SyntaxNode
If name.IsKind(SyntaxKind.IdentifierName) OrElse name.IsKind(SyntaxKind.GenericName) Then
Dim sname = DirectCast(name, SimpleNameSyntax)
Return SyntaxFactory.GenericName(sname.Identifier, SyntaxFactory.TypeArgumentList(SyntaxFactory.SeparatedList(typeArguments.Cast(Of TypeSyntax)())))
ElseIf name.IsKind(SyntaxKind.QualifiedName) Then
Dim qname = DirectCast(name, QualifiedNameSyntax)
Return SyntaxFactory.QualifiedName(qname.Left, DirectCast(WithTypeArguments(qname.Right, typeArguments), SimpleNameSyntax))
ElseIf name.IsKind(SyntaxKind.SimpleMemberAccessExpression) Then
Dim sma = DirectCast(name, MemberAccessExpressionSyntax)
Return SyntaxFactory.MemberAccessExpression(name.Kind(), sma.Expression, sma.OperatorToken, DirectCast(WithTypeArguments(sma.Name, typeArguments), SimpleNameSyntax))
Else
Throw New NotSupportedException()
End If
End Function
Public Overrides Function SubtractExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode
Return SyntaxFactory.SubtractExpression(Parenthesize(left), Parenthesize(right))
End Function
Public Overrides Function DivideExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode
Return SyntaxFactory.DivideExpression(Parenthesize(left), Parenthesize(right))
End Function
Public Overrides Function ModuloExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode
Return SyntaxFactory.ModuloExpression(Parenthesize(left), Parenthesize(right))
End Function
Public Overrides Function BitwiseNotExpression(operand As SyntaxNode) As SyntaxNode
Return SyntaxFactory.NotExpression(Parenthesize(operand))
End Function
Public Overrides Function CoalesceExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode
Return SyntaxFactory.BinaryConditionalExpression(DirectCast(left, ExpressionSyntax), DirectCast(right, ExpressionSyntax))
End Function
Public Overrides Function LessThanExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode
Return SyntaxFactory.LessThanExpression(Parenthesize(left), Parenthesize(right))
End Function
Public Overrides Function LessThanOrEqualExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode
Return SyntaxFactory.LessThanOrEqualExpression(Parenthesize(left), Parenthesize(right))
End Function
Public Overrides Function GreaterThanExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode
Return SyntaxFactory.GreaterThanExpression(Parenthesize(left), Parenthesize(right))
End Function
Public Overrides Function GreaterThanOrEqualExpression(left As SyntaxNode, right As SyntaxNode) As SyntaxNode
Return SyntaxFactory.GreaterThanOrEqualExpression(Parenthesize(left), Parenthesize(right))
End Function
Public Overrides Function TryCatchStatement(tryStatements As IEnumerable(Of SyntaxNode), catchClauses As IEnumerable(Of SyntaxNode), Optional finallyStatements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode
Return SyntaxFactory.TryBlock(
GetStatementList(tryStatements),
If(catchClauses IsNot Nothing, SyntaxFactory.List(catchClauses.Cast(Of CatchBlockSyntax)()), Nothing),
If(finallyStatements IsNot Nothing, SyntaxFactory.FinallyBlock(GetStatementList(finallyStatements)), Nothing)
)
End Function
Public Overrides Function CatchClause(type As SyntaxNode, identifier As String, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode
Return SyntaxFactory.CatchBlock(
SyntaxFactory.CatchStatement(
SyntaxFactory.IdentifierName(identifier),
SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax)),
whenClause:=Nothing
),
GetStatementList(statements)
)
End Function
Public Overrides Function WhileStatement(condition As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode
Return SyntaxFactory.WhileBlock(
SyntaxFactory.WhileStatement(DirectCast(condition, ExpressionSyntax)),
GetStatementList(statements))
End Function
Friend Overrides Function ScopeBlock(statements As IEnumerable(Of SyntaxNode)) As SyntaxNode
Throw New NotSupportedException()
End Function
Friend Overrides Function RefExpression(expression As SyntaxNode) As SyntaxNode
Return expression
End Function
#End Region
#Region "Declarations"
Private Function AsReadOnlyList(Of T)(sequence As IEnumerable(Of T)) As IReadOnlyList(Of T)
Dim list = TryCast(sequence, IReadOnlyList(Of T))
If list Is Nothing Then
list = sequence.ToImmutableReadOnlyListOrEmpty()
End If
Return list
End Function
Private Shared s_fieldModifiers As DeclarationModifiers = DeclarationModifiers.Const Or DeclarationModifiers.[New] Or DeclarationModifiers.ReadOnly Or DeclarationModifiers.Static Or DeclarationModifiers.WithEvents
Private Shared s_methodModifiers As DeclarationModifiers = DeclarationModifiers.Abstract Or DeclarationModifiers.Async Or DeclarationModifiers.[New] Or DeclarationModifiers.Override Or DeclarationModifiers.Partial Or DeclarationModifiers.Sealed Or DeclarationModifiers.Static Or DeclarationModifiers.Virtual
Private Shared s_constructorModifiers As DeclarationModifiers = DeclarationModifiers.Static
Private Shared s_propertyModifiers As DeclarationModifiers = DeclarationModifiers.Abstract Or DeclarationModifiers.[New] Or DeclarationModifiers.Override Or DeclarationModifiers.ReadOnly Or DeclarationModifiers.WriteOnly Or DeclarationModifiers.Sealed Or DeclarationModifiers.Static Or DeclarationModifiers.Virtual
Private Shared s_indexerModifiers As DeclarationModifiers = DeclarationModifiers.Abstract Or DeclarationModifiers.[New] Or DeclarationModifiers.Override Or DeclarationModifiers.ReadOnly Or DeclarationModifiers.WriteOnly Or DeclarationModifiers.Sealed Or DeclarationModifiers.Static Or DeclarationModifiers.Virtual
Private Shared s_classModifiers As DeclarationModifiers = DeclarationModifiers.Abstract Or DeclarationModifiers.[New] Or DeclarationModifiers.Partial Or DeclarationModifiers.Sealed Or DeclarationModifiers.Static
Private Shared s_structModifiers As DeclarationModifiers = DeclarationModifiers.[New] Or DeclarationModifiers.Partial
Private Shared s_interfaceModifiers As DeclarationModifiers = DeclarationModifiers.[New] Or DeclarationModifiers.Partial
Private Shared s_accessorModifiers As DeclarationModifiers = DeclarationModifiers.Abstract Or DeclarationModifiers.[New] Or DeclarationModifiers.Override Or DeclarationModifiers.Virtual
Private Function GetAllowedModifiers(kind As SyntaxKind) As DeclarationModifiers
Select Case kind
Case SyntaxKind.ClassBlock, SyntaxKind.ClassStatement
Return s_classModifiers
Case SyntaxKind.EnumBlock, SyntaxKind.EnumStatement
Return DeclarationModifiers.[New]
Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement
Return DeclarationModifiers.[New]
Case SyntaxKind.InterfaceBlock, SyntaxKind.InterfaceStatement
Return s_interfaceModifiers
Case SyntaxKind.StructureBlock, SyntaxKind.StructureStatement
Return s_structModifiers
Case SyntaxKind.FunctionBlock,
SyntaxKind.FunctionStatement,
SyntaxKind.SubBlock,
SyntaxKind.SubStatement,
SyntaxKind.OperatorBlock,
SyntaxKind.OperatorStatement
Return s_methodModifiers
Case SyntaxKind.ConstructorBlock,
SyntaxKind.SubNewStatement
Return s_constructorModifiers
Case SyntaxKind.FieldDeclaration
Return s_fieldModifiers
Case SyntaxKind.PropertyBlock,
SyntaxKind.PropertyStatement
Return s_propertyModifiers
Case SyntaxKind.EventBlock,
SyntaxKind.EventStatement
Return s_propertyModifiers
Case SyntaxKind.GetAccessorBlock,
SyntaxKind.GetAccessorStatement,
SyntaxKind.SetAccessorBlock,
SyntaxKind.SetAccessorStatement,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.AddHandlerAccessorStatement,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorStatement,
SyntaxKind.RaiseEventAccessorBlock,
SyntaxKind.RaiseEventAccessorStatement
Return s_accessorModifiers
Case SyntaxKind.EnumMemberDeclaration
Case SyntaxKind.Parameter
Case SyntaxKind.LocalDeclarationStatement
Case Else
Return DeclarationModifiers.None
End Select
End Function
Public Overrides Function FieldDeclaration(name As String, type As SyntaxNode, Optional accessibility As Accessibility = Nothing, Optional modifiers As DeclarationModifiers = Nothing, Optional initializer As SyntaxNode = Nothing) As SyntaxNode
Return SyntaxFactory.FieldDeclaration(
attributeLists:=Nothing,
modifiers:=GetModifierList(accessibility, modifiers And s_fieldModifiers, DeclarationKind.Field),
declarators:=SyntaxFactory.SingletonSeparatedList(VariableDeclarator(type, name.ToModifiedIdentifier, initializer)))
End Function
Public Overrides Function MethodDeclaration(
identifier As String,
Optional parameters As IEnumerable(Of SyntaxNode) = Nothing,
Optional typeParameters As IEnumerable(Of String) = Nothing,
Optional returnType As SyntaxNode = Nothing,
Optional accessibility As Accessibility = Nothing,
Optional modifiers As DeclarationModifiers = Nothing,
Optional statements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode
Dim statement = SyntaxFactory.MethodStatement(
kind:=If(returnType Is Nothing, SyntaxKind.SubStatement, SyntaxKind.FunctionStatement),
attributeLists:=Nothing,
modifiers:=GetModifierList(accessibility, modifiers And s_methodModifiers, DeclarationKind.Method),
subOrFunctionKeyword:=If(returnType Is Nothing, SyntaxFactory.Token(SyntaxKind.SubKeyword), SyntaxFactory.Token(SyntaxKind.FunctionKeyword)),
identifier:=identifier.ToIdentifierToken(),
typeParameterList:=GetTypeParameters(typeParameters),
parameterList:=GetParameterList(parameters),
asClause:=If(returnType IsNot Nothing, SyntaxFactory.SimpleAsClause(DirectCast(returnType, TypeSyntax)), Nothing),
handlesClause:=Nothing,
implementsClause:=Nothing)
If modifiers.IsAbstract Then
Return statement
Else
Return SyntaxFactory.MethodBlock(
kind:=If(returnType Is Nothing, SyntaxKind.SubBlock, SyntaxKind.FunctionBlock),
subOrFunctionStatement:=statement,
statements:=GetStatementList(statements),
endSubOrFunctionStatement:=If(returnType Is Nothing, SyntaxFactory.EndSubStatement(), SyntaxFactory.EndFunctionStatement()))
End If
End Function
Public Overrides Function OperatorDeclaration(kind As OperatorKind,
Optional parameters As IEnumerable(Of SyntaxNode) = Nothing,
Optional returnType As SyntaxNode = Nothing,
Optional accessibility As Accessibility = Accessibility.NotApplicable,
Optional modifiers As DeclarationModifiers = Nothing,
Optional statements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode
Dim statement As OperatorStatementSyntax
Dim asClause = If(returnType IsNot Nothing, SyntaxFactory.SimpleAsClause(DirectCast(returnType, TypeSyntax)), Nothing)
Dim parameterList = GetParameterList(parameters)
Dim operatorToken = SyntaxFactory.Token(GetTokenKind(kind))
Dim modifierList As SyntaxTokenList = GetModifierList(accessibility, modifiers And s_methodModifiers, DeclarationKind.Operator)
If kind = OperatorKind.ImplicitConversion OrElse kind = OperatorKind.ExplicitConversion Then
modifierList = modifierList.Add(SyntaxFactory.Token(
If(kind = OperatorKind.ImplicitConversion, SyntaxKind.WideningKeyword, SyntaxKind.NarrowingKeyword)))
statement = SyntaxFactory.OperatorStatement(
attributeLists:=Nothing, modifiers:=modifierList, operatorToken:=operatorToken,
parameterList:=parameterList, asClause:=asClause)
Else
statement = SyntaxFactory.OperatorStatement(
attributeLists:=Nothing, modifiers:=modifierList,
operatorToken:=operatorToken, parameterList:=parameterList,
asClause:=asClause)
End If
If modifiers.IsAbstract Then
Return statement
Else
Return SyntaxFactory.OperatorBlock(
operatorStatement:=statement,
statements:=GetStatementList(statements),
endOperatorStatement:=SyntaxFactory.EndOperatorStatement())
End If
End Function
Private Function GetTokenKind(kind As OperatorKind) As SyntaxKind
Select Case kind
Case OperatorKind.ImplicitConversion,
OperatorKind.ExplicitConversion
Return SyntaxKind.CTypeKeyword
Case OperatorKind.Addition
Return SyntaxKind.PlusToken
Case OperatorKind.BitwiseAnd
Return SyntaxKind.AndKeyword
Case OperatorKind.BitwiseOr
Return SyntaxKind.OrKeyword
Case OperatorKind.Division
Return SyntaxKind.SlashToken
Case OperatorKind.Equality
Return SyntaxKind.EqualsToken
Case OperatorKind.ExclusiveOr
Return SyntaxKind.XorKeyword
Case OperatorKind.False
Return SyntaxKind.IsFalseKeyword
Case OperatorKind.GreaterThan
Return SyntaxKind.GreaterThanToken
Case OperatorKind.GreaterThanOrEqual
Return SyntaxKind.GreaterThanEqualsToken
Case OperatorKind.Inequality
Return SyntaxKind.LessThanGreaterThanToken
Case OperatorKind.LeftShift
Return SyntaxKind.LessThanLessThanToken
Case OperatorKind.LessThan
Return SyntaxKind.LessThanToken
Case OperatorKind.LessThanOrEqual
Return SyntaxKind.LessThanEqualsToken
Case OperatorKind.LogicalNot
Return SyntaxKind.NotKeyword
Case OperatorKind.Modulus
Return SyntaxKind.ModKeyword
Case OperatorKind.Multiply
Return SyntaxKind.AsteriskToken
Case OperatorKind.RightShift
Return SyntaxKind.GreaterThanGreaterThanToken
Case OperatorKind.Subtraction
Return SyntaxKind.MinusToken
Case OperatorKind.True
Return SyntaxKind.IsTrueKeyword
Case OperatorKind.UnaryNegation
Return SyntaxKind.MinusToken
Case OperatorKind.UnaryPlus
Return SyntaxKind.PlusToken
Case Else
Throw New ArgumentException($"Operator {kind} cannot be generated in Visual Basic.")
End Select
End Function
Private Function GetParameterList(parameters As IEnumerable(Of SyntaxNode)) As ParameterListSyntax
Return If(parameters IsNot Nothing, SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(parameters.Cast(Of ParameterSyntax)())), SyntaxFactory.ParameterList())
End Function
Public Overrides Function ParameterDeclaration(name As String, Optional type As SyntaxNode = Nothing, Optional initializer As SyntaxNode = Nothing, Optional refKind As RefKind = Nothing) As SyntaxNode
Return SyntaxFactory.Parameter(
attributeLists:=Nothing,
modifiers:=GetParameterModifiers(refKind, initializer),
identifier:=name.ToModifiedIdentifier(),
asClause:=If(type IsNot Nothing, SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax)), Nothing),
[default]:=If(initializer IsNot Nothing, SyntaxFactory.EqualsValue(DirectCast(initializer, ExpressionSyntax)), Nothing))
End Function
Private Function GetParameterModifiers(refKind As RefKind, initializer As SyntaxNode) As SyntaxTokenList
Dim tokens As SyntaxTokenList = Nothing
If initializer IsNot Nothing Then
tokens = tokens.Add(SyntaxFactory.Token(SyntaxKind.OptionalKeyword))
End If
If refKind <> refKind.None Then
tokens = tokens.Add(SyntaxFactory.Token(SyntaxKind.ByRefKeyword))
End If
Return tokens
End Function
Public Overrides Function GetAccessorDeclaration(Optional accessibility As Accessibility = Accessibility.NotApplicable, Optional statements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode
Return SyntaxFactory.GetAccessorBlock(
SyntaxFactory.GetAccessorStatement().WithModifiers(GetModifierList(accessibility, DeclarationModifiers.None, DeclarationKind.Property)),
GetStatementList(statements))
End Function
Public Overrides Function SetAccessorDeclaration(Optional accessibility As Accessibility = Accessibility.NotApplicable, Optional statements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode
Return SyntaxFactory.SetAccessorBlock(
SyntaxFactory.SetAccessorStatement().WithModifiers(GetModifierList(accessibility, DeclarationModifiers.None, DeclarationKind.Property)),
GetStatementList(statements))
End Function
Public Overrides Function WithAccessorDeclarations(declaration As SyntaxNode, accessorDeclarations As IEnumerable(Of SyntaxNode)) As SyntaxNode
Dim propertyBlock = GetPropertyBlock(declaration)
If propertyBlock Is Nothing Then
Return declaration
End If
propertyBlock = propertyBlock.WithAccessors(
SyntaxFactory.List(accessorDeclarations.OfType(Of AccessorBlockSyntax)))
Dim hasGetAccessor = propertyBlock.Accessors.Any(SyntaxKind.GetAccessorBlock)
Dim hasSetAccessor = propertyBlock.Accessors.Any(SyntaxKind.SetAccessorBlock)
If hasGetAccessor AndAlso Not hasSetAccessor Then
propertyBlock = DirectCast(WithModifiers(propertyBlock, GetModifiers(propertyBlock) Or DeclarationModifiers.ReadOnly), PropertyBlockSyntax)
ElseIf Not hasGetAccessor AndAlso hasSetAccessor Then
propertyBlock = DirectCast(WithModifiers(propertyBlock, GetModifiers(propertyBlock) Or DeclarationModifiers.WriteOnly), PropertyBlockSyntax)
ElseIf hasGetAccessor AndAlso hasSetAccessor Then
propertyBlock = DirectCast(WithModifiers(propertyBlock, GetModifiers(propertyBlock).WithIsReadOnly(False).WithIsWriteOnly(False)), PropertyBlockSyntax)
End If
Return If(propertyBlock.Accessors.Count = 0,
propertyBlock.PropertyStatement,
DirectCast(propertyBlock, SyntaxNode))
End Function
Private Function GetPropertyBlock(declaration As SyntaxNode) As PropertyBlockSyntax
Dim propertyBlock = TryCast(declaration, PropertyBlockSyntax)
If propertyBlock IsNot Nothing Then
Return propertyBlock
End If
Dim propertyStatement = TryCast(declaration, PropertyStatementSyntax)
If propertyStatement IsNot Nothing Then
Return SyntaxFactory.PropertyBlock(propertyStatement, SyntaxFactory.List(Of AccessorBlockSyntax))
End If
Return Nothing
End Function
Public Overrides Function PropertyDeclaration(
identifier As String,
type As SyntaxNode,
Optional accessibility As Accessibility = Nothing,
Optional modifiers As DeclarationModifiers = Nothing,
Optional getAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing,
Optional setAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode
Dim asClause = SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax))
Dim statement = SyntaxFactory.PropertyStatement(
attributeLists:=Nothing,
modifiers:=GetModifierList(accessibility, modifiers And s_propertyModifiers, DeclarationKind.Property),
identifier:=identifier.ToIdentifierToken(),
parameterList:=Nothing,
asClause:=asClause,
initializer:=Nothing,
implementsClause:=Nothing)
If modifiers.IsAbstract Then
Return statement
Else
Dim accessors = New List(Of AccessorBlockSyntax)
If Not modifiers.IsWriteOnly Then
accessors.Add(CreateGetAccessorBlock(getAccessorStatements))
End If
If Not modifiers.IsReadOnly Then
accessors.Add(CreateSetAccessorBlock(type, setAccessorStatements))
End If
Return SyntaxFactory.PropertyBlock(
propertyStatement:=statement,
accessors:=SyntaxFactory.List(accessors),
endPropertyStatement:=SyntaxFactory.EndPropertyStatement())
End If
End Function
Public Overrides Function IndexerDeclaration(
parameters As IEnumerable(Of SyntaxNode),
type As SyntaxNode,
Optional accessibility As Accessibility = Nothing,
Optional modifiers As DeclarationModifiers = Nothing,
Optional getAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing,
Optional setAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode
Dim asClause = SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax))
Dim statement = SyntaxFactory.PropertyStatement(
attributeLists:=Nothing,
modifiers:=GetModifierList(accessibility, modifiers And s_indexerModifiers, DeclarationKind.Indexer, isDefault:=True),
identifier:=SyntaxFactory.Identifier("Item"),
parameterList:=SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(parameters.Cast(Of ParameterSyntax))),
asClause:=asClause,
initializer:=Nothing,
implementsClause:=Nothing)
If modifiers.IsAbstract Then
Return statement
Else
Dim accessors = New List(Of AccessorBlockSyntax)
If Not modifiers.IsWriteOnly Then
accessors.Add(CreateGetAccessorBlock(getAccessorStatements))
End If
If Not modifiers.IsReadOnly Then
accessors.Add(CreateSetAccessorBlock(type, setAccessorStatements))
End If
Return SyntaxFactory.PropertyBlock(
propertyStatement:=statement,
accessors:=SyntaxFactory.List(accessors),
endPropertyStatement:=SyntaxFactory.EndPropertyStatement())
End If
End Function
Private Function AccessorBlock(kind As SyntaxKind, statements As IEnumerable(Of SyntaxNode), type As SyntaxNode) As AccessorBlockSyntax
Select Case kind
Case SyntaxKind.GetAccessorBlock
Return CreateGetAccessorBlock(statements)
Case SyntaxKind.SetAccessorBlock
Return CreateSetAccessorBlock(type, statements)
Case SyntaxKind.AddHandlerAccessorBlock
Return CreateAddHandlerAccessorBlock(type, statements)
Case SyntaxKind.RemoveHandlerAccessorBlock
Return CreateRemoveHandlerAccessorBlock(type, statements)
Case Else
Return Nothing
End Select
End Function
Private Function CreateGetAccessorBlock(statements As IEnumerable(Of SyntaxNode)) As AccessorBlockSyntax
Return SyntaxFactory.AccessorBlock(
SyntaxKind.GetAccessorBlock,
SyntaxFactory.AccessorStatement(SyntaxKind.GetAccessorStatement, SyntaxFactory.Token(SyntaxKind.GetKeyword)),
GetStatementList(statements),
SyntaxFactory.EndGetStatement())
End Function
Private Function CreateSetAccessorBlock(type As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As AccessorBlockSyntax
Dim asClause = SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax))
Dim valueParameter = SyntaxFactory.Parameter(
attributeLists:=Nothing,
modifiers:=Nothing,
identifier:=SyntaxFactory.ModifiedIdentifier("value"),
asClause:=asClause,
[default]:=Nothing)
Return SyntaxFactory.AccessorBlock(
SyntaxKind.SetAccessorBlock,
SyntaxFactory.AccessorStatement(
kind:=SyntaxKind.SetAccessorStatement,
attributeLists:=Nothing,
modifiers:=Nothing,
accessorKeyword:=SyntaxFactory.Token(SyntaxKind.SetKeyword),
parameterList:=SyntaxFactory.ParameterList(SyntaxFactory.SingletonSeparatedList(valueParameter))),
GetStatementList(statements),
SyntaxFactory.EndSetStatement())
End Function
Private Function CreateAddHandlerAccessorBlock(delegateType As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As AccessorBlockSyntax
Dim asClause = SyntaxFactory.SimpleAsClause(DirectCast(delegateType, TypeSyntax))
Dim valueParameter = SyntaxFactory.Parameter(
attributeLists:=Nothing,
modifiers:=Nothing,
identifier:=SyntaxFactory.ModifiedIdentifier("value"),
asClause:=asClause,
[default]:=Nothing)
Return SyntaxFactory.AccessorBlock(
SyntaxKind.AddHandlerAccessorBlock,
SyntaxFactory.AccessorStatement(
kind:=SyntaxKind.AddHandlerAccessorStatement,
attributeLists:=Nothing,
modifiers:=Nothing,
accessorKeyword:=SyntaxFactory.Token(SyntaxKind.AddHandlerKeyword),
parameterList:=SyntaxFactory.ParameterList(SyntaxFactory.SingletonSeparatedList(valueParameter))),
GetStatementList(statements),
SyntaxFactory.EndAddHandlerStatement())
End Function
Private Function CreateRemoveHandlerAccessorBlock(delegateType As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As AccessorBlockSyntax
Dim asClause = SyntaxFactory.SimpleAsClause(DirectCast(delegateType, TypeSyntax))
Dim valueParameter = SyntaxFactory.Parameter(
attributeLists:=Nothing,
modifiers:=Nothing,
identifier:=SyntaxFactory.ModifiedIdentifier("value"),
asClause:=asClause,
[default]:=Nothing)
Return SyntaxFactory.AccessorBlock(
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxFactory.AccessorStatement(
kind:=SyntaxKind.RemoveHandlerAccessorStatement,
attributeLists:=Nothing,
modifiers:=Nothing,
accessorKeyword:=SyntaxFactory.Token(SyntaxKind.RemoveHandlerKeyword),
parameterList:=SyntaxFactory.ParameterList(SyntaxFactory.SingletonSeparatedList(valueParameter))),
GetStatementList(statements),
SyntaxFactory.EndRemoveHandlerStatement())
End Function
Private Function CreateRaiseEventAccessorBlock(parameters As IEnumerable(Of SyntaxNode), statements As IEnumerable(Of SyntaxNode)) As AccessorBlockSyntax
Dim parameterList = GetParameterList(parameters)
Return SyntaxFactory.AccessorBlock(
SyntaxKind.RaiseEventAccessorBlock,
SyntaxFactory.AccessorStatement(
kind:=SyntaxKind.RaiseEventAccessorStatement,
attributeLists:=Nothing,
modifiers:=Nothing,
accessorKeyword:=SyntaxFactory.Token(SyntaxKind.RaiseEventKeyword),
parameterList:=parameterList),
GetStatementList(statements),
SyntaxFactory.EndRaiseEventStatement())
End Function
Public Overrides Function AsPublicInterfaceImplementation(declaration As SyntaxNode, interfaceTypeName As SyntaxNode, interfaceMemberName As String) As SyntaxNode
Return Isolate(declaration, Function(decl) AsPublicInterfaceImplementationInternal(decl, interfaceTypeName, interfaceMemberName))
End Function
Private Function AsPublicInterfaceImplementationInternal(declaration As SyntaxNode, interfaceTypeName As SyntaxNode, interfaceMemberName As String) As SyntaxNode
Dim type = DirectCast(interfaceTypeName, NameSyntax)
declaration = WithBody(declaration, allowDefault:=True)
declaration = WithAccessibility(declaration, Accessibility.Public)
Dim memberName = If(interfaceMemberName IsNot Nothing, interfaceMemberName, GetInterfaceMemberName(declaration))
declaration = WithName(declaration, memberName)
declaration = WithImplementsClause(declaration, SyntaxFactory.ImplementsClause(SyntaxFactory.QualifiedName(type, SyntaxFactory.IdentifierName(memberName))))
Return declaration
End Function
Public Overrides Function AsPrivateInterfaceImplementation(declaration As SyntaxNode, interfaceTypeName As SyntaxNode, interfaceMemberName As String) As SyntaxNode
Return Isolate(declaration, Function(decl) AsPrivateInterfaceImplementationInternal(decl, interfaceTypeName, interfaceMemberName))
End Function
Private Function AsPrivateInterfaceImplementationInternal(declaration As SyntaxNode, interfaceTypeName As SyntaxNode, interfaceMemberName As String) As SyntaxNode
Dim type = DirectCast(interfaceTypeName, NameSyntax)
declaration = WithBody(declaration, allowDefault:=False)
declaration = WithAccessibility(declaration, Accessibility.Private)
Dim memberName = If(interfaceMemberName IsNot Nothing, interfaceMemberName, GetInterfaceMemberName(declaration))
declaration = WithName(declaration, GetNameAsIdentifier(interfaceTypeName) & "_" & memberName)
declaration = WithImplementsClause(declaration, SyntaxFactory.ImplementsClause(SyntaxFactory.QualifiedName(type, SyntaxFactory.IdentifierName(memberName))))
Return declaration
End Function
Private Function GetInterfaceMemberName(declaration As SyntaxNode) As String
Dim clause = GetImplementsClause(declaration)
If clause IsNot Nothing Then
Dim qname = clause.InterfaceMembers.FirstOrDefault(Function(n) n.Right IsNot Nothing)
If qname IsNot Nothing Then
Return qname.Right.ToString()
End If
End If
Return GetName(declaration)
End Function
Private Function GetImplementsClause(declaration As SyntaxNode) As ImplementsClauseSyntax
Select Case declaration.Kind
Case SyntaxKind.SubBlock,
SyntaxKind.FunctionBlock
Return DirectCast(declaration, MethodBlockSyntax).SubOrFunctionStatement.ImplementsClause
Case SyntaxKind.SubStatement,
SyntaxKind.FunctionStatement
Return DirectCast(declaration, MethodStatementSyntax).ImplementsClause
Case SyntaxKind.PropertyBlock
Return DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.ImplementsClause
Case SyntaxKind.PropertyStatement
Return DirectCast(declaration, PropertyStatementSyntax).ImplementsClause
Case Else
Return Nothing
End Select
End Function
Private Function WithImplementsClause(declaration As SyntaxNode, clause As ImplementsClauseSyntax) As SyntaxNode
Select Case declaration.Kind
Case SyntaxKind.SubBlock,
SyntaxKind.FunctionBlock
Dim mb = DirectCast(declaration, MethodBlockSyntax)
Return mb.WithSubOrFunctionStatement(mb.SubOrFunctionStatement.WithImplementsClause(clause))
Case SyntaxKind.SubStatement,
SyntaxKind.FunctionStatement
Return DirectCast(declaration, MethodStatementSyntax).WithImplementsClause(clause)
Case SyntaxKind.PropertyBlock
Dim pb = DirectCast(declaration, PropertyBlockSyntax)
Return pb.WithPropertyStatement(pb.PropertyStatement.WithImplementsClause(clause))
Case SyntaxKind.PropertyStatement
Return DirectCast(declaration, PropertyStatementSyntax).WithImplementsClause(clause)
Case Else
Return declaration
End Select
End Function
Private Function GetNameAsIdentifier(type As SyntaxNode) As String
Dim name = TryCast(type, IdentifierNameSyntax)
If name IsNot Nothing Then
Return name.Identifier.ValueText
End If
Dim gname = TryCast(type, GenericNameSyntax)
If gname IsNot Nothing Then
Return gname.Identifier.ValueText & "_" & gname.TypeArgumentList.Arguments.Select(Function(t) GetNameAsIdentifier(t)).Aggregate(Function(a, b) a & "_" & b)
End If
Dim qname = TryCast(type, QualifiedNameSyntax)
If qname IsNot Nothing Then
Return GetNameAsIdentifier(qname.Right)
End If
Return "[" & type.ToString() & "]"
End Function
Private Function WithBody(declaration As SyntaxNode, allowDefault As Boolean) As SyntaxNode
declaration = Me.WithModifiersInternal(declaration, Me.GetModifiers(declaration) - DeclarationModifiers.Abstract)
Dim method = TryCast(declaration, MethodStatementSyntax)
If method IsNot Nothing Then
Return SyntaxFactory.MethodBlock(
kind:=If(method.IsKind(SyntaxKind.FunctionStatement), SyntaxKind.FunctionBlock, SyntaxKind.SubBlock),
subOrFunctionStatement:=method,
endSubOrFunctionStatement:=If(method.IsKind(SyntaxKind.FunctionStatement), SyntaxFactory.EndFunctionStatement(), SyntaxFactory.EndSubStatement()))
End If
Dim prop = TryCast(declaration, PropertyStatementSyntax)
If prop IsNot Nothing Then
prop = prop.WithModifiers(WithIsDefault(prop.Modifiers, GetIsDefault(prop.Modifiers) And allowDefault, GetDeclarationKind(declaration)))
Dim accessors = New List(Of AccessorBlockSyntax)
accessors.Add(CreateGetAccessorBlock(Nothing))
If (Not prop.Modifiers.Any(SyntaxKind.ReadOnlyKeyword)) Then
accessors.Add(CreateSetAccessorBlock(prop.AsClause.Type, Nothing))
End If
Return SyntaxFactory.PropertyBlock(
propertyStatement:=prop,
accessors:=SyntaxFactory.List(accessors),
endPropertyStatement:=SyntaxFactory.EndPropertyStatement())
End If
Return declaration
End Function
Private Function GetIsDefault(modifierList As SyntaxTokenList) As Boolean
Dim access As Accessibility
Dim modifiers As DeclarationModifiers
Dim isDefault As Boolean
Me.GetAccessibilityAndModifiers(modifierList, access, modifiers, isDefault)
Return isDefault
End Function
Private Function WithIsDefault(modifierList As SyntaxTokenList, isDefault As Boolean, kind As DeclarationKind) As SyntaxTokenList
Dim access As Accessibility
Dim modifiers As DeclarationModifiers
Dim currentIsDefault As Boolean
Me.GetAccessibilityAndModifiers(modifierList, access, modifiers, currentIsDefault)
If currentIsDefault <> isDefault Then
Return GetModifierList(access, modifiers, kind, isDefault)
Else
Return modifierList
End If
End Function
Public Overrides Function ConstructorDeclaration(
Optional name As String = Nothing,
Optional parameters As IEnumerable(Of SyntaxNode) = Nothing,
Optional accessibility As Accessibility = Nothing,
Optional modifiers As DeclarationModifiers = Nothing,
Optional baseConstructorArguments As IEnumerable(Of SyntaxNode) = Nothing,
Optional statements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode
Dim stats = GetStatementList(statements)
If (baseConstructorArguments IsNot Nothing) Then
Dim baseCall = DirectCast(Me.ExpressionStatement(Me.InvocationExpression(Me.MemberAccessExpression(Me.BaseExpression(), SyntaxFactory.IdentifierName("New")), baseConstructorArguments)), StatementSyntax)
stats = stats.Insert(0, baseCall)
End If
Return SyntaxFactory.ConstructorBlock(
subNewStatement:=SyntaxFactory.SubNewStatement(
attributeLists:=Nothing,
modifiers:=GetModifierList(accessibility, modifiers And s_constructorModifiers, DeclarationKind.Constructor),
parameterList:=If(parameters IsNot Nothing, SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(parameters.Cast(Of ParameterSyntax)())), SyntaxFactory.ParameterList())),
statements:=stats)
End Function
Public Overrides Function ClassDeclaration(
name As String,
Optional typeParameters As IEnumerable(Of String) = Nothing,
Optional accessibility As Accessibility = Nothing,
Optional modifiers As DeclarationModifiers = Nothing,
Optional baseType As SyntaxNode = Nothing,
Optional interfaceTypes As IEnumerable(Of SyntaxNode) = Nothing,
Optional members As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode
Dim itypes = If(interfaceTypes IsNot Nothing, interfaceTypes.Cast(Of TypeSyntax), Nothing)
If itypes IsNot Nothing AndAlso itypes.Count = 0 Then
itypes = Nothing
End If
Return SyntaxFactory.ClassBlock(
classStatement:=SyntaxFactory.ClassStatement(
attributeLists:=Nothing,
modifiers:=GetModifierList(accessibility, modifiers And s_classModifiers, DeclarationKind.Class),
identifier:=name.ToIdentifierToken(),
typeParameterList:=GetTypeParameters(typeParameters)),
[inherits]:=If(baseType IsNot Nothing, SyntaxFactory.SingletonList(SyntaxFactory.InheritsStatement(DirectCast(baseType, TypeSyntax))), Nothing),
[implements]:=If(itypes IsNot Nothing, SyntaxFactory.SingletonList(SyntaxFactory.ImplementsStatement(SyntaxFactory.SeparatedList(itypes))), Nothing),
members:=AsClassMembers(members))
End Function
Private Function AsClassMembers(nodes As IEnumerable(Of SyntaxNode)) As SyntaxList(Of StatementSyntax)
If nodes IsNot Nothing Then
Return SyntaxFactory.List(nodes.Select(AddressOf AsClassMember).Where(Function(n) n IsNot Nothing))
Else
Return Nothing
End If
End Function
Private Function AsClassMember(node As SyntaxNode) As StatementSyntax
Return TryCast(AsIsolatedDeclaration(node), StatementSyntax)
End Function
Public Overrides Function StructDeclaration(
name As String,
Optional typeParameters As IEnumerable(Of String) = Nothing,
Optional accessibility As Accessibility = Nothing,
Optional modifiers As DeclarationModifiers = Nothing,
Optional interfaceTypes As IEnumerable(Of SyntaxNode) = Nothing,
Optional members As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode
Dim itypes = If(interfaceTypes IsNot Nothing, interfaceTypes.Cast(Of TypeSyntax), Nothing)
If itypes IsNot Nothing AndAlso itypes.Count = 0 Then
itypes = Nothing
End If
Return SyntaxFactory.StructureBlock(
structureStatement:=SyntaxFactory.StructureStatement(
attributeLists:=Nothing,
modifiers:=GetModifierList(accessibility, modifiers And s_structModifiers, DeclarationKind.Struct),
identifier:=name.ToIdentifierToken(),
typeParameterList:=GetTypeParameters(typeParameters)),
[inherits]:=Nothing,
[implements]:=If(itypes IsNot Nothing, SyntaxFactory.SingletonList(SyntaxFactory.ImplementsStatement(SyntaxFactory.SeparatedList(itypes))), Nothing),
members:=If(members IsNot Nothing, SyntaxFactory.List(members.Cast(Of StatementSyntax)()), Nothing))
End Function
Private Function AsStructureMembers(nodes As IEnumerable(Of SyntaxNode)) As SyntaxList(Of StatementSyntax)
If nodes IsNot Nothing Then
Return SyntaxFactory.List(nodes.Select(AddressOf AsStructureMember).Where(Function(n) n IsNot Nothing))
Else
Return Nothing
End If
End Function
Private Function AsStructureMember(node As SyntaxNode) As StatementSyntax
Return TryCast(node, StatementSyntax)
End Function
Public Overrides Function InterfaceDeclaration(
name As String,
Optional typeParameters As IEnumerable(Of String) = Nothing,
Optional accessibility As Accessibility = Nothing,
Optional interfaceTypes As IEnumerable(Of SyntaxNode) = Nothing,
Optional members As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode
Dim itypes = If(interfaceTypes IsNot Nothing, interfaceTypes.Cast(Of TypeSyntax), Nothing)
If itypes IsNot Nothing AndAlso itypes.Count = 0 Then
itypes = Nothing
End If
Return SyntaxFactory.InterfaceBlock(
interfaceStatement:=SyntaxFactory.InterfaceStatement(
attributeLists:=Nothing,
modifiers:=GetModifierList(accessibility, DeclarationModifiers.None, DeclarationKind.Interface),
identifier:=name.ToIdentifierToken(),
typeParameterList:=GetTypeParameters(typeParameters)),
[inherits]:=If(itypes IsNot Nothing, SyntaxFactory.SingletonList(SyntaxFactory.InheritsStatement(SyntaxFactory.SeparatedList(itypes))), Nothing),
[implements]:=Nothing,
members:=AsInterfaceMembers(members))
End Function
Private Function AsInterfaceMembers(nodes As IEnumerable(Of SyntaxNode)) As SyntaxList(Of StatementSyntax)
If nodes IsNot Nothing Then
Return SyntaxFactory.List(nodes.Select(AddressOf AsInterfaceMember).Where(Function(n) n IsNot Nothing))
Else
Return Nothing
End If
End Function
Friend Overrides Function AsInterfaceMember(node As SyntaxNode) As SyntaxNode
If node IsNot Nothing Then
Select Case node.Kind
Case SyntaxKind.FunctionBlock,
SyntaxKind.SubBlock
Return AsInterfaceMember(DirectCast(node, MethodBlockSyntax).BlockStatement)
Case SyntaxKind.FunctionStatement,
SyntaxKind.SubStatement
Return Isolate(node, Function(d) DirectCast(d, MethodStatementSyntax).WithModifiers(Nothing))
Case SyntaxKind.PropertyBlock
Return AsInterfaceMember(DirectCast(node, PropertyBlockSyntax).PropertyStatement)
Case SyntaxKind.PropertyStatement
Return Isolate(
node,
Function(d)
Dim propertyStatement = DirectCast(d, PropertyStatementSyntax)
Dim mods = SyntaxFactory.TokenList(propertyStatement.Modifiers.Where(Function(tk) tk.IsKind(SyntaxKind.ReadOnlyKeyword) Or tk.IsKind(SyntaxKind.DefaultKeyword)))
Return propertyStatement.WithModifiers(mods)
End Function)
Case SyntaxKind.EventBlock
Return AsInterfaceMember(DirectCast(node, EventBlockSyntax).EventStatement)
Case SyntaxKind.EventStatement
Return Isolate(node, Function(d) DirectCast(d, EventStatementSyntax).WithModifiers(Nothing).WithCustomKeyword(Nothing))
End Select
End If
Return Nothing
End Function
Public Overrides Function EnumDeclaration(
name As String,
Optional accessibility As Accessibility = Nothing,
Optional modifiers As DeclarationModifiers = Nothing,
Optional members As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode
Return SyntaxFactory.EnumBlock(
enumStatement:=SyntaxFactory.EnumStatement(
attributeLists:=Nothing,
modifiers:=GetModifierList(accessibility, modifiers And GetAllowedModifiers(SyntaxKind.EnumStatement), DeclarationKind.Enum),
identifier:=name.ToIdentifierToken(),
underlyingType:=Nothing),
members:=AsEnumMembers(members))
End Function
Public Overrides Function EnumMember(name As String, Optional expression As SyntaxNode = Nothing) As SyntaxNode
Return SyntaxFactory.EnumMemberDeclaration(
attributeLists:=Nothing,
identifier:=name.ToIdentifierToken(),
initializer:=If(expression IsNot Nothing, SyntaxFactory.EqualsValue(DirectCast(expression, ExpressionSyntax)), Nothing))
End Function
Private Function AsEnumMembers(nodes As IEnumerable(Of SyntaxNode)) As SyntaxList(Of StatementSyntax)
If nodes IsNot Nothing Then
Return SyntaxFactory.List(nodes.Select(AddressOf AsEnumMember).Where(Function(n) n IsNot Nothing))
Else
Return Nothing
End If
End Function
Private Function AsEnumMember(node As SyntaxNode) As StatementSyntax
Dim id = TryCast(node, IdentifierNameSyntax)
If id IsNot Nothing Then
Return DirectCast(EnumMember(id.Identifier.ValueText), EnumMemberDeclarationSyntax)
End If
Return TryCast(node, EnumMemberDeclarationSyntax)
End Function
Public Overrides Function DelegateDeclaration(
name As String,
Optional parameters As IEnumerable(Of SyntaxNode) = Nothing,
Optional typeParameters As IEnumerable(Of String) = Nothing,
Optional returnType As SyntaxNode = Nothing,
Optional accessibility As Accessibility = Accessibility.NotApplicable,
Optional modifiers As DeclarationModifiers = Nothing) As SyntaxNode
Dim kind = If(returnType Is Nothing, SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement)
Return SyntaxFactory.DelegateStatement(
kind:=kind,
attributeLists:=Nothing,
modifiers:=GetModifierList(accessibility, modifiers And GetAllowedModifiers(kind), DeclarationKind.Delegate),
subOrFunctionKeyword:=If(kind = SyntaxKind.DelegateSubStatement, SyntaxFactory.Token(SyntaxKind.SubKeyword), SyntaxFactory.Token(SyntaxKind.FunctionKeyword)),
identifier:=name.ToIdentifierToken(),
typeParameterList:=GetTypeParameters(typeParameters),
parameterList:=GetParameterList(parameters),
asClause:=If(kind = SyntaxKind.DelegateFunctionStatement, SyntaxFactory.SimpleAsClause(DirectCast(returnType, TypeSyntax)), Nothing))
End Function
Public Overrides Function CompilationUnit(declarations As IEnumerable(Of SyntaxNode)) As SyntaxNode
Return SyntaxFactory.CompilationUnit().WithImports(AsImports(declarations)).WithMembers(AsNamespaceMembers(declarations))
End Function
Private Function AsImports(declarations As IEnumerable(Of SyntaxNode)) As SyntaxList(Of ImportsStatementSyntax)
Return If(declarations Is Nothing, Nothing, SyntaxFactory.List(declarations.Select(AddressOf AsNamespaceImport).OfType(Of ImportsStatementSyntax)()))
End Function
Private Function AsNamespaceImport(node As SyntaxNode) As SyntaxNode
Dim name = TryCast(node, NameSyntax)
If name IsNot Nothing Then
Return Me.NamespaceImportDeclaration(name)
End If
Return TryCast(node, ImportsStatementSyntax)
End Function
Private Function AsNamespaceMembers(declarations As IEnumerable(Of SyntaxNode)) As SyntaxList(Of StatementSyntax)
Return If(declarations Is Nothing, Nothing, SyntaxFactory.List(declarations.OfType(Of StatementSyntax)().Where(Function(s) Not TypeOf s Is ImportsStatementSyntax)))
End Function
Public Overrides Function NamespaceImportDeclaration(name As SyntaxNode) As SyntaxNode
Return SyntaxFactory.ImportsStatement(SyntaxFactory.SingletonSeparatedList(Of ImportsClauseSyntax)(SyntaxFactory.SimpleImportsClause(DirectCast(name, NameSyntax))))
End Function
Public Overrides Function AliasImportDeclaration(aliasIdentifierName As String, name As SyntaxNode) As SyntaxNode
If TypeOf name Is NameSyntax Then
Return SyntaxFactory.ImportsStatement(SyntaxFactory.SeparatedList(Of ImportsClauseSyntax).Add(
SyntaxFactory.SimpleImportsClause(
SyntaxFactory.ImportAliasClause(aliasIdentifierName),
CType(name, NameSyntax))))
End If
Throw New ArgumentException("name is not a NameSyntax.", NameOf(name))
End Function
Public Overrides Function NamespaceDeclaration(name As SyntaxNode, nestedDeclarations As IEnumerable(Of SyntaxNode)) As SyntaxNode
Dim imps As IEnumerable(Of StatementSyntax) = AsImports(nestedDeclarations)
Dim members As IEnumerable(Of StatementSyntax) = AsNamespaceMembers(nestedDeclarations)
' put imports at start
Dim statements = imps.Concat(members)
Return SyntaxFactory.NamespaceBlock(
SyntaxFactory.NamespaceStatement(DirectCast(name, NameSyntax)),
members:=SyntaxFactory.List(statements))
End Function
Public Overrides Function Attribute(name As SyntaxNode, Optional attributeArguments As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode
Dim attr = SyntaxFactory.Attribute(
target:=Nothing,
name:=DirectCast(name, TypeSyntax),
argumentList:=AsArgumentList(attributeArguments))
Return AsAttributeList(attr)
End Function
Private Function AsArgumentList(arguments As IEnumerable(Of SyntaxNode)) As ArgumentListSyntax
If arguments IsNot Nothing Then
Return SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(arguments.Select(AddressOf AsArgument)))
Else
Return Nothing
End If
End Function
Public Overrides Function AttributeArgument(name As String, expression As SyntaxNode) As SyntaxNode
Return Argument(name, RefKind.None, expression)
End Function
Public Overrides Function ClearTrivia(Of TNode As SyntaxNode)(node As TNode) As TNode
If node IsNot Nothing Then
Return node.WithLeadingTrivia(SyntaxFactory.ElasticMarker).WithTrailingTrivia(SyntaxFactory.ElasticMarker)
Else
Return Nothing
End If
End Function
Private Function AsAttributeLists(attributes As IEnumerable(Of SyntaxNode)) As SyntaxList(Of AttributeListSyntax)
If attributes IsNot Nothing Then
Return SyntaxFactory.List(attributes.Select(AddressOf AsAttributeList))
Else
Return Nothing
End If
End Function
Private Function AsAttributeList(node As SyntaxNode) As AttributeListSyntax
Dim attr = TryCast(node, AttributeSyntax)
If attr IsNot Nothing Then
Return SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(WithNoTarget(attr)))
Else
Return WithNoTargets(DirectCast(node, AttributeListSyntax))
End If
End Function
Private Overloads Function WithNoTargets(attrs As AttributeListSyntax) As AttributeListSyntax
If (attrs.Attributes.Any(Function(a) a.Target IsNot Nothing)) Then
Return attrs.WithAttributes(SyntaxFactory.SeparatedList(attrs.Attributes.Select(AddressOf WithAssemblyTarget)))
Else
Return attrs
End If
End Function
Private Overloads Function WithNoTarget(attr As AttributeSyntax) As AttributeSyntax
Return attr.WithTarget(Nothing)
End Function
Friend Overrides Function GetTypeInheritance(declaration As SyntaxNode) As ImmutableArray(Of SyntaxNode)
Dim typeDecl = TryCast(declaration, TypeBlockSyntax)
If typeDecl Is Nothing Then
Return ImmutableArray(Of SyntaxNode).Empty
End If
Dim builder = ArrayBuilder(Of SyntaxNode).GetInstance()
builder.AddRange(typeDecl.Inherits)
builder.AddRange(typeDecl.Implements)
Return builder.ToImmutableAndFree()
End Function
Public Overrides Function GetAttributes(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode)
Return Me.Flatten(GetAttributeLists(declaration))
End Function
Public Overrides Function InsertAttributes(declaration As SyntaxNode, index As Integer, attributes As IEnumerable(Of SyntaxNode)) As SyntaxNode
Return Isolate(declaration, Function(d) InsertAttributesInternal(d, index, attributes))
End Function
Private Function InsertAttributesInternal(declaration As SyntaxNode, index As Integer, attributes As IEnumerable(Of SyntaxNode)) As SyntaxNode
Dim newAttributes = AsAttributeLists(attributes)
Dim existingAttributes = Me.GetAttributes(declaration)
If index >= 0 AndAlso index < existingAttributes.Count Then
Return Me.InsertNodesBefore(declaration, existingAttributes(index), newAttributes)
ElseIf existingAttributes.Count > 0 Then
Return Me.InsertNodesAfter(declaration, existingAttributes(existingAttributes.Count - 1), newAttributes)
Else
Dim lists = GetAttributeLists(declaration)
Return Me.WithAttributeLists(declaration, lists.AddRange(AsAttributeLists(attributes)))
End If
End Function
Private Shared Function HasAssemblyTarget(attr As AttributeSyntax) As Boolean
Return attr.Target IsNot Nothing AndAlso attr.Target.AttributeModifier.IsKind(SyntaxKind.AssemblyKeyword)
End Function
Private Overloads Function WithAssemblyTargets(attrs As AttributeListSyntax) As AttributeListSyntax
If attrs.Attributes.Any(Function(a) Not HasAssemblyTarget(a)) Then
Return attrs.WithAttributes(SyntaxFactory.SeparatedList(attrs.Attributes.Select(AddressOf WithAssemblyTarget)))
Else
Return attrs
End If
End Function
Private Overloads Function WithAssemblyTarget(attr As AttributeSyntax) As AttributeSyntax
If Not HasAssemblyTarget(attr) Then
Return attr.WithTarget(SyntaxFactory.AttributeTarget(SyntaxFactory.Token(SyntaxKind.AssemblyKeyword)))
Else
Return attr
End If
End Function
Public Overrides Function GetReturnAttributes(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode)
Return Me.Flatten(GetReturnAttributeLists(declaration))
End Function
Public Overrides Function InsertReturnAttributes(declaration As SyntaxNode, index As Integer, attributes As IEnumerable(Of SyntaxNode)) As SyntaxNode
Select Case declaration.Kind
Case SyntaxKind.FunctionBlock,
SyntaxKind.FunctionStatement,
SyntaxKind.DelegateFunctionStatement
Return Isolate(declaration, Function(d) InsertReturnAttributesInternal(d, index, attributes))
Case Else
Return declaration
End Select
End Function
Private Function InsertReturnAttributesInternal(declaration As SyntaxNode, index As Integer, attributes As IEnumerable(Of SyntaxNode)) As SyntaxNode
Dim newAttributes = AsAttributeLists(attributes)
Dim existingReturnAttributes = Me.GetReturnAttributes(declaration)
If index >= 0 AndAlso index < existingReturnAttributes.Count Then
Return Me.InsertNodesBefore(declaration, existingReturnAttributes(index), newAttributes)
ElseIf existingReturnAttributes.Count > 0 Then
Return Me.InsertNodesAfter(declaration, existingReturnAttributes(existingReturnAttributes.Count - 1), newAttributes)
Else
Dim lists = Me.GetReturnAttributeLists(declaration)
Dim newLists = lists.AddRange(newAttributes)
Return Me.WithReturnAttributeLists(declaration, newLists)
End If
End Function
Private Function GetReturnAttributeLists(declaration As SyntaxNode) As SyntaxList(Of AttributeListSyntax)
Dim asClause = GetAsClause(declaration)
If asClause IsNot Nothing Then
Select Case declaration.Kind()
Case SyntaxKind.FunctionBlock,
SyntaxKind.FunctionStatement,
SyntaxKind.DelegateFunctionStatement
Return asClause.Attributes
End Select
End If
Return Nothing
End Function
Private Function WithReturnAttributeLists(declaration As SyntaxNode, lists As IEnumerable(Of AttributeListSyntax)) As SyntaxNode
If declaration Is Nothing Then
Return Nothing
End If
Select Case declaration.Kind()
Case SyntaxKind.FunctionBlock
Dim fb = DirectCast(declaration, MethodBlockSyntax)
Dim asClause = DirectCast(WithReturnAttributeLists(GetAsClause(declaration), lists), SimpleAsClauseSyntax)
Return fb.WithSubOrFunctionStatement(fb.SubOrFunctionStatement.WithAsClause(asClause))
Case SyntaxKind.FunctionStatement
Dim ms = DirectCast(declaration, MethodStatementSyntax)
Dim asClause = DirectCast(WithReturnAttributeLists(GetAsClause(declaration), lists), SimpleAsClauseSyntax)
Return ms.WithAsClause(asClause)
Case SyntaxKind.DelegateFunctionStatement
Dim df = DirectCast(declaration, DelegateStatementSyntax)
Dim asClause = DirectCast(WithReturnAttributeLists(GetAsClause(declaration), lists), SimpleAsClauseSyntax)
Return df.WithAsClause(asClause)
Case SyntaxKind.SimpleAsClause
Return DirectCast(declaration, SimpleAsClauseSyntax).WithAttributeLists(SyntaxFactory.List(lists))
Case Else
Return Nothing
End Select
End Function
Friend Shared Function GetAttributeLists(node As SyntaxNode) As SyntaxList(Of AttributeListSyntax)
Select Case node.Kind
Case SyntaxKind.CompilationUnit
Return SyntaxFactory.List(DirectCast(node, CompilationUnitSyntax).Attributes.SelectMany(Function(s) s.AttributeLists))
Case SyntaxKind.ClassBlock
Return DirectCast(node, ClassBlockSyntax).BlockStatement.AttributeLists
Case SyntaxKind.ClassStatement
Return DirectCast(node, ClassStatementSyntax).AttributeLists
Case SyntaxKind.StructureBlock
Return DirectCast(node, StructureBlockSyntax).BlockStatement.AttributeLists
Case SyntaxKind.StructureStatement
Return DirectCast(node, StructureStatementSyntax).AttributeLists
Case SyntaxKind.InterfaceBlock
Return DirectCast(node, InterfaceBlockSyntax).BlockStatement.AttributeLists
Case SyntaxKind.InterfaceStatement
Return DirectCast(node, InterfaceStatementSyntax).AttributeLists
Case SyntaxKind.EnumBlock
Return DirectCast(node, EnumBlockSyntax).EnumStatement.AttributeLists
Case SyntaxKind.EnumStatement
Return DirectCast(node, EnumStatementSyntax).AttributeLists
Case SyntaxKind.EnumMemberDeclaration
Return DirectCast(node, EnumMemberDeclarationSyntax).AttributeLists
Case SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement
Return DirectCast(node, DelegateStatementSyntax).AttributeLists
Case SyntaxKind.FieldDeclaration
Return DirectCast(node, FieldDeclarationSyntax).AttributeLists
Case SyntaxKind.FunctionBlock,
SyntaxKind.SubBlock,
SyntaxKind.ConstructorBlock
Return DirectCast(node, MethodBlockBaseSyntax).BlockStatement.AttributeLists
Case SyntaxKind.FunctionStatement,
SyntaxKind.SubStatement
Return DirectCast(node, MethodStatementSyntax).AttributeLists
Case SyntaxKind.SubNewStatement
Return DirectCast(node, SubNewStatementSyntax).AttributeLists
Case SyntaxKind.Parameter
Return DirectCast(node, ParameterSyntax).AttributeLists
Case SyntaxKind.PropertyBlock
Return DirectCast(node, PropertyBlockSyntax).PropertyStatement.AttributeLists
Case SyntaxKind.PropertyStatement
Return DirectCast(node, PropertyStatementSyntax).AttributeLists
Case SyntaxKind.OperatorBlock
Return DirectCast(node, OperatorBlockSyntax).BlockStatement.AttributeLists
Case SyntaxKind.OperatorStatement
Return DirectCast(node, OperatorStatementSyntax).AttributeLists
Case SyntaxKind.EventBlock
Return DirectCast(node, EventBlockSyntax).EventStatement.AttributeLists
Case SyntaxKind.EventStatement
Return DirectCast(node, EventStatementSyntax).AttributeLists
Case SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock
Return DirectCast(node, AccessorBlockSyntax).AccessorStatement.AttributeLists
Case SyntaxKind.GetAccessorStatement,
SyntaxKind.SetAccessorStatement,
SyntaxKind.AddHandlerAccessorStatement,
SyntaxKind.RemoveHandlerAccessorStatement,
SyntaxKind.RaiseEventAccessorStatement
Return DirectCast(node, AccessorStatementSyntax).AttributeLists
Case Else
Return Nothing
End Select
End Function
Private Function WithAttributeLists(node As SyntaxNode, lists As IEnumerable(Of AttributeListSyntax)) As SyntaxNode
Dim arg = SyntaxFactory.List(lists)
Select Case node.Kind
Case SyntaxKind.CompilationUnit
'convert to assembly target
arg = SyntaxFactory.List(lists.Select(Function(lst) Me.WithAssemblyTargets(lst)))
' add as single attributes statement
Return DirectCast(node, CompilationUnitSyntax).WithAttributes(SyntaxFactory.SingletonList(SyntaxFactory.AttributesStatement(arg)))
Case SyntaxKind.ClassBlock
Return DirectCast(node, ClassBlockSyntax).WithClassStatement(DirectCast(node, ClassBlockSyntax).ClassStatement.WithAttributeLists(arg))
Case SyntaxKind.ClassStatement
Return DirectCast(node, ClassStatementSyntax).WithAttributeLists(arg)
Case SyntaxKind.StructureBlock
Return DirectCast(node, StructureBlockSyntax).WithStructureStatement(DirectCast(node, StructureBlockSyntax).StructureStatement.WithAttributeLists(arg))
Case SyntaxKind.StructureStatement
Return DirectCast(node, StructureStatementSyntax).WithAttributeLists(arg)
Case SyntaxKind.InterfaceBlock
Return DirectCast(node, InterfaceBlockSyntax).WithInterfaceStatement(DirectCast(node, InterfaceBlockSyntax).InterfaceStatement.WithAttributeLists(arg))
Case SyntaxKind.InterfaceStatement
Return DirectCast(node, InterfaceStatementSyntax).WithAttributeLists(arg)
Case SyntaxKind.EnumBlock
Return DirectCast(node, EnumBlockSyntax).WithEnumStatement(DirectCast(node, EnumBlockSyntax).EnumStatement.WithAttributeLists(arg))
Case SyntaxKind.EnumStatement
Return DirectCast(node, EnumStatementSyntax).WithAttributeLists(arg)
Case SyntaxKind.EnumMemberDeclaration
Return DirectCast(node, EnumMemberDeclarationSyntax).WithAttributeLists(arg)
Case SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement
Return DirectCast(node, DelegateStatementSyntax).WithAttributeLists(arg)
Case SyntaxKind.FieldDeclaration
Return DirectCast(node, FieldDeclarationSyntax).WithAttributeLists(arg)
Case SyntaxKind.FunctionBlock,
SyntaxKind.SubBlock
Return DirectCast(node, MethodBlockSyntax).WithSubOrFunctionStatement(DirectCast(node, MethodBlockSyntax).SubOrFunctionStatement.WithAttributeLists(arg))
Case SyntaxKind.FunctionStatement,
SyntaxKind.SubStatement
Return DirectCast(node, MethodStatementSyntax).WithAttributeLists(arg)
Case SyntaxKind.ConstructorBlock
Return DirectCast(node, ConstructorBlockSyntax).WithSubNewStatement(DirectCast(node, ConstructorBlockSyntax).SubNewStatement.WithAttributeLists(arg))
Case SyntaxKind.SubNewStatement
Return DirectCast(node, SubNewStatementSyntax).WithAttributeLists(arg)
Case SyntaxKind.Parameter
Return DirectCast(node, ParameterSyntax).WithAttributeLists(arg)
Case SyntaxKind.PropertyBlock
Return DirectCast(node, PropertyBlockSyntax).WithPropertyStatement(DirectCast(node, PropertyBlockSyntax).PropertyStatement.WithAttributeLists(arg))
Case SyntaxKind.PropertyStatement
Return DirectCast(node, PropertyStatementSyntax).WithAttributeLists(arg)
Case SyntaxKind.OperatorBlock
Return DirectCast(node, OperatorBlockSyntax).WithOperatorStatement(DirectCast(node, OperatorBlockSyntax).OperatorStatement.WithAttributeLists(arg))
Case SyntaxKind.OperatorStatement
Return DirectCast(node, OperatorStatementSyntax).WithAttributeLists(arg)
Case SyntaxKind.EventBlock
Return DirectCast(node, EventBlockSyntax).WithEventStatement(DirectCast(node, EventBlockSyntax).EventStatement.WithAttributeLists(arg))
Case SyntaxKind.EventStatement
Return DirectCast(node, EventStatementSyntax).WithAttributeLists(arg)
Case SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock
Return DirectCast(node, AccessorBlockSyntax).WithAccessorStatement(DirectCast(node, AccessorBlockSyntax).AccessorStatement.WithAttributeLists(arg))
Case SyntaxKind.GetAccessorStatement,
SyntaxKind.SetAccessorStatement,
SyntaxKind.AddHandlerAccessorStatement,
SyntaxKind.RemoveHandlerAccessorStatement,
SyntaxKind.RaiseEventAccessorStatement
Return DirectCast(node, AccessorStatementSyntax).WithAttributeLists(arg)
Case Else
Return node
End Select
End Function
Public Overrides Function GetDeclarationKind(declaration As SyntaxNode) As DeclarationKind
Select Case declaration.Kind
Case SyntaxKind.CompilationUnit
Return DeclarationKind.CompilationUnit
Case SyntaxKind.NamespaceBlock
Return DeclarationKind.Namespace
Case SyntaxKind.ImportsStatement
Return DeclarationKind.NamespaceImport
Case SyntaxKind.ClassBlock
Return DeclarationKind.Class
Case SyntaxKind.StructureBlock
Return DeclarationKind.Struct
Case SyntaxKind.InterfaceBlock
Return DeclarationKind.Interface
Case SyntaxKind.EnumBlock
Return DeclarationKind.Enum
Case SyntaxKind.EnumMemberDeclaration
Return DeclarationKind.EnumMember
Case SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement
Return DeclarationKind.Delegate
Case SyntaxKind.FunctionBlock,
SyntaxKind.SubBlock
Return DeclarationKind.Method
Case SyntaxKind.FunctionStatement
If Not IsChildOf(declaration, SyntaxKind.FunctionBlock) Then
Return DeclarationKind.Method
End If
Case SyntaxKind.SubStatement
If Not IsChildOf(declaration, SyntaxKind.SubBlock) Then
Return DeclarationKind.Method
End If
Case SyntaxKind.ConstructorBlock
Return DeclarationKind.Constructor
Case SyntaxKind.PropertyBlock
If IsIndexer(declaration) Then
Return DeclarationKind.Indexer
Else
Return DeclarationKind.Property
End If
Case SyntaxKind.PropertyStatement
If Not IsChildOf(declaration, SyntaxKind.PropertyBlock) Then
If IsIndexer(declaration) Then
Return DeclarationKind.Indexer
Else
Return DeclarationKind.Property
End If
End If
Case SyntaxKind.OperatorBlock
Return DeclarationKind.Operator
Case SyntaxKind.OperatorStatement
If Not IsChildOf(declaration, SyntaxKind.OperatorBlock) Then
Return DeclarationKind.Operator
End If
Case SyntaxKind.EventBlock
Return DeclarationKind.CustomEvent
Case SyntaxKind.EventStatement
If Not IsChildOf(declaration, SyntaxKind.EventBlock) Then
Return DeclarationKind.Event
End If
Case SyntaxKind.Parameter
Return DeclarationKind.Parameter
Case SyntaxKind.FieldDeclaration
If GetDeclarationCount(declaration) = 1 Then
Return DeclarationKind.Field
End If
Case SyntaxKind.LocalDeclarationStatement
If GetDeclarationCount(declaration) = 1 Then
Return DeclarationKind.Variable
End If
Case SyntaxKind.ModifiedIdentifier
If IsChildOf(declaration, SyntaxKind.VariableDeclarator) Then
If IsChildOf(declaration.Parent, SyntaxKind.FieldDeclaration) And GetDeclarationCount(declaration.Parent.Parent) > 1 Then
Return DeclarationKind.Field
ElseIf IsChildOf(declaration.Parent, SyntaxKind.LocalDeclarationStatement) And GetDeclarationCount(declaration.Parent.Parent) > 1 Then
Return DeclarationKind.Variable
End If
End If
Case SyntaxKind.Attribute
Dim list = TryCast(declaration.Parent, AttributeListSyntax)
If list Is Nothing OrElse list.Attributes.Count > 1 Then
Return DeclarationKind.Attribute
End If
Case SyntaxKind.AttributeList
Dim list = DirectCast(declaration, AttributeListSyntax)
If list.Attributes.Count = 1 Then
Return DeclarationKind.Attribute
End If
Case SyntaxKind.GetAccessorBlock
Return DeclarationKind.GetAccessor
Case SyntaxKind.SetAccessorBlock
Return DeclarationKind.SetAccessor
Case SyntaxKind.AddHandlerAccessorBlock
Return DeclarationKind.AddAccessor
Case SyntaxKind.RemoveHandlerAccessorBlock
Return DeclarationKind.RemoveAccessor
Case SyntaxKind.RaiseEventAccessorBlock
Return DeclarationKind.RaiseAccessor
End Select
Return DeclarationKind.None
End Function
Private Function GetDeclarationCount(nodes As IReadOnlyList(Of SyntaxNode)) As Integer
Dim count As Integer = 0
For i = 0 To nodes.Count - 1
count = count + GetDeclarationCount(nodes(i))
Next
Return count
End Function
Private Function GetDeclarationCount(node As SyntaxNode) As Integer
Select Case node.Kind
Case SyntaxKind.FieldDeclaration
Return GetDeclarationCount(DirectCast(node, FieldDeclarationSyntax).Declarators)
Case SyntaxKind.LocalDeclarationStatement
Return GetDeclarationCount(DirectCast(node, LocalDeclarationStatementSyntax).Declarators)
Case SyntaxKind.VariableDeclarator
Return DirectCast(node, VariableDeclaratorSyntax).Names.Count
Case SyntaxKind.AttributesStatement
Return GetDeclarationCount(DirectCast(node, AttributesStatementSyntax).AttributeLists)
Case SyntaxKind.AttributeList
Return DirectCast(node, AttributeListSyntax).Attributes.Count
Case SyntaxKind.ImportsStatement
Return DirectCast(node, ImportsStatementSyntax).ImportsClauses.Count
End Select
Return 1
End Function
Private Shared Function IsChildOf(node As SyntaxNode, kind As SyntaxKind) As Boolean
Return node.Parent IsNot Nothing AndAlso node.Parent.IsKind(kind)
End Function
Private Shared Function IsChildOfVariableDeclaration(node As SyntaxNode) As Boolean
Return IsChildOf(node, SyntaxKind.FieldDeclaration) OrElse IsChildOf(node, SyntaxKind.LocalDeclarationStatement)
End Function
Private Function Isolate(declaration As SyntaxNode, editor As Func(Of SyntaxNode, SyntaxNode)) As SyntaxNode
Dim isolated = AsIsolatedDeclaration(declaration)
Return PreserveTrivia(isolated, editor)
End Function
Private Function GetFullDeclaration(declaration As SyntaxNode) As SyntaxNode
Select Case declaration.Kind
Case SyntaxKind.ModifiedIdentifier
If IsChildOf(declaration, SyntaxKind.VariableDeclarator) Then
Return GetFullDeclaration(declaration.Parent)
End If
Case SyntaxKind.VariableDeclarator
If IsChildOfVariableDeclaration(declaration) Then
Return declaration.Parent
End If
Case SyntaxKind.Attribute
If declaration.Parent IsNot Nothing Then
Return declaration.Parent
End If
Case SyntaxKind.SimpleImportsClause,
SyntaxKind.XmlNamespaceImportsClause
If declaration.Parent IsNot Nothing Then
Return declaration.Parent
End If
End Select
Return declaration
End Function
Private Function AsIsolatedDeclaration(declaration As SyntaxNode) As SyntaxNode
Select Case declaration.Kind
Case SyntaxKind.ModifiedIdentifier
Dim full = GetFullDeclaration(declaration)
If full IsNot declaration Then
Return WithSingleVariable(full, DirectCast(declaration, ModifiedIdentifierSyntax))
End If
Case SyntaxKind.Attribute
Dim list = TryCast(declaration.Parent, AttributeListSyntax)
If list IsNot Nothing Then
Return list.WithAttributes(SyntaxFactory.SingletonSeparatedList(DirectCast(declaration, AttributeSyntax)))
End If
Case SyntaxKind.SimpleImportsClause,
SyntaxKind.XmlNamespaceImportsClause
Dim stmt = TryCast(declaration.Parent, ImportsStatementSyntax)
If stmt IsNot Nothing Then
Return stmt.WithImportsClauses(SyntaxFactory.SingletonSeparatedList(DirectCast(declaration, ImportsClauseSyntax)))
End If
End Select
Return declaration
End Function
Private Function WithSingleVariable(declaration As SyntaxNode, variable As ModifiedIdentifierSyntax) As SyntaxNode
Select Case declaration.Kind
Case SyntaxKind.FieldDeclaration
Dim fd = DirectCast(declaration, FieldDeclarationSyntax)
Return ReplaceWithTrivia(declaration, fd.Declarators(0), fd.Declarators(0).WithNames(SyntaxFactory.SingletonSeparatedList(variable)))
Case SyntaxKind.LocalDeclarationStatement
Dim ld = DirectCast(declaration, LocalDeclarationStatementSyntax)
Return ReplaceWithTrivia(declaration, ld.Declarators(0), ld.Declarators(0).WithNames(SyntaxFactory.SingletonSeparatedList(variable)))
Case SyntaxKind.VariableDeclarator
Dim vd = DirectCast(declaration, VariableDeclaratorSyntax)
Return vd.WithNames(SyntaxFactory.SingletonSeparatedList(variable))
Case Else
Return declaration
End Select
End Function
Private Shared Function IsIndexer(declaration As SyntaxNode) As Boolean
Select Case declaration.Kind
Case SyntaxKind.PropertyBlock
Dim p = DirectCast(declaration, PropertyBlockSyntax).PropertyStatement
Return p.ParameterList IsNot Nothing AndAlso p.ParameterList.Parameters.Count > 0 AndAlso p.Modifiers.Any(SyntaxKind.DefaultKeyword)
Case SyntaxKind.PropertyStatement
If Not IsChildOf(declaration, SyntaxKind.PropertyBlock) Then
Dim p = DirectCast(declaration, PropertyStatementSyntax)
Return p.ParameterList IsNot Nothing AndAlso p.ParameterList.Parameters.Count > 0 AndAlso p.Modifiers.Any(SyntaxKind.DefaultKeyword)
End If
End Select
Return False
End Function
Public Overrides Function GetName(declaration As SyntaxNode) As String
Select Case declaration.Kind
Case SyntaxKind.ClassBlock
Return DirectCast(declaration, ClassBlockSyntax).BlockStatement.Identifier.ValueText
Case SyntaxKind.StructureBlock
Return DirectCast(declaration, StructureBlockSyntax).BlockStatement.Identifier.ValueText
Case SyntaxKind.InterfaceBlock
Return DirectCast(declaration, InterfaceBlockSyntax).BlockStatement.Identifier.ValueText
Case SyntaxKind.EnumBlock
Return DirectCast(declaration, EnumBlockSyntax).EnumStatement.Identifier.ValueText
Case SyntaxKind.EnumMemberDeclaration
Return DirectCast(declaration, EnumMemberDeclarationSyntax).Identifier.ValueText
Case SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement
Return DirectCast(declaration, DelegateStatementSyntax).Identifier.ValueText
Case SyntaxKind.FunctionBlock,
SyntaxKind.SubBlock
Return DirectCast(declaration, MethodBlockSyntax).SubOrFunctionStatement.Identifier.ValueText
Case SyntaxKind.FunctionStatement,
SyntaxKind.SubStatement
Return DirectCast(declaration, MethodStatementSyntax).Identifier.ValueText
Case SyntaxKind.PropertyBlock
Return DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.Identifier.ValueText
Case SyntaxKind.PropertyStatement
Return DirectCast(declaration, PropertyStatementSyntax).Identifier.ValueText
Case SyntaxKind.EventBlock
Return DirectCast(declaration, EventBlockSyntax).EventStatement.Identifier.ValueText
Case SyntaxKind.EventStatement
Return DirectCast(declaration, EventStatementSyntax).Identifier.ValueText
Case SyntaxKind.EventStatement
Return DirectCast(declaration, EventStatementSyntax).Identifier.ValueText
Case SyntaxKind.Parameter
Return DirectCast(declaration, ParameterSyntax).Identifier.Identifier.ValueText
Case SyntaxKind.NamespaceBlock
Return DirectCast(declaration, NamespaceBlockSyntax).NamespaceStatement.Name.ToString()
Case SyntaxKind.FieldDeclaration
Dim fd = DirectCast(declaration, FieldDeclarationSyntax)
If GetDeclarationCount(fd) = 1 Then
Return fd.Declarators(0).Names(0).Identifier.ValueText
End If
Case SyntaxKind.LocalDeclarationStatement
Dim ld = DirectCast(declaration, LocalDeclarationStatementSyntax)
If GetDeclarationCount(ld) = 1 Then
Return ld.Declarators(0).Names(0).Identifier.ValueText
End If
Case SyntaxKind.VariableDeclarator
Dim vd = DirectCast(declaration, VariableDeclaratorSyntax)
If vd.Names.Count = 1 Then
Return vd.Names(0).Identifier.ValueText
End If
Case SyntaxKind.ModifiedIdentifier
Return DirectCast(declaration, ModifiedIdentifierSyntax).Identifier.ValueText
Case SyntaxKind.Attribute
Return DirectCast(declaration, AttributeSyntax).Name.ToString()
Case SyntaxKind.AttributeList
Dim list = DirectCast(declaration, AttributeListSyntax)
If list.Attributes.Count = 1 Then
Return list.Attributes(0).Name.ToString()
End If
Case SyntaxKind.ImportsStatement
Dim stmt = DirectCast(declaration, ImportsStatementSyntax)
If stmt.ImportsClauses.Count = 1 Then
Return GetName(stmt.ImportsClauses(0))
End If
Case SyntaxKind.SimpleImportsClause
Return DirectCast(declaration, SimpleImportsClauseSyntax).Name.ToString()
End Select
Return String.Empty
End Function
Public Overrides Function WithName(declaration As SyntaxNode, name As String) As SyntaxNode
Return Isolate(declaration, Function(d) WithNameInternal(d, name))
End Function
Private Function WithNameInternal(declaration As SyntaxNode, name As String) As SyntaxNode
Dim id = name.ToIdentifierToken()
Select Case declaration.Kind
Case SyntaxKind.ClassBlock
Return ReplaceWithTrivia(declaration, DirectCast(declaration, ClassBlockSyntax).BlockStatement.Identifier, id)
Case SyntaxKind.StructureBlock
Return ReplaceWithTrivia(declaration, DirectCast(declaration, StructureBlockSyntax).BlockStatement.Identifier, id)
Case SyntaxKind.InterfaceBlock
Return ReplaceWithTrivia(declaration, DirectCast(declaration, InterfaceBlockSyntax).BlockStatement.Identifier, id)
Case SyntaxKind.EnumBlock
Return ReplaceWithTrivia(declaration, DirectCast(declaration, EnumBlockSyntax).EnumStatement.Identifier, id)
Case SyntaxKind.EnumMemberDeclaration
Return ReplaceWithTrivia(declaration, DirectCast(declaration, EnumMemberDeclarationSyntax).Identifier, id)
Case SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement
Return ReplaceWithTrivia(declaration, DirectCast(declaration, DelegateStatementSyntax).Identifier, id)
Case SyntaxKind.FunctionBlock,
SyntaxKind.SubBlock
Return ReplaceWithTrivia(declaration, DirectCast(declaration, MethodBlockSyntax).SubOrFunctionStatement.Identifier, id)
Case SyntaxKind.FunctionStatement,
SyntaxKind.SubStatement
Return ReplaceWithTrivia(declaration, DirectCast(declaration, MethodStatementSyntax).Identifier, id)
Case SyntaxKind.PropertyBlock
Return ReplaceWithTrivia(declaration, DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.Identifier, id)
Case SyntaxKind.PropertyStatement
Return ReplaceWithTrivia(declaration, DirectCast(declaration, PropertyStatementSyntax).Identifier, id)
Case SyntaxKind.EventBlock
Return ReplaceWithTrivia(declaration, DirectCast(declaration, EventBlockSyntax).EventStatement.Identifier, id)
Case SyntaxKind.EventStatement
Return ReplaceWithTrivia(declaration, DirectCast(declaration, EventStatementSyntax).Identifier, id)
Case SyntaxKind.EventStatement
Return ReplaceWithTrivia(declaration, DirectCast(declaration, EventStatementSyntax).Identifier, id)
Case SyntaxKind.Parameter
Return ReplaceWithTrivia(declaration, DirectCast(declaration, ParameterSyntax).Identifier.Identifier, id)
Case SyntaxKind.NamespaceBlock
Return ReplaceWithTrivia(declaration, DirectCast(declaration, NamespaceBlockSyntax).NamespaceStatement.Name, Me.DottedName(name))
Case SyntaxKind.LocalDeclarationStatement
Dim ld = DirectCast(declaration, LocalDeclarationStatementSyntax)
If ld.Declarators.Count = 1 AndAlso ld.Declarators(0).Names.Count = 1 Then
Return ReplaceWithTrivia(declaration, ld.Declarators(0).Names(0).Identifier, id)
End If
Case SyntaxKind.FieldDeclaration
Dim fd = DirectCast(declaration, FieldDeclarationSyntax)
If fd.Declarators.Count = 1 AndAlso fd.Declarators(0).Names.Count = 1 Then
Return ReplaceWithTrivia(declaration, fd.Declarators(0).Names(0).Identifier, id)
End If
Case SyntaxKind.Attribute
Return ReplaceWithTrivia(declaration, DirectCast(declaration, AttributeSyntax).Name, Me.DottedName(name))
Case SyntaxKind.AttributeList
Dim al = DirectCast(declaration, AttributeListSyntax)
If al.Attributes.Count = 1 Then
Return ReplaceWithTrivia(declaration, al.Attributes(0).Name, Me.DottedName(name))
End If
Case SyntaxKind.ImportsStatement
Dim stmt = DirectCast(declaration, ImportsStatementSyntax)
If stmt.ImportsClauses.Count = 1 Then
Dim clause = stmt.ImportsClauses(0)
Select Case clause.Kind
Case SyntaxKind.SimpleImportsClause
Return ReplaceWithTrivia(declaration, DirectCast(clause, SimpleImportsClauseSyntax).Name, Me.DottedName(name))
End Select
End If
End Select
Return declaration
End Function
Public Overrides Function [GetType](declaration As SyntaxNode) As SyntaxNode
Select Case declaration.Kind
Case SyntaxKind.ModifiedIdentifier
Dim vd = TryCast(declaration.Parent, VariableDeclaratorSyntax)
If vd IsNot Nothing Then
Return [GetType](vd)
End If
Case Else
Dim asClause = GetAsClause(declaration)
If asClause IsNot Nothing Then
Return asClause.Type
End If
End Select
Return Nothing
End Function
Public Overrides Function WithType(declaration As SyntaxNode, type As SyntaxNode) As SyntaxNode
Return Isolate(declaration, Function(d) WithTypeInternal(d, type))
End Function
Private Function WithTypeInternal(declaration As SyntaxNode, type As SyntaxNode) As SyntaxNode
If type Is Nothing Then
declaration = AsSub(declaration)
Else
declaration = AsFunction(declaration)
End If
Dim asClause = GetAsClause(declaration)
If asClause IsNot Nothing Then
If type IsNot Nothing Then
Select Case asClause.Kind
Case SyntaxKind.SimpleAsClause
asClause = DirectCast(asClause, SimpleAsClauseSyntax).WithType(DirectCast(type, TypeSyntax))
Case SyntaxKind.AsNewClause
Dim asNew = DirectCast(asClause, AsNewClauseSyntax)
Select Case asNew.NewExpression.Kind
Case SyntaxKind.ObjectCreationExpression
asClause = asNew.WithNewExpression(DirectCast(asNew.NewExpression, ObjectCreationExpressionSyntax).WithType(DirectCast(type, TypeSyntax)))
Case SyntaxKind.ArrayCreationExpression
asClause = asNew.WithNewExpression(DirectCast(asNew.NewExpression, ArrayCreationExpressionSyntax).WithType(DirectCast(type, TypeSyntax)))
End Select
End Select
Else
asClause = Nothing
End If
ElseIf type IsNot Nothing Then
asClause = SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax))
End If
Return WithAsClause(declaration, asClause)
End Function
Private Function GetAsClause(declaration As SyntaxNode) As AsClauseSyntax
Select Case declaration.Kind
Case SyntaxKind.DelegateFunctionStatement
Return DirectCast(declaration, DelegateStatementSyntax).AsClause
Case SyntaxKind.FunctionBlock
Return DirectCast(declaration, MethodBlockSyntax).SubOrFunctionStatement.AsClause
Case SyntaxKind.FunctionStatement
Return DirectCast(declaration, MethodStatementSyntax).AsClause
Case SyntaxKind.PropertyBlock
Return DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.AsClause
Case SyntaxKind.PropertyStatement
Return DirectCast(declaration, PropertyStatementSyntax).AsClause
Case SyntaxKind.EventBlock
Return DirectCast(declaration, EventBlockSyntax).EventStatement.AsClause
Case SyntaxKind.EventStatement
Return DirectCast(declaration, EventStatementSyntax).AsClause
Case SyntaxKind.Parameter
Return DirectCast(declaration, ParameterSyntax).AsClause
Case SyntaxKind.FieldDeclaration
Dim fd = DirectCast(declaration, FieldDeclarationSyntax)
If fd.Declarators.Count = 1 Then
Return fd.Declarators(0).AsClause
End If
Case SyntaxKind.LocalDeclarationStatement
Dim ld = DirectCast(declaration, LocalDeclarationStatementSyntax)
If ld.Declarators.Count = 1 Then
Return ld.Declarators(0).AsClause
End If
Case SyntaxKind.VariableDeclarator
Return DirectCast(declaration, VariableDeclaratorSyntax).AsClause
Case SyntaxKind.ModifiedIdentifier
Dim vd = TryCast(declaration.Parent, VariableDeclaratorSyntax)
If vd IsNot Nothing Then
Return vd.AsClause
End If
End Select
Return Nothing
End Function
Private Function WithAsClause(declaration As SyntaxNode, asClause As AsClauseSyntax) As SyntaxNode
Select Case declaration.Kind
Case SyntaxKind.DelegateFunctionStatement
Return DirectCast(declaration, DelegateStatementSyntax).WithAsClause(DirectCast(asClause, SimpleAsClauseSyntax))
Case SyntaxKind.FieldDeclaration
Dim fd = DirectCast(declaration, FieldDeclarationSyntax)
If fd.Declarators.Count = 1 Then
Return ReplaceWithTrivia(declaration, fd.Declarators(0), fd.Declarators(0).WithAsClause(asClause))
End If
Case SyntaxKind.FunctionBlock
Return DirectCast(declaration, MethodBlockSyntax).WithSubOrFunctionStatement(DirectCast(declaration, MethodBlockSyntax).SubOrFunctionStatement.WithAsClause(DirectCast(asClause, SimpleAsClauseSyntax)))
Case SyntaxKind.FunctionStatement
Return DirectCast(declaration, MethodStatementSyntax).WithAsClause(DirectCast(asClause, SimpleAsClauseSyntax))
Case SyntaxKind.PropertyBlock
Return DirectCast(declaration, PropertyBlockSyntax).WithPropertyStatement(DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.WithAsClause(asClause))
Case SyntaxKind.PropertyStatement
Return DirectCast(declaration, PropertyStatementSyntax).WithAsClause(asClause)
Case SyntaxKind.EventBlock
Return DirectCast(declaration, EventBlockSyntax).WithEventStatement(DirectCast(declaration, EventBlockSyntax).EventStatement.WithAsClause(DirectCast(asClause, SimpleAsClauseSyntax)))
Case SyntaxKind.EventStatement
Return DirectCast(declaration, EventStatementSyntax).WithAsClause(DirectCast(asClause, SimpleAsClauseSyntax))
Case SyntaxKind.Parameter
Return DirectCast(declaration, ParameterSyntax).WithAsClause(DirectCast(asClause, SimpleAsClauseSyntax))
Case SyntaxKind.LocalDeclarationStatement
Dim ld = DirectCast(declaration, LocalDeclarationStatementSyntax)
If ld.Declarators.Count = 1 Then
Return ReplaceWithTrivia(declaration, ld.Declarators(0), ld.Declarators(0).WithAsClause(asClause))
End If
Case SyntaxKind.VariableDeclarator
Return DirectCast(declaration, VariableDeclaratorSyntax).WithAsClause(asClause)
End Select
Return declaration
End Function
Private Function AsFunction(declaration As SyntaxNode) As SyntaxNode
Return Isolate(declaration, AddressOf AsFunctionInternal)
End Function
Private Function AsFunctionInternal(declaration As SyntaxNode) As SyntaxNode
Select Case declaration.Kind
Case SyntaxKind.SubBlock
Dim sb = DirectCast(declaration, MethodBlockSyntax)
Return SyntaxFactory.MethodBlock(
SyntaxKind.FunctionBlock,
DirectCast(AsFunction(sb.BlockStatement), MethodStatementSyntax),
sb.Statements,
SyntaxFactory.EndBlockStatement(
SyntaxKind.EndFunctionStatement,
sb.EndBlockStatement.EndKeyword,
SyntaxFactory.Token(sb.EndBlockStatement.BlockKeyword.LeadingTrivia, SyntaxKind.FunctionKeyword, sb.EndBlockStatement.BlockKeyword.TrailingTrivia)
))
Case SyntaxKind.SubStatement
Dim ss = DirectCast(declaration, MethodStatementSyntax)
Return SyntaxFactory.MethodStatement(
SyntaxKind.FunctionStatement,
ss.AttributeLists,
ss.Modifiers,
SyntaxFactory.Token(ss.DeclarationKeyword.LeadingTrivia, SyntaxKind.FunctionKeyword, ss.DeclarationKeyword.TrailingTrivia),
ss.Identifier,
ss.TypeParameterList,
ss.ParameterList,
SyntaxFactory.SimpleAsClause(SyntaxFactory.IdentifierName("Object")),
ss.HandlesClause,
ss.ImplementsClause)
Case SyntaxKind.DelegateSubStatement
Dim ds = DirectCast(declaration, DelegateStatementSyntax)
Return SyntaxFactory.DelegateStatement(
SyntaxKind.DelegateFunctionStatement,
ds.AttributeLists,
ds.Modifiers,
SyntaxFactory.Token(ds.DeclarationKeyword.LeadingTrivia, SyntaxKind.FunctionKeyword, ds.DeclarationKeyword.TrailingTrivia),
ds.Identifier,
ds.TypeParameterList,
ds.ParameterList,
SyntaxFactory.SimpleAsClause(SyntaxFactory.IdentifierName("Object")))
Case SyntaxKind.MultiLineSubLambdaExpression
Dim ml = DirectCast(declaration, MultiLineLambdaExpressionSyntax)
Return SyntaxFactory.MultiLineLambdaExpression(
SyntaxKind.MultiLineFunctionLambdaExpression,
DirectCast(AsFunction(ml.SubOrFunctionHeader), LambdaHeaderSyntax),
ml.Statements,
SyntaxFactory.EndBlockStatement(
SyntaxKind.EndFunctionStatement,
ml.EndSubOrFunctionStatement.EndKeyword,
SyntaxFactory.Token(ml.EndSubOrFunctionStatement.BlockKeyword.LeadingTrivia, SyntaxKind.FunctionKeyword, ml.EndSubOrFunctionStatement.BlockKeyword.TrailingTrivia)
))
Case SyntaxKind.SingleLineSubLambdaExpression
Dim sl = DirectCast(declaration, SingleLineLambdaExpressionSyntax)
Return SyntaxFactory.SingleLineLambdaExpression(
SyntaxKind.SingleLineFunctionLambdaExpression,
DirectCast(AsFunction(sl.SubOrFunctionHeader), LambdaHeaderSyntax),
sl.Body)
Case SyntaxKind.SubLambdaHeader
Dim lh = DirectCast(declaration, LambdaHeaderSyntax)
Return SyntaxFactory.LambdaHeader(
SyntaxKind.FunctionLambdaHeader,
lh.AttributeLists,
lh.Modifiers,
SyntaxFactory.Token(lh.DeclarationKeyword.LeadingTrivia, SyntaxKind.FunctionKeyword, lh.DeclarationKeyword.TrailingTrivia),
lh.ParameterList,
asClause:=Nothing)
Case SyntaxKind.DeclareSubStatement
Dim ds = DirectCast(declaration, DeclareStatementSyntax)
Return SyntaxFactory.DeclareStatement(
SyntaxKind.DeclareFunctionStatement,
ds.AttributeLists,
ds.Modifiers,
ds.CharsetKeyword,
SyntaxFactory.Token(ds.DeclarationKeyword.LeadingTrivia, SyntaxKind.FunctionKeyword, ds.DeclarationKeyword.TrailingTrivia),
ds.Identifier,
ds.LibraryName,
ds.AliasName,
ds.ParameterList,
SyntaxFactory.SimpleAsClause(SyntaxFactory.IdentifierName("Object")))
Case Else
Return declaration
End Select
End Function
Private Function AsSub(declaration As SyntaxNode) As SyntaxNode
Return Isolate(declaration, AddressOf AsSubInternal)
End Function
Private Function AsSubInternal(declaration As SyntaxNode) As SyntaxNode
Select Case declaration.Kind
Case SyntaxKind.FunctionBlock
Dim mb = DirectCast(declaration, MethodBlockSyntax)
Return SyntaxFactory.MethodBlock(
SyntaxKind.SubBlock,
DirectCast(AsSub(mb.BlockStatement), MethodStatementSyntax),
mb.Statements,
SyntaxFactory.EndBlockStatement(
SyntaxKind.EndSubStatement,
mb.EndBlockStatement.EndKeyword,
SyntaxFactory.Token(mb.EndBlockStatement.BlockKeyword.LeadingTrivia, SyntaxKind.SubKeyword, mb.EndBlockStatement.BlockKeyword.TrailingTrivia)
))
Case SyntaxKind.FunctionStatement
Dim ms = DirectCast(declaration, MethodStatementSyntax)
Return SyntaxFactory.MethodStatement(
SyntaxKind.SubStatement,
ms.AttributeLists,
ms.Modifiers,
SyntaxFactory.Token(ms.DeclarationKeyword.LeadingTrivia, SyntaxKind.SubKeyword, ms.DeclarationKeyword.TrailingTrivia),
ms.Identifier,
ms.TypeParameterList,
ms.ParameterList,
asClause:=Nothing,
handlesClause:=ms.HandlesClause,
implementsClause:=ms.ImplementsClause)
Case SyntaxKind.DelegateFunctionStatement
Dim ds = DirectCast(declaration, DelegateStatementSyntax)
Return SyntaxFactory.DelegateStatement(
SyntaxKind.DelegateSubStatement,
ds.AttributeLists,
ds.Modifiers,
SyntaxFactory.Token(ds.DeclarationKeyword.LeadingTrivia, SyntaxKind.SubKeyword, ds.DeclarationKeyword.TrailingTrivia),
ds.Identifier,
ds.TypeParameterList,
ds.ParameterList,
asClause:=Nothing)
Case SyntaxKind.MultiLineFunctionLambdaExpression
Dim ml = DirectCast(declaration, MultiLineLambdaExpressionSyntax)
Return SyntaxFactory.MultiLineLambdaExpression(
SyntaxKind.MultiLineSubLambdaExpression,
DirectCast(AsSub(ml.SubOrFunctionHeader), LambdaHeaderSyntax),
ml.Statements,
SyntaxFactory.EndBlockStatement(
SyntaxKind.EndSubStatement,
ml.EndSubOrFunctionStatement.EndKeyword,
SyntaxFactory.Token(ml.EndSubOrFunctionStatement.BlockKeyword.LeadingTrivia, SyntaxKind.SubKeyword, ml.EndSubOrFunctionStatement.BlockKeyword.TrailingTrivia)
))
Case SyntaxKind.SingleLineFunctionLambdaExpression
Dim sl = DirectCast(declaration, SingleLineLambdaExpressionSyntax)
Return SyntaxFactory.SingleLineLambdaExpression(
SyntaxKind.SingleLineSubLambdaExpression,
DirectCast(AsSub(sl.SubOrFunctionHeader), LambdaHeaderSyntax),
sl.Body)
Case SyntaxKind.FunctionLambdaHeader
Dim lh = DirectCast(declaration, LambdaHeaderSyntax)
Return SyntaxFactory.LambdaHeader(
SyntaxKind.SubLambdaHeader,
lh.AttributeLists,
lh.Modifiers,
SyntaxFactory.Token(lh.DeclarationKeyword.LeadingTrivia, SyntaxKind.SubKeyword, lh.DeclarationKeyword.TrailingTrivia),
lh.ParameterList,
asClause:=Nothing)
Case SyntaxKind.DeclareFunctionStatement
Dim ds = DirectCast(declaration, DeclareStatementSyntax)
Return SyntaxFactory.DeclareStatement(
SyntaxKind.DeclareSubStatement,
ds.AttributeLists,
ds.Modifiers,
ds.CharsetKeyword,
SyntaxFactory.Token(ds.DeclarationKeyword.LeadingTrivia, SyntaxKind.SubKeyword, ds.DeclarationKeyword.TrailingTrivia),
ds.Identifier,
ds.LibraryName,
ds.AliasName,
ds.ParameterList,
asClause:=Nothing)
Case Else
Return declaration
End Select
End Function
Public Overrides Function GetModifiers(declaration As SyntaxNode) As DeclarationModifiers
Dim tokens = GetModifierTokens(declaration)
Dim acc As Accessibility
Dim mods As DeclarationModifiers
Dim isDefault As Boolean
GetAccessibilityAndModifiers(tokens, acc, mods, isDefault)
Return mods
End Function
Public Overrides Function WithModifiers(declaration As SyntaxNode, modifiers As DeclarationModifiers) As SyntaxNode
Return Isolate(declaration, Function(d) Me.WithModifiersInternal(d, modifiers))
End Function
Private Function WithModifiersInternal(declaration As SyntaxNode, modifiers As DeclarationModifiers) As SyntaxNode
Dim tokens = GetModifierTokens(declaration)
Dim acc As Accessibility
Dim currentMods As DeclarationModifiers
Dim isDefault As Boolean
GetAccessibilityAndModifiers(tokens, acc, currentMods, isDefault)
If (currentMods <> modifiers) Then
Dim newTokens = GetModifierList(acc, modifiers And GetAllowedModifiers(declaration.Kind), GetDeclarationKind(declaration), isDefault)
Return WithModifierTokens(declaration, Merge(tokens, newTokens))
Else
Return declaration
End If
End Function
Private Function GetModifierTokens(declaration As SyntaxNode) As SyntaxTokenList
Select Case declaration.Kind
Case SyntaxKind.ClassBlock
Return DirectCast(declaration, ClassBlockSyntax).BlockStatement.Modifiers
Case SyntaxKind.ClassStatement
Return DirectCast(declaration, ClassStatementSyntax).Modifiers
Case SyntaxKind.StructureBlock
Return DirectCast(declaration, StructureBlockSyntax).BlockStatement.Modifiers
Case SyntaxKind.StructureStatement
Return DirectCast(declaration, StructureStatementSyntax).Modifiers
Case SyntaxKind.InterfaceBlock
Return DirectCast(declaration, InterfaceBlockSyntax).BlockStatement.Modifiers
Case SyntaxKind.InterfaceStatement
Return DirectCast(declaration, InterfaceStatementSyntax).Modifiers
Case SyntaxKind.EnumBlock
Return DirectCast(declaration, EnumBlockSyntax).EnumStatement.Modifiers
Case SyntaxKind.EnumStatement
Return DirectCast(declaration, EnumStatementSyntax).Modifiers
Case SyntaxKind.ModuleBlock
Return DirectCast(declaration, ModuleBlockSyntax).ModuleStatement.Modifiers
Case SyntaxKind.ModuleStatement
Return DirectCast(declaration, ModuleStatementSyntax).Modifiers
Case SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement
Return DirectCast(declaration, DelegateStatementSyntax).Modifiers
Case SyntaxKind.FieldDeclaration
Return DirectCast(declaration, FieldDeclarationSyntax).Modifiers
Case SyntaxKind.FunctionBlock,
SyntaxKind.SubBlock
Return DirectCast(declaration, MethodBlockSyntax).BlockStatement.Modifiers
Case SyntaxKind.ConstructorBlock
Return DirectCast(declaration, ConstructorBlockSyntax).BlockStatement.Modifiers
Case SyntaxKind.FunctionStatement,
SyntaxKind.SubStatement
Return DirectCast(declaration, MethodStatementSyntax).Modifiers
Case SyntaxKind.SubNewStatement
Return DirectCast(declaration, SubNewStatementSyntax).Modifiers
Case SyntaxKind.PropertyBlock
Return DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.Modifiers
Case SyntaxKind.PropertyStatement
Return DirectCast(declaration, PropertyStatementSyntax).Modifiers
Case SyntaxKind.OperatorBlock
Return DirectCast(declaration, OperatorBlockSyntax).BlockStatement.Modifiers
Case SyntaxKind.OperatorStatement
Return DirectCast(declaration, OperatorStatementSyntax).Modifiers
Case SyntaxKind.EventBlock
Return DirectCast(declaration, EventBlockSyntax).EventStatement.Modifiers
Case SyntaxKind.EventStatement
Return DirectCast(declaration, EventStatementSyntax).Modifiers
Case SyntaxKind.ModifiedIdentifier
If IsChildOf(declaration, SyntaxKind.VariableDeclarator) Then
Return GetModifierTokens(declaration.Parent)
End If
Case SyntaxKind.VariableDeclarator
If IsChildOfVariableDeclaration(declaration) Then
Return GetModifierTokens(declaration.Parent)
End If
Case SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock
Return GetModifierTokens(DirectCast(declaration, AccessorBlockSyntax).AccessorStatement)
Case SyntaxKind.GetAccessorStatement,
SyntaxKind.SetAccessorStatement,
SyntaxKind.AddHandlerAccessorStatement,
SyntaxKind.RemoveHandlerAccessorStatement,
SyntaxKind.RaiseEventAccessorStatement
Return DirectCast(declaration, AccessorStatementSyntax).Modifiers
Case Else
Return Nothing
End Select
End Function
Private Function WithModifierTokens(declaration As SyntaxNode, tokens As SyntaxTokenList) As SyntaxNode
Select Case declaration.Kind
Case SyntaxKind.ClassBlock
Return DirectCast(declaration, ClassBlockSyntax).WithClassStatement(DirectCast(declaration, ClassBlockSyntax).ClassStatement.WithModifiers(tokens))
Case SyntaxKind.ClassStatement
Return DirectCast(declaration, ClassStatementSyntax).WithModifiers(tokens)
Case SyntaxKind.StructureBlock
Return DirectCast(declaration, StructureBlockSyntax).WithStructureStatement(DirectCast(declaration, StructureBlockSyntax).StructureStatement.WithModifiers(tokens))
Case SyntaxKind.StructureStatement
Return DirectCast(declaration, StructureStatementSyntax).WithModifiers(tokens)
Case SyntaxKind.InterfaceBlock
Return DirectCast(declaration, InterfaceBlockSyntax).WithInterfaceStatement(DirectCast(declaration, InterfaceBlockSyntax).InterfaceStatement.WithModifiers(tokens))
Case SyntaxKind.InterfaceStatement
Return DirectCast(declaration, InterfaceStatementSyntax).WithModifiers(tokens)
Case SyntaxKind.EnumBlock
Return DirectCast(declaration, EnumBlockSyntax).WithEnumStatement(DirectCast(declaration, EnumBlockSyntax).EnumStatement.WithModifiers(tokens))
Case SyntaxKind.EnumStatement
Return DirectCast(declaration, EnumStatementSyntax).WithModifiers(tokens)
Case SyntaxKind.ModuleBlock
Return DirectCast(declaration, ModuleBlockSyntax).WithModuleStatement(DirectCast(declaration, ModuleBlockSyntax).ModuleStatement.WithModifiers(tokens))
Case SyntaxKind.ModuleStatement
Return DirectCast(declaration, ModuleStatementSyntax).WithModifiers(tokens)
Case SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement
Return DirectCast(declaration, DelegateStatementSyntax).WithModifiers(tokens)
Case SyntaxKind.FieldDeclaration
Return DirectCast(declaration, FieldDeclarationSyntax).WithModifiers(tokens)
Case SyntaxKind.FunctionBlock,
SyntaxKind.SubBlock
Return DirectCast(declaration, MethodBlockSyntax).WithSubOrFunctionStatement(DirectCast(declaration, MethodBlockSyntax).SubOrFunctionStatement.WithModifiers(tokens))
Case SyntaxKind.ConstructorBlock
Return DirectCast(declaration, ConstructorBlockSyntax).WithSubNewStatement(DirectCast(declaration, ConstructorBlockSyntax).SubNewStatement.WithModifiers(tokens))
Case SyntaxKind.FunctionStatement,
SyntaxKind.SubStatement
Return DirectCast(declaration, MethodStatementSyntax).WithModifiers(tokens)
Case SyntaxKind.SubNewStatement
Return DirectCast(declaration, SubNewStatementSyntax).WithModifiers(tokens)
Case SyntaxKind.PropertyBlock
Return DirectCast(declaration, PropertyBlockSyntax).WithPropertyStatement(DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.WithModifiers(tokens))
Case SyntaxKind.PropertyStatement
Return DirectCast(declaration, PropertyStatementSyntax).WithModifiers(tokens)
Case SyntaxKind.OperatorBlock
Return DirectCast(declaration, OperatorBlockSyntax).WithOperatorStatement(DirectCast(declaration, OperatorBlockSyntax).OperatorStatement.WithModifiers(tokens))
Case SyntaxKind.OperatorStatement
Return DirectCast(declaration, OperatorStatementSyntax).WithModifiers(tokens)
Case SyntaxKind.EventBlock
Return DirectCast(declaration, EventBlockSyntax).WithEventStatement(DirectCast(declaration, EventBlockSyntax).EventStatement.WithModifiers(tokens))
Case SyntaxKind.EventStatement
Return DirectCast(declaration, EventStatementSyntax).WithModifiers(tokens)
Case SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock
Return DirectCast(declaration, AccessorBlockSyntax).WithAccessorStatement(
DirectCast(Me.WithModifierTokens(DirectCast(declaration, AccessorBlockSyntax).AccessorStatement, tokens), AccessorStatementSyntax))
Case SyntaxKind.GetAccessorStatement,
SyntaxKind.SetAccessorStatement,
SyntaxKind.AddHandlerAccessorStatement,
SyntaxKind.RemoveHandlerAccessorStatement,
SyntaxKind.RaiseEventAccessorStatement
Return DirectCast(declaration, AccessorStatementSyntax).WithModifiers(tokens)
Case Else
Return declaration
End Select
End Function
Public Overrides Function GetAccessibility(declaration As SyntaxNode) As Accessibility
If Not CanHaveAccessibility(declaration) Then
Return Accessibility.NotApplicable
End If
Dim tokens = GetModifierTokens(declaration)
Dim acc As Accessibility
Dim mods As DeclarationModifiers
Dim isDefault As Boolean
GetAccessibilityAndModifiers(tokens, acc, mods, isDefault)
Return acc
End Function
Public Overrides Function WithAccessibility(declaration As SyntaxNode, accessibility As Accessibility) As SyntaxNode
If Not CanHaveAccessibility(declaration) AndAlso
accessibility <> accessibility.NotApplicable Then
Return declaration
End If
Return Isolate(declaration, Function(d) Me.WithAccessibilityInternal(d, accessibility))
End Function
Private Function WithAccessibilityInternal(declaration As SyntaxNode, accessibility As Accessibility) As SyntaxNode
If Not CanHaveAccessibility(declaration) Then
Return declaration
End If
Dim tokens = GetModifierTokens(declaration)
Dim currentAcc As Accessibility
Dim mods As DeclarationModifiers
Dim isDefault As Boolean
GetAccessibilityAndModifiers(tokens, currentAcc, mods, isDefault)
If currentAcc = accessibility Then
Return declaration
End If
Dim newTokens = GetModifierList(accessibility, mods, GetDeclarationKind(declaration), isDefault)
'GetDeclarationKind returns None for Field if the count is > 1
'To handle multiple declarations on a field if the Accessibility is NotApplicable, we need to add the Dim
If declaration.Kind = SyntaxKind.FieldDeclaration AndAlso accessibility = accessibility.NotApplicable AndAlso newTokens.Count = 0 Then
' Add the Dim
newTokens = newTokens.Add(SyntaxFactory.Token(SyntaxKind.DimKeyword))
End If
Return WithModifierTokens(declaration, Merge(tokens, newTokens))
End Function
Friend Overrides Function CanHaveAccessibility(declaration As SyntaxNode) As Boolean
Select Case declaration.Kind
Case SyntaxKind.ClassBlock,
SyntaxKind.ClassStatement,
SyntaxKind.StructureBlock,
SyntaxKind.StructureStatement,
SyntaxKind.InterfaceBlock,
SyntaxKind.InterfaceStatement,
SyntaxKind.EnumBlock,
SyntaxKind.EnumStatement,
SyntaxKind.ModuleBlock,
SyntaxKind.ModuleStatement,
SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement,
SyntaxKind.FieldDeclaration,
SyntaxKind.FunctionBlock,
SyntaxKind.SubBlock,
SyntaxKind.FunctionStatement,
SyntaxKind.SubStatement,
SyntaxKind.PropertyBlock,
SyntaxKind.PropertyStatement,
SyntaxKind.OperatorBlock,
SyntaxKind.OperatorStatement,
SyntaxKind.EventBlock,
SyntaxKind.EventStatement,
SyntaxKind.GetAccessorBlock,
SyntaxKind.GetAccessorStatement,
SyntaxKind.SetAccessorBlock,
SyntaxKind.SetAccessorStatement,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.AddHandlerAccessorStatement,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorStatement,
SyntaxKind.RaiseEventAccessorBlock,
SyntaxKind.RaiseEventAccessorStatement
Return True
Case SyntaxKind.ConstructorBlock,
SyntaxKind.SubNewStatement
' Shared constructor cannot have modifiers in VB.
Return Not declaration.GetModifiers().Any(SyntaxKind.SharedKeyword)
Case SyntaxKind.ModifiedIdentifier
Return If(IsChildOf(declaration, SyntaxKind.VariableDeclarator),
CanHaveAccessibility(declaration.Parent),
False)
Case SyntaxKind.VariableDeclarator
Return If(IsChildOfVariableDeclaration(declaration),
CanHaveAccessibility(declaration.Parent),
False)
Case Else
Return False
End Select
End Function
Private Function GetModifierList(accessibility As Accessibility, modifiers As DeclarationModifiers, kind As DeclarationKind, Optional isDefault As Boolean = False) As SyntaxTokenList
Dim _list = SyntaxFactory.TokenList()
' While partial must always be last in C#, its preferred position in VB is to be first,
' even before accessibility modifiers. This order is enforced by line commit.
If modifiers.IsPartial Then
_list = _list.Add(SyntaxFactory.Token(SyntaxKind.PartialKeyword))
End If
If isDefault Then
_list = _list.Add(SyntaxFactory.Token(SyntaxKind.DefaultKeyword))
End If
Select Case (accessibility)
Case accessibility.Internal
_list = _list.Add(SyntaxFactory.Token(SyntaxKind.FriendKeyword))
Case accessibility.Public
_list = _list.Add(SyntaxFactory.Token(SyntaxKind.PublicKeyword))
Case accessibility.Private
_list = _list.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword))
Case accessibility.Protected
_list = _list.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword))
Case accessibility.ProtectedOrInternal
_list = _list.Add(SyntaxFactory.Token(SyntaxKind.FriendKeyword)).Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword))
Case accessibility.ProtectedAndInternal
_list = _list.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)).Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword))
Case accessibility.NotApplicable
Case Else
Throw New NotSupportedException(String.Format("Accessibility '{0}' not supported.", accessibility))
End Select
If modifiers.IsAbstract Then
If kind = DeclarationKind.Class Then
_list = _list.Add(SyntaxFactory.Token(SyntaxKind.MustInheritKeyword))
Else
_list = _list.Add(SyntaxFactory.Token(SyntaxKind.MustOverrideKeyword))
End If
End If
If modifiers.IsNew Then
_list = _list.Add(SyntaxFactory.Token(SyntaxKind.ShadowsKeyword))
End If
If modifiers.IsSealed Then
If kind = DeclarationKind.Class Then
_list = _list.Add(SyntaxFactory.Token(SyntaxKind.NotInheritableKeyword))
Else
_list = _list.Add(SyntaxFactory.Token(SyntaxKind.NotOverridableKeyword))
End If
End If
If modifiers.IsOverride Then
_list = _list.Add(SyntaxFactory.Token(SyntaxKind.OverridesKeyword))
End If
If modifiers.IsVirtual Then
_list = _list.Add(SyntaxFactory.Token(SyntaxKind.OverridableKeyword))
End If
If modifiers.IsStatic Then
_list = _list.Add(SyntaxFactory.Token(SyntaxKind.SharedKeyword))
End If
If modifiers.IsAsync Then
_list = _list.Add(SyntaxFactory.Token(SyntaxKind.AsyncKeyword))
End If
If modifiers.IsConst Then
_list = _list.Add(SyntaxFactory.Token(SyntaxKind.ConstKeyword))
End If
If modifiers.IsReadOnly Then
_list = _list.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword))
End If
If modifiers.IsWriteOnly Then
_list = _list.Add(SyntaxFactory.Token(SyntaxKind.WriteOnlyKeyword))
End If
If modifiers.IsUnsafe Then
Throw New NotSupportedException("Unsupported modifier")
''''_list = _list.Add(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword))
End If
If modifiers.IsWithEvents Then
_list = _list.Add(SyntaxFactory.Token(SyntaxKind.WithEventsKeyword))
End If
If (kind = DeclarationKind.Field AndAlso _list.Count = 0) Then
_list = _list.Add(SyntaxFactory.Token(SyntaxKind.DimKeyword))
End If
Return _list
End Function
Private Sub GetAccessibilityAndModifiers(modifierTokens As SyntaxTokenList, ByRef accessibility As Accessibility, ByRef modifiers As DeclarationModifiers, ByRef isDefault As Boolean)
accessibility = accessibility.NotApplicable
modifiers = DeclarationModifiers.None
isDefault = False
For Each token In modifierTokens
Select Case token.Kind
Case SyntaxKind.DefaultKeyword
isDefault = True
Case SyntaxKind.PublicKeyword
accessibility = accessibility.Public
Case SyntaxKind.PrivateKeyword
If accessibility = accessibility.Protected Then
accessibility = accessibility.ProtectedAndFriend
Else
accessibility = accessibility.Private
End If
Case SyntaxKind.FriendKeyword
If accessibility = accessibility.Protected Then
accessibility = accessibility.ProtectedOrFriend
Else
accessibility = accessibility.Friend
End If
Case SyntaxKind.ProtectedKeyword
If accessibility = accessibility.Friend Then
accessibility = accessibility.ProtectedOrFriend
ElseIf accessibility = accessibility.Private Then
accessibility = accessibility.ProtectedAndFriend
Else
accessibility = accessibility.Protected
End If
Case SyntaxKind.MustInheritKeyword, SyntaxKind.MustOverrideKeyword
modifiers = modifiers Or DeclarationModifiers.Abstract
Case SyntaxKind.ShadowsKeyword
modifiers = modifiers Or DeclarationModifiers.[New]
Case SyntaxKind.OverridesKeyword
modifiers = modifiers Or DeclarationModifiers.Override
Case SyntaxKind.OverridableKeyword
modifiers = modifiers Or DeclarationModifiers.Virtual
Case SyntaxKind.SharedKeyword
modifiers = modifiers Or DeclarationModifiers.Static
Case SyntaxKind.AsyncKeyword
modifiers = modifiers Or DeclarationModifiers.Async
Case SyntaxKind.ConstKeyword
modifiers = modifiers Or DeclarationModifiers.Const
Case SyntaxKind.ReadOnlyKeyword
modifiers = modifiers Or DeclarationModifiers.ReadOnly
Case SyntaxKind.WriteOnlyKeyword
modifiers = modifiers Or DeclarationModifiers.WriteOnly
Case SyntaxKind.NotInheritableKeyword, SyntaxKind.NotOverridableKeyword
modifiers = modifiers Or DeclarationModifiers.Sealed
Case SyntaxKind.WithEventsKeyword
modifiers = modifiers Or DeclarationModifiers.WithEvents
Case SyntaxKind.PartialKeyword
modifiers = modifiers Or DeclarationModifiers.Partial
End Select
Next
End Sub
Private Function GetTypeParameters(typeParameterNames As IEnumerable(Of String)) As TypeParameterListSyntax
If typeParameterNames Is Nothing Then
Return Nothing
End If
Dim typeParameterList = SyntaxFactory.TypeParameterList(SyntaxFactory.SeparatedList(typeParameterNames.Select(Function(name) SyntaxFactory.TypeParameter(name))))
If typeParameterList.Parameters.Count = 0 Then
typeParameterList = Nothing
End If
Return typeParameterList
End Function
Public Overrides Function WithTypeParameters(declaration As SyntaxNode, typeParameterNames As IEnumerable(Of String)) As SyntaxNode
Dim typeParameterList = GetTypeParameters(typeParameterNames)
Return ReplaceTypeParameterList(declaration, Function(old) typeParameterList)
End Function
Private Function ReplaceTypeParameterList(declaration As SyntaxNode, replacer As Func(Of TypeParameterListSyntax, TypeParameterListSyntax)) As SyntaxNode
Dim method = TryCast(declaration, MethodStatementSyntax)
If method IsNot Nothing Then
Return method.WithTypeParameterList(replacer(method.TypeParameterList))
End If
Dim methodBlock = TryCast(declaration, MethodBlockSyntax)
If methodBlock IsNot Nothing Then
Return methodBlock.WithSubOrFunctionStatement(methodBlock.SubOrFunctionStatement.WithTypeParameterList(replacer(methodBlock.SubOrFunctionStatement.TypeParameterList)))
End If
Dim classBlock = TryCast(declaration, ClassBlockSyntax)
If classBlock IsNot Nothing Then
Return classBlock.WithClassStatement(classBlock.ClassStatement.WithTypeParameterList(replacer(classBlock.ClassStatement.TypeParameterList)))
End If
Dim structureBlock = TryCast(declaration, StructureBlockSyntax)
If structureBlock IsNot Nothing Then
Return structureBlock.WithStructureStatement(structureBlock.StructureStatement.WithTypeParameterList(replacer(structureBlock.StructureStatement.TypeParameterList)))
End If
Dim interfaceBlock = TryCast(declaration, InterfaceBlockSyntax)
If interfaceBlock IsNot Nothing Then
Return interfaceBlock.WithInterfaceStatement(interfaceBlock.InterfaceStatement.WithTypeParameterList(replacer(interfaceBlock.InterfaceStatement.TypeParameterList)))
End If
Return declaration
End Function
Friend Overrides Function WithExplicitInterfaceImplementations(declaration As SyntaxNode, explicitInterfaceImplementations As ImmutableArray(Of IMethodSymbol)) As SyntaxNode
If TypeOf declaration Is MethodStatementSyntax Then
Dim methodStatement = DirectCast(declaration, MethodStatementSyntax)
Dim interfaceMembers = explicitInterfaceImplementations.Select(AddressOf GenerateInterfaceMember)
Return methodStatement.WithImplementsClause(
SyntaxFactory.ImplementsClause(SyntaxFactory.SeparatedList(interfaceMembers)))
ElseIf TypeOf declaration Is MethodBlockSyntax Then
Dim methodBlock = DirectCast(declaration, MethodBlockSyntax)
Return methodBlock.WithSubOrFunctionStatement(
DirectCast(WithExplicitInterfaceImplementations(methodBlock.SubOrFunctionStatement, explicitInterfaceImplementations), MethodStatementSyntax))
End If
Return declaration
End Function
Private Function GenerateInterfaceMember(method As IMethodSymbol) As QualifiedNameSyntax
Dim interfaceName = method.ContainingType.GenerateTypeSyntax()
Return SyntaxFactory.QualifiedName(
DirectCast(interfaceName, NameSyntax),
SyntaxFactory.IdentifierName(method.Name))
End Function
Public Overrides Function WithTypeConstraint(declaration As SyntaxNode, typeParameterName As String, kinds As SpecialTypeConstraintKind, Optional types As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode
Dim constraints = SyntaxFactory.SeparatedList(Of ConstraintSyntax)
If types IsNot Nothing Then
constraints = constraints.AddRange(types.Select(Function(t) SyntaxFactory.TypeConstraint(DirectCast(t, TypeSyntax))))
End If
If (kinds And SpecialTypeConstraintKind.Constructor) <> 0 Then
constraints = constraints.Add(SyntaxFactory.NewConstraint(SyntaxFactory.Token(SyntaxKind.NewKeyword)))
End If
Dim isReferenceType = (kinds And SpecialTypeConstraintKind.ReferenceType) <> 0
Dim isValueType = (kinds And SpecialTypeConstraintKind.ValueType) <> 0
If isReferenceType Then
constraints = constraints.Insert(0, SyntaxFactory.ClassConstraint(SyntaxFactory.Token(SyntaxKind.ClassKeyword)))
ElseIf isValueType Then
constraints = constraints.Insert(0, SyntaxFactory.StructureConstraint(SyntaxFactory.Token(SyntaxKind.StructureKeyword)))
End If
Dim clause As TypeParameterConstraintClauseSyntax = Nothing
If constraints.Count = 1 Then
clause = SyntaxFactory.TypeParameterSingleConstraintClause(constraints(0))
ElseIf constraints.Count > 1 Then
clause = SyntaxFactory.TypeParameterMultipleConstraintClause(constraints)
End If
Return ReplaceTypeParameterList(declaration, Function(old) WithTypeParameterConstraints(old, typeParameterName, clause))
End Function
Private Function WithTypeParameterConstraints(typeParameterList As TypeParameterListSyntax, typeParameterName As String, clause As TypeParameterConstraintClauseSyntax) As TypeParameterListSyntax
If typeParameterList IsNot Nothing Then
Dim typeParameter = typeParameterList.Parameters.FirstOrDefault(Function(tp) tp.Identifier.ToString() = typeParameterName)
If typeParameter IsNot Nothing Then
Return typeParameterList.WithParameters(typeParameterList.Parameters.Replace(typeParameter, typeParameter.WithTypeParameterConstraintClause(clause)))
End If
End If
Return typeParameterList
End Function
Public Overrides Function GetParameters(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode)
Dim list = GetParameterList(declaration)
Return If(list IsNot Nothing,
list.Parameters,
SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode))
End Function
Public Overrides Function InsertParameters(declaration As SyntaxNode, index As Integer, parameters As IEnumerable(Of SyntaxNode)) As SyntaxNode
Dim currentList = GetParameterList(declaration)
Dim newList = GetParameterList(parameters)
If currentList IsNot Nothing Then
Return WithParameterList(declaration, currentList.WithParameters(currentList.Parameters.InsertRange(index, newList.Parameters)))
Else
Return WithParameterList(declaration, newList)
End If
End Function
Public Overrides Function GetSwitchSections(switchStatement As SyntaxNode) As IReadOnlyList(Of SyntaxNode)
Dim statement = TryCast(switchStatement, SelectBlockSyntax)
If statement Is Nothing Then
Return SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode)
End If
Return statement.CaseBlocks
End Function
Public Overrides Function InsertSwitchSections(switchStatement As SyntaxNode, index As Integer, switchSections As IEnumerable(Of SyntaxNode)) As SyntaxNode
Dim statement = TryCast(switchStatement, SelectBlockSyntax)
If statement Is Nothing Then
Return switchStatement
End If
Return statement.WithCaseBlocks(
statement.CaseBlocks.InsertRange(index, switchSections.Cast(Of CaseBlockSyntax)))
End Function
Friend Overrides Function GetParameterListNode(declaration As SyntaxNode) As SyntaxNode
Return GetParameterList(declaration)
End Function
Friend Shared Function GetParameterList(declaration As SyntaxNode) As ParameterListSyntax
Select Case declaration.Kind
Case SyntaxKind.SubBlock,
SyntaxKind.FunctionBlock
Return DirectCast(declaration, MethodBlockSyntax).BlockStatement.ParameterList
Case SyntaxKind.ConstructorBlock
Return DirectCast(declaration, ConstructorBlockSyntax).BlockStatement.ParameterList
Case SyntaxKind.OperatorBlock
Return DirectCast(declaration, OperatorBlockSyntax).BlockStatement.ParameterList
Case SyntaxKind.SubStatement,
SyntaxKind.FunctionStatement
Return DirectCast(declaration, MethodStatementSyntax).ParameterList
Case SyntaxKind.SubNewStatement
Return DirectCast(declaration, SubNewStatementSyntax).ParameterList
Case SyntaxKind.OperatorStatement
Return DirectCast(declaration, OperatorStatementSyntax).ParameterList
Case SyntaxKind.DeclareSubStatement,
SyntaxKind.DeclareFunctionStatement
Return DirectCast(declaration, DeclareStatementSyntax).ParameterList
Case SyntaxKind.DelegateSubStatement,
SyntaxKind.DelegateFunctionStatement
Return DirectCast(declaration, DelegateStatementSyntax).ParameterList
Case SyntaxKind.PropertyBlock
Return DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.ParameterList
Case SyntaxKind.PropertyStatement
Return DirectCast(declaration, PropertyStatementSyntax).ParameterList
Case SyntaxKind.EventBlock
Return DirectCast(declaration, EventBlockSyntax).EventStatement.ParameterList
Case SyntaxKind.EventStatement
Return DirectCast(declaration, EventStatementSyntax).ParameterList
Case SyntaxKind.MultiLineFunctionLambdaExpression,
SyntaxKind.MultiLineSubLambdaExpression
Return DirectCast(declaration, MultiLineLambdaExpressionSyntax).SubOrFunctionHeader.ParameterList
Case SyntaxKind.SingleLineFunctionLambdaExpression,
SyntaxKind.SingleLineSubLambdaExpression
Return DirectCast(declaration, SingleLineLambdaExpressionSyntax).SubOrFunctionHeader.ParameterList
Case Else
Return Nothing
End Select
End Function
Private Function WithParameterList(declaration As SyntaxNode, list As ParameterListSyntax) As SyntaxNode
Select Case declaration.Kind
Case SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement
Return DirectCast(declaration, DelegateStatementSyntax).WithParameterList(list)
Case SyntaxKind.SubBlock,
SyntaxKind.FunctionBlock
Return DirectCast(declaration, MethodBlockSyntax).WithBlockStatement(DirectCast(declaration, MethodBlockSyntax).BlockStatement.WithParameterList(list))
Case SyntaxKind.ConstructorBlock
Return DirectCast(declaration, ConstructorBlockSyntax).WithBlockStatement(DirectCast(declaration, ConstructorBlockSyntax).BlockStatement.WithParameterList(list))
Case SyntaxKind.OperatorBlock
Return DirectCast(declaration, OperatorBlockSyntax).WithBlockStatement(DirectCast(declaration, OperatorBlockSyntax).BlockStatement.WithParameterList(list))
Case SyntaxKind.SubStatement,
SyntaxKind.FunctionStatement
Return DirectCast(declaration, MethodStatementSyntax).WithParameterList(list)
Case SyntaxKind.SubNewStatement
Return DirectCast(declaration, SubNewStatementSyntax).WithParameterList(list)
Case SyntaxKind.OperatorStatement
Return DirectCast(declaration, OperatorStatementSyntax).WithParameterList(list)
Case SyntaxKind.DeclareSubStatement,
SyntaxKind.DeclareFunctionStatement
Return DirectCast(declaration, DeclareStatementSyntax).WithParameterList(list)
Case SyntaxKind.DelegateSubStatement,
SyntaxKind.DelegateFunctionStatement
Return DirectCast(declaration, DelegateStatementSyntax).WithParameterList(list)
Case SyntaxKind.PropertyBlock
If GetDeclarationKind(declaration) = DeclarationKind.Indexer Then
Return DirectCast(declaration, PropertyBlockSyntax).WithPropertyStatement(DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.WithParameterList(list))
End If
Case SyntaxKind.PropertyStatement
If GetDeclarationKind(declaration) = DeclarationKind.Indexer Then
Return DirectCast(declaration, PropertyStatementSyntax).WithParameterList(list)
End If
Case SyntaxKind.EventBlock
Return DirectCast(declaration, EventBlockSyntax).WithEventStatement(DirectCast(declaration, EventBlockSyntax).EventStatement.WithParameterList(list))
Case SyntaxKind.EventStatement
Return DirectCast(declaration, EventStatementSyntax).WithParameterList(list)
Case SyntaxKind.MultiLineFunctionLambdaExpression,
SyntaxKind.MultiLineSubLambdaExpression
Return DirectCast(declaration, MultiLineLambdaExpressionSyntax).WithSubOrFunctionHeader(DirectCast(declaration, MultiLineLambdaExpressionSyntax).SubOrFunctionHeader.WithParameterList(list))
Case SyntaxKind.SingleLineFunctionLambdaExpression,
SyntaxKind.SingleLineSubLambdaExpression
Return DirectCast(declaration, SingleLineLambdaExpressionSyntax).WithSubOrFunctionHeader(DirectCast(declaration, SingleLineLambdaExpressionSyntax).SubOrFunctionHeader.WithParameterList(list))
End Select
Return declaration
End Function
Public Overrides Function GetExpression(declaration As SyntaxNode) As SyntaxNode
Select Case declaration.Kind
Case SyntaxKind.SingleLineFunctionLambdaExpression,
SyntaxKind.SingleLineSubLambdaExpression
Return AsExpression(DirectCast(declaration, SingleLineLambdaExpressionSyntax).Body)
Case Else
Dim ev = GetEqualsValue(declaration)
If ev IsNot Nothing Then
Return ev.Value
End If
End Select
Return Nothing
End Function
Private Function AsExpression(node As SyntaxNode) As ExpressionSyntax
Dim es = TryCast(node, ExpressionStatementSyntax)
If es IsNot Nothing Then
Return es.Expression
End If
Return DirectCast(node, ExpressionSyntax)
End Function
Public Overrides Function WithExpression(declaration As SyntaxNode, expression As SyntaxNode) As SyntaxNode
Return Isolate(declaration, Function(d) WithExpressionInternal(d, expression))
End Function
Private Function WithExpressionInternal(declaration As SyntaxNode, expression As SyntaxNode) As SyntaxNode
Dim expr = DirectCast(expression, ExpressionSyntax)
Select Case declaration.Kind
Case SyntaxKind.SingleLineFunctionLambdaExpression
Dim sll = DirectCast(declaration, SingleLineLambdaExpressionSyntax)
If expression IsNot Nothing Then
Return sll.WithBody(expr)
Else
Return SyntaxFactory.MultiLineLambdaExpression(SyntaxKind.MultiLineFunctionLambdaExpression, sll.SubOrFunctionHeader, SyntaxFactory.EndFunctionStatement())
End If
Case SyntaxKind.MultiLineFunctionLambdaExpression
Dim mll = DirectCast(declaration, MultiLineLambdaExpressionSyntax)
If expression IsNot Nothing Then
Return SyntaxFactory.SingleLineLambdaExpression(SyntaxKind.SingleLineFunctionLambdaExpression, mll.SubOrFunctionHeader, expr)
End If
Case SyntaxKind.SingleLineSubLambdaExpression
Dim sll = DirectCast(declaration, SingleLineLambdaExpressionSyntax)
If expression IsNot Nothing Then
Return sll.WithBody(AsStatement(expr))
Else
Return SyntaxFactory.MultiLineLambdaExpression(SyntaxKind.MultiLineSubLambdaExpression, sll.SubOrFunctionHeader, SyntaxFactory.EndSubStatement())
End If
Case SyntaxKind.MultiLineSubLambdaExpression
Dim mll = DirectCast(declaration, MultiLineLambdaExpressionSyntax)
If expression IsNot Nothing Then
Return SyntaxFactory.SingleLineLambdaExpression(SyntaxKind.SingleLineSubLambdaExpression, mll.SubOrFunctionHeader, AsStatement(expr))
End If
Case Else
Dim currentEV = GetEqualsValue(declaration)
If currentEV IsNot Nothing Then
Return WithEqualsValue(declaration, currentEV.WithValue(expr))
Else
Return WithEqualsValue(declaration, SyntaxFactory.EqualsValue(expr))
End If
End Select
Return declaration
End Function
Private Function GetEqualsValue(declaration As SyntaxNode) As EqualsValueSyntax
Select Case declaration.Kind
Case SyntaxKind.Parameter
Return DirectCast(declaration, ParameterSyntax).Default
Case SyntaxKind.LocalDeclarationStatement
Dim ld = DirectCast(declaration, LocalDeclarationStatementSyntax)
If ld.Declarators.Count = 1 Then
Return ld.Declarators(0).Initializer
End If
Case SyntaxKind.FieldDeclaration
Dim fd = DirectCast(declaration, FieldDeclarationSyntax)
If fd.Declarators.Count = 1 Then
Return fd.Declarators(0).Initializer
End If
Case SyntaxKind.VariableDeclarator
Return DirectCast(declaration, VariableDeclaratorSyntax).Initializer
End Select
Return Nothing
End Function
Private Function WithEqualsValue(declaration As SyntaxNode, ev As EqualsValueSyntax) As SyntaxNode
Select Case declaration.Kind
Case SyntaxKind.Parameter
Return DirectCast(declaration, ParameterSyntax).WithDefault(ev)
Case SyntaxKind.LocalDeclarationStatement
Dim ld = DirectCast(declaration, LocalDeclarationStatementSyntax)
If ld.Declarators.Count = 1 Then
Return ReplaceWithTrivia(declaration, ld.Declarators(0), ld.Declarators(0).WithInitializer(ev))
End If
Case SyntaxKind.FieldDeclaration
Dim fd = DirectCast(declaration, FieldDeclarationSyntax)
If fd.Declarators.Count = 1 Then
Return ReplaceWithTrivia(declaration, fd.Declarators(0), fd.Declarators(0).WithInitializer(ev))
End If
End Select
Return declaration
End Function
Public Overrides Function GetNamespaceImports(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode)
Return Me.Flatten(Me.GetUnflattenedNamespaceImports(declaration))
End Function
Private Function GetUnflattenedNamespaceImports(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode)
Select Case declaration.Kind
Case SyntaxKind.CompilationUnit
Return DirectCast(declaration, CompilationUnitSyntax).Imports
Case Else
Return SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode)
End Select
End Function
Public Overrides Function InsertNamespaceImports(declaration As SyntaxNode, index As Integer, [imports] As IEnumerable(Of SyntaxNode)) As SyntaxNode
Return Isolate(declaration, Function(d) InsertNamespaceImportsInternal(d, index, [imports]))
End Function
Private Function InsertNamespaceImportsInternal(declaration As SyntaxNode, index As Integer, [imports] As IEnumerable(Of SyntaxNode)) As SyntaxNode
Dim newImports = AsImports([imports])
Dim existingImports = Me.GetNamespaceImports(declaration)
If index >= 0 AndAlso index < existingImports.Count Then
Return Me.InsertNodesBefore(declaration, existingImports(index), newImports)
ElseIf existingImports.Count > 0 Then
Return Me.InsertNodesAfter(declaration, existingImports(existingImports.Count - 1), newImports)
Else
Select Case declaration.Kind
Case SyntaxKind.CompilationUnit
Dim cu = DirectCast(declaration, CompilationUnitSyntax)
Return cu.WithImports(cu.Imports.AddRange(newImports))
Case Else
Return declaration
End Select
End If
End Function
Public Overrides Function GetMembers(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode)
Return Flatten(GetUnflattenedMembers(declaration))
End Function
Private Function GetUnflattenedMembers(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode)
Select Case declaration.Kind
Case SyntaxKind.CompilationUnit
Return DirectCast(declaration, CompilationUnitSyntax).Members
Case SyntaxKind.NamespaceBlock
Return DirectCast(declaration, NamespaceBlockSyntax).Members
Case SyntaxKind.ClassBlock
Return DirectCast(declaration, ClassBlockSyntax).Members
Case SyntaxKind.StructureBlock
Return DirectCast(declaration, StructureBlockSyntax).Members
Case SyntaxKind.InterfaceBlock
Return DirectCast(declaration, InterfaceBlockSyntax).Members
Case SyntaxKind.EnumBlock
Return DirectCast(declaration, EnumBlockSyntax).Members
Case Else
Return SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode)()
End Select
End Function
Private Function AsMembersOf(declaration As SyntaxNode, members As IEnumerable(Of SyntaxNode)) As IEnumerable(Of StatementSyntax)
Select Case declaration.Kind
Case SyntaxKind.CompilationUnit
Return AsNamespaceMembers(members)
Case SyntaxKind.NamespaceBlock
Return AsNamespaceMembers(members)
Case SyntaxKind.ClassBlock
Return AsClassMembers(members)
Case SyntaxKind.StructureBlock
Return AsClassMembers(members)
Case SyntaxKind.InterfaceBlock
Return AsInterfaceMembers(members)
Case SyntaxKind.EnumBlock
Return AsEnumMembers(members)
Case Else
Return SpecializedCollections.EmptyEnumerable(Of StatementSyntax)
End Select
End Function
Public Overrides Function InsertMembers(declaration As SyntaxNode, index As Integer, members As IEnumerable(Of SyntaxNode)) As SyntaxNode
Return Isolate(declaration, Function(d) InsertMembersInternal(d, index, members))
End Function
Private Function InsertMembersInternal(declaration As SyntaxNode, index As Integer, members As IEnumerable(Of SyntaxNode)) As SyntaxNode
Dim newMembers = Me.AsMembersOf(declaration, members)
Dim existingMembers = Me.GetMembers(declaration)
If index >= 0 AndAlso index < existingMembers.Count Then
Return Me.InsertNodesBefore(declaration, existingMembers(index), members)
ElseIf existingMembers.Count > 0 Then
Return Me.InsertNodesAfter(declaration, existingMembers(existingMembers.Count - 1), members)
End If
Select Case declaration.Kind
Case SyntaxKind.CompilationUnit
Dim cu = DirectCast(declaration, CompilationUnitSyntax)
Return cu.WithMembers(cu.Members.AddRange(newMembers))
Case SyntaxKind.NamespaceBlock
Dim ns = DirectCast(declaration, NamespaceBlockSyntax)
Return ns.WithMembers(ns.Members.AddRange(newMembers))
Case SyntaxKind.ClassBlock
Dim cb = DirectCast(declaration, ClassBlockSyntax)
Return cb.WithMembers(cb.Members.AddRange(newMembers))
Case SyntaxKind.StructureBlock
Dim sb = DirectCast(declaration, StructureBlockSyntax)
Return sb.WithMembers(sb.Members.AddRange(newMembers))
Case SyntaxKind.InterfaceBlock
Dim ib = DirectCast(declaration, InterfaceBlockSyntax)
Return ib.WithMembers(ib.Members.AddRange(newMembers))
Case SyntaxKind.EnumBlock
Dim eb = DirectCast(declaration, EnumBlockSyntax)
Return eb.WithMembers(eb.Members.AddRange(newMembers))
Case Else
Return declaration
End Select
End Function
Public Overrides Function GetStatements(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode)
Select Case declaration.Kind
Case SyntaxKind.FunctionBlock,
SyntaxKind.SubBlock,
SyntaxKind.ConstructorBlock,
SyntaxKind.OperatorBlock
Return DirectCast(declaration, MethodBlockBaseSyntax).Statements
Case SyntaxKind.MultiLineFunctionLambdaExpression,
SyntaxKind.MultiLineSubLambdaExpression
Return DirectCast(declaration, MultiLineLambdaExpressionSyntax).Statements
Case SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock
Return DirectCast(declaration, AccessorBlockSyntax).Statements
Case Else
Return SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode)
End Select
End Function
Public Overrides Function WithStatements(declaration As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode
Return Isolate(declaration, Function(d) WithStatementsInternal(d, statements))
End Function
Private Function WithStatementsInternal(declaration As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode
Dim list = GetStatementList(statements)
Select Case declaration.Kind
Case SyntaxKind.FunctionBlock,
SyntaxKind.SubBlock
Return DirectCast(declaration, MethodBlockSyntax).WithStatements(list)
Case SyntaxKind.ConstructorBlock
Return DirectCast(declaration, ConstructorBlockSyntax).WithStatements(list)
Case SyntaxKind.OperatorBlock
Return DirectCast(declaration, OperatorBlockSyntax).WithStatements(list)
Case SyntaxKind.MultiLineFunctionLambdaExpression,
SyntaxKind.MultiLineSubLambdaExpression
Return DirectCast(declaration, MultiLineLambdaExpressionSyntax).WithStatements(list)
Case SyntaxKind.SingleLineFunctionLambdaExpression
Dim sll = DirectCast(declaration, SingleLineLambdaExpressionSyntax)
Return SyntaxFactory.MultiLineLambdaExpression(SyntaxKind.MultiLineFunctionLambdaExpression, sll.SubOrFunctionHeader, list, SyntaxFactory.EndFunctionStatement())
Case SyntaxKind.SingleLineSubLambdaExpression
Dim sll = DirectCast(declaration, SingleLineLambdaExpressionSyntax)
Return SyntaxFactory.MultiLineLambdaExpression(SyntaxKind.MultiLineSubLambdaExpression, sll.SubOrFunctionHeader, list, SyntaxFactory.EndSubStatement())
Case SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock
Return DirectCast(declaration, AccessorBlockSyntax).WithStatements(list)
Case Else
Return declaration
End Select
End Function
Public Overrides Function GetAccessors(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode)
Select Case declaration.Kind
Case SyntaxKind.PropertyBlock
Return DirectCast(declaration, PropertyBlockSyntax).Accessors
Case SyntaxKind.EventBlock
Return DirectCast(declaration, EventBlockSyntax).Accessors
Case Else
Return SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode)()
End Select
End Function
Public Overrides Function InsertAccessors(declaration As SyntaxNode, index As Integer, accessors As IEnumerable(Of SyntaxNode)) As SyntaxNode
Dim currentList = GetAccessorList(declaration)
Dim newList = AsAccessorList(accessors, declaration.Kind)
If Not currentList.IsEmpty Then
Return WithAccessorList(declaration, currentList.InsertRange(index, newList))
Else
Return WithAccessorList(declaration, newList)
End If
End Function
Private Function GetAccessorList(declaration As SyntaxNode) As SyntaxList(Of AccessorBlockSyntax)
Select Case declaration.Kind
Case SyntaxKind.PropertyBlock
Return DirectCast(declaration, PropertyBlockSyntax).Accessors
Case SyntaxKind.EventBlock
Return DirectCast(declaration, EventBlockSyntax).Accessors
Case Else
Return Nothing
End Select
End Function
Private Function WithAccessorList(declaration As SyntaxNode, accessorList As SyntaxList(Of AccessorBlockSyntax)) As SyntaxNode
Select Case declaration.Kind
Case SyntaxKind.PropertyBlock
Return DirectCast(declaration, PropertyBlockSyntax).WithAccessors(accessorList)
Case SyntaxKind.EventBlock
Return DirectCast(declaration, EventBlockSyntax).WithAccessors(accessorList)
Case Else
Return declaration
End Select
End Function
Private Function AsAccessorList(nodes As IEnumerable(Of SyntaxNode), parentKind As SyntaxKind) As SyntaxList(Of AccessorBlockSyntax)
Return SyntaxFactory.List(nodes.Select(Function(n) AsAccessor(n, parentKind)).Where(Function(n) n IsNot Nothing))
End Function
Private Function AsAccessor(node As SyntaxNode, parentKind As SyntaxKind) As AccessorBlockSyntax
Select Case parentKind
Case SyntaxKind.PropertyBlock
Select Case node.Kind
Case SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock
Return DirectCast(node, AccessorBlockSyntax)
End Select
Case SyntaxKind.EventBlock
Select Case node.Kind
Case SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock
Return DirectCast(node, AccessorBlockSyntax)
End Select
End Select
Return Nothing
End Function
Private Function CanHaveAccessors(kind As SyntaxKind) As Boolean
Select Case kind
Case SyntaxKind.PropertyBlock,
SyntaxKind.EventBlock
Return True
Case Else
Return False
End Select
End Function
Public Overrides Function GetGetAccessorStatements(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode)
Return GetAccessorStatements(declaration, SyntaxKind.GetAccessorBlock)
End Function
Public Overrides Function WithGetAccessorStatements(declaration As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode
Return WithAccessorStatements(declaration, statements, SyntaxKind.GetAccessorBlock)
End Function
Public Overrides Function GetSetAccessorStatements(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode)
Return GetAccessorStatements(declaration, SyntaxKind.SetAccessorBlock)
End Function
Public Overrides Function WithSetAccessorStatements(declaration As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As SyntaxNode
Return WithAccessorStatements(declaration, statements, SyntaxKind.SetAccessorBlock)
End Function
Private Function GetAccessorStatements(declaration As SyntaxNode, kind As SyntaxKind) As IReadOnlyList(Of SyntaxNode)
Dim accessor = Me.GetAccessorBlock(declaration, kind)
If accessor IsNot Nothing Then
Return Me.GetStatements(accessor)
Else
Return SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode)()
End If
End Function
Private Function WithAccessorStatements(declaration As SyntaxNode, statements As IEnumerable(Of SyntaxNode), kind As SyntaxKind) As SyntaxNode
Dim accessor = Me.GetAccessorBlock(declaration, kind)
If accessor IsNot Nothing Then
accessor = DirectCast(Me.WithStatements(accessor, statements), AccessorBlockSyntax)
Return Me.WithAccessorBlock(declaration, kind, accessor)
ElseIf Me.CanHaveAccessors(declaration.Kind) Then
accessor = Me.AccessorBlock(kind, statements, Me.ClearTrivia(Me.GetType(declaration)))
Return Me.WithAccessorBlock(declaration, kind, accessor)
Else
Return declaration
End If
End Function
Private Function GetAccessorBlock(declaration As SyntaxNode, kind As SyntaxKind) As AccessorBlockSyntax
Select Case declaration.Kind
Case SyntaxKind.PropertyBlock
Return DirectCast(declaration, PropertyBlockSyntax).Accessors.FirstOrDefault(Function(a) a.IsKind(kind))
Case SyntaxKind.EventBlock
Return DirectCast(declaration, EventBlockSyntax).Accessors.FirstOrDefault(Function(a) a.IsKind(kind))
Case Else
Return Nothing
End Select
End Function
Private Function WithAccessorBlock(declaration As SyntaxNode, kind As SyntaxKind, accessor As AccessorBlockSyntax) As SyntaxNode
Dim currentAccessor = Me.GetAccessorBlock(declaration, kind)
If currentAccessor IsNot Nothing Then
Return Me.ReplaceNode(declaration, currentAccessor, accessor)
ElseIf accessor IsNot Nothing Then
Select Case declaration.Kind
Case SyntaxKind.PropertyBlock
Dim pb = DirectCast(declaration, PropertyBlockSyntax)
Return pb.WithAccessors(pb.Accessors.Add(accessor))
Case SyntaxKind.EventBlock
Dim eb = DirectCast(declaration, EventBlockSyntax)
Return eb.WithAccessors(eb.Accessors.Add(accessor))
End Select
End If
Return declaration
End Function
Public Overrides Function EventDeclaration(name As String, type As SyntaxNode, Optional accessibility As Accessibility = Accessibility.NotApplicable, Optional modifiers As DeclarationModifiers = Nothing) As SyntaxNode
Return SyntaxFactory.EventStatement(
attributeLists:=Nothing,
modifiers:=GetModifierList(accessibility, modifiers And GetAllowedModifiers(SyntaxKind.EventStatement), DeclarationKind.Event),
customKeyword:=Nothing,
eventKeyword:=SyntaxFactory.Token(SyntaxKind.EventKeyword),
identifier:=name.ToIdentifierToken(),
parameterList:=Nothing,
asClause:=SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax)),
implementsClause:=Nothing)
End Function
Public Overrides Function CustomEventDeclaration(
name As String, type As SyntaxNode,
Optional accessibility As Accessibility = Accessibility.NotApplicable,
Optional modifiers As DeclarationModifiers = Nothing,
Optional parameters As IEnumerable(Of SyntaxNode) = Nothing,
Optional addAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing,
Optional removeAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode
Return CustomEventDeclarationWithRaise(name, type, accessibility, modifiers, parameters, addAccessorStatements, removeAccessorStatements)
End Function
Public Function CustomEventDeclarationWithRaise(
name As String,
type As SyntaxNode,
Optional accessibility As Accessibility = Accessibility.NotApplicable,
Optional modifiers As DeclarationModifiers = Nothing,
Optional parameters As IEnumerable(Of SyntaxNode) = Nothing,
Optional addAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing,
Optional removeAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing,
Optional raiseAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode
Dim accessors = New List(Of AccessorBlockSyntax)()
If modifiers.IsAbstract Then
addAccessorStatements = Nothing
removeAccessorStatements = Nothing
raiseAccessorStatements = Nothing
Else
If addAccessorStatements Is Nothing Then
addAccessorStatements = SpecializedCollections.EmptyEnumerable(Of SyntaxNode)()
End If
If removeAccessorStatements Is Nothing Then
removeAccessorStatements = SpecializedCollections.EmptyEnumerable(Of SyntaxNode)()
End If
If raiseAccessorStatements Is Nothing Then
raiseAccessorStatements = SpecializedCollections.EmptyEnumerable(Of SyntaxNode)()
End If
End If
accessors.Add(CreateAddHandlerAccessorBlock(type, addAccessorStatements))
accessors.Add(CreateRemoveHandlerAccessorBlock(type, removeAccessorStatements))
accessors.Add(CreateRaiseEventAccessorBlock(parameters, raiseAccessorStatements))
Dim evStatement = SyntaxFactory.EventStatement(
attributeLists:=Nothing,
modifiers:=GetModifierList(accessibility, modifiers And GetAllowedModifiers(SyntaxKind.EventStatement), DeclarationKind.Event),
customKeyword:=SyntaxFactory.Token(SyntaxKind.CustomKeyword),
eventKeyword:=SyntaxFactory.Token(SyntaxKind.EventKeyword),
identifier:=name.ToIdentifierToken(),
parameterList:=Nothing,
asClause:=SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax)),
implementsClause:=Nothing)
Return SyntaxFactory.EventBlock(
eventStatement:=evStatement,
accessors:=SyntaxFactory.List(accessors),
endEventStatement:=SyntaxFactory.EndEventStatement())
End Function
Public Overrides Function GetAttributeArguments(attributeDeclaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode)
Dim list = GetArgumentList(attributeDeclaration)
If list IsNot Nothing Then
Return list.Arguments
Else
Return SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode)()
End If
End Function
Public Overrides Function InsertAttributeArguments(attributeDeclaration As SyntaxNode, index As Integer, attributeArguments As IEnumerable(Of SyntaxNode)) As SyntaxNode
Return Isolate(attributeDeclaration, Function(d) InsertAttributeArgumentsInternal(d, index, attributeArguments))
End Function
Private Function InsertAttributeArgumentsInternal(attributeDeclaration As SyntaxNode, index As Integer, attributeArguments As IEnumerable(Of SyntaxNode)) As SyntaxNode
Dim list = GetArgumentList(attributeDeclaration)
Dim newArguments = AsArgumentList(attributeArguments)
If list Is Nothing Then
list = newArguments
Else
list = list.WithArguments(list.Arguments.InsertRange(index, newArguments.Arguments))
End If
Return WithArgumentList(attributeDeclaration, list)
End Function
Private Function GetArgumentList(declaration As SyntaxNode) As ArgumentListSyntax
Select Case declaration.Kind
Case SyntaxKind.AttributeList
Dim al = DirectCast(declaration, AttributeListSyntax)
If al.Attributes.Count = 1 Then
Return al.Attributes(0).ArgumentList
End If
Case SyntaxKind.Attribute
Return DirectCast(declaration, AttributeSyntax).ArgumentList
End Select
Return Nothing
End Function
Private Function WithArgumentList(declaration As SyntaxNode, argumentList As ArgumentListSyntax) As SyntaxNode
Select Case declaration.Kind
Case SyntaxKind.AttributeList
Dim al = DirectCast(declaration, AttributeListSyntax)
If al.Attributes.Count = 1 Then
Return ReplaceWithTrivia(declaration, al.Attributes(0), al.Attributes(0).WithArgumentList(argumentList))
End If
Case SyntaxKind.Attribute
Return DirectCast(declaration, AttributeSyntax).WithArgumentList(argumentList)
End Select
Return declaration
End Function
Public Overrides Function GetBaseAndInterfaceTypes(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode)
Return Me.GetInherits(declaration).SelectMany(Function(ih) ih.Types).Concat(Me.GetImplements(declaration).SelectMany(Function(imp) imp.Types)).ToImmutableReadOnlyListOrEmpty()
End Function
Public Overrides Function AddBaseType(declaration As SyntaxNode, baseType As SyntaxNode) As SyntaxNode
If declaration.IsKind(SyntaxKind.ClassBlock) Then
Dim existingBaseType = Me.GetInherits(declaration).SelectMany(Function(inh) inh.Types).FirstOrDefault()
If existingBaseType IsNot Nothing Then
Return declaration.ReplaceNode(existingBaseType, baseType.WithTriviaFrom(existingBaseType))
Else
Return Me.WithInherits(declaration, SyntaxFactory.SingletonList(SyntaxFactory.InheritsStatement(DirectCast(baseType, TypeSyntax))))
End If
Else
Return declaration
End If
End Function
Public Overrides Function AddInterfaceType(declaration As SyntaxNode, interfaceType As SyntaxNode) As SyntaxNode
If declaration.IsKind(SyntaxKind.InterfaceBlock) Then
Dim inh = Me.GetInherits(declaration)
Dim last = inh.SelectMany(Function(s) s.Types).LastOrDefault()
If inh.Count = 1 AndAlso last IsNot Nothing Then
Dim inh0 = inh(0)
Dim newInh0 = PreserveTrivia(inh0.TrackNodes(last), Function(_inh0) InsertNodesAfter(_inh0, _inh0.GetCurrentNode(last), {interfaceType}))
Return ReplaceNode(declaration, inh0, newInh0)
Else
Return Me.WithInherits(declaration, inh.Add(SyntaxFactory.InheritsStatement(DirectCast(interfaceType, TypeSyntax))))
End If
Else
Dim imp = Me.GetImplements(declaration)
Dim last = imp.SelectMany(Function(s) s.Types).LastOrDefault()
If imp.Count = 1 AndAlso last IsNot Nothing Then
Dim imp0 = imp(0)
Dim newImp0 = PreserveTrivia(imp0.TrackNodes(last), Function(_imp0) InsertNodesAfter(_imp0, _imp0.GetCurrentNode(last), {interfaceType}))
Return ReplaceNode(declaration, imp0, newImp0)
Else
Return Me.WithImplements(declaration, imp.Add(SyntaxFactory.ImplementsStatement(DirectCast(interfaceType, TypeSyntax))))
End If
End If
End Function
Private Function GetInherits(declaration As SyntaxNode) As SyntaxList(Of InheritsStatementSyntax)
Select Case declaration.Kind
Case SyntaxKind.ClassBlock
Return DirectCast(declaration, ClassBlockSyntax).Inherits
Case SyntaxKind.InterfaceBlock
Return DirectCast(declaration, InterfaceBlockSyntax).Inherits
Case Else
Return Nothing
End Select
End Function
Private Function WithInherits(declaration As SyntaxNode, list As SyntaxList(Of InheritsStatementSyntax)) As SyntaxNode
Select Case declaration.Kind
Case SyntaxKind.ClassBlock
Return DirectCast(declaration, ClassBlockSyntax).WithInherits(list)
Case SyntaxKind.InterfaceBlock
Return DirectCast(declaration, InterfaceBlockSyntax).WithInherits(list)
Case Else
Return declaration
End Select
End Function
Private Function GetImplements(declaration As SyntaxNode) As SyntaxList(Of ImplementsStatementSyntax)
Select Case declaration.Kind
Case SyntaxKind.ClassBlock
Return DirectCast(declaration, ClassBlockSyntax).Implements
Case SyntaxKind.StructureBlock
Return DirectCast(declaration, StructureBlockSyntax).Implements
Case Else
Return Nothing
End Select
End Function
Private Function WithImplements(declaration As SyntaxNode, list As SyntaxList(Of ImplementsStatementSyntax)) As SyntaxNode
Select Case declaration.Kind
Case SyntaxKind.ClassBlock
Return DirectCast(declaration, ClassBlockSyntax).WithImplements(list)
Case SyntaxKind.StructureBlock
Return DirectCast(declaration, StructureBlockSyntax).WithImplements(list)
Case Else
Return declaration
End Select
End Function
#End Region
#Region "Remove, Replace, Insert"
Public Overrides Function ReplaceNode(root As SyntaxNode, declaration As SyntaxNode, newDeclaration As SyntaxNode) As SyntaxNode
If newDeclaration Is Nothing Then
Return Me.RemoveNode(root, declaration)
End If
If root.Span.Contains(declaration.Span) Then
Dim newFullDecl = Me.AsIsolatedDeclaration(newDeclaration)
Dim fullDecl = Me.GetFullDeclaration(declaration)
' special handling for replacing at location of a sub-declaration
If fullDecl IsNot declaration AndAlso fullDecl.IsKind(newFullDecl.Kind) Then
' try to replace inline if possible
If GetDeclarationCount(newFullDecl) = 1 Then
Dim newSubDecl = Me.GetSubDeclarations(newFullDecl)(0)
If AreInlineReplaceableSubDeclarations(declaration, newSubDecl) Then
Return MyBase.ReplaceNode(root, declaration, newSubDecl)
End If
End If
' otherwise replace by splitting full-declaration into two parts and inserting newDeclaration between them
Dim index = MyBase.IndexOf(Me.GetSubDeclarations(fullDecl), declaration)
Return Me.ReplaceSubDeclaration(root, fullDecl, index, newFullDecl)
End If
' attempt normal replace
Return MyBase.ReplaceNode(root, declaration, newFullDecl)
Else
Return MyBase.ReplaceNode(root, declaration, newDeclaration)
End If
End Function
' return true if one sub-declaration can be replaced in-line with another sub-declaration
Private Function AreInlineReplaceableSubDeclarations(decl1 As SyntaxNode, decl2 As SyntaxNode) As Boolean
Dim kind = decl1.Kind
If Not decl2.IsKind(kind) Then
Return False
End If
Select Case kind
Case SyntaxKind.ModifiedIdentifier,
SyntaxKind.Attribute,
SyntaxKind.SimpleImportsClause,
SyntaxKind.XmlNamespaceImportsClause
Return AreSimilarExceptForSubDeclarations(decl1.Parent, decl2.Parent)
End Select
Return False
End Function
Private Function AreSimilarExceptForSubDeclarations(decl1 As SyntaxNode, decl2 As SyntaxNode) As Boolean
If decl1 Is Nothing OrElse decl2 Is Nothing Then
Return False
End If
Dim kind = decl1.Kind
If Not decl2.IsKind(kind) Then
Return False
End If
Select Case kind
Case SyntaxKind.FieldDeclaration
Dim fd1 = DirectCast(decl1, FieldDeclarationSyntax)
Dim fd2 = DirectCast(decl2, FieldDeclarationSyntax)
Return SyntaxFactory.AreEquivalent(fd1.AttributeLists, fd2.AttributeLists) AndAlso SyntaxFactory.AreEquivalent(fd1.Modifiers, fd2.Modifiers)
Case SyntaxKind.LocalDeclarationStatement
Dim ld1 = DirectCast(decl1, LocalDeclarationStatementSyntax)
Dim ld2 = DirectCast(decl2, LocalDeclarationStatementSyntax)
Return SyntaxFactory.AreEquivalent(ld1.Modifiers, ld2.Modifiers)
Case SyntaxKind.VariableDeclarator
Dim vd1 = DirectCast(decl1, VariableDeclaratorSyntax)
Dim vd2 = DirectCast(decl2, VariableDeclaratorSyntax)
Return SyntaxFactory.AreEquivalent(vd1.AsClause, vd2.AsClause) AndAlso SyntaxFactory.AreEquivalent(vd2.Initializer, vd1.Initializer) AndAlso AreSimilarExceptForSubDeclarations(decl1.Parent, decl2.Parent)
Case SyntaxKind.AttributeList,
SyntaxKind.ImportsStatement
Return True
End Select
Return False
End Function
Public Overrides Function InsertNodesBefore(root As SyntaxNode, declaration As SyntaxNode, newDeclarations As IEnumerable(Of SyntaxNode)) As SyntaxNode
If root.Span.Contains(declaration.Span) Then
Return Isolate(root.TrackNodes(declaration), Function(r) InsertDeclarationsBeforeInternal(r, r.GetCurrentNode(declaration), newDeclarations))
Else
Return MyBase.InsertNodesBefore(root, declaration, newDeclarations)
End If
End Function
Private Function InsertDeclarationsBeforeInternal(root As SyntaxNode, declaration As SyntaxNode, newDeclarations As IEnumerable(Of SyntaxNode)) As SyntaxNode
Dim fullDecl = Me.GetFullDeclaration(declaration)
If fullDecl Is declaration OrElse GetDeclarationCount(fullDecl) = 1 Then
Return MyBase.InsertNodesBefore(root, declaration, newDeclarations)
End If
Dim subDecls = Me.GetSubDeclarations(fullDecl)
Dim count = subDecls.Count
Dim index = MyBase.IndexOf(subDecls, declaration)
' insert New declaration between full declaration split into two
If index > 0 Then
Return ReplaceRange(root, fullDecl, SplitAndInsert(fullDecl, subDecls, index, newDeclarations))
End If
Return MyBase.InsertNodesBefore(root, fullDecl, newDeclarations)
End Function
Public Overrides Function InsertNodesAfter(root As SyntaxNode, declaration As SyntaxNode, newDeclarations As IEnumerable(Of SyntaxNode)) As SyntaxNode
If root.Span.Contains(declaration.Span) Then
Return Isolate(root.TrackNodes(declaration), Function(r) InsertNodesAfterInternal(r, r.GetCurrentNode(declaration), newDeclarations))
Else
Return MyBase.InsertNodesAfter(root, declaration, newDeclarations)
End If
End Function
Private Function InsertNodesAfterInternal(root As SyntaxNode, declaration As SyntaxNode, newDeclarations As IEnumerable(Of SyntaxNode)) As SyntaxNode
Dim fullDecl = Me.GetFullDeclaration(declaration)
If fullDecl Is declaration OrElse GetDeclarationCount(fullDecl) = 1 Then
Return MyBase.InsertNodesAfter(root, declaration, newDeclarations)
End If
Dim subDecls = Me.GetSubDeclarations(fullDecl)
Dim count = subDecls.Count
Dim index = MyBase.IndexOf(subDecls, declaration)
' insert New declaration between full declaration split into two
If index >= 0 AndAlso index < count - 1 Then
Return ReplaceRange(root, fullDecl, SplitAndInsert(fullDecl, subDecls, index + 1, newDeclarations))
End If
Return MyBase.InsertNodesAfter(root, fullDecl, newDeclarations)
End Function
Private Function SplitAndInsert(multiPartDeclaration As SyntaxNode, subDeclarations As IReadOnlyList(Of SyntaxNode), index As Integer, newDeclarations As IEnumerable(Of SyntaxNode)) As IEnumerable(Of SyntaxNode)
Dim count = subDeclarations.Count
Dim newNodes = New List(Of SyntaxNode)()
newNodes.Add(Me.WithSubDeclarationsRemoved(multiPartDeclaration, index, count - index).WithTrailingTrivia(SyntaxFactory.ElasticSpace))
newNodes.AddRange(newDeclarations)
newNodes.Add(Me.WithSubDeclarationsRemoved(multiPartDeclaration, 0, index).WithLeadingTrivia(SyntaxFactory.ElasticSpace))
Return newNodes
End Function
' replaces sub-declaration by splitting multi-part declaration first
Private Function ReplaceSubDeclaration(root As SyntaxNode, declaration As SyntaxNode, index As Integer, newDeclaration As SyntaxNode) As SyntaxNode
Dim newNodes = New List(Of SyntaxNode)()
Dim count = GetDeclarationCount(declaration)
If index >= 0 AndAlso index < count Then
If (index > 0) Then
' make a single declaration with only the sub-declarations before the sub-declaration being replaced
newNodes.Add(Me.WithSubDeclarationsRemoved(declaration, index, count - index).WithTrailingTrivia(SyntaxFactory.ElasticSpace))
End If
newNodes.Add(newDeclaration)
If (index < count - 1) Then
' make a single declaration with only the sub-declarations after the sub-declaration being replaced
newNodes.Add(Me.WithSubDeclarationsRemoved(declaration, 0, index + 1).WithLeadingTrivia(SyntaxFactory.ElasticSpace))
End If
' replace declaration with multiple declarations
Return ReplaceRange(root, declaration, newNodes)
Else
Return root
End If
End Function
Private Function WithSubDeclarationsRemoved(declaration As SyntaxNode, index As Integer, count As Integer) As SyntaxNode
Return Me.RemoveNodes(declaration, Me.GetSubDeclarations(declaration).Skip(index).Take(count))
End Function
Private Function GetSubDeclarations(declaration As SyntaxNode) As IReadOnlyList(Of SyntaxNode)
Select Case declaration.Kind
Case SyntaxKind.FieldDeclaration
Return DirectCast(declaration, FieldDeclarationSyntax).Declarators.SelectMany(Function(d) d.Names).ToImmutableReadOnlyListOrEmpty()
Case SyntaxKind.LocalDeclarationStatement
Return DirectCast(declaration, LocalDeclarationStatementSyntax).Declarators.SelectMany(Function(d) d.Names).ToImmutableReadOnlyListOrEmpty()
Case SyntaxKind.AttributeList
Return DirectCast(declaration, AttributeListSyntax).Attributes
Case SyntaxKind.ImportsStatement
Return DirectCast(declaration, ImportsStatementSyntax).ImportsClauses
Case Else
Return SpecializedCollections.EmptyReadOnlyList(Of SyntaxNode)
End Select
End Function
Private Function Flatten(members As IReadOnlyList(Of SyntaxNode)) As IReadOnlyList(Of SyntaxNode)
If members.Count = 0 OrElse Not members.Any(Function(m) GetDeclarationCount(m) > 1) Then
Return members
End If
Dim list = New List(Of SyntaxNode)
Flatten(members, list)
Return list.ToImmutableReadOnlyListOrEmpty()
End Function
Private Sub Flatten(members As IReadOnlyList(Of SyntaxNode), list As List(Of SyntaxNode))
For Each m In members
If GetDeclarationCount(m) > 1 Then
Select Case m.Kind
Case SyntaxKind.FieldDeclaration
Flatten(DirectCast(m, FieldDeclarationSyntax).Declarators, list)
Case SyntaxKind.LocalDeclarationStatement
Flatten(DirectCast(m, LocalDeclarationStatementSyntax).Declarators, list)
Case SyntaxKind.VariableDeclarator
Flatten(DirectCast(m, VariableDeclaratorSyntax).Names, list)
Case SyntaxKind.AttributesStatement
Flatten(DirectCast(m, AttributesStatementSyntax).AttributeLists, list)
Case SyntaxKind.AttributeList
Flatten(DirectCast(m, AttributeListSyntax).Attributes, list)
Case SyntaxKind.ImportsStatement
Flatten(DirectCast(m, ImportsStatementSyntax).ImportsClauses, list)
Case Else
list.Add(m)
End Select
Else
list.Add(m)
End If
Next
End Sub
Public Overrides Function RemoveNode(root As SyntaxNode, declaration As SyntaxNode) As SyntaxNode
Return RemoveNode(root, declaration, DefaultRemoveOptions)
End Function
Public Overrides Function RemoveNode(root As SyntaxNode, declaration As SyntaxNode, options As SyntaxRemoveOptions) As SyntaxNode
If root.Span.Contains(declaration.Span) Then
Return Isolate(root.TrackNodes(declaration), Function(r) Me.RemoveNodeInternal(r, r.GetCurrentNode(declaration), options))
Else
Return MyBase.RemoveNode(root, declaration, options)
End If
End Function
Private Function RemoveNodeInternal(root As SyntaxNode, node As SyntaxNode, options As SyntaxRemoveOptions) As SyntaxNode
' special case handling for nodes that remove their parents too
Select Case node.Kind
Case SyntaxKind.ModifiedIdentifier
Dim vd = TryCast(node.Parent, VariableDeclaratorSyntax)
If vd IsNot Nothing AndAlso vd.Names.Count = 1 Then
' remove entire variable declarator if only name
Return RemoveNodeInternal(root, vd, options)
End If
Case SyntaxKind.VariableDeclarator
If IsChildOfVariableDeclaration(node) AndAlso GetDeclarationCount(node.Parent) = 1 Then
' remove entire parent declaration if this is the only declarator
Return RemoveNodeInternal(root, node.Parent, options)
End If
Case SyntaxKind.AttributeList
Dim attrList = DirectCast(node, AttributeListSyntax)
Dim attrStmt = TryCast(attrList.Parent, AttributesStatementSyntax)
If attrStmt IsNot Nothing AndAlso attrStmt.AttributeLists.Count = 1 Then
' remove entire attribute statement if this is the only attribute list
Return RemoveNodeInternal(root, attrStmt, options)
End If
Case SyntaxKind.Attribute
Dim attrList = TryCast(node.Parent, AttributeListSyntax)
If attrList IsNot Nothing AndAlso attrList.Attributes.Count = 1 Then
' remove entire attribute list if this is the only attribute
Return RemoveNodeInternal(root, attrList, options)
End If
Case SyntaxKind.SimpleArgument
If IsChildOf(node, SyntaxKind.ArgumentList) AndAlso IsChildOf(node.Parent, SyntaxKind.Attribute) Then
Dim argList = DirectCast(node.Parent, ArgumentListSyntax)
If argList.Arguments.Count = 1 Then
' remove attribute's arg list if this is the only argument
Return RemoveNodeInternal(root, argList, options)
End If
End If
Case SyntaxKind.SimpleImportsClause,
SyntaxKind.XmlNamespaceImportsClause
Dim imps = DirectCast(node.Parent, ImportsStatementSyntax)
If imps.ImportsClauses.Count = 1 Then
' remove entire imports statement if this is the only clause
Return RemoveNodeInternal(root, node.Parent, options)
End If
Case Else
Dim parent = node.Parent
If parent IsNot Nothing Then
Select Case parent.Kind
Case SyntaxKind.ImplementsStatement
Dim imp = DirectCast(parent, ImplementsStatementSyntax)
If imp.Types.Count = 1 Then
Return RemoveNodeInternal(root, parent, options)
End If
Case SyntaxKind.InheritsStatement
Dim inh = DirectCast(parent, InheritsStatementSyntax)
If inh.Types.Count = 1 Then
Return RemoveNodeInternal(root, parent, options)
End If
End Select
End If
End Select
' do it the normal way
Return root.RemoveNode(node, options)
End Function
Friend Overrides Function IdentifierName(identifier As SyntaxToken) As SyntaxNode
Return SyntaxFactory.IdentifierName(identifier)
End Function
Friend Overrides Function Identifier(text As String) As SyntaxToken
Return SyntaxFactory.Identifier(text)
End Function
Friend Overrides Function NamedAnonymousObjectMemberDeclarator(identifier As SyntaxNode, expression As SyntaxNode) As SyntaxNode
Return SyntaxFactory.NamedFieldInitializer(
DirectCast(identifier, IdentifierNameSyntax),
DirectCast(expression, ExpressionSyntax))
End Function
Friend Overrides Function IsRegularOrDocComment(trivia As SyntaxTrivia) As Boolean
Return trivia.IsRegularOrDocComment()
End Function
Friend Overrides Function RemoveAllComments(node As SyntaxNode) As SyntaxNode
Return RemoveLeadingAndTrailingComments(node)
End Function
Friend Overrides Function RemoveCommentLines(syntaxList As SyntaxTriviaList) As SyntaxTriviaList
Return syntaxList.Where(Function(s) Not IsRegularOrDocComment(s)).ToSyntaxTriviaList()
End Function
#End Region
#Region "Patterns"
Friend Overrides Function SupportsPatterns(options As ParseOptions) As Boolean
Return False
End Function
Friend Overrides Function IsPatternExpression(expression As SyntaxNode, pattern As SyntaxNode) As SyntaxNode
Throw New NotImplementedException()
End Function
Friend Overrides Function ConstantPattern(expression As SyntaxNode) As SyntaxNode
Throw New NotImplementedException()
End Function
Friend Overrides Function DeclarationPattern(type As INamedTypeSymbol, name As String) As SyntaxNode
Throw New NotImplementedException()
End Function
#End Region
End Class
End Namespace
|
nguerrera/roslyn
|
src/Workspaces/VisualBasic/Portable/CodeGeneration/VisualBasicSyntaxGenerator.vb
|
Visual Basic
|
apache-2.0
| 236,011
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Collections.Immutable
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.ImplementInterface
Imports System.Composition
Namespace Microsoft.CodeAnalysis.VisualBasic.ImplementInterface
<ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.ImplementInterface), [Shared]>
<ExtensionOrder(After:=PredefinedCodeFixProviderNames.ImplementAbstractClass)>
Friend Class VisualBasicImplementInterfaceCodeFixProvider
Inherits CodeFixProvider
Friend Const BC30149 As String = "BC30149" ' Class 'bar' must implement 'Sub goo()' for interface 'igoo'.
<ImportingConstructor>
Public Sub New()
End Sub
Public NotOverridable Overrides ReadOnly Property FixableDiagnosticIds As ImmutableArray(Of String)
Get
Return ImmutableArray.Create(BC30149)
End Get
End Property
Public NotOverridable Overrides Function GetFixAllProvider() As FixAllProvider
Return WellKnownFixAllProviders.BatchFixer
End Function
Public NotOverridable Overrides Async Function RegisterCodeFixesAsync(context As CodeFixContext) As Task
Dim document = context.Document
Dim span = context.Span
Dim cancellationToken = context.CancellationToken
Dim root = Await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False)
Dim token = root.FindToken(span.Start)
If Not token.Span.IntersectsWith(span) Then
Return
End If
Dim implementsNode = token.GetAncestors(Of ImplementsStatementSyntax) _
.FirstOrDefault(Function(c) c.Span.IntersectsWith(span))
If implementsNode Is Nothing Then
Return
End If
Dim typeNode = implementsNode.Types.Where(Function(c) c.Span.IntersectsWith(span)) _
.FirstOrDefault(Function(c) c.Span.IntersectsWith(span))
If typeNode Is Nothing Then
Return
End If
Dim service = document.GetLanguageService(Of IImplementInterfaceService)()
Dim actions = service.GetCodeActions(
document,
Await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(False),
typeNode,
cancellationToken)
context.RegisterFixes(actions, context.Diagnostics)
End Function
End Class
End Namespace
|
nguerrera/roslyn
|
src/Features/VisualBasic/Portable/ImplementInterface/VisualBasicImplementInterfaceCodeFixProvider.vb
|
Visual Basic
|
apache-2.0
| 2,773
|
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.Data.Entity
Namespace EntityFramework_CodeFirst2
Class Program
Shared Sub Main(args As String())
Try
Console.WriteLine("start")
Database.SetInitializer(Of StudentContext)(Nothing)
Dim ctx As New StudentContext()
Dim t As Object = ctx.Database.SqlQuery(Of Student)("SELECT ID,FNAME,LNAME,MAJOR,MINOR FROM STUDENT_NF_SUB")
For Each item As Student In t
Console.WriteLine(item.ID & "=>" & item.FNAME & "=>" & item.LNAME & "=>" & item.MAJOR & "=>" & item.MINOR)
Next
Catch e As Exception
Dim s As String = e.Message
If e.InnerException IsNot Nothing Then
s &= e.InnerException.Message
End If
Console.WriteLine(s)
Finally
Console.WriteLine("Enter to exit:")
Dim line As String = Console.ReadLine()
End Try
End Sub
End Class
End Namespace
|
RocketSoftware/multivalue-lab
|
U2/Demos/U2-Toolkit/.NET Samples/samples/VB.NET/UniData/EntityFramework_CodeFirst2/Program.vb
|
Visual Basic
|
mit
| 1,149
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Collections.Immutable
Imports System.Composition
Imports System.Threading
Imports Microsoft.CodeAnalysis.Formatting
Imports Microsoft.CodeAnalysis.Formatting.Rules
Imports Microsoft.CodeAnalysis.Host
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.Shared.Collections
Imports Microsoft.CodeAnalysis.Text
Namespace Microsoft.CodeAnalysis.VisualBasic.Formatting
<ExportLanguageService(GetType(ISyntaxFormattingService), LanguageNames.VisualBasic), [Shared]>
Friend Class VisualBasicSyntaxFormattingService
Inherits AbstractSyntaxFormattingService
Private ReadOnly lazyExportedRules As Lazy(Of IEnumerable(Of IFormattingRule))
<ImportingConstructor>
Sub New(<ImportMany> rules As IEnumerable(Of Lazy(Of IFormattingRule, OrderableLanguageMetadata)))
Me.lazyExportedRules = New Lazy(Of IEnumerable(Of IFormattingRule))(
Function()
Return ExtensionOrderer.Order(rules).Where(Function(x) x.Metadata.Language = LanguageNames.VisualBasic).Select(Function(x) x.Value).Concat(New DefaultOperationProvider()).ToImmutableArray()
End Function)
End Sub
Public Overrides Function GetDefaultFormattingRules() As IEnumerable(Of IFormattingRule)
Return lazyExportedRules.Value
End Function
Protected Overrides Function CreateAggregatedFormattingResult(node As SyntaxNode, results As IList(Of AbstractFormattingResult), Optional formattingSpans As SimpleIntervalTree(Of TextSpan) = Nothing) As IFormattingResult
Return New AggregatedFormattingResult(node, results, formattingSpans)
End Function
Protected Overrides Function Format(root As SyntaxNode, optionSet As OptionSet, formattingRules As IEnumerable(Of IFormattingRule), token1 As SyntaxToken, token2 As SyntaxToken, cancellationToken As CancellationToken) As AbstractFormattingResult
Return New VisualBasicFormatEngine(root, optionSet, formattingRules, token1, token2).Format(cancellationToken)
End Function
End Class
End Namespace
|
ManishJayaswal/roslyn
|
src/Workspaces/VisualBasic/Portable/Formatting/VisualBasicSyntaxFormattingService.vb
|
Visual Basic
|
apache-2.0
| 2,315
|
' 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.
Imports System.Collections.Immutable
Imports System.Reflection
Imports Microsoft.CodeAnalysis.Emit
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic.Emit
Friend NotInheritable Class ModuleReference
Implements Cci.IModuleReference
Implements Cci.IFileReference
Private ReadOnly _moduleBeingBuilt As PEModuleBuilder
Private ReadOnly _underlyingModule As ModuleSymbol
Friend Sub New(moduleBeingBuilt As PEModuleBuilder, underlyingModule As ModuleSymbol)
Debug.Assert(moduleBeingBuilt IsNot Nothing)
Debug.Assert(underlyingModule IsNot Nothing)
Me._moduleBeingBuilt = moduleBeingBuilt
Me._underlyingModule = underlyingModule
End Sub
Private Sub IReferenceDispatch(visitor As Cci.MetadataVisitor) Implements Cci.IReference.Dispatch
visitor.Visit(DirectCast(Me, Cci.IModuleReference))
End Sub
Private ReadOnly Property INamedEntityName As String Implements Cci.INamedEntity.Name
Get
Return _underlyingModule.Name
End Get
End Property
Private ReadOnly Property IFileReferenceHasMetadata As Boolean Implements Cci.IFileReference.HasMetadata
Get
Return True
End Get
End Property
Private ReadOnly Property IFileReferenceFileName As String Implements Cci.IFileReference.FileName
Get
Return _underlyingModule.Name
End Get
End Property
Private Function IFileReferenceGetHashValue(algorithmId As AssemblyHashAlgorithm) As ImmutableArray(Of Byte) Implements Cci.IFileReference.GetHashValue
Return _underlyingModule.GetHash(algorithmId)
End Function
Private Function IModuleReferenceGetContainingAssembly(context As EmitContext) As Cci.IAssemblyReference Implements Cci.IModuleReference.GetContainingAssembly
If _moduleBeingBuilt.OutputKind.IsNetModule() AndAlso
_moduleBeingBuilt.SourceModule.ContainingAssembly Is _underlyingModule.ContainingAssembly Then
Return Nothing
End If
Return _moduleBeingBuilt.Translate(_underlyingModule.ContainingAssembly, context.Diagnostics)
End Function
Public Overrides Function ToString() As String
Return _underlyingModule.ToString()
End Function
Private Function IReferenceAttributes(context As EmitContext) As IEnumerable(Of Cci.ICustomAttribute) Implements Cci.IReference.GetAttributes
Return SpecializedCollections.EmptyEnumerable(Of Cci.ICustomAttribute)()
End Function
Private Function IReferenceAsDefinition(context As EmitContext) As Cci.IDefinition Implements Cci.IReference.AsDefinition
Return Nothing
End Function
End Class
End Namespace
|
jmarolf/roslyn
|
src/Compilers/VisualBasic/Portable/Emit/ModuleReference.vb
|
Visual Basic
|
mit
| 3,129
|
'-------------------------------------------------------------------------------------------'
' Inicio del codigo
'-------------------------------------------------------------------------------------------'
' Importando librerias
'-------------------------------------------------------------------------------------------'
Imports System.Data
'-------------------------------------------------------------------------------------------'
' Inicio de clase "rMInventarios_Articulos "
'-------------------------------------------------------------------------------------------'
Partial Class rMInventarios_Articulos
Inherits vis2formularios.frmReporte
Dim loObjetoReporte As CrystalDecisions.CrystalReports.Engine.ReportDocument
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
Dim lcParametro0Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(0))
Dim lcParametro0Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(0))
Dim lcParametro1Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(1), goServicios.enuOpcionesRedondeo.KN_FechaInicioDelDia)
Dim lcParametro1Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(1), goServicios.enuOpcionesRedondeo.KN_FechaFinDelDia)
Dim lcParametro2Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(2))
Dim lcParametro2Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(2))
Dim lcParametro3Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(3))
Dim lcParametro3Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(3))
Dim lcParametro4Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(4))
Dim lcParametro4Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(4))
Dim lcParametro5Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(5))
Dim lcParametro5Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(5))
Dim lcParametro6Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(6))
Dim lcParametro6Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(6))
Dim lcParametro7Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(7))
Dim lcParametro7Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(7))
Dim lcParametro8Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(8))
Dim lcParametro8Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(8))
Dim lcParametro9Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(9))
Dim lcParametro9Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(9))
Dim lcParametro10Desde As String = goServicios.mObtenerListaFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(10))
Dim lcParametro11Desde As String = goServicios.mObtenerListaFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(11))
Dim lcParametro12Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(12))
Dim lcParametro12Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(12))
Dim lcParametro13Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(13))
Dim lcParametro13Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(13))
Dim lcOrdenamiento As String = cusAplicacion.goReportes.pcOrden
Dim lcCosto As String = "Cos_Pro1"
Dim loComandoSeleccionar As New StringBuilder()
Select Case lcParametro11Desde
Case "'Promedio MP'"
lcCosto = "Cos_Pro1"
Case "'Ultimo MP'"
lcCosto = "Cos_Ult1"
Case "'Anterior MP'"
lcCosto = "Cos_Ant1"
Case "'Promedio MS'"
lcCosto = "Cos_Pro2"
Case "'Ultimo MS'"
lcCosto = "Cos_Ult2"
Case "'Anterior MS'"
lcCosto = "Cos_Ant2"
End Select
'---------------------------------------------------------------------------------------------------------------'
' El código del Almacén de Tránsito se requiere para los Traslados entre Almacénes Confirmados o Procesados. '
'---------------------------------------------------------------------------------------------------------------'
Dim lcAlmacenTransito As String
lcAlmacenTransito = goServicios.mObtenerCampoFormatoSQL(goOpciones.mObtener("CODALMTRA", "C"))
Select Case lcParametro10Desde
Case "'Todos'"
' Select de la tabla de Ajustes
loComandoSeleccionar.AppendLine("SELECT 'Ajustes' AS Operacion, ")
loComandoSeleccionar.AppendLine(" Ajustes.Documento AS Documento, ")
loComandoSeleccionar.AppendLine(" Renglones_Ajustes.Cod_Art AS Cod_Art, ")
loComandoSeleccionar.AppendLine(" Ajustes.Fec_Ini AS Fec_Ini, ")
loComandoSeleccionar.AppendLine(" Renglones_Ajustes.Renglon AS Renglon, ")
loComandoSeleccionar.AppendLine(" 'No Aplica' AS Cliente, ")
loComandoSeleccionar.AppendLine(" Renglones_Ajustes.Cod_Alm AS Cod_Alm, ")
loComandoSeleccionar.AppendLine(" (CASE WHEN Renglones_Ajustes.Tipo = 'Salida' THEN Renglones_Ajustes.Can_Art1 ELSE 0.0 END) AS Can_Sal, ")
loComandoSeleccionar.AppendLine(" (CASE WHEN Renglones_Ajustes.Tipo = 'Entrada' THEN Renglones_Ajustes.Can_Art1 ELSE 0.0 END) AS Can_Ent, ")
loComandoSeleccionar.AppendLine(" Renglones_Ajustes.Tipo AS Tipo, ")
loComandoSeleccionar.AppendLine(" Renglones_Ajustes." & lcCosto & " AS Cos_Pro, ")
loComandoSeleccionar.AppendLine(" Articulos.Nom_Art AS Nom_Art, ")
loComandoSeleccionar.AppendLine(" " & lcParametro11Desde & " AS Costo ")
loComandoSeleccionar.AppendLine("INTO #curTemporal ")
loComandoSeleccionar.AppendLine("FROM Ajustes, ")
loComandoSeleccionar.AppendLine(" Renglones_Ajustes, ")
loComandoSeleccionar.AppendLine(" Articulos ")
loComandoSeleccionar.AppendLine("WHERE Ajustes.Documento = Renglones_Ajustes.Documento ")
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Art = Renglones_Ajustes.Cod_Art ")
loComandoSeleccionar.AppendLine(" AND Ajustes.Status = 'Confirmado' ")
loComandoSeleccionar.AppendLine(" AND Renglones_Ajustes.Tipo IN ('Entrada', 'Salida') ")
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Art BETWEEN " & lcParametro0Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro0Hasta)
loComandoSeleccionar.AppendLine(" AND Ajustes.Fec_Ini BETWEEN " & lcParametro1Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro1Hasta)
loComandoSeleccionar.AppendLine(" AND Renglones_Ajustes.Cod_Alm BETWEEN " & lcParametro2Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro2Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Dep BETWEEN " & lcParametro3Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro3Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Sec BETWEEN " & lcParametro4Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro4Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Mar BETWEEN " & lcParametro5Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro5Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Cla BETWEEN " & lcParametro6Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro6Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Tip BETWEEN " & lcParametro7Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro7Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Pro BETWEEN " & lcParametro8Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro8Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Suc BETWEEN " & lcParametro9Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro9Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Uni1 BETWEEN " & lcParametro12Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro12Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Ubi BETWEEN " & lcParametro13Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro13Hasta)
' Union con Select de la tabla de Traslados en las Salidas
loComandoSeleccionar.AppendLine("UNION ALL ")
loComandoSeleccionar.AppendLine("SELECT 'Traslados' AS Operacion, ")
loComandoSeleccionar.AppendLine(" Traslados.Documento AS Documento, ")
loComandoSeleccionar.AppendLine(" Renglones_Traslados.Cod_Art AS Cod_Art, ")
loComandoSeleccionar.AppendLine(" Traslados.Fec_Ini AS Fec_Ini, ")
loComandoSeleccionar.AppendLine(" Renglones_Traslados.Renglon AS Renglon, ")
loComandoSeleccionar.AppendLine(" 'No Aplica' AS Cliente, ")
loComandoSeleccionar.AppendLine(" Traslados.Alm_Ori AS Cod_Alm, ")
loComandoSeleccionar.AppendLine(" Renglones_Traslados.Can_Art1 AS Can_Sal, ")
loComandoSeleccionar.AppendLine(" 0.0 AS Can_Ent, ")
loComandoSeleccionar.AppendLine(" 'Salida' AS Tipo, ")
loComandoSeleccionar.AppendLine(" Renglones_Traslados." & lcCosto & " AS Cos_Pro, ")
loComandoSeleccionar.AppendLine(" Articulos.Nom_Art AS Nom_Art, ")
loComandoSeleccionar.AppendLine(" " & lcParametro11Desde & " AS Costo ")
loComandoSeleccionar.AppendLine("FROM Traslados, ")
loComandoSeleccionar.AppendLine(" Renglones_Traslados, ")
loComandoSeleccionar.AppendLine(" Articulos ")
loComandoSeleccionar.AppendLine("WHERE Traslados.Documento = Renglones_Traslados.Documento ")
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Art = Renglones_Traslados.Cod_Art ")
loComandoSeleccionar.AppendLine(" AND Traslados.Status IN ('Confirmado', 'Procesado') ")
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Art BETWEEN " & lcParametro0Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro0Hasta)
loComandoSeleccionar.AppendLine(" AND Traslados.Fec_Ini BETWEEN " & lcParametro1Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro1Hasta)
loComandoSeleccionar.AppendLine(" AND Traslados.Alm_Ori BETWEEN " & lcParametro2Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro2Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Dep BETWEEN " & lcParametro3Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro3Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Sec BETWEEN " & lcParametro4Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro4Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Mar BETWEEN " & lcParametro5Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro5Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Cla BETWEEN " & lcParametro6Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro6Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Tip BETWEEN " & lcParametro7Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro7Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Pro BETWEEN " & lcParametro8Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro8Hasta)
loComandoSeleccionar.AppendLine(" AND Traslados.Cod_Suc BETWEEN " & lcParametro9Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro9Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Uni1 BETWEEN " & lcParametro12Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro12Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Ubi BETWEEN " & lcParametro13Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro13Hasta)
' Union con Select de la tabla de Traslados en las Entradas
loComandoSeleccionar.AppendLine("UNION ALL ")
loComandoSeleccionar.AppendLine("SELECT 'Traslados' AS Operacion, ")
loComandoSeleccionar.AppendLine(" Traslados.Documento AS Documento, ")
loComandoSeleccionar.AppendLine(" Renglones_Traslados.Cod_Art AS Cod_Art, ")
loComandoSeleccionar.AppendLine(" Traslados.Fec_Ini AS Fec_Ini, ")
loComandoSeleccionar.AppendLine(" Renglones_Traslados.Renglon AS Renglon, ")
loComandoSeleccionar.AppendLine(" 'No Aplica' AS Cliente, ")
loComandoSeleccionar.AppendLine(" CASE Traslados.Status ")
loComandoSeleccionar.AppendLine(" WHEN 'Confirmado' THEN " & lcAlmacenTransito)
loComandoSeleccionar.AppendLine(" WHEN 'Procesado' THEN Traslados.Alm_Des")
loComandoSeleccionar.AppendLine(" END AS Cod_Alm, ")
loComandoSeleccionar.AppendLine(" 0.0 AS Can_Sal, ")
loComandoSeleccionar.AppendLine(" Renglones_Traslados.Can_Art1 AS Can_Ent, ")
loComandoSeleccionar.AppendLine(" 'Entrada' AS Tipo, ")
loComandoSeleccionar.AppendLine(" Renglones_Traslados." & lcCosto & " AS Cos_Pro, ")
loComandoSeleccionar.AppendLine(" Articulos.Nom_Art AS Nom_Art, ")
loComandoSeleccionar.AppendLine(" " & lcParametro11Desde & " AS Costo ")
loComandoSeleccionar.AppendLine("FROM Traslados, ")
loComandoSeleccionar.AppendLine(" Renglones_Traslados, ")
loComandoSeleccionar.AppendLine(" Articulos ")
loComandoSeleccionar.AppendLine("WHERE Traslados.Documento = Renglones_Traslados.Documento ")
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Art = Renglones_Traslados.Cod_Art ")
loComandoSeleccionar.AppendLine(" AND Traslados.Status IN ('Confirmado', 'Procesado') ")
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Art BETWEEN " & lcParametro0Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro0Hasta)
loComandoSeleccionar.AppendLine(" AND Traslados.Fec_Ini BETWEEN " & lcParametro1Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro1Hasta)
loComandoSeleccionar.AppendLine(" AND (CASE Traslados.Status ")
loComandoSeleccionar.AppendLine(" WHEN 'Confirmado' THEN " & lcAlmacenTransito & "")
loComandoSeleccionar.AppendLine(" ELSE Traslados.Alm_Des " )
loComandoSeleccionar.AppendLine(" END) BETWEEN " & lcParametro2Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro2Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Dep BETWEEN " & lcParametro3Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro3Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Sec BETWEEN " & lcParametro4Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro4Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Mar BETWEEN " & lcParametro5Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro5Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Cla BETWEEN " & lcParametro6Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro6Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Tip BETWEEN " & lcParametro7Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro7Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Pro BETWEEN " & lcParametro8Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro8Hasta)
loComandoSeleccionar.AppendLine(" AND Traslados.Cod_Suc BETWEEN " & lcParametro9Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro9Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Uni1 BETWEEN " & lcParametro12Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro12Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Ubi BETWEEN " & lcParametro13Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro13Hasta)
' Union con Select de la tabla de Entregas
loComandoSeleccionar.AppendLine("UNION ALL ")
loComandoSeleccionar.AppendLine("SELECT 'Entregas' AS Operacion, ")
loComandoSeleccionar.AppendLine(" Entregas.Documento AS Documento, ")
loComandoSeleccionar.AppendLine(" Renglones_Entregas.Cod_Art AS Cod_Art, ")
loComandoSeleccionar.AppendLine(" Entregas.Fec_Ini AS Fec_Ini, ")
loComandoSeleccionar.AppendLine(" Renglones_Entregas.Renglon AS Renglon, ")
loComandoSeleccionar.AppendLine(" Entregas.Cod_Cli AS Cliente, ")
loComandoSeleccionar.AppendLine(" Renglones_Entregas.Cod_Alm AS Cod_Alm, ")
loComandoSeleccionar.AppendLine(" Renglones_Entregas.Can_Art1 AS Can_Sal, ")
loComandoSeleccionar.AppendLine(" 0.0 AS Can_Ent, ")
loComandoSeleccionar.AppendLine(" 'Salida' AS Tipo, ")
loComandoSeleccionar.AppendLine(" Renglones_Entregas." & lcCosto & " AS Cos_Pro, ")
loComandoSeleccionar.AppendLine(" Articulos.Nom_Art AS Nom_Art, ")
loComandoSeleccionar.AppendLine(" " & lcParametro11Desde & " AS Costo ")
loComandoSeleccionar.AppendLine("FROM Entregas, ")
loComandoSeleccionar.AppendLine(" Renglones_Entregas, ")
loComandoSeleccionar.AppendLine(" Articulos ")
loComandoSeleccionar.AppendLine("WHERE Entregas.Documento = Renglones_Entregas.Documento ")
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Art = Renglones_Entregas.Cod_Art ")
loComandoSeleccionar.AppendLine(" AND Entregas.Status IN ('Confirmado', 'Afectado', 'Procesado') ")
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Art BETWEEN " & lcParametro0Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro0Hasta)
loComandoSeleccionar.AppendLine(" AND Entregas.Fec_Ini BETWEEN " & lcParametro1Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro1Hasta)
loComandoSeleccionar.AppendLine(" AND Renglones_Entregas.Cod_Alm BETWEEN " & lcParametro2Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro2Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Dep BETWEEN " & lcParametro3Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro3Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Sec BETWEEN " & lcParametro4Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro4Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Mar BETWEEN " & lcParametro5Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro5Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Cla BETWEEN " & lcParametro6Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro6Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Tip BETWEEN " & lcParametro7Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro7Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Pro BETWEEN " & lcParametro8Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro8Hasta)
loComandoSeleccionar.AppendLine(" AND Entregas.Cod_Suc BETWEEN " & lcParametro9Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro9Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Uni1 BETWEEN " & lcParametro12Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro12Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Ubi BETWEEN " & lcParametro13Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro13Hasta)
' Union con Select de la tabla de Facturas
loComandoSeleccionar.AppendLine("UNION ALL ")
loComandoSeleccionar.AppendLine("SELECT 'Facturas' AS Operacion, ")
loComandoSeleccionar.AppendLine(" Facturas.Documento AS Documento, ")
loComandoSeleccionar.AppendLine(" Renglones_Facturas.Cod_Art AS Cod_Art, ")
loComandoSeleccionar.AppendLine(" Facturas.Fec_Ini AS Fec_Ini, ")
loComandoSeleccionar.AppendLine(" Renglones_Facturas.Renglon AS Renglon, ")
loComandoSeleccionar.AppendLine(" Facturas.Cod_Cli AS Cliente, ")
loComandoSeleccionar.AppendLine(" Renglones_Facturas.Cod_Alm AS Cod_Alm, ")
loComandoSeleccionar.AppendLine(" Renglones_Facturas.Can_Art1 AS Can_Sal, ")
loComandoSeleccionar.AppendLine(" 0.0 AS Can_Ent, ")
loComandoSeleccionar.AppendLine(" 'Salida' AS Tipo, ")
loComandoSeleccionar.AppendLine(" Renglones_Facturas." & lcCosto & " AS Cos_Pro, ")
loComandoSeleccionar.AppendLine(" Articulos.Nom_Art AS Nom_Art, ")
loComandoSeleccionar.AppendLine(" " & lcParametro11Desde & " AS Costo ")
loComandoSeleccionar.AppendLine("FROM Facturas, ")
loComandoSeleccionar.AppendLine(" Renglones_Facturas, ")
loComandoSeleccionar.AppendLine(" Articulos ")
loComandoSeleccionar.AppendLine("WHERE Facturas.Documento = Renglones_Facturas.Documento ")
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Art = Renglones_Facturas.Cod_Art ")
loComandoSeleccionar.AppendLine(" AND Facturas.Status IN ('Confirmado', 'Afectado', 'Procesado') ")
loComandoSeleccionar.AppendLine(" AND Renglones_Facturas.Tip_Ori <> 'Entregas' ")
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Art BETWEEN " & lcParametro0Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro0Hasta)
loComandoSeleccionar.AppendLine(" AND Facturas.Fec_Ini BETWEEN " & lcParametro1Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro1Hasta)
loComandoSeleccionar.AppendLine(" AND Renglones_Facturas.Cod_Alm BETWEEN " & lcParametro2Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro2Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Dep BETWEEN " & lcParametro3Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro3Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Sec BETWEEN " & lcParametro4Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro4Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Mar BETWEEN " & lcParametro5Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro5Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Cla BETWEEN " & lcParametro6Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro6Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Tip BETWEEN " & lcParametro7Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro7Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Pro BETWEEN " & lcParametro8Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro8Hasta)
loComandoSeleccionar.AppendLine(" AND Facturas.Cod_Suc BETWEEN " & lcParametro9Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro9Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Uni1 BETWEEN " & lcParametro12Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro12Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Ubi BETWEEN " & lcParametro13Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro13Hasta)
' Union con Select de la tabla de Recepciones
loComandoSeleccionar.AppendLine("UNION ALL ")
loComandoSeleccionar.AppendLine("SELECT 'Recepciones' AS Operacion, ")
loComandoSeleccionar.AppendLine(" Recepciones.Documento AS Documento, ")
loComandoSeleccionar.AppendLine(" Renglones_Recepciones.Cod_Art AS Cod_Art, ")
loComandoSeleccionar.AppendLine(" Recepciones.Fec_Ini AS Fec_Ini, ")
loComandoSeleccionar.AppendLine(" Renglones_Recepciones.Renglon AS Renglon, ")
loComandoSeleccionar.AppendLine(" Recepciones.Cod_Pro AS Cliente, ")
loComandoSeleccionar.AppendLine(" Renglones_Recepciones.Cod_Alm AS Cod_Alm, ")
loComandoSeleccionar.AppendLine(" 0.0 AS Can_Sal, ")
loComandoSeleccionar.AppendLine(" Renglones_Recepciones.Can_Art1 AS Can_Ent, ")
loComandoSeleccionar.AppendLine(" 'Entrada' AS Tipo, ")
loComandoSeleccionar.AppendLine(" Renglones_Recepciones." & lcCosto & " AS Cos_Pro, ")
loComandoSeleccionar.AppendLine(" Articulos.Nom_Art AS Nom_Art, ")
loComandoSeleccionar.AppendLine(" " & lcParametro11Desde & " AS Costo ")
loComandoSeleccionar.AppendLine("FROM Recepciones, ")
loComandoSeleccionar.AppendLine(" Renglones_Recepciones, ")
loComandoSeleccionar.AppendLine(" Articulos ")
loComandoSeleccionar.AppendLine("WHERE Recepciones.Documento = Renglones_Recepciones.Documento ")
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Art = Renglones_Recepciones.Cod_Art ")
loComandoSeleccionar.AppendLine(" AND Recepciones.Status IN ('Confirmado', 'Afectado', 'Procesado') ")
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Art BETWEEN " & lcParametro0Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro0Hasta)
loComandoSeleccionar.AppendLine(" AND Recepciones.Fec_Ini BETWEEN " & lcParametro1Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro1Hasta)
loComandoSeleccionar.AppendLine(" AND Renglones_Recepciones.Cod_Alm BETWEEN " & lcParametro2Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro2Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Dep BETWEEN " & lcParametro3Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro3Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Sec BETWEEN " & lcParametro4Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro4Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Mar BETWEEN " & lcParametro5Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro5Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Cla BETWEEN " & lcParametro6Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro6Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Tip BETWEEN " & lcParametro7Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro7Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Pro BETWEEN " & lcParametro8Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro8Hasta)
loComandoSeleccionar.AppendLine(" AND Recepciones.Cod_Suc BETWEEN " & lcParametro9Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro9Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Uni1 BETWEEN " & lcParametro12Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro12Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Ubi BETWEEN " & lcParametro13Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro13Hasta)
' Union con Select de la tabla de Compras
loComandoSeleccionar.AppendLine("UNION ALL ")
loComandoSeleccionar.AppendLine("SELECT 'Compras' AS Operacion, ")
loComandoSeleccionar.AppendLine(" Compras.Documento AS Documento, ")
loComandoSeleccionar.AppendLine(" Renglones_Compras.Cod_Art AS Cod_Art, ")
loComandoSeleccionar.AppendLine(" Compras.Fec_Ini AS Fec_Ini, ")
loComandoSeleccionar.AppendLine(" Renglones_Compras.Renglon AS Renglon, ")
loComandoSeleccionar.AppendLine(" Compras.Cod_Pro AS Cliente, ")
loComandoSeleccionar.AppendLine(" Renglones_Compras.Cod_Alm AS Cod_Alm, ")
loComandoSeleccionar.AppendLine(" 0.0 AS Can_Sal, ")
loComandoSeleccionar.AppendLine(" Renglones_Compras.Can_Art1 AS Can_Ent, ")
loComandoSeleccionar.AppendLine(" 'Entrada' AS Tipo, ")
loComandoSeleccionar.AppendLine(" Renglones_Compras." & lcCosto & " AS Cos_Pro, ")
loComandoSeleccionar.AppendLine(" Articulos.Nom_Art AS Nom_Art, ")
loComandoSeleccionar.AppendLine(" " & lcParametro11Desde & " AS Costo ")
loComandoSeleccionar.AppendLine("FROM Compras, ")
loComandoSeleccionar.AppendLine(" Renglones_Compras, ")
loComandoSeleccionar.AppendLine(" Articulos ")
loComandoSeleccionar.AppendLine("WHERE Compras.Documento = Renglones_Compras.Documento ")
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Art = Renglones_Compras.Cod_Art ")
loComandoSeleccionar.AppendLine(" AND Compras.Status IN ('Confirmado', 'Afectado', 'Procesado') ")
loComandoSeleccionar.AppendLine(" AND Renglones_Compras.Tip_Ori <> 'Recepciones' ")
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Art BETWEEN " & lcParametro0Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro0Hasta)
loComandoSeleccionar.AppendLine(" AND Compras.Fec_Ini BETWEEN " & lcParametro1Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro1Hasta)
loComandoSeleccionar.AppendLine(" AND Renglones_Compras.Cod_Alm BETWEEN " & lcParametro2Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro2Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Dep BETWEEN " & lcParametro3Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro3Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Sec BETWEEN " & lcParametro4Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro4Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Mar BETWEEN " & lcParametro5Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro5Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Cla BETWEEN " & lcParametro6Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro6Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Tip BETWEEN " & lcParametro7Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro7Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Pro BETWEEN " & lcParametro8Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro8Hasta)
loComandoSeleccionar.AppendLine(" AND Compras.Cod_Suc BETWEEN " & lcParametro9Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro9Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Uni1 BETWEEN " & lcParametro12Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro12Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Ubi BETWEEN " & lcParametro13Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro13Hasta)
' Union con Select de la tabla de Devoluciones_Clientes
loComandoSeleccionar.AppendLine("UNION ALL ")
loComandoSeleccionar.AppendLine("SELECT 'Dev_Cli' AS Operacion, ")
loComandoSeleccionar.AppendLine(" Devoluciones_Clientes.Documento AS Documento, ")
loComandoSeleccionar.AppendLine(" Renglones_DClientes.Cod_Art AS Cod_Art, ")
loComandoSeleccionar.AppendLine(" Devoluciones_Clientes.Fec_Ini AS Fec_Ini, ")
loComandoSeleccionar.AppendLine(" Renglones_DClientes.Renglon AS Renglon, ")
loComandoSeleccionar.AppendLine(" Devoluciones_Clientes.Cod_Cli AS Cliente, ")
loComandoSeleccionar.AppendLine(" Renglones_DClientes.Cod_Alm AS Cod_Alm, ")
loComandoSeleccionar.AppendLine(" 0.0 AS Can_Sal, ")
loComandoSeleccionar.AppendLine(" Renglones_DClientes.Can_Art1 AS Can_Ent, ")
loComandoSeleccionar.AppendLine(" 'Entrada' AS Tipo, ")
loComandoSeleccionar.AppendLine(" Renglones_DClientes." & lcCosto & " AS Cos_Pro, ")
loComandoSeleccionar.AppendLine(" Articulos.Nom_Art AS Nom_Art, ")
loComandoSeleccionar.AppendLine(" " & lcParametro11Desde & " AS Costo ")
loComandoSeleccionar.AppendLine("FROM Devoluciones_Clientes, ")
loComandoSeleccionar.AppendLine(" Renglones_DClientes, ")
loComandoSeleccionar.AppendLine(" Articulos ")
loComandoSeleccionar.AppendLine("WHERE Devoluciones_Clientes.Documento = Renglones_DClientes.Documento ")
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Art = Renglones_DClientes.Cod_Art ")
loComandoSeleccionar.AppendLine(" AND Devoluciones_Clientes.Status IN ('Confirmado', 'Afectado', 'Procesado') ")
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Art BETWEEN " & lcParametro0Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro0Hasta)
loComandoSeleccionar.AppendLine(" AND Devoluciones_Clientes.Fec_Ini BETWEEN " & lcParametro1Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro1Hasta)
loComandoSeleccionar.AppendLine(" AND Renglones_DClientes.Cod_Alm BETWEEN " & lcParametro2Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro2Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Dep BETWEEN " & lcParametro3Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro3Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Sec BETWEEN " & lcParametro4Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro4Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Mar BETWEEN " & lcParametro5Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro5Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Cla BETWEEN " & lcParametro6Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro6Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Tip BETWEEN " & lcParametro7Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro7Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Pro BETWEEN " & lcParametro8Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro8Hasta)
loComandoSeleccionar.AppendLine(" AND Devoluciones_Clientes.Cod_Suc BETWEEN " & lcParametro9Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro9Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Uni1 BETWEEN " & lcParametro12Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro12Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Ubi BETWEEN " & lcParametro13Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro13Hasta)
' Union con Select de la tabla de Devoluciones_Proveedores
loComandoSeleccionar.AppendLine("UNION ALL ")
loComandoSeleccionar.AppendLine("SELECT 'Dev_Pro' AS Operacion, ")
loComandoSeleccionar.AppendLine(" Devoluciones_Proveedores.Documento AS Documento, ")
loComandoSeleccionar.AppendLine(" Renglones_DProveedores.Cod_Art AS Cod_Art, ")
loComandoSeleccionar.AppendLine(" Devoluciones_Proveedores.Fec_Ini AS Fec_Ini, ")
loComandoSeleccionar.AppendLine(" Renglones_DProveedores.Renglon AS Renglon, ")
loComandoSeleccionar.AppendLine(" Devoluciones_Proveedores.Cod_Pro AS Cliente, ")
loComandoSeleccionar.AppendLine(" Renglones_DProveedores.Cod_Alm AS Cod_Alm, ")
loComandoSeleccionar.AppendLine(" Renglones_DProveedores.Can_Art1 AS Can_Sal, ")
loComandoSeleccionar.AppendLine(" 0.0 AS Can_Ent, ")
loComandoSeleccionar.AppendLine(" 'Salida' AS Tipo, ")
loComandoSeleccionar.AppendLine(" Renglones_DProveedores." & lcCosto & " AS Cos_Pro, ")
loComandoSeleccionar.AppendLine(" Articulos.Nom_Art AS Nom_Art, ")
loComandoSeleccionar.AppendLine(" " & lcParametro11Desde & " AS Costo ")
loComandoSeleccionar.AppendLine("FROM Devoluciones_Proveedores, ")
loComandoSeleccionar.AppendLine(" Renglones_DProveedores, ")
loComandoSeleccionar.AppendLine(" Articulos ")
loComandoSeleccionar.AppendLine("WHERE Devoluciones_Proveedores.Documento = Renglones_DProveedores.Documento ")
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Art = Renglones_DProveedores.Cod_Art ")
loComandoSeleccionar.AppendLine(" AND Devoluciones_Proveedores.Status IN ('Confirmado', 'Afectado', 'Procesado') ")
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Art BETWEEN " & lcParametro0Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro0Hasta)
loComandoSeleccionar.AppendLine(" AND Devoluciones_Proveedores.Fec_Ini BETWEEN " & lcParametro1Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro1Hasta)
loComandoSeleccionar.AppendLine(" AND Renglones_DProveedores.Cod_Alm BETWEEN " & lcParametro2Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro2Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Dep BETWEEN " & lcParametro3Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro3Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Sec BETWEEN " & lcParametro4Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro4Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Mar BETWEEN " & lcParametro5Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro5Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Cla BETWEEN " & lcParametro6Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro6Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Tip BETWEEN " & lcParametro7Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro7Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Pro BETWEEN " & lcParametro8Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro8Hasta)
loComandoSeleccionar.AppendLine(" AND Devoluciones_Proveedores.Cod_Suc BETWEEN " & lcParametro9Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro9Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Uni1 BETWEEN " & lcParametro12Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro12Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Ubi BETWEEN " & lcParametro13Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro13Hasta)
Case "'Ajustes_Entrada'"
' Select de la tabla de Ajustes solo para las Entradas
loComandoSeleccionar.AppendLine("SELECT 'Ajustes' AS Operacion, ")
loComandoSeleccionar.AppendLine(" Ajustes.Documento AS Documento, ")
loComandoSeleccionar.AppendLine(" Renglones_Ajustes.Cod_Art AS Cod_Art, ")
loComandoSeleccionar.AppendLine(" Ajustes.Fec_Ini AS Fec_Ini, ")
loComandoSeleccionar.AppendLine(" Renglones_Ajustes.Renglon AS Renglon, ")
loComandoSeleccionar.AppendLine(" 'No Aplica' AS Cliente, ")
loComandoSeleccionar.AppendLine(" Renglones_Ajustes.Cod_Alm AS Cod_Alm, ")
loComandoSeleccionar.AppendLine(" 0.00 AS Can_Sal, ")
loComandoSeleccionar.AppendLine(" Renglones_Ajustes.Can_Art1 AS Can_Ent, ")
loComandoSeleccionar.AppendLine(" Renglones_Ajustes.Tipo AS Tipo, ")
loComandoSeleccionar.AppendLine(" Renglones_Ajustes." & lcCosto & " AS Cos_Pro, ")
loComandoSeleccionar.AppendLine(" Articulos.Nom_Art AS Nom_Art, ")
loComandoSeleccionar.AppendLine(" " & lcParametro11Desde & " AS Costo ")
loComandoSeleccionar.AppendLine("INTO #curTemporal ")
loComandoSeleccionar.AppendLine("FROM Ajustes, ")
loComandoSeleccionar.AppendLine(" Renglones_Ajustes, ")
loComandoSeleccionar.AppendLine(" Articulos ")
loComandoSeleccionar.AppendLine("WHERE Ajustes.Documento = Renglones_Ajustes.Documento ")
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Art = Renglones_Ajustes.Cod_Art ")
loComandoSeleccionar.AppendLine(" AND Renglones_Ajustes.Tipo = 'Entrada' ")
loComandoSeleccionar.AppendLine(" AND Ajustes.Status = 'Confirmado' ")
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Art BETWEEN " & lcParametro0Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro0Hasta)
loComandoSeleccionar.AppendLine(" AND Ajustes.Fec_Ini BETWEEN " & lcParametro1Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro1Hasta)
loComandoSeleccionar.AppendLine(" AND Renglones_Ajustes.Cod_Alm BETWEEN " & lcParametro2Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro2Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Dep BETWEEN " & lcParametro3Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro3Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Sec BETWEEN " & lcParametro4Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro4Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Mar BETWEEN " & lcParametro5Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro5Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Cla BETWEEN " & lcParametro6Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro6Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Tip BETWEEN " & lcParametro7Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro7Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Pro BETWEEN " & lcParametro8Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro8Hasta)
loComandoSeleccionar.AppendLine(" AND Ajustes.Cod_Suc BETWEEN " & lcParametro9Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro9Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Uni1 BETWEEN " & lcParametro12Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro12Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Ubi BETWEEN " & lcParametro13Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro13Hasta)
Case "'Ajustes_Salida'"
' Select de la tabla de Ajustes solo para las Salidas
loComandoSeleccionar.AppendLine("SELECT 'Ajustes' AS Operacion, ")
loComandoSeleccionar.AppendLine(" Ajustes.Documento AS Documento, ")
loComandoSeleccionar.AppendLine(" Renglones_Ajustes.Cod_Art AS Cod_Art, ")
loComandoSeleccionar.AppendLine(" Ajustes.Fec_Ini AS Fec_Ini, ")
loComandoSeleccionar.AppendLine(" Renglones_Ajustes.Renglon AS Renglon, ")
loComandoSeleccionar.AppendLine(" 'No Aplica' AS Cliente, ")
loComandoSeleccionar.AppendLine(" Renglones_Ajustes.Cod_Alm AS Cod_Alm, ")
loComandoSeleccionar.AppendLine(" Renglones_Ajustes.Can_Art1 AS Can_Sal, ")
loComandoSeleccionar.AppendLine(" 0.00 AS Can_Ent, ")
loComandoSeleccionar.AppendLine(" Renglones_Ajustes.Tipo AS Tipo, ")
loComandoSeleccionar.AppendLine(" Renglones_Ajustes." & lcCosto & " AS Cos_Pro, ")
loComandoSeleccionar.AppendLine(" Articulos.Nom_Art AS Nom_Art, ")
loComandoSeleccionar.AppendLine(" " & lcParametro11Desde & " AS Costo ")
loComandoSeleccionar.AppendLine("INTO #curTemporal ")
loComandoSeleccionar.AppendLine("FROM Ajustes, ")
loComandoSeleccionar.AppendLine(" Renglones_Ajustes, ")
loComandoSeleccionar.AppendLine(" Articulos ")
loComandoSeleccionar.AppendLine("WHERE Ajustes.Documento = Renglones_Ajustes.Documento ")
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Art = Renglones_Ajustes.Cod_Art ")
loComandoSeleccionar.AppendLine(" AND Renglones_Ajustes.Tipo = 'Salida' ")
loComandoSeleccionar.AppendLine(" AND Ajustes.Status = 'Confirmado' ")
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Art BETWEEN " & lcParametro0Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro0Hasta)
loComandoSeleccionar.AppendLine(" AND Ajustes.Fec_Ini BETWEEN " & lcParametro1Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro1Hasta)
loComandoSeleccionar.AppendLine(" AND Renglones_Ajustes.Cod_Alm BETWEEN " & lcParametro2Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro2Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Dep BETWEEN " & lcParametro3Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro3Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Sec BETWEEN " & lcParametro4Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro4Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Mar BETWEEN " & lcParametro5Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro5Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Cla BETWEEN " & lcParametro6Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro6Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Tip BETWEEN " & lcParametro7Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro7Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Pro BETWEEN " & lcParametro8Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro8Hasta)
loComandoSeleccionar.AppendLine(" AND Ajustes.Cod_Suc BETWEEN " & lcParametro9Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro9Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Uni1 BETWEEN " & lcParametro12Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro12Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Ubi BETWEEN " & lcParametro13Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro13Hasta)
Case "'Traslados_Salida'"
' Union con Select de la tabla de Traslados en las Salidas
loComandoSeleccionar.AppendLine("SELECT 'Traslados' AS Operacion, ")
loComandoSeleccionar.AppendLine(" Traslados.Documento AS Documento, ")
loComandoSeleccionar.AppendLine(" Renglones_Traslados.Cod_Art AS Cod_Art, ")
loComandoSeleccionar.AppendLine(" Traslados.Fec_Ini AS Fec_Ini, ")
loComandoSeleccionar.AppendLine(" Renglones_Traslados.Renglon AS Renglon, ")
loComandoSeleccionar.AppendLine(" 'No Aplica' AS Cliente, ")
loComandoSeleccionar.AppendLine(" Traslados.Alm_Ori AS Cod_Alm, ")
loComandoSeleccionar.AppendLine(" Renglones_Traslados.Can_Art1 AS Can_Sal, ")
loComandoSeleccionar.AppendLine(" 0.0 AS Can_Ent, ")
loComandoSeleccionar.AppendLine(" 'Salida' AS Tipo, ")
loComandoSeleccionar.AppendLine(" Renglones_Traslados." & lcCosto & " AS Cos_Pro, ")
loComandoSeleccionar.AppendLine(" Articulos.Nom_Art AS Nom_Art, ")
loComandoSeleccionar.AppendLine(" " & lcParametro11Desde & " AS Costo ")
loComandoSeleccionar.AppendLine("INTO #curTemporal ")
loComandoSeleccionar.AppendLine("FROM Traslados, ")
loComandoSeleccionar.AppendLine(" Renglones_Traslados, ")
loComandoSeleccionar.AppendLine(" Articulos ")
loComandoSeleccionar.AppendLine("WHERE Traslados.Documento = Renglones_Traslados.Documento ")
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Art = Renglones_Traslados.Cod_Art ")
loComandoSeleccionar.AppendLine(" AND Traslados.Status IN ('Confirmado', 'Procesado') ")
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Art BETWEEN " & lcParametro0Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro0Hasta)
loComandoSeleccionar.AppendLine(" AND Traslados.Fec_Ini BETWEEN " & lcParametro1Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro1Hasta)
loComandoSeleccionar.AppendLine(" AND Traslados.Alm_Ori BETWEEN " & lcParametro2Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro2Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Dep BETWEEN " & lcParametro3Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro3Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Sec BETWEEN " & lcParametro4Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro4Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Mar BETWEEN " & lcParametro5Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro5Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Cla BETWEEN " & lcParametro6Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro6Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Tip BETWEEN " & lcParametro7Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro7Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Pro BETWEEN " & lcParametro8Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro8Hasta)
loComandoSeleccionar.AppendLine(" AND Traslados.Cod_Suc BETWEEN " & lcParametro9Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro9Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Uni1 BETWEEN " & lcParametro12Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro12Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Ubi BETWEEN " & lcParametro13Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro13Hasta)
Case "'Traslados_Entrada'"
' Union con Select de la tabla de Traslados en las Entradas
loComandoSeleccionar.AppendLine("SELECT 'Traslados' AS Operacion, ")
loComandoSeleccionar.AppendLine(" Traslados.Documento AS Documento, ")
loComandoSeleccionar.AppendLine(" Renglones_Traslados.Cod_Art AS Cod_Art, ")
loComandoSeleccionar.AppendLine(" Traslados.Fec_Ini AS Fec_Ini, ")
loComandoSeleccionar.AppendLine(" Renglones_Traslados.Renglon AS Renglon, ")
loComandoSeleccionar.AppendLine(" 'No Aplica' AS Cliente, ")
loComandoSeleccionar.AppendLine(" CASE Traslados.Status ")
loComandoSeleccionar.AppendLine(" WHEN 'Confirmado' THEN " & lcAlmacenTransito)
loComandoSeleccionar.AppendLine(" WHEN 'Procesado' THEN Traslados.Alm_Des")
loComandoSeleccionar.AppendLine(" END AS Cod_Alm, ")
loComandoSeleccionar.AppendLine(" 0.0 AS Can_Sal, ")
loComandoSeleccionar.AppendLine(" Renglones_Traslados.Can_Art1 AS Can_Ent, ")
loComandoSeleccionar.AppendLine(" 'Entrada' AS Tipo, ")
loComandoSeleccionar.AppendLine(" Renglones_Traslados." & lcCosto & " AS Cos_Pro, ")
loComandoSeleccionar.AppendLine(" Articulos.Nom_Art AS Nom_Art, ")
loComandoSeleccionar.AppendLine(" " & lcParametro11Desde & " AS Costo ")
loComandoSeleccionar.AppendLine("INTO #curTemporal ")
loComandoSeleccionar.AppendLine("FROM Traslados, ")
loComandoSeleccionar.AppendLine(" Renglones_Traslados, ")
loComandoSeleccionar.AppendLine(" Articulos ")
loComandoSeleccionar.AppendLine("WHERE Traslados.Documento = Renglones_Traslados.Documento ")
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Art = Renglones_Traslados.Cod_Art ")
loComandoSeleccionar.AppendLine(" AND Traslados.Status IN ('Confirmado', 'Procesado') ")
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Art BETWEEN " & lcParametro0Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro0Hasta)
loComandoSeleccionar.AppendLine(" AND Traslados.Fec_Ini BETWEEN " & lcParametro1Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro1Hasta)
loComandoSeleccionar.AppendLine(" AND (CASE Traslados.Status ")
loComandoSeleccionar.AppendLine(" WHEN 'Confirmado' THEN " & lcAlmacenTransito & "")
loComandoSeleccionar.AppendLine(" ELSE Traslados.Alm_Des " )
loComandoSeleccionar.AppendLine(" END) BETWEEN " & lcParametro2Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro2Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Dep BETWEEN " & lcParametro3Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro3Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Sec BETWEEN " & lcParametro4Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro4Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Mar BETWEEN " & lcParametro5Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro5Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Cla BETWEEN " & lcParametro6Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro6Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Tip BETWEEN " & lcParametro7Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro7Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Pro BETWEEN " & lcParametro8Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro8Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Suc BETWEEN " & lcParametro9Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro9Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Uni1 BETWEEN " & lcParametro12Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro12Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Ubi BETWEEN " & lcParametro13Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro13Hasta)
Case "'Facturas_Venta'"
' Union con Select de la tabla de Facturas
loComandoSeleccionar.AppendLine("SELECT 'Facturas' AS Operacion, ")
loComandoSeleccionar.AppendLine(" Facturas.Documento AS Documento, ")
loComandoSeleccionar.AppendLine(" Renglones_Facturas.Cod_Art AS Cod_Art, ")
loComandoSeleccionar.AppendLine(" Facturas.Fec_Ini AS Fec_Ini, ")
loComandoSeleccionar.AppendLine(" Renglones_Facturas.Renglon AS Renglon, ")
loComandoSeleccionar.AppendLine(" Facturas.Cod_Cli AS Cliente, ")
loComandoSeleccionar.AppendLine(" Renglones_Facturas.Cod_Alm AS Cod_Alm, ")
loComandoSeleccionar.AppendLine(" Renglones_Facturas.Can_Art1 AS Can_Sal, ")
loComandoSeleccionar.AppendLine(" 0.0 AS Can_Ent, ")
loComandoSeleccionar.AppendLine(" 'Salida' AS Tipo, ")
loComandoSeleccionar.AppendLine(" Renglones_Facturas." & lcCosto & " AS Cos_Pro, ")
loComandoSeleccionar.AppendLine(" Articulos.Nom_Art AS Nom_Art, ")
loComandoSeleccionar.AppendLine(" " & lcParametro11Desde & " AS Costo ")
loComandoSeleccionar.AppendLine("INTO #curTemporal ")
loComandoSeleccionar.AppendLine("FROM Facturas, ")
loComandoSeleccionar.AppendLine(" Renglones_Facturas, ")
loComandoSeleccionar.AppendLine(" Articulos ")
loComandoSeleccionar.AppendLine("WHERE Facturas.Documento = Renglones_Facturas.Documento ")
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Art = Renglones_Facturas.Cod_Art ")
loComandoSeleccionar.AppendLine(" AND Facturas.Status IN ('Confirmado', 'Afectado', 'Procesado') ")
loComandoSeleccionar.AppendLine(" AND Renglones_Facturas.Tip_Ori <> 'Entregas' ")
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Art BETWEEN " & lcParametro0Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro0Hasta)
loComandoSeleccionar.AppendLine(" AND Facturas.Fec_Ini BETWEEN " & lcParametro1Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro1Hasta)
loComandoSeleccionar.AppendLine(" AND Renglones_Facturas.Cod_Alm BETWEEN " & lcParametro2Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro2Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Dep BETWEEN " & lcParametro3Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro3Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Sec BETWEEN " & lcParametro4Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro4Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Mar BETWEEN " & lcParametro5Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro5Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Cla BETWEEN " & lcParametro6Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro6Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Tip BETWEEN " & lcParametro7Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro7Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Pro BETWEEN " & lcParametro8Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro8Hasta)
loComandoSeleccionar.AppendLine(" AND Facturas.Cod_Suc BETWEEN " & lcParametro9Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro9Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Uni1 BETWEEN " & lcParametro12Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro12Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Ubi BETWEEN " & lcParametro13Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro13Hasta)
Case "'Facturas_Compra'"
' Union con Select de la tabla de Compras
loComandoSeleccionar.AppendLine("SELECT 'Compras' AS Operacion, ")
loComandoSeleccionar.AppendLine(" Compras.Documento AS Documento, ")
loComandoSeleccionar.AppendLine(" Renglones_Compras.Cod_Art AS Cod_Art, ")
loComandoSeleccionar.AppendLine(" Compras.Fec_Ini AS Fec_Ini, ")
loComandoSeleccionar.AppendLine(" Renglones_Compras.Renglon AS Renglon, ")
loComandoSeleccionar.AppendLine(" Compras.Cod_Pro AS Cliente, ")
loComandoSeleccionar.AppendLine(" Renglones_Compras.Cod_Alm AS Cod_Alm, ")
loComandoSeleccionar.AppendLine(" 0.0 AS Can_Sal, ")
loComandoSeleccionar.AppendLine(" Renglones_Compras.Can_Art1 AS Can_Ent, ")
loComandoSeleccionar.AppendLine(" 'Entrada' AS Tipo, ")
loComandoSeleccionar.AppendLine(" Renglones_Compras." & lcCosto & " AS Cos_Pro, ")
loComandoSeleccionar.AppendLine(" Articulos.Nom_Art AS Nom_Art, ")
loComandoSeleccionar.AppendLine(" " & lcParametro11Desde & " AS Costo ")
loComandoSeleccionar.AppendLine("INTO #curTemporal ")
loComandoSeleccionar.AppendLine("FROM Compras, ")
loComandoSeleccionar.AppendLine(" Renglones_Compras, ")
loComandoSeleccionar.AppendLine(" Articulos ")
loComandoSeleccionar.AppendLine("WHERE Compras.Documento = Renglones_Compras.Documento ")
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Art = Renglones_Compras.Cod_Art ")
loComandoSeleccionar.AppendLine(" AND Compras.Status IN ('Confirmado', 'Afectado', 'Procesado') ")
loComandoSeleccionar.AppendLine(" AND Renglones_Compras.Tip_Ori <> 'Recepciones' ")
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Art BETWEEN " & lcParametro0Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro0Hasta)
loComandoSeleccionar.AppendLine(" AND Compras.Fec_Ini BETWEEN " & lcParametro1Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro1Hasta)
loComandoSeleccionar.AppendLine(" AND Renglones_Compras.Cod_Alm BETWEEN " & lcParametro2Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro2Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Dep BETWEEN " & lcParametro3Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro3Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Sec BETWEEN " & lcParametro4Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro4Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Mar BETWEEN " & lcParametro5Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro5Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Cla BETWEEN " & lcParametro6Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro6Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Tip BETWEEN " & lcParametro7Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro7Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Pro BETWEEN " & lcParametro8Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro8Hasta)
loComandoSeleccionar.AppendLine(" AND Compras.Cod_Suc BETWEEN " & lcParametro9Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro9Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Uni1 BETWEEN " & lcParametro12Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro12Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Ubi BETWEEN " & lcParametro13Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro13Hasta)
Case "'Notas_Entrega'"
' Union con Select de la tabla de Entregas
loComandoSeleccionar.AppendLine("SELECT 'Entregas' AS Operacion, ")
loComandoSeleccionar.AppendLine(" Entregas.Documento AS Documento, ")
loComandoSeleccionar.AppendLine(" Renglones_Entregas.Cod_Art AS Cod_Art, ")
loComandoSeleccionar.AppendLine(" Entregas.Fec_Ini AS Fec_Ini, ")
loComandoSeleccionar.AppendLine(" Renglones_Entregas.Renglon AS Renglon, ")
loComandoSeleccionar.AppendLine(" Entregas.Cod_Cli AS Cliente, ")
loComandoSeleccionar.AppendLine(" Renglones_Entregas.Cod_Alm AS Cod_Alm, ")
loComandoSeleccionar.AppendLine(" 0.0 AS Can_Sal, ")
loComandoSeleccionar.AppendLine(" Renglones_Entregas.Can_Art1 AS Can_Ent, ")
loComandoSeleccionar.AppendLine(" 'Salida' AS Tipo, ")
loComandoSeleccionar.AppendLine(" Renglones_Entregas." & lcCosto & " AS Cos_Pro, ")
loComandoSeleccionar.AppendLine(" Articulos.Nom_Art AS Nom_Art, ")
loComandoSeleccionar.AppendLine(" " & lcParametro11Desde & " AS Costo ")
loComandoSeleccionar.AppendLine("INTO #curTemporal ")
loComandoSeleccionar.AppendLine("FROM Entregas, ")
loComandoSeleccionar.AppendLine(" Renglones_Entregas, ")
loComandoSeleccionar.AppendLine(" Articulos ")
loComandoSeleccionar.AppendLine("WHERE Entregas.Documento = Renglones_Entregas.Documento ")
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Art = Renglones_Entregas.Cod_Art ")
loComandoSeleccionar.AppendLine(" AND Entregas.Status IN ('Confirmado', 'Afectado', 'Procesado') ")
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Art BETWEEN " & lcParametro0Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro0Hasta)
loComandoSeleccionar.AppendLine(" AND Entregas.Fec_Ini BETWEEN " & lcParametro1Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro1Hasta)
loComandoSeleccionar.AppendLine(" AND Renglones_Entregas.Cod_Alm BETWEEN " & lcParametro2Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro2Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Dep BETWEEN " & lcParametro3Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro3Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Sec BETWEEN " & lcParametro4Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro4Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Mar BETWEEN " & lcParametro5Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro5Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Cla BETWEEN " & lcParametro6Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro6Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Tip BETWEEN " & lcParametro7Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro7Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Pro BETWEEN " & lcParametro8Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro8Hasta)
loComandoSeleccionar.AppendLine(" AND Entregas.Cod_Suc BETWEEN " & lcParametro9Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro9Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Uni1 BETWEEN " & lcParametro12Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro12Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Ubi BETWEEN " & lcParametro13Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro13Hasta)
Case "'Notas_Recepcion'"
' Union con Select de la tabla de Recepciones
loComandoSeleccionar.AppendLine("SELECT 'Recepciones' AS Operacion, ")
loComandoSeleccionar.AppendLine(" Recepciones.Documento AS Documento, ")
loComandoSeleccionar.AppendLine(" Renglones_Recepciones.Cod_Art AS Cod_Art, ")
loComandoSeleccionar.AppendLine(" Recepciones.Fec_Ini AS Fec_Ini, ")
loComandoSeleccionar.AppendLine(" Renglones_Recepciones.Renglon AS Renglon, ")
loComandoSeleccionar.AppendLine(" Recepciones.Cod_Pro AS Cliente, ")
loComandoSeleccionar.AppendLine(" Renglones_Recepciones.Cod_Alm AS Cod_Alm, ")
loComandoSeleccionar.AppendLine(" 0.0 AS Can_Sal, ")
loComandoSeleccionar.AppendLine(" Renglones_Recepciones.Can_Art1 AS Can_Ent, ")
loComandoSeleccionar.AppendLine(" 'Entrada' AS Tipo, ")
loComandoSeleccionar.AppendLine(" Renglones_Recepciones." & lcCosto & " AS Cos_Pro, ")
loComandoSeleccionar.AppendLine(" Articulos.Nom_Art AS Nom_Art, ")
loComandoSeleccionar.AppendLine(" " & lcParametro11Desde & " AS Costo ")
loComandoSeleccionar.AppendLine("INTO #curTemporal ")
loComandoSeleccionar.AppendLine("FROM Recepciones, ")
loComandoSeleccionar.AppendLine(" Renglones_Recepciones, ")
loComandoSeleccionar.AppendLine(" Articulos ")
loComandoSeleccionar.AppendLine("WHERE Recepciones.Documento = Renglones_Recepciones.Documento ")
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Art = Renglones_Recepciones.Cod_Art ")
loComandoSeleccionar.AppendLine(" AND Recepciones.Status IN ('Confirmado', 'Afectado', 'Procesado') ")
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Art BETWEEN " & lcParametro0Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro0Hasta)
loComandoSeleccionar.AppendLine(" AND Recepciones.Fec_Ini BETWEEN " & lcParametro1Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro1Hasta)
loComandoSeleccionar.AppendLine(" AND Renglones_Recepciones.Cod_Alm BETWEEN " & lcParametro2Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro2Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Dep BETWEEN " & lcParametro3Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro3Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Sec BETWEEN " & lcParametro4Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro4Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Mar BETWEEN " & lcParametro5Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro5Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Cla BETWEEN " & lcParametro6Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro6Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Tip BETWEEN " & lcParametro7Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro7Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Pro BETWEEN " & lcParametro8Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro8Hasta)
loComandoSeleccionar.AppendLine(" AND Recepciones.Cod_Suc BETWEEN " & lcParametro9Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro9Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Uni1 BETWEEN " & lcParametro12Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro12Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Ubi BETWEEN " & lcParametro13Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro13Hasta)
Case "'Devolucion_Ventas'"
' Union con Select de la tabla de Devoluciones_Clientes
loComandoSeleccionar.AppendLine("SELECT 'Dev_Cli' AS Operacion, ")
loComandoSeleccionar.AppendLine(" Devoluciones_Clientes.Documento AS Documento, ")
loComandoSeleccionar.AppendLine(" Renglones_DClientes.Cod_Art AS Cod_Art, ")
loComandoSeleccionar.AppendLine(" Devoluciones_Clientes.Fec_Ini AS Fec_Ini, ")
loComandoSeleccionar.AppendLine(" Renglones_DClientes.Renglon AS Renglon, ")
loComandoSeleccionar.AppendLine(" Devoluciones_Clientes.Cod_Cli AS Cliente, ")
loComandoSeleccionar.AppendLine(" Renglones_DClientes.Cod_Alm AS Cod_Alm, ")
loComandoSeleccionar.AppendLine(" 0.0 AS Can_Sal, ")
loComandoSeleccionar.AppendLine(" Renglones_DClientes.Can_Art1 AS Can_Ent, ")
loComandoSeleccionar.AppendLine(" 'Entrada' AS Tipo, ")
loComandoSeleccionar.AppendLine(" Renglones_DClientes." & lcCosto & " AS Cos_Pro, ")
loComandoSeleccionar.AppendLine(" Articulos.Nom_Art AS Nom_Art, ")
loComandoSeleccionar.AppendLine(" " & lcParametro11Desde & " AS Costo ")
loComandoSeleccionar.AppendLine("INTO #curTemporal ")
loComandoSeleccionar.AppendLine("FROM Devoluciones_Clientes, ")
loComandoSeleccionar.AppendLine(" Renglones_DClientes, ")
loComandoSeleccionar.AppendLine(" Articulos ")
loComandoSeleccionar.AppendLine("WHERE Devoluciones_Clientes.Documento = Renglones_DClientes.Documento ")
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Art = Renglones_DClientes.Cod_Art ")
loComandoSeleccionar.AppendLine(" AND Devoluciones_Clientes.Status IN ('Confirmado', 'Afectado', 'Procesado') ")
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Art BETWEEN " & lcParametro0Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro0Hasta)
loComandoSeleccionar.AppendLine(" AND Devoluciones_Clientes.Fec_Ini BETWEEN " & lcParametro1Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro1Hasta)
loComandoSeleccionar.AppendLine(" AND Renglones_DClientes.Cod_Alm BETWEEN " & lcParametro2Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro2Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Dep BETWEEN " & lcParametro3Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro3Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Sec BETWEEN " & lcParametro4Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro4Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Mar BETWEEN " & lcParametro5Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro5Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Cla BETWEEN " & lcParametro6Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro6Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Tip BETWEEN " & lcParametro7Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro7Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Pro BETWEEN " & lcParametro8Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro8Hasta)
loComandoSeleccionar.AppendLine(" AND Devoluciones_Clientes.Cod_Suc BETWEEN " & lcParametro9Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro9Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Uni1 BETWEEN " & lcParametro12Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro12Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Ubi BETWEEN " & lcParametro13Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro13Hasta)
Case "'Devolucion_Compras'"
' Union con Select de la tabla de Devoluciones_Proveedores
loComandoSeleccionar.AppendLine("SELECT 'Dev_Pro' AS Operacion, ")
loComandoSeleccionar.AppendLine(" Devoluciones_Proveedores.Documento AS Documento, ")
loComandoSeleccionar.AppendLine(" Renglones_DProveedores.Cod_Art AS Cod_Art, ")
loComandoSeleccionar.AppendLine(" Devoluciones_Proveedores.Fec_Ini AS Fec_Ini, ")
loComandoSeleccionar.AppendLine(" Renglones_DProveedores.Renglon AS Renglon, ")
loComandoSeleccionar.AppendLine(" Devoluciones_Proveedores.Cod_Pro AS Cliente, ")
loComandoSeleccionar.AppendLine(" Renglones_DProveedores.Cod_Alm AS Cod_Alm, ")
loComandoSeleccionar.AppendLine(" Renglones_DProveedores.Can_Art1 AS Can_Sal, ")
loComandoSeleccionar.AppendLine(" 0.0 AS Can_Ent, ")
loComandoSeleccionar.AppendLine(" 'Salida' AS Tipo, ")
loComandoSeleccionar.AppendLine(" Renglones_DProveedores." & lcCosto & " AS Cos_Pro, ")
loComandoSeleccionar.AppendLine(" Articulos.Nom_Art AS Nom_Art, ")
loComandoSeleccionar.AppendLine(" " & lcParametro11Desde & " AS Costo ")
loComandoSeleccionar.AppendLine("INTO #curTemporal ")
loComandoSeleccionar.AppendLine("FROM Devoluciones_Proveedores, ")
loComandoSeleccionar.AppendLine(" Renglones_DProveedores, ")
loComandoSeleccionar.AppendLine(" Articulos ")
loComandoSeleccionar.AppendLine("WHERE Devoluciones_Proveedores.Documento = Renglones_DProveedores.Documento ")
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Art = Renglones_DProveedores.Cod_Art ")
loComandoSeleccionar.AppendLine(" AND Devoluciones_Proveedores.Status IN ('Confirmado', 'Afectado', 'Procesado') ")
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Art BETWEEN " & lcParametro0Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro0Hasta)
loComandoSeleccionar.AppendLine(" AND Devoluciones_Proveedores.Fec_Ini BETWEEN " & lcParametro1Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro1Hasta)
loComandoSeleccionar.AppendLine(" AND Renglones_DProveedores.Cod_Alm BETWEEN " & lcParametro2Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro2Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Dep BETWEEN " & lcParametro3Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro3Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Sec BETWEEN " & lcParametro4Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro4Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Mar BETWEEN " & lcParametro5Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro5Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Cla BETWEEN " & lcParametro6Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro6Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Tip BETWEEN " & lcParametro7Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro7Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Pro BETWEEN " & lcParametro8Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro8Hasta)
loComandoSeleccionar.AppendLine(" AND Devoluciones_Proveedores.Cod_Suc BETWEEN " & lcParametro9Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro9Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Uni1 BETWEEN " & lcParametro12Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro12Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Ubi BETWEEN " & lcParametro13Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro13Hasta)
End Select
loComandoSeleccionar.AppendLine("")
loComandoSeleccionar.AppendLine("SELECT Operacion, ")
loComandoSeleccionar.AppendLine(" Documento, ")
loComandoSeleccionar.AppendLine(" Cod_Art, ")
loComandoSeleccionar.AppendLine(" Fec_Ini, ")
loComandoSeleccionar.AppendLine(" Renglon, ")
loComandoSeleccionar.AppendLine(" Cliente, ")
loComandoSeleccionar.AppendLine(" Cod_Alm, ")
loComandoSeleccionar.AppendLine(" Can_Sal, ")
loComandoSeleccionar.AppendLine(" Can_Ent, ")
loComandoSeleccionar.AppendLine(" Tipo, ")
loComandoSeleccionar.AppendLine(" Cos_Pro, ")
loComandoSeleccionar.AppendLine(" (Cos_Pro * Can_Sal) AS Cos_Pro_Sal, ")
loComandoSeleccionar.AppendLine(" (Cos_Pro * Can_Ent) AS Cos_Pro_Ent, ")
loComandoSeleccionar.AppendLine(" ((Cos_Pro * Can_Ent) - (Cos_Pro * Can_Sal)) AS Cos_Tot, ")
loComandoSeleccionar.AppendLine(" Nom_Art, ")
loComandoSeleccionar.AppendLine(" Costo ")
loComandoSeleccionar.AppendLine("FROM #curTemporal ")
loComandoSeleccionar.AppendLine("ORDER BY " & lcOrdenamiento)
loComandoSeleccionar.AppendLine("")
'Me.mEscribirConsulta(loComandoSeleccionar.ToString())
Dim loServicios As New cusDatos.goDatos
Dim laDatosReporte As DataSet = loServicios.mObtenerTodosSinEsquema(loComandoSeleccionar.ToString, "curReportes")
'-------------------------------------------------------------------------------------------------------
' Verificando si el select (tabla nº0) trae registros
'-------------------------------------------------------------------------------------------------------
If (laDatosReporte.Tables(0).Rows.Count <= 0) Then
Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Información", _
"No se Encontraron Registros para los Parámetros Especificados. ", _
vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Informacion, _
"350px", _
"200px")
End If
loObjetoReporte = cusAplicacion.goReportes.mCargarReporte("rMInventarios_Articulos", laDatosReporte)
Me.mTraducirReporte(loObjetoReporte)
Me.mFormatearCamposReporte(loObjetoReporte)
Me.crvrMInventarios_Articulos.ReportSource = loObjetoReporte
Catch loExcepcion As Exception
Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Error", _
"No se pudo Completar el Proceso: " & loExcepcion.Message, _
vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Error, _
"auto", _
"auto")
End Try
End Sub
Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
Try
loObjetoReporte.Close()
Catch loExcepcion As Exception
End Try
End Sub
End Class
'-------------------------------------------------------------------------------------------'
' Fin del codigo
'-------------------------------------------------------------------------------------------'
' JJD: 30/09/08: Codigo inicial
'-------------------------------------------------------------------------------------------'
' CMS: 12/05/09: Ordenamiento
'-------------------------------------------------------------------------------------------'
' AAP: 29/06/09: Filtro "Sucursal"
'-------------------------------------------------------------------------------------------'
' JJD: 24/07/09: Se desgloso por origen. Ajuste, Traslados, Devoluciones Clientes, etc.
'-------------------------------------------------------------------------------------------'
' CMS: 19/08/09: Verificacion de registros y filtro cod_ubi
'-------------------------------------------------------------------------------------------'
' RJG: 14/03/10: Corecciones varias: no mostraba todos los documentos, corrección en '
' Traslados, Compras, Entregas. Ajustados Status de documentos de Compra y '
' Venta (agregados los Afectados y Procesados). '
'-------------------------------------------------------------------------------------------'
' RJG: 08/12/10: Ajustado Estatus de Facturas de Venta: Ahora omite las facturas de venta '
' pendientes e incluye las confirmadas. '
'-------------------------------------------------------------------------------------------'
' MAT: 17/03/11: Mejora en la vista de diseño. '
'-------------------------------------------------------------------------------------------'
' RJG: 15/05/12: Corrección de los filtros de almacén (en traslados) y de sucursal. '
'-------------------------------------------------------------------------------------------'
|
kodeitsolutions/ef-reports
|
rMInventarios_Articulos.aspx.vb
|
Visual Basic
|
mit
| 96,212
|
Option Infer On
Imports System
Imports System.Collections.Generic
Imports System.Runtime.InteropServices
Namespace Examples
Friend Class Program
<STAThread>
Shared Sub Main(ByVal args() As String)
Dim application As SolidEdgeFramework.Application = Nothing
Dim partDocument As SolidEdgePart.PartDocument = Nothing
Dim models As SolidEdgePart.Models = Nothing
Dim model As SolidEdgePart.Model = Nothing
Dim helixCutouts As SolidEdgePart.HelixCutouts = Nothing
Dim helixCutout As SolidEdgePart.HelixCutout = Nothing
Try
' See "Handling 'Application is Busy' and 'Call was Rejected By Callee' errors" topic.
OleMessageFilter.Register()
' Attempt to connect to a running instance of Solid Edge.
application = DirectCast(Marshal.GetActiveObject("SolidEdge.Application"), SolidEdgeFramework.Application)
partDocument = TryCast(application.ActiveDocument, SolidEdgePart.PartDocument)
If partDocument IsNot Nothing Then
models = partDocument.Models
model = models.Item(1)
helixCutouts = model.HelixCutouts
For i As Integer = 1 To helixCutouts.Count
helixCutout = helixCutouts.Item(i)
Dim Xorigin As Double = 0.02
Dim Yorigin As Double = 0
Dim Zorigin As Double = 0.02
Dim Xdir As Double = 0
Dim Ydir As Double = 1
Dim Zdir As Double = 0
Dim faces = CType(helixCutout.FacesByRay(Xorigin, Yorigin, Zorigin, Xdir, Ydir, Zdir), SolidEdgeGeometry.Faces)
Next i
End If
Catch ex As System.Exception
Console.WriteLine(ex)
Finally
OleMessageFilter.Unregister()
End Try
End Sub
End Class
End Namespace
|
SolidEdgeCommunity/docs
|
docfx_project/snippets/SolidEdgePart.HelixCutout.FacesByRay.vb
|
Visual Basic
|
mit
| 2,082
|
Imports System.Collections.Generic
Imports DotNetNuke.Collections
Imports DotNetNuke.Data
Imports System
Imports System.CodeDom
Imports System.Linq
Imports DotNetNuke.Common
Imports DotNetNuke.Framework
Namespace Components
Public Class CTCallRepository
Public Function CreateCTCall(t As CTCall) As Integer
Using ctx As IDataContext = DataContext.Instance()
Dim rep = ctx.GetRepository(Of CTCall)()
rep.Insert(DirectCast(t, CTCall))
Return t.CallId
End Using
End Function
'Public Sub CreateCTCall(ByVal t As CTCall)
' Using ctx As IDataContext = DataContext.Instance()
' Dim rep As IRepository(Of CTCall) = ctx.GetRepository(Of CTCall)()
' rep.Insert(t)
' End Using
'End Sub
Public Sub DeleteCTCall(ByVal t As Integer, ByVal moduleId As Integer)
Dim _item As CTCall = GetCTCall(t, moduleId)
DeleteCTCall(_item)
End Sub
Public Sub DeleteCTCall(ByVal t As CTCall)
Using ctx As IDataContext = DataContext.Instance()
Dim rep As IRepository(Of CTCall) = ctx.GetRepository(Of CTCall)()
rep.Delete(t)
End Using
End Sub
Public Function GetCTCalls(ByVal _moduleId As Integer) As IEnumerable(Of CTCall)
Dim t As IEnumerable(Of CTCall)
Using ctx As IDataContext = DataContext.Instance()
Dim rep As IRepository(Of CTCall) = ctx.GetRepository(Of CTCall)()
t = rep.Get(_moduleId)
End Using
Return t
End Function
Public Function GetCTCall(ByVal Callid As Integer, ByVal moduleId As Integer) As CTCall
Dim t As CTCall
Using ctx As IDataContext = DataContext.Instance()
Dim rep As IRepository(Of CTCall) = ctx.GetRepository(Of CTCall)()
t = rep.GetById(Of Int32, Int32)(Callid, moduleId)
End Using
Return t
End Function
Public Sub UpdateCTCall(ByVal t As CTCall)
Using ctx As IDataContext = DataContext.Instance()
Dim rep As IRepository(Of CTCall) = ctx.GetRepository(Of CTCall)()
rep.Update(t)
End Using
End Sub
End Class
End Namespace
|
dmcdonald11/dmAngular8
|
Components/CTCallRepository.vb
|
Visual Basic
|
mit
| 2,382
|
''' <see cref="System.Action"/>
Public Class See
End Class
|
GeorgeAlexandria/CoCo
|
tests/Identifiers/VisualBasicIdentifiers/XmlDocComment/See.vb
|
Visual Basic
|
mit
| 62
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Microsoft.CodeAnalysis.Semantics
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
Partial Public Class IOperationTests
Inherits SemanticModelTestBase
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
<WorkItem(19819, "https://github.com/dotnet/roslyn/issues/19819")>
Public Sub UsingDeclarationSyntaxNotNull()
Dim source = <compilation>
<file name="c.vb">
<![CDATA[
Imports System
Module Module1
Class C1
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
Throw New NotImplementedException()
End Sub
End Class
Sub S1()
Using D1 as New C1()
End Using
End Sub
End Module
]]>
</file>
</compilation>
Dim comp = CreateCompilationWithMscorlibAndVBRuntime(source, parseOptions:=TestOptions.RegularWithIOperationFeature)
CompilationUtils.AssertNoDiagnostics(comp)
Dim tree = comp.SyntaxTrees.Single()
Dim node = tree.GetRoot().DescendantNodes().OfType(Of UsingBlockSyntax).Single()
Dim op = DirectCast(comp.GetSemanticModel(tree).GetOperationInternal(node), IUsingStatement)
Assert.NotNull(op.Resources.Syntax)
Assert.Same(node.UsingStatement, op.Resources.Syntax)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
<WorkItem(19887, "https://github.com/dotnet/roslyn/issues/19887")>
Public Sub UsingDeclarationIncompleteUsingInvalidExpression()
Dim source = <compilation>
<file name="c.vb">
<![CDATA[
Imports System
Module Module1
Class C1
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
Throw New NotImplementedException()
End Sub
End Class
Sub S1()
Using
End Using
End Sub
End Module
]]>
</file>
</compilation>
Dim comp = CreateCompilationWithMscorlibAndVBRuntime(source, parseOptions:=TestOptions.RegularWithIOperationFeature)
CompilationUtils.AssertTheseDiagnostics(comp,
<expected>
BC30201: Expression expected.
Using
~
</expected>)
Dim tree = comp.SyntaxTrees.Single()
Dim node = tree.GetRoot().DescendantNodes().OfType(Of UsingBlockSyntax).Single()
Dim op = DirectCast(comp.GetSemanticModel(tree).GetOperationInternal(node), IUsingStatement)
Assert.Equal(OperationKind.InvalidExpression, op.Resources.Kind)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub IUsingStatement_MultipleNewResources()
Dim source = <![CDATA[
Imports System
Module Program
Class C
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
Sub Main(args As String())
Using c1 As C = New C, c2 As C = New C'BIND:"Using c1 As C = New C, c2 As C = New C"
Console.WriteLine(c1)
End Using
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IUsingStatement (OperationKind.UsingStatement) (Syntax: 'Using c1 As ... End Using')
Resources:
IVariableDeclarationStatement (2 declarations) (OperationKind.VariableDeclarationStatement) (Syntax: 'Using c1 As ... s C = New C')
IVariableDeclaration (1 variables) (OperationKind.VariableDeclaration) (Syntax: 'c1')
Variables: Local_1: c1 As Program.C
Initializer:
IVariableInitializer (OperationKind.VariableInitializer) (Syntax: '= New C')
IObjectCreationExpression (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreationExpression, Type: Program.C) (Syntax: 'New C')
Arguments(0)
Initializer:
null
IVariableDeclaration (1 variables) (OperationKind.VariableDeclaration) (Syntax: 'c2')
Variables: Local_1: c2 As Program.C
Initializer:
IVariableInitializer (OperationKind.VariableInitializer) (Syntax: '= New C')
IObjectCreationExpression (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreationExpression, Type: Program.C) (Syntax: 'New C')
Arguments(0)
Initializer:
null
Body:
IBlockStatement (1 statements) (OperationKind.BlockStatement, IsImplicit) (Syntax: 'Using c1 As ... End Using')
IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: 'Console.WriteLine(c1)')
Expression:
IInvocationExpression (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.InvocationExpression, Type: System.Void) (Syntax: 'Console.WriteLine(c1)')
Instance Receiver:
null
Arguments(1):
IArgument (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument) (Syntax: 'c1')
IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Object, IsImplicit) (Syntax: 'c1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceExpression: c1 (OperationKind.LocalReferenceExpression, Type: Program.C) (Syntax: 'c1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub IUsingStatement_SingleNewResource()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Class C
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
Sub Main(args As String())
Using c1 As C = New C'BIND:"Using c1 As C = New C"
Console.WriteLine(c1)
End Using
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IUsingStatement (OperationKind.UsingStatement) (Syntax: 'Using c1 As ... End Using')
Resources:
IVariableDeclarationStatement (1 declarations) (OperationKind.VariableDeclarationStatement) (Syntax: 'Using c1 As C = New C')
IVariableDeclaration (1 variables) (OperationKind.VariableDeclaration) (Syntax: 'c1')
Variables: Local_1: c1 As Program.C
Initializer:
IVariableInitializer (OperationKind.VariableInitializer) (Syntax: '= New C')
IObjectCreationExpression (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreationExpression, Type: Program.C) (Syntax: 'New C')
Arguments(0)
Initializer:
null
Body:
IBlockStatement (1 statements) (OperationKind.BlockStatement, IsImplicit) (Syntax: 'Using c1 As ... End Using')
IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: 'Console.WriteLine(c1)')
Expression:
IInvocationExpression (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.InvocationExpression, Type: System.Void) (Syntax: 'Console.WriteLine(c1)')
Instance Receiver:
null
Arguments(1):
IArgument (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument) (Syntax: 'c1')
IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Object, IsImplicit) (Syntax: 'c1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceExpression: c1 (OperationKind.LocalReferenceExpression, Type: Program.C) (Syntax: 'c1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub IUsingStatement_SingleAsNewResource()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Class C
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
Sub Main(args As String())
Using c1 As New C'BIND:"Using c1 As New C"
Console.WriteLine(c1)
End Using
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IUsingStatement (OperationKind.UsingStatement) (Syntax: 'Using c1 As ... End Using')
Resources:
IVariableDeclarationStatement (1 declarations) (OperationKind.VariableDeclarationStatement) (Syntax: 'Using c1 As New C')
IVariableDeclaration (1 variables) (OperationKind.VariableDeclaration) (Syntax: 'c1')
Variables: Local_1: c1 As Program.C
Initializer:
IVariableInitializer (OperationKind.VariableInitializer) (Syntax: 'As New C')
IObjectCreationExpression (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreationExpression, Type: Program.C) (Syntax: 'New C')
Arguments(0)
Initializer:
null
Body:
IBlockStatement (1 statements) (OperationKind.BlockStatement, IsImplicit) (Syntax: 'Using c1 As ... End Using')
IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: 'Console.WriteLine(c1)')
Expression:
IInvocationExpression (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.InvocationExpression, Type: System.Void) (Syntax: 'Console.WriteLine(c1)')
Instance Receiver:
null
Arguments(1):
IArgument (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument) (Syntax: 'c1')
IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Object, IsImplicit) (Syntax: 'c1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceExpression: c1 (OperationKind.LocalReferenceExpression, Type: Program.C) (Syntax: 'c1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub IUsingStatement_MultipleAsNewResources()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Class C
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
Sub Main(args As String())
Using c1, c2 As New C'BIND:"Using c1, c2 As New C"
Console.WriteLine(c1)
End Using
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IUsingStatement (OperationKind.UsingStatement) (Syntax: 'Using c1, c ... End Using')
Resources:
IVariableDeclarationStatement (1 declarations) (OperationKind.VariableDeclarationStatement) (Syntax: 'Using c1, c2 As New C')
IVariableDeclaration (2 variables) (OperationKind.VariableDeclaration) (Syntax: 'c1, c2 As New C')
Variables: Local_1: c1 As Program.C
Local_2: c2 As Program.C
Initializer:
IVariableInitializer (OperationKind.VariableInitializer) (Syntax: 'As New C')
IObjectCreationExpression (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreationExpression, Type: Program.C) (Syntax: 'New C')
Arguments(0)
Initializer:
null
Body:
IBlockStatement (1 statements) (OperationKind.BlockStatement, IsImplicit) (Syntax: 'Using c1, c ... End Using')
IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: 'Console.WriteLine(c1)')
Expression:
IInvocationExpression (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.InvocationExpression, Type: System.Void) (Syntax: 'Console.WriteLine(c1)')
Instance Receiver:
null
Arguments(1):
IArgument (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument) (Syntax: 'c1')
IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Object, IsImplicit) (Syntax: 'c1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceExpression: c1 (OperationKind.LocalReferenceExpression, Type: Program.C) (Syntax: 'c1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub IUsingStatement_SingleExistingResource()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Class C
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
Sub Main(args As String())
Dim c1 As New C
Using c1'BIND:"Using c1"
Console.WriteLine(c1)
End Using
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IUsingStatement (OperationKind.UsingStatement) (Syntax: 'Using c1'BI ... End Using')
Resources:
ILocalReferenceExpression: c1 (OperationKind.LocalReferenceExpression, Type: Program.C) (Syntax: 'c1')
Body:
IBlockStatement (1 statements) (OperationKind.BlockStatement, IsImplicit) (Syntax: 'Using c1'BI ... End Using')
IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: 'Console.WriteLine(c1)')
Expression:
IInvocationExpression (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.InvocationExpression, Type: System.Void) (Syntax: 'Console.WriteLine(c1)')
Instance Receiver:
null
Arguments(1):
IArgument (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument) (Syntax: 'c1')
IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Object, IsImplicit) (Syntax: 'c1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceExpression: c1 (OperationKind.LocalReferenceExpression, Type: Program.C) (Syntax: 'c1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub IUsingStatement_InvalidMultipleExistingResources()
Dim source = <![CDATA[
Imports System
Module Program
Class C
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
Sub Main(args As String())
Dim c1, c2 As New C
Using c1, c2'BIND:"Using c1, c2"
Console.WriteLine(c1)
End Using
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IUsingStatement (OperationKind.UsingStatement, IsInvalid) (Syntax: 'Using c1, c ... End Using')
Resources:
IVariableDeclarationStatement (2 declarations) (OperationKind.VariableDeclarationStatement, IsInvalid) (Syntax: 'Using c1, c2')
IVariableDeclaration (1 variables) (OperationKind.VariableDeclaration, IsInvalid) (Syntax: 'c1')
Variables: Local_1: c1 As System.Object
Initializer:
null
IVariableDeclaration (1 variables) (OperationKind.VariableDeclaration, IsInvalid) (Syntax: 'c2')
Variables: Local_1: c2 As System.Object
Initializer:
null
Body:
IBlockStatement (1 statements) (OperationKind.BlockStatement, IsInvalid, IsImplicit) (Syntax: 'Using c1, c ... End Using')
IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: 'Console.WriteLine(c1)')
Expression:
IInvocationExpression (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.InvocationExpression, Type: System.Void) (Syntax: 'Console.WriteLine(c1)')
Instance Receiver:
null
Arguments(1):
IArgument (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument) (Syntax: 'c1')
ILocalReferenceExpression: c1 (OperationKind.LocalReferenceExpression, Type: System.Object) (Syntax: 'c1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30616: Variable 'c1' hides a variable in an enclosing block.
Using c1, c2'BIND:"Using c1, c2"
~~
BC36011: 'Using' resource variable must have an explicit initialization.
Using c1, c2'BIND:"Using c1, c2"
~~
BC30616: Variable 'c2' hides a variable in an enclosing block.
Using c1, c2'BIND:"Using c1, c2"
~~
BC42104: Variable 'c1' is used before it has been assigned a value. A null reference exception could result at runtime.
Console.WriteLine(c1)
~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub IUsingStatement_NestedUsing()
Dim source = <![CDATA[
Imports System
Module Program
Class C
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
Sub Main(args As String())
Dim c1, c2 As New C
Using c1'BIND:"Using c1"
Using c2
Console.WriteLine(c1)
End Using
End Using
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IUsingStatement (OperationKind.UsingStatement) (Syntax: 'Using c1'BI ... End Using')
Resources:
ILocalReferenceExpression: c1 (OperationKind.LocalReferenceExpression, Type: Program.C) (Syntax: 'c1')
Body:
IBlockStatement (1 statements) (OperationKind.BlockStatement, IsImplicit) (Syntax: 'Using c1'BI ... End Using')
IUsingStatement (OperationKind.UsingStatement) (Syntax: 'Using c2 ... End Using')
Resources:
ILocalReferenceExpression: c2 (OperationKind.LocalReferenceExpression, Type: Program.C) (Syntax: 'c2')
Body:
IBlockStatement (1 statements) (OperationKind.BlockStatement, IsImplicit) (Syntax: 'Using c2 ... End Using')
IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: 'Console.WriteLine(c1)')
Expression:
IInvocationExpression (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.InvocationExpression, Type: System.Void) (Syntax: 'Console.WriteLine(c1)')
Instance Receiver:
null
Arguments(1):
IArgument (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument) (Syntax: 'c1')
IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Object, IsImplicit) (Syntax: 'c1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceExpression: c1 (OperationKind.LocalReferenceExpression, Type: Program.C) (Syntax: 'c1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub IUsingStatement_MixedAsNewAndSingleInitializer()
Dim source = <![CDATA[
Imports System
Module Program
Class C
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
Sub Main(args As String())
Using c1 = New C, c2, c3 As New C'BIND:"Using c1 = New C, c2, c3 As New C"
Console.WriteLine(c1)
End Using
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IUsingStatement (OperationKind.UsingStatement) (Syntax: 'Using c1 = ... End Using')
Resources:
IVariableDeclarationStatement (2 declarations) (OperationKind.VariableDeclarationStatement) (Syntax: 'Using c1 = ... c3 As New C')
IVariableDeclaration (1 variables) (OperationKind.VariableDeclaration) (Syntax: 'c1')
Variables: Local_1: c1 As Program.C
Initializer:
IVariableInitializer (OperationKind.VariableInitializer) (Syntax: '= New C')
IObjectCreationExpression (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreationExpression, Type: Program.C) (Syntax: 'New C')
Arguments(0)
Initializer:
null
IVariableDeclaration (2 variables) (OperationKind.VariableDeclaration) (Syntax: 'c2, c3 As New C')
Variables: Local_1: c2 As Program.C
Local_2: c3 As Program.C
Initializer:
IVariableInitializer (OperationKind.VariableInitializer) (Syntax: 'As New C')
IObjectCreationExpression (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreationExpression, Type: Program.C) (Syntax: 'New C')
Arguments(0)
Initializer:
null
Body:
IBlockStatement (1 statements) (OperationKind.BlockStatement, IsImplicit) (Syntax: 'Using c1 = ... End Using')
IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: 'Console.WriteLine(c1)')
Expression:
IInvocationExpression (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.InvocationExpression, Type: System.Void) (Syntax: 'Console.WriteLine(c1)')
Instance Receiver:
null
Arguments(1):
IArgument (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument) (Syntax: 'c1')
IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Object, IsImplicit) (Syntax: 'c1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceExpression: c1 (OperationKind.LocalReferenceExpression, Type: Program.C) (Syntax: 'c1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub IUsingStatement_InvalidNoInitializerOneVariable()
Dim source = <![CDATA[
Imports System
Module Program
Class C
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
Sub Main(args As String())
Dim c2 As New C
Using c1 = New C, c2'BIND:"Using c1 = New C, c2"
Console.WriteLine(c1)
End Using
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IUsingStatement (OperationKind.UsingStatement, IsInvalid) (Syntax: 'Using c1 = ... End Using')
Resources:
IVariableDeclarationStatement (2 declarations) (OperationKind.VariableDeclarationStatement, IsInvalid) (Syntax: 'Using c1 = New C, c2')
IVariableDeclaration (1 variables) (OperationKind.VariableDeclaration) (Syntax: 'c1')
Variables: Local_1: c1 As Program.C
Initializer:
IVariableInitializer (OperationKind.VariableInitializer) (Syntax: '= New C')
IObjectCreationExpression (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreationExpression, Type: Program.C) (Syntax: 'New C')
Arguments(0)
Initializer:
null
IVariableDeclaration (1 variables) (OperationKind.VariableDeclaration, IsInvalid) (Syntax: 'c2')
Variables: Local_1: c2 As System.Object
Initializer:
null
Body:
IBlockStatement (1 statements) (OperationKind.BlockStatement, IsInvalid, IsImplicit) (Syntax: 'Using c1 = ... End Using')
IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: 'Console.WriteLine(c1)')
Expression:
IInvocationExpression (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.InvocationExpression, Type: System.Void) (Syntax: 'Console.WriteLine(c1)')
Instance Receiver:
null
Arguments(1):
IArgument (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument) (Syntax: 'c1')
IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Object, IsImplicit) (Syntax: 'c1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceExpression: c1 (OperationKind.LocalReferenceExpression, Type: Program.C) (Syntax: 'c1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30616: Variable 'c2' hides a variable in an enclosing block.
Using c1 = New C, c2'BIND:"Using c1 = New C, c2"
~~
BC36011: 'Using' resource variable must have an explicit initialization.
Using c1 = New C, c2'BIND:"Using c1 = New C, c2"
~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub IUsingStatement_InvalidNonDisposableResource()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Class C
End Class
Sub Main(args As String())
Using c1 As New C'BIND:"Using c1 As New C"
Console.WriteLine(c1)
End Using
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IUsingStatement (OperationKind.UsingStatement, IsInvalid) (Syntax: 'Using c1 As ... End Using')
Resources:
IVariableDeclarationStatement (1 declarations) (OperationKind.VariableDeclarationStatement, IsInvalid) (Syntax: 'Using c1 As New C')
IVariableDeclaration (1 variables) (OperationKind.VariableDeclaration, IsInvalid) (Syntax: 'c1')
Variables: Local_1: c1 As Program.C
Initializer:
IVariableInitializer (OperationKind.VariableInitializer, IsInvalid) (Syntax: 'As New C')
IObjectCreationExpression (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreationExpression, Type: Program.C, IsInvalid) (Syntax: 'New C')
Arguments(0)
Initializer:
null
Body:
IBlockStatement (1 statements) (OperationKind.BlockStatement, IsInvalid, IsImplicit) (Syntax: 'Using c1 As ... End Using')
IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: 'Console.WriteLine(c1)')
Expression:
IInvocationExpression (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.InvocationExpression, Type: System.Void) (Syntax: 'Console.WriteLine(c1)')
Instance Receiver:
null
Arguments(1):
IArgument (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument) (Syntax: 'c1')
IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Object, IsImplicit) (Syntax: 'c1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceExpression: c1 (OperationKind.LocalReferenceExpression, Type: Program.C) (Syntax: 'c1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36010: 'Using' operand of type 'Program.C' must implement 'System.IDisposable'.
Using c1 As New C'BIND:"Using c1 As New C"
~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub IUsingStatement_InvalidEmptyUsingResource()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub Main(args As String())
Using'BIND:"Using"
End Using
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IUsingStatement (OperationKind.UsingStatement, IsInvalid) (Syntax: 'Using'BIND: ... End Using')
Resources:
IInvalidExpression (OperationKind.InvalidExpression, Type: null, IsInvalid) (Syntax: '')
Children(0)
Body:
IBlockStatement (0 statements) (OperationKind.BlockStatement, IsInvalid, IsImplicit) (Syntax: 'Using'BIND: ... End Using')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30201: Expression expected.
Using'BIND:"Using"
~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub IUsingStatement_InvalidNothingResources()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub Main(args As String())
Using Nothing'BIND:"Using Nothing"
End Using
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IUsingStatement (OperationKind.UsingStatement, IsInvalid) (Syntax: 'Using Nothi ... End Using')
Resources:
IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Object, Constant: null, IsInvalid, IsImplicit) (Syntax: 'Nothing')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralExpression (OperationKind.LiteralExpression, Type: null, Constant: null, IsInvalid) (Syntax: 'Nothing')
Body:
IBlockStatement (0 statements) (OperationKind.BlockStatement, IsInvalid, IsImplicit) (Syntax: 'Using Nothi ... End Using')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36010: 'Using' operand of type 'Object' must implement 'System.IDisposable'.
Using Nothing'BIND:"Using Nothing"
~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub IUsingStatement_UsingWithoutSavedReference()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub Main(args As String())
Using GetC()'BIND:"Using GetC()"
End Using
End Sub
Function GetC() As C
Return New C
End Function
Class C
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IUsingStatement (OperationKind.UsingStatement) (Syntax: 'Using GetC( ... End Using')
Resources:
IInvocationExpression (Function Program.GetC() As Program.C) (OperationKind.InvocationExpression, Type: Program.C) (Syntax: 'GetC()')
Instance Receiver:
null
Arguments(0)
Body:
IBlockStatement (0 statements) (OperationKind.BlockStatement, IsImplicit) (Syntax: 'Using GetC( ... End Using')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub IUsingStatement_UsingBlockSyntax_UsingStatementSyntax_WithDeclarationResource()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub Main(args As String())
Using c1 = New C, c2 = New C'BIND:"Using c1 = New C, c2 = New C"
End Using
End Sub
Class C
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IVariableDeclarationStatement (2 declarations) (OperationKind.VariableDeclarationStatement) (Syntax: 'Using c1 = ... c2 = New C')
IVariableDeclaration (1 variables) (OperationKind.VariableDeclaration) (Syntax: 'c1')
Variables: Local_1: c1 As Program.C
Initializer:
IVariableInitializer (OperationKind.VariableInitializer) (Syntax: '= New C')
IObjectCreationExpression (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreationExpression, Type: Program.C) (Syntax: 'New C')
Arguments(0)
Initializer:
null
IVariableDeclaration (1 variables) (OperationKind.VariableDeclaration) (Syntax: 'c2')
Variables: Local_1: c2 As Program.C
Initializer:
IVariableInitializer (OperationKind.VariableInitializer) (Syntax: '= New C')
IObjectCreationExpression (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreationExpression, Type: Program.C) (Syntax: 'New C')
Arguments(0)
Initializer:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of UsingStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub IUsingStatement_UsingBlockSyntax_UsingStatementSyntax_WithExpressionResource()
Dim source = <compilation>
<file Name="a.vb">
<![CDATA[
Option Strict On
Imports System
Module Program
Sub Main(args As String())
Dim c1 As New C
Using c1'BIND:"Using c1"
Console.WriteLine()
End Using
End Sub
Class C
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
End Module]]>
</file>
</compilation>
Dim comp = CreateCompilationWithMscorlibAndVBRuntime(source, parseOptions:=TestOptions.RegularWithIOperationFeature)
CompilationUtils.AssertNoDiagnostics(comp)
Dim tree = comp.SyntaxTrees.Single()
Dim node = tree.GetRoot().DescendantNodes().OfType(Of UsingBlockSyntax).Single().UsingStatement
Assert.Null(comp.GetSemanticModel(node.SyntaxTree).GetOperation(node))
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(Skip:="https://github.com/dotnet/roslyn/issues/22362")>
Public Sub IUsingStatement_UsingStatementSyntax_VariablesSyntax()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub Main(args As String())
Using c1 = New C, c2 = New C'BIND:"c1 = New C"
End Using
End Sub
Class C
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
End Module]]>.Value
' This should be returning a variable declaration, but the associated variable declarator operation has a
' ModifiedIdentifierSyntax as the associated syntax node. Fixing is tracked by
' https://github.com/dotnet/roslyn/issues/22362
Dim expectedOperationTree = <![CDATA[
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of VariableDeclaratorSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub IUsingStatement_UsingStatementSyntax_Expression()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub Main(args As String())
Dim c1 As New C
Using c1'BIND:"c1"
Console.WriteLine()
End Using
End Sub
Class C
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ILocalReferenceExpression: c1 (OperationKind.LocalReferenceExpression, Type: Program.C) (Syntax: 'c1')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of IdentifierNameSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub IUsingStatement_UsingBlockSyntax_StatementsSyntax()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub Main(args As String())
Using c1 = New C, c2 = New C
Console.WriteLine()'BIND:"Console.WriteLine()"
End Using
End Sub
Class C
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IExpressionStatement (OperationKind.ExpressionStatement) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationExpression (Sub System.Console.WriteLine()) (OperationKind.InvocationExpression, Type: System.Void) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ExpressionStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
End Class
End Namespace
|
pdelvo/roslyn
|
src/Compilers/VisualBasic/Test/Semantic/IOperation/IOperationTests_IUsingStatement.vb
|
Visual Basic
|
apache-2.0
| 43,240
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.IO
Imports System.Xml.Linq
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.SpecialType
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit
Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics.ConversionsTests.Parameters
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
Public Class ConversionsTests
Inherits BasicTestBase
Private Shared ReadOnly NoConversion As ConversionKind = Nothing
<Fact()>
Public Sub TryCastDirectCastConversions()
Dim dummyCode =
<file>
Class C1
Shared Sub MethodDecl()
End Sub
End Class
</file>
Dim dummyTree = VisualBasicSyntaxTree.ParseText(dummyCode.Value)
' Tests are based on the source code used to compile VBConversions.dll, VBConversions.vb is
' checked in next to the DLL.
Dim vbConversionsRef = TestReferences.SymbolsTests.VBConversions
Dim modifiersRef = TestReferences.SymbolsTests.CustomModifiers.Modifiers.dll
Dim c1 = VisualBasicCompilation.Create("Test", syntaxTrees:={dummyTree}, references:={TestReferences.NetFx.v4_0_21006.mscorlib, vbConversionsRef, modifiersRef})
Dim sourceModule = DirectCast(c1.Assembly.Modules(0), SourceModuleSymbol)
Dim methodDeclSymbol = DirectCast(sourceModule.GlobalNamespace.GetTypeMembers("C1").Single().GetMembers("MethodDecl").Single(), SourceMethodSymbol)
Dim methodBodyBinder = BinderBuilder.CreateBinderForMethodBody(sourceModule, dummyTree, methodDeclSymbol)
Dim asmVBConversions = c1.GetReferencedAssemblySymbol(vbConversionsRef)
Dim asmModifiers = c1.GetReferencedAssemblySymbol(modifiersRef)
Dim test = asmVBConversions.Modules(0).GlobalNamespace.GetTypeMembers("Test").Single()
Dim m13 = DirectCast(test.GetMembers("M13").Single(), MethodSymbol)
Dim m13p = m13.Parameters.Select(Function(p) p.Type).ToArray()
Assert.Equal(ConversionKind.WideningReference, ClassifyDirectCastAssignment(m13p(a), m13p(b), methodBodyBinder)) ' Object)
Assert.Equal(ConversionKind.WideningValue, ClassifyDirectCastAssignment(m13p(a), m13p(c), methodBodyBinder)) ' Object)
Assert.Equal(ConversionKind.NarrowingReference, ClassifyDirectCastAssignment(m13p(b), m13p(a), methodBodyBinder)) ' ValueType)
Assert.Equal(ConversionKind.WideningValue, ClassifyDirectCastAssignment(m13p(b), m13p(c), methodBodyBinder)) ' ValueType)
Assert.Equal(ConversionKind.NarrowingValue, ClassifyDirectCastAssignment(m13p(c), m13p(a), methodBodyBinder)) ' Integer)
Assert.Equal(ConversionKind.NarrowingValue, ClassifyDirectCastAssignment(m13p(c), m13p(b), methodBodyBinder)) ' Integer)
Assert.True(Conversions.IsIdentityConversion(ClassifyDirectCastAssignment(m13p(c), m13p(c), methodBodyBinder))) ' Integer)
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(c), m13p(d), methodBodyBinder)) ' Integer) 'error BC30311: Value of type 'Long' cannot be converted to 'Integer'.
Assert.Equal(ConversionKind.WideningNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyDirectCastAssignment(m13p(c), m13p(e), methodBodyBinder)) ' Integer)
Assert.True(Conversions.IsIdentityConversion(ClassifyDirectCastAssignment(m13p(d), m13p(d), methodBodyBinder))) ' Long)
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(d), m13p(c), methodBodyBinder)) ' Long) 'error BC30311: Value of type 'Integer' cannot be converted to 'Long'.
Assert.True(Conversions.IsIdentityConversion(ClassifyDirectCastAssignment(m13p(e), m13p(e), methodBodyBinder))) ' Enum1)
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(e), m13p(f), methodBodyBinder)) ' Enum1) 'error BC30311: Value of type 'Enum2' cannot be converted to 'Enum1'.
Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyDirectCastAssignment(m13p(e), m13p(g), methodBodyBinder)) ' Enum1)
Assert.True(Conversions.IsIdentityConversion(ClassifyDirectCastAssignment(m13p(f), m13p(f), methodBodyBinder))) ' Enum2)
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(f), m13p(g), methodBodyBinder)) ' Enum2) ' error BC30311: Value of type 'Enum4' cannot be converted to 'Enum2'.
Assert.Equal(ConversionKind.WideningArray, ClassifyDirectCastAssignment(m13p(h), m13p(i), methodBodyBinder)) ' Class8())
Assert.Equal(ConversionKind.NarrowingArray, ClassifyDirectCastAssignment(m13p(i), m13p(h), methodBodyBinder)) ' Class9())
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(i), m13p(j), methodBodyBinder)) ' Class9()) ' error BC30332: Value of type '1-dimensional array of Class11' cannot be converted to '1-dimensional array of Class9' because 'Class11' is not derived from 'Class9'.
Assert.True(Conversions.IsIdentityConversion(ClassifyDirectCastAssignment(m13p(k), m13p(k), methodBodyBinder))) ' MT1)
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(k), m13p(l), methodBodyBinder)) ' MT1) ' error BC30311: Value of type 'MT2' cannot be converted to 'MT1'.
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyDirectCastAssignment(m13p(k), m13p(m), methodBodyBinder)) ' MT1)
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(k), m13p(q), methodBodyBinder)) ' MT1) ' error BC30311: Value of type 'MT4' cannot be converted to 'MT1'.
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(l), m13p(k), methodBodyBinder)) ' MT2) ' Value of type 'MT1' cannot be converted to 'MT2'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyDirectCastAssignment(m13p(m), m13p(k), methodBodyBinder)) ' MT3)
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(n), m13p(o), methodBodyBinder)) ' MT1()) ' Value of type '1-dimensional array of MT2' cannot be converted to '1-dimensional array of MT1' because 'MT2' is not derived from 'MT1'.
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(n), m13p(p), methodBodyBinder)) ' MT1()) ' error BC30332: Value of type '2-dimensional array of MT2' cannot be converted to '1-dimensional array of MT1' because 'MT2' is not derived from 'MT1'.
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(n), m13p(u), methodBodyBinder)) ' MT1()) ' error BC30332: Value of type '1-dimensional array of Integer' cannot be converted to '1-dimensional array of MT1' because 'Integer' is not derived from 'MT1'.
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(q), m13p(k), methodBodyBinder)) ' MT4) ' error BC30311: Value of type 'MT1' cannot be converted to 'MT4'.
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(q), m13p(b), methodBodyBinder)) ' MT4) ' error BC30311: Value of type 'System.ValueType' cannot be converted
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(q), m13p(c), methodBodyBinder)) ' MT4) ' error BC30311: Value of type 'Integer' cannot be converted to 'MT4'
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(r), m13p(s), methodBodyBinder)) ' MT5) ' error BC30311: Value of type 'MT6' cannot be converted to 'MT5'.
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(r), m13p(t), methodBodyBinder)) ' MT5) ' error BC30311: Value of type 'MT7' cannot be converted to 'MT5'.
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(r), m13p(w), methodBodyBinder)) ' MT5) ' error BC30311: Value of type 'MT8' cannot be converted to 'MT5'.
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(s), m13p(r), methodBodyBinder)) ' MT6) ' error BC30311: Value of type 'MT5' cannot be converted to 'MT6'.
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(s), m13p(t), methodBodyBinder)) ' MT6) ' error BC30311: Value of type 'MT7' cannot be converted to 'MT6'.
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyDirectCastAssignment(m13p(s), m13p(w), methodBodyBinder)) ' MT6)
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(t), m13p(r), methodBodyBinder)) ' MT7) ' error BC30311: Value of type 'MT5' cannot be converted to 'MT7'.
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(t), m13p(s), methodBodyBinder)) ' MT7) ' error BC30311: Value of type 'MT6' cannot be converted to 'MT7'.
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(t), m13p(w), methodBodyBinder)) ' MT7) ' error BC30311: Value of type 'MT8' cannot be converted to 'MT7'.
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(u), m13p(n), methodBodyBinder)) ' Integer()) 'error BC30332: Value of type '1-dimensional array of MT1' cannot be converted to '1-dimensional array of Integer' because 'MT1' is not derived from 'Integer'.
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(u), m13p(v), methodBodyBinder)) ' Integer()) 'error BC30332: Value of type '1-dimensional array of MT4' cannot be converted to '1-dimensional array of Integer' because 'MT4' is not derived from 'Integer'.
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(v), m13p(u), methodBodyBinder)) ' MT4()) 'error BC30332: Value of type '1-dimensional array of Integer' cannot be converted to '1-dimensional array of MT4' because 'Integer' is not derived from 'MT4'.
Dim [nothing] = New BoundLiteral(DirectCast(DirectCast(dummyTree.GetRoot(Nothing), VisualBasicSyntaxNode), VisualBasicSyntaxNode), ConstantValue.Nothing, Nothing)
Dim intZero = New BoundLiteral(DirectCast(DirectCast(dummyTree.GetRoot(Nothing), VisualBasicSyntaxNode), VisualBasicSyntaxNode), ConstantValue.Create(0I), m13p(c))
Dim longZero = New BoundLiteral(DirectCast(DirectCast(dummyTree.GetRoot(Nothing), VisualBasicSyntaxNode), VisualBasicSyntaxNode), ConstantValue.Create(0L), m13p(d))
Assert.Equal(ConversionKind.WideningNothingLiteral, ClassifyDirectCastAssignment(m13p(a), [nothing], methodBodyBinder))
Assert.Equal(ConversionKind.WideningNothingLiteral, ClassifyDirectCastAssignment(m13p(b), [nothing], methodBodyBinder))
Assert.Equal(ConversionKind.WideningNothingLiteral, ClassifyDirectCastAssignment(m13p(c), [nothing], methodBodyBinder))
Assert.True(Conversions.IsIdentityConversion(ClassifyDirectCastAssignment(m13p(c), intZero, methodBodyBinder)))
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(c), longZero, methodBodyBinder)) 'error BC30311: Value of type 'Long' cannot be converted to 'Integer'.
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(d), intZero, methodBodyBinder)) ' error BC30311: Value of type 'Integer' cannot be converted to 'Long'.
Assert.True(Conversions.IsIdentityConversion(ClassifyDirectCastAssignment(m13p(d), longZero, methodBodyBinder)))
Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyDirectCastAssignment(m13p(e), intZero, methodBodyBinder))
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(e), longZero, methodBodyBinder)) ' error BC30311: Value of type 'Long' cannot be converted to 'Enum1'.
Assert.Equal(ConversionKind.WideningNothingLiteral, ClassifyDirectCastAssignment(m13p(e), [nothing], methodBodyBinder))
Assert.Equal(ConversionKind.WideningNothingLiteral, ClassifyDirectCastAssignment(m13p(k), [nothing], methodBodyBinder))
Assert.Equal(ConversionKind.WideningNothingLiteral, ClassifyDirectCastAssignment(m13p(q), [nothing], methodBodyBinder))
Assert.Equal(ConversionKind.WideningReference, ClassifyTryCastAssignment(m13p(a), m13p(b), methodBodyBinder)) ' Object)
Assert.Equal(ConversionKind.WideningValue, ClassifyTryCastAssignment(m13p(a), m13p(c), methodBodyBinder)) ' Object)
Assert.Equal(ConversionKind.NarrowingReference, ClassifyTryCastAssignment(m13p(b), m13p(a), methodBodyBinder)) ' ValueType)
Assert.Equal(ConversionKind.WideningValue, ClassifyTryCastAssignment(m13p(b), m13p(c), methodBodyBinder)) ' ValueType)
Assert.Equal(ConversionKind.NarrowingValue, ClassifyTryCastAssignment(m13p(c), m13p(a), methodBodyBinder)) ' Integer) ' error BC30792: 'TryCast' operand must be reference type, but 'Integer' is a value type.
Assert.Equal(ConversionKind.NarrowingValue, ClassifyTryCastAssignment(m13p(c), m13p(b), methodBodyBinder)) ' Integer) ' error BC30792: 'TryCast' operand must be reference type, but 'Integer' is a value type.
Assert.Equal(ConversionKind.Identity, ClassifyTryCastAssignment(m13p(c), m13p(c), methodBodyBinder)) ' Integer) ' error BC30792: 'TryCast' operand must be reference type, but 'Integer' is a value type.
Assert.Equal(NoConversion, ClassifyTryCastAssignment(m13p(c), m13p(d), methodBodyBinder)) ' Integer) ' error BC30792: 'TryCast' operand must be reference type, but 'Integer' is a value type.
Assert.Equal(ConversionKind.WideningNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyTryCastAssignment(m13p(c), m13p(e), methodBodyBinder)) ' Integer) ' error BC30792: 'TryCast' operand must be reference type, but 'Integer' is a value type.
Assert.Equal(ConversionKind.Identity, ClassifyTryCastAssignment(m13p(d), m13p(d), methodBodyBinder)) ' Long) ' error BC30792: 'TryCast' operand must be reference type, but 'Long' is a value type.
Assert.Equal(NoConversion, ClassifyTryCastAssignment(m13p(d), m13p(c), methodBodyBinder)) ' Long) ' error BC30792: 'TryCast' operand must be reference type, but 'Long' is a value type.
Assert.Equal(ConversionKind.Identity, ClassifyTryCastAssignment(m13p(e), m13p(e), methodBodyBinder)) ' Enum1) ' error BC30792: 'TryCast' operand must be reference type, but 'Enum1' is a value type.
Assert.Equal(NoConversion, ClassifyTryCastAssignment(m13p(e), m13p(f), methodBodyBinder)) ' Enum1) ' error BC30792: 'TryCast' operand must be reference type, but 'Enum1' is a value type.
Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyTryCastAssignment(m13p(e), m13p(g), methodBodyBinder)) ' Enum1) ' error BC30792: 'TryCast' operand must be reference type, but 'Enum1' is a value type.
Assert.Equal(ConversionKind.Identity, ClassifyTryCastAssignment(m13p(f), m13p(f), methodBodyBinder)) ' Enum2) ' error BC30792: 'TryCast' operand must be reference type, but 'Enum2' is a value type.
Assert.Equal(NoConversion, ClassifyTryCastAssignment(m13p(f), m13p(g), methodBodyBinder)) ' Enum2) ' error BC30792: 'TryCast' operand must be reference type, but 'Enum2' is a value type.
Assert.Equal(ConversionKind.WideningArray, ClassifyTryCastAssignment(m13p(h), m13p(i), methodBodyBinder)) ' Class8())
Assert.Equal(ConversionKind.NarrowingArray, ClassifyTryCastAssignment(m13p(i), m13p(h), methodBodyBinder)) ' Class9())
Assert.Equal(NoConversion, ClassifyTryCastAssignment(m13p(i), m13p(j), methodBodyBinder)) ' Class9()) ' error BC30332: Value of type '1-dimensional array of Class11' cannot be converted to '1-dimensional array of Class9' because 'Class11' is not derived from 'Class9'.
Assert.Equal(ConversionKind.Identity, ClassifyTryCastAssignment(m13p(k), m13p(k), methodBodyBinder)) ' MT1) ' error BC30793: 'TryCast' operands must be class-constrained type parameter, but 'MT1' has no class constraint.
Assert.Equal(ConversionKind.Narrowing, ClassifyTryCastAssignment(m13p(k), m13p(l), methodBodyBinder)) ' MT1) ' error BC30793: 'TryCast' operands must be class-constrained type parameter, but 'MT1' has no class constraint.
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyTryCastAssignment(m13p(k), m13p(m), methodBodyBinder)) ' MT1) ' error BC30793: 'TryCast' operands must be class-constrained type parameter, but 'MT1' has no class constraint.
Assert.Equal(ConversionKind.Narrowing, ClassifyTryCastAssignment(m13p(k), m13p(q), methodBodyBinder)) ' MT1) ' error BC30793: 'TryCast' operands must be class-constrained type parameter, but 'MT1' has no class constraint.
Assert.Equal(ConversionKind.Narrowing, ClassifyTryCastAssignment(m13p(l), m13p(k), methodBodyBinder)) ' MT2) ' error BC30793: 'TryCast' operands must be class-constrained type parameter, but 'MT2' has no class constraint.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyTryCastAssignment(m13p(m), m13p(k), methodBodyBinder)) ' MT3) ' error BC30793: 'TryCast' operands must be class-constrained type parameter, but 'MT3' has no class constraint.
Assert.Equal(ConversionKind.Narrowing, ClassifyTryCastAssignment(m13p(n), m13p(o), methodBodyBinder)) ' MT1())
Assert.Equal(ConversionKind.Narrowing, ClassifyTryCastAssignment(m13p(n), m13p(p), methodBodyBinder)) ' MT1())
Assert.Equal(ConversionKind.Narrowing, ClassifyTryCastAssignment(m13p(n), m13p(u), methodBodyBinder)) ' MT1())
Assert.Equal(ConversionKind.Narrowing, ClassifyTryCastAssignment(m13p(q), m13p(k), methodBodyBinder)) ' MT4)
Assert.Equal(ConversionKind.Narrowing, ClassifyTryCastAssignment(m13p(q), m13p(b), methodBodyBinder)) ' MT4)
Assert.Equal(ConversionKind.Narrowing, ClassifyTryCastAssignment(m13p(q), m13p(c), methodBodyBinder)) ' MT4)
Assert.Equal(ConversionKind.Narrowing, ClassifyTryCastAssignment(m13p(r), m13p(s), methodBodyBinder)) ' MT5)
Assert.Equal(ConversionKind.Narrowing, ClassifyTryCastAssignment(m13p(r), m13p(t), methodBodyBinder)) ' MT5)
Assert.Equal(ConversionKind.Narrowing, ClassifyTryCastAssignment(m13p(r), m13p(w), methodBodyBinder)) ' MT5)
Assert.Equal(ConversionKind.Narrowing, ClassifyTryCastAssignment(m13p(s), m13p(r), methodBodyBinder)) ' MT6)
Assert.Equal(NoConversion, ClassifyTryCastAssignment(m13p(s), m13p(t), methodBodyBinder)) ' MT6) ' error BC30311: Value of type 'MT7' cannot be converted to 'MT6'.
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyTryCastAssignment(m13p(s), m13p(w), methodBodyBinder)) ' MT6)
Assert.Equal(ConversionKind.Narrowing, ClassifyTryCastAssignment(m13p(t), m13p(r), methodBodyBinder)) ' MT7)
Assert.Equal(NoConversion, ClassifyTryCastAssignment(m13p(t), m13p(s), methodBodyBinder)) ' MT7) ' error BC30311: Value of type 'MT6' cannot be converted to 'MT7'.
Assert.Equal(NoConversion, ClassifyTryCastAssignment(m13p(t), m13p(w), methodBodyBinder)) ' MT7) ' error BC30311: Value of type 'MT8' cannot be converted to 'MT7'.
Assert.Equal(ConversionKind.Narrowing, ClassifyTryCastAssignment(m13p(u), m13p(n), methodBodyBinder)) ' Integer())
Assert.Equal(NoConversion, ClassifyTryCastAssignment(m13p(u), m13p(v), methodBodyBinder)) ' Integer()) 'error BC30332: Value of type '1-dimensional array of MT4' cannot be converted to '1-dimensional array of Integer' because 'MT4' is not derived from 'Integer'.
Assert.Equal(NoConversion, ClassifyTryCastAssignment(m13p(v), m13p(u), methodBodyBinder)) ' MT4()) 'error BC30332: Value of type '1-dimensional array of Integer' cannot be converted to '1-dimensional array of MT4' because 'Integer' is not derived from 'MT4'.
Assert.Equal(ConversionKind.WideningNothingLiteral, ClassifyTryCastAssignment(m13p(a), [nothing], methodBodyBinder))
Assert.Equal(ConversionKind.WideningValue, ClassifyTryCastAssignment(m13p(a), intZero, methodBodyBinder))
Assert.Equal(ConversionKind.WideningNothingLiteral, ClassifyTryCastAssignment(m13p(b), [nothing], methodBodyBinder))
Assert.Equal(ConversionKind.WideningNothingLiteral, ClassifyTryCastAssignment(m13p(c), [nothing], methodBodyBinder)) ' error BC30792: 'TryCast' operand must be reference type, but 'Integer' is a value type.
Assert.Equal(ConversionKind.Identity, ClassifyTryCastAssignment(m13p(c), intZero, methodBodyBinder)) ' error BC30792: 'TryCast' operand must be reference type, but 'Integer' is a value type.
Assert.Equal(NoConversion, ClassifyTryCastAssignment(m13p(c), longZero, methodBodyBinder)) ' error BC30792: 'TryCast' operand must be reference type, but 'Integer' is a value type.
Assert.Equal(NoConversion, ClassifyTryCastAssignment(m13p(d), intZero, methodBodyBinder)) ' error BC30792: 'TryCast' operand must be reference type, but 'Long' is a value type.
Assert.Equal(ConversionKind.Identity, ClassifyTryCastAssignment(m13p(d), longZero, methodBodyBinder)) ' error BC30792: 'TryCast' operand must be reference type, but 'Long' is a value type.
Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyTryCastAssignment(m13p(e), intZero, methodBodyBinder)) ' error BC30792: 'TryCast' operand must be reference type, but 'Enum1' is a value type.
Assert.Equal(NoConversion, ClassifyTryCastAssignment(m13p(e), longZero, methodBodyBinder)) ' error BC30792: 'TryCast' operand must be reference type, but 'Enum1' is a value type.
Assert.Equal(ConversionKind.WideningNothingLiteral, ClassifyTryCastAssignment(m13p(e), [nothing], methodBodyBinder)) ' error BC30792: 'TryCast' operand must be reference type, but 'Enum1' is a value type.
Assert.Equal(ConversionKind.WideningNothingLiteral, ClassifyTryCastAssignment(m13p(k), [nothing], methodBodyBinder)) ' error BC30793: 'TryCast' operands must be class-constrained type parameter, but 'MT1' has no class constraint.
Assert.Equal(ConversionKind.WideningNothingLiteral, ClassifyTryCastAssignment(m13p(q), [nothing], methodBodyBinder))
End Sub
Private Shared Function ClassifyDirectCastAssignment([to] As TypeSymbol, [from] As TypeSymbol, binder As Binder) As ConversionKind
Dim result As ConversionKind = Conversions.ClassifyDirectCastConversion([from], [to], Nothing) And Not ConversionKind.MightSucceedAtRuntime
Return result
End Function
Private Shared Function ClassifyDirectCastAssignment([to] As TypeSymbol, [from] As BoundLiteral, binder As Binder) As ConversionKind
Dim result As ConversionKind = Conversions.ClassifyDirectCastConversion([from], [to], binder, Nothing)
Return result
End Function
Private Shared Function ClassifyTryCastAssignment([to] As TypeSymbol, [from] As TypeSymbol, binder As Binder) As ConversionKind
Dim result As ConversionKind = Conversions.ClassifyTryCastConversion([from], [to], Nothing)
Return result
End Function
Private Shared Function ClassifyTryCastAssignment([to] As TypeSymbol, [from] As BoundLiteral, binder As Binder) As ConversionKind
Dim result As ConversionKind = Conversions.ClassifyTryCastConversion([from], [to], binder, Nothing)
Return result
End Function
Private Shared Function ClassifyConversion(source As TypeSymbol, destination As TypeSymbol) As ConversionKind
Dim result As KeyValuePair(Of ConversionKind, MethodSymbol) = Conversions.ClassifyConversion(source, destination, Nothing)
Assert.Null(result.Value)
Return result.Key
End Function
Private Shared Function ClassifyConversion(source As BoundExpression, destination As TypeSymbol, binder As Binder) As ConversionKind
Dim result As KeyValuePair(Of ConversionKind, MethodSymbol) = Conversions.ClassifyConversion(source, destination, binder, Nothing)
Assert.Null(result.Value)
Return result.Key
End Function
<Fact()>
Public Sub ConstantExpressionConversions()
Dim dummyCode =
<file>
Class C1
Shared Sub MethodDecl()
End Sub
End Class
</file>
Dim dummyTree = VisualBasicSyntaxTree.ParseText(dummyCode.Value)
Dim c1 = VisualBasicCompilation.Create("Test", syntaxTrees:={dummyTree}, references:={TestReferences.NetFx.v4_0_21006.mscorlib})
Dim sourceModule = DirectCast(c1.Assembly.Modules(0), SourceModuleSymbol)
Dim methodDeclSymbol = DirectCast(sourceModule.GlobalNamespace.GetTypeMembers("C1").Single().GetMembers("MethodDecl").Single(), SourceMethodSymbol)
Dim methodBodyBinder = BinderBuilder.CreateBinderForMethodBody(sourceModule, dummyTree, methodDeclSymbol)
Assert.True(c1.Options.CheckOverflow)
Dim objectType = c1.GetSpecialType(System_Object)
Dim booleanType = c1.GetSpecialType(System_Boolean)
Dim byteType = c1.GetSpecialType(System_Byte)
Dim sbyteType = c1.GetSpecialType(System_SByte)
Dim int16Type = c1.GetSpecialType(System_Int16)
Dim uint16Type = c1.GetSpecialType(System_UInt16)
Dim int32Type = c1.GetSpecialType(System_Int32)
Dim uint32Type = c1.GetSpecialType(System_UInt32)
Dim int64Type = c1.GetSpecialType(System_Int64)
Dim uint64Type = c1.GetSpecialType(System_UInt64)
Dim doubleType = c1.GetSpecialType(System_Double)
Dim singleType = c1.GetSpecialType(System_Single)
Dim decimalType = c1.GetSpecialType(System_Decimal)
Dim dateType = c1.GetSpecialType(System_DateTime)
Dim stringType = c1.GetSpecialType(System_String)
Dim charType = c1.GetSpecialType(System_Char)
Dim intPtrType = c1.GetSpecialType(System_IntPtr)
Dim typeCodeType = c1.GlobalNamespace.GetMembers("System").OfType(Of NamespaceSymbol)().Single().GetTypeMembers("TypeCode").Single()
Dim allTestTypes = New TypeSymbol() {
objectType, booleanType, byteType, sbyteType, int16Type, uint16Type, int32Type, uint32Type, int64Type, uint64Type, doubleType, singleType, decimalType, dateType,
stringType, charType, intPtrType, typeCodeType}
Dim convertableTypes = New HashSet(Of TypeSymbol)({
booleanType, byteType, sbyteType, int16Type, uint16Type, int32Type, uint32Type, int64Type, uint64Type, doubleType, singleType, decimalType, dateType,
stringType, charType, typeCodeType})
Dim integralTypes = New HashSet(Of TypeSymbol)({
byteType, sbyteType, int16Type, uint16Type, int32Type, uint32Type, int64Type, uint64Type, typeCodeType})
Dim unsignedTypes = New HashSet(Of TypeSymbol)({
byteType, uint16Type, uint32Type, uint64Type})
Dim numericTypes = New HashSet(Of TypeSymbol)({
byteType, sbyteType, int16Type, uint16Type, int32Type, uint32Type, int64Type, uint64Type, doubleType, singleType, decimalType, typeCodeType})
Dim floatingTypes = New HashSet(Of TypeSymbol)({doubleType, singleType})
' -------------- NOTHING literal conversions
Dim _nothing = New BoundLiteral(DirectCast(DirectCast(dummyTree.GetRoot(Nothing), VisualBasicSyntaxNode), VisualBasicSyntaxNode), ConstantValue.Nothing, Nothing)
Dim resultValue As ConstantValue
Dim integerOverflow As Boolean
Dim literal As BoundExpression
Dim constant As BoundConversion
For Each testType In allTestTypes
Assert.Equal(ConversionKind.WideningNothingLiteral, ClassifyConversion(_nothing, testType, methodBodyBinder))
resultValue = Conversions.TryFoldConstantConversion(_nothing, testType, integerOverflow)
If convertableTypes.Contains(testType) Then
Assert.NotNull(resultValue)
Assert.Equal(If(testType.IsStringType(), ConstantValueTypeDiscriminator.Nothing, testType.GetConstantValueTypeDiscriminator()), resultValue.Discriminator)
If testType IsNot dateType Then
Assert.Equal(0, Convert.ToInt64(resultValue.Value))
If testType Is stringType Then
Assert.Null(resultValue.StringValue)
End If
Else
Assert.Equal(New DateTime(), resultValue.DateTimeValue)
End If
Else
Assert.Null(resultValue)
End If
Assert.False(integerOverflow)
If resultValue IsNot Nothing Then
Assert.False(resultValue.IsBad)
End If
Next
' -------------- integer literal zero to enum conversions
For Each integralType In integralTypes
Dim zero = ConstantValue.Default(integralType.GetConstantValueTypeDiscriminator())
literal = New BoundLiteral(DirectCast(DirectCast(dummyTree.GetRoot(Nothing), VisualBasicSyntaxNode), VisualBasicSyntaxNode), zero, integralType)
constant = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), literal, ConversionKind.Widening, True, True, zero, integralType, Nothing)
Assert.Equal(If(integralType Is int32Type, ConversionKind.WideningNumeric Or ConversionKind.InvolvesEnumTypeConversions, If(integralType Is typeCodeType, ConversionKind.Identity, ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions)),
ClassifyConversion(literal, typeCodeType, methodBodyBinder))
resultValue = Conversions.TryFoldConstantConversion(literal, typeCodeType, integerOverflow)
Assert.NotNull(resultValue)
Assert.False(integerOverflow)
Assert.Equal(ConstantValueTypeDiscriminator.Int32, resultValue.Discriminator)
Assert.Equal(0, resultValue.Int32Value)
Assert.Equal(If(integralType Is typeCodeType, ConversionKind.Identity, ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions), ClassifyConversion(constant, typeCodeType, methodBodyBinder))
resultValue = Conversions.TryFoldConstantConversion(constant, typeCodeType, integerOverflow)
Assert.NotNull(resultValue)
Assert.False(integerOverflow)
Assert.Equal(ConstantValueTypeDiscriminator.Int32, resultValue.Discriminator)
Assert.Equal(0, resultValue.Int32Value)
Next
For Each convertibleType In convertableTypes
If Not integralTypes.Contains(convertibleType) Then
Dim zero = ConstantValue.Default(If(convertibleType.IsStringType(), ConstantValueTypeDiscriminator.Nothing, convertibleType.GetConstantValueTypeDiscriminator()))
If convertibleType.IsStringType() Then
literal = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), New BoundLiteral(DirectCast(DirectCast(dummyTree.GetRoot(Nothing), VisualBasicSyntaxNode), VisualBasicSyntaxNode), ConstantValue.Null, Nothing), ConversionKind.WideningNothingLiteral, False, True, zero, convertibleType, Nothing)
Else
literal = New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), zero, convertibleType)
End If
Assert.Equal(ClassifyConversion(convertibleType, typeCodeType), ClassifyConversion(literal, typeCodeType, methodBodyBinder))
resultValue = Conversions.TryFoldConstantConversion(literal, typeCodeType, integerOverflow)
If Not numericTypes.Contains(convertibleType) AndAlso convertibleType IsNot booleanType Then
Assert.Null(resultValue)
Assert.False(integerOverflow)
Else
Assert.NotNull(resultValue)
Assert.False(integerOverflow)
Assert.Equal(ConstantValueTypeDiscriminator.Int32, resultValue.Discriminator)
Assert.Equal(0, resultValue.Int32Value)
End If
End If
Next
' -------------- Numeric conversions
Dim nullableType = c1.GetSpecialType(System_Nullable_T)
' Zero
For Each type1 In convertableTypes
Dim zero = ConstantValue.Default(If(type1.IsStringType(), ConstantValueTypeDiscriminator.Nothing, type1.GetConstantValueTypeDiscriminator()))
If type1.IsStringType() Then
literal = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), New BoundLiteral(DirectCast(dummyTree.GetRoot(Nothing), VisualBasicSyntaxNode), ConstantValue.Null, Nothing), ConversionKind.WideningNothingLiteral, False, True, zero, type1, Nothing)
Else
literal = New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), zero, type1)
End If
constant = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing),
New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), ConstantValue.Default(ConstantValueTypeDiscriminator.Int32), int32Type),
ConversionKind.Widening, True, True, zero, type1, Nothing)
For Each type2 In allTestTypes
Dim expectedConv As ConversionKind
If numericTypes.Contains(type1) AndAlso numericTypes.Contains(type2) Then
If type1 Is type2 Then
expectedConv = ConversionKind.Identity
ElseIf type1.IsEnumType() Then
expectedConv = ClassifyConversion(type1.GetEnumUnderlyingTypeOrSelf(), type2)
If Conversions.IsWideningConversion(expectedConv) Then
expectedConv = expectedConv Or ConversionKind.InvolvesEnumTypeConversions
If (expectedConv And ConversionKind.Identity) <> 0 Then
expectedConv = (expectedConv And Not ConversionKind.Identity) Or ConversionKind.Widening Or ConversionKind.Numeric
End If
ElseIf Conversions.IsNarrowingConversion(expectedConv) Then
expectedConv = expectedConv Or ConversionKind.InvolvesEnumTypeConversions
End If
ElseIf type2.IsEnumType() Then
expectedConv = ClassifyConversion(type1, type2.GetEnumUnderlyingTypeOrSelf())
If Not Conversions.NoConversion(expectedConv) Then
expectedConv = (expectedConv And Not ConversionKind.Widening) Or ConversionKind.Narrowing Or ConversionKind.InvolvesEnumTypeConversions
If (expectedConv And ConversionKind.Identity) <> 0 Then
expectedConv = (expectedConv And Not ConversionKind.Identity) Or ConversionKind.Numeric
End If
End If
ElseIf integralTypes.Contains(type2) Then
If integralTypes.Contains(type1) Then
If Conversions.IsNarrowingConversion(ClassifyConversion(type1, type2)) Then
expectedConv = ConversionKind.WideningNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant
Else
expectedConv = ConversionKind.WideningNumeric
End If
Else
expectedConv = ConversionKind.NarrowingNumeric
End If
ElseIf floatingTypes.Contains(type2) Then
If Conversions.IsNarrowingConversion(ClassifyConversion(type1, type2)) Then
expectedConv = ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant
Else
expectedConv = ConversionKind.WideningNumeric
End If
Else
Assert.Same(decimalType, type2)
expectedConv = ClassifyConversion(type1, type2)
End If
Assert.Equal(If(type2.IsEnumType() AndAlso type1 Is int32Type, ConversionKind.WideningNumeric Or ConversionKind.InvolvesEnumTypeConversions, expectedConv), ClassifyConversion(literal, type2, methodBodyBinder))
Assert.Equal(expectedConv, ClassifyConversion(constant, type2, methodBodyBinder))
resultValue = Conversions.TryFoldConstantConversion(literal, type2, integerOverflow)
Assert.NotNull(resultValue)
Assert.False(integerOverflow)
Assert.False(resultValue.IsBad)
Assert.Equal(type2.GetConstantValueTypeDiscriminator(), resultValue.Discriminator)
Assert.Equal(0, Convert.ToDouble(resultValue.Value))
resultValue = Conversions.TryFoldConstantConversion(constant, type2, integerOverflow)
Assert.NotNull(resultValue)
Assert.False(integerOverflow)
Assert.False(resultValue.IsBad)
Assert.Equal(type2.GetConstantValueTypeDiscriminator(), resultValue.Discriminator)
Assert.Equal(0, Convert.ToDouble(resultValue.Value))
Dim nullableType2 = nullableType.Construct(type2)
expectedConv = ClassifyConversion(type1, nullableType2) Or (expectedConv And ConversionKind.InvolvesNarrowingFromNumericConstant)
If type2.IsEnumType() AndAlso type1.SpecialType = SpecialType.System_Int32 Then
Assert.Equal(expectedConv Or ConversionKind.InvolvesNarrowingFromNumericConstant, ClassifyConversion(literal, nullableType2, methodBodyBinder))
Else
Assert.Equal(expectedConv, ClassifyConversion(literal, nullableType2, methodBodyBinder))
End If
Assert.Equal(expectedConv, ClassifyConversion(constant, nullableType2, methodBodyBinder))
resultValue = Conversions.TryFoldConstantConversion(literal, nullableType2, integerOverflow)
Assert.Null(resultValue)
Assert.False(integerOverflow)
resultValue = Conversions.TryFoldConstantConversion(constant, nullableType2, integerOverflow)
Assert.Null(resultValue)
Assert.False(integerOverflow)
ElseIf type1 Is booleanType AndAlso numericTypes.Contains(type2) Then
' Will test separately
Continue For
ElseIf type2 Is booleanType AndAlso numericTypes.Contains(type1) Then
Assert.Equal(If(type1 Is typeCodeType, ConversionKind.NarrowingBoolean Or ConversionKind.InvolvesEnumTypeConversions, ConversionKind.NarrowingBoolean), ClassifyConversion(literal, type2, methodBodyBinder))
Assert.Equal(If(type1 Is typeCodeType, ConversionKind.NarrowingBoolean Or ConversionKind.InvolvesEnumTypeConversions, ConversionKind.NarrowingBoolean), ClassifyConversion(constant, type2, methodBodyBinder))
resultValue = Conversions.TryFoldConstantConversion(literal, type2, integerOverflow)
Assert.NotNull(resultValue)
Assert.False(integerOverflow)
Assert.False(resultValue.IsBad)
Assert.Equal(type2.GetConstantValueTypeDiscriminator(), resultValue.Discriminator)
Assert.False(DirectCast(resultValue.Value, Boolean))
resultValue = Conversions.TryFoldConstantConversion(constant, type2, integerOverflow)
Assert.NotNull(resultValue)
Assert.False(integerOverflow)
Assert.False(resultValue.IsBad)
Assert.Equal(type2.GetConstantValueTypeDiscriminator(), resultValue.Discriminator)
Assert.False(DirectCast(resultValue.Value, Boolean))
ElseIf type1 Is stringType AndAlso type2 Is charType Then
' Will test separately
Continue For
ElseIf type1 Is charType AndAlso type2 Is stringType Then
' Will test separately
Continue For
ElseIf type2 Is typeCodeType AndAlso integralTypes.Contains(type1) Then
' Already tested
Continue For
ElseIf (type1 Is dateType AndAlso type2 Is dateType) OrElse
(type1 Is booleanType AndAlso type2 Is booleanType) OrElse
(type1 Is stringType AndAlso type2 Is stringType) OrElse
(type1 Is charType AndAlso type2 Is charType) Then
Assert.True(Conversions.IsIdentityConversion(ClassifyConversion(literal, type2, methodBodyBinder)))
Assert.True(Conversions.IsIdentityConversion(ClassifyConversion(constant, type2, methodBodyBinder)))
resultValue = Conversions.TryFoldConstantConversion(literal, type2, integerOverflow)
Assert.NotNull(resultValue)
Assert.False(integerOverflow)
Assert.False(resultValue.IsBad)
Assert.True(type2.IsValidForConstantValue(resultValue))
Assert.Equal(literal.ConstantValueOpt, resultValue)
resultValue = Conversions.TryFoldConstantConversion(constant, type2, integerOverflow)
Assert.NotNull(resultValue)
Assert.False(integerOverflow)
Assert.False(resultValue.IsBad)
Assert.True(type2.IsValidForConstantValue(resultValue))
Assert.Equal(constant.ConstantValueOpt, resultValue)
Else
Dim expectedConv1 As KeyValuePair(Of ConversionKind, MethodSymbol) = Conversions.ClassifyConversion(type1, type2, Nothing)
Assert.Equal(expectedConv1, Conversions.ClassifyConversion(literal, type2, methodBodyBinder, Nothing))
Assert.Equal(expectedConv1, Conversions.ClassifyConversion(constant, type2, methodBodyBinder, Nothing))
resultValue = Conversions.TryFoldConstantConversion(literal, type2, integerOverflow)
Assert.Null(resultValue)
Assert.False(integerOverflow)
resultValue = Conversions.TryFoldConstantConversion(constant, type2, integerOverflow)
Assert.Null(resultValue)
Assert.False(integerOverflow)
If type2.IsValueType Then
Dim nullableType2 = nullableType.Construct(type2)
expectedConv1 = Conversions.ClassifyConversion(type1, nullableType2, Nothing)
Assert.Equal(expectedConv1, Conversions.ClassifyConversion(literal, nullableType2, methodBodyBinder, Nothing))
Assert.Equal(expectedConv1, Conversions.ClassifyConversion(constant, nullableType2, methodBodyBinder, Nothing))
resultValue = Conversions.TryFoldConstantConversion(literal, nullableType2, integerOverflow)
Assert.Null(resultValue)
Assert.False(integerOverflow)
resultValue = Conversions.TryFoldConstantConversion(constant, nullableType2, integerOverflow)
Assert.Null(resultValue)
Assert.False(integerOverflow)
End If
End If
Next
Next
' -------- Numeric non-zero values
Dim nonZeroValues = New TypeAndValue() {
New TypeAndValue(sbyteType, SByte.MinValue),
New TypeAndValue(int16Type, Int16.MinValue),
New TypeAndValue(int32Type, Int32.MinValue),
New TypeAndValue(int64Type, Int64.MinValue),
New TypeAndValue(doubleType, Double.MinValue),
New TypeAndValue(singleType, Single.MinValue),
New TypeAndValue(decimalType, Decimal.MinValue),
New TypeAndValue(sbyteType, SByte.MaxValue),
New TypeAndValue(int16Type, Int16.MaxValue),
New TypeAndValue(int32Type, Int32.MaxValue),
New TypeAndValue(int64Type, Int64.MaxValue),
New TypeAndValue(byteType, Byte.MaxValue),
New TypeAndValue(uint16Type, UInt16.MaxValue),
New TypeAndValue(uint32Type, UInt32.MaxValue),
New TypeAndValue(uint64Type, UInt64.MaxValue),
New TypeAndValue(doubleType, Double.MaxValue),
New TypeAndValue(singleType, Single.MaxValue),
New TypeAndValue(decimalType, Decimal.MaxValue),
New TypeAndValue(sbyteType, CSByte(-1)),
New TypeAndValue(int16Type, CShort(-2)),
New TypeAndValue(int32Type, CInt(-3)),
New TypeAndValue(int64Type, CLng(-4)),
New TypeAndValue(sbyteType, CSByte(5)),
New TypeAndValue(int16Type, CShort(6)),
New TypeAndValue(int32Type, CInt(7)),
New TypeAndValue(int64Type, CLng(8)),
New TypeAndValue(doubleType, CDbl(-9)),
New TypeAndValue(singleType, CSng(-10)),
New TypeAndValue(decimalType, CDec(-11)),
New TypeAndValue(doubleType, CDbl(12)),
New TypeAndValue(singleType, CSng(13)),
New TypeAndValue(decimalType, CDec(14)),
New TypeAndValue(byteType, CByte(15)),
New TypeAndValue(uint16Type, CUShort(16)),
New TypeAndValue(uint32Type, CUInt(17)),
New TypeAndValue(uint64Type, CULng(18)),
New TypeAndValue(decimalType, CDec(-11.3)),
New TypeAndValue(doubleType, CDbl(&HF000000000000000UL)),
New TypeAndValue(doubleType, CDbl(&H70000000000000F0L)),
New TypeAndValue(typeCodeType, Int32.MinValue),
New TypeAndValue(typeCodeType, Int32.MaxValue),
New TypeAndValue(typeCodeType, CInt(-3)),
New TypeAndValue(typeCodeType, CInt(7))
}
Dim resultValue2 As ConstantValue
Dim integerOverflow2 As Boolean
For Each mv In nonZeroValues
Dim v = ConstantValue.Create(mv.Value, mv.Type.GetConstantValueTypeDiscriminator())
Assert.Equal(v.Discriminator, mv.Type.GetConstantValueTypeDiscriminator())
literal = New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), v, mv.Type)
constant = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing),
New BoundLiteral(DirectCast(dummyTree.GetRoot(Nothing), VisualBasicSyntaxNode), ConstantValue.Null, Nothing),
ConversionKind.Widening, True, True, v, mv.Type, Nothing)
For Each numericType In numericTypes
Dim typeConv = ClassifyConversion(mv.Type, numericType)
Dim conv = ClassifyConversion(literal, numericType, methodBodyBinder)
Dim conv2 = ClassifyConversion(constant, numericType, methodBodyBinder)
Assert.Equal(conv, conv2)
resultValue = Conversions.TryFoldConstantConversion(literal, numericType, integerOverflow)
resultValue2 = Conversions.TryFoldConstantConversion(constant, numericType, integerOverflow2)
Assert.Equal(resultValue Is Nothing, resultValue2 Is Nothing)
Assert.Equal(integerOverflow, integerOverflow2)
Assert.Equal(resultValue IsNot Nothing AndAlso resultValue.IsBad, resultValue2 IsNot Nothing AndAlso resultValue2.IsBad)
If resultValue IsNot Nothing Then
Assert.Equal(resultValue2, resultValue)
If Not resultValue.IsBad Then
Assert.Equal(numericType.GetConstantValueTypeDiscriminator(), resultValue.Discriminator)
End If
End If
Dim resultValueAsObject As Object = Nothing
Dim overflow As Boolean = False
Try
resultValueAsObject = CheckedConvert(v.Value, numericType)
Catch ex As OverflowException
overflow = True
End Try
If Not overflow Then
If Conversions.IsIdentityConversion(typeConv) Then
Assert.True(Conversions.IsIdentityConversion(conv))
ElseIf Conversions.IsNarrowingConversion(typeConv) Then
If mv.Type Is doubleType AndAlso numericType Is singleType Then
Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant, conv)
ElseIf integralTypes.Contains(mv.Type) AndAlso integralTypes.Contains(numericType) AndAlso Not mv.Type.IsEnumType() AndAlso Not numericType.IsEnumType() Then
Assert.Equal(ConversionKind.WideningNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant, conv)
Else
Assert.Equal(typeConv, conv)
End If
ElseIf mv.Type.IsEnumType() Then
Assert.Equal(ConversionKind.WideningNumeric Or ConversionKind.InvolvesEnumTypeConversions, conv)
Else
Assert.Equal(ConversionKind.WideningNumeric, conv)
End If
Assert.NotNull(resultValue)
Assert.False(integerOverflow)
Assert.False(resultValue.IsBad)
Assert.Equal(resultValueAsObject, resultValue.Value)
If mv.Type Is doubleType AndAlso numericType Is singleType Then
If v.DoubleValue = Double.MinValue Then
Dim min As Single = Double.MinValue
Assert.True(Single.IsNegativeInfinity(min))
Assert.Equal(resultValue.SingleValue, min)
ElseIf v.DoubleValue = Double.MaxValue Then
Dim max As Single = Double.MaxValue
Assert.Equal(Double.MaxValue, v.DoubleValue)
Assert.True(Single.IsPositiveInfinity(max))
Assert.Equal(resultValue.SingleValue, max)
End If
End If
ElseIf Not integralTypes.Contains(mv.Type) OrElse Not integralTypes.Contains(numericType) Then
'Assert.Equal(typeConv, conv)
If integralTypes.Contains(numericType) Then
Assert.NotNull(resultValue)
If resultValue.IsBad Then
Assert.False(integerOverflow)
Assert.Equal(ConversionKind.FailedDueToNumericOverflow, conv)
Else
Assert.True(integerOverflow)
Assert.Equal(ConversionKind.FailedDueToIntegerOverflow, conv)
Dim intermediate As Object
If unsignedTypes.Contains(numericType) Then
intermediate = Convert.ToUInt64(mv.Value)
Else
intermediate = Convert.ToInt64(mv.Value)
End If
Dim gotException As Boolean
Try
gotException = False
CheckedConvert(intermediate, numericType) ' Should get an overflow
Catch x As Exception
gotException = True
End Try
Assert.True(gotException)
Assert.Equal(UncheckedConvert(intermediate, numericType), resultValue.Value)
End If
Else
Assert.NotNull(resultValue)
Assert.False(integerOverflow)
Assert.True(resultValue.IsBad)
Assert.Equal(ConversionKind.FailedDueToNumericOverflow, conv)
End If
Else
' An integer overflow case
Assert.Equal(ConversionKind.FailedDueToIntegerOverflow, conv)
Assert.NotNull(resultValue)
Assert.True(integerOverflow)
Assert.False(resultValue.IsBad)
Assert.Equal(UncheckedConvert(v.Value, numericType), resultValue.Value)
End If
Dim nullableType2 = nullableType.Construct(numericType)
Dim zero = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), New BoundLiteral(DirectCast(dummyTree.GetRoot(Nothing), VisualBasicSyntaxNode), ConstantValue.Null, Nothing), ConversionKind.Widening, True, True, ConstantValue.Default(mv.Type.GetConstantValueTypeDiscriminator()), mv.Type, Nothing)
conv = ClassifyConversion(literal, numericType, methodBodyBinder)
If (conv And ConversionKind.FailedDueToNumericOverflowMask) = 0 Then
conv = ClassifyConversion(mv.Type, nullableType2) Or
(ClassifyConversion(zero, nullableType2, methodBodyBinder) And ConversionKind.InvolvesNarrowingFromNumericConstant)
End If
Assert.Equal(conv, ClassifyConversion(literal, nullableType2, methodBodyBinder))
Assert.Equal(conv, ClassifyConversion(constant, nullableType2, methodBodyBinder))
resultValue = Conversions.TryFoldConstantConversion(literal, nullableType2, integerOverflow)
Assert.Null(resultValue)
Assert.False(integerOverflow)
resultValue = Conversions.TryFoldConstantConversion(constant, nullableType2, integerOverflow)
Assert.Null(resultValue)
Assert.False(integerOverflow)
Next
Next
Dim dbl As Double = -1.5
Dim doubleValue = ConstantValue.Create(dbl)
constant = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), ConstantValue.Null, Nothing), ConversionKind.Widening, True, True, doubleValue, doubleType, Nothing)
resultValue = Conversions.TryFoldConstantConversion(constant, int32Type, integerOverflow)
Assert.NotNull(resultValue)
Assert.False(integerOverflow)
Assert.False(resultValue.IsBad)
Assert.Equal(-2, CInt(dbl))
Assert.Equal(-2, DirectCast(resultValue.Value, Int32))
dbl = -2.5
doubleValue = ConstantValue.Create(dbl)
constant = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), ConstantValue.Null, Nothing), ConversionKind.Widening, True, True, doubleValue, doubleType, Nothing)
resultValue = Conversions.TryFoldConstantConversion(constant, int32Type, integerOverflow)
Assert.NotNull(resultValue)
Assert.False(integerOverflow)
Assert.False(resultValue.IsBad)
Assert.Equal(-2, CInt(dbl))
Assert.Equal(-2, DirectCast(resultValue.Value, Int32))
dbl = 1.5
doubleValue = ConstantValue.Create(dbl)
constant = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), ConstantValue.Null, Nothing), ConversionKind.Widening, True, True, doubleValue, doubleType, Nothing)
resultValue = Conversions.TryFoldConstantConversion(constant, uint32Type, integerOverflow)
Assert.NotNull(resultValue)
Assert.False(integerOverflow)
Assert.False(resultValue.IsBad)
Assert.Equal(2UI, CUInt(dbl))
Assert.Equal(2UI, DirectCast(resultValue.Value, UInt32))
dbl = 2.5
doubleValue = ConstantValue.Create(dbl)
constant = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), ConstantValue.Null, Nothing), ConversionKind.Widening, True, True, doubleValue, doubleType, Nothing)
resultValue = Conversions.TryFoldConstantConversion(constant, uint32Type, integerOverflow)
Assert.NotNull(resultValue)
Assert.False(integerOverflow)
Assert.False(resultValue.IsBad)
Assert.Equal(2UI, CUInt(dbl))
Assert.Equal(2UI, DirectCast(resultValue.Value, UInt32))
dbl = 2147483648.0 * 4294967296.0 + 10
doubleValue = ConstantValue.Create(dbl)
constant = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), ConstantValue.Null, Nothing), ConversionKind.Widening, True, True, doubleValue, doubleType, Nothing)
resultValue = Conversions.TryFoldConstantConversion(constant, uint64Type, integerOverflow)
Assert.NotNull(resultValue)
Assert.False(integerOverflow)
Assert.False(resultValue.IsBad)
Assert.Equal(Convert.ToUInt64(dbl), DirectCast(resultValue.Value, UInt64))
' ------- Boolean
Dim falseValue = ConstantValue.Create(False)
Assert.Equal(falseValue.Discriminator, booleanType.GetConstantValueTypeDiscriminator())
literal = New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), falseValue, booleanType)
constant = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), ConstantValue.Null, Nothing), ConversionKind.Widening, True, True, falseValue, booleanType, Nothing)
For Each numericType In numericTypes
Dim typeConv = ClassifyConversion(booleanType, numericType)
Dim conv = ClassifyConversion(literal, numericType, methodBodyBinder)
Dim conv2 = ClassifyConversion(constant, numericType, methodBodyBinder)
Assert.Equal(conv, conv2)
Assert.Equal(typeConv, conv)
resultValue = Conversions.TryFoldConstantConversion(literal, numericType, integerOverflow)
resultValue2 = Conversions.TryFoldConstantConversion(constant, numericType, integerOverflow2)
Assert.NotNull(resultValue)
Assert.NotNull(resultValue2)
Assert.False(integerOverflow)
Assert.False(resultValue.IsBad)
Assert.Equal(integerOverflow, integerOverflow2)
Assert.Equal(resultValue.IsBad, resultValue2.IsBad)
Assert.Equal(resultValue2, resultValue)
Assert.Equal(numericType.GetConstantValueTypeDiscriminator(), resultValue.Discriminator)
Assert.Equal(0, Convert.ToInt64(resultValue.Value))
Next
Dim trueValue = ConstantValue.Create(True)
Assert.Equal(falseValue.Discriminator, booleanType.GetConstantValueTypeDiscriminator())
literal = New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), trueValue, booleanType)
constant = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), ConstantValue.Null, Nothing), ConversionKind.Widening, True, True, trueValue, booleanType, Nothing)
For Each numericType In numericTypes
Dim typeConv = ClassifyConversion(booleanType, numericType)
Dim conv = ClassifyConversion(literal, numericType, methodBodyBinder)
Dim conv2 = ClassifyConversion(constant, numericType, methodBodyBinder)
Assert.Equal(conv, conv2)
Assert.Equal(typeConv, conv)
resultValue = Conversions.TryFoldConstantConversion(literal, numericType, integerOverflow)
resultValue2 = Conversions.TryFoldConstantConversion(constant, numericType, integerOverflow2)
Assert.NotNull(resultValue)
Assert.NotNull(resultValue2)
Assert.False(integerOverflow)
Assert.False(resultValue.IsBad)
Assert.Equal(integerOverflow, integerOverflow2)
Assert.Equal(resultValue.IsBad, resultValue2.IsBad)
Assert.Equal(resultValue2, resultValue)
Assert.Equal(numericType.GetConstantValueTypeDiscriminator(), resultValue.Discriminator)
'The literal True converts to the literal 255 for Byte, 65535 for UShort, 4294967295 for UInteger, 18446744073709551615 for ULong,
'and to the expression -1 for SByte, Short, Integer, Long, Decimal, Single, and Double
If numericType Is byteType Then
Assert.Equal(255, DirectCast(resultValue.Value, Byte))
ElseIf numericType Is uint16Type Then
Assert.Equal(65535, DirectCast(resultValue.Value, UInt16))
ElseIf numericType Is uint32Type Then
Assert.Equal(4294967295, DirectCast(resultValue.Value, UInt32))
ElseIf numericType Is uint64Type Then
Assert.Equal(18446744073709551615UL, DirectCast(resultValue.Value, UInt64))
Else
Assert.Equal(-1, Convert.ToInt64(resultValue.Value))
End If
Next
resultValue = Conversions.TryFoldConstantConversion(literal, booleanType, integerOverflow)
resultValue2 = Conversions.TryFoldConstantConversion(constant, booleanType, integerOverflow2)
Assert.NotNull(resultValue)
Assert.NotNull(resultValue2)
Assert.False(integerOverflow)
Assert.False(resultValue.IsBad)
Assert.Equal(integerOverflow, integerOverflow2)
Assert.Equal(resultValue.IsBad, resultValue2.IsBad)
Assert.Equal(resultValue2, resultValue)
Assert.Equal(booleanType.GetConstantValueTypeDiscriminator(), resultValue.Discriminator)
Assert.True(DirectCast(resultValue.Value, Boolean))
For Each mv In nonZeroValues
Dim v = ConstantValue.Create(mv.Value, mv.Type.GetConstantValueTypeDiscriminator())
Assert.Equal(v.Discriminator, mv.Type.GetConstantValueTypeDiscriminator())
literal = New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), v, mv.Type)
constant = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), ConstantValue.Null, Nothing), ConversionKind.Widening, True, True, v, mv.Type, Nothing)
Dim typeConv = ClassifyConversion(mv.Type, booleanType)
Dim conv = ClassifyConversion(literal, booleanType, methodBodyBinder)
Dim conv2 = ClassifyConversion(constant, booleanType, methodBodyBinder)
Assert.Equal(conv, conv2)
Assert.Equal(typeConv, conv)
resultValue = Conversions.TryFoldConstantConversion(literal, booleanType, integerOverflow)
resultValue2 = Conversions.TryFoldConstantConversion(constant, booleanType, integerOverflow2)
Assert.NotNull(resultValue)
Assert.NotNull(resultValue2)
Assert.False(integerOverflow)
Assert.False(resultValue.IsBad)
Assert.Equal(integerOverflow, integerOverflow2)
Assert.Equal(resultValue2, resultValue)
Assert.Equal(booleanType.GetConstantValueTypeDiscriminator(), resultValue.Discriminator)
Assert.True(DirectCast(resultValue.Value, Boolean))
Next
' ------- String <-> Char
Dim stringValue = ConstantValue.Nothing
Assert.Null(stringValue.StringValue)
literal = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), stringValue, Nothing), ConversionKind.WideningNothingLiteral, False, True, stringValue, stringType, Nothing)
constant = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), ConstantValue.Null, Nothing), ConversionKind.Widening, True, True, stringValue, stringType, Nothing)
Assert.Equal(ConversionKind.NarrowingString, ClassifyConversion(literal, charType, methodBodyBinder))
Assert.Equal(ConversionKind.NarrowingString, ClassifyConversion(constant, charType, methodBodyBinder))
resultValue = Conversions.TryFoldConstantConversion(literal, charType, integerOverflow)
resultValue2 = Conversions.TryFoldConstantConversion(constant, charType, integerOverflow2)
Assert.NotNull(resultValue)
Assert.NotNull(resultValue2)
Assert.False(integerOverflow)
Assert.False(resultValue.IsBad)
Assert.Equal(integerOverflow, integerOverflow2)
Assert.Equal(resultValue2, resultValue)
Assert.Equal(charType.GetConstantValueTypeDiscriminator(), resultValue.Discriminator)
Assert.Equal(ChrW(0), CChar(stringValue.StringValue))
Assert.Equal(ChrW(0), DirectCast(resultValue.Value, Char))
stringValue = ConstantValue.Create("")
Assert.Equal(0, stringValue.StringValue.Length)
literal = New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), stringValue, stringType)
constant = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), ConstantValue.Null, Nothing), ConversionKind.Widening, True, True, stringValue, stringType, Nothing)
Assert.Equal(ConversionKind.NarrowingString, ClassifyConversion(literal, charType, methodBodyBinder))
Assert.Equal(ConversionKind.NarrowingString, ClassifyConversion(constant, charType, methodBodyBinder))
resultValue = Conversions.TryFoldConstantConversion(literal, charType, integerOverflow)
resultValue2 = Conversions.TryFoldConstantConversion(constant, charType, integerOverflow2)
Assert.NotNull(resultValue)
Assert.NotNull(resultValue2)
Assert.False(integerOverflow)
Assert.False(resultValue.IsBad)
Assert.Equal(integerOverflow, integerOverflow2)
Assert.Equal(resultValue2, resultValue)
Assert.Equal(charType.GetConstantValueTypeDiscriminator(), resultValue.Discriminator)
Assert.Equal(ChrW(0), CChar(""))
Assert.Equal(ChrW(0), DirectCast(resultValue.Value, Char))
stringValue = ConstantValue.Create("abc")
literal = New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), stringValue, stringType)
constant = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), ConstantValue.Null, Nothing), ConversionKind.Widening, True, True, stringValue, stringType, Nothing)
Assert.Equal(ConversionKind.NarrowingString, ClassifyConversion(literal, charType, methodBodyBinder))
Assert.Equal(ConversionKind.NarrowingString, ClassifyConversion(constant, charType, methodBodyBinder))
resultValue = Conversions.TryFoldConstantConversion(literal, charType, integerOverflow)
resultValue2 = Conversions.TryFoldConstantConversion(constant, charType, integerOverflow2)
Assert.NotNull(resultValue)
Assert.NotNull(resultValue2)
Assert.False(integerOverflow)
Assert.False(resultValue.IsBad)
Assert.Equal(integerOverflow, integerOverflow2)
Assert.Equal(resultValue2, resultValue)
Assert.Equal(charType.GetConstantValueTypeDiscriminator(), resultValue.Discriminator)
Assert.Equal("a"c, DirectCast(resultValue.Value, Char))
Dim charValue = ConstantValue.Create("b"c)
literal = New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), charValue, charType)
constant = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), ConstantValue.Null, Nothing), ConversionKind.Widening, True, True, charValue, charType, Nothing)
Assert.Equal(ConversionKind.WideningString, ClassifyConversion(literal, stringType, methodBodyBinder))
Assert.Equal(ConversionKind.WideningString, ClassifyConversion(constant, stringType, methodBodyBinder))
resultValue = Conversions.TryFoldConstantConversion(literal, stringType, integerOverflow)
resultValue2 = Conversions.TryFoldConstantConversion(constant, stringType, integerOverflow2)
Assert.NotNull(resultValue)
Assert.NotNull(resultValue2)
Assert.False(integerOverflow)
Assert.False(resultValue.IsBad)
Assert.Equal(integerOverflow, integerOverflow2)
Assert.Equal(resultValue2, resultValue)
Assert.Equal(stringType.GetConstantValueTypeDiscriminator(), resultValue.Discriminator)
Assert.Equal("b", DirectCast(resultValue.Value, String))
End Sub
<Fact()>
Public Sub ConstantExpressionConversions2()
Dim dummyCode =
<file>
Class C1
Shared Sub MethodDecl()
End Sub
End Class
</file>
Dim dummyTree = VisualBasicSyntaxTree.ParseText(dummyCode.Value)
Dim c1 = VisualBasicCompilation.Create("Test", syntaxTrees:={dummyTree}, references:={TestReferences.NetFx.v4_0_21006.mscorlib},
options:=TestOptions.ReleaseExe.WithOverflowChecks(False))
Dim sourceModule = DirectCast(c1.Assembly.Modules(0), SourceModuleSymbol)
Dim methodDeclSymbol = DirectCast(sourceModule.GlobalNamespace.GetTypeMembers("C1").Single().GetMembers("MethodDecl").Single(), SourceMethodSymbol)
Dim methodBodyBinder = BinderBuilder.CreateBinderForMethodBody(sourceModule, dummyTree, methodDeclSymbol)
Assert.False(c1.Options.CheckOverflow)
Dim objectType = c1.GetSpecialType(System_Object)
Dim booleanType = c1.GetSpecialType(System_Boolean)
Dim byteType = c1.GetSpecialType(System_Byte)
Dim sbyteType = c1.GetSpecialType(System_SByte)
Dim int16Type = c1.GetSpecialType(System_Int16)
Dim uint16Type = c1.GetSpecialType(System_UInt16)
Dim int32Type = c1.GetSpecialType(System_Int32)
Dim uint32Type = c1.GetSpecialType(System_UInt32)
Dim int64Type = c1.GetSpecialType(System_Int64)
Dim uint64Type = c1.GetSpecialType(System_UInt64)
Dim doubleType = c1.GetSpecialType(System_Double)
Dim singleType = c1.GetSpecialType(System_Single)
Dim decimalType = c1.GetSpecialType(System_Decimal)
Dim dateType = c1.GetSpecialType(System_DateTime)
Dim stringType = c1.GetSpecialType(System_String)
Dim charType = c1.GetSpecialType(System_Char)
Dim intPtrType = c1.GetSpecialType(System_IntPtr)
Dim typeCodeType = c1.GlobalNamespace.GetMembers("System").OfType(Of NamespaceSymbol)().Single().GetTypeMembers("TypeCode").Single()
Dim allTestTypes = New TypeSymbol() {
objectType, booleanType, byteType, sbyteType, int16Type, uint16Type, int32Type, uint32Type, int64Type, uint64Type, doubleType, singleType, decimalType, dateType,
stringType, charType, intPtrType, typeCodeType}
Dim convertableTypes = New HashSet(Of TypeSymbol)({
booleanType, byteType, sbyteType, int16Type, uint16Type, int32Type, uint32Type, int64Type, uint64Type, doubleType, singleType, decimalType, dateType,
stringType, charType, typeCodeType})
Dim integralTypes = New HashSet(Of TypeSymbol)({
byteType, sbyteType, int16Type, uint16Type, int32Type, uint32Type, int64Type, uint64Type, typeCodeType})
Dim unsignedTypes = New HashSet(Of TypeSymbol)({
byteType, uint16Type, uint32Type, uint64Type})
Dim numericTypes = New HashSet(Of TypeSymbol)({
byteType, sbyteType, int16Type, uint16Type, int32Type, uint32Type, int64Type, uint64Type, doubleType, singleType, decimalType, typeCodeType})
Dim floatingTypes = New HashSet(Of TypeSymbol)({doubleType, singleType})
Dim _nothing = New BoundLiteral(DirectCast(dummyTree.GetRoot(Nothing), VisualBasicSyntaxNode), ConstantValue.Nothing, Nothing)
Dim resultValue As ConstantValue
Dim integerOverflow As Boolean
Dim literal As BoundLiteral
Dim constant As BoundConversion
Dim nullableType = c1.GetSpecialType(System_Nullable_T)
' -------- Numeric non-zero values
Dim nonZeroValues = New TypeAndValue() {
New TypeAndValue(sbyteType, SByte.MinValue),
New TypeAndValue(int16Type, Int16.MinValue),
New TypeAndValue(int32Type, Int32.MinValue),
New TypeAndValue(int64Type, Int64.MinValue),
New TypeAndValue(doubleType, Double.MinValue),
New TypeAndValue(singleType, Single.MinValue),
New TypeAndValue(decimalType, Decimal.MinValue),
New TypeAndValue(sbyteType, SByte.MaxValue),
New TypeAndValue(int16Type, Int16.MaxValue),
New TypeAndValue(int32Type, Int32.MaxValue),
New TypeAndValue(int64Type, Int64.MaxValue),
New TypeAndValue(byteType, Byte.MaxValue),
New TypeAndValue(uint16Type, UInt16.MaxValue),
New TypeAndValue(uint32Type, UInt32.MaxValue),
New TypeAndValue(uint64Type, UInt64.MaxValue),
New TypeAndValue(doubleType, Double.MaxValue),
New TypeAndValue(singleType, Single.MaxValue),
New TypeAndValue(decimalType, Decimal.MaxValue),
New TypeAndValue(sbyteType, CSByte(-1)),
New TypeAndValue(int16Type, CShort(-2)),
New TypeAndValue(int32Type, CInt(-3)),
New TypeAndValue(int64Type, CLng(-4)),
New TypeAndValue(sbyteType, CSByte(5)),
New TypeAndValue(int16Type, CShort(6)),
New TypeAndValue(int32Type, CInt(7)),
New TypeAndValue(int64Type, CLng(8)),
New TypeAndValue(doubleType, CDbl(-9)),
New TypeAndValue(singleType, CSng(-10)),
New TypeAndValue(decimalType, CDec(-11)),
New TypeAndValue(doubleType, CDbl(12)),
New TypeAndValue(singleType, CSng(13)),
New TypeAndValue(decimalType, CDec(14)),
New TypeAndValue(byteType, CByte(15)),
New TypeAndValue(uint16Type, CUShort(16)),
New TypeAndValue(uint32Type, CUInt(17)),
New TypeAndValue(uint64Type, CULng(18)),
New TypeAndValue(decimalType, CDec(-11.3)),
New TypeAndValue(doubleType, CDbl(&HF000000000000000UL)),
New TypeAndValue(doubleType, CDbl(&H70000000000000F0L)),
New TypeAndValue(typeCodeType, Int32.MinValue),
New TypeAndValue(typeCodeType, Int32.MaxValue),
New TypeAndValue(typeCodeType, CInt(-3)),
New TypeAndValue(typeCodeType, CInt(7))
}
Dim resultValue2 As ConstantValue
Dim integerOverflow2 As Boolean
For Each mv In nonZeroValues
Dim v = ConstantValue.Create(mv.Value, mv.Type.GetConstantValueTypeDiscriminator())
Assert.Equal(v.Discriminator, mv.Type.GetConstantValueTypeDiscriminator())
literal = New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), v, mv.Type)
constant = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing),
New BoundLiteral(DirectCast(dummyTree.GetRoot(Nothing), VisualBasicSyntaxNode), ConstantValue.Null, Nothing),
ConversionKind.Widening, True, True, v, mv.Type, Nothing)
For Each numericType In numericTypes
Dim typeConv = ClassifyConversion(mv.Type, numericType)
Dim conv = ClassifyConversion(literal, numericType, methodBodyBinder)
Dim conv2 = ClassifyConversion(constant, numericType, methodBodyBinder)
Assert.Equal(conv, conv2)
resultValue = Conversions.TryFoldConstantConversion(literal, numericType, integerOverflow)
resultValue2 = Conversions.TryFoldConstantConversion(constant, numericType, integerOverflow2)
Assert.Equal(resultValue Is Nothing, resultValue2 Is Nothing)
Assert.Equal(integerOverflow, integerOverflow2)
If resultValue IsNot Nothing Then
Assert.Equal(resultValue2, resultValue)
If Not resultValue.IsBad Then
Assert.Equal(numericType.GetConstantValueTypeDiscriminator(), resultValue.Discriminator)
End If
End If
Dim resultValueAsObject As Object = Nothing
Dim overflow As Boolean = False
Try
resultValueAsObject = CheckedConvert(v.Value, numericType)
Catch ex As OverflowException
overflow = True
End Try
If Not overflow Then
If Conversions.IsIdentityConversion(typeConv) Then
Assert.True(Conversions.IsIdentityConversion(conv))
ElseIf Conversions.IsNarrowingConversion(typeConv) Then
If mv.Type Is doubleType AndAlso numericType Is singleType Then
Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant, conv)
ElseIf integralTypes.Contains(mv.Type) AndAlso numericType.IsEnumType() Then
Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions, conv)
ElseIf integralTypes.Contains(mv.Type) AndAlso integralTypes.Contains(numericType) AndAlso Not mv.Type.IsEnumType() AndAlso Not numericType.IsEnumType() Then
Assert.Equal(ConversionKind.WideningNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant, conv)
Else
Assert.Equal(typeConv, conv)
End If
ElseIf mv.Type.IsEnumType() Then
Assert.Equal(ConversionKind.WideningNumeric Or ConversionKind.InvolvesEnumTypeConversions, conv)
Else
Assert.Equal(ConversionKind.WideningNumeric, conv)
End If
Assert.NotNull(resultValue)
Assert.False(integerOverflow)
Assert.False(resultValue.IsBad)
Assert.Equal(resultValueAsObject, resultValue.Value)
If mv.Type Is doubleType AndAlso numericType Is singleType Then
If v.DoubleValue = Double.MinValue Then
Dim min As Single = Double.MinValue
Assert.True(Single.IsNegativeInfinity(min))
Assert.Equal(resultValue.SingleValue, min)
ElseIf v.DoubleValue = Double.MaxValue Then
Dim max As Single = Double.MaxValue
Assert.Equal(Double.MaxValue, v.DoubleValue)
Assert.True(Single.IsPositiveInfinity(max))
Assert.Equal(resultValue.SingleValue, max)
End If
End If
ElseIf Not integralTypes.Contains(mv.Type) OrElse Not integralTypes.Contains(numericType) Then
'Assert.Equal(typeConv, conv)
If integralTypes.Contains(numericType) Then
Assert.NotNull(resultValue)
If resultValue.IsBad Then
Assert.False(integerOverflow)
Assert.Equal(ConversionKind.FailedDueToNumericOverflow, conv)
Else
Assert.True(integerOverflow)
Assert.Equal(typeConv, conv)
Dim intermediate As Object
If unsignedTypes.Contains(numericType) Then
intermediate = Convert.ToUInt64(mv.Value)
Else
intermediate = Convert.ToInt64(mv.Value)
End If
Dim gotException As Boolean
Try
gotException = False
CheckedConvert(intermediate, numericType) ' Should get an overflow
Catch x As Exception
gotException = True
End Try
Assert.True(gotException)
Assert.Equal(UncheckedConvert(intermediate, numericType), resultValue.Value)
End If
Else
Assert.NotNull(resultValue)
Assert.False(integerOverflow)
Assert.True(resultValue.IsBad)
Assert.Equal(ConversionKind.FailedDueToNumericOverflow, conv)
End If
Else
' An integer overflow case
If numericType.IsEnumType() OrElse mv.Type.IsEnumType() Then
Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions, conv)
Else
Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant, conv)
End If
Assert.NotNull(resultValue)
Assert.True(integerOverflow)
Assert.False(resultValue.IsBad)
Assert.Equal(UncheckedConvert(v.Value, numericType), resultValue.Value)
End If
Dim nullableType2 = nullableType.Construct(numericType)
Dim zero = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing),
New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), ConstantValue.Default(ConstantValueTypeDiscriminator.Int32), int32Type),
ConversionKind.Widening, True, True, ConstantValue.Default(mv.Type.GetConstantValueTypeDiscriminator()), mv.Type, Nothing)
conv = ClassifyConversion(literal, numericType, methodBodyBinder)
If (conv And ConversionKind.FailedDueToNumericOverflowMask) = 0 Then
conv = ClassifyConversion(mv.Type, nullableType2) Or
(ClassifyConversion(zero, nullableType2, methodBodyBinder) And ConversionKind.InvolvesNarrowingFromNumericConstant)
End If
Assert.Equal(conv, ClassifyConversion(literal, nullableType2, methodBodyBinder))
Assert.Equal(conv, ClassifyConversion(constant, nullableType2, methodBodyBinder))
resultValue = Conversions.TryFoldConstantConversion(literal, nullableType2, integerOverflow)
Assert.Null(resultValue)
Assert.False(integerOverflow)
resultValue = Conversions.TryFoldConstantConversion(constant, nullableType2, integerOverflow)
Assert.Null(resultValue)
Assert.False(integerOverflow)
Next
Next
End Sub
Private Function CheckedConvert(value As Object, type As TypeSymbol) As Object
type = type.GetEnumUnderlyingTypeOrSelf()
Select Case type.SpecialType
Case System_Byte : Return CByte(value)
Case System_SByte : Return CSByte(value)
Case System_Int16 : Return CShort(value)
Case System_UInt16 : Return CUShort(value)
Case System_Int32 : Return CInt(value)
Case System_UInt32 : Return CUInt(value)
Case System_Int64 : Return CLng(value)
Case System_UInt64 : Return CULng(value)
Case System_Single : Return CSng(value)
Case System_Double : Return CDbl(value)
Case System_Decimal : Return CDec(value)
Case Else
Throw New NotSupportedException()
End Select
End Function
Private Function UncheckedConvert(value As Object, type As TypeSymbol) As Object
type = type.GetEnumUnderlyingTypeOrSelf()
Select Case System.Type.GetTypeCode(value.GetType())
Case TypeCode.Byte, TypeCode.UInt16, TypeCode.UInt32, TypeCode.UInt64
Dim val As UInt64 = Convert.ToUInt64(value)
Select Case type.SpecialType
Case System_Byte : Return UncheckedCByte(UncheckedCLng(val))
Case System_SByte : Return UncheckedCSByte(UncheckedCLng(val))
Case System_Int16 : Return UncheckedCShort(val)
Case System_UInt16 : Return UncheckedCUShort(UncheckedCLng(val))
Case System_Int32 : Return UncheckedCInt(val)
Case System_UInt32 : Return UncheckedCUInt(val)
Case System_Int64 : Return UncheckedCLng(val)
Case System_UInt64 : Return UncheckedCULng(val)
Case Else
Throw New NotSupportedException()
End Select
Case TypeCode.SByte, TypeCode.Int16, TypeCode.Int32, TypeCode.Int64
Dim val As Int64 = Convert.ToInt64(value)
Select Case type.SpecialType
Case System_Byte : Return UncheckedCByte(val)
Case System_SByte : Return UncheckedCSByte(val)
Case System_Int16 : Return UncheckedCShort(val)
Case System_UInt16 : Return UncheckedCUShort(val)
Case System_Int32 : Return UncheckedCInt(val)
Case System_UInt32 : Return UncheckedCUInt(val)
Case System_Int64 : Return UncheckedCLng(val)
Case System_UInt64 : Return UncheckedCULng(val)
Case Else
Throw New NotSupportedException()
End Select
Case Else
Throw New NotSupportedException()
End Select
Select Case type.SpecialType
Case System_Byte : Return CByte(value)
Case System_SByte : Return CSByte(value)
Case System_Int16 : Return CShort(value)
Case System_UInt16 : Return CUShort(value)
Case System_Int32 : Return CInt(value)
Case System_UInt32 : Return CUInt(value)
Case System_Int64 : Return CLng(value)
Case System_UInt64 : Return CULng(value)
Case System_Single : Return CSng(value)
Case System_Double : Return CDbl(value)
Case System_Decimal : Return CDec(value)
Case Else
Throw New NotSupportedException()
End Select
End Function
Friend Structure TypeAndValue
Public ReadOnly Type As TypeSymbol
Public ReadOnly Value As Object
Sub New(type As TypeSymbol, value As Object)
Me.Type = type
Me.Value = value
End Sub
End Structure
<Fact()>
Public Sub PredefinedNotBuiltIn()
' Tests are based on the source code used to compile VBConversions.dll, VBConversions.vb is
' checked in next to the DLL.
Dim vbConversionsRef = TestReferences.SymbolsTests.VBConversions
Dim modifiersRef = TestReferences.SymbolsTests.CustomModifiers.Modifiers.dll
Dim c1 = VisualBasicCompilation.Create("Test", references:={TestReferences.NetFx.v4_0_21006.mscorlib, vbConversionsRef, modifiersRef})
Dim asmVBConversions = c1.GetReferencedAssemblySymbol(vbConversionsRef)
Dim asmModifiers = c1.GetReferencedAssemblySymbol(modifiersRef)
Dim test = asmVBConversions.Modules(0).GlobalNamespace.GetTypeMembers("Test").Single()
'--------------- Identity
Dim m1 = DirectCast(test.GetMembers("M1").Single(), MethodSymbol)
Dim m1p = m1.Parameters.Select(Function(p) p.Type).ToArray()
Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m1p(a), m1p(b))))
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m1p(a), m1p(c))) 'error BC30311: Value of type 'Class2' cannot be converted to 'Class1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m1p(a), m1p(d))) 'error BC30311: Value of type '1-dimensional array of Class1' cannot be converted to 'Class1'.
Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m1p(d), m1p(e))))
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m1p(d), m1p(f))) 'error BC30332: Value of type '1-dimensional array of Class2' cannot be converted to '1-dimensional array of Class1' because 'Class2' is not derived from 'Class1'.
Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m1p(g), m1p(h))))
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m1p(g), m1p(i))) 'error BC30311: Value of type 'Class2.Class3(Of Byte)' cannot be converted to 'Class2.Class3(Of Integer)'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m1p(g), m1p(j))) 'error BC30311: Value of type 'Class4(Of Integer)' cannot be converted to 'Class2.Class3(Of Integer)'.
Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m1p(j), m1p(k))))
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m1p(j), m1p(l))) 'error BC30311: Value of type 'Class4(Of Byte)' cannot be converted to 'Class4(Of Integer)'.
Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m1p(m), m1p(n))))
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m1p(m), m1p(o))) 'error BC30311: Value of type 'Class4(Of Byte).Class5(Of Integer)' cannot be converted to 'Class4(Of Integer).Class5(Of Integer)'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m1p(m), m1p(p))) 'error BC30311: Value of type 'Class4(Of Integer).Class5(Of Byte)' cannot be converted to 'Class4(Of Integer).Class5(Of Integer)'.
Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m1p(q), m1p(r))))
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m1p(q), m1p(s))) 'error BC30311: Value of type 'Class4(Of Byte).Class6' cannot be converted to 'Class4(Of Integer).Class6'.
Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m1p(t), m1p(u))))
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m1p(t), m1p(v))) 'error BC30311: Value of type 'Class4(Of Byte).Class6.Class7(Of Integer)' cannot be converted to 'Class4(Of Integer).Class6.Class7(Of Integer)'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m1p(t), m1p(w))) 'error BC30311: Value of type 'Class4(Of Integer).Class6.Class7(Of Byte)' cannot be converted to 'Class4(Of Integer).Class6.Class7(Of Integer)'.
Dim modifiers = asmModifiers.Modules(0).GlobalNamespace.GetTypeMembers("Modifiers").Single()
Dim modifiedArrayInt32 = modifiers.GetMembers("F5").OfType(Of MethodSymbol)().Single().Parameters(0).Type
Dim arrayInt32 = c1.CreateArrayTypeSymbol(c1.GetSpecialType(System_Int32))
Assert.NotEqual(modifiedArrayInt32, arrayInt32)
Assert.NotEqual(arrayInt32, modifiedArrayInt32)
Assert.True(arrayInt32.IsSameTypeIgnoringCustomModifiers(modifiedArrayInt32))
Assert.True(modifiedArrayInt32.IsSameTypeIgnoringCustomModifiers(arrayInt32))
Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(arrayInt32, modifiedArrayInt32)))
Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(modifiedArrayInt32, arrayInt32)))
Dim enumerable = c1.GetSpecialType(System_Collections_Generic_IEnumerable_T)
Dim enumerableOfModifiedArrayInt32 = enumerable.Construct(modifiedArrayInt32)
Dim enumerableOfArrayInt32 = enumerable.Construct(arrayInt32)
Assert.NotEqual(enumerableOfModifiedArrayInt32, enumerableOfArrayInt32)
Assert.NotEqual(enumerableOfArrayInt32, enumerableOfModifiedArrayInt32)
Assert.True(enumerableOfArrayInt32.IsSameTypeIgnoringCustomModifiers(enumerableOfModifiedArrayInt32))
Assert.True(enumerableOfModifiedArrayInt32.IsSameTypeIgnoringCustomModifiers(enumerableOfArrayInt32))
Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(enumerableOfArrayInt32, enumerableOfModifiedArrayInt32)))
Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(enumerableOfModifiedArrayInt32, enumerableOfArrayInt32)))
'--------------- Numeric
Dim m2 = DirectCast(test.GetMembers("M2").Single(), MethodSymbol)
Dim m2p = m2.Parameters.Select(Function(p) p.Type).ToArray()
Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m2p(a), m2p(b))))
Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m2p(a), m2p(c))) 'error BC30512: Option Strict On disallows implicit conversions from 'Enum2' to 'Enum1'.
Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m2p(a), m2p(d))) 'error BC30512: Option Strict On disallows implicit conversions from 'Enum3' to 'Enum1'.
Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m2p(a), m2p(e))) 'error BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'Enum1'.
Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m2p(a), m2p(f))) 'error BC30512: Option Strict On disallows implicit conversions from 'Long' to 'Enum1'.
Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m2p(a), m2p(g))) 'error BC30512: Option Strict On disallows implicit conversions from 'Short' to 'Enum1'.
Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m2p(a), m2p(h))) 'error BC30512: Option Strict On disallows implicit conversions from 'Enum4' to 'Enum1'.
Assert.Equal(ConversionKind.WideningNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m2p(e), m2p(a)))
Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m2p(e), m2p(c))) 'error BC30512: Option Strict On disallows implicit conversions from 'Enum2' to 'Integer'.
Assert.Equal(ConversionKind.WideningNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m2p(e), m2p(d)))
Assert.Equal(ConversionKind.WideningNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m2p(f), m2p(a)))
Assert.Equal(ConversionKind.WideningNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m2p(f), m2p(c)))
Assert.Equal(ConversionKind.WideningNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m2p(f), m2p(d)))
Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m2p(g), m2p(a))) 'error BC30512: Option Strict On disallows implicit conversions from 'Enum1' to 'Short'.
Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m2p(g), m2p(c))) 'error BC30512: Option Strict On disallows implicit conversions from 'Enum2' to 'Short'.
Assert.Equal(ConversionKind.WideningNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m2p(g), m2p(d)))
'--------------- Reference
Dim m3 = DirectCast(test.GetMembers("M3").Single(), MethodSymbol)
Dim m3p = m3.Parameters.Select(Function(p) p.Type).ToArray()
Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m3p(a), m3p(a))))
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(a), m3p(d)))
Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m3p(b), m3p(b))))
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(b), m3p(c)))
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(b), m3p(d)))
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(c), m3p(d)))
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(d), m3p(a))) 'error BC30512: Option Strict On disallows implicit conversions from 'Object' to 'Class10'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(c), m3p(b))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class8' to 'Class9'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(d), m3p(b))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class8' to 'Class10'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(d), m3p(c))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class9' to 'Class10'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m3p(c), m3p(e))) 'error BC30311: Value of type 'Class11' cannot be converted to 'Class9'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m3p(e), m3p(c))) 'error BC30311: Value of type 'Class9' cannot be converted to 'Class11'.
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(a), m3p(g)))
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(f), m3p(g)))
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(a), m3p(h)))
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(f), m3p(h)))
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(g), m3p(a))) 'error BC30512: Option Strict On disallows implicit conversions from 'Object' to '1-dimensional array of Integer'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(g), m3p(f))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.Array' to '1-dimensional array of Integer'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(h), m3p(a))) 'error BC30512: Option Strict On disallows implicit conversions from 'Object' to '2-dimensional array of Integer'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(h), m3p(f))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.Array' to '2-dimensional array of Integer'.
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(i), m3p(d)))
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(j), m3p(d)))
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(k), m3p(d)))
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(l), m3p(c)))
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(l), m3p(d)))
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(m), m3p(b)))
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(m), m3p(c)))
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(m), m3p(d)))
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(n), m3p(d)))
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(p), m3p(g)))
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(p), m3p(h)))
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(q), m3p(g)))
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(r), m3p(g)))
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(s), m3p(g)))
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(v), m3p(u)))
Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m3p(i), m3p(i))))
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(i), m3p(j)))
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(i), m3p(k)))
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(i), m3p(o)))
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(n), m3p(o)))
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(i), m3p(b))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class8' to 'Interface1'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(i), m3p(c))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class9' to 'Interface1'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(i), m3p(e))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class11' to 'Interface1'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(j), m3p(b))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class8' to 'Interface2'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(j), m3p(c))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class9' to 'Interface2'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(k), m3p(b))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class8' to 'Interface3'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(k), m3p(c))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class9' to 'Interface3'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(l), m3p(b))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class8' to 'Interface4'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(n), m3p(b))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class8' to 'Interface6'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(n), m3p(c))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class9' to 'Interface6'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(o), m3p(b))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class8' to 'Interface7'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(o), m3p(c))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class9' to 'Interface7'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(o), m3p(d))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class10' to 'Interface7'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m3p(q), m3p(h))) 'error BC30311: Value of type '2-dimensional array of Integer' cannot be converted to 'System.Collections.Generic.IList(Of Integer)'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m3p(r), m3p(h))) 'error BC30311: Value of type '2-dimensional array of Integer' cannot be converted to 'System.Collections.Generic.ICollection(Of Integer)'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m3p(s), m3p(h))) 'error BC30311: Value of type '2-dimensional array of Integer' cannot be converted to 'System.Collections.Generic.IEnumerable(Of Integer)'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(t), m3p(g))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Integer' to 'System.Collections.Generic.IList(Of Long)'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(w), m3p(u))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Class9' to 'System.Collections.Generic.IList(Of Class11)'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(i), m3p(l))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface4' to 'Interface1'.
Assert.Equal(ConversionKind.NarrowingReference Or ConversionKind.DelegateRelaxationLevelNarrowing, ClassifyPredefinedAssignment(m3p(o), m3p(x))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.Action' to 'Interface7'.
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(a), m3p(o)))
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(x), m3p(o))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface7' to 'System.Action'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(e), m3p(o))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface7' to 'Class11'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m3p(g), m3p(o))) 'error BC30311: Value of type 'Interface7' cannot be converted to '1-dimensional array of Integer'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m3p(h), m3p(o))) 'error BC30311: Value of type 'Interface7' cannot be converted to '2-dimensional array of Integer'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m3p(u), m3p(o))) 'error BC30311: Value of type 'Interface7' cannot be converted to '1-dimensional array of Class9'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(g), m3p(p))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.Collections.IEnumerable' to '1-dimensional array of Integer'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(h), m3p(p))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.Collections.IEnumerable' to '2-dimensional array of Integer'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(g), m3p(q))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.Collections.Generic.IList(Of Integer)' to '1-dimensional array of Integer'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m3p(h), m3p(q))) 'error BC30311: Value of type 'System.Collections.Generic.IList(Of Integer)' cannot be converted to '2-dimensional array of Integer'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(g), m3p(t))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.Collections.Generic.IList(Of Long)' to '1-dimensional array of Integer'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m3p(h), m3p(t))) 'error BC30311: Value of type 'System.Collections.Generic.IList(Of Long)' cannot be converted to '2-dimensional array of Integer'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(g), m3p(w))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.Collections.Generic.IList(Of Class11)' to '1-dimensional array of Integer'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m3p(h), m3p(w))) 'error BC30311: Value of type 'System.Collections.Generic.IList(Of Class11)' cannot be converted to '2-dimensional array of Integer'.
Dim [object] = c1.GetSpecialType(System_Object)
Dim module2 = asmVBConversions.Modules(0).GlobalNamespace.GetTypeMembers("Module2").Single()
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment([object], module2))
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(module2, [object]))
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(i), module2))
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(module2, m3p(i)))
' ------------- Type Parameter
Dim m6 = DirectCast(test.GetMembers("M6").Single(), MethodSymbol)
Dim m6p = m6.Parameters.Select(Function(p) p.Type).ToArray()
Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m6p(b), m6p(b))))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m6p(a), m6p(b)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m6p(a), m6p(c)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m6p(a), m6p(d)))
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(b), m6p(a))) 'error BC30512: Option Strict On disallows implicit conversions from 'Object' to 'MT1'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(c), m6p(a))) 'error BC30512: Option Strict On disallows implicit conversions from 'Object' to 'MT2'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(d), m6p(a))) 'error BC30512: Option Strict On disallows implicit conversions from 'Object' to 'MT3'.
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m6p(e), m6p(f)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m6p(e), m6p(h)))
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(f), m6p(e))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface3' to 'MT4'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(h), m6p(e))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface3' to 'MT6'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m6p(f), m6p(g))) 'error BC30311: Value of type 'MT5' cannot be converted to 'MT4'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m6p(g), m6p(f))) 'error BC30311: Value of type 'MT4' cannot be converted to 'MT5'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m6p(h), m6p(i))) 'error BC30311: Value of type 'MT7' cannot be converted to 'MT6'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m6p(i), m6p(h))) 'error BC30311: Value of type 'MT6' cannot be converted to 'MT7'.
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m6p(e), m6p(k)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m6p(j), m6p(k)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m6p(j), m6p(f)))
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(k), m6p(e))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface3' to 'MT8'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(k), m6p(j))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface1' to 'MT8'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(f), m6p(j))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface1' to 'MT4'.
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m6p(l), m6p(k)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m6p(m), m6p(k)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m6p(p), m6p(c)))
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(k), m6p(l))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class10' to 'MT8'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(k), m6p(m))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class8' to 'MT8'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(c), m6p(p))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.ValueType' to 'MT2'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m6p(n), m6p(k))) 'error BC30311: Value of type 'MT8' cannot be converted to 'Class12'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m6p(k), m6p(n))) 'error BC30311: Value of type 'Class12' cannot be converted to 'MT8'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m6p(k), m6p(o))) 'error BC30311: Value of type 'MT9' cannot be converted to 'MT8'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m6p(o), m6p(k))) 'error BC30311: Value of type 'MT8' cannot be converted to 'MT9'.
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m6p(b), m6p(q)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m6p(b), m6p(r)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m6p(t), m6p(s)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m6p(m), m6p(s)))
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(q), m6p(b))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT1' to 'MT10'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(r), m6p(b))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT1' to 'MT11'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(s), m6p(t))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class9' to 'MT13'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(s), m6p(m))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class8' to 'MT13'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m6p(l), m6p(s))) 'error BC30311: Value of type 'MT13' cannot be converted to 'Class10'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m6p(s), m6p(l))) 'error BC30311: Value of type 'Class10' cannot be converted to 'MT13'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(u), m6p(k))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT8' to 'Interface7'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(k), m6p(u))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface7' to 'MT8'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(u), m6p(f))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT4' to 'Interface7'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(f), m6p(u))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface7' to 'MT4'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(u), m6p(b))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT1' to 'Interface7'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(b), m6p(u))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface7' to 'MT1'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(u), m6p(c))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT2' to 'Interface7'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(c), m6p(u))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface7' to 'MT2'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m6p(v), m6p(q))) 'error BC30311: Value of type 'MT10' cannot be converted to 'MT14'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m6p(q), m6p(v))) 'error BC30311: Value of type 'MT14' cannot be converted to 'MT10'.
Dim m7 = DirectCast(test.GetMembers("M7").Single(), MethodSymbol)
Dim m7p = m7.Parameters.Select(Function(p) p.Type).ToArray()
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m7p(p), m7p(a)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m7p(p), m7p(b)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m7p(q), m7p(c)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m7p(q), m7p(d)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m7p(r), m7p(d)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m7p(t), m7p(g)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m7p(v), m7p(j)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m7p(v), m7p(k)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m7p(w), m7p(n)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m7p(x), m7p(i)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m7p(y), m7p(j)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m7p(y), m7p(k)))
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(a), m7p(p))) 'error BC30512: Option Strict On disallows implicit conversions from 'Object' to 'MT1'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(b), m7p(p))) 'error BC30512: Option Strict On disallows implicit conversions from 'Object' to 'MT2'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(c), m7p(q))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.Enum' to 'MT3'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(d), m7p(q))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.Enum' to 'MT4'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(d), m7p(r))) 'error BC30512: Option Strict On disallows implicit conversions from 'Enum1' to 'MT4'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(g), m7p(t))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Integer' to 'MT7'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(j), m7p(v))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Class9' to 'MT10'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(k), m7p(v))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Class9' to 'MT11'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(n), m7p(w))) 'error BC30512: Option Strict On disallows implicit conversions from 'Structure1' to 'MT14'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(i), m7p(x))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.Collections.IEnumerable' to 'MT9'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(y), m7p(i))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT9' to 'System.Collections.Generic.IList(Of Class9)'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(i), m7p(y))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.Collections.Generic.IList(Of Class9)' to 'MT9'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(j), m7p(y))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.Collections.Generic.IList(Of Class9)' to 'MT10'
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(k), m7p(y))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.Collections.Generic.IList(Of Class9)' to 'MT11'
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(y), m7p(z))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT15' to 'System.Collections.Generic.IList(Of Class9)'
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(z), m7p(y))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.Collections.Generic.IList(Of Class9)' to 'MT15'
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(n), m7p(o))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface1' to 'MT14'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(o), m7p(n))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT14' to 'Interface1'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(m), m7p(o))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface1' to 'MT13'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(o), m7p(m))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT13' to 'Interface1'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(d), m7p(o))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface1' to 'MT4'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(o), m7p(d))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT4' to 'Interface1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m7p(r), m7p(e))) 'error BC30311: Value of type 'MT5' cannot be converted to 'Enum1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m7p(e), m7p(r))) 'error BC30311: Value of type 'Enum1' cannot be converted to 'MT5'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m7p(s), m7p(d))) 'error BC30311: Value of type 'MT4' cannot be converted to 'Enum2'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m7p(d), m7p(s))) 'error BC30311: Value of type 'Enum2' cannot be converted to 'MT4'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m7p(r), m7p(f))) 'error BC30311: Value of type 'MT6' cannot be converted to 'Enum1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m7p(f), m7p(r))) 'error BC30311: Value of type 'Enum1' cannot be converted to 'MT6'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m7p(t), m7p(h))) 'error BC30311: Value of type 'MT8' cannot be converted to '1-dimensional array of Integer'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m7p(h), m7p(t))) 'error BC30311: Value of type '1-dimensional array of Integer' cannot be converted to 'MT8'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m7p(v), m7p(i))) 'error BC30311: Value of type 'MT9' cannot be converted to '1-dimensional array of Class9'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m7p(i), m7p(v))) 'error BC30311: Value of type '1-dimensional array of Class9' cannot be converted to 'MT9'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m7p(a), m7p(b))) 'error BC30311: Value of type 'MT2' cannot be converted to 'MT1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m7p(b), m7p(a))) 'error BC30311: Value of type 'MT1' cannot be converted to 'MT2'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m7p(g), m7p(h))) 'error BC30311: Value of type 'MT8' cannot be converted to 'MT7'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m7p(h), m7p(g))) 'error BC30311: Value of type 'MT7' cannot be converted to 'MT8'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m7p(g), m7p(l))) 'error BC30311: Value of type 'MT12' cannot be converted to 'MT7'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m7p(l), m7p(g))) 'error BC30311: Value of type 'MT7' cannot be converted to 'MT12'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m7p(c), m7p(d))) 'error BC30311: Value of type 'MT4' cannot be converted to 'MT3'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m7p(d), m7p(c))) 'error BC30311: Value of type 'MT3' cannot be converted to 'MT4'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m7p(i), m7p(j))) 'error BC30311: Value of type 'MT10' cannot be converted to 'MT9'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m7p(j), m7p(i))) 'error BC30311: Value of type 'MT9' cannot be converted to 'MT10'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m7p(a), m7p(n))) 'error BC30311: Value of type 'MT14' cannot be converted to 'MT1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m7p(n), m7p(a))) 'error BC30311: Value of type 'MT1' cannot be converted to 'MT14'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m7p(d), m7p(f))) 'error BC30311: Value of type 'MT6' cannot be converted to 'MT4'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m7p(f), m7p(d))) 'error BC30311: Value of type 'MT4' cannot be converted to 'MT6'.
Dim m8 = DirectCast(test.GetMembers("M8").Single(), MethodSymbol)
Dim m8p = m8.Parameters.Select(Function(p) p.Type).ToArray()
Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m8p(a), m8p(a))))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m8p(a), m8p(d)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m8p(b), m8p(f)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m8p(a), m8p(c)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m8p(b), m8p(e)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m8p(g), m8p(h)))
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m8p(c), m8p(a))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT1' to 'MT3'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m8p(d), m8p(a))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT1' to 'MT4'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m8p(e), m8p(b))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT2' to 'MT5'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m8p(f), m8p(b))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT2' to 'MT6'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m8p(h), m8p(g))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT7' to 'MT8'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m8p(a), m8p(b))) 'error BC30311: Value of type 'MT2' cannot be converted to 'MT1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m8p(b), m8p(a))) 'error BC30311: Value of type 'MT1' cannot be converted to 'MT2'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m8p(b), m8p(d))) 'error BC30311: Value of type 'MT4' cannot be converted to 'MT2'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m8p(d), m8p(b))) 'error BC30311: Value of type 'MT2' cannot be converted to 'MT4'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m8p(a), m8p(g))) 'error BC30311: Value of type 'MT7' cannot be converted to 'MT1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m8p(g), m8p(a))) 'error BC30311: Value of type 'MT1' cannot be converted to 'MT7'.
Dim m9 = DirectCast(test.GetMembers("M9").Single(), MethodSymbol)
Dim m9p = m9.Parameters.Select(Function(p) p.Type).ToArray()
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m9p(a), m9p(b)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m9p(j), m9p(a)))
Assert.Equal(ConversionKind.WideningTypeParameter Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m9p(j), m9p(e)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m9p(l), m9p(e)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m9p(m), m9p(n)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m9p(p), m9p(q)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m9p(s), m9p(u)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m9p(t), m9p(u)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m9p(s), m9p(v)))
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m9p(b), m9p(a))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT1' to 'MT2'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m9p(a), m9p(j))) 'error BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'MT1'.
Assert.Equal(ConversionKind.NarrowingTypeParameter Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m9p(e), m9p(j))) 'error BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'MT5'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m9p(e), m9p(l))) 'error BC30512: Option Strict On disallows implicit conversions from 'Enum1' to 'MT5'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m9p(n), m9p(m))) 'error BC30512: Option Strict On disallows implicit conversions from 'Structure1' to 'MT10'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m9p(q), m9p(p))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class1' to 'MT12'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m9p(u), m9p(s))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.ValueType' to 'MT15'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m9p(u), m9p(t))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT14' to 'MT15'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m9p(v), m9p(s))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.ValueType' to 'MT16'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(a), m9p(e))) 'error BC30311: Value of type 'MT5' cannot be converted to 'MT1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(e), m9p(a))) 'error BC30311: Value of type 'MT1' cannot be converted to 'MT5'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(e), m9p(g))) 'error BC30311: Value of type 'MT7' cannot be converted to 'MT5'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(g), m9p(e))) 'error BC30311: Value of type 'MT5' cannot be converted to 'MT7'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(a), m9p(l))) 'error BC30311: Value of type 'Enum1' cannot be converted to 'MT1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(l), m9p(a))) 'error BC30311: Value of type 'MT1' cannot be converted to 'Enum1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(a), m9p(i))) 'error BC30311: Value of type 'MT9' cannot be converted to 'MT1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(a), m9p(c))) 'error BC30311: Value of type 'MT3' cannot be converted to 'MT1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(c), m9p(a))) 'error BC30311: Value of type 'MT1' cannot be converted to 'MT3'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(a), m9p(d))) 'error BC30311: Value of type 'MT4' cannot be converted to 'MT1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(d), m9p(a))) 'error BC30311: Value of type 'MT1' cannot be converted to 'MT4'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(a), m9p(f))) 'error BC30311: Value of type 'MT6' cannot be converted to 'MT1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(f), m9p(a))) 'error BC30311: Value of type 'MT1' cannot be converted to 'MT6'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(a), m9p(h))) 'error BC30311: Value of type 'MT8' cannot be converted to 'MT1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(h), m9p(a))) 'error BC30311: Value of type 'MT1' cannot be converted to 'MT8'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(e), m9p(f))) 'error BC30311: Value of type 'MT6' cannot be converted to 'MT5'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(f), m9p(e))) 'error BC30311: Value of type 'MT5' cannot be converted to 'MT6'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(e), m9p(h))) 'error BC30311: Value of type 'MT8' cannot be converted to 'MT5'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(h), m9p(e))) 'error BC30311: Value of type 'MT5' cannot be converted to 'MT8'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(a), m9p(k))) 'error BC30311: Value of type 'UInteger' cannot be converted to 'MT1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(k), m9p(a))) 'error BC30311: Value of type 'MT1' cannot be converted to 'UInteger'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(e), m9p(k))) 'error BC30311: Value of type 'UInteger' cannot be converted to 'MT5'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(k), m9p(e))) 'error BC30311: Value of type 'MT5' cannot be converted to 'UInteger'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(n), m9p(o))) 'error BC30311: Value of type 'MT11' cannot be converted to 'MT10'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(o), m9p(n))) 'error BC30311: Value of type 'MT10' cannot be converted to 'MT11'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(q), m9p(r))) 'error BC30311: Value of type 'MT13' cannot be converted to 'MT12'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(r), m9p(q))) 'error BC30311: Value of type 'MT12' cannot be converted to 'MT13'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(v), m9p(w))) 'error BC30311: Value of type 'MT17' cannot be converted to 'MT16'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(w), m9p(v))) 'error BC30311: Value of type 'MT16' cannot be converted to 'MT17'.
' ------------- Array conversions
Dim m4 = DirectCast(test.GetMembers("M4").Single(), MethodSymbol)
Dim m4p = m4.Parameters.Select(Function(p) p.Type).ToArray()
Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m4p(a), m4p(a))))
Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m4p(l), m4p(l))))
Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m4p(n), m4p(n))))
Assert.Equal(ConversionKind.WideningArray, ClassifyPredefinedAssignment(m4p(a), m4p(d)))
Assert.Equal(ConversionKind.WideningArray, ClassifyPredefinedAssignment(m4p(b), m4p(f)))
Assert.Equal(ConversionKind.WideningArray, ClassifyPredefinedAssignment(m4p(i), m4p(j)))
Assert.Equal(ConversionKind.WideningArray, ClassifyPredefinedAssignment(m4p(i), m4p(k)))
Assert.Equal(ConversionKind.WideningArray, ClassifyPredefinedAssignment(m4p(l), m4p(m)))
Assert.Equal(ConversionKind.WideningArray, ClassifyPredefinedAssignment(m4p(n), m4p(o)))
Assert.Equal(ConversionKind.WideningArray, ClassifyPredefinedAssignment(m4p(p), m4p(i)))
Assert.Equal(ConversionKind.WideningArray, ClassifyPredefinedAssignment(m4p(x), m4p(i)))
Assert.Equal(ConversionKind.WideningArray, ClassifyPredefinedAssignment(m4p(x), m4p(w)))
Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m4p(a), m4p(c))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT3' to '1-dimensional array of MT1'.
Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m4p(c), m4p(a))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT1' to '1-dimensional array of MT3'.
Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m4p(d), m4p(a))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT1' to '1-dimensional array of MT4'.
Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m4p(b), m4p(e))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT5' to '1-dimensional array of MT2'.
Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m4p(e), m4p(b))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT2' to '1-dimensional array of MT5'.
Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m4p(f), m4p(b))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT2' to '1-dimensional array of MT6'.
Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m4p(g), m4p(h))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT8' to '1-dimensional array of MT7'.
Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m4p(h), m4p(g))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT7' to '1-dimensional array of MT8'.
Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m4p(j), m4p(i))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Class8' to '1-dimensional array of Class9'.
Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m4p(k), m4p(i))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Class8' to '1-dimensional array of Class11'.
Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m4p(m), m4p(l))) 'error BC30512: Option Strict On disallows implicit conversions from '2-dimensional array of Class8' to '2-dimensional array of Class9'.
Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m4p(o), m4p(n))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of 1-dimensional array of Class8' to '1-dimensional array of 1-dimensional array of Class9'.
Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m4p(i), m4p(p))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Interface5' to '1-dimensional array of Class8'.
Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m4p(i), m4p(x))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Object' to '1-dimensional array of Class8'.
Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m4p(w), m4p(x))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Object' to '1-dimensional array of System.ValueType'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m4p(a), m4p(b))) 'error BC30332: Value of type '1-dimensional array of MT2' cannot be converted to '1-dimensional array of MT1' because 'MT2' is not derived from 'MT1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m4p(b), m4p(a))) 'error BC30332: Value of type '1-dimensional array of MT1' cannot be converted to '1-dimensional array of MT2' because 'MT1' is not derived from 'MT2'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m4p(b), m4p(d))) 'error BC30332: Value of type '1-dimensional array of MT4' cannot be converted to '1-dimensional array of MT2' because 'MT4' is not derived from 'MT2'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m4p(d), m4p(b))) 'error BC30332: Value of type '1-dimensional array of MT2' cannot be converted to '1-dimensional array of MT4' because 'MT2' is not derived from 'MT4'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m4p(a), m4p(g))) 'error BC30332: Value of type '1-dimensional array of MT7' cannot be converted to '1-dimensional array of MT1' because 'MT7' is not derived from 'MT1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m4p(g), m4p(a))) 'error BC30332: Value of type '1-dimensional array of MT1' cannot be converted to '1-dimensional array of MT7' because 'MT1' is not derived from 'MT7'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m4p(j), m4p(k))) 'error BC30332: Value of type '1-dimensional array of Class11' cannot be converted to '1-dimensional array of Class9' because 'Class11' is not derived from 'Class9'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m4p(i), m4p(l))) 'error BC30414: Value of type '2-dimensional array of Class8' cannot be converted to '1-dimensional array of Class8' because the array types have different numbers of dimensions.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m4p(l), m4p(i))) 'error BC30414: Value of type '1-dimensional array of Class8' cannot be converted to '2-dimensional array of Class8' because the array types have different numbers of dimensions.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m4p(l), m4p(n))) 'error BC30332: Value of type '1-dimensional array of 1-dimensional array of Class8' cannot be converted to '2-dimensional array of Class8' because '1-dimensional array of Class8' is not derived from 'Class8'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m4p(n), m4p(l))) 'error BC30332: Value of type '2-dimensional array of Class8' cannot be converted to '1-dimensional array of 1-dimensional array of Class8' because 'Class8' is not derived from '1-dimensional array of Class8'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m4p(p), m4p(q))) 'error BC30332: Value of type '1-dimensional array of Structure1' cannot be converted to '1-dimensional array of Interface5' because 'Structure1' is not derived from 'Interface5'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m4p(q), m4p(p))) 'error BC30332: Value of type '1-dimensional array of Interface5' cannot be converted to '1-dimensional array of Structure1' because 'Interface5' is not derived from 'Structure1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m4p(q), m4p(w))) 'error BC30332: Value of type '1-dimensional array of System.ValueType' cannot be converted to '1-dimensional array of Structure1' because 'System.ValueType' is not derived from 'Structure1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m4p(w), m4p(q))) 'error BC30333: Value of type '1-dimensional array of Structure1' cannot be converted to '1-dimensional array of System.ValueType' because 'Structure1' is not a reference type.
Assert.Equal(ConversionKind.WideningArray Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m4p(r), m4p(t)))
Assert.Equal(ConversionKind.WideningArray Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m4p(s), m4p(u)))
Assert.Equal(ConversionKind.NarrowingArray Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m4p(t), m4p(r))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Integer' to '1-dimensional array of Enum1'.
Assert.Equal(ConversionKind.NarrowingArray Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m4p(u), m4p(s))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Long' to '1-dimensional array of Enum2'.
Assert.Equal(ConversionKind.NarrowingArray Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m4p(t), m4p(v))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Enum4' to '1-dimensional array of Enum1'.
Assert.Equal(ConversionKind.NarrowingArray Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m4p(v), m4p(t))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Enum1' to '1-dimensional array of Enum4'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m4p(r), m4p(s))) 'error BC30332: Value of type '1-dimensional array of Long' cannot be converted to '1-dimensional array of Integer' because 'Long' is not derived from 'Integer'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m4p(s), m4p(r))) 'error BC30332: Value of type '1-dimensional array of Integer' cannot be converted to '1-dimensional array of Long' because 'Integer' is not derived from 'Long'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m4p(r), m4p(u))) 'error BC30332: Value of type '1-dimensional array of Enum2' cannot be converted to '1-dimensional array of Integer' because 'Enum2' is not derived from 'Integer'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m4p(u), m4p(r))) 'error BC30332: Value of type '1-dimensional array of Integer' cannot be converted to '1-dimensional array of Enum2' because 'Integer' is not derived from 'Enum2'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m4p(t), m4p(u))) 'error BC30332: Value of type '1-dimensional array of Enum2' cannot be converted to '1-dimensional array of Enum1' because 'Enum2' is not derived from 'Enum1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m4p(u), m4p(t))) 'error BC30332: Value of type '1-dimensional array of Enum1' cannot be converted to '1-dimensional array of Enum2' because 'Enum1' is not derived from 'Enum2'.
Dim m5 = DirectCast(test.GetMembers("M5").Single(), MethodSymbol)
Dim m5p = m5.Parameters.Select(Function(p) p.Type).ToArray()
Assert.Equal(ConversionKind.WideningArray, ClassifyPredefinedAssignment(m5p(a), m5p(b)))
Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m5p(b), m5p(a))) ' error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT1' to '1-dimensional array of MT2'.
Assert.Equal(ConversionKind.WideningArray, ClassifyPredefinedAssignment(m5p(j), m5p(a)))
Assert.Equal(ConversionKind.WideningArray Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m5p(j), m5p(e)))
Assert.Equal(ConversionKind.WideningArray, ClassifyPredefinedAssignment(m5p(l), m5p(e)))
Assert.Equal(ConversionKind.NarrowingArray Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m5p(a), m5p(e))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT5' to '1-dimensional array of MT1'.
Assert.Equal(ConversionKind.NarrowingArray Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m5p(e), m5p(a))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT1' to '1-dimensional array of MT5'.
Assert.Equal(ConversionKind.NarrowingArray Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m5p(e), m5p(g))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT7' to '1-dimensional array of MT5'.
Assert.Equal(ConversionKind.NarrowingArray Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m5p(g), m5p(e))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT5' to '1-dimensional array of MT7'.
Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m5p(a), m5p(j))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Integer' to '1-dimensional array of MT1'.
Assert.Equal(ConversionKind.NarrowingArray Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m5p(a), m5p(l))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Enum1' to '1-dimensional array of MT1'.
Assert.Equal(ConversionKind.NarrowingArray Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m5p(l), m5p(a))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT1' to '1-dimensional array of Enum1'.
Assert.Equal(ConversionKind.NarrowingArray Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m5p(e), m5p(j))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Integer' to '1-dimensional array of MT5'.
Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m5p(e), m5p(l))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Enum1' to '1-dimensional array of MT5'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m5p(a), m5p(i))) 'error BC30332: Value of type '1-dimensional array of MT9' cannot be converted to '1-dimensional array of MT1' because 'MT9' is not derived from 'MT1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m5p(a), m5p(c))) 'error BC30332: Value of type '1-dimensional array of MT3' cannot be converted to '1-dimensional array of MT1' because 'MT3' is not derived from 'MT1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m5p(c), m5p(a))) 'error BC30332: Value of type '1-dimensional array of MT1' cannot be converted to '1-dimensional array of MT3' because 'MT1' is not derived from 'MT3'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m5p(a), m5p(d))) 'error BC30332: Value of type '1-dimensional array of MT4' cannot be converted to '1-dimensional array of MT1' because 'MT4' is not derived from 'MT1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m5p(d), m5p(a))) 'error BC30332: Value of type '1-dimensional array of MT1' cannot be converted to '1-dimensional array of MT4' because 'MT1' is not derived from 'MT4'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m5p(a), m5p(f))) 'error BC30332: Value of type '1-dimensional array of MT6' cannot be converted to '1-dimensional array of MT1' because 'MT6' is not derived from 'MT1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m5p(f), m5p(a))) 'error BC30332: Value of type '1-dimensional array of MT1' cannot be converted to '1-dimensional array of MT6' because 'MT1' is not derived from 'MT6'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m5p(a), m5p(h))) 'error BC30332: Value of type '1-dimensional array of MT8' cannot be converted to '1-dimensional array of MT1' because 'MT8' is not derived from 'MT1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m5p(h), m5p(a))) 'error BC30332: Value of type '1-dimensional array of MT1' cannot be converted to '1-dimensional array of MT8' because 'MT1' is not derived from 'MT8'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m5p(e), m5p(f))) 'error BC30332: Value of type '1-dimensional array of MT6' cannot be converted to '1-dimensional array of MT5' because 'MT6' is not derived from 'MT5'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m5p(f), m5p(e))) 'error BC30332: Value of type '1-dimensional array of MT5' cannot be converted to '1-dimensional array of MT6' because 'MT5' is not derived from 'MT6'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m5p(e), m5p(h))) 'error BC30332: Value of type '1-dimensional array of MT8' cannot be converted to '1-dimensional array of MT5' because 'MT8' is not derived from 'MT5'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m5p(h), m5p(e))) 'error BC30332: Value of type '1-dimensional array of MT5' cannot be converted to '1-dimensional array of MT8' because 'MT5' is not derived from 'MT8'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m5p(a), m5p(k))) 'error BC30332: Value of type '1-dimensional array of UInteger' cannot be converted to '1-dimensional array of MT1' because 'UInteger' is not derived from 'MT1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m5p(k), m5p(a))) 'error BC30332: Value of type '1-dimensional array of MT1' cannot be converted to '1-dimensional array of UInteger' because 'MT1' is not derived from 'UInteger'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m5p(e), m5p(k))) 'error BC30332: Value of type '1-dimensional array of UInteger' cannot be converted to '1-dimensional array of MT5' because 'UInteger' is not derived from 'MT5'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m5p(k), m5p(e))) 'error BC30332: Value of type '1-dimensional array of MT5' cannot be converted to '1-dimensional array of UInteger' because 'MT5' is not derived from 'UInteger'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m5p(j), m5p(k))) 'error BC30332: Value of type '1-dimensional array of UInteger' cannot be converted to '1-dimensional array of Integer' because 'UInteger' is not derived from 'Integer'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m5p(k), m5p(j))) 'error BC30332: Value of type '1-dimensional array of Integer' cannot be converted to '1-dimensional array of UInteger' because 'Integer' is not derived from 'UInteger'.
Assert.Equal(ConversionKind.WideningArray, ClassifyPredefinedAssignment(m5p(m), m5p(n)))
Assert.Equal(ConversionKind.WideningArray, ClassifyPredefinedAssignment(m5p(p), m5p(q)))
Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m5p(n), m5p(m))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Structure1' to '1-dimensional array of MT10'.
Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m5p(q), m5p(p))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Class1' to '1-dimensional array of MT12'.
Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m5p(s), m5p(u))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT15' to '1-dimensional array of System.ValueType'.
Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m5p(u), m5p(s))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of System.ValueType' to '1-dimensional array of MT15'.
Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m5p(t), m5p(u))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT15' to '1-dimensional array of MT14'.
Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m5p(u), m5p(t))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT14' to '1-dimensional array of MT15'.
Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m5p(s), m5p(v))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT16' to '1-dimensional array of System.ValueType'.
Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m5p(v), m5p(s))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of System.ValueType' to '1-dimensional array of MT16'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m5p(n), m5p(o))) 'error BC30332: Value of type '1-dimensional array of MT11' cannot be converted to '1-dimensional array of MT10' because 'MT11' is not derived from 'MT10'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m5p(o), m5p(n))) 'error BC30332: Value of type '1-dimensional array of MT10' cannot be converted to '1-dimensional array of MT11' because 'MT10' is not derived from 'MT11'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m5p(q), m5p(r))) 'error BC30332: Value of type '1-dimensional array of MT13' cannot be converted to '1-dimensional array of MT12' because 'MT13' is not derived from 'MT12'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m5p(r), m5p(q))) 'error BC30332: Value of type '1-dimensional array of MT12' cannot be converted to '1-dimensional array of MT13' because 'MT12' is not derived from 'MT13'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m5p(v), m5p(w))) 'error BC30332: Value of type '1-dimensional array of MT17' cannot be converted to '1-dimensional array of MT16' because 'MT17' is not derived from 'MT16'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m5p(w), m5p(v))) 'error BC30332: Value of type '1-dimensional array of MT16' cannot be converted to '1-dimensional array of MT17' because 'MT16' is not derived from 'MT17'.
' ------------- Value Type
Dim void = c1.GetSpecialType(System_Void)
Dim valueType = c1.GetSpecialType(System_ValueType)
Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(void, void)))
Assert.Equal(NoConversion, ClassifyPredefinedAssignment([object], void))
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(void, [object]))
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(valueType, void))
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(void, valueType))
Dim m10 = DirectCast(test.GetMembers("M10").Single(), MethodSymbol)
Dim m10p = m10.Parameters.Select(Function(p) p.Type).ToArray()
Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m10p(f), m10p(f))))
Assert.Equal(ConversionKind.WideningValue, ClassifyPredefinedAssignment(m10p(a), m10p(f)))
Assert.Equal(ConversionKind.WideningValue, ClassifyPredefinedAssignment(m10p(b), m10p(f)))
Assert.Equal(ConversionKind.WideningValue, ClassifyPredefinedAssignment(m10p(a), m10p(h)))
Assert.Equal(ConversionKind.WideningValue, ClassifyPredefinedAssignment(m10p(b), m10p(h)))
Assert.Equal(ConversionKind.WideningValue, ClassifyPredefinedAssignment(m10p(c), m10p(h)))
Assert.Equal(ConversionKind.WideningValue, ClassifyPredefinedAssignment(m10p(d), m10p(f)))
Assert.Equal(ConversionKind.WideningValue, ClassifyPredefinedAssignment(m10p(i), m10p(f)))
Assert.Equal(ConversionKind.NarrowingValue, ClassifyPredefinedAssignment(m10p(f), m10p(a))) 'error BC30512: Option Strict On disallows implicit conversions from 'Object' to 'Structure2'.
Assert.Equal(ConversionKind.NarrowingValue, ClassifyPredefinedAssignment(m10p(f), m10p(b))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.ValueType' to 'Structure2'.
Assert.Equal(ConversionKind.NarrowingValue, ClassifyPredefinedAssignment(m10p(h), m10p(a))) 'error BC30512: Option Strict On disallows implicit conversions from 'Object' to 'Enum1'.
Assert.Equal(ConversionKind.NarrowingValue, ClassifyPredefinedAssignment(m10p(h), m10p(b))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.ValueType' to 'Enum1'.
Assert.Equal(ConversionKind.NarrowingValue, ClassifyPredefinedAssignment(m10p(h), m10p(c))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.Enum' to 'Enum1'.
Assert.Equal(ConversionKind.NarrowingValue, ClassifyPredefinedAssignment(m10p(f), m10p(d))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface1' to 'Structure2'.
Assert.Equal(ConversionKind.NarrowingValue, ClassifyPredefinedAssignment(m10p(f), m10p(i))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface3' to 'Structure2'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m10p(c), m10p(f))) 'error BC30311: Value of type 'Structure2' cannot be converted to 'System.Enum'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m10p(f), m10p(c))) 'error BC30311: Value of type 'System.Enum' cannot be converted to 'Structure2'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m10p(d), m10p(h))) 'error BC30311: Value of type 'Enum1' cannot be converted to 'Interface1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m10p(h), m10p(d))) 'error BC30311: Value of type 'Interface1' cannot be converted to 'Enum1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m10p(e), m10p(f))) 'error BC30311: Value of type 'Structure2' cannot be converted to 'Interface7'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m10p(f), m10p(e))) 'error BC30311: Value of type 'Interface7' cannot be converted to 'Structure2'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m10p(f), m10p(g))) 'error BC30311: Value of type 'Structure1' cannot be converted to 'Structure2'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m10p(g), m10p(f))) 'error BC30311: Value of type 'Structure2' cannot be converted to 'Structure1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m10p(f), m10p(h))) 'error BC30311: Value of type 'Enum1' cannot be converted to 'Structure2'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m10p(h), m10p(f))) 'error BC30311: Value of type 'Structure2' cannot be converted to 'Enum1'.
' ------------ Nullable
Dim m11 = DirectCast(test.GetMembers("M11").Single(), MethodSymbol)
Dim m11p = m11.Parameters.Select(Function(p) p.Type).ToArray()
Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m11p(d), m11p(d))))
Assert.Equal(ConversionKind.WideningValue, ClassifyPredefinedAssignment(m11p(a), m11p(d)))
Assert.Equal(ConversionKind.WideningValue, ClassifyPredefinedAssignment(m11p(b), m11p(d)))
Assert.Equal(ConversionKind.WideningNullable, ClassifyPredefinedAssignment(m11p(d), m11p(c)))
Assert.Equal(ConversionKind.WideningNullable, ClassifyPredefinedAssignment(m11p(e), m11p(d)))
Assert.Equal(ConversionKind.WideningNullable, ClassifyPredefinedAssignment(m11p(f), m11p(d)))
Assert.Equal(ConversionKind.WideningNullable, ClassifyPredefinedAssignment(m11p(i), m11p(h)))
Assert.Equal(ConversionKind.WideningNullable, ClassifyPredefinedAssignment(m11p(k), m11p(i)))
Assert.Equal(ConversionKind.NarrowingValue, ClassifyPredefinedAssignment(m11p(d), m11p(a))) 'error BC30512: Option Strict On disallows implicit conversions from 'Object' to 'Structure2?'.
Assert.Equal(ConversionKind.NarrowingValue, ClassifyPredefinedAssignment(m11p(d), m11p(b))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.ValueType' to 'Structure2?'.
Assert.Equal(ConversionKind.NarrowingNullable, ClassifyPredefinedAssignment(m11p(c), m11p(d))) 'error BC30512: Option Strict On disallows implicit conversions from 'Structure2?' to 'Structure2'.
Assert.Equal(ConversionKind.NarrowingNullable, ClassifyPredefinedAssignment(m11p(d), m11p(e))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface1' to 'Structure2?'.
Assert.Equal(ConversionKind.NarrowingNullable, ClassifyPredefinedAssignment(m11p(d), m11p(f))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface3' to 'Structure2?'.
Assert.Equal(ConversionKind.NarrowingNullable, ClassifyPredefinedAssignment(m11p(h), m11p(i))) 'error BC30512: Option Strict On disallows implicit conversions from 'Integer?' to 'Integer'.
Assert.Equal(ConversionKind.NarrowingNullable, ClassifyPredefinedAssignment(m11p(i), m11p(k))) 'error BC30512: Option Strict On disallows implicit conversions from 'Long?' to 'Integer?'.
Assert.Equal(ConversionKind.NarrowingNullable, ClassifyPredefinedAssignment(m11p(i), m11p(j))) 'error BC30512: Option Strict On disallows implicit conversions from 'Long' to 'Integer?'.
Assert.Equal(ConversionKind.NarrowingNullable, ClassifyPredefinedAssignment(m11p(j), m11p(i))) 'error BC30512: Option Strict On disallows implicit conversions from 'Integer?' to 'Long'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m11p(c), m11p(i))) 'error BC30311: Value of type 'Integer?' cannot be converted to 'Structure2'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m11p(i), m11p(c))) 'error BC30311: Value of type 'Structure2' cannot be converted to 'Integer?'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m11p(d), m11p(h))) 'error BC30311: Value of type 'Integer' cannot be converted to 'Structure2?'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m11p(h), m11p(d))) 'error BC30311: Value of type 'Structure2?' cannot be converted to 'Integer'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m11p(d), m11p(i))) 'error BC30311: Value of type 'Integer?' cannot be converted to 'Structure2?'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m11p(i), m11p(d))) 'error BC30311: Value of type 'Structure2?' cannot be converted to 'Integer?'.
' ------------ String
Dim m12 = DirectCast(test.GetMembers("M12").Single(), MethodSymbol)
Dim m12p = m12.Parameters.Select(Function(p) p.Type).ToArray()
Assert.Equal(ConversionKind.WideningString, ClassifyPredefinedAssignment(m12p(a), m12p(b)))
Assert.Equal(ConversionKind.WideningString, ClassifyPredefinedAssignment(m12p(a), m12p(c)))
Assert.Equal(ConversionKind.NarrowingString, ClassifyPredefinedAssignment(m12p(b), m12p(a))) 'error BC30512: Option Strict On disallows implicit conversions from 'String' to 'Char'.
Assert.Equal(ConversionKind.NarrowingString, ClassifyPredefinedAssignment(m12p(c), m12p(a))) 'error BC30512: Option Strict On disallows implicit conversions from 'String' to '1-dimensional array of Char'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m12p(b), m12p(c))) 'error BC30311: Value of type '1-dimensional array of Char' cannot be converted to 'Char'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m12p(c), m12p(b))) 'error BC30311: Value of type 'Char' cannot be converted to '1-dimensional array of Char'.
End Sub
Private Shared Function ClassifyPredefinedAssignment([to] As TypeSymbol, [from] As TypeSymbol) As ConversionKind
Dim result As ConversionKind = Conversions.ClassifyPredefinedConversion([from], [to], Nothing) And Not ConversionKind.MightSucceedAtRuntime
Assert.Equal(result, ClassifyConversion([from], [to]))
Return result
End Function
Enum Parameters
a
b
c
d
e
f
g
h
i
j
k
l
m
n
o
p
q
r
s
t
u
v
w
x
y
z
End Enum
<Fact()>
Public Sub BuiltIn()
Dim c1 = VisualBasicCompilation.Create("Test", references:={TestReferences.NetFx.v4_0_21006.mscorlib})
Dim nullable = c1.GetSpecialType(System_Nullable_T)
Dim types As NamedTypeSymbol() = {
c1.GetSpecialType(System_Byte),
c1.GetSpecialType(System_SByte),
c1.GetSpecialType(System_UInt16),
c1.GetSpecialType(System_Int16),
c1.GetSpecialType(System_UInt32),
c1.GetSpecialType(System_Int32),
c1.GetSpecialType(System_UInt64),
c1.GetSpecialType(System_Int64),
c1.GetSpecialType(System_Decimal),
c1.GetSpecialType(System_Single),
c1.GetSpecialType(System_Double),
c1.GetSpecialType(System_String),
c1.GetSpecialType(System_Char),
c1.GetSpecialType(System_Boolean),
c1.GetSpecialType(System_DateTime),
c1.GetSpecialType(System_Object),
nullable.Construct(c1.GetSpecialType(System_Byte)),
nullable.Construct(c1.GetSpecialType(System_SByte)),
nullable.Construct(c1.GetSpecialType(System_UInt16)),
nullable.Construct(c1.GetSpecialType(System_Int16)),
nullable.Construct(c1.GetSpecialType(System_UInt32)),
nullable.Construct(c1.GetSpecialType(System_Int32)),
nullable.Construct(c1.GetSpecialType(System_UInt64)),
nullable.Construct(c1.GetSpecialType(System_Int64)),
nullable.Construct(c1.GetSpecialType(System_Decimal)),
nullable.Construct(c1.GetSpecialType(System_Single)),
nullable.Construct(c1.GetSpecialType(System_Double)),
nullable.Construct(c1.GetSpecialType(System_Char)),
nullable.Construct(c1.GetSpecialType(System_Boolean)),
nullable.Construct(c1.GetSpecialType(System_DateTime))
}
For i As Integer = 0 To types.Length - 1 Step 1
For j As Integer = 0 To types.Length - 1 Step 1
Dim convClass = Conversions.ClassifyPredefinedConversion(types(i), types(j), Nothing)
Assert.Equal(convClass, Conversions.ConversionEasyOut.ClassifyPredefinedConversion(types(i), types(j)))
Assert.Equal(convClass, ClassifyConversion(types(i), types(j)))
If (i = j) Then
Assert.True(Conversions.IsIdentityConversion(convClass))
Else
Dim baseline = HasBuiltInWideningConversions(types(i), types(j))
If baseline = NoConversion Then
baseline = HasBuiltInNarrowingConversions(types(i), types(j))
End If
Assert.Equal(baseline, convClass)
End If
Next
Next
End Sub
Private Function HasBuiltInWideningConversions(from As TypeSymbol, [to] As TypeSymbol) As ConversionKind
Dim result = HasBuiltInWideningConversions(from.SpecialType, [to].SpecialType)
If result = NoConversion Then
Dim fromIsNullable = from.IsNullableType()
Dim fromElement = If(fromIsNullable, from.GetNullableUnderlyingType(), Nothing)
If fromIsNullable AndAlso [to].SpecialType = System_Object Then
Return ConversionKind.WideningValue
End If
Dim toIsNullable = [to].IsNullableType()
Dim toElement = If(toIsNullable, [to].GetNullableUnderlyingType(), Nothing)
'Nullable Value Type conversions
'• From a type T? to a type S?, where there is a widening conversion from the type T to the type S.
If (fromIsNullable AndAlso toIsNullable) Then
If (HasBuiltInWideningConversions(fromElement, toElement) And ConversionKind.Widening) <> 0 Then
Return ConversionKind.WideningNullable
End If
End If
If (Not fromIsNullable AndAlso toIsNullable) Then
'• From a type T to the type T?.
If from.Equals(toElement) Then
Return ConversionKind.WideningNullable
End If
'• From a type T to a type S?, where there is a widening conversion from the type T to the type S.
If (HasBuiltInWideningConversions(from, toElement) And ConversionKind.Widening) <> 0 Then
Return ConversionKind.WideningNullable
End If
End If
End If
Return result
End Function
Private Function HasBuiltInNarrowingConversions(from As TypeSymbol, [to] As TypeSymbol) As ConversionKind
Dim result = HasBuiltInNarrowingConversions(from.SpecialType, [to].SpecialType)
If result = NoConversion Then
Dim toIsNullable = [to].IsNullableType()
Dim toElement = If(toIsNullable, [to].GetNullableUnderlyingType(), Nothing)
If from.SpecialType = System_Object AndAlso toIsNullable Then
Return ConversionKind.NarrowingValue
End If
Dim fromIsNullable = from.IsNullableType()
Dim fromElement = If(fromIsNullable, from.GetNullableUnderlyingType(), Nothing)
'Nullable Value Type conversions
If (fromIsNullable AndAlso Not toIsNullable) Then
'• From a type T? to a type T.
If fromElement.Equals([to]) Then
Return ConversionKind.NarrowingNullable
End If
'• From a type S? to a type T, where there is a conversion from the type S to the type T.
If HasBuiltInWideningConversions(fromElement, [to]) <> NoConversion OrElse
HasBuiltInNarrowingConversions(fromElement, [to]) <> NoConversion Then
Return ConversionKind.NarrowingNullable
End If
End If
'• From a type T? to a type S?, where there is a narrowing conversion from the type T to the type S.
If (fromIsNullable AndAlso toIsNullable) Then
If (HasBuiltInNarrowingConversions(fromElement, toElement) And ConversionKind.Narrowing) <> 0 Then
Return ConversionKind.NarrowingNullable
End If
End If
'• From a type T to a type S?, where there is a narrowing conversion from the type T to the type S.
If (Not fromIsNullable AndAlso toIsNullable) Then
If (HasBuiltInNarrowingConversions(from, toElement) And ConversionKind.Narrowing) <> 0 Then
Return ConversionKind.NarrowingNullable
End If
End If
End If
Return result
End Function
Const [Byte] = System_Byte
Const [SByte] = System_SByte
Const [UShort] = System_UInt16
Const [Short] = System_Int16
Const [UInteger] = System_UInt32
Const [Integer] = System_Int32
Const [ULong] = System_UInt64
Const [Long] = System_Int64
Const [Decimal] = System_Decimal
Const [Single] = System_Single
Const [Double] = System_Double
Const [String] = System_String
Const [Char] = System_Char
Const [Boolean] = System_Boolean
Const [Date] = System_DateTime
Const [Object] = System_Object
Private Function HasBuiltInWideningConversions(from As SpecialType, [to] As SpecialType) As ConversionKind
Select Case CInt(from)
'Numeric conversions
'• From Byte to UShort, Short, UInteger, Integer, ULong, Long, Decimal, Single, or Double.
Case [Byte]
Select Case CInt([to])
Case [UShort], [Short], [UInteger], [Integer], [ULong], [Long], [Decimal], [Single], [Double]
Return ConversionKind.WideningNumeric
End Select
'• From SByte to Short, Integer, Long, Decimal, Single, or Double.
Case [SByte]
Select Case CInt([to])
Case [Short], [Integer], [Long], [Decimal], [Single], [Double]
Return ConversionKind.WideningNumeric
End Select
'• From UShort to UInteger, Integer, ULong, Long, Decimal, Single, or Double.
Case [UShort]
Select Case CInt([to])
Case [UInteger], [Integer], [ULong], [Long], [Decimal], [Single], [Double]
Return ConversionKind.WideningNumeric
End Select
'• From Short to Integer, Long, Decimal, Single or Double.
Case [Short]
Select Case CInt([to])
Case [Integer], [Long], [Decimal], [Single], [Double]
Return ConversionKind.WideningNumeric
End Select
'• From UInteger to ULong, Long, Decimal, Single, or Double.
Case [UInteger]
Select Case CInt([to])
Case [ULong], [Long], [Decimal], [Single], [Double]
Return ConversionKind.WideningNumeric
End Select
'• From Integer to Long, Decimal, Single or Double.
Case [Integer]
Select Case CInt([to])
Case [Long], [Decimal], [Single], [Double]
Return ConversionKind.WideningNumeric
End Select
'• From ULong to Decimal, Single, or Double.
Case [ULong]
Select Case CInt([to])
Case [Decimal], [Single], [Double]
Return ConversionKind.WideningNumeric
End Select
'• From Long to Decimal, Single or Double.
Case [Long]
Select Case CInt([to])
Case [Decimal], [Single], [Double]
Return ConversionKind.WideningNumeric
End Select
'• From Decimal to Single or Double.
Case [Decimal]
Select Case CInt([to])
Case [Single], [Double]
Return ConversionKind.WideningNumeric
End Select
'• From Single to Double.
Case [Single]
Select Case CInt([to])
Case [Double]
Return ConversionKind.WideningNumeric
End Select
'Reference conversions
'• From a reference type to a base type.
Case [String]
Select Case CInt([to])
Case [Object]
Return ConversionKind.WideningReference
End Select
'String conversions
'• From Char to String.
Case [Char]
Select Case CInt([to])
Case [String]
Return ConversionKind.WideningString
End Select
End Select
Select Case CInt([to])
'Value Type conversions
'• From a value type to a base type.
Case [Object]
Select Case CInt([from])
Case [Byte], [SByte], [UShort], [Short], [UInteger], [Integer], [ULong], [Long], [Decimal], [Single], [Double],
[Char], [Boolean], [Date]
Return ConversionKind.WideningValue
End Select
End Select
Return NoConversion
End Function
Private Function HasBuiltInNarrowingConversions(from As SpecialType, [to] As SpecialType) As ConversionKind
Select Case CInt(from)
'Boolean conversions
'• From Boolean to Byte, SByte, UShort, Short, UInteger, Integer, ULong, Long, Decimal, Single, or Double.
Case [Boolean]
Select Case CInt([to])
Case [Byte], [SByte], [UShort], [Short], [UInteger], [Integer], [ULong], [Long], [Decimal], [Single], [Double]
Return ConversionKind.NarrowingBoolean
End Select
'Numeric conversions
'• From Byte to SByte.
Case [Byte]
Select Case CInt([to])
Case [SByte]
Return ConversionKind.NarrowingNumeric
End Select
'• From SByte to Byte, UShort, UInteger, or ULong.
Case [SByte]
Select Case CInt([to])
Case [Byte], [UShort], [UInteger], [ULong]
Return ConversionKind.NarrowingNumeric
End Select
'• From UShort to Byte, SByte, or Short.
Case [UShort]
Select Case CInt([to])
Case [Byte], [SByte], [Short]
Return ConversionKind.NarrowingNumeric
End Select
'• From Short to Byte, SByte, UShort, UInteger, or ULong.
Case [Short]
Select Case CInt([to])
Case [Byte], [SByte], [UShort], [UInteger], [ULong]
Return ConversionKind.NarrowingNumeric
End Select
'• From UInteger to Byte, SByte, UShort, Short, or Integer.
Case [UInteger]
Select Case CInt([to])
Case [Byte], [SByte], [UShort], [Short], [Integer]
Return ConversionKind.NarrowingNumeric
End Select
'• From Integer to Byte, SByte, UShort, Short, UInteger, or ULong.
Case [Integer]
Select Case CInt([to])
Case [Byte], [SByte], [UShort], [Short], [UInteger], [ULong]
Return ConversionKind.NarrowingNumeric
End Select
'• From ULong to Byte, SByte, UShort, Short, UInteger, Integer, or Long.
Case [ULong]
Select Case CInt([to])
Case [Byte], [SByte], [UShort], [Short], [UInteger], [Integer], [Long]
Return ConversionKind.NarrowingNumeric
End Select
'• From Long to Byte, SByte, UShort, Short, UInteger, Integer, or ULong.
Case [Long]
Select Case CInt([to])
Case [Byte], [SByte], [UShort], [Short], [UInteger], [Integer], [ULong]
Return ConversionKind.NarrowingNumeric
End Select
'• From Decimal to Byte, SByte, UShort, Short, UInteger, Integer, ULong, or Long.
Case [Decimal]
Select Case CInt([to])
Case [Byte], [SByte], [UShort], [Short], [UInteger], [Integer], [ULong], [Long]
Return ConversionKind.NarrowingNumeric
End Select
'• From Single to Byte, SByte, UShort, Short, UInteger, Integer, ULong, Long, or Decimal.
Case [Single]
Select Case CInt([to])
Case [Byte], [SByte], [UShort], [Short], [UInteger], [Integer], [ULong], [Long], [Decimal]
Return ConversionKind.NarrowingNumeric
End Select
'• From Double to Byte, SByte, UShort, Short, UInteger, Integer, ULong, Long, Decimal, or Single.
Case [Double]
Select Case CInt([to])
Case [Byte], [SByte], [UShort], [Short], [UInteger], [Integer], [ULong], [Long], [Decimal], [Single]
Return ConversionKind.NarrowingNumeric
End Select
'String conversions
'• From String to Char.
'• From String to Boolean and from Boolean to String.
'• Conversions between String and Byte, SByte, UShort, Short, UInteger, Integer, ULong, Long, Decimal, Single, or Double.
'• From String to Date and from Date to String.
Case [String]
Select Case CInt([to])
Case [Char],
[Boolean],
[Byte], [SByte], [UShort], [Short], [UInteger], [Integer], [ULong], [Long], [Decimal], [Single], [Double],
[Date]
Return ConversionKind.NarrowingString
End Select
'VB Runtime Conversions
Case [Object]
Select Case CInt([to])
Case [Byte], [SByte], [UShort], [Short], [UInteger], [Integer], [ULong], [Long], [Decimal], [Single], [Double],
[Char], [Boolean], [Date]
Return ConversionKind.NarrowingValue
Case [String]
Return ConversionKind.NarrowingReference
End Select
End Select
Select Case CInt([to])
'Boolean conversions
'• From Byte, SByte, UShort, Short, UInteger, Integer, ULong, Long, Decimal, Single, or Double to Boolean.
Case [Boolean]
Select Case CInt([from])
Case [Byte], [SByte], [UShort], [Short], [UInteger], [Integer], [ULong], [Long], [Decimal], [Single], [Double]
Return ConversionKind.NarrowingBoolean
End Select
'String conversions
'• From String to Boolean and from Boolean to String.
'• Conversions between String and Byte, SByte, UShort, Short, UInteger, Integer, ULong, Long, Decimal, Single, or Double.
'• From String to Date and from Date to String.
Case [String]
Select Case CInt([from])
Case [Boolean],
[Byte], [SByte], [UShort], [Short], [UInteger], [Integer], [ULong], [Long], [Decimal], [Single], [Double],
[Date]
Return ConversionKind.NarrowingString
End Select
End Select
Return NoConversion
End Function
<Fact()>
Public Sub EnumConversions()
CompileAndVerify(
<compilation name="VBEnumConversions">
<file name="a.vb">
Option Strict Off
Imports System
Imports System.Globalization
Imports System.Collections.Generic
Module Module1
Sub Main()
Dim BoFalse As Boolean
Dim BoTrue As Boolean
Dim SB As SByte
Dim By As Byte
Dim Sh As Short
Dim US As UShort
Dim [In] As Integer
Dim UI As UInteger
Dim Lo As Long
Dim UL As ULong
Dim De As Decimal
Dim Si As Single
Dim [Do] As Double
Dim St As String
Dim Ob As Object
Dim Tc As TypeCode
Dim TcAsVT As ValueType
BoFalse = False
BoTrue = True
SB = 1
By = 2
Sh = 3
US = 4
[In] = 5
UI = 6
Lo = 7
UL = 8
Si = 10
[Do] = 11
De = 9D
St = "12"
Ob = 13
Tc = TypeCode.Decimal
TcAsVT = Tc
System.Console.WriteLine("Conversions to enum:")
PrintResultTc(BoFalse)
PrintResultTc(BoTrue)
PrintResultTc(SB)
PrintResultTc(By)
PrintResultTc(Sh)
PrintResultTc(US)
PrintResultTc([In])
PrintResultTc(UI)
PrintResultTc(Lo)
PrintResultTc(UL)
PrintResultTc(Si)
PrintResultTc([Do])
PrintResultTc(De)
PrintResultTc(Ob)
PrintResultTc(St)
PrintResultTc(TcAsVT)
System.Console.WriteLine()
System.Console.WriteLine("Conversions from enum:")
PrintResultBo(Tc)
PrintResultSB(Tc)
PrintResultBy(Tc)
PrintResultSh(Tc)
PrintResultUs(Tc)
PrintResultIn(Tc)
PrintResultUI(Tc)
PrintResultLo(Tc)
PrintResultUL(Tc)
PrintResultSi(Tc)
PrintResultDo(Tc)
PrintResultDe(Tc)
PrintResultOb(Tc)
PrintResultSt(Tc)
PrintResultValueType(Tc)
End Sub
Sub PrintResultTc(val As TypeCode)
System.Console.WriteLine("TypeCode: {0}", val)
End Sub
Sub PrintResultBo(val As Boolean)
System.Console.WriteLine("Boolean: {0}", val)
End Sub
Sub PrintResultSB(val As SByte)
System.Console.WriteLine("SByte: {0}", val)
End Sub
Sub PrintResultBy(val As Byte)
System.Console.WriteLine("Byte: {0}", val)
End Sub
Sub PrintResultSh(val As Short)
System.Console.WriteLine("Short: {0}", val)
End Sub
Sub PrintResultUs(val As UShort)
System.Console.WriteLine("UShort: {0}", val)
End Sub
Sub PrintResultIn(val As Integer)
System.Console.WriteLine("Integer: {0}", val)
End Sub
Sub PrintResultUI(val As UInteger)
System.Console.WriteLine("UInteger: {0}", val)
End Sub
Sub PrintResultLo(val As Long)
System.Console.WriteLine("Long: {0}", val)
End Sub
Sub PrintResultUL(val As ULong)
System.Console.WriteLine("ULong: {0}", val)
End Sub
Sub PrintResultDe(val As Decimal)
System.Console.WriteLine("Decimal: {0}", val)
End Sub
Sub PrintResultSi(val As Single)
System.Console.WriteLine("Single: {0}", val)
End Sub
Sub PrintResultDo(val As Double)
System.Console.WriteLine("Double: {0}", val)
End Sub
Sub PrintResultSt(val As String)
System.Console.WriteLine("String: {0}", val)
End Sub
Sub PrintResultOb(val As Object)
System.Console.WriteLine("Object: {0}", val)
End Sub
Sub PrintResultValueType(val As ValueType)
System.Console.WriteLine("ValueType: {0}", val)
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
Conversions to enum:
TypeCode: Empty
TypeCode: -1
TypeCode: Object
TypeCode: DBNull
TypeCode: Boolean
TypeCode: Char
TypeCode: SByte
TypeCode: Byte
TypeCode: Int16
TypeCode: UInt16
TypeCode: UInt32
TypeCode: Int64
TypeCode: Int32
TypeCode: Single
TypeCode: UInt64
TypeCode: Decimal
Conversions from enum:
Boolean: True
SByte: 15
Byte: 15
Short: 15
UShort: 15
Integer: 15
UInteger: 15
Long: 15
ULong: 15
Single: 15
Double: 15
Decimal: 15
Object: Decimal
String: 15
ValueType: Decimal
]]>)
End Sub
<Fact()>
Public Sub ConversionDiagnostic1()
Dim compilationDef =
<compilation name="VBConversionsDiagnostic1">
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Dim [In] As Integer
[In] = Console.WriteLine()
[In] = CType(Console.WriteLine(), Integer)
[In] = CType(1, UnknownType)
[In] = CType(unknownValue, Integer)
[In] = CType(unknownValue, UnknownType)
Dim tr As System.TypedReference = Nothing
Dim ai As System.ArgIterator = Nothing
Dim ra As System.RuntimeArgumentHandle = Nothing
Dim Ob As Object
Ob = tr
Ob = ai
Ob = ra
Ob = CType(tr, Object)
Ob = CType(ai, Object)
Ob = CType(ra, Object)
Dim vt As ValueType
vt = tr
vt = ai
vt = ra
vt = CType(tr, ValueType)
vt = CType(ai, ValueType)
vt = CType(ra, ValueType)
Dim collection As Microsoft.VisualBasic.Collection = Nothing
Dim _collection As _Collection = Nothing
collection = _collection
_collection = collection
collection = CType(_collection, Microsoft.VisualBasic.Collection)
_collection = CType(collection, _Collection)
Dim Si As Single
Dim De As Decimal
[In] = Int64.MaxValue
[In] = CInt(Int64.MaxValue)
Si = System.Double.MaxValue
Si = CSng(System.Double.MaxValue)
De = System.Double.MaxValue
De = CDec(System.Double.MaxValue)
De = 10.0F
De = CDec(10.0F)
Dim Da As DateTime = Nothing
[In] = Da
[In] = CInt(Da)
Da = [In]
Da = CDate([In])
Dim [Do] As Double = Nothing
Dim Ch As Char = Nothing
[Do] = Da
[Do] = CDbl(Da)
Da = [Do]
Da = CDate([Do])
[In] = Ch
[In] = CInt(Ch)
Ch = [In]
Ch = CChar([In])
Dim InArray As Integer() = Nothing
Dim ObArray As Object() = Nothing
Dim VtArray As ValueType() = Nothing
ObArray = InArray
ObArray = CType(InArray, Object())
VtArray = InArray
VtArray = CType(InArray, ValueType())
Dim TC1Array As TestClass1() = Nothing
Dim TC2Array As TestClass2() = Nothing
TC1Array = TC2Array
TC2Array = CType(TC1Array, TestClass2())
Dim InArray2 As Integer(,) = Nothing
InArray = InArray2
InArray2 = CType(InArray, Integer(,))
Dim TI1Array As TestInterface1() = Nothing
InArray = TI1Array
TI1Array = CType(InArray, TestInterface1())
End Sub
End Module
Interface TestInterface1
End Interface
Interface _Collection
End Interface
Class TestClass1
End Class
Class TestClass2
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.On))
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_VoidValue, "Console.WriteLine()"),
Diagnostic(ERRID.ERR_VoidValue, "Console.WriteLine()"),
Diagnostic(ERRID.ERR_UndefinedType1, "UnknownType").WithArguments("UnknownType"),
Diagnostic(ERRID.ERR_NameNotDeclared1, "unknownValue").WithArguments("unknownValue"),
Diagnostic(ERRID.ERR_NameNotDeclared1, "unknownValue").WithArguments("unknownValue"),
Diagnostic(ERRID.ERR_UndefinedType1, "UnknownType").WithArguments("UnknownType"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"),
Diagnostic(ERRID.WRN_InterfaceConversion2, "_collection").WithArguments("_Collection", "Microsoft.VisualBasic.Collection"),
Diagnostic(ERRID.ERR_NarrowingConversionCollection2, "_collection").WithArguments("_Collection", "Microsoft.VisualBasic.Collection"),
Diagnostic(ERRID.WRN_InterfaceConversion2, "collection").WithArguments("Microsoft.VisualBasic.Collection", "_Collection"),
Diagnostic(ERRID.ERR_NarrowingConversionCollection2, "collection").WithArguments("Microsoft.VisualBasic.Collection", "_Collection"),
Diagnostic(ERRID.WRN_InterfaceConversion2, "_collection").WithArguments("_Collection", "Microsoft.VisualBasic.Collection"),
Diagnostic(ERRID.WRN_InterfaceConversion2, "collection").WithArguments("Microsoft.VisualBasic.Collection", "_Collection"),
Diagnostic(ERRID.ERR_ExpressionOverflow1, "Int64.MaxValue").WithArguments("Integer"),
Diagnostic(ERRID.ERR_ExpressionOverflow1, "Int64.MaxValue").WithArguments("Integer"),
Diagnostic(ERRID.ERR_ExpressionOverflow1, "System.Double.MaxValue").WithArguments("Decimal"),
Diagnostic(ERRID.ERR_ExpressionOverflow1, "System.Double.MaxValue").WithArguments("Decimal"),
Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, "10.0F").WithArguments("Single", "Decimal"),
Diagnostic(ERRID.ERR_TypeMismatch2, "Da").WithArguments("Date", "Integer"),
Diagnostic(ERRID.ERR_TypeMismatch2, "Da").WithArguments("Date", "Integer"),
Diagnostic(ERRID.ERR_TypeMismatch2, "[In]").WithArguments("Integer", "Date"),
Diagnostic(ERRID.ERR_TypeMismatch2, "[In]").WithArguments("Integer", "Date"),
Diagnostic(ERRID.ERR_DateToDoubleConversion, "Da"),
Diagnostic(ERRID.ERR_DateToDoubleConversion, "Da"),
Diagnostic(ERRID.ERR_DoubleToDateConversion, "[Do]"),
Diagnostic(ERRID.ERR_DoubleToDateConversion, "[Do]"),
Diagnostic(ERRID.ERR_CharToIntegralTypeMismatch1, "Ch").WithArguments("Integer"),
Diagnostic(ERRID.ERR_CharToIntegralTypeMismatch1, "Ch").WithArguments("Integer"),
Diagnostic(ERRID.ERR_IntegralToCharTypeMismatch1, "[In]").WithArguments("Integer"),
Diagnostic(ERRID.ERR_IntegralToCharTypeMismatch1, "[In]").WithArguments("Integer"),
Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "Object()", "Integer"),
Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "Object()", "Integer"),
Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "System.ValueType()", "Integer"),
Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "System.ValueType()", "Integer"),
Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "TC2Array").WithArguments("TestClass2()", "TestClass1()", "TestClass2", "TestClass1"),
Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "TC1Array").WithArguments("TestClass1()", "TestClass2()", "TestClass1", "TestClass2"),
Diagnostic(ERRID.ERR_ConvertArrayRankMismatch2, "InArray2").WithArguments("Integer(*,*)", "Integer()"),
Diagnostic(ERRID.ERR_ConvertArrayRankMismatch2, "InArray").WithArguments("Integer()", "Integer(*,*)"),
Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "TI1Array").WithArguments("TestInterface1()", "Integer()", "TestInterface1", "Integer"),
Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "InArray").WithArguments("Integer()", "TestInterface1()", "Integer", "TestInterface1"))
compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.Off))
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_VoidValue, "Console.WriteLine()"),
Diagnostic(ERRID.ERR_VoidValue, "Console.WriteLine()"),
Diagnostic(ERRID.ERR_UndefinedType1, "UnknownType").WithArguments("UnknownType"),
Diagnostic(ERRID.ERR_NameNotDeclared1, "unknownValue").WithArguments("unknownValue"),
Diagnostic(ERRID.ERR_NameNotDeclared1, "unknownValue").WithArguments("unknownValue"),
Diagnostic(ERRID.ERR_UndefinedType1, "UnknownType").WithArguments("UnknownType"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"),
Diagnostic(ERRID.WRN_InterfaceConversion2, "_collection").WithArguments("_Collection", "Microsoft.VisualBasic.Collection"),
Diagnostic(ERRID.WRN_InterfaceConversion2, "collection").WithArguments("Microsoft.VisualBasic.Collection", "_Collection"),
Diagnostic(ERRID.WRN_InterfaceConversion2, "_collection").WithArguments("_Collection", "Microsoft.VisualBasic.Collection"),
Diagnostic(ERRID.WRN_InterfaceConversion2, "collection").WithArguments("Microsoft.VisualBasic.Collection", "_Collection"),
Diagnostic(ERRID.ERR_ExpressionOverflow1, "Int64.MaxValue").WithArguments("Integer"),
Diagnostic(ERRID.ERR_ExpressionOverflow1, "Int64.MaxValue").WithArguments("Integer"),
Diagnostic(ERRID.ERR_ExpressionOverflow1, "System.Double.MaxValue").WithArguments("Decimal"),
Diagnostic(ERRID.ERR_ExpressionOverflow1, "System.Double.MaxValue").WithArguments("Decimal"),
Diagnostic(ERRID.ERR_TypeMismatch2, "Da").WithArguments("Date", "Integer"),
Diagnostic(ERRID.ERR_TypeMismatch2, "Da").WithArguments("Date", "Integer"),
Diagnostic(ERRID.ERR_TypeMismatch2, "[In]").WithArguments("Integer", "Date"),
Diagnostic(ERRID.ERR_TypeMismatch2, "[In]").WithArguments("Integer", "Date"),
Diagnostic(ERRID.ERR_DateToDoubleConversion, "Da"),
Diagnostic(ERRID.ERR_DateToDoubleConversion, "Da"),
Diagnostic(ERRID.ERR_DoubleToDateConversion, "[Do]"),
Diagnostic(ERRID.ERR_DoubleToDateConversion, "[Do]"),
Diagnostic(ERRID.ERR_CharToIntegralTypeMismatch1, "Ch").WithArguments("Integer"),
Diagnostic(ERRID.ERR_CharToIntegralTypeMismatch1, "Ch").WithArguments("Integer"),
Diagnostic(ERRID.ERR_IntegralToCharTypeMismatch1, "[In]").WithArguments("Integer"),
Diagnostic(ERRID.ERR_IntegralToCharTypeMismatch1, "[In]").WithArguments("Integer"),
Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "Object()", "Integer"),
Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "Object()", "Integer"),
Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "System.ValueType()", "Integer"),
Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "System.ValueType()", "Integer"),
Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "TC2Array").WithArguments("TestClass2()", "TestClass1()", "TestClass2", "TestClass1"),
Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "TC1Array").WithArguments("TestClass1()", "TestClass2()", "TestClass1", "TestClass2"),
Diagnostic(ERRID.ERR_ConvertArrayRankMismatch2, "InArray2").WithArguments("Integer(*,*)", "Integer()"),
Diagnostic(ERRID.ERR_ConvertArrayRankMismatch2, "InArray").WithArguments("Integer()", "Integer(*,*)"),
Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "TI1Array").WithArguments("TestInterface1()", "Integer()", "TestInterface1", "Integer"),
Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "InArray").WithArguments("Integer()", "TestInterface1()", "Integer", "TestInterface1"))
compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.Custom))
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_VoidValue, "Console.WriteLine()"),
Diagnostic(ERRID.ERR_VoidValue, "Console.WriteLine()"),
Diagnostic(ERRID.ERR_UndefinedType1, "UnknownType").WithArguments("UnknownType"),
Diagnostic(ERRID.ERR_NameNotDeclared1, "unknownValue").WithArguments("unknownValue"),
Diagnostic(ERRID.ERR_NameNotDeclared1, "unknownValue").WithArguments("unknownValue"),
Diagnostic(ERRID.ERR_UndefinedType1, "UnknownType").WithArguments("UnknownType"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"),
Diagnostic(ERRID.WRN_InterfaceConversion2, "_collection").WithArguments("_Collection", "Microsoft.VisualBasic.Collection"),
Diagnostic(ERRID.WRN_ImplicitConversionSubst1, "_collection").WithArguments("Implicit conversion from '_Collection' to 'Collection'."),
Diagnostic(ERRID.WRN_InterfaceConversion2, "collection").WithArguments("Microsoft.VisualBasic.Collection", "_Collection"),
Diagnostic(ERRID.WRN_ImplicitConversionSubst1, "collection").WithArguments("Implicit conversion from 'Collection' to '_Collection'."),
Diagnostic(ERRID.WRN_InterfaceConversion2, "_collection").WithArguments("_Collection", "Microsoft.VisualBasic.Collection"),
Diagnostic(ERRID.WRN_InterfaceConversion2, "collection").WithArguments("Microsoft.VisualBasic.Collection", "_Collection"),
Diagnostic(ERRID.ERR_ExpressionOverflow1, "Int64.MaxValue").WithArguments("Integer"),
Diagnostic(ERRID.ERR_ExpressionOverflow1, "Int64.MaxValue").WithArguments("Integer"),
Diagnostic(ERRID.ERR_ExpressionOverflow1, "System.Double.MaxValue").WithArguments("Decimal"),
Diagnostic(ERRID.ERR_ExpressionOverflow1, "System.Double.MaxValue").WithArguments("Decimal"),
Diagnostic(ERRID.WRN_ImplicitConversionSubst1, "10.0F").WithArguments("Implicit conversion from 'Single' to 'Decimal'."),
Diagnostic(ERRID.ERR_TypeMismatch2, "Da").WithArguments("Date", "Integer"),
Diagnostic(ERRID.ERR_TypeMismatch2, "Da").WithArguments("Date", "Integer"),
Diagnostic(ERRID.ERR_TypeMismatch2, "[In]").WithArguments("Integer", "Date"),
Diagnostic(ERRID.ERR_TypeMismatch2, "[In]").WithArguments("Integer", "Date"),
Diagnostic(ERRID.ERR_DateToDoubleConversion, "Da"),
Diagnostic(ERRID.ERR_DateToDoubleConversion, "Da"),
Diagnostic(ERRID.ERR_DoubleToDateConversion, "[Do]"),
Diagnostic(ERRID.ERR_DoubleToDateConversion, "[Do]"),
Diagnostic(ERRID.ERR_CharToIntegralTypeMismatch1, "Ch").WithArguments("Integer"),
Diagnostic(ERRID.ERR_CharToIntegralTypeMismatch1, "Ch").WithArguments("Integer"),
Diagnostic(ERRID.ERR_IntegralToCharTypeMismatch1, "[In]").WithArguments("Integer"),
Diagnostic(ERRID.ERR_IntegralToCharTypeMismatch1, "[In]").WithArguments("Integer"),
Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "Object()", "Integer"),
Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "Object()", "Integer"),
Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "System.ValueType()", "Integer"),
Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "System.ValueType()", "Integer"),
Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "TC2Array").WithArguments("TestClass2()", "TestClass1()", "TestClass2", "TestClass1"),
Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "TC1Array").WithArguments("TestClass1()", "TestClass2()", "TestClass1", "TestClass2"),
Diagnostic(ERRID.ERR_ConvertArrayRankMismatch2, "InArray2").WithArguments("Integer(*,*)", "Integer()"),
Diagnostic(ERRID.ERR_ConvertArrayRankMismatch2, "InArray").WithArguments("Integer()", "Integer(*,*)"),
Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "TI1Array").WithArguments("TestInterface1()", "Integer()", "TestInterface1", "Integer"),
Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "InArray").WithArguments("Integer()", "TestInterface1()", "Integer", "TestInterface1"))
End Sub
<Fact()>
Public Sub DirectCastDiagnostic1()
Dim compilationDef =
<compilation name="DirectCastDiagnostic1">
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Dim [In] As Integer
[In] = DirectCast(Console.WriteLine(), Integer)
[In] = DirectCast(1, UnknownType)
[In] = DirectCast(unknownValue, Integer)
[In] = DirectCast(unknownValue, UnknownType)
Dim tr As System.TypedReference = Nothing
Dim ai As System.ArgIterator = Nothing
Dim ra As System.RuntimeArgumentHandle = Nothing
Dim Ob As Object
Ob = DirectCast(tr, Object)
Ob = DirectCast(ai, Object)
Ob = DirectCast(ra, Object)
Dim vt As ValueType
vt = DirectCast(tr, ValueType)
vt = DirectCast(ai, ValueType)
vt = DirectCast(ra, ValueType)
Dim collection As Microsoft.VisualBasic.Collection = Nothing
Dim _collection As _Collection = Nothing
collection = DirectCast(_collection, Microsoft.VisualBasic.Collection)
_collection = DirectCast(collection, _Collection)
Dim Si As Single
Dim De As Decimal
[In] = DirectCast(Int64.MaxValue, Int32)
De = DirectCast(System.Double.MaxValue, System.Decimal)
Dim Da As DateTime = Nothing
[In] = DirectCast(Da, Int32)
Da = DirectCast([In], DateTime)
Dim [Do] As Double = Nothing
Dim Ch As Char = Nothing
[Do] = DirectCast(Da, System.Double)
Da = DirectCast([Do], DateTime)
[In] = DirectCast(Ch, Int32)
Ch = DirectCast([In], System.Char)
Dim InArray As Integer() = Nothing
Dim ObArray As Object() = Nothing
Dim VtArray As ValueType() = Nothing
ObArray = DirectCast(InArray, Object())
VtArray = DirectCast(InArray, ValueType())
Dim TC1Array As TestClass1() = Nothing
Dim TC2Array As TestClass2() = Nothing
TC2Array = DirectCast(TC1Array, TestClass2())
Dim InArray2 As Integer(,) = Nothing
InArray2 = DirectCast(InArray, Integer(,))
Dim TI1Array As TestInterface1() = Nothing
TI1Array = DirectCast(InArray, TestInterface1())
Dim St As String = Nothing
Dim ChArray As Char() = Nothing
Ch = DirectCast(St, System.Char)
St = DirectCast(Ch, System.String)
St = DirectCast(ChArray, System.String)
ChArray = DirectCast(St, System.Char())
[In] = DirectCast([In], System.Int32)
Si = DirectCast(Si, System.Single)
[Do] = DirectCast([Do], System.Double)
[Do] = DirectCast(Si, System.Double)
End Sub
End Module
Interface TestInterface1
End Interface
Interface _Collection
End Interface
Class TestClass1
End Class
Class TestClass2
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.On))
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_VoidValue, "Console.WriteLine()"),
Diagnostic(ERRID.ERR_UndefinedType1, "UnknownType").WithArguments("UnknownType"),
Diagnostic(ERRID.ERR_NameNotDeclared1, "unknownValue").WithArguments("unknownValue"),
Diagnostic(ERRID.ERR_NameNotDeclared1, "unknownValue").WithArguments("unknownValue"),
Diagnostic(ERRID.ERR_UndefinedType1, "UnknownType").WithArguments("UnknownType"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"),
Diagnostic(ERRID.WRN_InterfaceConversion2, "_collection").WithArguments("_Collection", "Microsoft.VisualBasic.Collection"),
Diagnostic(ERRID.WRN_InterfaceConversion2, "collection").WithArguments("Microsoft.VisualBasic.Collection", "_Collection"),
Diagnostic(ERRID.ERR_TypeMismatch2, "Int64.MaxValue").WithArguments("Long", "Integer"),
Diagnostic(ERRID.ERR_TypeMismatch2, "System.Double.MaxValue").WithArguments("Double", "Decimal"),
Diagnostic(ERRID.ERR_TypeMismatch2, "Da").WithArguments("Date", "Integer"),
Diagnostic(ERRID.ERR_TypeMismatch2, "[In]").WithArguments("Integer", "Date"),
Diagnostic(ERRID.ERR_DateToDoubleConversion, "Da"),
Diagnostic(ERRID.ERR_DoubleToDateConversion, "[Do]"),
Diagnostic(ERRID.ERR_CharToIntegralTypeMismatch1, "Ch").WithArguments("Integer"),
Diagnostic(ERRID.ERR_IntegralToCharTypeMismatch1, "[In]").WithArguments("Integer"),
Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "Object()", "Integer"),
Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "System.ValueType()", "Integer"),
Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "TC1Array").WithArguments("TestClass1()", "TestClass2()", "TestClass1", "TestClass2"),
Diagnostic(ERRID.ERR_ConvertArrayRankMismatch2, "InArray").WithArguments("Integer()", "Integer(*,*)"),
Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "InArray").WithArguments("Integer()", "TestInterface1()", "Integer", "TestInterface1"),
Diagnostic(ERRID.ERR_TypeMismatch2, "St").WithArguments("String", "Char"),
Diagnostic(ERRID.ERR_TypeMismatch2, "Ch").WithArguments("Char", "String"),
Diagnostic(ERRID.ERR_TypeMismatch2, "ChArray").WithArguments("Char()", "String"),
Diagnostic(ERRID.ERR_TypeMismatch2, "St").WithArguments("String", "Char()"),
Diagnostic(ERRID.WRN_ObsoleteIdentityDirectCastForValueType, "[In]"),
Diagnostic(ERRID.ERR_IdentityDirectCastForFloat, "Si"),
Diagnostic(ERRID.ERR_IdentityDirectCastForFloat, "[Do]"),
Diagnostic(ERRID.ERR_TypeMismatch2, "Si").WithArguments("Single", "Double"))
compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.Off))
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_VoidValue, "Console.WriteLine()"),
Diagnostic(ERRID.ERR_UndefinedType1, "UnknownType").WithArguments("UnknownType"),
Diagnostic(ERRID.ERR_NameNotDeclared1, "unknownValue").WithArguments("unknownValue"),
Diagnostic(ERRID.ERR_NameNotDeclared1, "unknownValue").WithArguments("unknownValue"),
Diagnostic(ERRID.ERR_UndefinedType1, "UnknownType").WithArguments("UnknownType"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"),
Diagnostic(ERRID.WRN_InterfaceConversion2, "_collection").WithArguments("_Collection", "Microsoft.VisualBasic.Collection"),
Diagnostic(ERRID.WRN_InterfaceConversion2, "collection").WithArguments("Microsoft.VisualBasic.Collection", "_Collection"),
Diagnostic(ERRID.ERR_TypeMismatch2, "Int64.MaxValue").WithArguments("Long", "Integer"),
Diagnostic(ERRID.ERR_TypeMismatch2, "System.Double.MaxValue").WithArguments("Double", "Decimal"),
Diagnostic(ERRID.ERR_TypeMismatch2, "Da").WithArguments("Date", "Integer"),
Diagnostic(ERRID.ERR_TypeMismatch2, "[In]").WithArguments("Integer", "Date"),
Diagnostic(ERRID.ERR_DateToDoubleConversion, "Da"),
Diagnostic(ERRID.ERR_DoubleToDateConversion, "[Do]"),
Diagnostic(ERRID.ERR_CharToIntegralTypeMismatch1, "Ch").WithArguments("Integer"),
Diagnostic(ERRID.ERR_IntegralToCharTypeMismatch1, "[In]").WithArguments("Integer"),
Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "Object()", "Integer"),
Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "System.ValueType()", "Integer"),
Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "TC1Array").WithArguments("TestClass1()", "TestClass2()", "TestClass1", "TestClass2"),
Diagnostic(ERRID.ERR_ConvertArrayRankMismatch2, "InArray").WithArguments("Integer()", "Integer(*,*)"),
Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "InArray").WithArguments("Integer()", "TestInterface1()", "Integer", "TestInterface1"),
Diagnostic(ERRID.ERR_TypeMismatch2, "St").WithArguments("String", "Char"),
Diagnostic(ERRID.ERR_TypeMismatch2, "Ch").WithArguments("Char", "String"),
Diagnostic(ERRID.ERR_TypeMismatch2, "ChArray").WithArguments("Char()", "String"),
Diagnostic(ERRID.ERR_TypeMismatch2, "St").WithArguments("String", "Char()"),
Diagnostic(ERRID.WRN_ObsoleteIdentityDirectCastForValueType, "[In]"),
Diagnostic(ERRID.ERR_IdentityDirectCastForFloat, "Si"),
Diagnostic(ERRID.ERR_IdentityDirectCastForFloat, "[Do]"),
Diagnostic(ERRID.ERR_TypeMismatch2, "Si").WithArguments("Single", "Double"))
End Sub
<Fact()>
Public Sub TryCastDiagnostic1()
Dim compilationDef =
<compilation name="TryCastDiagnostic1">
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Dim [In] As Integer
[In] = TryCast(Console.WriteLine(), Integer)
[In] = TryCast(1, UnknownType)
[In] = TryCast(unknownValue, Integer)
[In] = TryCast(unknownValue, UnknownType)
Dim tr As System.TypedReference = Nothing
Dim ai As System.ArgIterator = Nothing
Dim ra As System.RuntimeArgumentHandle = Nothing
Dim Ob As Object
Ob = TryCast(tr, Object)
Ob = TryCast(ai, Object)
Ob = TryCast(ra, Object)
Dim vt As ValueType
vt = TryCast(tr, ValueType)
vt = TryCast(ai, ValueType)
vt = TryCast(ra, ValueType)
Dim collection As Microsoft.VisualBasic.Collection = Nothing
Dim _collection As _Collection = Nothing
collection = TryCast(_collection, Microsoft.VisualBasic.Collection)
_collection = TryCast(collection, _Collection)
Dim De As Decimal
[In] = TryCast(Int64.MaxValue, Int32)
De = TryCast(System.Double.MaxValue, System.Decimal)
Dim Ch As Char = Nothing
Dim InArray As Integer() = Nothing
Dim ObArray As Object() = Nothing
Dim VtArray As ValueType() = Nothing
ObArray = TryCast(InArray, Object())
VtArray = TryCast(InArray, ValueType())
Dim TC1Array As TestClass1() = Nothing
Dim TC2Array As TestClass2() = Nothing
TC2Array = TryCast(TC1Array, TestClass2())
Dim InArray2 As Integer(,) = Nothing
InArray2 = TryCast(InArray, Integer(,))
Dim TI1Array As TestInterface1() = Nothing
TI1Array = TryCast(InArray, TestInterface1())
Dim St As String = Nothing
Dim ChArray As Char() = Nothing
Ch = TryCast(St, System.Char)
St = TryCast(Ch, System.String)
St = TryCast(ChArray, System.String)
ChArray = TryCast(St, System.Char())
End Sub
End Module
Interface TestInterface1
End Interface
Interface _Collection
End Interface
Class TestClass1
End Class
Class TestClass2
End Class
Class TestClass3(Of T)
Sub Test(val As Object)
Dim x As T = TryCast(val, T)
End Sub
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.On))
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_VoidValue, "Console.WriteLine()"),
Diagnostic(ERRID.ERR_UndefinedType1, "UnknownType").WithArguments("UnknownType"),
Diagnostic(ERRID.ERR_NameNotDeclared1, "unknownValue").WithArguments("unknownValue"),
Diagnostic(ERRID.ERR_NameNotDeclared1, "unknownValue").WithArguments("unknownValue"),
Diagnostic(ERRID.ERR_UndefinedType1, "UnknownType").WithArguments("UnknownType"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"),
Diagnostic(ERRID.WRN_InterfaceConversion2, "_collection").WithArguments("_Collection", "Microsoft.VisualBasic.Collection"),
Diagnostic(ERRID.WRN_InterfaceConversion2, "collection").WithArguments("Microsoft.VisualBasic.Collection", "_Collection"),
Diagnostic(ERRID.ERR_TryCastOfValueType1, "Int32").WithArguments("Integer"),
Diagnostic(ERRID.ERR_TryCastOfValueType1, "System.Decimal").WithArguments("Decimal"),
Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "Object()", "Integer"),
Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "System.ValueType()", "Integer"),
Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "TC1Array").WithArguments("TestClass1()", "TestClass2()", "TestClass1", "TestClass2"),
Diagnostic(ERRID.ERR_ConvertArrayRankMismatch2, "InArray").WithArguments("Integer()", "Integer(*,*)"),
Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "InArray").WithArguments("Integer()", "TestInterface1()", "Integer", "TestInterface1"),
Diagnostic(ERRID.ERR_TryCastOfValueType1, "System.Char").WithArguments("Char"),
Diagnostic(ERRID.ERR_TypeMismatch2, "Ch").WithArguments("Char", "String"),
Diagnostic(ERRID.ERR_TypeMismatch2, "ChArray").WithArguments("Char()", "String"),
Diagnostic(ERRID.ERR_TypeMismatch2, "St").WithArguments("String", "Char()"),
Diagnostic(ERRID.ERR_TryCastOfUnconstrainedTypeParam1, "T").WithArguments("T"))
compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.Off))
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_VoidValue, "Console.WriteLine()"),
Diagnostic(ERRID.ERR_UndefinedType1, "UnknownType").WithArguments("UnknownType"),
Diagnostic(ERRID.ERR_NameNotDeclared1, "unknownValue").WithArguments("unknownValue"),
Diagnostic(ERRID.ERR_NameNotDeclared1, "unknownValue").WithArguments("unknownValue"),
Diagnostic(ERRID.ERR_UndefinedType1, "UnknownType").WithArguments("UnknownType"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"),
Diagnostic(ERRID.WRN_InterfaceConversion2, "_collection").WithArguments("_Collection", "Microsoft.VisualBasic.Collection"),
Diagnostic(ERRID.WRN_InterfaceConversion2, "collection").WithArguments("Microsoft.VisualBasic.Collection", "_Collection"),
Diagnostic(ERRID.ERR_TryCastOfValueType1, "Int32").WithArguments("Integer"),
Diagnostic(ERRID.ERR_TryCastOfValueType1, "System.Decimal").WithArguments("Decimal"),
Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "Object()", "Integer"),
Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "System.ValueType()", "Integer"),
Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "TC1Array").WithArguments("TestClass1()", "TestClass2()", "TestClass1", "TestClass2"),
Diagnostic(ERRID.ERR_ConvertArrayRankMismatch2, "InArray").WithArguments("Integer()", "Integer(*,*)"),
Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "InArray").WithArguments("Integer()", "TestInterface1()", "Integer", "TestInterface1"),
Diagnostic(ERRID.ERR_TryCastOfValueType1, "System.Char").WithArguments("Char"),
Diagnostic(ERRID.ERR_TypeMismatch2, "Ch").WithArguments("Char", "String"),
Diagnostic(ERRID.ERR_TypeMismatch2, "ChArray").WithArguments("Char()", "String"),
Diagnostic(ERRID.ERR_TypeMismatch2, "St").WithArguments("String", "Char()"),
Diagnostic(ERRID.ERR_TryCastOfUnconstrainedTypeParam1, "T").WithArguments("T"))
End Sub
<Fact()>
Public Sub ExplicitConversions1()
' the argument past to CDate("") is following system setting,
' so "1/2/2012" could be Jan 2nd OR Feb 1st
Dim currCulture = System.Threading.Thread.CurrentThread.CurrentCulture
System.Threading.Thread.CurrentThread.CurrentCulture = New System.Globalization.CultureInfo("en-US")
Try
Dim compilationDef =
<compilation name="VBExplicitConversions1">
<file name="lib.vb">
<%= My.Resources.Resource.PrintResultTestSource %>
</file>
<file name="a.vb">
Option Strict Off
Imports System
Imports System.Collections.Generic
Module Module1
Sub Main()
PrintResult(CObj(Nothing))
PrintResult(CBool(Nothing))
PrintResult(CByte(Nothing))
'PrintResult(CChar(Nothing))
PrintResult(CDate(Nothing))
PrintResult(CDec(Nothing))
PrintResult(CDbl(Nothing))
PrintResult(CInt(Nothing))
PrintResult(CLng(Nothing))
PrintResult(CSByte(Nothing))
PrintResult(CShort(Nothing))
PrintResult(CSng(Nothing))
PrintResult(CStr(Nothing))
PrintResult(CUInt(Nothing))
PrintResult(CULng(Nothing))
PrintResult(CUShort(Nothing))
PrintResult(CType(Nothing, System.Object))
PrintResult(CType(Nothing, System.Boolean))
PrintResult(CType(Nothing, System.Byte))
'PrintResult(CType(Nothing, System.Char))
PrintResult(CType(Nothing, System.DateTime))
PrintResult(CType(Nothing, System.Decimal))
PrintResult(CType(Nothing, System.Double))
PrintResult(CType(Nothing, System.Int32))
PrintResult(CType(Nothing, System.Int64))
PrintResult(CType(Nothing, System.SByte))
PrintResult(CType(Nothing, System.Int16))
PrintResult(CType(Nothing, System.Single))
PrintResult(CType(Nothing, System.String))
PrintResult(CType(Nothing, System.UInt32))
PrintResult(CType(Nothing, System.UInt64))
PrintResult(CType(Nothing, System.UInt16))
PrintResult(CType(Nothing, System.Guid))
PrintResult(CType(Nothing, System.ValueType))
PrintResult(CByte(300))
PrintResult(CObj("String"))
PrintResult(CBool("False"))
PrintResult(CByte("1"))
PrintResult(CChar("a"))
PrintResult(CDate("11/12/2001 12:00:00 AM"))
PrintResult(CDec("-2"))
PrintResult(CDbl("3"))
PrintResult(CInt("-4"))
PrintResult(CLng("5"))
PrintResult(CSByte("-6"))
PrintResult(CShort("7"))
PrintResult(CSng("-8"))
PrintResult(CStr(9))
PrintResult(CUInt("10"))
PrintResult(CULng("11"))
PrintResult(CUShort("12"))
End Sub
Function Int32ToInt32(val As System.Int32) As Int32
Return CInt(val)
End Function
Function SingleToSingle(val As System.Single) As Single
Return CSng(val)
End Function
Function DoubleToDouble(val As System.Double) As Double
Return CDbl(val)
End Function
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
options:=TestOptions.ReleaseExe.WithOverflowChecks(False),
expectedOutput:=<![CDATA[
Object: []
Boolean: False
Byte: 0
Date: 1/1/0001 12:00:00 AM
Decimal: 0
Double: 0
Integer: 0
Long: 0
SByte: 0
Short: 0
Single: 0
String: []
UInteger: 0
ULong: 0
UShort: 0
Object: []
Boolean: False
Byte: 0
Date: 1/1/0001 12:00:00 AM
Decimal: 0
Double: 0
Integer: 0
Long: 0
SByte: 0
Short: 0
Single: 0
String: []
UInteger: 0
ULong: 0
UShort: 0
Guid: 00000000-0000-0000-0000-000000000000
ValueType: []
Byte: 44
Object: [String]
Boolean: False
Byte: 1
Char: [a]
Date: 11/12/2001 12:00:00 AM
Decimal: -2
Double: 3
Integer: -4
Long: 5
SByte: -6
Short: 7
Single: -8
String: [9]
UInteger: 10
ULong: 11
UShort: 12
]]>).
VerifyIL("Module1.Int32ToInt32",
<![CDATA[
{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ret
}
]]>).
VerifyIL("Module1.SingleToSingle",
<![CDATA[
{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ret
}
]]>).
VerifyIL("Module1.DoubleToDouble",
<![CDATA[
{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ret
}
]]>)
Catch ex As Exception
Finally
System.Threading.Thread.CurrentThread.CurrentCulture = currCulture
End Try
End Sub
<Fact()>
Public Sub DirectCast1()
Dim compilationDef =
<compilation name="DirectCast1">
<file name="helper.vb"><%= My.Resources.Resource.PrintResultTestSource %></file>
<file name="a.vb">
Option Strict Off
Imports System
Imports System.Globalization
Imports System.Collections.Generic
Module Module1
Sub Main()
PrintResult(DirectCast(Nothing, System.Object))
PrintResult(DirectCast(Nothing, System.Boolean))
PrintResult(DirectCast(Nothing, System.Byte))
PrintResult(DirectCast(Nothing, System.DateTime))
PrintResult(DirectCast(Nothing, System.Decimal))
PrintResult(DirectCast(Nothing, System.Double))
PrintResult(DirectCast(Nothing, System.Int32))
PrintResult(DirectCast(Nothing, System.Int64))
PrintResult(DirectCast(Nothing, System.SByte))
PrintResult(DirectCast(Nothing, System.Int16))
PrintResult(DirectCast(Nothing, System.Single))
PrintResult(DirectCast(Nothing, System.String))
PrintResult(DirectCast(Nothing, System.UInt32))
PrintResult(DirectCast(Nothing, System.UInt64))
PrintResult(DirectCast(Nothing, System.UInt16))
PrintResult(DirectCast(Nothing, System.ValueType))
PrintResult(DirectCast(1, System.Object))
PrintResult(DirectCast(3.5R, System.ValueType))
Dim guid As Guid = New Guid("8c5dffd5-1778-4dd3-a9f5-6a9708146a7c")
Dim guidObject As Object = guid
PrintResult(DirectCast(guid, System.Object))
PrintResult(DirectCast(guidObject, System.Guid))
PrintResult(DirectCast("abc", System.IComparable))
PrintResult(GenericParamTestHelperOfString.NothingToT())
'PrintResult(DirectCast(Nothing, System.Guid))
PrintResult(GenericParamTestHelperOfGuid.NothingToT())
PrintResult(GenericParamTestHelperOfString.TToObject("abcd"))
PrintResult(GenericParamTestHelperOfString.TToObject(Nothing))
PrintResult(GenericParamTestHelperOfGuid.TToObject(guid))
PrintResult(GenericParamTestHelperOfString.TToIComparable("abcde"))
PrintResult(GenericParamTestHelperOfString.TToIComparable(Nothing))
PrintResult(GenericParamTestHelperOfGuid.TToIComparable(guid))
PrintResult(GenericParamTestHelperOfGuid.ObjectToT(guidObject))
'PrintResult(GenericParamTestHelperOfGuid.ObjectToT(Nothing))
PrintResult(GenericParamTestHelperOfString.ObjectToT("ObString"))
PrintResult(GenericParamTestHelperOfString.ObjectToT(Nothing))
'PrintResult(GenericParamTestHelper(Of System.Int32).ObjectToT(Nothing))
PrintResult(GenericParamTestHelperOfString.IComparableToT("abcde"))
PrintResult(GenericParamTestHelperOfString.IComparableToT(Nothing))
PrintResult(GenericParamTestHelperOfGuid.IComparableToT(guid))
'PrintResult(GenericParamTestHelperOfGuid.IComparableToT(Nothing))
'PrintResult(GenericParamTestHelper(Of System.Double).IComparableToT(Nothing))
Dim [In] As Integer = 23
Dim De As Decimal = 24
PrintResult(DirectCast([In], System.Int32))
PrintResult(DirectCast(De, System.Decimal))
End Sub
Function NothingToGuid() As Guid
Return DirectCast(Nothing, System.Guid)
End Function
Function NothingToInt32() As Int32
Return DirectCast(Nothing, System.Int32)
End Function
Function Int32ToInt32(val As System.Int32) As Int32
Return DirectCast(val, System.Int32)
End Function
Class GenericParamTestHelper(Of T)
Public Shared Function ObjectToT(val As Object) As T
Return DirectCast(val, T)
End Function
Public Shared Function TToObject(val As T) As Object
Return DirectCast(val, Object)
End Function
Public Shared Function TToIComparable(val As T) As IComparable
Return DirectCast(val, IComparable)
End Function
Public Shared Function IComparableToT(val As IComparable) As T
Return DirectCast(val, T)
End Function
Public Shared Function NothingToT() As T
Return DirectCast(Nothing, T)
End Function
End Class
Class GenericParamTestHelperOfString
Inherits GenericParamTestHelper(Of String)
End Class
Class GenericParamTestHelperOfGuid
Inherits GenericParamTestHelper(Of Guid)
End Class
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=<![CDATA[
Object: []
Boolean: False
Byte: 0
Date: 1/1/0001 12:00:00 AM
Decimal: 0
Double: 0
Integer: 0
Long: 0
SByte: 0
Short: 0
Single: 0
String: []
UInteger: 0
ULong: 0
UShort: 0
ValueType: []
Object: [1]
ValueType: [3.5]
Object: [8c5dffd5-1778-4dd3-a9f5-6a9708146a7c]
Guid: 8c5dffd5-1778-4dd3-a9f5-6a9708146a7c
IComparable: [abc]
String: []
Guid: 00000000-0000-0000-0000-000000000000
Object: [abcd]
Object: []
Object: [8c5dffd5-1778-4dd3-a9f5-6a9708146a7c]
IComparable: [abcde]
IComparable: []
IComparable: [8c5dffd5-1778-4dd3-a9f5-6a9708146a7c]
Guid: 8c5dffd5-1778-4dd3-a9f5-6a9708146a7c
String: [ObString]
String: []
String: [abcde]
String: []
Guid: 8c5dffd5-1778-4dd3-a9f5-6a9708146a7c
Integer: 23
Decimal: 24
]]>).
VerifyIL("Module1.NothingToGuid",
<![CDATA[
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldnull
IL_0001: unbox.any "System.Guid"
IL_0006: ret
}
]]>).
VerifyIL("Module1.NothingToInt32",
<![CDATA[
{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: ret
}
]]>).
VerifyIL("Module1.Int32ToInt32",
<![CDATA[
{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ret
}
]]>).
VerifyIL("Module1.GenericParamTestHelper(Of T).ObjectToT",
<![CDATA[
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: unbox.any "T"
IL_0006: ret
}
]]>).
VerifyIL("Module1.GenericParamTestHelper(Of T).TToObject",
<![CDATA[
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: box "T"
IL_0006: ret
}
]]>).
VerifyIL("Module1.GenericParamTestHelper(Of T).TToIComparable",
<![CDATA[
{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldarg.0
IL_0001: box "T"
IL_0006: castclass "System.IComparable"
IL_000b: ret
}
]]>).
VerifyIL("Module1.GenericParamTestHelper(Of T).IComparableToT",
<![CDATA[
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: unbox.any "T"
IL_0006: ret
}
]]>).
VerifyIL("Module1.GenericParamTestHelper(Of T).NothingToT",
<![CDATA[
{
// Code size 10 (0xa)
.maxstack 1
.locals init (T V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj "T"
IL_0008: ldloc.0
IL_0009: ret
}
]]>)
End Sub
<Fact()>
Public Sub TryCast1()
Dim compilationDef =
<compilation name="TryCast1">
<file name="helper.vb"><%= My.Resources.Resource.PrintResultTestSource %></file>
<file name="a.vb">
Option Strict Off
Imports System
Imports System.Globalization
Imports System.Collections.Generic
Module Module1
Sub Main()
PrintResult(TryCast(Nothing, System.Object))
PrintResult(TryCast(Nothing, System.String))
PrintResult(TryCast(Nothing, System.ValueType))
PrintResult(TryCast(1, System.Object))
PrintResult(TryCast(3.5R, System.ValueType))
PrintResult(TryCast(CObj("sdf"), System.String))
PrintResult(TryCast(New Object(), System.String))
Dim guid As Guid = New Guid("8c5dffd5-1778-4dd3-a9f5-6a9708146a7c")
Dim guidObject As Object = guid
PrintResult(TryCast(guid, System.Object))
PrintResult(TryCast("abc", System.IComparable))
PrintResult(TryCast(guid, System.IComparable))
PrintResult(GenericParamTestHelperOfString2.NothingToT())
PrintResult(GenericParamTestHelperOfString1.TToObject("abcd"))
PrintResult(GenericParamTestHelperOfString1.TToObject(Nothing))
PrintResult(GenericParamTestHelperOfGuid1.TToObject(guid))
PrintResult(GenericParamTestHelperOfString1.TToIComparable("abcde"))
PrintResult(GenericParamTestHelperOfString1.TToIComparable(Nothing))
PrintResult(GenericParamTestHelperOfGuid1.TToIComparable(guid))
PrintResult(GenericParamTestHelperOfString2.ObjectToT("ObString"))
PrintResult(GenericParamTestHelperOfString2.ObjectToT(Nothing))
PrintResult(GenericParamTestHelperOfString2.IComparableToT("abcde"))
PrintResult(GenericParamTestHelperOfString2.IComparableToT(Nothing))
End Sub
Function NothingToString() As String
Return DirectCast(Nothing, System.String)
End Function
Function StringToString(val As String) As String
Return DirectCast(val, System.String)
End Function
Class GenericParamTestHelper1(Of T)
Public Shared Function TToObject(val As T) As Object
Return TryCast(val, Object)
End Function
Public Shared Function TToIComparable(val As T) As IComparable
Return TryCast(val, IComparable)
End Function
End Class
Class GenericParamTestHelper2(Of T As Class)
Public Shared Function ObjectToT(val As Object) As T
Return TryCast(val, T)
End Function
Public Shared Function IComparableToT(val As IComparable) As T
Return TryCast(val, T)
End Function
Public Shared Function NothingToT() As T
Return TryCast(Nothing, T)
End Function
End Class
Class GenericParamTestHelperOfString1
Inherits GenericParamTestHelper1(Of String)
End Class
Class GenericParamTestHelperOfString2
Inherits GenericParamTestHelper2(Of String)
End Class
Class GenericParamTestHelperOfGuid1
Inherits GenericParamTestHelper1(Of Guid)
End Class
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=<![CDATA[
Object: []
String: []
ValueType: []
Object: [1]
ValueType: [3.5]
String: [sdf]
String: []
Object: [8c5dffd5-1778-4dd3-a9f5-6a9708146a7c]
IComparable: [abc]
IComparable: [8c5dffd5-1778-4dd3-a9f5-6a9708146a7c]
String: []
Object: [abcd]
Object: []
Object: [8c5dffd5-1778-4dd3-a9f5-6a9708146a7c]
IComparable: [abcde]
IComparable: []
IComparable: [8c5dffd5-1778-4dd3-a9f5-6a9708146a7c]
String: [ObString]
String: []
String: [abcde]
String: []
]]>).
VerifyIL("Module1.NothingToString",
<![CDATA[
{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldnull
IL_0001: ret
}
]]>).
VerifyIL("Module1.StringToString",
<![CDATA[
{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ret
}
]]>).
VerifyIL("Module1.GenericParamTestHelper2(Of T).ObjectToT",
<![CDATA[
{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldarg.0
IL_0001: isinst "T"
IL_0006: unbox.any "T"
IL_000b: ret
}
]]>).
VerifyIL("Module1.GenericParamTestHelper1(Of T).TToObject",
<![CDATA[
{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldarg.0
IL_0001: box "T"
IL_0006: isinst "Object"
IL_000b: ret
}
]]>).
VerifyIL("Module1.GenericParamTestHelper1(Of T).TToIComparable",
<![CDATA[
{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldarg.0
IL_0001: box "T"
IL_0006: isinst "System.IComparable"
IL_000b: ret
}
]]>).
VerifyIL("Module1.GenericParamTestHelper2(Of T).IComparableToT",
<![CDATA[
{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldarg.0
IL_0001: isinst "T"
IL_0006: unbox.any "T"
IL_000b: ret
}
]]>).
VerifyIL("Module1.GenericParamTestHelper2(Of T).NothingToT",
<![CDATA[
{
// Code size 10 (0xa)
.maxstack 1
.locals init (T V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj "T"
IL_0008: ldloc.0
IL_0009: ret
}
]]>)
End Sub
<Fact()>
Public Sub Bug4281_1()
Dim compilationDef =
<compilation name="Bug4281_1">
<file name="a.vb">
Imports System
Module M
Sub Main()
Dim x As Object= DirectCast(1, DayOfWeek)
System.Console.WriteLine(x.GetType())
System.Console.WriteLine(x)
Dim y As Integer = 2
x = DirectCast(y, DayOfWeek)
System.Console.WriteLine(x.GetType())
System.Console.WriteLine(x)
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=<![CDATA[
System.DayOfWeek
Monday
System.DayOfWeek
Tuesday
]]>).
VerifyIL("M.Main",
<![CDATA[
{
// Code size 55 (0x37)
.maxstack 2
IL_0000: ldc.i4.1
IL_0001: box "System.DayOfWeek"
IL_0006: dup
IL_0007: callvirt "Function Object.GetType() As System.Type"
IL_000c: call "Sub System.Console.WriteLine(Object)"
IL_0011: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_0016: call "Sub System.Console.WriteLine(Object)"
IL_001b: ldc.i4.2
IL_001c: box "System.DayOfWeek"
IL_0021: dup
IL_0022: callvirt "Function Object.GetType() As System.Type"
IL_0027: call "Sub System.Console.WriteLine(Object)"
IL_002c: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_0031: call "Sub System.Console.WriteLine(Object)"
IL_0036: ret
}
]]>)
End Sub
<Fact()>
Public Sub Bug4281_2()
Dim compilationDef =
<compilation name="Bug4281_2">
<file name="a.vb">
Imports System
Module M
Sub Main()
Dim x As DayOfWeek= DirectCast(1, DayOfWeek)
System.Console.WriteLine(x.GetType())
System.Console.WriteLine(x)
Dim y As Integer = 2
x = DirectCast(y, DayOfWeek)
System.Console.WriteLine(x.GetType())
System.Console.WriteLine(x)
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=<![CDATA[
System.DayOfWeek
1
System.DayOfWeek
2
]]>)
End Sub
<Fact()>
Public Sub Bug4256()
Dim compilationDef =
<compilation name="Bug4256">
<file name="a.vb">
Option Strict On
Module M
Sub Main()
Dim x As Object = 1
Dim y As Long = CLng(x)
System.Console.WriteLine(y.GetType())
System.Console.WriteLine(y)
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=<![CDATA[
System.Int64
1
]]>)
End Sub
<WorkItem(11515, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub TestIdentityConversionForGenericNested()
Dim vbCompilation = CreateVisualBasicCompilation("TestIdentityConversionForGenericNested",
<![CDATA[Option Strict On
Imports System
Public Module Program
Class C1(Of T)
Public EnumField As E1
Structure S1
Public EnumField As E1
End Structure
Enum E1
A
End Enum
End Class
Sub Main()
Dim outer As New C1(Of Integer)
Dim inner As New C1(Of Integer).S1
outer.EnumField = C1(Of Integer).E1.A
inner.EnumField = C1(Of Integer).E1.A
Foo(inner.EnumField)
End Sub
Sub Foo(x As Object)
Console.WriteLine(x.ToString)
End Sub
End Module]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication))
CompileAndVerify(vbCompilation, expectedOutput:="A").VerifyDiagnostics()
End Sub
<WorkItem(544919, "DevDiv")>
<Fact>
Public Sub TestClassifyConversion()
Dim source =
<text>
Imports System
Module Program
Sub M()
End Sub
Sub M(l As Long)
End Sub
Sub M(s As Short)
End Sub
Sub M(i As Integer)
End Sub
Sub Main()
Dim ii As Integer = 0
Console.WriteLine(ii)
Dim jj As Short = 1
Console.WriteLine(jj)
Dim ss As String = String.Empty
Console.WriteLine(ss)
' Perform conversion classification here.
End Sub
End Module
</text>.Value
Dim tree = Parse(source)
Dim c As VisualBasicCompilation = VisualBasicCompilation.Create("MyCompilation").AddReferences(MscorlibRef).AddSyntaxTrees(tree)
Dim model = c.GetSemanticModel(tree)
' Get VariableDeclaratorSyntax corresponding to variable 'ii' above.
Dim variableDeclarator = CType(tree.GetCompilationUnitRoot().FindToken(source.IndexOf("ii", StringComparison.Ordinal)).Parent.Parent, VariableDeclaratorSyntax)
' Get TypeSymbol corresponding to above VariableDeclaratorSyntax.
Dim targetType As TypeSymbol = CType(model.GetDeclaredSymbol(variableDeclarator.Names.Single), LocalSymbol).Type
Dim local As LocalSymbol = CType(model.GetDeclaredSymbol(variableDeclarator.Names.Single), LocalSymbol)
Assert.Equal(1, local.Locations.Length)
' Perform ClassifyConversion for expressions from within the above SyntaxTree.
Dim sourceExpression1 = CType(tree.GetCompilationUnitRoot().FindToken(source.IndexOf("jj)", StringComparison.Ordinal)).Parent, ExpressionSyntax)
Dim conversion As Conversion = model.ClassifyConversion(sourceExpression1, targetType)
Assert.True(conversion.IsWidening)
Assert.True(conversion.IsNumeric)
Dim sourceExpression2 = CType(tree.GetCompilationUnitRoot().FindToken(source.IndexOf("ss)", StringComparison.Ordinal)).Parent, ExpressionSyntax)
conversion = model.ClassifyConversion(sourceExpression2, targetType)
Assert.True(conversion.IsNarrowing)
Assert.True(conversion.IsString)
' Perform ClassifyConversion for constructed expressions
' at the position identified by the comment "' Perform ..." above.
Dim sourceExpression3 As ExpressionSyntax = SyntaxFactory.IdentifierName("jj")
Dim position = source.IndexOf("' ", StringComparison.Ordinal)
conversion = model.ClassifyConversion(position, sourceExpression3, targetType)
Assert.True(conversion.IsWidening)
Assert.True(conversion.IsNumeric)
Dim sourceExpression4 As ExpressionSyntax = SyntaxFactory.IdentifierName("ss")
conversion = model.ClassifyConversion(position, sourceExpression4, targetType)
Assert.True(conversion.IsNarrowing)
Assert.True(conversion.IsString)
Dim sourceExpression5 As ExpressionSyntax = SyntaxFactory.ParseExpression("100L")
conversion = model.ClassifyConversion(position, sourceExpression5, targetType)
' This is Widening because the numeric literal constant 100L can be converted to Integer
' without any data loss. Note: This is special for literal constants.
Assert.True(conversion.IsWidening)
Assert.True(conversion.IsNumeric)
End Sub
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<WorkItem(544919, "DevDiv")>
<Fact>
Public Sub TestClassifyConversionStaticLocal()
Dim source =
<text>
Imports System
Module Program
Sub M()
End Sub
Sub M(l As Long)
End Sub
Sub M(s As Short)
End Sub
Sub M(i As Integer)
End Sub
Sub Main()
Static ii As Integer = 0
Console.WriteLine(ii)
Static jj As Short = 1
Console.WriteLine(jj)
Static ss As String = String.Empty
Console.WriteLine(ss)
' Perform conversion classification here.
End Sub
End Module
</text>.Value
Dim tree = Parse(source)
Dim c As VisualBasicCompilation = VisualBasicCompilation.Create("MyCompilation").AddReferences(MscorlibRef).AddSyntaxTrees(tree)
Dim model = c.GetSemanticModel(tree)
' Get VariableDeclaratorSyntax corresponding to variable 'ii' above.
Dim variableDeclarator = CType(tree.GetCompilationUnitRoot().FindToken(source.IndexOf("ii", StringComparison.Ordinal)).Parent.Parent, VariableDeclaratorSyntax)
' Get TypeSymbol corresponding to above VariableDeclaratorSyntax.
Dim targetType As TypeSymbol = CType(model.GetDeclaredSymbol(variableDeclarator.Names.Single), LocalSymbol).Type
Dim local As LocalSymbol = CType(model.GetDeclaredSymbol(variableDeclarator.Names.Single), LocalSymbol)
Assert.Equal(1, local.Locations.Length)
' Perform ClassifyConversion for expressions from within the above SyntaxTree.
Dim sourceExpression1 = CType(tree.GetCompilationUnitRoot().FindToken(source.IndexOf("jj)", StringComparison.Ordinal)).Parent, ExpressionSyntax)
Dim conversion As Conversion = model.ClassifyConversion(sourceExpression1, targetType)
Assert.True(conversion.IsWidening)
Assert.True(conversion.IsNumeric)
Dim sourceExpression2 = CType(tree.GetCompilationUnitRoot().FindToken(source.IndexOf("ss)", StringComparison.Ordinal)).Parent, ExpressionSyntax)
conversion = model.ClassifyConversion(sourceExpression2, targetType)
Assert.True(conversion.IsNarrowing)
Assert.True(conversion.IsString)
' Perform ClassifyConversion for constructed expressions
' at the position identified by the comment "' Perform ..." above.
Dim sourceExpression3 As ExpressionSyntax = SyntaxFactory.IdentifierName("jj")
Dim position = source.IndexOf("' ", StringComparison.Ordinal)
conversion = model.ClassifyConversion(position, sourceExpression3, targetType)
Assert.True(conversion.IsWidening)
Assert.True(conversion.IsNumeric)
Dim sourceExpression4 As ExpressionSyntax = SyntaxFactory.IdentifierName("ss")
conversion = model.ClassifyConversion(position, sourceExpression4, targetType)
Assert.True(conversion.IsNarrowing)
Assert.True(conversion.IsString)
Dim sourceExpression5 As ExpressionSyntax = SyntaxFactory.ParseExpression("100L")
conversion = model.ClassifyConversion(position, sourceExpression5, targetType)
' This is Widening because the numeric literal constant 100L can be converted to Integer
' without any data loss. Note: This is special for literal constants.
Assert.True(conversion.IsWidening)
Assert.True(conversion.IsNumeric)
End Sub
<WorkItem(544620, "DevDiv")>
<Fact()>
Public Sub Bug13088()
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Module Program
Public Const Z1 As Integer = 300
Public Const Z2 As Byte = Z1
Public Const Z3 As Byte = CByte(300)
Public Const Z4 As Byte = DirectCast(300, Byte)
Sub Main()
End Sub
End Module
]]></file>
</compilation>)
VerifyDiagnostics(compilation, Diagnostic(ERRID.ERR_ExpressionOverflow1, "Z1").WithArguments("Byte"),
Diagnostic(ERRID.ERR_ExpressionOverflow1, "300").WithArguments("Byte"),
Diagnostic(ERRID.ERR_TypeMismatch2, "300").WithArguments("Integer", "Byte"))
Dim symbol = compilation.GlobalNamespace.GetTypeMembers("Program").Single.GetMembers("Z2").Single
Assert.False(DirectCast(symbol, FieldSymbol).HasConstantValue)
symbol = compilation.GlobalNamespace.GetTypeMembers("Program").Single.GetMembers("Z3").Single
Assert.False(DirectCast(symbol, FieldSymbol).HasConstantValue)
symbol = compilation.GlobalNamespace.GetTypeMembers("Program").Single.GetMembers("Z4").Single
Assert.False(DirectCast(symbol, FieldSymbol).HasConstantValue)
End Sub
<WorkItem(545760, "DevDiv")>
<Fact()>
Public Sub Bug14409()
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Module M1
Sub Main()
Dim x As System.DayOfWeek? = 0
Test(0)
End Sub
Sub Test(x As System.DayOfWeek?)
End Sub
End Module
]]></file>
</compilation>, TestOptions.ReleaseExe)
CompileAndVerify(compilation)
End Sub
<WorkItem(545760, "DevDiv")>
<Fact()>
Public Sub Bug14409_2()
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Module M1
Sub Main()
Test(0)
End Sub
Sub Test(x As System.DayOfWeek?)
End Sub
Sub Test(x As System.TypeCode?)
End Sub
End Module
]]></file>
</compilation>, TestOptions.ReleaseExe)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30519: Overload resolution failed because no accessible 'Test' can be called without a narrowing conversion:
'Public Sub Test(x As DayOfWeek?)': Argument matching parameter 'x' narrows from 'Integer' to 'DayOfWeek?'.
'Public Sub Test(x As TypeCode?)': Argument matching parameter 'x' narrows from 'Integer' to 'TypeCode?'.
Test(0)
~~~~
</expected>)
End Sub
<WorkItem(571095, "DevDiv")>
<Fact()>
Public Sub Bug571095()
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
imports System
Module Module1
Sub Main()
Dim Y(10, 10) As Integer
'COMPILEERROR: BC30311, "Y"
For Each x As string() In Y
Console.WriteLine(x)
Next x
'COMPILEERROR: BC30311, "Y"
For Each x As Integer(,) In Y
Console.WriteLine(x)
Next x
End Sub
End Module
]]></file>
</compilation>, TestOptions.ReleaseExe)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30311: Value of type 'Integer' cannot be converted to 'String()'.
For Each x As string() In Y
~
BC30311: Value of type 'Integer' cannot be converted to 'Integer(*,*)'.
For Each x As Integer(,) In Y
~
</expected>)
End Sub
<WorkItem(31)>
<Fact()>
Public Sub BugCodePlex_31()
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Module Module1
Property Value As BooleanEx?
Sub Main()
If Value Then
End If
System.Console.WriteLine("---")
Value = true
System.Console.WriteLine("---")
Dim x as Boolean? = Value
System.Console.WriteLine("---")
If Value Then
End If
End Sub
End Module
Structure BooleanEx
Private b As Boolean
Public Sub New(value As Boolean)
b = value
End Sub
Public Shared Widening Operator CType(value As Boolean) As BooleanEx
System.Console.WriteLine("CType(value As Boolean) As BooleanEx")
Return New BooleanEx(value)
End Operator
Public Shared Widening Operator CType(value As BooleanEx) As Boolean
System.Console.WriteLine("CType(value As BooleanEx) As Boolean")
Return value.b
End Operator
Public Shared Widening Operator CType(value As Integer) As BooleanEx
System.Console.WriteLine("CType(value As Integer) As BooleanEx")
Return New BooleanEx(CBool(value))
End Operator
Public Shared Widening Operator CType(value As BooleanEx) As Integer
System.Console.WriteLine("CType(value As BooleanEx) As Integer")
Return CInt(value.b)
End Operator
Public Shared Widening Operator CType(value As String) As BooleanEx
System.Console.WriteLine("CType(value As String) As BooleanEx")
Return New BooleanEx(CBool(value))
End Operator
Public Shared Widening Operator CType(value As BooleanEx) As String
System.Console.WriteLine("CType(value As BooleanEx) As String")
Return CStr(value.b)
End Operator
Public Shared Operator =(value1 As BooleanEx, value2 As Boolean) As Boolean
System.Console.WriteLine("=(value1 As BooleanEx, value2 As Boolean) As Boolean")
Return False
End Operator
Public Shared Operator <>(value1 As BooleanEx, value2 As Boolean) As Boolean
System.Console.WriteLine("<>(value1 As BooleanEx, value2 As Boolean) As Boolean")
Return False
End Operator
End Structure
]]></file>
</compilation>, TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput:=
"---
CType(value As Boolean) As BooleanEx
---
CType(value As BooleanEx) As Boolean
---
CType(value As BooleanEx) As Boolean")
End Sub
<WorkItem(1099862, "DevDiv")>
<Fact()>
Public Sub Bug1099862_01()
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Module Program
Sub Main(args As String())
Dim x As Integer = Double.MaxValue
End Sub
End Module
]]></file>
</compilation>)
Dim expectedErr = <expected>
BC30439: Constant expression not representable in type 'Integer'.
Dim x As Integer = Double.MaxValue
~~~~~~~~~~~~~~~
</expected>
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Off).WithOverflowChecks(False))
AssertTheseDiagnostics(compilation, expectedErr)
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Custom).WithOverflowChecks(False))
AssertTheseDiagnostics(compilation, expectedErr)
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.On).WithOverflowChecks(False))
AssertTheseDiagnostics(compilation, expectedErr)
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Off).WithOverflowChecks(True))
AssertTheseDiagnostics(compilation, expectedErr)
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Custom).WithOverflowChecks(True))
AssertTheseDiagnostics(compilation, expectedErr)
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.On).WithOverflowChecks(True))
AssertTheseDiagnostics(compilation, expectedErr)
End Sub
<WorkItem(1099862, "DevDiv")>
<Fact()>
Public Sub Bug1099862_02()
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Module Program
Sub Main(args As String())
Dim x As Integer? = Double.MaxValue
End Sub
End Module
]]></file>
</compilation>)
Dim expectedError = <expected>
BC30439: Constant expression not representable in type 'Integer?'.
Dim x As Integer? = Double.MaxValue
~~~~~~~~~~~~~~~
</expected>
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Off).WithOverflowChecks(False))
AssertTheseDiagnostics(compilation, expectedError)
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Custom).WithOverflowChecks(False))
AssertTheseDiagnostics(compilation, expectedError)
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.On).WithOverflowChecks(False))
AssertTheseDiagnostics(compilation, expectedError)
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Off).WithOverflowChecks(True))
AssertTheseDiagnostics(compilation, expectedError)
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Custom).WithOverflowChecks(True))
AssertTheseDiagnostics(compilation, expectedError)
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.On).WithOverflowChecks(True))
AssertTheseDiagnostics(compilation, expectedError)
End Sub
<WorkItem(1099862, "DevDiv")>
<Fact()>
Public Sub Bug1099862_03()
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Module Program
Sub Main(args As String())
Dim x As Short = Integer.MaxValue
System.Console.WriteLine(x)
End Sub
End Module
]]></file>
</compilation>)
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Off).WithOverflowChecks(False))
CompileAndVerify(compilation, expectedOutput:="-1").VerifyDiagnostics()
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Custom).WithOverflowChecks(False))
CompileAndVerify(compilation, expectedOutput:="-1").VerifyDiagnostics()
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.On).WithOverflowChecks(False))
CompileAndVerify(compilation, expectedOutput:="-1").VerifyDiagnostics()
Dim expectedError = <expected>
BC30439: Constant expression not representable in type 'Short'.
Dim x As Short = Integer.MaxValue
~~~~~~~~~~~~~~~~
</expected>
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Off).WithOverflowChecks(True))
AssertTheseDiagnostics(compilation, expectedError)
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Custom).WithOverflowChecks(True))
AssertTheseDiagnostics(compilation, expectedError)
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.On).WithOverflowChecks(True))
AssertTheseDiagnostics(compilation, expectedError)
End Sub
<WorkItem(1099862, "DevDiv")>
<Fact()>
Public Sub Bug1099862_04()
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Module Program
Sub Main(args As String())
Dim x As Short? = Integer.MaxValue
System.Console.WriteLine(x)
End Sub
End Module
]]></file>
</compilation>)
Dim expectedIL = <![CDATA[
{
// Code size 22 (0x16)
.maxstack 2
.locals init (Short? V_0) //x
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: ldc.i4.m1
IL_0004: call "Sub Short?..ctor(Short)"
IL_0009: ldloc.0
IL_000a: box "Short?"
IL_000f: call "Sub System.Console.WriteLine(Object)"
IL_0014: nop
IL_0015: ret
}
]]>
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Off).WithOverflowChecks(False))
Dim verifier = CompileAndVerify(compilation, expectedOutput:="-1").VerifyDiagnostics()
verifier.VerifyIL("Program.Main", expectedIL)
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Custom).WithOverflowChecks(False))
verifier = CompileAndVerify(compilation, expectedOutput:="-1").VerifyDiagnostics()
verifier.VerifyIL("Program.Main", expectedIL)
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.On).WithOverflowChecks(False))
verifier = CompileAndVerify(compilation, expectedOutput:="-1").VerifyDiagnostics()
verifier.VerifyIL("Program.Main", expectedIL)
Dim expectedError = <expected>
BC30439: Constant expression not representable in type 'Short?'.
Dim x As Short? = Integer.MaxValue
~~~~~~~~~~~~~~~~
</expected>
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Off).WithOverflowChecks(True))
AssertTheseDiagnostics(compilation, expectedError)
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Custom).WithOverflowChecks(True))
AssertTheseDiagnostics(compilation, expectedError)
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.On).WithOverflowChecks(True))
AssertTheseDiagnostics(compilation, expectedError)
End Sub
<WorkItem(1099862, "DevDiv")>
<Fact()>
Public Sub Bug1099862_05()
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Module Program
Sub Main(args As String())
Dim x As Short = CInt(Short.MaxValue)
System.Console.WriteLine(x)
End Sub
End Module
]]></file>
</compilation>)
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Off).WithOverflowChecks(False))
CompileAndVerify(compilation, expectedOutput:="32767").VerifyDiagnostics()
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Custom).WithOverflowChecks(False))
CompileAndVerify(compilation, expectedOutput:="32767").VerifyDiagnostics()
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.On).WithOverflowChecks(False))
CompileAndVerify(compilation, expectedOutput:="32767").VerifyDiagnostics()
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Off).WithOverflowChecks(True))
CompileAndVerify(compilation, expectedOutput:="32767").VerifyDiagnostics()
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Custom).WithOverflowChecks(True))
CompileAndVerify(compilation, expectedOutput:="32767").VerifyDiagnostics()
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.On).WithOverflowChecks(True))
CompileAndVerify(compilation, expectedOutput:="32767").VerifyDiagnostics()
End Sub
<WorkItem(1099862, "DevDiv")>
<Fact()>
Public Sub Bug1099862_06()
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Module Program
Sub Main(args As String())
Dim x As Short? = CInt(Short.MaxValue)
System.Console.WriteLine(x)
End Sub
End Module
]]></file>
</compilation>)
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Off).WithOverflowChecks(False))
CompileAndVerify(compilation, expectedOutput:="32767").VerifyDiagnostics()
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Custom).WithOverflowChecks(False))
CompileAndVerify(compilation, expectedOutput:="32767").VerifyDiagnostics()
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.On).WithOverflowChecks(False))
CompileAndVerify(compilation, expectedOutput:="32767").VerifyDiagnostics()
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Off).WithOverflowChecks(True))
CompileAndVerify(compilation, expectedOutput:="32767").VerifyDiagnostics()
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Custom).WithOverflowChecks(True))
CompileAndVerify(compilation, expectedOutput:="32767").VerifyDiagnostics()
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.On).WithOverflowChecks(True))
CompileAndVerify(compilation, expectedOutput:="32767").VerifyDiagnostics()
End Sub
<WorkItem(1099862, "DevDiv")>
<Fact()>
Public Sub Bug1099862_07()
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Module Program
Sub Main(args As String())
Dim x = CType(Double.MaxValue, System.Nullable(Of Integer))
End Sub
End Module
]]></file>
</compilation>)
Dim expectedError = <expected>
BC30439: Constant expression not representable in type 'Integer?'.
Dim x = CType(Double.MaxValue, System.Nullable(Of Integer))
~~~~~~~~~~~~~~~
</expected>
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Off).WithOverflowChecks(False))
AssertTheseDiagnostics(compilation, expectedError)
End Sub
End Class
End Namespace
|
ManishJayaswal/roslyn
|
src/Compilers/VisualBasic/Test/Semantic/Semantics/Conversions.vb
|
Visual Basic
|
apache-2.0
| 285,552
|
Imports BVSoftware.Bvc5.Core
Imports System.Collections.ObjectModel
Partial Class EmailFriend
Inherits BaseStorePage
Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
Me.MasterPageFile = PersonalizationServices.GetSafeMasterPage("Popup.master")
End Sub
Sub PageLoad(ByVal Sender As Object, ByVal E As EventArgs) Handles MyBase.Load
If Not Page.IsPostBack Then
btnSend.ImageUrl = PersonalizationServices.GetThemedButton("Submit")
inMessage.Text = "<a href=""" & Request.Params("page") & """>" & Request.Params("page") & "</a>"
If SessionManager.IsUserAuthenticated = True Then
Dim u As Membership.UserAccount = Membership.UserAccount.FindByBvin(SessionManager.GetCurrentUserId)
Me.FromEmailField.Text = u.Email
End If
Me.pnlMain.Visible = True
Me.pnlRegister.Visible = False
'Me.valEmail.Text = ImageHelper.GetErrorIconTag
'Me.valEmail2.Text = ImageHelper.GetErrorIconTag
'Me.Requiredfieldvalidator1.Text = ImageHelper.GetErrorIconTag
'Me.Regularexpressionvalidator1.Text = ImageHelper.GetErrorIconTag
End If
End Sub
Sub btnSend_OnClick(ByVal Sender As Object, ByVal E As ImageClickEventArgs) Handles btnSend.Click
lblErrorMessage.Visible = False
lblErrorMessage.Text = ""
lblResults.Text = ""
Dim f As String = String.Empty
Dim p As Catalog.Product
p = Catalog.InternalProduct.FindByBvin(Request.QueryString("productID"))
Dim t As Content.EmailTemplate
t = Content.EmailTemplate.FindByBvin(WebAppSettings.EmailTemplateID_EmailFriend)
If t IsNot Nothing Then
Dim m As System.Net.Mail.MailMessage
m = t.ConvertToMailMessage(Me.FromEmailField.Text.Trim, Me.toEmailField.Text.Trim, p)
If Utilities.MailServices.SendMail(m) = False Then
lblErrorMessage.Text = "Error while sending mail!"
lblErrorMessage.Visible = True
Else
lblResults.Text = "Thank you. Your message has been sent."
End If
End If
End Sub
End Class
|
ajaydex/Scopelist_2015
|
EmailFriend.aspx.vb
|
Visual Basic
|
apache-2.0
| 2,273
|
' Copyright 2015, Google Inc. All Rights Reserved.
'
' Licensed under the Apache License, Version 2.0 (the "License");
' you may not use this file except in compliance with the License.
' You may obtain a copy of the License at
'
' http://www.apache.org/licenses/LICENSE-2.0
'
' Unless required by applicable law or agreed to in writing, software
' distributed under the License is distributed on an "AS IS" BASIS,
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' See the License for the specific language governing permissions and
' limitations under the License.
' Author: api.anash@gmail.com (Anash P. Oommen)
Imports Google.Api.Ads.AdWords.Lib
Imports Google.Api.Ads.AdWords.Util.Reports
Imports Google.Api.Ads.AdWords.v201502
Imports Google.Api.Ads.Common.Util.Reports
Imports System
Imports System.Collections.Generic
Imports System.IO
Namespace Google.Api.Ads.AdWords.Examples.VB.v201502
''' <summary>
''' This code example gets and downloads a criteria Ad Hoc report from an XML
''' report definition.
''' </summary>
Public Class DownloadCriteriaReport
Inherits ExampleBase
''' <summary>
''' Main method, to run this code example as a standalone application.
''' </summary>
''' <param name="args">The command line arguments.</param>
Public Shared Sub Main(ByVal args As String())
Dim codeExample As New DownloadCriteriaReport
Console.WriteLine(codeExample.Description)
Try
Dim fileName As String = "INSERT_OUTPUT_FILE_NAME"
codeExample.Run(New AdWordsUser, fileName)
Catch ex As Exception
Console.WriteLine("An exception occurred while running this code example. {0}", _
ExampleUtilities.FormatException(ex))
End Try
End Sub
''' <summary>
''' Returns a description about the code example.
''' </summary>
Public Overrides ReadOnly Property Description() As String
Get
Return "This code example gets and downloads a criteria Ad Hoc report from an XML report" & _
" definition."
End Get
End Property
''' <summary>
''' Runs the code example.
''' </summary>
''' <param name="user">The AdWords user.</param>
''' <param name="fileName">The file to which the report is downloaded.
''' </param>
Public Sub Run(ByVal user As AdWordsUser, ByVal fileName As String)
Dim definition As New ReportDefinition
definition.reportName = "Last 7 days CRITERIA_PERFORMANCE_REPORT"
definition.reportType = ReportDefinitionReportType.CRITERIA_PERFORMANCE_REPORT
definition.downloadFormat = DownloadFormat.GZIPPED_CSV
definition.dateRangeType = ReportDefinitionDateRangeType.LAST_7_DAYS
' Create the selector.
Dim selector As New Selector
selector.fields = New String() {"CampaignId", "AdGroupId", "Id", "CriteriaType", "Criteria", _
"FinalUrls", "Clicks", "Impressions", "Cost"}
Dim predicate As New Predicate
predicate.field = "Status"
predicate.operator = PredicateOperator.IN
predicate.values = New String() {"ENABLED", "PAUSED"}
selector.predicates = New Predicate() {predicate}
definition.selector = selector
definition.includeZeroImpressions = True
Dim filePath As String = ExampleUtilities.GetHomeDir() & Path.DirectorySeparatorChar & _
fileName
Try
Dim utilities As New ReportUtilities(user, "v201502", definition)
Using reportResponse As ReportResponse = utilities.GetResponse()
reportResponse.Save(filePath)
End Using
Console.WriteLine("Report was downloaded to '{0}'.", filePath)
Catch ex As Exception
Throw New System.ApplicationException("Failed to download report.", ex)
End Try
End Sub
End Class
End Namespace
|
stevemanderson/googleads-dotnet-lib
|
examples/AdXBuyer/Vb/v201502/Reporting/DownloadCriteriaReport.vb
|
Visual Basic
|
apache-2.0
| 3,826
|
' 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.
Imports System.Composition
Imports Microsoft.CodeAnalysis.Editor.Implementation.InlineRename
Imports Microsoft.CodeAnalysis.Host.Mef
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.InlineRename
<ExportLanguageService(GetType(IEditorInlineRenameService), LanguageNames.VisualBasic), [Shared]>
Friend Class VisualBasicEditorInlineRenameService
Inherits AbstractEditorInlineRenameService
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New(
<ImportMany> refactorNotifyServices As IEnumerable(Of IRefactorNotifyService))
MyBase.New(refactorNotifyServices)
End Sub
Protected Overrides Function CheckLanguageSpecificIssues(semanticModel As SemanticModel, symbol As ISymbol, triggerToken As SyntaxToken, ByRef langError As String) As Boolean
Return False
End Function
End Class
End Namespace
|
CyrusNajmabadi/roslyn
|
src/EditorFeatures/VisualBasic/InlineRename/VisualBasicEditorInlineRenameService.vb
|
Visual Basic
|
mit
| 1,148
|
' 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.
Imports System.Collections.Immutable
Imports System.Composition
Imports System.Threading
Imports Microsoft.CodeAnalysis.Completion
Imports Microsoft.CodeAnalysis.Completion.Providers
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.Providers
<ExportCompletionProvider(NameOf(ObjectCreationCompletionProvider), LanguageNames.VisualBasic)>
<ExtensionOrder(After:=NameOf(ObjectInitializerCompletionProvider))>
<[Shared]>
Partial Friend Class ObjectCreationCompletionProvider
Inherits AbstractObjectCreationCompletionProvider
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Friend Overrides Function IsInsertionTrigger(text As SourceText, characterPosition As Integer, options As OptionSet) As Boolean
Return CompletionUtilities.IsTriggerAfterSpaceOrStartOfWordCharacter(text, characterPosition, options)
End Function
Friend Overrides ReadOnly Property TriggerCharacters As ImmutableHashSet(Of Char) = CompletionUtilities.SpaceTriggerChar
Protected Overrides Function GetObjectCreationNewExpression(tree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As SyntaxNode
Dim newExpression As SyntaxNode = Nothing
If tree IsNot Nothing AndAlso Not tree.IsInNonUserCode(position, cancellationToken) AndAlso Not tree.IsInSkippedText(position, cancellationToken) Then
Dim newToken = tree.FindTokenOnLeftOfPosition(position, cancellationToken)
newToken = newToken.GetPreviousTokenIfTouchingWord(position)
' Only after 'new'.
If newToken.Kind = SyntaxKind.NewKeyword Then
' Only if the 'new' belongs to an object creation expression.
If tree.IsObjectCreationTypeContext(position, cancellationToken) Then
newExpression = TryCast(newToken.Parent, ExpressionSyntax)
End If
End If
End If
Return newExpression
End Function
Protected Overrides Async Function CreateContextAsync(document As Document, position As Integer, cancellationToken As CancellationToken) As Task(Of SyntaxContext)
Dim semanticModel = Await document.ReuseExistingSpeculativeModelAsync(position, cancellationToken).ConfigureAwait(False)
Return Await VisualBasicSyntaxContext.CreateContextAsync(document.Project.Solution.Workspace, semanticModel, position, cancellationToken).ConfigureAwait(False)
End Function
Private Shared ReadOnly s_rules As CompletionItemRules =
CompletionItemRules.Create(
commitCharacterRules:=ImmutableArray.Create(CharacterSetModificationRule.Create(CharacterSetModificationKind.Replace, " "c, "("c)),
matchPriority:=MatchPriority.Preselect,
selectionBehavior:=CompletionItemSelectionBehavior.HardSelection)
Protected Overrides Function GetCompletionItemRules(symbols As IReadOnlyList(Of ISymbol), preselect As Boolean) As CompletionItemRules
Return s_rules
End Function
End Class
End Namespace
|
jmarolf/roslyn
|
src/Features/VisualBasic/Portable/Completion/CompletionProviders/ObjectCreationCompletionProvider.vb
|
Visual Basic
|
mit
| 3,736
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class MethodDocumentationCommentTests
Inherits BasicTestBase
Private ReadOnly _compilation As VisualBasicCompilation
Private ReadOnly _acmeNamespace As NamespaceSymbol
Private ReadOnly _widgetClass As NamedTypeSymbol
Public Sub New()
_compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation name="MethodDocumentationCommentTests">
<file name="a.vb">
Namespace Acme
Structure ValueType
Public Sub M(i As Integer)
End Sub
Public Shared Widening Operator CType(value As Byte) As ValueType
Return New ValueType
End Operator
End Structure
Class Widget
Public Class NestedClass
Public Sub M(i As Integer)
End Sub
End Class
Public Shared Sub M0()
End Sub
Public Sub M1(c As Char, ByRef f As Single, _
ByRef v As ValueType)
End Sub
Public Sub M2(x1() As Short, x2(,) As Integer, _
x3()() As Long)
End Sub
Public Sub M3(x3()() As Long, x4()(,,) As Widget)
End Sub
Public Sub M4(Optional i As Integer = 1)
End Sub
Public Sub M5(ParamArray args() As Object)
End Sub
End Class
Class MyList(Of T)
Public Sub Test(t As T)
End Sub
Public Sub Zip(other As MyList(Of T))
End Sub
Public Sub ReallyZip(other as MyList(Of MyList(Of T)))
End Sub
End Class
Class UseList
Public Sub Process(list As MyList(Of Integer))
End Sub
Public Function GetValues(Of T)(inputValue As T) As MyList(Of T)
Return Nothing
End Function
End Class
End Namespace
</file>
</compilation>)
_acmeNamespace = DirectCast(_compilation.GlobalNamespace.GetMembers("Acme").Single(), NamespaceSymbol)
_widgetClass = DirectCast(_acmeNamespace.GetTypeMembers("Widget").Single(), NamedTypeSymbol)
End Sub
<Fact>
Public Sub TestMethodInStructure()
Assert.Equal("M:Acme.ValueType.M(System.Int32)",
_acmeNamespace.GetTypeMembers("ValueType").Single() _
.GetMembers("M").Single().GetDocumentationCommentId())
End Sub
<Fact>
Public Sub TestMethodInNestedClass()
Assert.Equal("M:Acme.Widget.NestedClass.M(System.Int32)",
_widgetClass.GetTypeMembers("NestedClass").Single() _
.GetMembers("M").Single().GetDocumentationCommentId())
End Sub
<Fact>
Public Sub TestMethod1()
Assert.Equal("M:Acme.Widget.M0",
_widgetClass.GetMembers("M0").Single().GetDocumentationCommentId())
End Sub
<Fact>
Public Sub TestMethod2()
Assert.Equal("M:Acme.Widget.M1(System.Char,System.Single@,Acme.ValueType@)",
_widgetClass.GetMembers("M1").Single().GetDocumentationCommentId())
End Sub
<Fact>
Public Sub TestMethod3()
Assert.Equal("M:Acme.Widget.M2(System.Int16[],System.Int32[0:,0:],System.Int64[][])",
_widgetClass.GetMembers("M2").Single().GetDocumentationCommentId())
End Sub
<Fact>
Public Sub TestMethod4()
Assert.Equal("M:Acme.Widget.M3(System.Int64[][],Acme.Widget[0:,0:,0:][])",
_widgetClass.GetMembers("M3").Single().GetDocumentationCommentId())
End Sub
<Fact>
Public Sub TestMethod5()
Assert.Equal("M:Acme.Widget.M4(System.Int32)",
_widgetClass.GetMembers("M4").Single().GetDocumentationCommentId())
End Sub
<Fact>
Public Sub TestMethod6()
Assert.Equal("M:Acme.Widget.M5(System.Object[])",
_widgetClass.GetMembers("M5").Single().GetDocumentationCommentId())
End Sub
<Fact>
Public Sub TestMethodInGenericClass()
Assert.Equal("M:Acme.MyList`1.Test(`0)",
_acmeNamespace.GetTypeMembers("MyList", 1).Single() _
.GetMembers("Test").Single().GetDocumentationCommentId())
End Sub
<WorkItem(766313, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/766313")>
<Fact>
Public Sub TestMethodWithGenericDeclaringTypeAsParameter()
Assert.Equal("M:Acme.MyList`1.Zip(Acme.MyList{`0})",
_acmeNamespace.GetTypeMembers("MyList", 1).Single() _
.GetMembers("Zip").Single().GetDocumentationCommentId())
End Sub
<WorkItem(766313, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/766313")>
<Fact>
Public Sub TestMethodWithGenericDeclaringTypeAsTypeParameter()
Assert.Equal("M:Acme.MyList`1.ReallyZip(Acme.MyList{Acme.MyList{`0}})",
_acmeNamespace.GetTypeMembers("MyList", 1).Single() _
.GetMembers("ReallyZip").Single().GetDocumentationCommentId())
End Sub
<Fact>
Public Sub TestMethodWithClosedGenericParameter()
Assert.Equal("M:Acme.UseList.Process(Acme.MyList{System.Int32})",
_acmeNamespace.GetTypeMembers("UseList").Single() _
.GetMembers("Process").Single().GetDocumentationCommentId())
End Sub
<Fact>
Public Sub TestGenericMethod()
Assert.Equal("M:Acme.UseList.GetValues``1(``0)",
_acmeNamespace.GetTypeMembers("UseList").Single() _
.GetMembers("GetValues").Single().GetDocumentationCommentId())
End Sub
<Fact>
Public Sub TestMethodWithMissingType()
Dim csharpAssemblyReference = TestReferences.SymbolsTests.UseSiteErrors.CSharp
Dim ilAssemblyReference = TestReferences.SymbolsTests.UseSiteErrors.IL
Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndReferences(
<compilation>
<file name="a.vb">
Class C
Friend Shared F As CSharpErrors.ClassMethods
End Class
</file>
</compilation>,
{csharpAssemblyReference, ilAssemblyReference})
Dim type = compilation.Assembly.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C")
type = DirectCast(type.GetMember(Of FieldSymbol)("F").Type, NamedTypeSymbol)
Dim members = type.GetMembers()
Assert.InRange(members.Length, 1, Integer.MaxValue)
For Each member In members
Dim docComment = member.GetDocumentationCommentXml()
Assert.NotNull(docComment)
Next
End Sub
<Fact, WorkItem(530924, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530924")>
Public Sub TestConversionOperator()
Assert.Equal("M:Acme.ValueType.op_Implicit(System.Byte)~Acme.ValueType",
_acmeNamespace.GetTypeMembers("ValueType").Single() _
.GetMembers("op_Implicit").Single().GetDocumentationCommentId())
End Sub
<Fact, WorkItem(4699, "https://github.com/dotnet/roslyn/issues/4699")>
Public Sub GetMalformedDocumentationCommentXml()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Class Test
''' <summary>
''' Info
''' <!-- comment
''' </summary
Shared Sub Main()
End Sub
End Class
]]></file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(source, parseOptions:=TestOptions.Regular.WithDocumentationMode(DocumentationMode.Diagnose))
Dim main = compilation.GetTypeByMetadataName("Test").GetMember(Of MethodSymbol)("Main")
Assert.Equal(
"<member name=""M:Test.Main"">
<summary>
Info
<!-- comment
</summary
</member>", main.GetDocumentationCommentXml().Trim())
compilation = CompilationUtils.CreateCompilationWithMscorlib(source, parseOptions:=TestOptions.Regular.WithDocumentationMode(DocumentationMode.Parse))
main = compilation.GetTypeByMetadataName("Test").GetMember(Of MethodSymbol)("Main")
Assert.Equal(
"<member name=""M:Test.Main"">
<summary>
Info
<!-- comment
</summary
</member>", main.GetDocumentationCommentXml().Trim())
compilation = CompilationUtils.CreateCompilationWithMscorlib(source, parseOptions:=TestOptions.Regular.WithDocumentationMode(DocumentationMode.None))
main = compilation.GetTypeByMetadataName("Test").GetMember(Of MethodSymbol)("Main")
Assert.Equal("", main.GetDocumentationCommentXml().Trim())
End Sub
End Class
End Namespace
|
ericfe-ms/roslyn
|
src/Compilers/VisualBasic/Test/Symbol/DocumentationComments/MethodDocumentationCommentTests.vb
|
Visual Basic
|
apache-2.0
| 10,195
|
Imports System
Imports System.Reflection
Imports 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.
' Review the values of the assembly attributes
<Assembly: AssemblyTitle("WeatherStationVB")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("")>
<Assembly: AssemblyProduct("WeatherStationVB")>
<Assembly: AssemblyCopyright("Copyright © 2015")>
<Assembly: AssemblyTrademark("")>
' 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")>
<Assembly: ComVisible(False)>
|
sndnvaps/ms-iot_samples
|
WeatherStation/VB/WeatherStationVB/My Project/AssemblyInfo.vb
|
Visual Basic
|
mit
| 998
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.0
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
|
f14n/code-cracker
|
test/VisualBasic/CodeCracker.Test/My Project/Application.Designer.vb
|
Visual Basic
|
apache-2.0
| 424
|
Imports System
Imports System.Reflection
Imports 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.
' Review the values of the assembly attributes
<Assembly: AssemblyTitle("Triple A Number")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("University of Hartford")>
<Assembly: AssemblyProduct("Triple A Number")>
<Assembly: AssemblyCopyright("Copyright © University of Hartford 2013")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("602e2fbf-9bea-4e66-9459-7f08f512a310")>
' 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")>
|
patkub/visual-basic-intro
|
Triple A Number/Triple A Number/My Project/AssemblyInfo.vb
|
Visual Basic
|
mit
| 1,192
|
Imports Microsoft.Devices.Sensors
Imports Microsoft.Phone.Reactive
Imports Microsoft.Xna.Framework
Imports System.Threading
Partial Public Class MainPage
Inherits PhoneApplicationPage
' Constructor
Private _Accelerometer As Accelerometer
Private _UseEmulation As Boolean = True
Public Sub New()
InitializeComponent()
End Sub
Private Sub Button_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
If Not _UseEmulation Then
_Accelerometer = New Accelerometer
Dim accelerometerReadingAsObservable = Observable.FromEvent(Of AccelerometerReadingEventArgs)(_Accelerometer, "ReadingChanged")
Dim vector3FromAccelerometerEventArgs = From args In accelerometerReadingAsObservable
Select New Vector3(
CSng(args.EventArgs.X),
CSng(args.EventArgs.Y),
CSng(args.EventArgs.Z))
vector3FromAccelerometerEventArgs.Subscribe(
Sub(args)
InvokeAccelerometerReadingChanged(args)
End Sub)
Try
_Accelerometer.Start()
Catch ex As Exception
ReadingTextBlock.Text = "Error starting accelerometer"
End Try
Else
StartAccelerometerEmulation()
End If
End Sub
Private _Subscribed As IDisposable
Private Sub InvokeAccelerometerReadingChanged(ByVal data As Vector3)
Deployment.Current.Dispatcher.BeginInvoke(
Sub() AccelerometerReadingChanged(data))
End Sub
Private Sub StartAccelerometerEmulation()
If _Subscribed Is Nothing Then
Dim emulationObservable = GetEmulator()
_Subscribed = emulationObservable.SubscribeOn(Scheduler.ThreadPool).
Subscribe(Sub(accelerometerReadingEventArgs) InvokeAccelerometerReadingChanged(accelerometerReadingEventArgs))
Else
_Subscribed.Dispose()
_Subscribed = Nothing
End If
End Sub
Private Sub AccelerometerReadingChanged(ByVal data As Vector3)
ReadingTextBlock.Text = String.Format("X: {0} y: {1} z: {2}",
data.X.ToString("0.00"),
data.Y.ToString("0.00"),
data.Z.ToString("0.00"))
Dim multiplier As Short
If Short.TryParse(Me.MoveMultiplier.Text, multiplier) Then
ButtonTransform.X = data.X * multiplier
ButtonTransform.Y = data.Y * multiplier
End If
End Sub
Public Shared Function GetEmulator() As IObservable(Of Vector3)
Dim obs = Observable.Create(Of Vector3)(
Function(subscriber)
Dim rnd = New Random
Dim theta As Double
Do
theta = rnd.NextDouble
Dim reading = New Vector3(CSng(Math.Sin(theta)), CSng(Math.Cos(theta * 1.1)), CSng(Math.Sin(theta * 0.7)))
reading.Normalize()
Thread.Sleep(100)
subscriber.OnNext(reading)
Loop
End Function)
Return obs
End Function
End Class
|
jwooley/RxSamples
|
WP7RxSamplesVB/WP7AccelerometerVB/WP7AccelerometerVB/MainPage.xaml.vb
|
Visual Basic
|
mit
| 3,429
|
'
' News Articles for DotNetNuke - http://www.dotnetnuke.com
' Copyright (c) 2002-2007
' by Ventrian ( sales@ventrian.com ) ( http://www.ventrian.com )
'
Imports System
Imports System.Configuration
Imports System.Data
Imports DotNetNuke.Common.Utilities
Namespace Ventrian.NewsArticles.Components.Types
Public Enum TextEditorModeType
Basic
Rich
End Enum
End Namespace
|
ventrian/News-Articles
|
Components/Types/TextEditorModeType.vb
|
Visual Basic
|
mit
| 422
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> Partial Class frmpricechange
#Region "Windows Form Designer generated code "
<System.Diagnostics.DebuggerNonUserCode()> Public Sub New()
MyBase.New()
'This call is required by the Windows Form Designer.
InitializeComponent()
End Sub
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> Protected Overloads Overrides Sub Dispose(ByVal Disposing As Boolean)
If Disposing Then
If Not components Is Nothing Then
components.Dispose()
End If
End If
MyBase.Dispose(Disposing)
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
Public ToolTip1 As System.Windows.Forms.ToolTip
Public WithEvents cmdcancel As System.Windows.Forms.Button
Public WithEvents cmdshow As System.Windows.Forms.Button
Public WithEvents cmdenddate As System.Windows.Forms.Button
Public WithEvents txtenddate As System.Windows.Forms.TextBox
Public WithEvents txtstartdate As System.Windows.Forms.TextBox
Public WithEvents cmdstart As System.Windows.Forms.Button
Public WithEvents lblInstruction As System.Windows.Forms.Label
Public WithEvents Label2 As System.Windows.Forms.Label
Public WithEvents Label1 As System.Windows.Forms.Label
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
Dim resources As System.Resources.ResourceManager = New System.Resources.ResourceManager(GetType(frmpricechange))
Me.components = New System.ComponentModel.Container()
Me.ToolTip1 = New System.Windows.Forms.ToolTip(components)
Me.cmdcancel = New System.Windows.Forms.Button
Me.cmdshow = New System.Windows.Forms.Button
Me.cmdenddate = New System.Windows.Forms.Button
Me.txtenddate = New System.Windows.Forms.TextBox
Me.txtstartdate = New System.Windows.Forms.TextBox
Me.cmdstart = New System.Windows.Forms.Button
Me.lblInstruction = New System.Windows.Forms.Label
Me.Label2 = New System.Windows.Forms.Label
Me.Label1 = New System.Windows.Forms.Label
Me.SuspendLayout()
Me.ToolTip1.Active = True
Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle
Me.Text = "Price Changes"
Me.ClientSize = New System.Drawing.Size(442, 155)
Me.Location = New System.Drawing.Point(3, 29)
Me.Icon = CType(resources.GetObject("frmpricechange.Icon"), System.Drawing.Icon)
Me.KeyPreview = True
Me.MaximizeBox = False
Me.MinimizeBox = False
Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.BackColor = System.Drawing.SystemColors.Control
Me.ControlBox = True
Me.Enabled = True
Me.Cursor = System.Windows.Forms.Cursors.Default
Me.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.ShowInTaskbar = True
Me.HelpButton = False
Me.WindowState = System.Windows.Forms.FormWindowState.Normal
Me.Name = "frmpricechange"
Me.cmdcancel.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
Me.cmdcancel.Text = "&Cancel"
Me.cmdcancel.Size = New System.Drawing.Size(81, 33)
Me.cmdcancel.Location = New System.Drawing.Point(352, 112)
Me.cmdcancel.TabIndex = 7
Me.cmdcancel.BackColor = System.Drawing.SystemColors.Control
Me.cmdcancel.CausesValidation = True
Me.cmdcancel.Enabled = True
Me.cmdcancel.ForeColor = System.Drawing.SystemColors.ControlText
Me.cmdcancel.Cursor = System.Windows.Forms.Cursors.Default
Me.cmdcancel.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.cmdcancel.TabStop = True
Me.cmdcancel.Name = "cmdcancel"
Me.cmdshow.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
Me.cmdshow.Text = "&Show"
Me.cmdshow.Size = New System.Drawing.Size(81, 33)
Me.cmdshow.Location = New System.Drawing.Point(248, 112)
Me.cmdshow.TabIndex = 6
Me.cmdshow.BackColor = System.Drawing.SystemColors.Control
Me.cmdshow.CausesValidation = True
Me.cmdshow.Enabled = True
Me.cmdshow.ForeColor = System.Drawing.SystemColors.ControlText
Me.cmdshow.Cursor = System.Windows.Forms.Cursors.Default
Me.cmdshow.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.cmdshow.TabStop = True
Me.cmdshow.Name = "cmdshow"
Me.cmdenddate.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
Me.cmdenddate.Text = "..."
Me.cmdenddate.Font = New System.Drawing.Font("Verdana", 8.25!, System.Drawing.FontStyle.Bold Or System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.cmdenddate.Size = New System.Drawing.Size(33, 33)
Me.cmdenddate.Location = New System.Drawing.Point(400, 64)
Me.cmdenddate.TabIndex = 5
Me.cmdenddate.BackColor = System.Drawing.SystemColors.Control
Me.cmdenddate.CausesValidation = True
Me.cmdenddate.Enabled = True
Me.cmdenddate.ForeColor = System.Drawing.SystemColors.ControlText
Me.cmdenddate.Cursor = System.Windows.Forms.Cursors.Default
Me.cmdenddate.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.cmdenddate.TabStop = True
Me.cmdenddate.Name = "cmdenddate"
Me.txtenddate.AutoSize = False
Me.txtenddate.Size = New System.Drawing.Size(81, 33)
Me.txtenddate.Location = New System.Drawing.Point(320, 64)
Me.txtenddate.TabIndex = 4
Me.txtenddate.AcceptsReturn = True
Me.txtenddate.TextAlign = System.Windows.Forms.HorizontalAlignment.Left
Me.txtenddate.BackColor = System.Drawing.SystemColors.Window
Me.txtenddate.CausesValidation = True
Me.txtenddate.Enabled = True
Me.txtenddate.ForeColor = System.Drawing.SystemColors.WindowText
Me.txtenddate.HideSelection = True
Me.txtenddate.ReadOnly = False
Me.txtenddate.Maxlength = 0
Me.txtenddate.Cursor = System.Windows.Forms.Cursors.IBeam
Me.txtenddate.MultiLine = False
Me.txtenddate.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.txtenddate.ScrollBars = System.Windows.Forms.ScrollBars.None
Me.txtenddate.TabStop = True
Me.txtenddate.Visible = True
Me.txtenddate.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
Me.txtenddate.Name = "txtenddate"
Me.txtstartdate.AutoSize = False
Me.txtstartdate.Size = New System.Drawing.Size(81, 33)
Me.txtstartdate.Location = New System.Drawing.Point(112, 64)
Me.txtstartdate.TabIndex = 2
Me.txtstartdate.AcceptsReturn = True
Me.txtstartdate.TextAlign = System.Windows.Forms.HorizontalAlignment.Left
Me.txtstartdate.BackColor = System.Drawing.SystemColors.Window
Me.txtstartdate.CausesValidation = True
Me.txtstartdate.Enabled = True
Me.txtstartdate.ForeColor = System.Drawing.SystemColors.WindowText
Me.txtstartdate.HideSelection = True
Me.txtstartdate.ReadOnly = False
Me.txtstartdate.Maxlength = 0
Me.txtstartdate.Cursor = System.Windows.Forms.Cursors.IBeam
Me.txtstartdate.MultiLine = False
Me.txtstartdate.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.txtstartdate.ScrollBars = System.Windows.Forms.ScrollBars.None
Me.txtstartdate.TabStop = True
Me.txtstartdate.Visible = True
Me.txtstartdate.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
Me.txtstartdate.Name = "txtstartdate"
Me.cmdstart.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
Me.cmdstart.Text = "..."
Me.cmdstart.Font = New System.Drawing.Font("Verdana", 8.25!, System.Drawing.FontStyle.Bold Or System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.cmdstart.Size = New System.Drawing.Size(33, 33)
Me.cmdstart.Location = New System.Drawing.Point(192, 64)
Me.cmdstart.TabIndex = 1
Me.cmdstart.BackColor = System.Drawing.SystemColors.Control
Me.cmdstart.CausesValidation = True
Me.cmdstart.Enabled = True
Me.cmdstart.ForeColor = System.Drawing.SystemColors.ControlText
Me.cmdstart.Cursor = System.Windows.Forms.Cursors.Default
Me.cmdstart.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.cmdstart.TabStop = True
Me.cmdstart.Name = "cmdstart"
Me.lblInstruction.Text = "This Process will print you the Price Changes of the Date range you selected.Please Select the 'Start Date' and the 'End Date' and Click the Show button.Please Note the Start Date must be earlier than the 'End Date'"
Me.lblInstruction.Size = New System.Drawing.Size(424, 45)
Me.lblInstruction.Location = New System.Drawing.Point(8, 8)
Me.lblInstruction.TabIndex = 8
Me.lblInstruction.TextAlign = System.Drawing.ContentAlignment.TopLeft
Me.lblInstruction.BackColor = System.Drawing.SystemColors.Control
Me.lblInstruction.Enabled = True
Me.lblInstruction.ForeColor = System.Drawing.SystemColors.ControlText
Me.lblInstruction.Cursor = System.Windows.Forms.Cursors.Default
Me.lblInstruction.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.lblInstruction.UseMnemonic = True
Me.lblInstruction.Visible = True
Me.lblInstruction.AutoSize = False
Me.lblInstruction.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
Me.lblInstruction.Name = "lblInstruction"
Me.Label2.Text = "End Date:"
Me.Label2.Size = New System.Drawing.Size(81, 33)
Me.Label2.Location = New System.Drawing.Point(232, 72)
Me.Label2.TabIndex = 3
Me.Label2.TextAlign = System.Drawing.ContentAlignment.TopLeft
Me.Label2.BackColor = System.Drawing.SystemColors.Control
Me.Label2.Enabled = True
Me.Label2.ForeColor = System.Drawing.SystemColors.ControlText
Me.Label2.Cursor = System.Windows.Forms.Cursors.Default
Me.Label2.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.Label2.UseMnemonic = True
Me.Label2.Visible = True
Me.Label2.AutoSize = False
Me.Label2.BorderStyle = System.Windows.Forms.BorderStyle.None
Me.Label2.Name = "Label2"
Me.Label1.Text = " Start Date:"
Me.Label1.Size = New System.Drawing.Size(97, 25)
Me.Label1.Location = New System.Drawing.Point(8, 72)
Me.Label1.TabIndex = 0
Me.Label1.TextAlign = System.Drawing.ContentAlignment.TopLeft
Me.Label1.BackColor = System.Drawing.SystemColors.Control
Me.Label1.Enabled = True
Me.Label1.ForeColor = System.Drawing.SystemColors.ControlText
Me.Label1.Cursor = System.Windows.Forms.Cursors.Default
Me.Label1.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.Label1.UseMnemonic = True
Me.Label1.Visible = True
Me.Label1.AutoSize = False
Me.Label1.BorderStyle = System.Windows.Forms.BorderStyle.None
Me.Label1.Name = "Label1"
Me.Controls.Add(cmdcancel)
Me.Controls.Add(cmdshow)
Me.Controls.Add(cmdenddate)
Me.Controls.Add(txtenddate)
Me.Controls.Add(txtstartdate)
Me.Controls.Add(cmdstart)
Me.Controls.Add(lblInstruction)
Me.Controls.Add(Label2)
Me.Controls.Add(Label1)
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
#End Region
End Class
|
nodoid/PointOfSale
|
VB/4PosBackOffice.NET/frmpricechange.Designer.vb
|
Visual Basic
|
mit
| 10,918
|
'-------------------------------------------------------------------------------------------'
' Inicio del codigo
'-------------------------------------------------------------------------------------------'
' Importando librerias
'-------------------------------------------------------------------------------------------'
Imports System.Data
'-------------------------------------------------------------------------------------------'
' Inicio de clase "rTCobros_Fechas"
'-------------------------------------------------------------------------------------------'
Partial Class rTCobros_Fechas
Inherits vis2formularios.frmReporte
Dim loObjetoReporte As CrystalDecisions.CrystalReports.Engine.ReportDocument
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
Dim lcParametro0Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(0), goServicios.enuOpcionesRedondeo.KN_FechaInicioDelDia)
Dim lcParametro0Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(0), goServicios.enuOpcionesRedondeo.KN_FechaFinDelDia)
Dim lcParametro1Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(1))
Dim lcParametro1Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(1))
Dim lcParametro2Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(2))
Dim lcParametro2Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(2))
Dim lcParametro3Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(3))
Dim lcParametro3Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(3))
Dim lcParametro4Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(4))
Dim lcParametro4Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(4))
Dim lcParametro5Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(5))
Dim lcParametro5Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(5))
Dim lcOrdenamiento As String = cusAplicacion.goReportes.pcOrden
Dim loComandoSeleccionar As New StringBuilder()
loComandoSeleccionar.AppendLine(" SELECT DATEPART(YEAR, Fec_Ini) AS Año,")
loComandoSeleccionar.AppendLine(" DATEPART(MONTH, Fec_Ini) AS Mes,")
loComandoSeleccionar.AppendLine(" DATEPART(DAY, Fec_Ini) AS Dia,")
loComandoSeleccionar.AppendLine(" SUM(ISNULL(Mon_Net,0)) AS Mon_Net")
loComandoSeleccionar.AppendLine(" INTO #Temporal")
loComandoSeleccionar.AppendLine(" FROM Cuentas_Cobrar")
loComandoSeleccionar.AppendLine(" WHERE Cuentas_Cobrar.Cod_Tip IN ('Fact','ATD')")
loComandoSeleccionar.AppendLine(" AND Fec_Ini BETWEEN " & lcParametro0Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro0Hasta)
loComandoSeleccionar.AppendLine(" AND Cod_Cli BETWEEN " & lcParametro1Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro1Hasta)
loComandoSeleccionar.AppendLine(" AND Cod_Ven BETWEEN " & lcParametro2Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro2Hasta)
loComandoSeleccionar.AppendLine(" AND Cuentas_Cobrar.Status IN ('Afectado', 'Pagado')")
loComandoSeleccionar.AppendLine(" AND Cod_Mon BETWEEN " & lcParametro3Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro3Hasta)
loComandoSeleccionar.AppendLine(" AND Cod_Rev BETWEEN " & lcParametro4Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro4Hasta)
loComandoSeleccionar.AppendLine(" AND Cod_Suc BETWEEN " & lcParametro5Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro5Hasta)
loComandoSeleccionar.AppendLine(" GROUP BY DATEPART(YEAR, Fec_Ini),DATEPART(MONTH, Fec_Ini), DATEPART(DAY, Fec_Ini) ")
loComandoSeleccionar.AppendLine(" SELECT DATEPART(YEAR, Cobros.fec_ini) AS Año,")
loComandoSeleccionar.AppendLine(" DATEPART(MONTH, Cobros.fec_ini)AS Mes,")
loComandoSeleccionar.AppendLine(" DATEPART(DAY, Cobros.fec_ini)AS Dia,")
loComandoSeleccionar.AppendLine(" SUM(CASE WHEN Detalles_Cobros.Tip_Ope = 'Efectivo' THEN Detalles_Cobros.Mon_Net ELSE 0 END) AS Efectivo, ")
loComandoSeleccionar.AppendLine(" SUM(CASE WHEN Detalles_Cobros.Tip_Ope = 'Ticket' THEN Detalles_Cobros.Mon_Net ELSE 0 END) AS Ticket, ")
loComandoSeleccionar.AppendLine(" SUM(CASE WHEN Detalles_Cobros.Tip_Ope = 'Cheque' THEN Detalles_Cobros.Mon_Net ELSE 0 END) AS Cheque, ")
loComandoSeleccionar.AppendLine(" SUM(CASE WHEN Detalles_Cobros.Tip_Ope = 'Tarjeta' THEN Detalles_Cobros.Mon_Net ELSE 0 END) AS Tarjeta, ")
loComandoSeleccionar.AppendLine(" SUM(CASE WHEN Detalles_Cobros.Tip_Ope = 'Deposito' THEN Detalles_Cobros.Mon_Net ELSE 0 END) AS Deposito, ")
loComandoSeleccionar.AppendLine(" SUM(CASE WHEN Detalles_Cobros.Tip_Ope = 'Transferencia' THEN Detalles_Cobros.Mon_Net ELSE 0 END) AS Transferencia ")
loComandoSeleccionar.AppendLine(" INTO #Temporal2 ")
loComandoSeleccionar.AppendLine(" FROM Cobros Cobros")
loComandoSeleccionar.AppendLine(" JOIN Vendedores AS Vendedores ON Vendedores.Cod_Ven = Cobros.Cod_Ven ")
loComandoSeleccionar.AppendLine(" JOIN Detalles_Cobros AS Detalles_Cobros ON Detalles_Cobros.Documento = Cobros.Documento")
loComandoSeleccionar.AppendLine(" WHERE Cobros.Fec_Ini BETWEEN " & lcParametro0Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro0Hasta)
loComandoSeleccionar.AppendLine(" AND Cobros.Cod_Cli BETWEEN " & lcParametro1Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro1Hasta)
loComandoSeleccionar.AppendLine(" AND Cobros.Cod_Ven BETWEEN " & lcParametro2Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro2Hasta)
loComandoSeleccionar.AppendLine(" AND Cobros.Status IN ('Confirmado')")
loComandoSeleccionar.AppendLine(" AND Cobros.Cod_Mon BETWEEN " & lcParametro3Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro3Hasta)
loComandoSeleccionar.AppendLine(" AND Cobros.Cod_Rev BETWEEN " & lcParametro4Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro4Hasta)
loComandoSeleccionar.AppendLine(" AND Cobros.Cod_Suc BETWEEN " & lcParametro5Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro5Hasta)
loComandoSeleccionar.AppendLine(" GROUP BY DATEPART(YEAR, Cobros.Fec_Ini),DATEPART(MONTH, Cobros.Fec_Ini), DATEPART(DAY, Cobros.Fec_Ini)")
loComandoSeleccionar.AppendLine(" SELECT ISNULL(#temporal.Año, #temporal2.Año) AS Año, ")
loComandoSeleccionar.AppendLine(" ISNULL(#temporal.Mes, #temporal2.Mes) AS Mes, ")
loComandoSeleccionar.AppendLine(" ISNULL(#temporal.Dia, #temporal2.Dia) AS Dia, ")
loComandoSeleccionar.AppendLine(" ISNULL(#temporal.Mon_Net,0) AS Mon_Net, ")
loComandoSeleccionar.AppendLine(" (ISNULL(#temporal2.Efectivo,0)) AS Efectivo, ")
loComandoSeleccionar.AppendLine(" (ISNULL(#temporal2.Ticket,0)) AS Ticket, ")
loComandoSeleccionar.AppendLine(" (ISNULL(#temporal2.Cheque,0)) AS Cheque, ")
loComandoSeleccionar.AppendLine(" (ISNULL(#temporal2.Tarjeta,0)) AS Tarjeta, ")
loComandoSeleccionar.AppendLine(" (ISNULL(#temporal2.Deposito,0)) AS Deposito, ")
loComandoSeleccionar.AppendLine(" (ISNULL(#temporal2.Transferencia,0)) AS Transferencia,")
loComandoSeleccionar.AppendLine(" (ISNULL(#temporal2.Efectivo,0) + ISNULL(#temporal2.Cheque,0) + ISNULL(#temporal2.Tarjeta,0) + ISNULL(#temporal2.Deposito,0) + ISNULL(#temporal2.Transferencia,0) + ISNULL(#temporal2.Ticket,0)) AS Total_Cobros")
loComandoSeleccionar.AppendLine(" INTO #Temporal002 ")
loComandoSeleccionar.AppendLine(" FROM #Temporal #Temporal ")
loComandoSeleccionar.AppendLine(" FULL JOIN #temporal2 AS #temporal2 ON ((#temporal.Año = #temporal2.Año) AND (#temporal.Mes = #temporal2.Mes) AND (#temporal.Dia = #temporal2.Dia)) ")
loComandoSeleccionar.AppendLine(" SELECT 'Cuantos' AS Cuantos, ")
loComandoSeleccionar.AppendLine(" Año, ")
loComandoSeleccionar.AppendLine(" Mes, ")
loComandoSeleccionar.AppendLine(" Dia, ")
loComandoSeleccionar.AppendLine(" Mon_Net, ")
loComandoSeleccionar.AppendLine(" Efectivo, ")
loComandoSeleccionar.AppendLine(" Ticket, ")
loComandoSeleccionar.AppendLine(" Cheque, ")
loComandoSeleccionar.AppendLine(" Tarjeta, ")
loComandoSeleccionar.AppendLine(" Deposito, ")
loComandoSeleccionar.AppendLine(" Transferencia,")
loComandoSeleccionar.AppendLine(" Total_Cobros")
loComandoSeleccionar.AppendLine(" FROM #Temporal002 ")
loComandoSeleccionar.AppendLine(" ORDER BY " & lcOrdenamiento)
Dim loServicios As New cusDatos.goDatos
Dim laDatosReporte As DataSet = loServicios.mObtenerTodosSinEsquema(loComandoSeleccionar.ToString, "curReportes")
'-------------------------------------------------------------------------------------------------------
' Verificando si el select (tabla nº0) trae registros
'-------------------------------------------------------------------------------------------------------
If (laDatosReporte.Tables(0).Rows.Count <= 0) Then
Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Información", _
"No se Encontraron Registros para los Parámetros Especificados. ", _
vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Informacion, _
"350px", _
"200px")
End If
loObjetoReporte = cusAplicacion.goReportes.mCargarReporte("rTCobros_Fechas", laDatosReporte)
Me.mTraducirReporte(loObjetoReporte)
Me.mFormatearCamposReporte(loObjetoReporte)
Me.crvrTCobros_Fechas.ReportSource = loObjetoReporte
Catch loExcepcion As Exception
Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Error", _
"No se pudo Completar el Proceso: " & loExcepcion.Message, _
vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Error, _
"auto", _
"auto")
End Try
End Sub
Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
Try
loObjetoReporte.Close()
Catch loExcepcion As Exception
End Try
End Sub
End Class
'-------------------------------------------------------------------------------------------'
' Fin del codigo '
'-------------------------------------------------------------------------------------------'
' CMS: 08/07/09: Programacion inicial '
'-------------------------------------------------------------------------------------------'
' CMS: 20/07/09: Se agregaron las columnas ticket y transferencia '
'-------------------------------------------------------------------------------------------'
' RJG: 28/06/11: Corrección de agrupación de monto neto. '
'-------------------------------------------------------------------------------------------'
|
kodeitsolutions/ef-reports
|
rTCobros_Fechas.aspx.vb
|
Visual Basic
|
mit
| 13,148
|
Imports YamlDotNet.Serialization
Imports System.IO
Public Class YAMLskins
Inherits YAMLFilesBase
Public Const skinsFile As String = "skins.yaml"
Public Sub New(ByVal YAMLFileName As String, ByVal YAMLFilePath As String, ByRef DatabaseRef As Object, ByRef TranslationRef As YAMLTranslations)
MyBase.New(YAMLFileName, YAMLFilePath, DatabaseRef, TranslationRef)
End Sub
''' <summary>
''' Imports the yaml file into the database set in the constructor
''' </summary>
''' <param name="Params">What the row location is and whether to insert the data or not (for bulk import)</param>
Public Sub ImportFile(ByVal Params As ImportParameters)
Dim DSB = New DeserializerBuilder()
If Not TestForSDEChanges Then
DSB.IgnoreUnmatchedProperties()
End If
DSB = DSB.WithNamingConvention(New NamingConventions.NullNamingConvention)
Dim DS As New Deserializer
DS = DSB.Build
Dim YAMLRecords As New Dictionary(Of Long, skin)
Dim DataFields As List(Of DBField)
Dim IndexFields As List(Of String)
Dim SQL As String = ""
Dim Count As Long = 0
Dim TotalRecords As Long = 0
' Build table
Dim Table As New List(Of DBTableField)
Table.Add(New DBTableField("skinID", FieldType.int_type, 0, True))
Table.Add(New DBTableField("skinDescription", FieldType.text_type, MaxFieldLen, True))
Table.Add(New DBTableField("internalName", FieldType.varchar_type, 100, True))
Table.Add(New DBTableField("skinMaterialID", FieldType.int_type, 0, True))
Table.Add(New DBTableField("isStructureSkin", FieldType.int_type, 0, True))
Table.Add(New DBTableField("typeID", FieldType.int_type, 0, True))
Table.Add(New DBTableField("allowCCPDevs", FieldType.bit_type, 0, True))
Table.Add(New DBTableField("visibleSerenity", FieldType.bit_type, 0, True))
Table.Add(New DBTableField("visibleTranquility", FieldType.bit_type, 0, True))
Call UpdateDB.CreateTable(TableName, Table)
' Create indexes
IndexFields = New List(Of String)
IndexFields.Add("skinID")
Call UpdateDB.CreateIndex(TableName, "IDX_" & TableName & "_SID", IndexFields)
' See if we only want to build the table and indexes
If Not Params.InsertRecords Then
Exit Sub
End If
' Start processing
Call InitGridRow(Params.RowLocation)
Try
' Parse the input text
YAMLRecords = DS.Deserialize(Of Dictionary(Of Long, skin))(New StringReader(File.ReadAllText(YAMLFile)))
Catch ex As Exception
Call ShowErrorMessage(ex)
End Try
TotalRecords = YAMLRecords.Count
' Process Data
For Each DataField In YAMLRecords
For Each DF In DataField.Value.types
DataFields = New List(Of DBField)
With DataField.Value
' Build the insert list
DataFields.Add(UpdateDB.BuildDatabaseField("skinID", .skinID, FieldType.int_type))
DataFields.Add(UpdateDB.BuildDatabaseField("skinDescription", .skinDescription, FieldType.text_type))
DataFields.Add(UpdateDB.BuildDatabaseField("internalName", .internalName, FieldType.varchar_type))
DataFields.Add(UpdateDB.BuildDatabaseField("skinMaterialID", .skinMaterialID, FieldType.int_type))
DataFields.Add(UpdateDB.BuildDatabaseField("isStructureSkin", .isStructureSkin, FieldType.int_type))
DataFields.Add(UpdateDB.BuildDatabaseField("typeID", DF, FieldType.int_type))
DataFields.Add(UpdateDB.BuildDatabaseField("allowCCPDevs", .allowCCPDevs, FieldType.bit_type))
DataFields.Add(UpdateDB.BuildDatabaseField("visibleSerenity", .visibleSerenity, FieldType.bit_type))
DataFields.Add(UpdateDB.BuildDatabaseField("visibleTranquility", .visibleTranquility, FieldType.bit_type))
End With
Call UpdateDB.InsertRecord(TableName, DataFields)
Next
' Update grid progress
Call UpdateGridRowProgress(Params.RowLocation, Count, TotalRecords)
Count += 1
Next
Call FinalizeGridRow(Params.RowLocation)
End Sub
End Class
Public Class skin
Public Property skinID As Object
Public Property skinDescription As Object
Public Property allowCCPDevs As Object
Public Property internalName As Object
Public Property skinMaterialID As Object
Public Property isStructureSkin As Object
Public Property types As List(Of Object)
Public Property visibleSerenity As Object
Public Property visibleTranquility As Object
End Class
|
EVEIPH/EVE-SDE-Database-Builder
|
EVE SDE Database Builder/SDE YAML Classses/YAMLskins.vb
|
Visual Basic
|
mit
| 4,831
|
'-------------------------------------------------------------------------------------------'
' Inicio del codigo
'-------------------------------------------------------------------------------------------'
' Importando librerias
'-------------------------------------------------------------------------------------------'
Imports System.Data
'-------------------------------------------------------------------------------------------'
' Inicio de clase "rClientes_Tipos"
'-------------------------------------------------------------------------------------------'
Partial Class rClientes_Tipos
Inherits vis2Formularios.frmReporte
Dim loObjetoReporte As CrystalDecisions.CrystalReports.Engine.ReportDocument
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
Dim lcParametro0Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(0))
Dim lcParametro0Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(0))
Dim lcParametro1Desde As String = goServicios.mObtenerListaFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(1))
Dim lcOrdenamiento As String = cusAplicacion.goReportes.pcOrden
Dim loComandoSeleccionar As New StringBuilder()
loComandoSeleccionar.Append("SELECT Cod_Tip, ")
loComandoSeleccionar.Append("Nom_Tip, ")
loComandoSeleccionar.Append("(Case when status = 'A' then 'Activo' Else 'Inactivo' End) As Status ")
loComandoSeleccionar.Append("FROM Tipos_Clientes ")
loComandoSeleccionar.Append("WHERE Cod_Tip between " & lcParametro0Desde)
loComandoSeleccionar.Append(" And " & lcParametro0Hasta)
loComandoSeleccionar.Append(" And status IN (" & lcParametro1Desde & ")")
'loComandoSeleccionar.Append(" ORDER BY Cod_Tip, Nom_Tip")
loComandoSeleccionar.AppendLine("ORDER BY " & lcOrdenamiento)
Dim loServicios As New cusDatos.goDatos
Dim laDatosReporte As DataSet = loServicios.mObtenerTodos(loComandoSeleccionar.ToString, "curReportes")
loObjetoReporte = cusAplicacion.goReportes.mCargarReporte("rClientes_Tipos", laDatosReporte)
Me.mTraducirReporte(loObjetoReporte)
Me.mFormatearCamposReporte(loObjetoReporte)
Me.crvrClientes_Tipos.ReportSource = loObjetoReporte
Catch loExcepcion As Exception
Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Error", _
"No se pudo Completar el Proceso: " & loExcepcion.Message, _
vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Error, _
"auto", _
"auto")
End Try
End Sub
Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
Try
loObjetoReporte.Close()
Catch loExcepcion As Exception
End Try
End Sub
End Class
'-------------------------------------------------------------------------------------------'
' Fin del codigo
'-------------------------------------------------------------------------------------------'
' MVP: 08/07 08/: Codigo inicial
'-------------------------------------------------------------------------------------------'
' MVP: 11/07/08: Adición de loObjetoReporte para eliminar los archivos temp en Uranus
'-------------------------------------------------------------------------------------------'
' MVP: 01/08/08: Cambios para multi idioma, mensaje de error y clase padre.
'-------------------------------------------------------------------------------------------'
' YJP: 27/04/09: Agregar combo y estandarizacion
'-------------------------------------------------------------------------------------------'
' CMS: 06/05/09: Ordenamiento
'-------------------------------------------------------------------------------------------'
|
kodeitsolutions/ef-reports
|
rClientes_Tipos.aspx.vb
|
Visual Basic
|
mit
| 4,088
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.42000
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My.Resources
'This class was auto-generated by the StronglyTypedResourceBuilder
'class via a tool like ResGen or Visual Studio.
'To add or remove a member, edit your .ResX file then rerun ResGen
'with the /str option, or rebuild your VS project.
'''<summary>
''' A strongly-typed resource class, for looking up localized strings, etc.
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0"), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.Microsoft.VisualBasic.HideModuleNameAttribute()> _
Friend Module Resources
Private resourceMan As Global.System.Resources.ResourceManager
Private resourceCulture As Global.System.Globalization.CultureInfo
'''<summary>
''' Returns the cached ResourceManager instance used by this class.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager
Get
If Object.ReferenceEquals(resourceMan, Nothing) Then
Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("Humidity_Calculator.Resources", GetType(Resources).Assembly)
resourceMan = temp
End If
Return resourceMan
End Get
End Property
'''<summary>
''' Overrides the current thread's CurrentUICulture property for all
''' resource lookups using this strongly typed resource class.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend Property Culture() As Global.System.Globalization.CultureInfo
Get
Return resourceCulture
End Get
Set(ByVal value As Global.System.Globalization.CultureInfo)
resourceCulture = value
End Set
End Property
End Module
End Namespace
|
haxtivitiez/Humidity_Calculator
|
My Project/Resources.Designer.vb
|
Visual Basic
|
mit
| 2,728
|
#Region "License"
' The MIT License (MIT)
'
' Copyright (c) 2017 Richard L King (TradeWright Software Systems)
'
' 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.
#End Region
Imports BarUtils27
Imports TimeframeUtils27
Imports TradeWright.Trading.Utils.Charts.BarFormatters
Public Class fApplyTemplate
Private mTemplateManager As TemplateManager
Private mTemplateableObject As ISupportsTemplates
Friend Sub New(templateManager As TemplateManager,
templateableObject As ISupportsTemplates)
InitializeComponent()
TemplateSelector1.Initialise(templateManager, templateableObject, False)
mTemplateManager = templateManager
mTemplateableObject = templateableObject
End Sub
Private Sub ApplyButton_Click(sender As Object, e As EventArgs) Handles ApplyButton.Click
If Not TemplateSelector1.IsExistingTemplateSelected Then
Me.Close()
Else
mTemplateableObject.LoadFromTemplate(TemplateSelector1.SelectedTemplate)
End If
Me.Close()
End Sub
Private Sub TemplateSelector1_PropertyChanged(sender As Object, e As System.ComponentModel.PropertyChangedEventArgs) Handles TemplateSelector1.PropertyChanged
If e.PropertyName = "IsReady" Then
ApplyButton.Enabled = TemplateSelector1.IsReady
End If
End Sub
End Class
|
tradewright/tradebuild-platform.net
|
src/TradingUI/fApplyTemplate.vb
|
Visual Basic
|
mit
| 2,381
|
Public Class ConfigForm
Private Sub ConfigForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim Reg As Microsoft.Win32.RegistryKey, s As String
Reg = My.Computer.Registry.CurrentUser.OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Run", False)
s = Reg.GetValue("LaoUnicode.exe", "")
Reg.Close()
' We won't worry about correct path comparisons here
StartWithWindowsCheckbox.Checked = s.Equals(Process.GetCurrentProcess().MainModule.FileName, StringComparison.InvariantCultureIgnoreCase)
End Sub
Private Sub OKButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OKButton.Click
Dim Reg As Microsoft.Win32.RegistryKey
Reg = My.Computer.Registry.CurrentUser.OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Run", False)
If StartWithWindowsCheckbox.Checked Then
Reg.SetValue("LaoUnicode", Process.GetCurrentProcess().MainModule.FileName)
Else
Reg.DeleteValue("LaoUnicode", False)
End If
Reg.Close()
DialogResult = Windows.Forms.DialogResult.OK
End Sub
End Class
|
tavultesoft/keymanweb
|
windows/src/developer/samples/Products/LaoUnicode/LaoUnicode/Config.vb
|
Visual Basic
|
apache-2.0
| 1,185
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class PreviewControl
Inherits System.Windows.Forms.UserControl
'UserControl overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.webPreview = New System.Windows.Forms.WebBrowser
Me.Bar1 = New DevComponents.DotNetBar.Bar
Me.ckbShowAssignedVariables = New DevComponents.DotNetBar.CheckBoxItem
Me.ckbShowVariableName = New DevComponents.DotNetBar.CheckBoxItem
Me.ckbShowValues = New DevComponents.DotNetBar.CheckBoxItem
Me.ckbShowConditions = New DevComponents.DotNetBar.CheckBoxItem
Me.ckbMetaData = New DevComponents.DotNetBar.CheckBoxItem
Me.ckbRoute = New DevComponents.DotNetBar.CheckBoxItem
Me.ckbPageBreak = New DevComponents.DotNetBar.CheckBoxItem
Me.ckbHiddenLV = New DevComponents.DotNetBar.CheckBoxItem
CType(Me.Bar1, System.ComponentModel.ISupportInitialize).BeginInit()
Me.SuspendLayout()
'
'webPreview
'
Me.webPreview.Dock = System.Windows.Forms.DockStyle.Fill
Me.webPreview.Location = New System.Drawing.Point(0, 42)
Me.webPreview.MinimumSize = New System.Drawing.Size(20, 20)
Me.webPreview.Name = "webPreview"
Me.webPreview.Size = New System.Drawing.Size(588, 409)
Me.webPreview.TabIndex = 0
'
'Bar1
'
Me.Bar1.AntiAlias = True
Me.Bar1.DisplayMoreItemsOnMenu = True
Me.Bar1.Dock = System.Windows.Forms.DockStyle.Top
Me.Bar1.EqualButtonSize = True
Me.Bar1.Items.AddRange(New DevComponents.DotNetBar.BaseItem() {Me.ckbShowAssignedVariables, Me.ckbShowVariableName, Me.ckbShowValues, Me.ckbShowConditions, Me.ckbMetaData, Me.ckbRoute, Me.ckbPageBreak, Me.ckbHiddenLV})
Me.Bar1.Location = New System.Drawing.Point(0, 0)
Me.Bar1.Name = "Bar1"
Me.Bar1.Size = New System.Drawing.Size(588, 42)
Me.Bar1.Stretch = True
Me.Bar1.TabIndex = 2
Me.Bar1.TabStop = False
Me.Bar1.Text = "Bar1"
Me.Bar1.ThemeAware = True
Me.Bar1.WrapItemsDock = True
'
'ckbShowAssignedVariables
'
Me.ckbShowAssignedVariables.Name = "ckbShowAssignedVariables"
Me.ckbShowAssignedVariables.Text = "Assigned Variables"
Me.ckbShowAssignedVariables.ThemeAware = True
'
'ckbShowVariableName
'
Me.ckbShowVariableName.Name = "ckbShowVariableName"
Me.ckbShowVariableName.Text = "Variable Names"
Me.ckbShowVariableName.ThemeAware = True
'
'ckbShowValues
'
Me.ckbShowValues.Name = "ckbShowValues"
Me.ckbShowValues.Text = "Values of Legal Values "
Me.ckbShowValues.ThemeAware = True
'
'ckbShowConditions
'
Me.ckbShowConditions.Name = "ckbShowConditions"
Me.ckbShowConditions.Text = "Conditions"
Me.ckbShowConditions.ThemeAware = True
'
'ckbMetaData
'
Me.ckbMetaData.Name = "ckbMetaData"
Me.ckbMetaData.Text = "Metadata"
Me.ckbMetaData.ThemeAware = True
'
'ckbRoute
'
Me.ckbRoute.Name = "ckbRoute"
Me.ckbRoute.Text = "Route"
Me.ckbRoute.ThemeAware = True
'
'ckbPageBreak
'
Me.ckbPageBreak.Name = "ckbPageBreak"
Me.ckbPageBreak.Text = "Page Breaks"
Me.ckbPageBreak.ThemeAware = True
'
'ckbHiddenLV
'
Me.ckbHiddenLV.Name = "ckbHiddenLV"
Me.ckbHiddenLV.Text = "Hidden Legal Values"
Me.ckbHiddenLV.ThemeAware = True
'
'PreviewControl
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.Controls.Add(Me.webPreview)
Me.Controls.Add(Me.Bar1)
Me.Name = "PreviewControl"
Me.Size = New System.Drawing.Size(588, 451)
CType(Me.Bar1, System.ComponentModel.ISupportInitialize).EndInit()
Me.ResumeLayout(False)
End Sub
Friend WithEvents webPreview As System.Windows.Forms.WebBrowser
Friend WithEvents Bar1 As DevComponents.DotNetBar.Bar
Friend WithEvents ckbShowAssignedVariables As DevComponents.DotNetBar.CheckBoxItem
Friend WithEvents ckbShowVariableName As DevComponents.DotNetBar.CheckBoxItem
Friend WithEvents ckbShowValues As DevComponents.DotNetBar.CheckBoxItem
Friend WithEvents ckbShowConditions As DevComponents.DotNetBar.CheckBoxItem
Friend WithEvents ckbMetaData As DevComponents.DotNetBar.CheckBoxItem
Friend WithEvents ckbRoute As DevComponents.DotNetBar.CheckBoxItem
Friend WithEvents ckbPageBreak As DevComponents.DotNetBar.CheckBoxItem
Friend WithEvents ckbHiddenLV As DevComponents.DotNetBar.CheckBoxItem
End Class
|
QMDevTeam/QMDesigner
|
UI/UserControls/PreviewControl.Designer.vb
|
Visual Basic
|
apache-2.0
| 5,562
|
' Copyright (c) 2015 ZZZ Projects. All rights reserved
' Licensed under MIT License (MIT) (https://github.com/zzzprojects/Z.ExtensionMethods)
' Website: http://www.zzzprojects.com/
' Feedback / Feature Requests / Issues : http://zzzprojects.uservoice.com/forums/283927
' All ZZZ Projects products: Entity Framework Extensions / Bulk Operations / Extension Methods /Icon Library
Public Module Extensions_206
''' <summary>
''' Returns the angle whose cosine is the specified number.
''' </summary>
''' <param name="d">
''' A number representing a cosine, where must be greater than or equal to -1, but less than or
''' equal to 1.
''' </param>
''' <returns>An angle, ?, measured in radians, such that 0 ????-or- if < -1 or > 1 or equals .</returns>
<System.Runtime.CompilerServices.Extension> _
Public Function Acos(d As [Double]) As [Double]
Return Math.Acos(d)
End Function
End Module
|
huoxudong125/Z.ExtensionMethods
|
src (VB.NET)/Z.ExtensionMethods.VB/Z.Core/System.Double/System.Math/Double.Acos.vb
|
Visual Basic
|
mit
| 927
|
' Copyright (c) 2015 ZZZ Projects. All rights reserved
' Licensed under MIT License (MIT) (https://github.com/zzzprojects/Z.ExtensionMethods)
' Website: http://www.zzzprojects.com/
' Feedback / Feature Requests / Issues : http://zzzprojects.uservoice.com/forums/283927
' All ZZZ Projects products: Entity Framework Extensions / Bulk Operations / Extension Methods /Icon Library
Imports System.Reflection
Public Module Extensions_826
''' <summary>
''' A T extension method that gets property value.
''' </summary>
''' <typeparam name="T">Generic type parameter.</typeparam>
''' <param name="this">The @this to act on.</param>
''' <param name="propertyName">Name of the property.</param>
''' <returns>The property value.</returns>
<System.Runtime.CompilerServices.Extension> _
Public Function GetPropertyValue(Of T)(this As T, propertyName As String) As Object
Dim type As Type = this.[GetType]()
Dim [property] As PropertyInfo = type.GetProperty(propertyName, BindingFlags.[Public] Or BindingFlags.NonPublic Or BindingFlags.Instance Or BindingFlags.[Static])
Return [property].GetValue(this, Nothing)
End Function
End Module
|
zzzprojects/Z.ExtensionMethods
|
src (VB.NET)/Z.ExtensionMethods.VB/Z.Reflection/System.Object/Object.GetPropertyValue.vb
|
Visual Basic
|
mit
| 1,151
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.