Compare commits

..
2 Commits
Author SHA1 Message Date
nobody 3215bf8472 This commit was manufactured by cvs2svn to create branch 'C5'.
svn path=/branches/C5/mcs/; revision=32379
2004-08-16 15:34:45 +00:00
nobody 9a8905dec1 This commit was manufactured by cvs2svn to create branch 'C5'.
svn path=/branches/C5/mcs/; revision=32375
2004-08-16 15:30:03 +00:00
290 changed files with 43045 additions and 107464 deletions

No files matched your search

+10 -11
View File
@@ -1,26 +1,25 @@
Makefile
Makefile.in
_tmpinst
aclocal.m4
autom4te.cache
config.cache
config.guess
config.h
config.h.in
config.h.in
config.log
config.status
config.sub
configure
libtool
ltconfig
ltmain.sh
mint.pc
ltconfig
Makefile
Makefile.in
mono-*.tar.gz
mono.pc
mono.spec
semantic.cache
stamp-h
stamp-h.in
mono.pc
mono.spec
autom4te.cache
mint.pc
stamp-h1
tmpinst-dir.stamp
config.h.in
_tmpinst
tmpinst-dir.stamp
-204
View File
@@ -1,207 +1,3 @@
2004-11-08 Jonathan Pryor <[email protected]>
* configure.in: Add new function/header/type checks for use by
MonoPosixHelper (the support directory).
* support/Makefile.am: Add sys-sendfile.c to the build.
* support/dirent.c, support/fcntl.c, support/unistd.c: Remove compile-time
checks for -64 apis (pread64, etc.), as they're superfluous. GLibc
#defines the functions to the appropriate -64 counterpart when necessary,
and Darwin is intrinsically large-file-aware, so manual checking on my
part is redundant and unnecessary.
* support/grp.c: Add checks for non-portable functions getgrnam_r,
getgrgid_r.
* support/pwd.c: Add checks for non-portable functions getpwnam_r,
getpwuid_r.
* support/map.c: Remove <poll.h> include. Building on Tigar (Mac OS X 10.4
beta) breaks when both <poll.h> and <sys/poll.h> are included, so only use
<sys/poll.h>.
* support/mph.h: Clean up macro handling for type overflow checking.
2004-11-08 Raja R Harinath <[email protected]>
* configure.in (mcs_topdir, mcs_topdir_from_srcdir): New 'subst'ed
variables. Used to support both an in-tree mcs/ and a sibling
mcs/ directory.
* Makefile.am (mcs_topdir): Remove.
(dist-hook): Distribute mcs/ as a subdirectory.
* runtime/Makefile.am ($(monoone_DATA) $(monotwo_DATA) $(monobins_DATA)):
Use mcs_topdir and mcs_topdir_from_srcdir.
* runtime/net_1_1/Makefile.am (mscorlib.dll $(gac_assemblies) $(mdb_files)):
Likewise.
(all-local): Depend on $(mdb_files) too.
* runtime/net_2_0/Makefile.am: Likewise.
2004-11-05 Zoltan Varga <[email protected]>
* runtime/net_2_0/Makefile.am (install-data-local):
* runtime/net_1_1/Makefile.am (install-data-local): Applied patch
from Götz Waschk ([email protected]). Make this work
with DESTDIR.
2004-11-05 Jonathan Pryor <[email protected]>
* support/.cvsignore: Ignore generated files.
* support/Makefile.am: Add new INCLUDE directives (for glib headers),
source; bump library version (so we don't clobber previous versions of
libMonoPosixHelper.so).
* support/dirent.c: New file; <dirent.h> wrapper functions;
BSD portability fixes.
* support/errno.c: New file; <errno.h> wrapper functions
* support/fcntl.c: New file; <fcntl.h> wrapper functions;
BSD portability fixes.
* support/grp.c: New file; <grp.h> wrapper functions;
BSD portability fixes.
* support/map.c: Updated macro mapping functions (more enums mapped, more
error checking, etc.).
* support/map.h: Updated macro mapping functions
* support/old-map.c: Previous map.c implementation, for backward compatibility
Remove spurious warning about redefining _GNU_SOURCE.
* support/old-map.h: Previous map.h implementation, for backward compatibility
* support/mph.h: New file; Utility types, macros;
BSD portability fixes.
* support/pwd.c: New file; <pwd.h> wrapper functions;
BSD portability fixes.
* support/stdio.c: New file; <stdio.h> wrapper functions
* support/stdlib.c: New file; <stdlib.h> wrapper functions
* support/sys-mman.c: New file; <sys/mman.h> wrapper functions
* support/sys-mount.c: New file; <sys/mount.h> wrapper functions;
BSD portability fixes.
* support/sys-sendfile.c: New file; <sys/sendfile.h> wrapper functions;
BSD portability fixes.
* support/sys-stat.c: New file; <sys/stat.h> wrapper functions
* support/sys-wait.c: New file; <sys/wait.h> wrapper functions
* support/time.c: New file; <time.h> wrapper functions;
BSD portability fixes.
* support/unistd.c: New file; <unistd.h> wrapper functions;
BSD portability fixes.
2004-10-31 Zoltan Varga <[email protected]>
* configure.in: Fix up --with-jit=no so it actually works. Fixes
#61320.
2004-10-29 Gonzalo Paniagua Javier <[email protected]>
* man/mono.1: documented MONO_THREADS_PER_CPU.
2004-10-29 Zoltan Varga <[email protected]>
* configure.in: Add INCLUDED_LIBGC automake conditional.
2004-10-24 Jonathan Pryor <[email protected]>
* man/mono.1: Add documentation for the MONO_TRACE environment variable.
2004-10-14 Joe Shaw <[email protected]>
* man/mono.1: Fix the syntax of the M: trace syntax
2004-10-10 Zoltan Varga <[email protected]>
* configure.in: Add some checks for cygwin weirdness.
2004-10-08 Zoltan Varga <[email protected]>
* support/Makefile.am (libMonoPosixHelper_la_SOURCES): Do not build
zlib_macros if zlib.h is not found.
* configure.in: Add check for zlib.h.
2004-09-28 Neale Ferguson <[email protected]>
* mini-s390.c: Fix AND_IMM/OR_IMM/DIV_IMM/REM_IMM
2004-09-28 Raja R Harinath <[email protected]>
* Makefile.am ($(tmpinst)/bin/pedump): New.
(mcs-do-run-test-profiles): Depend on it.
2004-09-27 Raja R Harinath <[email protected]>
* Makefile.am (mono-do-testjit): New target, unused for now. Runs
the mono testsuite in tests/.
(tmpinst-dir): Create etc/mono/2.0.
($(tmpinst)/bin/ilasm, $(tmpinst)/etc/mono/2.0/machine.config): New.
2004-09-21 Neale Ferguson <[email protected]>
* configure.in: Cater for S/390 on Linux
2004-09-21 <[email protected]>
* configure.in: Link with ole32 on windows.
2004-09-20 Jackson Harper <[email protected]>
* support/map.c/h: Add poll events map functions. Use values
instead of names for defines.
2004-09-17 Martin Baulig <[email protected]>
* Makefile.am (mcs-do-compiler-tests): Reverted Raja's latest
change in this target.
2004-09-14 Raja R Harinath <[email protected]>
* Makefile.am (mcs-do-full-build): Pass NO_SIGN_ASSEMBLIES=yes to
reduce the number of passes. We will get the assemblies signed in
the 'populate-runtime-subdir' phase.
(mcs-do-run-test-profiles): Rename from mcs-do-run-tests. Use
'test-profiles' to test all profiles.
(mcs-do-compiler-tests): Use 'compiler-tests' target in mcs/.
(bootstrap-check): Update.
* runtime/Makefile.am ($(monoone_DATA) $(monotwo_DATA) $(monobins_DATA)):
Simplify.
2004-09-10 Zoltan Varga <[email protected]>
* Makefile.am (populate-runtime-subdir): Avoid -path argument to find
since it is not supported on solaris.
2004-09-03 Martin Baulig <[email protected]>
* Makefile.am (bootstrap-world): New target.
2004-09-02 Martin Baulig <[email protected]>
* runtime/net_1_1/Makefile.am (install-data-local): Install
mscorlib.dll.mdb into $(corlibdir).
* runtime/net_2_0/Makefile.am: Likewise.
2004-08-30 Zoltan Varga <[email protected]>
* scripts/mcs.in: Remove obsolete comment.
2004-08-27 Lluis Sanchez Gual <[email protected]>
* data/net_1_1/DefaultWsdlHelpGenerator.aspx: Little fix.
* data/net_2_0/DefaultWsdlHelpGenerator.aspx: Added information about
basic profile compliance.
* data/net_2_0/machine.config: Use 2.0 assembly versions.
2004-08-26 Raja R Harinath <[email protected]>
* Makefile.am (mcs-do-run-test): Depend on '$(tmpinst)/bin/mbas'.
($(tmpinst)/bin/mbas): Create temporary wrapper file, so that the
testcases pick the built 'mbas.exe'.
2004-08-17 Zoltan Varga <[email protected]>
* mono/os/gc_wrapper.h: Only use thread local alloc if using the included libgc, since the
stock one has broken headers.
* configure.in (PLATFORM_WIN32): Make the included libgc the default on windows.
2004-08-17 Dick Porter <[email protected]>
* configure.in: Correct intl library for FreeBSD and OpenBSD.
Fixes bug 62884, patch by Tom McLaughlin ([email protected]).
2004-08-16 Zoltan Varga <[email protected]>
* configure.in: Set new automake variable LIBGC_STATIC_LIBS.
2004-08-14 Zoltan Varga <[email protected]>
* configure.in (HAVE_KW_THREAD): Pass USE_COMPILER_TLS to libgc if
+9 -46
View File
@@ -9,11 +9,6 @@ DIST_SUBDIRS = libgc mono ikvm-jni docs data runtime scripts man samples support
EXTRA_DIST= mono.pc.in mono.spec.in mint.pc.in
# Distribute the 'mcs' tree too
dist-hook:
test -d $(distdir)/mcs || mkdir $(distdir)/mcs
d=`cd $(distdir)/mcs && pwd`; cd $(mcs_topdir) && $(MAKE) distdir=$$d dist-recursive
pkgconfigdir = $(libdir)/pkgconfig
if JIT_SUPPORTED
pkgconfig_DATA= mono.pc mint.pc
@@ -28,6 +23,8 @@ DISTCLEANFILES= mono.pc mint.pc
# problems by doing the compilation in the right order.
#
mcs_topdir=$(top_srcdir)/../mcs
.PHONY: bootstrap faststrap fasterstrap bootstrap-clean bootstrap-check get-monolite-latest monolite-bootstrap
.PHONY: tmpinst-dir tmpinst-mcs-basic-build tmpinst-mcs-short-build tmpinst-mcs-full-build tmpinst-monolite
.PHONY: mono-do-runtime-only mcs-do-basic-build mcs-do-short-build mcs-do-full-build mcs-do-clean-profiles mcs-do-run-test
@@ -82,13 +79,7 @@ fasterstrap: tmpinst-mcs-full-build
$(MAKE)
bootstrap-clean: clean mcs-do-clean-profiles
bootstrap-check: check mcs-do-run-test-profiles #mono-do-testjit
mono-do-testjit: $(tmpinst)/bin/ilasm
tmpinst=`cd $(tmpinst) && pwd` ; \
PATH=$$tmpinst/bin:$$PATH ; export PATH ; \
cd mono/tests && $(MAKE) test
bootstrap-check: check mcs-do-run-test
# building with monolite
@@ -100,14 +91,6 @@ monolite-bootstrap: tmpinst-monolite mono-do-runtime-only
$(MAKE) tmpinst-mcs-short-build
$(MAKE) fasterstrap
compiler-tests:
$(MAKE) mcs-do-clean-profiles
$(MAKE) bootstrap
$(MAKE) mcs-do-compiler-tests
bootstrap-world: compiler-tests
$(MAKE) install
# internal targets
tmpinst-mcs-basic-build: mcs-do-basic-build tmpinst-dir
@@ -148,20 +131,15 @@ mcs-do-short-build:
mcs-do-full-build:
tmpinst=`cd $(tmpinst) && pwd` ; \
PATH=$$tmpinst/bin:$$PATH ; export PATH ; \
cd $(mcs_topdir) && $(MAKE) NO_SIGN_ASSEMBLY=yes all-profiles
cd $(mcs_topdir) && $(MAKE) all-profiles
mcs-do-clean-profiles:
cd $(mcs_topdir) && $(MAKE) clean-profiles
mcs-do-run-test-profiles: tmpinst-dir $(tmpinst)/bin/mbas $(tmpinst)/bin/ilasm $(tmpinst)/bin/pedump
mcs-do-run-test: tmpinst-dir
tmpinst=`cd $(tmpinst) && pwd` ; \
PATH=$$tmpinst/bin:$$PATH ; export PATH ; \
cd $(mcs_topdir) && $(MAKE) run-test-profiles
mcs-do-compiler-tests:
tmpinst=`cd $(tmpinst) && pwd` ; \
PATH=$$tmpinst/bin:$$PATH ; export PATH ; \
cd $(mcs_topdir) && $(MAKE) compiler-tests
cd $(mcs_topdir) && $(MAKE) PROFILE=default run-test
populate-runtime-subdir:
test -n '$(populate_profiles)'
@@ -173,16 +151,15 @@ populate-runtime-subdir:
cd $(mcs_topdir) && \
$(MAKE) PROGRAM_INSTALL_DIR=$$srcdir/runtime PROFILE=$$2 LIBRARY_INSTALL_DIR=$$srcdir/runtime/$$3 prefix=$$tmpinst/prefix install ) || exit 1 ; \
done
find $(tmpinst)/prefix -type f -name '*jay*' -exec rm -f '{}' ';'
for i in `find $(tmpinst)/prefix -type d -name '*jay*' -print`; do rm -f $$i/*; done
find $(tmpinst)/prefix -type f -path '*/jay*' -exec rm -f '{}' ';'
test -z "`find $(tmpinst)/prefix -type f -print`"
rm -rf $(tmpinst)/prefix
tmpinst-dir:
mkdir -p $(tmpinst) $(tmpinst)/bin $(tmpinst)/lib $(tmpinst)/etc/mono/1.0 $(tmpinst)/etc/mono/2.0
mkdir -p $(tmpinst) $(tmpinst)/bin $(tmpinst)/lib $(tmpinst)/etc/mono/1.0
$(MAKE) tmpinst-dir-contents
tmpinst-dir-contents: $(tmpinst)/bin/mono $(tmpinst)/bin/mcs $(tmpinst)/etc/mono/1.0/machine.config $(tmpinst)/etc/mono/2.0/machine.config
tmpinst-dir-contents: $(tmpinst)/bin/mono $(tmpinst)/bin/mcs $(tmpinst)/etc/mono/1.0/machine.config
if PLATFORM_WIN32
@@ -209,28 +186,14 @@ $(tmpinst)/bin/mono: $(srcdir)/Makefile.am
endif
$(tmpinst)/bin/pedump: $(srcdir)/Makefile.am
(b=`pwd`; echo '#! /bin/sh'; echo 'exec "'"$$b/libtool"'" --mode=execute "'"$$b/mono/metadata/pedump"'" "$$@"') > $@
chmod +x $@
$(tmpinst)/bin/mcs: $(srcdir)/Makefile.am
(t=`cd $(tmpinst) && pwd`; echo '#! /bin/sh'; echo 'exec "'"$$t/bin/mono"'" "'"$$t/lib/mcs.exe"'" "$$@"') > $@
chmod +x $@
# Used only by 'bootstrap-check' -- so, can safely use runtime/.
$(tmpinst)/bin/mbas $(tmpinst)/bin/ilasm: $(srcdir)/Makefile.am
t=`cd $(tmpinst) && pwd`; r=`cd $(srcdir)/runtime && pwd`; \
( echo '#! /bin/sh'; echo 'exec "'"$$t/bin/mono"'" "'"$$r/$(@F).exe"'" "$$@"' ) > $@
chmod +x $@
$(tmpinst)/etc/mono/1.0/machine.config: $(srcdir)/data/net_1_1/machine.config
rm -f $@
srcdir=`cd $(srcdir) && pwd`; cd $(tmpinst)/etc/mono/1.0 && $(LN_S) $$srcdir/data/net_1_1/machine.config machine.config
$(tmpinst)/etc/mono/2.0/machine.config: $(srcdir)/data/net_2_0/machine.config
rm -f $@
srcdir=`cd $(srcdir) && pwd`; cd $(tmpinst)/etc/mono/2.0 && $(LN_S) $$srcdir/data/net_2_0/machine.config machine.config
# Obsolete target -- don't use.
.PHONY: fullbuild
fullbuild: bootstrap
+7 -76
View File
@@ -1,7 +1,7 @@
AC_INIT(README)
AC_CANONICAL_SYSTEM
AM_CONFIG_HEADER(config.h)
AM_INIT_AUTOMAKE(mono,1.1.2.99)
AM_INIT_AUTOMAKE(mono,1.1.1)
AM_MAINTAINER_MODE
AC_PROG_LN_S
@@ -42,7 +42,7 @@ case "$host" in
*-*-mingw*|*-*-cygwin*)
platform_win32=yes
AC_DEFINE(PLATFORM_WIN32,1,[Platform is Win32])
CC="gcc -mno-cygwin -g"
CC="gcc -mno-cygwin"
HOST_CC="gcc"
# So libgc configure gets -mno-cygwin
export CC
@@ -51,10 +51,11 @@ case "$host" in
CPPFLAGS="$CPPFLAGS -DWIN32_THREADS"
libdl=
libgc_threads=win32
gc_default=included
with_nptl=default
gc_default=boehm
with_nptl=no
with_sigaltstack=no
LN_S=cp
;;
*-*-*netbsd*)
platform_win32=no
@@ -230,10 +231,6 @@ AM_CONDITIONAL(NO_VERSION_SCRIPT, test x$no_version_script = xyes)
AC_CHECK_HEADERS(sys/filio.h sys/sockio.h netdb.h utime.h semaphore.h sys/un.h)
AC_CHECK_HEADER(zlib.h, [have_zlib=yes], [have_zlib=no])
AM_CONDITIONAL(HAVE_ZLIB, test x$have_zlib = xyes)
# for mono/metadata/debug-symfile.c
AC_CHECK_HEADERS(elf.h)
@@ -259,19 +256,6 @@ else
fi
CFLAGS="$CFLAGS -g $WARN"
# Where's the 'mcs' source tree?
if test -d $srcdir/mcs; then
mcsdir=mcs
else
mcsdir=../mcs
fi
mcs_topdir='$(top_srcdir)/'$mcsdir
mcs_topdir_from_srcdir='$(top_builddir)/'$mcsdir
AC_SUBST([mcs_topdir])
AC_SUBST([mcs_topdir_from_srcdir])
AC_PATH_PROG(PKG_CONFIG, pkg-config, no)
if test "x$PKG_CONFIG" = "xno"; then
AC_MSG_ERROR([You need to install pkg-config])
@@ -312,27 +296,6 @@ AC_SUBST(GLIB_LIBS)
AC_SUBST(GMODULE_CFLAGS)
AC_SUBST(GMODULE_LIBS)
if test x$platform_win32 = xyes; then
AC_MSG_CHECKING(for cygwin glib2-dev package)
if [ cygcheck --f /usr/lib/libglib-2.0.dll.a | grep -q glib2-devel ]; then
AC_MSG_RESULT(found)
AC_MSG_ERROR([Mono cannot be built with the cygwin glib2-devel package installed, because that package doesn't work with -mno-cygwin. Please uninstall it then re-run configure.])
else
AC_MSG_RESULT(not found, ok)
fi
AC_MSG_CHECKING(for broken gwin32.h)
glib_include=`$PKG_CONFIG --cflags-only-I glib-2.0 | sed -e 's/ -I.*//g' | sed -e 's/-I//g'`
if test -f $glib_include/glib/gwin32.h; then
if [ grep ftruncate $glib_include/glib/gwin32.h | grep -q define ]; then
AC_MSG_RESULT(failed)
hashmark='#'
AC_MSG_ERROR([Your version of gwin32.h is broken and will cause compilation errors when building mono. Please fix it by deleting the line: '$hashmark define ftruncate...' from '$glib_include/glib/gwin32.h' then re-run configure.])
fi
fi
AC_MSG_RESULT(ok)
fi
AC_ARG_WITH(gc, [ --with-gc=boehm,included,none],[gc=$with_gc],[gc=$gc_default])
# Enable support for fast thread-local storage
@@ -367,7 +330,6 @@ AM_CONDITIONAL(WITH_BUNDLE, test x$with_bundle != xno)
LIBGC_CFLAGS=
LIBGC_LIBS=
LIBGC_STATIC_LIBS=
libgc_dir=
case "x$gc" in
xboehm|xbohem|xyes)
@@ -384,7 +346,6 @@ case "x$gc" in
AC_DEFINE(HAVE_BOEHM_GC)
AC_SUBST(HAVE_BOEHM_GC)
LIBGC_LIBS="-lgc $libdl"
LIBGC_STATIC_LIBS="$LIBGC_LIBS"
# AC_CHECK_FUNCS does not work for some reason...
AC_CHECK_LIB(gc, GC_gcj_malloc, found_gcj_malloc="yes",,$libdl)
@@ -407,7 +368,6 @@ case "x$gc" in
LIBGC_CFLAGS='-I$(top_srcdir)/libgc/include'
LIBGC_LIBS='$(top_builddir)/libgc/libmonogc.la'
LIBGC_STATIC_LIBS='$(top_builddir)/libgc/libmonogc-static.la'
AC_DEFINE(HAVE_BOEHM_GC)
AC_SUBST(HAVE_BOEHM_GC)
@@ -435,7 +395,6 @@ ac_configure_args="$ac_configure_args --disable-embed-check --with-libgc-threads
AM_CONDITIONAL(INCLUDED_LIBGC, test x$use_included_gc = xyes)
AC_SUBST(LIBGC_CFLAGS)
AC_SUBST(LIBGC_LIBS)
AC_SUBST(LIBGC_STATIC_LIBS)
AC_SUBST(libgc_dir)
dnl
@@ -1020,25 +979,10 @@ if test x$platform_win32 = xno; then
fi
AC_DEFINE_UNQUOTED(SIGVAL_PTR,$SIGVAL_PTR,[Pointer field name in 'union sigval'])
fi
dnl **********************************
dnl *** Checks for MonoPosixHelper ***
dnl **********************************
AC_CHECK_FUNCS(posix_fadvise)
AC_CHECK_FUNCS(posix_fallocate)
AC_CHECK_FUNCS(fgetgrent)
AC_CHECK_FUNCS(fgetpwent)
AC_CHECK_FUNCS(fgetpwent)
AC_CHECK_HEADERS(sys/sendfile.h)
AC_CHECK_FUNCS(sendfile)
AC_CHECK_FUNCS(stime)
AC_CHECK_FUNCS(ttyname_r)
AC_CHECK_SIZEOF(size_t)
else
jdk_headers_found=no
AC_CHECK_LIB(ws2_32, main, LIBS="$LIBS -lws2_32", AC_ERROR(bad mingw install?))
AC_CHECK_LIB(psapi, main, LIBS="$LIBS -lpsapi", AC_ERROR(bad mingw install?))
AC_CHECK_LIB(ole32, main, LIBS="$LIBS -lole32", AC_ERROR(bad mingw install?))
dnl *********************************
dnl *** Check for struct ip_mreqn ***
@@ -1310,11 +1254,7 @@ case "$host" in
esac
AC_ARG_WITH(jit, [ --with-jit=yes,no If you want to build scripts that default to the JIT],[
if test x$withval = xyes; then
jit_wanted=true
else
jit_wanted=false
fi
jit_wanted=true
])
USEJIT=false
@@ -1343,14 +1283,6 @@ case "$host" in
LIBC="libc.so.12"
INTL="libintl.so.0"
;;
*-*-*freebsd*)
LIBC="libc.so"
INTL="libintl.so"
;;
*-*-*openbsd*)
LIBC="libc.so"
INTL="libintl.so"
;;
esac
AC_SUBST(libsuffix)
@@ -1438,7 +1370,6 @@ AM_CONDITIONAL(S390x, test x$TARGET = xS390x)
AM_CONDITIONAL(HPPA, test x$TARGET = xHPPA)
AM_CONDITIONAL(JIT_SUPPORTED, test x$JIT_SUPPORTED = xyes)
AM_CONDITIONAL(INCLUDED_LIBGC, test x$gc = xincluded)
AC_SUBST(LIBC)
AC_SUBST(INTL)
@@ -1500,7 +1431,7 @@ tools/locale-builder/Makefile
])
echo "
mcs source: $mcs_topdir
GC: $gc
ICU: $enable_icu
TLS: $with_tls
File diff suppressed because it is too large. Load diff
+4083 -3302
View File
File diff suppressed because it is too large. Load diff
+216
View File
@@ -0,0 +1,216 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="appSettings" type="System.Configuration.NameValueFileSectionHandler, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<section name="system.diagnostics" type="System.Diagnostics.DiagnosticsConfigurationHandler, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<section name="system.runtime.remoting" type="System.Configuration.IgnoreSectionHandler, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowLocation="false"/>
<sectionGroup name="system.web">
<section name="httpHandlers"
type="System.Web.Configuration.HttpHandlersSectionHandler, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<section name="httpModules"
type="System.Web.Configuration.HttpModulesConfigurationHandler, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<section name="machineKey"
type="System.Web.Configuration.MachineKeyConfigHandler, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<section name="authentication"
type="System.Web.Configuration.AuthenticationConfigHandler, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<section name="authorization"
type="System.Web.Configuration.AuthorizationConfigHandler, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<section name="globalization"
type="System.Web.Configuration.GlobalizationConfigurationHandler, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<section name="sessionState"
type="System.Web.SessionState.SessionStateSectionHandler, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<section name="trace"
type="System.Web.Configuration.TraceConfigurationHandler, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<section name="webServices"
type="System.Web.Services.Configuration.WebServicesConfigurationSectionHandler, System.Web.Services, Version=1.0.5000.0 Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<section name="webControls"
type="System.Web.Configuration.WebControlsSectionHandler, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<section name="compilation"
type="System.Web.Configuration.CompilationConfigurationHandler, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<section name="httpRuntime"
type="System.Web.Configuration.HttpRuntimeConfigurationHandler, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<section name="customErrors"
type="System.Web.Configuration.CustomErrorsConfigHandler, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<section name="pages"
type="System.Web.Configuration.PagesConfigurationHandler, System.Web, Version=1.0.5000.0, Culture=neutral" />
<section name="clientTarget"
type="System.Web.Configuration.ClientTargetSectionHandler, System.Web, Version=1.0.5000.0, Culture=neutral" />
</sectionGroup>
<sectionGroup name="system.net">
<section name="settings"
type="System.Net.Configuration.NetConfigurationHandler, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<section name="connectionManagement"
type="System.Net.Configuration.ConnectionManagementHandler, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<section name="authenticationModules"
type="System.Net.Configuration.NetAuthenticationModuleHandler, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<section name="defaultProxy"
type="System.Net.Configuration.DefaultProxyHandler, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<section name="webRequestModules"
type="System.Net.Configuration.WebRequestModuleHandler, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</sectionGroup>
<section name="system.drawing" type="System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</configSections>
<system.net>
<connectionManagement>
<add address="*" maxconnection="2" />
</connectionManagement>
<authenticationModules>
<add type="System.Net.BasicClient, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<add type="System.Net.DigestClient, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<add type="System.Net.NtlmClient, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</authenticationModules>
<defaultProxy>
<proxy />
<!-- bypassonlocal and proxyaddress are ok -->
<!-- usessystemdefault is not supported -->
</defaultProxy>
<webRequestModules>
<add prefix="http" type="System.Net.HttpRequestCreator, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<add prefix="https" type="System.Net.HttpRequestCreator, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<add prefix="file" type="System.Net.FileWebRequestCreator, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</webRequestModules>
<settings>
<ipv6 enabled="false"/>
</settings>
</system.net>
<system.web>
<httpHandlers>
<add verb="*" path="Trace.axd" type="System.Web.Handlers.TraceHandler, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add verb="*" path="*.aspx" type="System.Web.UI.PageHandlerFactory, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add verb="*" path="*.asmx" validate="false" type="System.Web.Services.Protocols.WebServiceHandlerFactory, System.Web.Services, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add verb="*" path="*.ashx" type="System.Web.UI.SimpleHandlerFactory, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add verb="GET" path="WebResource.axd" type="System.Web.Handlers.AssemblyResourceLoader, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add verb="*" path="*.asax" type="System.Web.HttpForbiddenHandler, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add verb="*" path="*.ascx" type="System.Web.HttpForbiddenHandler, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add verb="*" path="*.config" type="System.Web.HttpForbiddenHandler, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add verb="*" path="*.cs" type="System.Web.HttpForbiddenHandler, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add verb="*" path="*.rem" type="System.Runtime.Remoting.Channels.Http.HttpRemotingHandlerFactory, System.Runtime.Remoting, Culture=neutral, PublicKeyToken=b77a5c561934e089" validate="false" />
<add verb="*" path="*.soap" type="System.Runtime.Remoting.Channels.Http.HttpRemotingHandlerFactory, System.Runtime.Remoting, Culture=neutral, PublicKeyToken=b77a5c561934e089" validate="false" />
<add verb="GET,HEAD" path="*" type="System.Web.StaticFileHandler, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add verb="*" path="*" type="System.Web.HttpMethodNotAllowedHandler, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</httpHandlers>
<httpModules>
<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add name="UrlAuthorization" type="System.Web.Security.UrlAuthorizationModule, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add name="Session" type="System.Web.SessionState.SessionStateModule, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add name="OutputCache" type="System.Web.Caching.OutputCacheModule, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</httpModules>
<authentication mode="Forms">
<forms name=".MONOAUTH" loginUrl="login.aspx" protection="All" timeout="30" path="/">
<credentials passwordFormat="Clear">
<!--<user name="gonzalo" password="gonz"/>-->
</credentials>
</forms>
</authentication>
<machineKey validationKey="AutoGenerate" decryptionKey="AutoGenerate" validation="SHA1" />
<globalization requestEncoding="utf-8"
responseEncoding="utf-8"
fileEncoding="utf-8"/>
<!--
culture="en-US"
uiculture="en-US" />
-->
<sessionState mode="InProc" />
<webServices>
<protocols>
<add name="HttpSoap"/>
<add name="HttpPost"/>
<add name="HttpGet"/>
<add name="Documentation"/>
</protocols>
<wsdlHelpGenerator href="DefaultWsdlHelpGenerator.aspx" />
</webServices>
<webControls clientScriptsLocation="/web_scripts" />
<compilation debug="false" defaultLanguage="c#">
<compilers>
<compiler language="cs;c#;csharp" extension=".cs" warningLevel="1" compilerOptions=""
type="Microsoft.CSharp.CSharpCodeProvider, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb"
warningLevel="1" compilerOptions=""
type="Microsoft.VisualBasic.VBCodeProvider, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</compilers>
<assemblies>
<!--<add assembly="mscorlib" /> -->
<add assembly="System" />
<add assembly="System.Xml" />
<add assembly="System.Data" />
<add assembly="System.Web" />
<add assembly="System.Web.Services" />
<add assembly="System.Drawing" />
<add assembly="*" /> <!-- Add assemblies in bin directory -->
</assemblies>
</compilation>
<httpRuntime executionTimeout="90"
maxRequestLength="4096"
useFullyQualifiedRedirectUrl="false"
minFreeThreads="8"
minLocalRequestFreeThreads="4"
appRequestQueueLimit="100" />
<pages buffer="true"
enableSessionState="true"
autoEventWireup="true"
validateRequest="true" />
<clientTarget>
<add alias="ie5" userAgent="Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 4.0)" />
<add alias="ie4" userAgent="Mozilla/4.0 (compatible; MSIE 4.0; Windows NT 4.0)" />
<add alias="uplevel" userAgent="Mozilla/4.0 (compatible; MSIE 4.0; Windows NT 4.0)" />
<add alias="downlevel" userAgent="Unknown" />
</clientTarget>
</system.web>
<system.runtime.remoting>
<application>
<channels>
<channel ref="http client" displayName="http client (delay loaded)" delayLoadAsClientChannel="true" />
<channel ref="tcp client" displayName="tcp client (delay loaded)" delayLoadAsClientChannel="true" />
</channels>
</application>
<channels>
<channel id="http" type="System.Runtime.Remoting.Channels.Http.HttpChannel, System.Runtime.Remoting, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<channel id="http client" type="System.Runtime.Remoting.Channels.Http.HttpClientChannel, System.Runtime.Remoting, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<channel id="http server" type="System.Runtime.Remoting.Channels.Http.HttpServerChannel, System.Runtime.Remoting, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<channel id="tcp" type="System.Runtime.Remoting.Channels.Tcp.TcpChannel, System.Runtime.Remoting, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<channel id="tcp client" type="System.Runtime.Remoting.Channels.Tcp.TcpClientChannel, System.Runtime.Remoting, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<channel id="tcp server" type="System.Runtime.Remoting.Channels.Tcp.TcpServerChannel, System.Runtime.Remoting, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</channels>
<channelSinkProviders>
<clientProviders>
<formatter id="soap" type="System.Runtime.Remoting.Channels.SoapClientFormatterSinkProvider, System.Runtime.Remoting, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<formatter id="binary" type="System.Runtime.Remoting.Channels.BinaryClientFormatterSinkProvider, System.Runtime.Remoting, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</clientProviders>
<serverProviders>
<formatter id="soap" type="System.Runtime.Remoting.Channels.SoapServerFormatterSinkProvider, System.Runtime.Remoting, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<formatter id="binary" type="System.Runtime.Remoting.Channels.BinaryServerFormatterSinkProvider, System.Runtime.Remoting, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<provider id="wsdl" type="System.Runtime.Remoting.MetadataServices.SdlChannelSinkProvider, System.Runtime.Remoting, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</serverProviders>
</channelSinkProviders>
</system.runtime.remoting>
<appSettings>
<!--<add key="yourkey" value="your value" /> -->
<!--<remove key="a key defined higher in the hierarchy" /> -->
<!--<clear/> Removes all defined settings -->
</appSettings>
<system.diagnostics>
<trace autoflush="false" indentsize="4" />
</system.diagnostics>
<system.drawing>
</system.drawing>
<strongNames>
<pubTokenMapping>
<!-- ECMA key -->
<map Token="b77a5c561934e089" PublicKey="002400000480000094000000060200000024000052534131000400000100010079159977d2d03a8e6bea7a2e74e8d1afcc93e8851974952bb480a12c9134474d04062447c37e0e68c080536fcf3c3fbe2ff9c979ce998475e506e8ce82dd5b0f350dc10e93bf2eeecf874b24770c5081dbea7447fddafa277b22de47d6ffea449674a4f9fccf84d15069089380284dbdd35f46cdff12a1bd78e4ef0065d016df" />
<!-- Microsoft (final) key -->
<map Token="b03f5f7f11d50a3a" PublicKey="002400000480000094000000060200000024000052534131000400000100010079159977d2d03a8e6bea7a2e74e8d1afcc93e8851974952bb480a12c9134474d04062447c37e0e68c080536fcf3c3fbe2ff9c979ce998475e506e8ce82dd5b0f350dc10e93bf2eeecf874b24770c5081dbea7447fddafa277b22de47d6ffea449674a4f9fccf84d15069089380284dbdd35f46cdff12a1bd78e4ef0065d016df" />
<!-- Microsoft (Web Service Enhancement) key -->
<map Token="31bf3856ad364e35" PublicKey="002400000480000094000000060200000024000052534131000400000100010079159977d2d03a8e6bea7a2e74e8d1afcc93e8851974952bb480a12c9134474d04062447c37e0e68c080536fcf3c3fbe2ff9c979ce998475e506e8ce82dd5b0f350dc10e93bf2eeecf874b24770c5081dbea7447fddafa277b22de47d6ffea449674a4f9fccf84d15069089380284dbdd35f46cdff12a1bd78e4ef0065d016df" />
<!-- IBM (DB2 Data Provider) key -->
<map Token="7c307b91aa13d208" PublicKey="002400000480000094000000060200000024000052534131000400000100010079159977d2d03a8e6bea7a2e74e8d1afcc93e8851974952bb480a12c9134474d04062447c37e0e68c080536fcf3c3fbe2ff9c979ce998475e506e8ce82dd5b0f350dc10e93bf2eeecf874b24770c5081dbea7447fddafa277b22de47d6ffea449674a4f9fccf84d15069089380284dbdd35f46cdff12a1bd78e4ef0065d016df" />
</pubTokenMapping>
</strongNames>
</configuration>
+2 -10
View File
@@ -940,23 +940,15 @@ public class HtmlSampleGenerator: SampleGenerator
}
// Serialize headers
bool writtenHeader = false;
foreach (object ob in msgbin.Extensions)
{
SoapHeaderBinding hb = ob as SoapHeaderBinding;
if (hb == null) continue;
if (!writtenHeader) {
xtw.WriteStartElement ("soap", "Header", SoapEnvelopeNamespace);
writtenHeader = true;
}
xtw.WriteStartElement ("soap", "Header", SoapEnvelopeNamespace);
WriteHeader (xtw, hb);
}
if (writtenHeader)
xtw.WriteEndElement ();
}
// Serialize body
xtw.WriteStartElement ("soap", "Body", SoapEnvelopeNamespace);
+3 -34
View File
@@ -14,7 +14,6 @@
<%@ Import Namespace="System.Xml.Serialization" %>
<%@ Import Namespace="System.Xml" %>
<%@ Import Namespace="System.Xml.Schema" %>
<%@ Import Namespace="System.Web.Services" %>
<%@ Import Namespace="System.Web.Services.Description" %>
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Net" %>
@@ -51,7 +50,6 @@ ArrayList InParams;
ArrayList OutParams;
string CurrentOperationProtocols;
int CodeTextColumns = 95;
BasicProfileViolationCollection ProfileViolations;
void Page_Load(object sender, EventArgs e)
{
@@ -68,8 +66,6 @@ void Page_Load(object sender, EventArgs e)
DefaultBinding = desc.Bindings[0].Name;
WebServiceDescription = service.Documentation;
if (WebServiceDescription == "" || WebServiceDescription == null)
WebServiceDescription = "Description has not been provided";
ServiceProtocols = FindServiceProtocols (null);
CurrentOperationName = Request.QueryString["op"];
@@ -86,9 +82,6 @@ void Page_Load(object sender, EventArgs e)
BindingsRepeater.DataSource = list;
Page.DataBind();
ProfileViolations = new BasicProfileViolationCollection ();
WebServicesInteroperability.CheckConformance (WsiClaims.BP10, descriptions, ProfileViolations);
}
void BuildOperationInfo ()
@@ -947,23 +940,15 @@ public class HtmlSampleGenerator: SampleGenerator
}
// Serialize headers
bool writtenHeader = false;
foreach (object ob in msgbin.Extensions)
{
SoapHeaderBinding hb = ob as SoapHeaderBinding;
if (hb == null) continue;
if (!writtenHeader) {
xtw.WriteStartElement ("soap", "Header", SoapEnvelopeNamespace);
writtenHeader = true;
}
xtw.WriteStartElement ("soap", "Header", SoapEnvelopeNamespace);
WriteHeader (xtw, hb);
}
if (writtenHeader)
xtw.WriteEndElement ();
}
// Serialize body
xtw.WriteStartElement ("soap", "Body", SoapEnvelopeNamespace);
@@ -1610,23 +1595,7 @@ function clearForm ()
<p class="label">Web Service Overview</p>
<%#WebServiceDescription%>
<br/><br/>
<% if (ProfileViolations.Count > 0) { %>
<p class="label">Basic Profile Conformance</p>
This web service does not conform to WS-I Basic Profile v1.0
<%
Response.Write ("<ul>");
foreach (BasicProfileViolation vio in ProfileViolations) {
Response.Write ("<li><b>" + vio.NormativeStatement + "</b>: " + vio.Details);
Response.Write ("<ul>");
foreach (string ele in vio.Elements)
Response.Write ("<li>" + ele + "</li>");
Response.Write ("</ul>");
Response.Write ("</li>");
}
Response.Write ("</ul>");
}%>
<%} if (DefaultBinding == null) {%>
This service does not contain any public web method.
<%} else if (CurrentPage == "op") {%>
+58 -58
View File
@@ -3,63 +3,63 @@
<configuration>
<configSections>
<section name="appSettings" type="System.Configuration.NameValueFileSectionHandler, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<section name="system.diagnostics" type="System.Diagnostics.DiagnosticsConfigurationHandler, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<section name="system.runtime.remoting" type="System.Configuration.IgnoreSectionHandler, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowLocation="false"/>
<section name="appSettings" type="System.Configuration.NameValueFileSectionHandler, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<section name="system.diagnostics" type="System.Diagnostics.DiagnosticsConfigurationHandler, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<section name="system.runtime.remoting" type="System.Configuration.IgnoreSectionHandler, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowLocation="false"/>
<sectionGroup name="system.web">
<section name="httpHandlers"
type="System.Web.Configuration.HttpHandlersSectionHandler, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
type="System.Web.Configuration.HttpHandlersSectionHandler, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<section name="httpModules"
type="System.Web.Configuration.HttpModulesConfigurationHandler, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
type="System.Web.Configuration.HttpModulesConfigurationHandler, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<section name="machineKey"
type="System.Web.Configuration.MachineKeyConfigHandler, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
type="System.Web.Configuration.MachineKeyConfigHandler, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<section name="authentication"
type="System.Web.Configuration.AuthenticationConfigHandler, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
type="System.Web.Configuration.AuthenticationConfigHandler, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<section name="authorization"
type="System.Web.Configuration.AuthorizationConfigHandler, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
type="System.Web.Configuration.AuthorizationConfigHandler, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<section name="globalization"
type="System.Web.Configuration.GlobalizationConfigurationHandler, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
type="System.Web.Configuration.GlobalizationConfigurationHandler, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<section name="sessionState"
type="System.Web.SessionState.SessionStateSectionHandler, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
type="System.Web.SessionState.SessionStateSectionHandler, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<section name="trace"
type="System.Web.Configuration.TraceConfigurationHandler, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
type="System.Web.Configuration.TraceConfigurationHandler, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<section name="webServices"
type="System.Web.Services.Configuration.WebServicesConfigurationSectionHandler, System.Web.Services, Version=2.0.3600.0 Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
type="System.Web.Services.Configuration.WebServicesConfigurationSectionHandler, System.Web.Services, Version=1.0.5000.0 Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<section name="webControls"
type="System.Web.Configuration.WebControlsSectionHandler, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
type="System.Web.Configuration.WebControlsSectionHandler, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<section name="compilation"
type="System.Web.Configuration.CompilationConfigurationHandler, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
type="System.Web.Configuration.CompilationConfigurationHandler, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<section name="httpRuntime"
type="System.Web.Configuration.HttpRuntimeConfigurationHandler, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
type="System.Web.Configuration.HttpRuntimeConfigurationHandler, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<section name="customErrors"
type="System.Web.Configuration.CustomErrorsConfigHandler, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
type="System.Web.Configuration.CustomErrorsConfigHandler, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<section name="pages"
type="System.Web.Configuration.PagesConfigurationHandler, System.Web, Version=2.0.3600.0, Culture=neutral" />
type="System.Web.Configuration.PagesConfigurationHandler, System.Web, Version=1.0.5000.0, Culture=neutral" />
<section name="clientTarget"
type="System.Web.Configuration.ClientTargetSectionHandler, System.Web, Version=2.0.3600.0, Culture=neutral" />
type="System.Web.Configuration.ClientTargetSectionHandler, System.Web, Version=1.0.5000.0, Culture=neutral" />
</sectionGroup>
<sectionGroup name="system.net">
<section name="settings"
type="System.Net.Configuration.NetConfigurationHandler, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
type="System.Net.Configuration.NetConfigurationHandler, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<section name="connectionManagement"
type="System.Net.Configuration.ConnectionManagementHandler, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
type="System.Net.Configuration.ConnectionManagementHandler, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<section name="authenticationModules"
type="System.Net.Configuration.NetAuthenticationModuleHandler, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
type="System.Net.Configuration.NetAuthenticationModuleHandler, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<section name="defaultProxy"
type="System.Net.Configuration.DefaultProxyHandler, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
type="System.Net.Configuration.DefaultProxyHandler, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<section name="webRequestModules"
type="System.Net.Configuration.WebRequestModuleHandler, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
type="System.Net.Configuration.WebRequestModuleHandler, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</sectionGroup>
<section name="system.drawing" type="System.Configuration.NameValueSectionHandler, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<section name="system.drawing" type="System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</configSections>
<system.net>
<connectionManagement>
<add address="*" maxconnection="2" />
</connectionManagement>
<authenticationModules>
<add type="System.Net.BasicClient, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<add type="System.Net.DigestClient, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<add type="System.Net.NtlmClient, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<add type="System.Net.BasicClient, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<add type="System.Net.DigestClient, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<add type="System.Net.NtlmClient, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</authenticationModules>
<defaultProxy>
<proxy />
@@ -67,9 +67,9 @@
<!-- usessystemdefault is not supported -->
</defaultProxy>
<webRequestModules>
<add prefix="http" type="System.Net.HttpRequestCreator, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<add prefix="https" type="System.Net.HttpRequestCreator, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<add prefix="file" type="System.Net.FileWebRequestCreator, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<add prefix="http" type="System.Net.HttpRequestCreator, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<add prefix="https" type="System.Net.HttpRequestCreator, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<add prefix="file" type="System.Net.FileWebRequestCreator, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</webRequestModules>
<settings>
<ipv6 enabled="false"/>
@@ -77,25 +77,25 @@
</system.net>
<system.web>
<httpHandlers>
<add verb="*" path="Trace.axd" type="System.Web.Handlers.TraceHandler, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add verb="*" path="*.aspx" type="System.Web.UI.PageHandlerFactory, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add verb="*" path="*.asmx" validate="false" type="System.Web.Services.Protocols.WebServiceHandlerFactory, System.Web.Services, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add verb="*" path="*.ashx" type="System.Web.UI.SimpleHandlerFactory, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add verb="GET" path="WebResource.axd" type="System.Web.Handlers.AssemblyResourceLoader, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add verb="*" path="*.asax" type="System.Web.HttpForbiddenHandler, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add verb="*" path="*.ascx" type="System.Web.HttpForbiddenHandler, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add verb="*" path="*.config" type="System.Web.HttpForbiddenHandler, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add verb="*" path="*.cs" type="System.Web.HttpForbiddenHandler, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add verb="*" path="Trace.axd" type="System.Web.Handlers.TraceHandler, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add verb="*" path="*.aspx" type="System.Web.UI.PageHandlerFactory, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add verb="*" path="*.asmx" validate="false" type="System.Web.Services.Protocols.WebServiceHandlerFactory, System.Web.Services, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add verb="*" path="*.ashx" type="System.Web.UI.SimpleHandlerFactory, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add verb="GET" path="WebResource.axd" type="System.Web.Handlers.AssemblyResourceLoader, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add verb="*" path="*.asax" type="System.Web.HttpForbiddenHandler, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add verb="*" path="*.ascx" type="System.Web.HttpForbiddenHandler, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add verb="*" path="*.config" type="System.Web.HttpForbiddenHandler, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add verb="*" path="*.cs" type="System.Web.HttpForbiddenHandler, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add verb="*" path="*.rem" type="System.Runtime.Remoting.Channels.Http.HttpRemotingHandlerFactory, System.Runtime.Remoting, Culture=neutral, PublicKeyToken=b77a5c561934e089" validate="false" />
<add verb="*" path="*.soap" type="System.Runtime.Remoting.Channels.Http.HttpRemotingHandlerFactory, System.Runtime.Remoting, Culture=neutral, PublicKeyToken=b77a5c561934e089" validate="false" />
<add verb="GET,HEAD" path="*" type="System.Web.StaticFileHandler, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add verb="*" path="*" type="System.Web.HttpMethodNotAllowedHandler, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add verb="GET,HEAD" path="*" type="System.Web.StaticFileHandler, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add verb="*" path="*" type="System.Web.HttpMethodNotAllowedHandler, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</httpHandlers>
<httpModules>
<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add name="UrlAuthorization" type="System.Web.Security.UrlAuthorizationModule, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add name="Session" type="System.Web.SessionState.SessionStateModule, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add name="OutputCache" type="System.Web.Caching.OutputCacheModule, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add name="UrlAuthorization" type="System.Web.Security.UrlAuthorizationModule, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add name="Session" type="System.Web.SessionState.SessionStateModule, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add name="OutputCache" type="System.Web.Caching.OutputCacheModule, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</httpModules>
<authentication mode="Forms">
<forms name=".MONOAUTH" loginUrl="login.aspx" protection="All" timeout="30" path="/">
@@ -126,10 +126,10 @@
<compilation debug="false" defaultLanguage="c#">
<compilers>
<compiler language="cs;c#;csharp" extension=".cs" warningLevel="1" compilerOptions=""
type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
type="Microsoft.CSharp.CSharpCodeProvider, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb"
warningLevel="1" compilerOptions=""
type="Microsoft.VisualBasic.VBCodeProvider, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
type="Microsoft.VisualBasic.VBCodeProvider, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</compilers>
<assemblies>
<!--<add assembly="mscorlib" /> -->
@@ -168,22 +168,22 @@
</channels>
</application>
<channels>
<channel id="http" type="System.Runtime.Remoting.Channels.Http.HttpChannel, System.Runtime.Remoting, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<channel id="http client" type="System.Runtime.Remoting.Channels.Http.HttpClientChannel, System.Runtime.Remoting, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<channel id="http server" type="System.Runtime.Remoting.Channels.Http.HttpServerChannel, System.Runtime.Remoting, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<channel id="tcp" type="System.Runtime.Remoting.Channels.Tcp.TcpChannel, System.Runtime.Remoting, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<channel id="tcp client" type="System.Runtime.Remoting.Channels.Tcp.TcpClientChannel, System.Runtime.Remoting, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<channel id="tcp server" type="System.Runtime.Remoting.Channels.Tcp.TcpServerChannel, System.Runtime.Remoting, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<channel id="http" type="System.Runtime.Remoting.Channels.Http.HttpChannel, System.Runtime.Remoting, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<channel id="http client" type="System.Runtime.Remoting.Channels.Http.HttpClientChannel, System.Runtime.Remoting, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<channel id="http server" type="System.Runtime.Remoting.Channels.Http.HttpServerChannel, System.Runtime.Remoting, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<channel id="tcp" type="System.Runtime.Remoting.Channels.Tcp.TcpChannel, System.Runtime.Remoting, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<channel id="tcp client" type="System.Runtime.Remoting.Channels.Tcp.TcpClientChannel, System.Runtime.Remoting, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<channel id="tcp server" type="System.Runtime.Remoting.Channels.Tcp.TcpServerChannel, System.Runtime.Remoting, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</channels>
<channelSinkProviders>
<clientProviders>
<formatter id="soap" type="System.Runtime.Remoting.Channels.SoapClientFormatterSinkProvider, System.Runtime.Remoting, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<formatter id="binary" type="System.Runtime.Remoting.Channels.BinaryClientFormatterSinkProvider, System.Runtime.Remoting, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<formatter id="soap" type="System.Runtime.Remoting.Channels.SoapClientFormatterSinkProvider, System.Runtime.Remoting, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<formatter id="binary" type="System.Runtime.Remoting.Channels.BinaryClientFormatterSinkProvider, System.Runtime.Remoting, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</clientProviders>
<serverProviders>
<formatter id="soap" type="System.Runtime.Remoting.Channels.SoapServerFormatterSinkProvider, System.Runtime.Remoting, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<formatter id="binary" type="System.Runtime.Remoting.Channels.BinaryServerFormatterSinkProvider, System.Runtime.Remoting, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<provider id="wsdl" type="System.Runtime.Remoting.MetadataServices.SdlChannelSinkProvider, System.Runtime.Remoting, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<formatter id="soap" type="System.Runtime.Remoting.Channels.SoapServerFormatterSinkProvider, System.Runtime.Remoting, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<formatter id="binary" type="System.Runtime.Remoting.Channels.BinaryServerFormatterSinkProvider, System.Runtime.Remoting, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<provider id="wsdl" type="System.Runtime.Remoting.MetadataServices.SdlChannelSinkProvider, System.Runtime.Remoting, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</serverProviders>
</channelSinkProviders>
</system.runtime.remoting>
+1 -14
View File
@@ -69,16 +69,7 @@
not interfere with code in other domains. This is useful if
you want to host different applications in your program.
Now, it is necessary to transfer control to Mono, and setup
the threading infrastructure, you do this like this:
void *user_data = NULL;
mono_runtime_exec_managed_code (domain, main_thread_handler, user_data);
Where your main_thread_handler can load your assembly and execute it:
static void main_thread_handler (gpointer user_data)
Then you can load an assembly containing code into the domain:
MonoAssembly *assembly;
@@ -121,10 +112,6 @@
layer, so in each file where you use pthread.h you should
include the <gc/gc.h> file.
If you can not do this for any reasons, just remember that you
can not store pointers to Mono Objects on the stack, you can
store them safely in the heap, or in global variables though
* Exposing C code to the CIL universe
The Mono runtime provides two mechanisms to expose C code to
+14 -35
View File
@@ -1,15 +1,20 @@
Mono Intermediate Representation Documentation
Operation: OP_ADDCC_IMM
Operation: OP_LOCALLOC
inst_left:
The value
ins->inst_left = *sp;
ins->cil_code = ip;
Add immediate that will set the carry flag.
dreg:
Destination register
inst_imm
Immediate value to add.
sreg1:
Source register to add.
This is the equivalent of alloca() in a C implementation: it
allocates a bunch of bytes on the stack dynamically. Local
variables are allocated statically in the stack instead.
It is implemented by moving the stack pointer according to the
platform ABI: you may need to keep a specific frame register
to address local variables when LOCALLOC is used (the PPC code
does this, for example: ifyou're doing the s390 port I suggest
starting from that)
Operation: OP_CALL_HANDLER.
@@ -47,29 +52,3 @@ Operation: OP_CCASTCLASS
throws an InvalidCastException exception otherwise.
Operation: OP_LOCALLOC
inst_left:
The value
ins->inst_left = *sp;
ins->cil_code = ip;
This is the equivalent of alloca() in a C implementation: it
allocates a bunch of bytes on the stack dynamically. Local
variables are allocated statically in the stack instead.
It is implemented by moving the stack pointer according to the
platform ABI: you may need to keep a specific frame register
to address local variables when LOCALLOC is used (the PPC code
does this, for example: ifyou're doing the s390 port I suggest
starting from that)
Operation: OP_SUBCC_IMM
Substract immediate that will set the borrow flag.
dreg:
Destination register
inst_imm
Immediate value to add.
sreg1:
Source register to add.
-5
View File
@@ -1,8 +1,3 @@
2004-11-07 Zoltan Varga <[email protected]>
* mono-jni.c (GET_SET_ARRAY_ELEMENTS): Fix compilation errors on
gcc 3.3.5.
2004-06-24 David Waite <[email protected]>
* mono-jni.c: change to C90-style comments from C99/C++-style
+2 -2
View File
@@ -841,13 +841,13 @@ static void JNICALL Get##Type##ArrayRegion (JNIEnv *env, type##Array array, jsiz
{\
MonoArray *obj; \
obj = jniFuncs.UnwrapRef (env, (void*)array); \
memcpy (buf, mono_array_addr (obj, type, start), (sizeof (type) * l)); \
memcpy (buf, mono_array_addr (obj, sizeof (type), start), (sizeof (type) * l)); \
} \
static void JNICALL Set##Type##ArrayRegion (JNIEnv *env, type##Array array, jsize start, jsize l, type *buf) \
{ \
MonoArray *obj; \
obj = jniFuncs.UnwrapRef (env, (void*)array); \
memcpy (mono_array_addr (obj, type, start), buf, (sizeof (type) * l)); \
memcpy (mono_array_addr (obj, sizeof (type), start), buf, (sizeof (type) * l)); \
}
GET_SET_ARRAY_ELEMENTS(Boolean,jboolean,gboolean)
-14
View File
@@ -108,20 +108,6 @@ key containers. The option is equivalent to including [assembly:
AssemblyKeyName ("CONTAINER")] in your source code. Compiler option
takes precedence over the attributes.
.TP
.I \-langversion:TEXT
The option specifies the version of the language to use. The feature
set is different in each C# version. This switch can be used to force
the compiler to allow only a subset of the features.
The possible values are:
.nf
Default - Instruct compiler to use the latest version. Equivalent
is to omit the switch.
ISO-1 - Restrict compiler to use only ISO standardized features.
The usage of features such as generics, static classes, anonymous
methods will lead to error.
.TP
.I -lib:PATHLIST
Each path specified in the comma-separated list will direct the
compiler to look for libraries in that specified path.
+26 -72
View File
@@ -210,7 +210,7 @@ And individual methods are referenced with the M: prefix, and the
standar method notation:
.nf
mono --trace=M:System.Console:WriteLine app.exe
mono --trace=M:System.Console.WriteLine app.exe
.fi
As previously noted, various rules can be specified at once:
@@ -232,30 +232,6 @@ Finally, namespaces can be specified using the N: prefix:
mono --trace=N:System.Xml
.fi
.SH DEBUGGING
.PP
If you are interested in debugging P/Invoke problems with your
application, you might want to use:
.nf
$ MONO_LOG_LEVEL="debug" MONO_LOG_MASK="dll" mono glue.exe
.fi
.SH SERIALIZATION
Mono's XML serialization engine by default will use a reflection-based
approach to serialize which might be slow for continous processing
(web service applications). The serialization engine will determine
when a class must use a hand-tuned serializer based on a few
parameters and if needed it will produce a customized C# serializer
for your types at runtime. This customized serializer then gets
dynamically loaded into your application.
.PP
You can control this with the MONO_XMLSERIALIZER_THS environment
variable.
.PP
The possible values are `no' to disable the use of a C# customized
serializer, or an integer that is the minimum number of uses before
the runtime will produce a custom serializer (0 will produce a
custom serializer on the first access, 50 will produce a serializer on
the 50th use).
.SH ENVIRONMENT VARIABLES
.TP
.I "GC_DONT_GC"
@@ -276,6 +252,21 @@ If set, this variable overrides the default runtime configuration file
($PREFIX/etc/mono/config). The --config command line options overrides the
environment variable.
.TP
.I "MONO_LOG_LEVEL"
If set, the logging level is changed to the set value. Possible values
are "error", "critical", "warning", "message", "info", "debug". The
default value is "error". Messages with a logging level greater then
or equal to the log level will be printed to stdout/stderr.
.TP
.I "MONO_LOG_MASK"
If set, the log mask is changed to the set value. Possible values are
"asm" (assembly loader), "type", "dll" (native library loader), "gc"
(garbage collector), "cfg" (config file loader), "aot" (precompiler), "all".
The default value is "all". Changing the mask value allows you to display only
messages for a certain component. You can use multiple masks by comma
separating them. For example to see config file messages and assembly loader
messages set you mask to "asm,cfg".
.TP
.I "MONO_DEBUG"
If set, enables some features of the runtime useful for debugging.
It makes the runtime display the stack traces for all the threads
@@ -311,66 +302,29 @@ conversion ending the search. When writing external text (e.g. new
filenames or arguments to new processes) the first item in this list
is used, or UTF-8 if the environment variable is not set.
.TP
.I "MONO_GAC_PREFIX"
Provides a prefix the runtime uses to look for Global Assembly Caches.
Directories are separated by the platform path separator (colons on
unix). MONO_GAC_PREFIX should point to the top directory of a prefixed
install. Or to the directory provided in the gacutil /gacdir command. Example:
.B /home/username/.mono:/usr/local/mono/
.TP
.I "MONO_LOG_LEVEL"
If set, the logging level is changed to the set value. Possible values
are "error", "critical", "warning", "message", "info", "debug". The
default value is "error". Messages with a logging level greater then
or equal to the log level will be printed to stdout/stderr.
.PP
Use info to track the dynamic loading of assemblies.
.TP
.I "MONO_LOG_MASK"
If set, the log mask is changed to the set value. Possible values are
"asm" (assembly loader), "type", "dll" (native library loader), "gc"
(garbage collector), "cfg" (config file loader), "aot" (precompiler), "all".
The default value is "all". Changing the mask value allows you to display only
messages for a certain component. You can use multiple masks by comma
separating them. For example to see config file messages and assembly loader
messages set you mask to "asm,cfg".
.TP
.I "MONO_MANAGED_WATCHER"
If set to any value, System.IO.FileSystemWatcher will use the default
managed implementation (slow). If unset, mono will try to use FAM under
Unix systems and native API calls on Windows, falling back to the
managed implementation on error.
.TP
.I "MONO_THREADS_PER_CPU"
Sets the maximum number of threads in the threadpool per CPU. The default is
50 for non-windows systems and 25 for windows.
.I "MONO_PATH"
Provides a search path to the runtime where to look for library files.
Directories are separated by the platform path separator (colons on unix). Example:
.B /home/username/lib:/usr/local/mono/lib
.TP
.I "MONO_TRACE"
If set, enables the System.Diagnostics.DefaultTraceListener, which will
print the output of the System.Diagnostics Trace and Debug classes.
It can be set to a filename, and to Console.Out or Console.Error to display
output to standard output or standard error, respectively.
See the System.Diagnostics.DefaultTraceListener documentation for more
information.
.I "MONO_GAC_PREFIX"
Provides a prefix the runtime uses to look for Global Assembly Caches.
Directories are separated by the platform path separator (colons on
unix). MONO_GAC_PREFIX should point to the top directory of a prefixed
install. Or to the directory provided in the gacutil /gacdir command. Example:
.B /home/username/.mono:/usr/local/mono/
.TP
.I "MONO_SHARED_DIR"
If set its the directory where the ".wapi" handle state is stored.
This is the directory where the Windows I/O Emulation layer stores its
shared state data (files, events, mutexes, pipes). By default Mono
will store the ".wapi" directory in the users's home directory.
.TP
.I "MONO_PATH"
Provides a search path to the runtime where to look for library files.
Directories are separated by the platform path separator (colons on unix). Example:
.B /home/username/lib:/usr/local/mono/lib
.TP
.I "MONO_XMLSERIALIZER_THS"
Controls the threshold for the XmlSerializer to produce a custom
serializer for a given class instead of using the Reflection-based
interpreter. The possible values are `no' to disable the use of a
custom serializer or a number to indicate when the XmlSerializer
should start serializing. The default value is 50, which means that
the a custom serializer will be produced on the 50th use.
.SH FILES
On Unix assemblies are loaded from the installation lib directory. If you set
`prefix' to /usr, the assemblies will be located in /usr/lib. On
+45 -27
View File
@@ -1,18 +1,18 @@
.TH sqlsharp 1 "21 October 2004"
.TH sqlsharp 1 "10 December 2002"
.SH NAME
sqlsharp \- Mono SQL Query command-line tool
sqlsharp \- Mono SQL# command-line SQL Query tool
.SH SYNOPSIS
.B sqlsharp
[\-f filename] [\-o filename] [\-s]
.SH DESCRIPTION
sqlsharp is a Mono SQL tool used for entering SQL queries
to a database using Mono data providers.
sqlsharp is the Mono SQL# tool used for entering SQL queries
to a database using Mono ADO.NET providers.
.PP
.SH OPTIONS
The following options are supported:
.TP
.I "-f filename"
Output file to load SQL commands from.
Output file to load SQL# commands from.
.TP
.I "-o filename"
Output file to send results.
@@ -21,7 +21,7 @@ Output file to send results.
Silent mode.
.PP
.SH HOW TO USE
The SQL tool accepts commands via its command line interface. Commands
The SQL# tool accepts commands via its command line interface. Commands
begin with a backslash followed by the command name.
.PP
Example:
@@ -344,25 +344,28 @@ ption defaulting to true.
PROVIDER NAME NAMESPACE ASSEMBLY
Oracle Oracle 8i System.Data.OracleClient System.Data.OracleClient
PostgreSql NetPostgreSQL Npgsql Npgsql
MySQL ByteFX MySQL ByteFX.Data.MySqlClient ByteFX.Data
Internal
--------
OleDb OLE DB System.Data.OleDb System.Data
SqlClient MS SQL 7/2000 System.Data.SqlClient System.Data
Odbc ODBC System.Data.Odbc System.Data
External to System.Data
-----------------------
MySql MySQL Mono.Data.MySql Mono.Data.MySql
Sqlite SQL Lite Mono.Data.SqliteClient Mono.Data.SqliteClient
Sybase Sybase Mono.Data.SybaseClient Mono.Data.SybaseClient
OleDb OLE DB System.Data.OleDb System.Data
Tds TDS Generic Mono.Data.TdsClient Mono.Data.TdsClient
MSOdbc MS ODBC Microsoft.Data.Odbc Microsoft.Data.Odbc
Firebird Firebird SQL FirebirdSql.Data.FirebirdSql FirebirdSql.Data.Firebird
PostgreSql M PostgreSQL Mono.Data.PostgreSqlClient Mono.Data.PostgreSqlClient
DB2 IBM DB2 Mono.Data.DB2Client Mono.Data.DB2Client
Oracle Oracle 8i System.Data.OracleClient System.Data.OracleClient
NOTES
External to Mono
----------------
Npgsql maps to PostgreSql above.
MySqlNet maps to MySql above.
Odbc is treated as an external provider for .NET 1.1 and above.
MSODBC is an external provider for compatibility with .NET 1.0
Firebird is not included with Mono.
Npgsql NetPostgreSQL Npgsql Npgsql
MySQLNet ByteFX MySQL ByteFX.Data.MySQL ByteFX.Data
.fi
.SH CONNECTION STRING SAMPLES
@@ -382,6 +385,20 @@ or Mono.Data.TdsClient provider:
Server=DANPC;Database=pubs;User ID=saPassword=
PostgreSQL via Mono.Data.PostgreSqlClient provider:
host=localhost;dbname=test;user=postgres;password=fun2db
or
Server=localhost;Database=test;User ID=postgres;Password=fun2db
MySQL via Mono.Data.MySql provider:
Server=localhost;Database=test;User ID=mysql;Password=
ODBC via System.Data.Odbc provider using
a DSN named "MSSQLDSN" I set up
@@ -410,6 +427,11 @@ Oracle via System.Data.OracleClient
Data Source=testdb;User ID=scott;Password=tiger
IBM DB2 Universal Database via Mono.Data.DB2Client
DSN=sample;User ID=db2admin;Password=mysecret
Npgsql (.NET PostgreSQL) from
http://gborg.postgresql.org/project/npgsql/projdisplay.php
@@ -421,24 +443,20 @@ http://sourceforge.net/projects/mysqlnet/
Server=localhost;Database=test;User ID=mysql;Password=
FirebirdSql via FirebirdSql.Data.Firebird (not included with Mono)
Database=C:\\FIREBIRD\\EXAMPLES\\EMPLOYEE.FDB;User=SYSDBA;Password=masterkey;Dialect=3;Server=localhost
.fi
.SH TRACING SUPPORT
No support for tracing right now.
.SH AUTHORS
The Mono SQL Query Tool was written
The Mono SQL# Tool was written
.nf
by Daniel Morgan <danielmorg[email protected]>
by Daniel Morgan <danmorg@sc.rr.com>
.fi
.PP
.SH LICENSE
The Mono SQL Query Tool is released under the terms of the GNU GPL.
The Mono SQL# Tool is released under the terms of the GNU GPL.
Please read the accompanying `COPYING' file for details. Alternative
licenses are available from Novell or Daniel Morgan.
licenses are available from Ximian or Daniel Morgan.
.SH BUGS
To report bugs in the compiler, you can use `bug-buddy', or you can
file bug reports in our bug tracking system:
@@ -454,7 +472,7 @@ http://mail.ximian.com/mailman/mono-list
.SH WEB SITE
For details, visit:
.nf
http://www.mono-project.com
http://www.go-mono.com
.fi
.PP
.SH SEE ALSO
+5 -12
View File
@@ -1,4 +1,4 @@
\"
.\"
.\" wsdl manual page.
.\" (C) 2003 Novell, Inc.
.\" Author:
@@ -13,13 +13,9 @@ wsdl \- Mono's Web Service Proxy Generator
[options] [path | url]
.SH DESCRIPTION
.I wsdl
is a tool for generating proxy classes that can be used to access to
web services. The tool reads a WSDL document from the provided path
or url, and downloads referenced schemas or other WSDL documents if
needed.
.PP
This tool is used to target the 1.x API, for targetting the 2.x API,
please use the wsdl2 tool.
is a tool for generating proxy classes that can be used to access to web services.
The tool reads a WSDL document from the provided path or url, and downloads
referenced schemas or other WSDL documents if needed.
.PP
.SH OPTIONS
The following options are available:
@@ -33,9 +29,6 @@ Specifies a base URL for the service. The final URL will be constructed by
combining this value with the URL read from the
.I -appsettingurlkey
option, and the
.I "-type:typename, assembly"
Generate a proxy for a compiled web service class. The URL parameter
can be used to providethe location of the service.
.I location
attribute specified in the WSDL document.
.TP
@@ -80,4 +73,4 @@ Lluis Sanchez Gual ([email protected])
wsdl is released under the terms of the GNU GPL.
.PP
.SH SEE ALSO
disco(1), soapsuds(1), mono(1), mcs(1), wsdl2(1)
disco(1), soapsuds(1), mono(1), mcs(1)
-79
View File
@@ -1,79 +0,0 @@
.\"
.\" wsdl manual page.
.\" (C) 2003 Novell, Inc.
.\" Author:
.\" Lluis Sanchez Gual ([email protected])
.\"
.TH wsdl 1
.SH NAME
wsdl \- Mono's Web Service Proxy Generator
.SH SYNOPSIS
.PP
.B wsdl
[options] [path | url]
.SH DESCRIPTION
.I wsdl
is a tool for generating proxy classes that can be used to access to web services.
The tool reads a WSDL document from the provided path or url, and downloads
referenced schemas or other WSDL documents if needed.
.PP
This tool is used to target the 2.x API, for targetting the 1.x API,
please use the wsdl tool.
.PP
.SH OPTIONS
The following options are available:
.TP
.I "-appsettingurlkey:key" "-urlkey:key"
Specifies that the url for the services should be read from the <appsettings> section
of the configuration file, using the provided key.
.TP
.I "-appsettingbaseurl:url", "-baseurl:url"
Specifies a base URL for the service. The final URL will be constructed by
combining this value with the URL read from the
.I -appsettingurlkey
option, and the
.I location
attribute specified in the WSDL document.
.TP
.I "-language:language", "-l"
Language of the code to generate. It can be CS (default) or VB.
.TP
.I "-namespace:name", "-n:name"
The namespace of the generated classes. If none is specified, the default
namespace is used.
.TP
.I "-out:filename", "-o:filename"
The target file for generated code.
.TP
.I "-protocol:protocol", "-p:protocol"
The protocol for which to generate code. It can be Soap (default), HttpGet or
HttpPost.
.TP
.I "-sample:METHOD"
This will display XML request and reply of the sample invocations to
that SOAP message. You can use the -protocol: option to render the
message in different forms.
.TP
.I "-server"
Generate a server skeleton instead of a client proxy.
.TP
.I "-nologo"
Supress the startup logo.
.TP
.I "-u:username", "-user:username"
The user name to use when connecting to the server.
.TP
.I "-p:password", "-password:password"
The password to use when connecting to the server.
.TP
.I "-d:domain", "-domain:domain"
The domain to use when connecting to the server.
.PP
.SH AUTHORS
Lluis Sanchez Gual ([email protected])
.PP
.SH LICENSE
wsdl is released under the terms of the GNU GPL.
.PP
.SH SEE ALSO
disco(1), soapsuds(1), mono(1), mcs(1), wsdl(1)
+79
View File
@@ -0,0 +1,79 @@
/*
Copyright (c) 2003-2004 Niels Kokholm <[email protected]> and Peter Sestoft <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System.Reflection;
using System.Runtime.CompilerServices;
//
// 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("C5: Copenhagen Comprehensive Collection Classes for CLI")]
[assembly: AssemblyDescription("This is a debug build of prerelease 0.5")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("(c) 2003-2004 Niels Kokholm <[email protected]>, Peter Sestoft <[email protected]>")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("0.5.*")]
//
// In order to sign your assembly you must specify a key to use. Refer to the
// Microsoft .NET Framework documentation for more information on assembly signing.
//
// Use the attributes below to control which key is used for signing.
//
// Notes:
// (*) If no key is specified, the assembly is not signed.
// (*) KeyName refers to a key that has been installed in the Crypto Service
// Provider (CSP) on your machine. KeyFile refers to a file which contains
// a key.
// (*) If the KeyFile and the KeyName values are both specified, the
// following processing occurs:
// (1) If the KeyName can be found in the CSP, that key is used.
// (2) If the KeyName does not exist and the KeyFile does exist, the key
// in the KeyFile is installed into the CSP and used.
// (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility.
// When specifying the KeyFile, the location of the KeyFile should be
// relative to the project output directory which is
// %Project Directory%\obj\<configuration>. For example, if your KeyFile is
// located in the project directory, you would specify the AssemblyKeyFile
// attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")]
// (*) Delay Signing is an advanced option - see the Microsoft .NET Framework
// documentation for more information on this.
//
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("..\\..\\..\\c5.snk")]
//[assembly: AssemblyKeyName("")]
+344
View File
@@ -0,0 +1,344 @@
/*
Copyright (c) 2003-2004 Niels Kokholm <[email protected]> and Peter Sestoft <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using C5;
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Diagnostics;
namespace C5.ComparerBuilder
{
/// <summary>
/// A default item comparer for an item type that is either generic (IComparable&lt;T&gt;)
/// or ordinarily (System.IComparable) comparable.
/// </summary>
public class FromComparable<T>
{
static Type naturalComparerO = typeof(NaturalComparerO<>);
static Type naturalComparer = typeof(NaturalComparer<>);
/// <summary>
/// Create a default comparer
/// <exception cref="ArgumentException"/> if T is not comparable.
/// </summary>
/// <returns>The comparer</returns>
[Tested]
public static IComparer<T> Examine()
{
Type t = typeof(T);
if (t.Equals(typeof(int)))
return (IComparer<T>)(new IC());
if (typeof(IComparable<T>).IsAssignableFrom(t))
{
Type c = naturalComparer.BindGenericParameters(new Type[] { t });
return (IComparer<T>)(c.GetConstructor(System.Type.EmptyTypes).Invoke(null));
}
if (t.GetInterface("System.IComparable") != null)
{
Type c = naturalComparerO.BindGenericParameters(new Type[] { t });
return (IComparer<T>)(c.GetConstructor(System.Type.EmptyTypes).Invoke(null));
}
throw new ArgumentException(String.Format("Cannot make IComparer<{0}>", t));
}
}
}
namespace C5.HasherBuilder
{
/// <summary>
/// Prototype for an sequenced hasher for IIndexed[W]
/// This will use the IIndexed[W] specific operations
/// </summary>
public class SequencedHasher<S, W> : IHasher<S>
where S : ISequenced<W>
{
/// <summary>
/// Get the hash code with respect to this sequenced hasher
/// </summary>
/// <param name="item">The item</param>
/// <returns>The hash code</returns>
[Tested]
public int GetHashCode(S item) { return item.GetHashCode(); }
/// <summary>
/// Check if two items are equal with respect to this sequenced hasher
/// </summary>
/// <param name="i1">first item</param>
/// <param name="i2">second item</param>
/// <returns>True if equal</returns>
[Tested]
public bool Equals(S i1, S i2) { return i1 == null ? i2 == null : i1.Equals(i2); }
}
/// <summary>
/// Prototype for an unsequenced hasher for ICollection[W]
/// This will use the ICollection[W] specific operations
/// </summary>
public class UnsequencedHasher<S, W> : IHasher<S>
where S : ICollection<W>
{
/// <summary>
/// Get the hash code with respect to this unsequenced hasher
/// </summary>
/// <param name="item">The item</param>
/// <returns>The hash code</returns>
[Tested]
public int GetHashCode(S item) { return item.GetHashCode(); }
/// <summary>
/// Check if two items are equal with respect to this unsequenced hasher
/// </summary>
/// <param name="i1">first item</param>
/// <param name="i2">second item</param>
/// <returns>True if equal</returns>
[Tested]
public bool Equals(S i1, S i2) { return i1 == null ? i2 == null : i1.Equals(i2); }
}
/// <summary>
/// Create a hasher for T that is DefaultValueTypeHasher[T]
/// or DefaultReferenceTypeHasher[T] unless T has been
/// instatiated to a type of the exact form IIndexed[W] or ICollection[W]
/// in which case Examine will return Sequenced- repectively UnsequencedHasher.
/// </summary>
public class ByPrototype<T>
{
static Type isequenced = typeof(ISequenced<>);
static Type ieditable = typeof(ICollection<>);
static Type orderedhasher = typeof(HasherBuilder.SequencedHasher<,>);
static Type unorderedhasher = typeof(HasherBuilder.UnsequencedHasher<,>);
/*
static Type isequenced = Type.GetType("C5.ISequenced");
static Type ieditable = Type.GetType("C5.ICollection");
static Type orderedhasher = Type.GetType("C5.HasherBuilder.SequencedHasher");
static Type unorderedhasher = Type.GetType("C5.HasherBuilder.UnsequencedHasher");
*/
/// <summary>
/// See class description
/// </summary>
/// <returns>The hasher</returns>
[Tested]
public static IHasher<T> Examine()
{
Type t = typeof(T);
if (!t.HasGenericArguments)
{
if (t.Equals(typeof(int)))
return (IHasher<T>)(new IntHasher());
else if (t.IsValueType)
return new DefaultValueTypeHasher<T>();
else
return new DefaultReferenceTypeHasher<T>();
}
Type s = t.GetGenericTypeDefinition();
Type[] v = t.GetGenericArguments();
Type b;
if (s.Equals(isequenced))
b = orderedhasher;
else if (s.Equals(ieditable))
b = unorderedhasher;
else if (t.IsValueType)
return new DefaultValueTypeHasher<T>();
else
return new DefaultReferenceTypeHasher<T>();
Type c = b.BindGenericParameters(new Type[] { t, v[0] });
return (IHasher<T>)(c.GetConstructor(System.Type.EmptyTypes).Invoke(null));
}
}
#if !EXPERIMENTAL
/// <summary>
/// IHasher factory class: examines at instatiation time if T is an
/// interface implementing "int GetHashCode()" and "bool Equals(T)".
/// If those are not present, MakeHasher will return a default hasher,
/// else this class will implement Ihasher[T] via Invoke() on the
/// reflected method infos.
/// </summary>
public class ByInvoke<T> : IHasher<T>
{
internal static readonly System.Reflection.MethodInfo hinfo, einfo;
static ByInvoke()
{
Type t = typeof(T);
if (!t.IsInterface) return;
BindingFlags f = BindingFlags.Public | BindingFlags.Instance;
hinfo = t.GetMethod("GetHashCode", f, null, new Type[0], null);
einfo = t.GetMethod("Equals", f, null, new Type[1] { t }, null);
}
private ByInvoke() { }
/// <summary>
///
/// </summary>
/// <returns></returns>
public static IHasher<T> MakeHasher()
{
if (hinfo != null && einfo != null)
return new ByInvoke<T>();
else
return new DefaultReferenceTypeHasher<T>();
}
/// <summary>
///
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public int GetHashCode(T item)
{
return (int)(hinfo.Invoke(item, null));
}
/// <summary>
///
/// </summary>
/// <param name="i1"></param>
/// <param name="i2"></param>
/// <returns></returns>
public bool Equals(T i1, T i2)
{
return (bool)(einfo.Invoke(i1, new object[1] { i2 }));
}
}
/// <summary>
/// Like ByInvoke, but tries to build a hasher by RTCG to
/// avoid the Invoke() overhead. Does not work as intended
/// because of a Whidbey RTCG bug.
/// </summary>
public class ByRTCG
{
private static ModuleBuilder moduleBuilder;
private static AssemblyBuilder assemblyBuilder;
private static int uid = 0;
/// <summary>
///
/// </summary>
/// <param name="hinfo"></param>
/// <param name="einfo"></param>
/// <returns></returns>
public static /*ObjectHasher */ IHasher<T> CreateHasher<T>(MethodInfo hinfo, MethodInfo einfo)
{
if (moduleBuilder == null)
{
string assmname = "LeFake";
string filename = assmname + ".dll";
AssemblyName assemblyName = new AssemblyName("LeFake");
AppDomain appdomain = AppDomain.CurrentDomain;
AssemblyBuilderAccess acc = AssemblyBuilderAccess.RunAndSave;
assemblyBuilder = appdomain.DefineDynamicAssembly(assemblyName, acc);
moduleBuilder = assemblyBuilder.DefineDynamicModule(assmname, filename);
}
Type t = typeof(/*object*/ T);
Type o_t = typeof(object);
Type h_t = typeof(/*ObjectHasher*/ IHasher<T>);
Type i_t = typeof(int);
//TODO: protect uid for thread safety!
string name = "C5.Dynamic.Hasher_" + uid++;
TypeAttributes tatt = TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.Sealed;
TypeBuilder tb = moduleBuilder.DefineType(name, tatt, o_t, new Type[1] { h_t });
MethodAttributes matt = MethodAttributes.Public | MethodAttributes.Virtual;
MethodBuilder mb = tb.DefineMethod("GetHashCode", matt, i_t, new Type[1] { t });
ILGenerator ilg = mb.GetILGenerator();
ilg.Emit(OpCodes.Ldarg_1);
ilg.Emit(OpCodes.Callvirt, hinfo);
ilg.Emit(OpCodes.Ret);
mb = tb.DefineMethod("Equals", matt, typeof(bool), new Type[2] { t, t });
ilg = mb.GetILGenerator();
ilg.Emit(OpCodes.Ldarg_1);
ilg.Emit(OpCodes.Ldarg_2);
ilg.Emit(OpCodes.Callvirt, einfo);
ilg.Emit(OpCodes.Ret);
Type hasher_t = tb.CreateType();
object hasher = hasher_t.GetConstructor(new Type[0]).Invoke(null);
return (IHasher<T>)hasher;
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static IHasher<T> build<T>()
{
MethodInfo hinfo = ByInvoke<T>.hinfo, einfo = ByInvoke<T>.einfo;
if (hinfo != null && einfo != null)
return CreateHasher<T>(hinfo, einfo);
else
return ByPrototype<T>.Examine();
}
/// <summary>
///
/// </summary>
public void dump()
{
assemblyBuilder.Save("LeFake.dll");
}
}
#endif
}
+124
View File
@@ -0,0 +1,124 @@
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<ProductVersion>8.0.40607</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{D70489CD-ABDA-48FF-BD1E-BE3F7495BE71}</ProjectGuid>
<OutputType>Library</OutputType>
<StartupObject>
</StartupObject>
<RootNamespace>C5</RootNamespace>
<NoStandardLibraries>false</NoStandardLibraries>
<AssemblyName>C5</AssemblyName>
<FileUpgradeFlags>
</FileUpgradeFlags>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<DebugSymbols>true</DebugSymbols>
<Optimize>false</Optimize>
<OutputPath>.\bin\Debug\</OutputPath>
<EnableUnmanagedDebugging>false</EnableUnmanagedDebugging>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<WarningLevel>4</WarningLevel>
<IncrementalBuild>false</IncrementalBuild>
<DocumentationFile>c5.xml</DocumentationFile>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<DebugSymbols>false</DebugSymbols>
<Optimize>true</Optimize>
<OutputPath>.\bin\Release\</OutputPath>
<EnableUnmanagedDebugging>false</EnableUnmanagedDebugging>
<DefineConstants>TRACE</DefineConstants>
<WarningLevel>4</WarningLevel>
<IncrementalBuild>false</IncrementalBuild>
<DocumentationFile>
</DocumentationFile>
</PropertyGroup>
<ItemGroup>
<Reference Include="System">
<HintPath>..\..\..\..\..\WINDOWS\Microsoft.NET\Framework\v1.2.30703\System.dll</HintPath>
<Name>System</Name>
</Reference>
<Reference Include="System.Data">
<HintPath>..\..\..\..\..\WINDOWS\Microsoft.NET\Framework\v1.2.30703\System.Data.dll</HintPath>
<Name>System.Data</Name>
</Reference>
<Reference Include="System.Xml">
<HintPath>..\..\..\..\..\WINDOWS\Microsoft.NET\Framework\v1.2.30703\System.XML.dll</HintPath>
<Name>System.XML</Name>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="AssemblyInfo.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="Builder.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="Collections.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="Dictionaries.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="Interfaces.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="Wrappers.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="arrays\ArrayList.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="arrays\HashedArray.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="arrays\SortedArray.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="hashing\HashBag.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="hashing\HashDictionary.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="hashing\HashTable.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="heaps\IntervalHeap.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="linkedlists\HashedLinkedList.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="linkedlists\LinkedList.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="trees\RedBlackTree.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="trees\RedBlackTreeBag.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="trees\TreeDictionary.cs">
<SubType>Code</SubType>
</Compile>
</ItemGroup>
<ItemGroup>
<AppDesigner Include="Project\" />
</ItemGroup>
<ItemGroup>
<Folder Include="Project\" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSHARP.Targets" />
<PropertyGroup>
<PreBuildEvent>
</PreBuildEvent>
<PostBuildEvent>
</PostBuildEvent>
</PropertyGroup>
<ProjectExtensions>
<VisualStudio>
</VisualStudio>
</ProjectExtensions>
</Project>
+59
View File
@@ -0,0 +1,59 @@
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<LastOpenVersion>8.0.40607</LastOpenVersion>
<ReferencePath>
</ReferencePath>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<DebugSecurityZoneURL>
</DebugSecurityZoneURL>
<DebugSecurityZone>NoZone</DebugSecurityZone>
<EnableASPDebugging>false</EnableASPDebugging>
<EnableASPXDebugging>false</EnableASPXDebugging>
<EnableUnmanagedDebugging>false</EnableUnmanagedDebugging>
<EnableSQLServerDebugging>false</EnableSQLServerDebugging>
<RemoteDebugEnabled>false</RemoteDebugEnabled>
<RemoteDebugMachine>
</RemoteDebugMachine>
<StartAction>Project</StartAction>
<StartArguments>
</StartArguments>
<StartPage>
</StartPage>
<StartProgram>
</StartProgram>
<StartURL>
</StartURL>
<StartWorkingDirectory>
</StartWorkingDirectory>
<StartWithIE>false</StartWithIE>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<DebugSecurityZoneURL>
</DebugSecurityZoneURL>
<DebugSecurityZone>NoZone</DebugSecurityZone>
<EnableASPDebugging>false</EnableASPDebugging>
<EnableASPXDebugging>false</EnableASPXDebugging>
<EnableUnmanagedDebugging>false</EnableUnmanagedDebugging>
<EnableSQLServerDebugging>false</EnableSQLServerDebugging>
<RemoteDebugEnabled>false</RemoteDebugEnabled>
<RemoteDebugMachine>
</RemoteDebugMachine>
<StartAction>Project</StartAction>
<StartArguments>
</StartArguments>
<StartPage>
</StartPage>
<StartProgram>
</StartProgram>
<StartURL>
</StartURL>
<StartWorkingDirectory>
</StartWorkingDirectory>
<StartWithIE>false</StartWithIE>
</PropertyGroup>
<PropertyGroup>
<ProjectView>ProjectFiles</ProjectView>
<ProjectTrust>0</ProjectTrust>
</PropertyGroup>
</Project>
Binary file not shown.
File diff suppressed because it is too large. Load diff
+469
View File
@@ -0,0 +1,469 @@
/*
Copyright (c) 2003-2004 Niels Kokholm <[email protected]> and Peter Sestoft <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
using System.Diagnostics;
using MSG = System.Collections.Generic;
namespace C5
{
/// <summary>
/// An entry in a dictionary from K to V.
/// </summary>
public struct KeyValuePair<K,V>
{
/// <summary>
/// The key field of the entry
/// </summary>
public K key;
/// <summary>
/// The value field of the entry
/// </summary>
public V value;
/// <summary>
/// Create an entry with specified key and value
/// </summary>
/// <param name="k">The key</param>
/// <param name="v">The value</param>
public KeyValuePair(K k, V v) { key = k; value = v; }
/// <summary>
/// Create an entry with a specified key. The value is undefined.
/// </summary>
/// <param name="k">The key</param>
public KeyValuePair(K k) { key = k; value = default(V); }
/// <summary>
/// Pretty print an entry
/// </summary>
/// <returns>(key, value)</returns>
[Tested]
public override string ToString() { return "(" + key + ", " + value + ")"; }
/// <summary>
/// Check equality of entries
/// </summary>
/// <param name="obj">The other object</param>
/// <returns>True if obj is an entry of the same type and has the same key</returns>
[Tested]
public override bool Equals(object obj)
{ return obj is KeyValuePair<K,V> && key.Equals(((KeyValuePair<K,V>)obj).key); }
/// <summary>
/// Get the hash code of the key.
/// </summary>
/// <returns>The hash code</returns>
[Tested]
public override int GetHashCode() { return key.GetHashCode(); }
}
/// <summary>
/// Default comparer for dictionary entries in a sorted dictionary.
/// Entry comparisons only look at keys.
/// </summary>
public class KeyValuePairComparer<K,V>: IComparer<KeyValuePair<K,V>>
{
IComparer<K> myc;
/// <summary>
/// Create an entry comparer for a item comparer of the keys
/// </summary>
/// <param name="c">Comparer of keys</param>
public KeyValuePairComparer(IComparer<K> c) { myc = c; }
/// <summary>
/// Compare two entries
/// </summary>
/// <param name="a">First entry</param>
/// <param name="b">Second entry</param>
/// <returns>The result of comparing the keys</returns>
[Tested]
public int Compare(KeyValuePair<K,V> a, KeyValuePair<K,V> b)
{ return myc.Compare(a.key, b.key); }
}
/// <summary>
/// Default hasher for dictionary entries.
/// Operations only look at keys.
/// </summary>
public sealed class KeyValuePairHasher<K,V>: IHasher<KeyValuePair<K,V>>
{
IHasher<K> myh;
/// <summary>
/// Create an entry hasher using the default hasher for keys
/// </summary>
public KeyValuePairHasher() { myh = HasherBuilder.ByPrototype<K>.Examine(); }
/// <summary>
/// Create an entry hasher from a specified item hasher for the keys
/// </summary>
/// <param name="c">The key hasher</param>
public KeyValuePairHasher(IHasher<K> c) { myh = c; }
/// <summary>
/// Get the hash code of the entry
/// </summary>
/// <param name="item">The entry</param>
/// <returns>The hash code of the key</returns>
[Tested]
public int GetHashCode(KeyValuePair<K,V> item) { return myh.GetHashCode(item.key); }
/// <summary>
/// Test two entries for equality
/// </summary>
/// <param name="i1">First entry</param>
/// <param name="i2">Second entry</param>
/// <returns>True if keys are equal</returns>
[Tested]
public bool Equals(KeyValuePair<K,V> i1, KeyValuePair<K,V> i2)
{ return myh.Equals(i1.key, i2.key); }
}
/// <summary>
/// A base class for implementing a dictionary based on a set collection implementation.
/// <p>See the source code for <see cref="T:C5.HashDictionary!2"/> for an example</p>
///
/// </summary>
public abstract class DictionaryBase<K,V>: EnumerableBase<KeyValuePair<K,V>>, IDictionary<K,V>
{
/// <summary>
/// The set collection of entries underlying this dictionary implementation
/// </summary>
protected ICollection<KeyValuePair<K,V>> pairs;
#region IDictionary<K,V> Members
/// <summary>
///
/// </summary>
/// <value>The number of entrues in the dictionary</value>
[Tested]
public int Count { [Tested]get { return pairs.Count; } }
/// <summary>
///
/// </summary>
/// <value>A distinguished object to use for locking to synchronize multithreaded access</value>
[Tested]
public object SyncRoot { [Tested]get { return pairs.SyncRoot; } }
/// <summary>
/// Add a new (key, value) pair (a mapping) to the dictionary.
/// <exception cref="InvalidOperationException"/> if there already is an entry with the same key.
/// </summary>
/// <param name="key">Key to add</param>
/// <param name="val">Value to add</param>
[Tested]
public void Add(K key, V val)
{
KeyValuePair<K,V> p = new KeyValuePair<K,V>(key, val);
if (!pairs.Add(p))
throw new System.ArgumentException("Item has already been added. Key in dictionary: '" + key + "' Key being added: '" + key + "'");
}
/// <summary>
/// Remove an entry with a given key from the dictionary
/// </summary>
/// <param name="key">The key of the entry to remove</param>
/// <returns>True if an entry was found (and removed)</returns>
[Tested]
public bool Remove(K key)
{
KeyValuePair<K,V> p = new KeyValuePair<K,V>(key);
return pairs.Remove(p);
}
/// <summary>
/// Remove an entry with a given key from the dictionary and report its value.
/// </summary>
/// <param name="key">The key of the entry to remove</param>
/// <param name="val">On exit, the value of the removed entry</param>
/// <returns>True if an entry was found (and removed)</returns>
[Tested]
public bool Remove(K key, out V val)
{
KeyValuePair<K,V> p = new KeyValuePair<K,V>(key);
if (pairs.RemoveWithReturn(ref p))
{
val = p.value;
return true;
}
else
{
val = default(V);
return false;
}
}
/// <summary>
/// Remove all entries from the dictionary
/// </summary>
[Tested]
public void Clear() { pairs.Clear(); }
/// <summary>
/// Check if there is an entry with a specified key
/// </summary>
/// <param name="key">The key to look for</param>
/// <returns>True if key was found</returns>
[Tested]
public bool Contains(K key)
{
KeyValuePair<K,V> p = new KeyValuePair<K,V>(key);
return pairs.Contains(p);
}
/// <summary>
/// Check if there is an entry with a specified key and report the corresponding
/// value if found. This can be seen as a safe form of "val = this[key]".
/// </summary>
/// <param name="key">The key to look for</param>
/// <param name="val">On exit, the value of the entry</param>
/// <returns>True if key was found</returns>
[Tested]
public bool Find(K key, out V val)
{
KeyValuePair<K,V> p = new KeyValuePair<K,V>(key);
if (pairs.Find(ref p))
{
val = p.value;
return true;
}
else
{
val = default(V);
return false;
}
}
/// <summary>
/// Look for a specific key in the dictionary and if found replace the value with a new one.
/// This can be seen as a non-adding version of "this[key] = val".
/// </summary>
/// <param name="key">The key to look for</param>
/// <param name="val">The new value</param>
/// <returns>True if key was found</returns>
[Tested]
public bool Update(K key, V val)
{
KeyValuePair<K,V> p = new KeyValuePair<K,V>(key, val);
return pairs.Update(p);
}
/// <summary>
/// Look for a specific key in the dictionary. If found, report the corresponding value,
/// else add an entry with the key and the supplied value.
/// </summary>
/// <param name="key">The key to look for</param>
/// <param name="val">On entry the value to add if the key is not found.
/// On exit the value found if any.</param>
/// <returns>True if key was found</returns>
[Tested]
public bool FindOrAdd(K key, ref V val)
{
KeyValuePair<K,V> p = new KeyValuePair<K,V>(key, val);
if (!pairs.FindOrAdd(ref p))
return false;
else
{
val = p.value;
return true;
}
}
/// <summary>
/// Update value in dictionary corresponding to key if found, else add new entry.
/// More general than "this[key] = val;" by reporting if key was found.
/// </summary>
/// <param name="key">The key to look for</param>
/// <param name="val">The value to add or replace with.</param>
/// <returns>True if entry was updated.</returns>
[Tested]
public bool UpdateOrAdd(K key, V val)
{
return pairs.UpdateOrAdd(new KeyValuePair<K,V>(key, val));
}
#region Keys,Values support classes
internal class ValuesCollection: CollectionValueBase<V>, ICollectionValue<V>
{
ICollection<KeyValuePair<K,V>> pairs;
internal ValuesCollection(ICollection<KeyValuePair<K,V>> pairs)
{ this.pairs = pairs; }
[Tested]
public override MSG.IEnumerator<V> GetEnumerator()
{
//Updatecheck is performed by the pairs enumerator
foreach (KeyValuePair<K,V> p in pairs)
yield return p.value;
}
[Tested]
public override int Count { [Tested]get { return pairs.Count; } }
public override Speed CountSpeed { get { return Speed.Constant; } }
}
internal class KeysCollection: CollectionValueBase<K>, ICollectionValue<K>
{
ICollection<KeyValuePair<K,V>> pairs;
internal KeysCollection(ICollection<KeyValuePair<K,V>> pairs)
{ this.pairs = pairs; }
[Tested]
public override MSG.IEnumerator<K> GetEnumerator()
{
foreach (KeyValuePair<K,V> p in pairs)
yield return p.key;
}
[Tested]
public override int Count { [Tested]get { return pairs.Count; } }
public override Speed CountSpeed { get { return pairs.CountSpeed; } }
}
#endregion
/// <summary>
///
/// </summary>
/// <value>A collection containg the all the keys of the dictionary</value>
[Tested]
public ICollectionValue<K> Keys { [Tested]get { return new KeysCollection(pairs); } }
/// <summary>
///
/// </summary>
/// <value>A collection containing all the values of the dictionary</value>
[Tested]
public ICollectionValue<V> Values { [Tested]get { return new ValuesCollection(pairs); } }
/// <summary>
/// Indexer for dictionary.
/// <exception cref="InvalidOperationException"/> if no entry is found.
/// </summary>
/// <value>The value corresponding to the key</value>
[Tested]
public V this[K key]
{
[Tested]
get
{
KeyValuePair<K,V> p = new KeyValuePair<K,V>(key);
if (pairs.Find(ref p))
return p.value;
else
throw new System.ArgumentException("Key not present in Dictionary");
}
[Tested]
set
{ pairs.UpdateOrAdd(new KeyValuePair<K,V>(key, value)); }
}
/// <summary>
///
/// </summary>
/// <value>True if dictionary is read only</value>
[Tested]
public bool IsReadOnly { [Tested]get { return pairs.IsReadOnly; } }
/// <summary>
/// Check the integrity of the internal data structures of this dictionary.
/// Only avaliable in DEBUG builds???
/// </summary>
/// <returns>True if check does not fail.</returns>
[Tested]
public bool Check() { return pairs.Check(); }
#endregion
#region IEnumerable<KeyValuePair<K,V>> Members
/// <summary>
/// Create an enumerator for the collection of entries of the dictionary
/// </summary>
/// <returns>The enumerator</returns>
[Tested]
public override MSG.IEnumerator<KeyValuePair<K,V>> GetEnumerator()
{
return pairs.GetEnumerator();;
}
#endregion
}
}
File diff suppressed because it is too large. Load diff
+19
View File
@@ -0,0 +1,19 @@
Copyright (c) 2003-2004 Niels Joergen Kokholm <[email protected]>, Peter Sestoft <[email protected]>
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.
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+636
View File
@@ -0,0 +1,636 @@
/*
Copyright (c) 2003-2004 Niels Kokholm <[email protected]> and Peter Sestoft <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
using System.Diagnostics;
using MSG = System.Collections.Generic;
namespace C5
{
/// <summary>
/// A set collection based on a dynamic array combined with a hash index
/// for item to index lookup.
/// </summary>
public class HashedArrayList<T>: ArrayList<T>, IList<T>
{
#region Fields
HashSet<KeyValuePair<T,int>> index;
#endregion
#region Util
private void reindex(int start) { reindex(start, underlyingsize); }
private void reindex(int start, int end)
{
for (int j = start; j < end; j++)
index.Update(new KeyValuePair<T,int>(array[j], j));
}
/// <summary>
/// Internal version of IndexOf without modification checks.
/// </summary>
/// <param name="item">Item to look for</param>
/// <returns>The index of first occurrence</returns>
protected override int indexOf(T item)
{
KeyValuePair<T,int> p = new KeyValuePair<T,int>(item);
if (!index.Find(ref p) || p.value < offset || p.value >= offset + size)
return -1;
return p.value - offset;
}
/// <summary>
/// Internal version of LastIndexOf without modification checks.
/// </summary>
/// <param name="item">Item to look for</param>
/// <returns>The index of last occurrence</returns>
protected override int lastIndexOf(T item) { return indexOf(item); }
/// <summary>
/// Internal version of Insert with no modification checks.
/// <exception cref="ArgumentException"/> if item already in list.
/// </summary>
/// <param name="i">Index to insert at</param>
/// <param name="item">Item to insert</param>
protected override void insert(int i, T item)
{
KeyValuePair<T,int> p = new KeyValuePair<T,int>(item, offset + i);
if (index.FindOrAdd(ref p))
throw new ArgumentException("Item already in indexed list");
base.insert(i, item);
reindex(i + 1);
}
/// <summary>
/// Internal version of RemoveAt with no modification checks.
/// </summary>
/// <param name="i">Index to remove at</param>
/// <returns>The removed item</returns>
protected override T removeAt(int i)
{
T val = base.removeAt(i);
index.Remove(new KeyValuePair<T,int>(val));
reindex(offset + i);
return val;
}
#endregion
#region Constructors
/// <summary>
/// Create a hashed array list with the natural hasher
/// </summary>
public HashedArrayList() : this(8) { }
/// <summary>
/// Create a hashed array list with the natural hasher and specified capacity
/// </summary>
/// <param name="cap">The initial capacity</param>
public HashedArrayList(int cap) : this(cap,HasherBuilder.ByPrototype<T>.Examine()) { }
/// <summary>
/// Create a hashed array list with an external hasher
/// </summary>
/// <param name="hasher">The external hasher</param>
public HashedArrayList(IHasher<T> hasher) : this(8,hasher) { }
/// <summary>
/// Create a hashed array list with an external hasher and specified capacity
/// </summary>
/// <param name="capacity">The initial capacity</param>
/// <param name="hasher">The external hasher</param>
public HashedArrayList(int capacity, IHasher<T> hasher) : base(capacity, hasher)
{
index = new HashSet<KeyValuePair<T,int>>(new KeyValuePairHasher<T,int>(hasher));
}
#endregion
#region IList<T> Members
/// <summary>
/// Insert into this list all items from an enumerable collection starting
/// at a particular index.
/// <exception cref="IndexOutOfRangeException"/> if i is negative or
/// &gt; the size of the collection.
/// <exception cref="InvalidOperationException"/> if one of the items to insert is
/// already in the list.
/// </summary>
/// <param name="i">Index to start inserting at</param>
/// <param name="items">Items to insert</param>
[Tested]
public override void InsertAll(int i, MSG.IEnumerable<T> items)
{
updatecheck();
if (i < 0 || i > size)
throw new IndexOutOfRangeException();
i += offset;
int j = i, toadd;
KeyValuePair<T,int> p = new KeyValuePair<T,int>();
foreach (T item in items)
{
p.key = item;
p.value = j;
if (!index.FindOrAdd(ref p)) j++;
}
toadd = j - i;
if (toadd + underlyingsize > array.Length)
expand(toadd + underlyingsize, underlyingsize);
if (underlyingsize > i)
Array.Copy(array, i, array, j, underlyingsize - i);
foreach (T item in items)
{
p.key = item;
index.Find(ref p);
if (i <= p.value && p.value < i + toadd)
array[p.value] = item;
}
addtosize(toadd);
reindex(j);
}
internal override void InsertAll<U>(int i, MSG.IEnumerable<U> items) //where U:T
{
updatecheck();
if (i < 0 || i > size)
throw new IndexOutOfRangeException();
i += offset;
int j = i, toadd;
KeyValuePair<T, int> p = new KeyValuePair<T, int>();
foreach (T item in items)
{
p.key = item;
p.value = j;
if (!index.FindOrAdd(ref p)) j++;
}
toadd = j - i;
if (toadd + underlyingsize > array.Length)
expand(toadd + underlyingsize, underlyingsize);
if (underlyingsize > i)
Array.Copy(array, i, array, j, underlyingsize - i);
foreach (T item in items)
{
p.key = item;
index.Find(ref p);
if (i <= p.value && p.value < i + toadd)
array[p.value] = item;
}
addtosize(toadd);
reindex(j);
}
/// <summary>
/// Insert an item right before the first occurrence of some target item.
/// <exception cref="ArgumentException"/> if target is not found.
/// <exception cref="InvalidOperationException"/> if the item to insert is
/// already in the list.
/// </summary>
/// <param name="item">The item to insert.</param>
/// <param name="target">The target before which to insert.</param>
[Tested]
public override void InsertBefore(T item, T target)
{
updatecheck();
int ind = indexOf(target);
if (ind < 0)
throw new ArgumentException("Target item not found");
insert(ind, item);
}
/// <summary>
/// Insert an item right after the last(???) occurrence of some target item.
/// <exception cref="ArgumentException"/> if target is not found.
/// <exception cref="InvalidOperationException"/> if the item to insert is
/// already in the list.
/// </summary>
/// <param name="item">The item to insert.</param>
/// <param name="target">The target after which to insert.</param>
[Tested]
public override void InsertAfter(T item, T target)
{
updatecheck();
int ind = indexOf(target);
if (ind < 0)
throw new ArgumentException("Target item not found");
insert(ind + 1, item);
}
/// <summary>
/// Create a list view on this list.
/// <exception cref="ArgumentOutOfRangeException"/> if the view would not fit into
/// this list.
/// </summary>
/// <param name="start">The index in this list of the start of the view.</param>
/// <param name="count">The size of the view.</param>
/// <returns>The new list view.</returns>
[Tested]
public override IList<T> View(int start, int count)
{
HashedArrayList<T> retval = (HashedArrayList<T>)MemberwiseClone();
retval.underlying = underlying != null ? underlying : this;
retval.offset = start;
retval.size = count;
return retval;
}
/// <summary>
/// Reverst part of the list so the items are in the opposite sequence order.
/// <exception cref="ArgumentException"/> if the count is negative.
/// <exception cref="ArgumentOutOfRangeException"/> if the part does not fit
/// into the list.
/// </summary>
/// <param name="start">The index of the start of the part to reverse.</param>
/// <param name="count">The size of the part to reverse.</param>
[Tested]
public override void Reverse(int start, int count)
{
base.Reverse(start, count);
reindex(offset + start, offset + start + count);
}
/// <summary>
/// Sort the items of the list according to a specific sorting order.
/// </summary>
/// <param name="c">The comparer defining the sorting order.</param>
[Tested]
public override void Sort(IComparer<T> c)
{
base.Sort(c);
reindex(offset, offset + size);
}
/// <summary>
/// Shuffle the items of this list according to a specific random source.
/// </summary>
/// <param name="rnd">The random source.</param>
public override void Shuffle(Random rnd)
{
base.Shuffle(rnd);
reindex(offset, offset + size);
}
#endregion
#region IIndexed<T> Members
/// <summary>
/// Remove all items in an index interval.
/// <exception cref="IndexOutOfRangeException"/>???.
/// </summary>
/// <param name="start">The index of the first item to remove.</param>
/// <param name="count">The number of items to remove.</param>
[Tested]
public override void RemoveInterval(int start, int count)
{
updatecheck();
KeyValuePair<T,int> p = new KeyValuePair<T,int>();
for (int i = offset + start, end = offset + start + count; i < end; i++)
{
p.key = array[i];
index.Remove(p);
}
base.RemoveInterval(start, count);
reindex(offset + start);
}
#endregion
#region ISequenced<T> Members
int ISequenced<T>.GetHashCode()
{ modifycheck(); return sequencedhashcode(); }
bool ISequenced<T>.Equals(ISequenced<T> that)
{ modifycheck(); return sequencedequals(that); }
#endregion
#region IEditableCollection<T> Members
/// <summary>
/// The value is symbolic indicating the type of asymptotic complexity
/// in terms of the size of this collection (expected).
/// </summary>
/// <value>Speed.Constant</value>
[Tested]
public override Speed ContainsSpeed { [Tested]get { return Speed.Constant; } }
/// <summary>
/// Check if this collection contains (an item equivalent to according to the
/// itemhasher) a particular value.
/// </summary>
/// <param name="item">The value to check for.</param>
/// <returns>True if the items is in this collection.</returns>
[Tested]
public override bool Contains(T item)
{ modifycheck(); return indexOf(item) >= 0; }
/// <summary>
/// Remove the first copy of a particular item from this collection.
/// </summary>
/// <param name="item">The value to remove.</param>
/// <returns>True if the item was found (and removed).</returns>
[Tested]
public override bool Remove(T item)
{
updatecheck();
int ind = indexOf(item);
if (ind < 0)
return false;
removeAt(ind);
return true;
}
/// <summary>
/// Remove all items in another collection from this one, taking multiplicities into account.
/// Matching items will be removed from the front. Current implementation is not optimal.
/// </summary>
/// <param name="items">The items to remove.</param>
[Tested]
public override void RemoveAll(MSG.IEnumerable<T> items)
{
updatecheck();
KeyValuePair<T,int> p = new KeyValuePair<T,int>();
foreach (T item in items)
{
p.key = item;
if (index.Find(ref p) && offset <= p.value && p.value < offset + size)
index.Remove(p);
}
int removed = underlyingsize - index.Count, j = offset;
for (int i = offset; i < underlyingsize; i++)
{
p.key = array[i];
p.value = j;
if (index.Update(p)) { array[j++] = p.key; }
}
addtosize(-removed);
Array.Clear(array, underlyingsize, removed);
}
/// <summary>
/// Remove all items from this collection, resetting internal array size.
/// </summary>
[Tested]
public override void Clear()
{
updatecheck();
if (underlying == null)
{
index.Clear();
base.Clear();
}
else
{
for (int i = offset, end = offset + size; i < end; i++)
index.Remove(new KeyValuePair<T,int>(array[i]));
base.Clear();
reindex(offset);
}
}
/// <summary>
/// Remove all items not in some other collection from this one.
/// </summary>
/// <param name="items">The items to retain.</param>
[Tested]
public override void RetainAll(MSG.IEnumerable<T> items)
{
updatecheck();
HashSet<T> toretain = new HashSet<T>(itemhasher);
KeyValuePair<T,int> p = new KeyValuePair<T,int>();
foreach (T item in items)
{
p.key = item;
if (index.Find(ref p) && offset <= p.value && p.value < offset + size)
toretain.Add(item);
}
int removed = size - toretain.Count, j = offset;
for (int i = offset; i < offset + size; i++)
{
p.key = array[i];
p.value = j;
if (toretain.Contains(p.key))
{
index.Update(p);
array[j++] = p.key;
}
else
{
index.Remove(p);
}
}
Array.Copy(array, offset + size, array, j, underlyingsize - offset - size);
addtosize(-removed);
reindex(j);
Array.Clear(array, underlyingsize, removed);
}
/// <summary>
/// Check if this collection contains all the values in another collection.
/// </summary>
/// <param name="items">The </param>
/// <returns>True if all values in <code>items</code>is in this collection.</returns>
[Tested]
public override bool ContainsAll(MSG.IEnumerable<T> items)
{
modifycheck();
foreach (T item in items)
if (indexOf(item) < 0)
return false;
return true;
}
/// <summary>
/// Count the number of items of the collection equal to a particular value.
/// Returns 0 if and only if the value is not in the collection.
/// </summary>
/// <param name="item">The value to count.</param>
/// <returns>The number of copies found (0 or 1).</returns>
[Tested]
public override int ContainsCount(T item)
{ modifycheck(); return indexOf(item) >= 0 ? 1 : 0; }
/// <summary>
/// Remove all items equal to a given one.
/// </summary>
/// <param name="item">The value to remove.</param>
[Tested]
public override void RemoveAllCopies(T item) { Remove(item); }
/// <summary>
/// Check the integrity of the internal data structures of this array list.
/// </summary>
/// <returns>True if check does not fail.</returns>
[Tested]
public override bool Check()
{
if (!base.Check())
return false;
bool retval = true;
if (underlyingsize != index.Count)
{
Console.WriteLine("size ({0})!= index.Count ({1})", size, index.Count);
retval = false;
}
for (int i = 0; i < underlyingsize; i++)
{
KeyValuePair<T,int> p = new KeyValuePair<T,int>(array[i]);
if (!index.Find(ref p))
{
Console.WriteLine("Item {1} at {0} not in hashindex", i, array[i]);
retval = false;
}
if (p.value != i)
{
Console.WriteLine("Item {1} at {0} has hashindex {2}", i, array[i], p.value);
retval = false;
}
}
return retval;
}
int ICollection<T>.GetHashCode() { return unsequencedhashcode(); }
bool ICollection<T>.Equals(ICollection<T> that)
{ return unsequencedequals(that); }
#endregion
#region ISink<T> Members
/// <summary>
///
/// </summary>
/// <value>False, indicating hashed array list has set semantics.</value>
[Tested]
public override bool AllowsDuplicates { [Tested]get { return false; } }
/// <summary>
/// Add an item to end of this list if not already in list.
/// </summary>
/// <param name="item">The item to add.</param>
/// <returns>True if item was added</returns>
[Tested]
public override bool Add(T item)
{
updatecheck();
KeyValuePair<T,int> p = new KeyValuePair<T,int>(item, size);
if (index.FindOrAdd(ref p))
return false;
base.insert(size, item);
reindex(size);
return true;
}
#endregion
#region IDirectedEnumerable<T> Members
IDirectedEnumerable<T> IDirectedEnumerable<T>.Backwards() { return Backwards(); }
#endregion
}
}
File diff suppressed because it is too large. Load diff
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large. Load diff
+492
View File
@@ -0,0 +1,492 @@
/*
Copyright (c) 2003-2004 Niels Kokholm <[email protected]> and Peter Sestoft <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
using System.Diagnostics;
using MSG = System.Collections.Generic;
namespace C5
{
/// <summary>
/// A bag collection based on a hash table of (item,count) pairs.
/// </summary>
public class HashBag<T>: CollectionBase<T>, ICollection<T>
{
#region Fields
HashSet<KeyValuePair<T,int>> dict;
#endregion
#region Constructors
/// <summary>
/// Create a hash bag with the deafult item hasher.
/// </summary>
public HashBag()
{
itemhasher = HasherBuilder.ByPrototype<T>.Examine();
dict = new HashSet<KeyValuePair<T,int>>();
}
/// <summary>
/// Create a hash bag with an external item hasher.
/// </summary>
/// <param name="h">The external hasher.</param>
public HashBag(IHasher<T> h)
{
itemhasher = h;
dict = new HashSet<KeyValuePair<T,int>>(new KeyValuePairHasher<T,int>(h));
}
#endregion
#region IEditableCollection<T> Members
/// <summary>
/// The complexity of the Contains operation
/// </summary>
/// <value>Always returns Speed.Constant</value>
[Tested]
public virtual Speed ContainsSpeed { [Tested]get { return Speed.Constant; } }
[Tested]
int ICollection<T>.GetHashCode() { return unsequencedhashcode(); }
[Tested]
bool ICollection<T>.Equals(ICollection<T> that)
{ return unsequencedequals(that); }
/// <summary>
/// Check if an item is in the bag
/// </summary>
/// <param name="item">The item to look for</param>
/// <returns>True if bag contains item</returns>
[Tested]
public virtual bool Contains(T item)
{ return dict.Contains(new KeyValuePair<T,int>(item, 0)); }
/// <summary>
/// Check if an item (collection equal to a given one) is in the bag and
/// if so report the actual item object found.
/// </summary>
/// <param name="item">On entry, the item to look for.
/// On exit the item found, if any</param>
/// <returns>True if bag contains item</returns>
[Tested]
public virtual bool Find(ref T item)
{
KeyValuePair<T,int> p = new KeyValuePair<T,int>(item, 0);
if (dict.Find(ref p))
{
item = p.key;
return true;
}
return false;
}
/// <summary>
/// Check if an item (collection equal to a given one) is in the bag and
/// if so replace the item object in the bag with the supplied one.
/// </summary>
/// <param name="item">The item object to update with</param>
/// <returns>True if item was found (and updated)</returns>
[Tested]
public virtual bool Update(T item)
{
KeyValuePair<T,int> p = new KeyValuePair<T,int>(item, 0);
updatecheck();
//Note: we cannot just do dict.Update. There is of course a way
//around if we use the implementation of hashset -which we do not want to do.
//The hashbag is moreover mainly a proof of concept
if (dict.Find(ref p))
{
p.key = item;
dict.Update(p);
return true;
}
return false;
}
/// <summary>
/// Check if an item (collection equal to a given one) is in the bag.
/// If found, report the actual item object in the bag,
/// else add the supplied one.
/// </summary>
/// <param name="item">On entry, the item to look for or add.
/// On exit the actual object found, if any.</param>
/// <returns>True if item was found</returns>
[Tested]
public virtual bool FindOrAdd(ref T item)
{
updatecheck();
if (Find(ref item))
return true;
Add(item);
return false;
}
/// <summary>
/// Check if an item (collection equal to a supplied one) is in the bag and
/// if so replace the item object in the set with the supplied one; else
/// add the supplied one.
/// </summary>
/// <param name="item">The item to look for and update or add</param>
/// <returns>True if item was updated</returns>
[Tested]
public virtual bool UpdateOrAdd(T item)
{
updatecheck();
if (Update(item))
return true;
Add(item);
return false;
}
/// <summary>
/// Remove one copy af an item from the bag
/// </summary>
/// <param name="item">The item to remove</param>
/// <returns>True if item was (found and) removed </returns>
[Tested]
public virtual bool Remove(T item)
{
KeyValuePair<T,int> p = new KeyValuePair<T,int>(item, 0);
updatecheck();
if (dict.Find(ref p))
{
size--;
if (p.value == 1)
dict.Remove(p);
else
{
p.value--;
dict.Update(p);
}
return true;
}
return false;
}
/// <summary>
/// Remove one copy of an item from the bag, reporting the actual matching item object.
/// </summary>
/// <param name="item">On entry the item to remove.
/// On exit, the actual removed item object.</param>
/// <returns>True if item was found.</returns>
[Tested]
public virtual bool RemoveWithReturn(ref T item)
{
KeyValuePair<T,int> p = new KeyValuePair<T,int>(item, 0);
updatecheck();
if (dict.Find(ref p))
{
item = p.key;
size--;
if (p.value == 1)
dict.Remove(p);
else
{
p.value--;
dict.Update(p);
}
return true;
}
return false;
}
/// <summary>
/// Remove all items in a supplied collection from this bag, counting multiplicities.
/// </summary>
/// <param name="items">The items to remove.</param>
[Tested]
public virtual void RemoveAll(MSG.IEnumerable<T> items)
{
updatecheck();
foreach (T item in items)
Remove(item);
}
/// <summary>
/// Remove all items from the bag, resetting internal table to initial size.
/// </summary>
[Tested]
public virtual void Clear()
{
updatecheck();
dict.Clear();
size = 0;
}
/// <summary>
/// Remove all items *not* in a supplied collection from this bag,
/// counting multiplicities.
/// </summary>
/// <param name="items">The items to retain</param>
[Tested]
public virtual void RetainAll(MSG.IEnumerable<T> items)
{
updatecheck();
HashBag<T> res = new HashBag<T>(itemhasher);
foreach (T item in items)
if (res.ContainsCount(item) < ContainsCount(item))
res.Add(item);
dict = res.dict;
size = res.size;
}
/// <summary>
/// Check if all items in a supplied collection is in this bag
/// (counting multiplicities).
/// </summary>
/// <param name="items">The items to look for.</param>
/// <returns>True if all items are found.</returns>
[Tested]
public virtual bool ContainsAll(MSG.IEnumerable<T> items)
{
HashBag<T> res = new HashBag<T>(itemhasher);
foreach (T item in items)
if (res.ContainsCount(item) < ContainsCount(item))
res.Add(item);
else
return false;
return true;
}
/// <summary>
/// Create an array containing all items in this bag (in enumeration order).
/// </summary>
/// <returns>The array</returns>
[Tested]
public override T[] ToArray()
{
T[] res = new T[size];
int ind = 0;
foreach (KeyValuePair<T,int> p in dict)
for (int i = 0; i < p.value; i++)
res[ind++] = p.key;
return res;
}
/// <summary>
/// Count the number of times an item is in this set.
/// </summary>
/// <param name="item">The item to look for.</param>
/// <returns>The count</returns>
[Tested]
public virtual int ContainsCount(T item)
{
KeyValuePair<T,int> p = new KeyValuePair<T,int>(item, 0);
if (dict.Find(ref p))
return p.value;
return 0;
}
/// <summary>
/// Remove all copies of item from this set.
/// </summary>
/// <param name="item">The item to remove</param>
[Tested]
public virtual void RemoveAllCopies(T item)
{
updatecheck();
KeyValuePair<T,int> p = new KeyValuePair<T,int>(item, 0);
if (dict.Find(ref p))
{
size -= p.value;
dict.Remove(p);
}
}
#endregion
#region ICollection<T> Members
/// <summary>
/// Copy the items of this bag to part of an array.
/// <exception cref="ArgumentOutOfRangeException"/> if i is negative.
/// <exception cref="ArgumentException"/> if the array does not have room for the items.
/// </summary>
/// <param name="a">The array to copy to</param>
/// <param name="i">The starting index.</param>
[Tested]
public override void CopyTo(T[] a, int i)
{
if (i < 0)
throw new ArgumentOutOfRangeException();
if (i + size > a.Length)
throw new ArgumentException();
foreach (KeyValuePair<T,int> p in dict)
for (int j = 0; j < p.value; j++)
a[i++] = p.key;
}
#endregion
#region ISink<T> Members
/// <summary>
/// Report if this is a set collection.
/// </summary>
/// <value>Always true</value>
[Tested]
public virtual bool AllowsDuplicates { [Tested] get { return true; } }
/// <summary>
/// Add an item to this bag.
/// </summary>
/// <param name="item">The item to add.</param>
/// <returns>Always true</returns>
[Tested]
public virtual bool Add(T item)
{
KeyValuePair<T,int> p = new KeyValuePair<T,int>(item, 1);
updatecheck();
if (dict.Find(ref p))
{
p.value++;
dict.Update(p);
}
else
dict.Add(p);
size++;
return true;
}
/// <summary>
/// Add all items of a collection to this set.
/// </summary>
/// <param name="items">The items to add</param>
[Tested]
public virtual void AddAll(MSG.IEnumerable<T> items)
{
foreach (T item in items)
Add(item);
}
/// <summary>
/// Add the elements from another collection with a more specialized item type
/// to this collection.
/// </summary>
/// <typeparam name="U">The type of items to add</typeparam>
/// <param name="items">The items to add</param>
public virtual void AddAll<U>(MSG.IEnumerable<U> items) where U : T
{
foreach (T item in items)
Add(item);
}
#endregion
#region IEnumerable<T> Members
/// <summary>
/// Create an enumerator for this bag.
/// </summary>
/// <returns>The enumerator</returns>
[Tested]
public override MSG.IEnumerator<T> GetEnumerator()
{
int left;
int mystamp = stamp;
foreach (KeyValuePair<T,int> p in dict)
{
left = p.value;
while (left > 0)
{
if (mystamp != stamp)
throw new InvalidOperationException("Collection was changed");
left--;
yield return p.key;
}
}
}
#endregion
#region Diagnostics
/// <summary>
/// Test internal structure of data (invariants)
/// </summary>
/// <returns>True if pass</returns>
[Tested]
public virtual bool Check()
{
bool retval = dict.Check();
int count = 0;
foreach (KeyValuePair<T,int> p in dict)
count += p.value;
if (count != size)
{
Console.WriteLine("count({0}) != size({1})", count, size);
retval = false;
}
return retval;
}
#endregion
}
}
@@ -0,0 +1,70 @@
/*
Copyright (c) 2003-2004 Niels Kokholm <[email protected]> and Peter Sestoft <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
using System.Diagnostics;
using MSG = System.Collections.Generic;
namespace C5
{
/// <summary>
/// A generic dictionary class based on a hash set class <see cref="T:C5.HashSet!1"/>.
/// </summary>
public class HashDictionary<K,V>: DictionaryBase<K,V>, IDictionary<K,V>
{
/// <summary>
/// Create a hash dictionary using a default hasher for the keys.
/// Initial capacity of internal table will be 16 entries and threshold for
/// expansion is 66% fill.
/// </summary>
public HashDictionary()
{
pairs = new HashSet<KeyValuePair<K,V>>(new KeyValuePairHasher<K,V>());
}
/// <summary>
/// Create a hash dictionary using a custom hasher for the keys.
/// Initial capacity of internal table will be 16 entries and threshold for
/// expansion is 66% fill.
/// </summary>
/// <param name="h">The external key hasher</param>
public HashDictionary(IHasher<K> h)
{
pairs = new HashSet<KeyValuePair<K,V>>(new KeyValuePairHasher<K,V>(h));
}
/// <summary>
/// Create a hash dictionary using a custom hasher and prescribing the
/// initial size of the dictionary and a non-default threshold for internal table expansion.
/// </summary>
/// <param name="capacity">The initial capacity. Will be rounded upwards to nearest
/// power of 2, at least 16.</param>
/// <param name="fill">The expansion threshold. Must be between 10% and 90%.</param>
/// <param name="h">The external key hasher</param>
public HashDictionary(int capacity, double fill, IHasher<K> h)
{
KeyValuePairHasher<K,V> kvph = new KeyValuePairHasher<K,V>(h);
pairs = new HashSet<KeyValuePair<K,V>>(capacity, fill, kvph);
}
}
}
File diff suppressed because it is too large. Load diff
+568
View File
@@ -0,0 +1,568 @@
/*
Copyright (c) 2003-2004 Niels Kokholm <[email protected]> and Peter Sestoft <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
using System.Diagnostics;
using MSG = System.Collections.Generic;
namespace C5
{
/// <summary>
/// A priority queue class based on an interval heap data structure.
/// </summary>
public class IntervalHeap<T>: CollectionValueBase<T>, IPriorityQueue<T>
{
#region Fields
struct Interval
{
internal T first, last;
public override string ToString() { return String.Format("[{0}; {1}]", first, last); }
}
object syncroot = new object();
int stamp;
IComparer<T> comparer;
Interval[] heap;
int size;
#endregion
#region Util
void heapifyMin(int i)
{
int j = i, minpt = j;
T pv = heap[j].first, min = pv;
while (true)
{
int l = 2 * j + 1, r = l + 1;
T lv, rv, other;
if (2 * l < size && comparer.Compare(lv = heap[l].first, min) < 0) { minpt = l; min = lv; }
if (2 * r < size && comparer.Compare(rv = heap[r].first, min) < 0) { minpt = r; min = rv; }
if (minpt == j)
break;
other = heap[minpt].last;
heap[j].first = min;
if (2 * minpt + 1 < size && comparer.Compare(pv, other) > 0)
{ heap[minpt].last = pv; pv = other; }
min = pv;
j = minpt;
}
if (minpt != i)
heap[minpt].first = min;
}
void heapifyMax(int i)
{
int j = i, maxpt = j;
T pv = heap[j].last, max = pv;
while (true)
{
int l = 2 * j + 1, r = l + 1;
T lv, rv, other;
if (2 * l + 1 < size && comparer.Compare(lv = heap[l].last, max) > 0) { maxpt = l; max = lv; }
if (2 * r + 1 < size && comparer.Compare(rv = heap[r].last, max) > 0) { maxpt = r; max = rv; }
if (maxpt == j)
break;
other = heap[maxpt].first;
heap[j].last = max;
if (comparer.Compare(pv, other) < 0)
{
heap[maxpt].first = pv;
pv = other;
}
max = pv;
j = maxpt;
}
if (maxpt != i)
heap[maxpt].last = max;
}
void bubbleUpMin(int i)
{
if (i > 0)
{
T min = heap[i].first, iv = min;
int p = (i + 1) / 2 - 1;
while (i > 0)
{
if (comparer.Compare(iv, min = heap[p = (i + 1) / 2 - 1].first) < 0)
{
heap[i].first = min; min = iv;
i = p;
}
else
break;
}
heap[i].first = iv;
}
}
void bubbleUpMax(int i)
{
if (i > 0)
{
T max = heap[i].last, iv = max;
int p = (i + 1) / 2 - 1;
while (i > 0)
{
if (comparer.Compare(iv, max = heap[p = (i + 1) / 2 - 1].last) > 0)
{
heap[i].last = max; max = iv;
i = p;
}
else
break;
}
heap[i].last = iv;
}
}
#endregion
#region Constructors
/// <summary>
/// Create an interval heap with natural item comparer and default initial capacity (16)
/// </summary>
public IntervalHeap() : this(16) { }
/// <summary>
/// Create an interval heap with external item comparer and default initial capacity (16)
/// </summary>
/// <param name="c">The external comparer</param>
public IntervalHeap(IComparer<T> c) : this(c,16) { }
/// <summary>
/// Create an interval heap with natural item comparer and prescribed initial capacity
/// </summary>
/// <param name="capacity">The initial capacity</param>
public IntervalHeap(int capacity) : this(ComparerBuilder.FromComparable<T>.Examine(),capacity) { }
/// <summary>
/// Create an interval heap with external item comparer and prescribed initial capacity
/// </summary>
/// <param name="c">The external comparer</param>
/// <param name="capacity">The initial capacity</param>
public IntervalHeap(IComparer<T> c, int capacity)
{
comparer = c;
int length = 1;
while (length < capacity) length <<= 1;
heap = new Interval[length];
}
#endregion
#region IPriorityQueue<T> Members
/// <summary>
/// Find the current least item of this priority queue.
/// <exception cref="InvalidOperationException"/> if queue is empty
/// </summary>
/// <returns>The least item.</returns>
[Tested]
public T FindMin()
{
if (size == 0)
throw new InvalidOperationException("Heap is empty");
return heap[0].first;
}
/// <summary>
/// Remove the least item from this priority queue.
/// <exception cref="InvalidOperationException"/> if queue is empty
/// </summary>
/// <returns>The removed item.</returns>
[Tested]
public T DeleteMin()
{
stamp++;
if (size == 0)
throw new InvalidOperationException("Heap is empty");
T retval = heap[0].first;;
if (size == 1)
{
size = 0;
heap[0].first = default(T);
}
else
{
int ind = (size - 1) / 2;
if (size % 2 == 0)
{
heap[0].first = heap[ind].last;
heap[ind].last = default(T);
}
else
{
heap[0].first = heap[ind].first;
heap[ind].first = default(T);
}
size--;
heapifyMin(0);
}
return retval;
}
/// <summary>
/// Find the current largest item of this priority queue.
/// <exception cref="InvalidOperationException"/> if queue is empty
/// </summary>
/// <returns>The largest item.</returns>
[Tested]
public T FindMax()
{
if (size == 0)
throw new InvalidOperationException("Heap is empty");
else if (size == 1)
return heap[0].first;
else
return heap[0].last;
}
/// <summary>
/// Remove the largest item from this priority queue.
/// <exception cref="InvalidOperationException"/> if queue is empty
/// </summary>
/// <returns>The removed item.</returns>
[Tested]
public T DeleteMax()
{
stamp++;
if (size == 0)
throw new InvalidOperationException("Heap is empty");
T retval;
if (size == 1)
{
size = 0;
retval = heap[0].first;
heap[0].first = default(T);
return retval;
}
else
{
retval = heap[0].last;
int ind = (size - 1) / 2;
if (size % 2 == 0)
{
heap[0].last = heap[ind].last;
heap[ind].last = default(T);
}
else
{
heap[0].last = heap[ind].first;
heap[ind].first = default(T);
}
size--;
heapifyMax(0);
return retval;
}
}
/// <summary>
/// The comparer object supplied at creation time for this collection
/// </summary>
/// <value>The comparer</value>
public IComparer<T> Comparer { get { return comparer; } }
#endregion
#region ISink<T> Members
/// <summary>
///
/// </summary>
/// <value>True since this collection has bag semantics</value>
[Tested]
public bool AllowsDuplicates { [Tested]get { return true; } }
/// <summary>
///
/// </summary>
/// <value>The distinguished object to use for locking to synchronize multithreaded access</value>
[Tested]
public object SyncRoot { [Tested]get { return syncroot; } }
/// <summary>
///
/// </summary>
/// <value>True if this collection is empty.</value>
[Tested]
public bool IsEmpty { [Tested]get { return size == 0; } }
/// <summary>
/// Add an item to this priority queue.
/// </summary>
/// <param name="item">The item to add.</param>
/// <returns>True</returns>
[Tested]
public bool Add(T item)
{
stamp++;
if (size == 0)
{
size = 1;
heap[0].first = item;
return true;
}
if (size == 2 * heap.Length)
{
Interval[] newheap = new Interval[2 * heap.Length];
Array.Copy(heap, newheap, heap.Length);
heap = newheap;
}
if (size % 2 == 0)
{
int i = size / 2, p = (i + 1) / 2 - 1;
T tmp;
size++;
if (comparer.Compare(item, tmp = heap[p].last) > 0)
{
heap[i].first = tmp;
heap[p].last = item;
bubbleUpMax(p);
}
else
{
heap[i].first = item;
if (comparer.Compare(item, heap[p].first) < 0)
bubbleUpMin(i);
}
}
else
{
int i = size / 2;
T other = heap[i].first;
size++;
if (comparer.Compare(item, other) < 0)
{
heap[i].first = item;
heap[i].last = other;
bubbleUpMin(i);
}
else
{
heap[i].last = item;
bubbleUpMax(i);
}
}
return true;
}
/// <summary>
/// Add the elements from another collection to this collection.
/// </summary>
/// <param name="items">The items to add.</param>
[Tested]
public void AddAll(MSG.IEnumerable<T> items)
{
//TODO: avoid incrementing stamp repeatedly
foreach (T item in items)
Add(item);
}
/// <summary>
/// Add the elements from another collection with a more specialized item type
/// to this collection.
/// </summary>
/// <typeparam name="U">The type of items to add</typeparam>
/// <param name="items">The items to add</param>
public void AddAll<U>(MSG.IEnumerable<U> items) where U : T
{
//TODO: avoid incrementing stamp repeatedly
foreach (T item in items)
Add(item);
}
#endregion
#region ICollection<T> members
/// <summary>
///
/// </summary>
/// <value>The size of this collection</value>
[Tested]
public override int Count { [Tested]get { return size; } }
/// <summary>
/// The value is symbolic indicating the type of asymptotic complexity
/// in terms of the size of this collection (worst-case or amortized as
/// relevant).
/// </summary>
/// <value>A characterization of the speed of the
/// <code>Count</code> property in this collection.</value>
public override Speed CountSpeed { get { return Speed.Constant; } }
/// <summary>
/// Create an enumerator for the collection
/// <para>Note: the enumerator does *not* enumerate the items in sorted order,
/// but in the internal table order.</para>
/// </summary>
/// <returns>The enumerator(SIC)</returns>
[Tested]
public override MSG.IEnumerator<T> GetEnumerator()
{
int mystamp = stamp;
for (int i = 0; i < size; i++)
{
if (mystamp != stamp) throw new InvalidOperationException();
yield return i % 2 == 0 ? heap[i >> 1].first : heap[i >> 1].last;
}
yield break;
}
#endregion
#region Diagnostics
private bool check(int i, T min, T max)
{
bool retval = true;
Interval interval = heap[i];
T first = interval.first, last = interval.last;
if (2 * i + 1 == size)
{
if (comparer.Compare(min, first) > 0)
{
Console.WriteLine("Cell {0}: parent.first({1}) > first({2}) [size={3}]", i, min, first, size);
retval = false;
}
if (comparer.Compare(first, max) > 0)
{
Console.WriteLine("Cell {0}: first({1}) > parent.last({2}) [size={3}]", i, first, max, size);
retval = false;
}
return retval;
}
else
{
if (comparer.Compare(min, first) > 0)
{
Console.WriteLine("Cell {0}: parent.first({1}) > first({2}) [size={3}]", i, min, first, size);
retval = false;
}
if (comparer.Compare(first, last) > 0)
{
Console.WriteLine("Cell {0}: first({1}) > last({2}) [size={3}]", i, first, last, size);
retval = false;
}
if (comparer.Compare(last, max) > 0)
{
Console.WriteLine("Cell {0}: last({1}) > parent.last({2}) [size={3}]", i, last, max, size);
retval = false;
}
int l = 2 * i + 1, r = l + 1;
if (2 * l < size)
retval = retval && check(l, first, last);
if (2 * r < size)
retval = retval && check(r, first, last);
}
return retval;
}
/// <summary>
/// Check the integrity of the internal data structures of this collection.
/// Only avaliable in DEBUG builds???
/// </summary>
/// <returns>True if check does not fail.</returns>
[Tested]
public bool Check()
{
if (size == 0)
return true;
if (size == 1)
return (object)(heap[0].first) != null;
return check(0, heap[0].first, heap[0].last);
}
#endregion
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+1
View File
@@ -0,0 +1 @@
RedBlackTreeBag.cs
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+134
View File
@@ -0,0 +1,134 @@
/*
Copyright (c) 2003-2004 Niels Kokholm <[email protected]> and Peter Sestoft <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
using MSG = System.Collections.Generic;
namespace C5
{
/// <summary>
/// A sorted generic dictionary based on a red-black tree set.
/// </summary>
public class TreeDictionary<K,V>: DictionaryBase<K,V>, IDictionary<K,V>, ISortedDictionary<K,V>
{
#region Fields
private TreeSet<KeyValuePair<K,V>> sortedpairs;
#endregion
#region Constructors
/// <summary>
/// Create a red-black tree dictionary using the natural comparer for keys.
/// <exception cref="ArgumentException"/> if the key type K is not comparable.
/// </summary>
public TreeDictionary() : this(ComparerBuilder.FromComparable<K>.Examine()) { }
/// <summary>
/// Create a red-black tree dictionary using an external comparer for keys.
/// </summary>
/// <param name="c">The external comparer</param>
public TreeDictionary(IComparer<K> c)
{
pairs = sortedpairs = new TreeSet<KeyValuePair<K,V>>(new KeyValuePairComparer<K,V>(c));
}
#endregion
#region ISortedDictionary<K,V> Members
/// <summary>
/// Get the entry in the dictionary whose key is the
/// predecessor of a specified key.
/// </summary>
/// <param name="key">The key</param>
/// <returns>The entry</returns>
[Tested]
public KeyValuePair<K,V> Predecessor(K key)
{
KeyValuePair<K,V> p = new KeyValuePair<K,V>(key);
return sortedpairs.Predecessor(p);
}
/// <summary>
/// Get the entry in the dictionary whose key is the
/// weak predecessor of a specified key.
/// </summary>
/// <param name="key">The key</param>
/// <returns>The entry</returns>
[Tested]
public KeyValuePair<K,V> WeakPredecessor(K key)
{
KeyValuePair<K,V> p = new KeyValuePair<K,V>(key);
return sortedpairs.WeakPredecessor(p);
}
/// <summary>
/// Get the entry in the dictionary whose key is the
/// successor of a specified key.
/// </summary>
/// <param name="key">The key</param>
/// <returns>The entry</returns>
[Tested]
public KeyValuePair<K,V> Successor(K key)
{
KeyValuePair<K,V> p = new KeyValuePair<K,V>(key);
return sortedpairs.Successor(p);
}
/// <summary>
/// Get the entry in the dictionary whose key is the
/// weak successor of a specified key.
/// </summary>
/// <param name="key">The key</param>
/// <returns>The entry</returns>
[Tested]
public KeyValuePair<K,V> WeakSuccessor(K key)
{
KeyValuePair<K,V> p = new KeyValuePair<K,V>(key);
return sortedpairs.WeakSuccessor(p);
}
#endregion
//TODO: put in interface
/// <summary>
/// Make a snapshot of the current state of this dictionary
/// </summary>
/// <returns>The snapshot</returns>
[Tested]
public MSG.IEnumerable<KeyValuePair<K,V>> Snapshot()
{
TreeDictionary<K,V> res = (TreeDictionary<K,V>)MemberwiseClone();
res.pairs = (TreeSet<KeyValuePair<K,V>>)sortedpairs.Snapshot();
return res;
}
}
}
+25
View File
@@ -0,0 +1,25 @@
#!/usr/bin/perl
use strict;
open(RBTS,"RedBlackTree.cs") || die "Can't open infile";
rename "RedBlackTreeBag.cs", "RedBlackTreeBag.cs.old" || die "Can't backup";
open(RBTB,">RedBlackTreeBag.cs") || die "Can't open outfile";
my @cond=(1);
my $printing = 1;
#Assume all conditions on BAG symbol is '#if BAG'
while (<RBTS>) {
if (/^#define BAG/) {
print RBTB "#define BAG\r\n";
next;
}
s/TreeSet/TreeBag/g;
print RBTB;
}
close(RBTS) || die "Can't close infile";
close(RBTB) || die "Can't close outfile";
-5
View File
@@ -1,5 +0,0 @@
*.dll
*.mdb
cs-parser.cs
semantic.cache
y.output
-8
View File
@@ -1,8 +0,0 @@
using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyVersion("1.1.2")]
[assembly: AssemblyTitle ("Mono C# Compiler")]
[assembly: AssemblyDescription ("Mono C# Compiler with Generics")]
[assembly: AssemblyCopyright ("2001, 2002, 2003 Ximian, Inc.")]
[assembly: AssemblyCompany ("Ximian, Inc.")]
-18576
View File
File diff suppressed because it is too large. Load diff
-406
View File
@@ -1,406 +0,0 @@
//
// CryptoConvert.cs - Crypto Convertion Routines
//
// Author:
// Sebastien Pouliot <[email protected]>
//
// (C) 2003 Motus Technologies Inc. (http://www.motus.com)
// (C) 2004 Novell (http://www.novell.com)
//
using System;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
namespace Mono.Security.Cryptography {
#if INSIDE_CORLIB
internal
#else
public
#endif
sealed class CryptoConvert {
private CryptoConvert ()
{
}
static private int ToInt32LE (byte [] bytes, int offset)
{
return (bytes [offset+3] << 24) | (bytes [offset+2] << 16) | (bytes [offset+1] << 8) | bytes [offset];
}
static private uint ToUInt32LE (byte [] bytes, int offset)
{
return (uint)((bytes [offset+3] << 24) | (bytes [offset+2] << 16) | (bytes [offset+1] << 8) | bytes [offset]);
}
static private byte [] GetBytesLE (int val)
{
return new byte [] {
(byte) (val & 0xff),
(byte) ((val >> 8) & 0xff),
(byte) ((val >> 16) & 0xff),
(byte) ((val >> 24) & 0xff)
};
}
static private byte[] Trim (byte[] array)
{
for (int i=0; i < array.Length; i++) {
if (array [i] != 0x00) {
byte[] result = new byte [array.Length - i];
Buffer.BlockCopy (array, i, result, 0, result.Length);
return result;
}
}
return null;
}
// convert the key from PRIVATEKEYBLOB to RSA
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/security/Security/private_key_blobs.asp
// e.g. SNK files, PVK files
static public RSA FromCapiPrivateKeyBlob (byte[] blob)
{
return FromCapiPrivateKeyBlob (blob, 0);
}
static public RSA FromCapiPrivateKeyBlob (byte[] blob, int offset)
{
if (blob == null)
throw new ArgumentNullException ("blob");
if (offset >= blob.Length)
throw new ArgumentException ("blob is too small.");
try {
if ((blob [offset] != 0x07) || // PRIVATEKEYBLOB (0x07)
(blob [offset+1] != 0x02) || // Version (0x02)
(blob [offset+2] != 0x00) || // Reserved (word)
(blob [offset+3] != 0x00) ||
(ToUInt32LE (blob, offset+8) != 0x32415352)) // DWORD magic = RSA2
throw new CryptographicException ("Invalid blob header");
// ALGID (CALG_RSA_SIGN, CALG_RSA_KEYX, ...)
int algId = ToInt32LE (blob, offset+4);
// DWORD bitlen
int bitLen = ToInt32LE (blob, offset+12);
// DWORD public exponent
RSAParameters rsap = new RSAParameters ();
byte[] exp = new byte [4];
Buffer.BlockCopy (blob, offset+16, exp, 0, 4);
Array.Reverse (exp);
rsap.Exponent = Trim (exp);
int pos = offset+20;
// BYTE modulus[rsapubkey.bitlen/8];
int byteLen = (bitLen >> 3);
rsap.Modulus = new byte [byteLen];
Buffer.BlockCopy (blob, pos, rsap.Modulus, 0, byteLen);
Array.Reverse (rsap.Modulus);
pos += byteLen;
// BYTE prime1[rsapubkey.bitlen/16];
int byteHalfLen = (byteLen >> 1);
rsap.P = new byte [byteHalfLen];
Buffer.BlockCopy (blob, pos, rsap.P, 0, byteHalfLen);
Array.Reverse (rsap.P);
pos += byteHalfLen;
// BYTE prime2[rsapubkey.bitlen/16];
rsap.Q = new byte [byteHalfLen];
Buffer.BlockCopy (blob, pos, rsap.Q, 0, byteHalfLen);
Array.Reverse (rsap.Q);
pos += byteHalfLen;
// BYTE exponent1[rsapubkey.bitlen/16];
rsap.DP = new byte [byteHalfLen];
Buffer.BlockCopy (blob, pos, rsap.DP, 0, byteHalfLen);
Array.Reverse (rsap.DP);
pos += byteHalfLen;
// BYTE exponent2[rsapubkey.bitlen/16];
rsap.DQ = new byte [byteHalfLen];
Buffer.BlockCopy (blob, pos, rsap.DQ, 0, byteHalfLen);
Array.Reverse (rsap.DQ);
pos += byteHalfLen;
// BYTE coefficient[rsapubkey.bitlen/16];
rsap.InverseQ = new byte [byteHalfLen];
Buffer.BlockCopy (blob, pos, rsap.InverseQ, 0, byteHalfLen);
Array.Reverse (rsap.InverseQ);
pos += byteHalfLen;
// ok, this is hackish but CryptoAPI support it so...
// note: only works because CRT is used by default
// http://bugzilla.ximian.com/show_bug.cgi?id=57941
rsap.D = new byte [byteLen]; // must be allocated
if (pos + byteLen + offset <= blob.Length) {
// BYTE privateExponent[rsapubkey.bitlen/8];
Buffer.BlockCopy (blob, pos, rsap.D, 0, byteLen);
Array.Reverse (rsap.D);
}
RSA rsa = (RSA)RSA.Create ();
rsa.ImportParameters (rsap);
return rsa;
}
catch (Exception e) {
throw new CryptographicException ("Invalid blob.", e);
}
}
static public byte[] ToCapiPrivateKeyBlob (RSA rsa)
{
RSAParameters p = rsa.ExportParameters (true);
int keyLength = p.Modulus.Length; // in bytes
byte[] blob = new byte [20 + (keyLength << 2) + (keyLength >> 1)];
blob [0] = 0x07; // Type - PRIVATEKEYBLOB (0x07)
blob [1] = 0x02; // Version - Always CUR_BLOB_VERSION (0x02)
// [2], [3] // RESERVED - Always 0
blob [5] = 0x24; // ALGID - Always 00 24 00 00 (for CALG_RSA_SIGN)
blob [8] = 0x52; // Magic - RSA2 (ASCII in hex)
blob [9] = 0x53;
blob [10] = 0x41;
blob [11] = 0x32;
byte[] bitlen = GetBytesLE (keyLength << 3);
blob [12] = bitlen [0]; // bitlen
blob [13] = bitlen [1];
blob [14] = bitlen [2];
blob [15] = bitlen [3];
// public exponent (DWORD)
int pos = 16;
int n = p.Exponent.Length;
while (n > 0)
blob [pos++] = p.Exponent [--n];
// modulus
pos = 20;
byte[] part = p.Modulus;
int len = part.Length;
Array.Reverse (part, 0, len);
Buffer.BlockCopy (part, 0, blob, pos, len);
pos += len;
// private key
part = p.P;
len = part.Length;
Array.Reverse (part, 0, len);
Buffer.BlockCopy (part, 0, blob, pos, len);
pos += len;
part = p.Q;
len = part.Length;
Array.Reverse (part, 0, len);
Buffer.BlockCopy (part, 0, blob, pos, len);
pos += len;
part = p.DP;
len = part.Length;
Array.Reverse (part, 0, len);
Buffer.BlockCopy (part, 0, blob, pos, len);
pos += len;
part = p.DQ;
len = part.Length;
Array.Reverse (part, 0, len);
Buffer.BlockCopy (part, 0, blob, pos, len);
pos += len;
part = p.InverseQ;
len = part.Length;
Array.Reverse (part, 0, len);
Buffer.BlockCopy (part, 0, blob, pos, len);
pos += len;
part = p.D;
len = part.Length;
Array.Reverse (part, 0, len);
Buffer.BlockCopy (part, 0, blob, pos, len);
return blob;
}
static public RSA FromCapiPublicKeyBlob (byte[] blob)
{
return FromCapiPublicKeyBlob (blob, 0);
}
static public RSA FromCapiPublicKeyBlob (byte[] blob, int offset)
{
if (blob == null)
throw new ArgumentNullException ("blob");
if (offset >= blob.Length)
throw new ArgumentException ("blob is too small.");
try {
if ((blob [offset] != 0x06) || // PUBLICKEYBLOB (0x06)
(blob [offset+1] != 0x02) || // Version (0x02)
(blob [offset+2] != 0x00) || // Reserved (word)
(blob [offset+3] != 0x00) ||
(ToUInt32LE (blob, offset+8) != 0x31415352)) // DWORD magic = RSA1
throw new CryptographicException ("Invalid blob header");
// ALGID (CALG_RSA_SIGN, CALG_RSA_KEYX, ...)
int algId = ToInt32LE (blob, offset+4);
// DWORD bitlen
int bitLen = ToInt32LE (blob, offset+12);
// DWORD public exponent
RSAParameters rsap = new RSAParameters ();
rsap.Exponent = new byte [3];
rsap.Exponent [0] = blob [offset+18];
rsap.Exponent [1] = blob [offset+17];
rsap.Exponent [2] = blob [offset+16];
int pos = offset+20;
// BYTE modulus[rsapubkey.bitlen/8];
int byteLen = (bitLen >> 3);
rsap.Modulus = new byte [byteLen];
Buffer.BlockCopy (blob, pos, rsap.Modulus, 0, byteLen);
Array.Reverse (rsap.Modulus);
RSA rsa = (RSA)RSA.Create ();
rsa.ImportParameters (rsap);
return rsa;
}
catch (Exception e) {
throw new CryptographicException ("Invalid blob.", e);
}
}
static public byte[] ToCapiPublicKeyBlob (RSA rsa)
{
RSAParameters p = rsa.ExportParameters (false);
int keyLength = p.Modulus.Length; // in bytes
byte[] blob = new byte [20 + keyLength];
blob [0] = 0x06; // Type - PUBLICKEYBLOB (0x06)
blob [1] = 0x02; // Version - Always CUR_BLOB_VERSION (0x02)
// [2], [3] // RESERVED - Always 0
blob [5] = 0x24; // ALGID - Always 00 24 00 00 (for CALG_RSA_SIGN)
blob [8] = 0x52; // Magic - RSA1 (ASCII in hex)
blob [9] = 0x53;
blob [10] = 0x41;
blob [11] = 0x31;
byte[] bitlen = GetBytesLE (keyLength << 3);
blob [12] = bitlen [0]; // bitlen
blob [13] = bitlen [1];
blob [14] = bitlen [2];
blob [15] = bitlen [3];
// public exponent (DWORD)
int pos = 16;
int n = p.Exponent.Length;
while (n > 0)
blob [pos++] = p.Exponent [--n];
// modulus
pos = 20;
byte[] part = p.Modulus;
int len = part.Length;
Array.Reverse (part, 0, len);
Buffer.BlockCopy (part, 0, blob, pos, len);
pos += len;
return blob;
}
// PRIVATEKEYBLOB
// PUBLICKEYBLOB
static public RSA FromCapiKeyBlob (byte[] blob)
{
return FromCapiKeyBlob (blob, 0);
}
static public RSA FromCapiKeyBlob (byte[] blob, int offset)
{
if (blob == null)
throw new ArgumentNullException ("blob");
if (offset >= blob.Length)
throw new ArgumentException ("blob is too small.");
switch (blob [offset]) {
case 0x00:
// this could be a public key inside an header
// like "sn -e" would produce
if (blob [offset + 12] == 0x06) {
return FromCapiPublicKeyBlob (blob, offset + 12);
}
break;
case 0x06:
return FromCapiPublicKeyBlob (blob, offset);
case 0x07:
return FromCapiPrivateKeyBlob (blob, offset);
}
throw new CryptographicException ("Unknown blob format.");
}
static public byte[] ToCapiKeyBlob (AsymmetricAlgorithm keypair, bool includePrivateKey)
{
if (keypair == null)
throw new ArgumentNullException ("keypair");
// check between RSA and DSA (and potentially others like DH)
if (keypair is RSA)
return ToCapiKeyBlob ((RSA)keypair, includePrivateKey);
else
return null; // TODO
}
static public byte[] ToCapiKeyBlob (RSA rsa, bool includePrivateKey)
{
if (rsa == null)
throw new ArgumentNullException ("rsa");
RSAParameters p = rsa.ExportParameters (includePrivateKey);
if (includePrivateKey)
return ToCapiPrivateKeyBlob (rsa);
else
return ToCapiPublicKeyBlob (rsa);
}
static public string ToHex (byte[] input)
{
if (input == null)
return null;
StringBuilder sb = new StringBuilder (input.Length * 2);
foreach (byte b in input) {
sb.Append (b.ToString ("X2", CultureInfo.InvariantCulture));
}
return sb.ToString ();
}
static private byte FromHexChar (char c)
{
if ((c >= 'a') && (c <= 'f'))
return (byte) (c - 'a' + 10);
if ((c >= 'A') && (c <= 'F'))
return (byte) (c - 'A' + 10);
if ((c >= '0') && (c <= '9'))
return (byte) (c - '0');
throw new ArgumentException ("invalid hex char");
}
static public byte[] FromHex (string hex)
{
if (hex == null)
return null;
if ((hex.Length & 0x1) == 0x1)
throw new ArgumentException ("Length must be a multiple of 2");
byte[] result = new byte [hex.Length >> 1];
int n = 0;
int i = 0;
while (n < result.Length) {
result [n] = (byte) (FromHexChar (hex [i++]) << 4);
result [n++] += FromHexChar (hex [i++]);
}
return result;
}
}
}
-144
View File
@@ -1,144 +0,0 @@
thisdir := gmcs
SUBDIRS :=
include ../build/rules.make
COMPILER_SOURCES = \
AssemblyInfo.cs \
anonymous.cs \
assign.cs \
attribute.cs \
driver.cs \
cs-tokenizer.cs \
cfold.cs \
class.cs \
codegen.cs \
const.cs \
constant.cs \
convert.cs \
decl.cs \
delegate.cs \
enum.cs \
ecore.cs \
expression.cs \
flowanalysis.cs \
generic.cs \
iterators.cs \
literal.cs \
location.cs \
modifiers.cs \
namespace.cs \
parameter.cs \
pending.cs \
report.cs \
rootcontext.cs \
statement.cs \
support.cs \
typemanager.cs \
symbolwriter.cs \
tree.cs \
CryptoConvert.cs \
$(topdir)/class/Mono.CSharp.Debugger/MonoSymbolFile.cs \
$(topdir)/class/Mono.CSharp.Debugger/MonoSymbolTable.cs \
$(topdir)/class/Mono.CSharp.Debugger/MonoSymbolWriter.cs
all_sources = $(COMPILER_SOURCES) cs-parser.cs
DISTFILES = \
$(COMPILER_SOURCES) \
cs-parser.jay \
gmcs.exe.config
# compiler.csproj \
# compiler.doc \
# compiler.sln \
# NOTES \
# TODO
#uncomment to enable some debug stuff
#DEBUG_FLAGS=/define:MCS_DEBUG
all-local: gmcs.exe
PROGRAM_INSTALL_DIR = $(prefix)/lib/mono/2.0
install-local: gmcs.exe
$(MKINSTALLDIRS) $(DESTDIR)$(PROGRAM_INSTALL_DIR)
$(INSTALL_BIN) gmcs.exe $(DESTDIR)$(PROGRAM_INSTALL_DIR)
$(INSTALL_DATA) gmcs.exe.config $(DESTDIR)$(PROGRAM_INSTALL_DIR)
$(INSTALL_DATA) gmcs.exe.mdb $(DESTDIR)$(PROGRAM_INSTALL_DIR)
uninstall-local:
-rm -f $(DESTDIR)$(PROGRAM_INSTALL_DIR)/gmcs.exe*
test-local run-test-local:
clean-local:
rm -f *.exe *.pdb cs-parser.cs y.output *.mdb
cd .. && $(MAKE) PROFILE=net_2_0_bootstrap clean
dist-local: dist-default
bootstrap_libs = mscorlib.dll System.dll System.Xml.dll Mono.CompilerServices.SymbolWriter.dll
bootstrap_libfiles = $(bootstrap_libs:%=$(topdir)/class/lib/net_2_0_bootstrap/%)
$(bootstrap_libfiles): bootstrap-libs
@:
.PHONY: bootstrap-libs
bootstrap-libs:
cd .. && $(MAKE) PROFILE=net_2_0_bootstrap all
gmcs.exe: $(all_sources) $(bootstrap_libfiles)
MONO_PATH="../class/lib/net_2_0_bootstrap$(PLATFORM_PATH_SEPARATOR)$$MONO_PATH" mono ../mcs/mcs.exe $(DEBUG_FLAGS) -2 /target:exe /debug /out:$@ $(all_sources)
gmcs2.exe: $(all_sources)
MONO_PATH="../class/lib/net_2_0$(PLATFORM_PATH_SEPARATOR)$$MONO_PATH" time mcs -2 /target:exe /debug /out:$@ $^ $(DEBUG_FLAGS)
gmcs3.exe: $(all_sources)
MONO_PATH="../class/lib/net_2_0$(PLATFORM_PATH_SEPARATOR)$$MONO_PATH" time $(RUNTIME) ./gmcs2.exe $(USE_MCS_FLAGS) $(DEBUG_FLAGS) -2 /target:exe /debug /out:$@ $^
gmcs4.exe: $(all_sources)
MONO_PATH="../class/lib/net_2_0$(PLATFORM_PATH_SEPARATOR)$$MONO_PATH" time $(RUNTIME) ./gmcs3.exe $(USE_MCS_FLAGS) $(DEBUG_FLAGS) -2 /target:exe /debug /out:$@ $^
cs-parser.cs: cs-parser.jay $(topdir)/jay/skeleton.cs
$(topdir)/jay/jay -ctv < $(topdir)/jay/skeleton.cs $< > jay-tmp.out && mv jay-tmp.out $@
# Testing targets
TIME =
# This used to be called test, but that conflicts with the global
# recursive target.
btest: gmcs2.exe gmcs3.exe gmcs4.exe
ls -l gmcs3.exe gmcs4.exe
wc:
wc -l $(all_sources)
ctest:
rm -f gmcs3.exe mcs4.exe
make btest USE_MCS_FLAGS=
# we need this because bash tries to use its own crappy timer
FRIENDLY_TIME = $(shell which time) -f'%U seconds'
do-time : mcs.exe
@ echo -n "Run 1: "
$(FRIENDLY_TIME) $(RUNTIME) ./mcs.exe $(USE_MCS_FLAGS) /target:exe /out:mcs2.exe $(all_sources) > /dev/null || (echo FAILED; exit 1)
@ echo -n "Run 2: "
@ $(FRIENDLY_TIME) $(RUNTIME) ./mcs2.exe $(USE_MCS_FLAGS) /target:exe /out:mcs3.exe $(all_sources) > /dev/null || (echo FAILED; exit 1)
@ echo -n "corlib: "
@ rm -f ../class/lib/mscorlib.dll
@ (cd ../class/corlib ; make BOOTSTRAP_MCS="$(FRIENDLY_TIME) mono ../../mcs/mcs.exe" > /dev/null ) || (echo FAILED; exit 1)
do-corlib:
@ echo -n "corlib: "
@ rm -f ../class/lib/mscorlib.dll
@ (cd ../class/corlib ; make BOOTSTRAP_MCS="$(FRIENDLY_TIME) mono ../../mcs/mcs.exe" > /dev/null ) || (echo FAILED; exit 1)
PROFILER=default
profile : gmcs2.exe
make gmcs3.exe RUNTIME="$(RUNTIME) --profile"
response:
echo $(all_sources) > res
-13
View File
@@ -1,13 +0,0 @@
Notes for Martin:
* We merged manually the patch from Sebastien from, this is the
only patch that is not part of the regular mcs/gmcs merger process.
2004-04-08 Sebastien Pouliot <[email protected]>
* codegen.cs: Fix another case where CS1548 must be reported (when
delay-sign isn't specified and no private is available #56564). Fix
loading the ECMA "key" to delay-sign an assembly. Report a CS1548
error when MCS is used on the MS runtime and we need to delay-sign
(which seems unsupported by AssemblyBuilder - see #56621).
-25
View File
@@ -1,25 +0,0 @@
This document lists some important changes between MCS and GMCS.
* Defining Types
There's a fundamental change in how we're defining types in
TypeContainer.DefineType().
In MCS, we resolve a type's parent type and the interface it
implements before actually creating the TypeBuilder. We can easily
detect "recursive" declarations (CS0146) if DefineType() is called
recursively.
This has changed in GMCS since the following type of a recursive
declaration is allowed:
class Foo<T> { }
class Bar<T> : Foo<Bar<T>> { }
To allow this, we must define Bar's TypeBuilder before resolving its
parent classes and call TypeBuilder.SetParent() later.
Last updated September 9th, 2004
Martin Baulig <[email protected]>
File diff suppressed because it is too large. Load diff
-616
View File
@@ -1,616 +0,0 @@
//
// assign.cs: Assignments.
//
// Author:
// Miguel de Icaza ([email protected])
// Martin Baulig ([email protected])
//
// (C) 2001, 2002, 2003 Ximian, Inc.
//
using System;
using System.Reflection;
using System.Reflection.Emit;
namespace Mono.CSharp {
/// <summary>
/// This interface is implemented by expressions that can be assigned to.
/// </summary>
/// <remarks>
/// This interface is implemented by Expressions whose values can not
/// store the result on the top of the stack.
///
/// Expressions implementing this (Properties, Indexers and Arrays) would
/// perform an assignment of the Expression "source" into its final
/// location.
///
/// No values on the top of the stack are expected to be left by
/// invoking this method.
/// </remarks>
public interface IAssignMethod {
//
// This is an extra version of Emit. If leave_copy is `true'
// A copy of the expression will be left on the stack at the
// end of the code generated for EmitAssign
//
void Emit (EmitContext ec, bool leave_copy);
//
// This method does the assignment
// `source' will be stored into the location specified by `this'
// if `leave_copy' is true, a copy of `source' will be left on the stack
// if `prepare_for_load' is true, when `source' is emitted, there will
// be data on the stack that it can use to compuatate its value. This is
// for expressions like a [f ()] ++, where you can't call `f ()' twice.
//
void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load);
/*
For simple assignments, this interface is very simple, EmitAssign is called with source
as the source expression and leave_copy and prepare_for_load false.
For compound assignments it gets complicated.
EmitAssign will be called as before, however, prepare_for_load will be
true. The @source expression will contain an expression
which calls Emit. So, the calls look like:
this.EmitAssign (ec, source, false, true) ->
source.Emit (ec); ->
[...] ->
this.Emit (ec, false); ->
end this.Emit (ec, false); ->
end [...]
end source.Emit (ec);
end this.EmitAssign (ec, source, false, true)
When prepare_for_load is true, EmitAssign emits a `token' on the stack that
Emit will use for its state.
Let's take FieldExpr as an example. assume we are emitting f ().y += 1;
Here is the call tree again. This time, each call is annotated with the IL
it produces:
this.EmitAssign (ec, source, false, true)
call f
dup
Binary.Emit ()
this.Emit (ec, false);
ldfld y
end this.Emit (ec, false);
IntConstant.Emit ()
ldc.i4.1
end IntConstant.Emit
add
end Binary.Emit ()
stfld
end this.EmitAssign (ec, source, false, true)
Observe two things:
1) EmitAssign left a token on the stack. It was the result of f ().
2) This token was used by Emit
leave_copy (in both EmitAssign and Emit) tells the compiler to leave a copy
of the expression at that point in evaluation. This is used for pre/post inc/dec
and for a = x += y. Let's do the above example with leave_copy true in EmitAssign
this.EmitAssign (ec, source, true, true)
call f
dup
Binary.Emit ()
this.Emit (ec, false);
ldfld y
end this.Emit (ec, false);
IntConstant.Emit ()
ldc.i4.1
end IntConstant.Emit
add
end Binary.Emit ()
dup
stloc temp
stfld
ldloc temp
end this.EmitAssign (ec, source, true, true)
And with it true in Emit
this.EmitAssign (ec, source, false, true)
call f
dup
Binary.Emit ()
this.Emit (ec, true);
ldfld y
dup
stloc temp
end this.Emit (ec, true);
IntConstant.Emit ()
ldc.i4.1
end IntConstant.Emit
add
end Binary.Emit ()
stfld
ldloc temp
end this.EmitAssign (ec, source, false, true)
Note that these two examples are what happens for ++x and x++, respectively.
*/
}
/// <summary>
/// An Expression to hold a temporary value.
/// </summary>
/// <remarks>
/// The LocalTemporary class is used to hold temporary values of a given
/// type to "simulate" the expression semantics on property and indexer
/// access whose return values are void.
///
/// The local temporary is used to alter the normal flow of code generation
/// basically it creates a local variable, and its emit instruction generates
/// code to access this value, return its address or save its value.
///
/// If `is_address' is true, then the value that we store is the address to the
/// real value, and not the value itself.
///
/// This is needed for a value type, because otherwise you just end up making a
/// copy of the value on the stack and modifying it. You really need a pointer
/// to the origional value so that you can modify it in that location. This
/// Does not happen with a class because a class is a pointer -- so you always
/// get the indirection.
///
/// The `is_address' stuff is really just a hack. We need to come up with a better
/// way to handle it.
/// </remarks>
public class LocalTemporary : Expression, IMemoryLocation {
LocalBuilder builder;
bool is_address;
public LocalTemporary (EmitContext ec, Type t) : this (ec, t, false) {}
public LocalTemporary (EmitContext ec, Type t, bool is_address)
{
type = t;
eclass = ExprClass.Value;
loc = Location.Null;
builder = ec.GetTemporaryLocal (is_address ? TypeManager.GetReferenceType (t): t);
this.is_address = is_address;
}
public LocalTemporary (LocalBuilder b, Type t)
{
type = t;
eclass = ExprClass.Value;
loc = Location.Null;
builder = b;
}
public void Release (EmitContext ec)
{
ec.FreeTemporaryLocal (builder, type);
builder = null;
}
public override Expression DoResolve (EmitContext ec)
{
return this;
}
public override void Emit (EmitContext ec)
{
ILGenerator ig = ec.ig;
ig.Emit (OpCodes.Ldloc, builder);
// we need to copy from the pointer
if (is_address)
LoadFromPtr (ig, type);
}
// NB: if you have `is_address' on the stack there must
// be a managed pointer. Otherwise, it is the type from
// the ctor.
public void Store (EmitContext ec)
{
ILGenerator ig = ec.ig;
ig.Emit (OpCodes.Stloc, builder);
}
public void AddressOf (EmitContext ec, AddressOp mode)
{
// if is_address, than this is just the address anyways,
// so we just return this.
ILGenerator ig = ec.ig;
if (is_address)
ig.Emit (OpCodes.Ldloc, builder);
else
ig.Emit (OpCodes.Ldloca, builder);
}
public bool PointsToAddress {
get {
return is_address;
}
}
}
/// <summary>
/// The Assign node takes care of assigning the value of source into
/// the expression represented by target.
/// </summary>
public class Assign : ExpressionStatement {
protected Expression target, source, real_source;
protected LocalTemporary temp = null, real_temp = null;
protected Assign embedded = null;
protected bool is_embedded = false;
protected bool must_free_temp = false;
public Assign (Expression target, Expression source, Location l)
{
this.target = target;
this.source = this.real_source = source;
this.loc = l;
}
protected Assign (Assign embedded, Location l)
: this (embedded.target, embedded.source, l)
{
this.is_embedded = true;
}
protected virtual Assign GetEmbeddedAssign (Location loc)
{
return new Assign (this, loc);
}
public Expression Target {
get {
return target;
}
set {
target = value;
}
}
public Expression Source {
get {
return source;
}
set {
source = value;
}
}
public static void error70 (EventInfo ei, Location l)
{
Report.Error (70, l, "The event '" + ei.Name +
"' can only appear on the left-side of a += or -= (except when" +
" used from within the type '" + ei.DeclaringType + "')");
}
//
// Will return either `this' or an instance of `New'.
//
public override Expression DoResolve (EmitContext ec)
{
// Create an embedded assignment if our source is an assignment.
if (source is Assign)
source = embedded = ((Assign) source).GetEmbeddedAssign (loc);
real_source = source = source.Resolve (ec);
if (source == null)
return null;
//
// This is used in an embedded assignment.
// As an example, consider the statement "A = X = Y = Z".
//
if (is_embedded && !(source is Constant)) {
// If this is the innermost assignment (the "Y = Z" in our example),
// create a new temporary local, otherwise inherit that variable
// from our child (the "X = (Y = Z)" inherits the local from the
// "Y = Z" assignment).
if (embedded == null) {
if (this is CompoundAssign)
real_temp = temp = new LocalTemporary (ec, target.Type);
else
real_temp = temp = new LocalTemporary (ec, source.Type);
} else
temp = embedded.temp;
// Set the source to the new temporary variable.
// This means that the following target.ResolveLValue () will tell
// the target to read it's source value from that variable.
source = temp;
}
// If we have an embedded assignment, use the embedded assignment's temporary
// local variable as source.
if (embedded != null)
source = (embedded.temp != null) ? embedded.temp : embedded.source;
target = target.ResolveLValue (ec, source);
if (target == null)
return null;
Type target_type = target.Type;
Type source_type = real_source.Type;
// If we're an embedded assignment, our parent will reuse our source as its
// source, it won't read from our target.
if (is_embedded)
type = source_type;
else
type = target_type;
eclass = ExprClass.Value;
if (target is EventExpr) {
EventInfo ei = ((EventExpr) target).EventInfo;
Expression ml = MemberLookup (
ec, ec.ContainerType, ei.Name,
MemberTypes.Event, AllBindingFlags | BindingFlags.DeclaredOnly, loc);
if (ml == null) {
//
// If this is the case, then the Event does not belong
// to this Type and so, according to the spec
// is allowed to only appear on the left hand of
// the += and -= operators
//
// Note that target will not appear as an EventExpr
// in the case it is being referenced within the same type container;
// it will appear as a FieldExpr in that case.
//
if (!(source is BinaryDelegate)) {
error70 (ei, loc);
return null;
}
}
}
if (!(target is IAssignMethod) && (target.eclass != ExprClass.EventAccess)) {
Report.Error (131, loc,
"Left hand of an assignment must be a variable, " +
"a property or an indexer");
return null;
}
if ((source.eclass == ExprClass.Type) && (source is TypeExpr)) {
source.Error_UnexpectedKind ("variable or value", loc);
return null;
} else if ((RootContext.Version == LanguageVersion.ISO_1) &&
(source is MethodGroupExpr)){
((MethodGroupExpr) source).ReportUsageError ();
return null;
}
if (target_type == source_type){
if (source is New && target_type.IsValueType &&
(target.eclass != ExprClass.IndexerAccess) && (target.eclass != ExprClass.PropertyAccess)){
New n = (New) source;
if (n.SetValueTypeVariable (target))
return n;
else
return null;
}
return this;
}
//
// If this assignemnt/operator was part of a compound binary
// operator, then we allow an explicit conversion, as detailed
// in the spec.
//
if (this is CompoundAssign){
CompoundAssign a = (CompoundAssign) this;
Binary b = source as Binary;
if (b != null){
//
// 1. if the source is explicitly convertible to the
// target_type
//
source = Convert.ExplicitConversion (ec, source, target_type, loc);
if (source == null){
Convert.Error_CannotImplicitConversion (loc, source_type, target_type);
return null;
}
//
// 2. and the original right side is implicitly convertible to
// the type of target
//
if (Convert.ImplicitStandardConversionExists (ec, a.original_source, target_type))
return this;
//
// In the spec 2.4 they added: or if type of the target is int
// and the operator is a shift operator...
//
if (source_type == TypeManager.int32_type &&
(b.Oper == Binary.Operator.LeftShift || b.Oper == Binary.Operator.RightShift))
return this;
Convert.Error_CannotImplicitConversion (loc, a.original_source.Type, target_type);
return null;
}
}
source = Convert.ImplicitConversionRequired (ec, source, target_type, loc);
if (source == null)
return null;
// If we're an embedded assignment, we need to create a new temporary variable
// for the converted value. Our parent will use this new variable as its source.
// The same applies when we have an embedded assignment - in this case, we need
// to convert our embedded assignment's temporary local variable to the correct
// type and store it in a new temporary local.
if (is_embedded || embedded != null) {
type = target_type;
temp = new LocalTemporary (ec, type);
must_free_temp = true;
}
return this;
}
Expression EmitEmbedded (EmitContext ec)
{
// Emit an embedded assignment.
if (real_temp != null) {
// If we're the innermost assignment, `real_source' is the right-hand
// expression which gets assigned to all the variables left of it.
// Emit this expression and store its result in real_temp.
real_source.Emit (ec);
real_temp.Store (ec);
}
if (embedded != null)
embedded.EmitEmbedded (ec);
// This happens when we've done a type conversion, in this case source will be
// the expression which does the type conversion from real_temp.
// So emit it and store the result in temp; this is the var which will be read
// by our parent.
if (temp != real_temp) {
source.Emit (ec);
temp.Store (ec);
}
Expression temp_source = (temp != null) ? temp : source;
((IAssignMethod) target).EmitAssign (ec, temp_source, false, false);
return temp_source;
}
void ReleaseEmbedded (EmitContext ec)
{
if (embedded != null)
embedded.ReleaseEmbedded (ec);
if (real_temp != null)
real_temp.Release (ec);
if (must_free_temp)
temp.Release (ec);
}
void Emit (EmitContext ec, bool is_statement)
{
if (target is EventExpr) {
((EventExpr) target).EmitAddOrRemove (ec, source);
return;
}
IAssignMethod am = (IAssignMethod) target;
Expression temp_source;
if (embedded != null) {
temp_source = embedded.EmitEmbedded (ec);
if (temp != null) {
source.Emit (ec);
temp.Store (ec);
temp_source = temp;
}
} else
temp_source = source;
am.EmitAssign (ec, temp_source, !is_statement, this is CompoundAssign);
if (embedded != null) {
if (temp != null)
temp.Release (ec);
embedded.ReleaseEmbedded (ec);
}
}
public override void Emit (EmitContext ec)
{
Emit (ec, false);
}
public override void EmitStatement (EmitContext ec)
{
Emit (ec, true);
}
}
//
// This class is used for compound assignments.
//
class CompoundAssign : Assign {
Binary.Operator op;
public Expression original_source;
public CompoundAssign (Binary.Operator op, Expression target, Expression source, Location l)
: base (target, source, l)
{
original_source = source;
this.op = op;
}
protected CompoundAssign (CompoundAssign embedded, Location l)
: this (embedded.op, embedded.target, embedded.source, l)
{
this.is_embedded = true;
}
protected override Assign GetEmbeddedAssign (Location loc)
{
return new CompoundAssign (this, loc);
}
public Expression ResolveSource (EmitContext ec)
{
return original_source.Resolve (ec);
}
public override Expression DoResolve (EmitContext ec)
{
original_source = original_source.Resolve (ec);
if (original_source == null)
return null;
target = target.Resolve (ec);
if (target == null)
return null;
//
// Only now we can decouple the original source/target
// into a tree, to guarantee that we do not have side
// effects.
//
source = new Binary (op, target, original_source, loc);
return base.DoResolve (ec);
}
}
}
File diff suppressed because it is too large. Load diff
-1194
View File
File diff suppressed because it is too large. Load diff
-7747
View File
File diff suppressed because it is too large. Load diff
-1341
View File
File diff suppressed because it is too large. Load diff
-284
View File
@@ -1,284 +0,0 @@
//
// const.cs: Constant declarations.
//
// Author:
// Miguel de Icaza ([email protected])
//
// (C) 2001 Ximian, Inc.
//
//
//
// This is needed because the following situation arises:
//
// The FieldBuilder is declared with the real type for an enumeration
//
// When we attempt to set the value for the constant, the FieldBuilder.SetConstant
// function aborts because it requires its argument to be of the same type
//
namespace Mono.CSharp {
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Collections;
public class Const : FieldMember {
public Expression Expr;
EmitContext const_ec;
bool resolved = false;
object ConstantValue = null;
bool in_transit = false;
public const int AllowedModifiers =
Modifiers.NEW |
Modifiers.PUBLIC |
Modifiers.PROTECTED |
Modifiers.INTERNAL |
Modifiers.PRIVATE;
public Const (TypeContainer parent, Expression constant_type, string name,
Expression expr, int mod_flags, Attributes attrs, Location loc)
: base (parent, constant_type, mod_flags, AllowedModifiers,
new MemberName (name), null, attrs, loc)
{
Expr = expr;
ModFlags |= Modifiers.STATIC;
}
public FieldAttributes FieldAttr {
get {
return FieldAttributes.Literal | FieldAttributes.Static |
Modifiers.FieldAttr (ModFlags) ;
}
}
#if DEBUG
void dump_tree (Type t)
{
Console.WriteLine ("Dumping hierarchy");
while (t != null){
Console.WriteLine (" " + t.FullName + " " +
(t.GetType ().IsEnum ? "yes" : "no"));
t = t.BaseType;
}
}
#endif
/// <summary>
/// Defines the constant in the @parent
/// </summary>
public override bool Define ()
{
if (!base.Define ())
return false;
const_ec = new EmitContext (Parent, Location, null, MemberType, ModFlags);
Type ttype = MemberType;
while (ttype.IsArray)
ttype = TypeManager.GetElementType (ttype);
if (!TypeManager.IsBuiltinType (ttype) && (!ttype.IsSubclassOf (TypeManager.enum_type)) && !(Expr is NullLiteral)) {
Report.Error (
-3, Location,
"Constant type is not valid (only system types are allowed)");
return false;
}
FieldBuilder = Parent.TypeBuilder.DefineField (Name, MemberType, FieldAttr);
TypeManager.RegisterConstant (FieldBuilder, this);
return true;
}
//
// Changes the type of the constant expression `expr' to the Type `type'
// Returns null on failure.
//
public static Constant ChangeType (Location loc, Constant expr, Type type)
{
if (type == TypeManager.object_type)
return expr;
bool fail;
// from the null type to any reference-type.
if (expr is NullLiteral && !type.IsValueType && !TypeManager.IsEnumType (type))
return NullLiteral.Null;
if (!Convert.ImplicitStandardConversionExists (Convert.ConstantEC, expr, type)){
Convert.Error_CannotImplicitConversion (loc, expr.Type, type);
return null;
}
object constant_value = TypeManager.ChangeType (expr.GetValue (), type, out fail);
if (fail){
Convert.Error_CannotImplicitConversion (loc, expr.Type, type);
//
// We should always catch the error before this is ever
// reached, by calling Convert.ImplicitStandardConversionExists
//
throw new Exception (
String.Format ("LookupConstantValue: This should never be reached {0} {1}", expr.Type, type));
}
Constant retval;
if (type == TypeManager.int32_type)
retval = new IntConstant ((int) constant_value);
else if (type == TypeManager.uint32_type)
retval = new UIntConstant ((uint) constant_value);
else if (type == TypeManager.int64_type)
retval = new LongConstant ((long) constant_value);
else if (type == TypeManager.uint64_type)
retval = new ULongConstant ((ulong) constant_value);
else if (type == TypeManager.float_type)
retval = new FloatConstant ((float) constant_value);
else if (type == TypeManager.double_type)
retval = new DoubleConstant ((double) constant_value);
else if (type == TypeManager.string_type)
retval = new StringConstant ((string) constant_value);
else if (type == TypeManager.short_type)
retval = new ShortConstant ((short) constant_value);
else if (type == TypeManager.ushort_type)
retval = new UShortConstant ((ushort) constant_value);
else if (type == TypeManager.sbyte_type)
retval = new SByteConstant ((sbyte) constant_value);
else if (type == TypeManager.byte_type)
retval = new ByteConstant ((byte) constant_value);
else if (type == TypeManager.char_type)
retval = new CharConstant ((char) constant_value);
else if (type == TypeManager.bool_type)
retval = new BoolConstant ((bool) constant_value);
else
throw new Exception ("LookupConstantValue: Unhandled constant type: " + type);
return retval;
}
/// <summary>
/// Looks up the value of a constant field. Defines it if it hasn't
/// already been. Similar to LookupEnumValue in spirit.
/// </summary>
public bool LookupConstantValue (out object value)
{
if (resolved) {
value = ConstantValue;
return true;
}
if (in_transit) {
Report.Error (110, Location,
"The evaluation of the constant value for `" +
Name + "' involves a circular definition.");
value = null;
return false;
}
in_transit = true;
int errors = Report.Errors;
//
// We might have cleared Expr ourselves in a recursive definition
//
if (Expr == null){
value = null;
return false;
}
Expr = Expr.Resolve (const_ec);
in_transit = false;
if (Expr == null) {
if (errors == Report.Errors)
Report.Error (150, Location, "A constant value is expected");
value = null;
return false;
}
Expression real_expr = Expr;
Constant ce = Expr as Constant;
if (ce == null){
UnCheckedExpr un_expr = Expr as UnCheckedExpr;
CheckedExpr ch_expr = Expr as CheckedExpr;
EmptyCast ec_expr = Expr as EmptyCast;
if ((un_expr != null) && (un_expr.Expr is Constant))
Expr = un_expr.Expr;
else if ((ch_expr != null) && (ch_expr.Expr is Constant))
Expr = ch_expr.Expr;
else if ((ec_expr != null) && (ec_expr.Child is Constant))
Expr = ec_expr.Child;
else if (Expr is ArrayCreation){
Report.Error (133, Location, "Arrays can not be constant");
} else {
if (errors == Report.Errors)
Report.Error (150, Location, "A constant value is expected");
value = null;
return false;
}
ce = Expr as Constant;
}
if (MemberType != real_expr.Type) {
ce = ChangeType (Location, ce, MemberType);
if (ce == null){
value = null;
return false;
}
Expr = ce;
}
ConstantValue = ce.GetValue ();
if (MemberType.IsEnum){
//
// This sadly does not work for our user-defined enumerations types ;-(
//
try {
ConstantValue = System.Enum.ToObject (
MemberType, ConstantValue);
} catch (ArgumentException){
Report.Error (
-16, Location,
".NET SDK 1.0 does not permit to create the constant "+
" field from a user-defined enumeration");
}
}
FieldBuilder.SetConstant (ConstantValue);
if (!TypeManager.RegisterFieldValue (FieldBuilder, ConstantValue))
throw new Exception ("Cannot register const value");
value = ConstantValue;
resolved = true;
return true;
}
/// <summary>
/// Emits the field value by evaluating the expression
/// </summary>
public override void Emit ()
{
object value;
LookupConstantValue (out value);
if (OptAttributes != null) {
OptAttributes.Emit (const_ec, this);
}
base.Emit ();
}
}
}
-1113
View File
File diff suppressed because it is too large. Load diff
-1964
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
-2360
View File
File diff suppressed because it is too large. Load diff
-1013
View File
File diff suppressed because it is too large. Load diff
-1768
View File
File diff suppressed because it is too large. Load diff
-3712
View File
File diff suppressed because it is too large. Load diff
-783
View File
@@ -1,783 +0,0 @@
//
// enum.cs: Enum handling.
//
// Author: Miguel de Icaza ([email protected])
// Ravi Pratap ([email protected])
//
// Licensed under the terms of the GNU GPL
//
// (C) 2001 Ximian, Inc (http://www.ximian.com)
//
using System;
using System.Collections;
using System.Reflection;
using System.Reflection.Emit;
using System.Globalization;
namespace Mono.CSharp {
class EnumMember: MemberCore {
static string[] attribute_targets = new string [] { "field" };
Enum parent_enum;
public FieldBuilder builder;
internal readonly Expression Type;
public EnumMember (Enum parent_enum, Expression expr, string name,
Location loc, Attributes attrs):
base (null, new MemberName (name), attrs, loc)
{
this.parent_enum = parent_enum;
this.ModFlags = parent_enum.ModFlags;
this.Type = expr;
}
public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
{
if (a.Type == TypeManager.marshal_as_attr_type) {
UnmanagedMarshal marshal = a.GetMarshal (this);
if (marshal != null) {
builder.SetMarshal (marshal);
}
return;
}
if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
a.Error_InvalidSecurityParent ();
return;
}
builder.SetCustomAttribute (cb);
}
public override AttributeTargets AttributeTargets {
get {
return AttributeTargets.Field;
}
}
public void DefineMember (TypeBuilder tb)
{
FieldAttributes attr = FieldAttributes.Public | FieldAttributes.Static
| FieldAttributes.Literal;
builder = tb.DefineField (Name, tb, attr);
}
public override bool Define ()
{
throw new NotImplementedException ();
}
public void Emit (EmitContext ec)
{
if (OptAttributes != null)
OptAttributes.Emit (ec, this);
Emit ();
}
public override string GetSignatureForError()
{
return String.Concat (parent_enum.GetSignatureForError (), '.', base.GetSignatureForError ());
}
public override string[] ValidAttributeTargets {
get {
return attribute_targets;
}
}
protected override bool VerifyClsCompliance(DeclSpace ds)
{
// Because parent is TypeContainer and we have only DeclSpace parent.
// Parameter replacing is required
return base.VerifyClsCompliance (parent_enum);
}
// There is no base type
protected override void VerifyObsoleteAttribute()
{
}
}
/// <summary>
/// Enumeration container
/// </summary>
public class Enum : DeclSpace {
ArrayList ordered_enums;
public Expression BaseType;
public Type UnderlyingType;
Hashtable member_to_location;
//
// This is for members that have been defined
//
Hashtable member_to_value;
//
// This is used to mark members we're currently defining
//
Hashtable in_transit;
ArrayList field_builders;
public const int AllowedModifiers =
Modifiers.NEW |
Modifiers.PUBLIC |
Modifiers.PROTECTED |
Modifiers.INTERNAL |
Modifiers.PRIVATE;
public Enum (NamespaceEntry ns, TypeContainer parent, Expression type,
int mod_flags, MemberName name, Attributes attrs, Location l)
: base (ns, parent, name, attrs, l)
{
this.BaseType = type;
ModFlags = Modifiers.Check (AllowedModifiers, mod_flags,
IsTopLevel ? Modifiers.INTERNAL : Modifiers.PRIVATE, l);
ordered_enums = new ArrayList ();
member_to_location = new Hashtable ();
member_to_value = new Hashtable ();
in_transit = new Hashtable ();
field_builders = new ArrayList ();
}
/// <summary>
/// Adds @name to the enumeration space, with @expr
/// being its definition.
/// </summary>
public void AddEnumMember (string name, Expression expr, Location loc, Attributes opt_attrs)
{
if (name == "value__") {
Report.Error (76, loc, "An item in an enumeration can't have an identifier `value__'");
return;
}
EnumMember em = new EnumMember (this, expr, name, loc, opt_attrs);
if (!AddToContainer (em, false, name, ""))
return;
// TODO: can be almost deleted
ordered_enums.Add (name);
member_to_location.Add (name, loc);
}
//
// This is used by corlib compilation: we map from our
// type to a type that is consumable by the DefineField
//
Type MapToInternalType (Type t)
{
if (t == TypeManager.int32_type)
return typeof (int);
if (t == TypeManager.int64_type)
return typeof (long);
if (t == TypeManager.uint32_type)
return typeof (uint);
if (t == TypeManager.uint64_type)
return typeof (ulong);
if (t == TypeManager.float_type)
return typeof (float);
if (t == TypeManager.double_type)
return typeof (double);
if (t == TypeManager.byte_type)
return typeof (byte);
if (t == TypeManager.sbyte_type)
return typeof (sbyte);
if (t == TypeManager.char_type)
return typeof (char);
if (t == TypeManager.short_type)
return typeof (short);
if (t == TypeManager.ushort_type)
return typeof (ushort);
throw new Exception ();
}
public override TypeBuilder DefineType ()
{
if (TypeBuilder != null)
return TypeBuilder;
TypeAttributes attr = Modifiers.TypeAttr (ModFlags, IsTopLevel);
attr |= TypeAttributes.Class | TypeAttributes.Sealed;
if (!(BaseType is TypeLookupExpression)) {
Report.Error (1008, Location,
"Type byte, sbyte, short, ushort, int, uint, " +
"long, or ulong expected (got: `{0}')", BaseType);
return null;
}
UnderlyingType = ResolveType (BaseType, false, Location);
if (UnderlyingType != TypeManager.int32_type &&
UnderlyingType != TypeManager.uint32_type &&
UnderlyingType != TypeManager.int64_type &&
UnderlyingType != TypeManager.uint64_type &&
UnderlyingType != TypeManager.short_type &&
UnderlyingType != TypeManager.ushort_type &&
UnderlyingType != TypeManager.byte_type &&
UnderlyingType != TypeManager.sbyte_type) {
Report.Error (1008, Location,
"Type byte, sbyte, short, ushort, int, uint, " +
"long, or ulong expected (got: " +
TypeManager.CSharpName (UnderlyingType) + ")");
return null;
}
if (IsTopLevel) {
if (TypeManager.NamespaceClash (Name, Location))
return null;
ModuleBuilder builder = CodeGen.Module.Builder;
TypeBuilder = builder.DefineType (Name, attr, TypeManager.enum_type);
} else {
TypeBuilder builder = Parent.TypeBuilder;
TypeBuilder = builder.DefineNestedType (
Basename, attr, TypeManager.enum_type);
}
//
// Call MapToInternalType for corlib
//
TypeBuilder.DefineField ("value__", UnderlyingType,
FieldAttributes.Public | FieldAttributes.SpecialName
| FieldAttributes.RTSpecialName);
TypeManager.AddEnumType (Name, TypeBuilder, this);
return TypeBuilder;
}
bool IsValidEnumConstant (Expression e)
{
if (!(e is Constant))
return false;
if (e is IntConstant || e is UIntConstant || e is LongConstant ||
e is ByteConstant || e is SByteConstant || e is ShortConstant ||
e is UShortConstant || e is ULongConstant || e is EnumConstant ||
e is CharConstant)
return true;
else
return false;
}
object GetNextDefaultValue (object default_value)
{
if (UnderlyingType == TypeManager.int32_type) {
int i = (int) default_value;
if (i < System.Int32.MaxValue)
return ++i;
else
return null;
} else if (UnderlyingType == TypeManager.uint32_type) {
uint i = (uint) default_value;
if (i < System.UInt32.MaxValue)
return ++i;
else
return null;
} else if (UnderlyingType == TypeManager.int64_type) {
long i = (long) default_value;
if (i < System.Int64.MaxValue)
return ++i;
else
return null;
} else if (UnderlyingType == TypeManager.uint64_type) {
ulong i = (ulong) default_value;
if (i < System.UInt64.MaxValue)
return ++i;
else
return null;
} else if (UnderlyingType == TypeManager.short_type) {
short i = (short) default_value;
if (i < System.Int16.MaxValue)
return ++i;
else
return null;
} else if (UnderlyingType == TypeManager.ushort_type) {
ushort i = (ushort) default_value;
if (i < System.UInt16.MaxValue)
return ++i;
else
return null;
} else if (UnderlyingType == TypeManager.byte_type) {
byte i = (byte) default_value;
if (i < System.Byte.MaxValue)
return ++i;
else
return null;
} else if (UnderlyingType == TypeManager.sbyte_type) {
sbyte i = (sbyte) default_value;
if (i < System.SByte.MaxValue)
return ++i;
else
return null;
}
return null;
}
void Error_ConstantValueCannotBeConverted (object val, Location loc)
{
if (val is Constant)
Report.Error (31, loc, "Constant value '" + ((Constant) val).AsString () +
"' cannot be converted" +
" to a " + TypeManager.CSharpName (UnderlyingType));
else
Report.Error (31, loc, "Constant value '" + val +
"' cannot be converted" +
" to a " + TypeManager.CSharpName (UnderlyingType));
return;
}
/// <summary>
/// Determines if a standard implicit conversion exists from
/// expr_type to target_type
/// </summary>
public static bool ImplicitConversionExists (Type expr_type, Type target_type)
{
expr_type = TypeManager.TypeToCoreType (expr_type);
if (expr_type == TypeManager.void_type)
return false;
if (expr_type == target_type)
return true;
// First numeric conversions
if (expr_type == TypeManager.sbyte_type){
//
// From sbyte to short, int, long, float, double.
//
if ((target_type == TypeManager.int32_type) ||
(target_type == TypeManager.int64_type) ||
(target_type == TypeManager.double_type) ||
(target_type == TypeManager.float_type) ||
(target_type == TypeManager.short_type) ||
(target_type == TypeManager.decimal_type))
return true;
} else if (expr_type == TypeManager.byte_type){
//
// From byte to short, ushort, int, uint, long, ulong, float, double
//
if ((target_type == TypeManager.short_type) ||
(target_type == TypeManager.ushort_type) ||
(target_type == TypeManager.int32_type) ||
(target_type == TypeManager.uint32_type) ||
(target_type == TypeManager.uint64_type) ||
(target_type == TypeManager.int64_type) ||
(target_type == TypeManager.float_type) ||
(target_type == TypeManager.double_type) ||
(target_type == TypeManager.decimal_type))
return true;
} else if (expr_type == TypeManager.short_type){
//
// From short to int, long, float, double
//
if ((target_type == TypeManager.int32_type) ||
(target_type == TypeManager.int64_type) ||
(target_type == TypeManager.double_type) ||
(target_type == TypeManager.float_type) ||
(target_type == TypeManager.decimal_type))
return true;
} else if (expr_type == TypeManager.ushort_type){
//
// From ushort to int, uint, long, ulong, float, double
//
if ((target_type == TypeManager.uint32_type) ||
(target_type == TypeManager.uint64_type) ||
(target_type == TypeManager.int32_type) ||
(target_type == TypeManager.int64_type) ||
(target_type == TypeManager.double_type) ||
(target_type == TypeManager.float_type) ||
(target_type == TypeManager.decimal_type))
return true;
} else if (expr_type == TypeManager.int32_type){
//
// From int to long, float, double
//
if ((target_type == TypeManager.int64_type) ||
(target_type == TypeManager.double_type) ||
(target_type == TypeManager.float_type) ||
(target_type == TypeManager.decimal_type))
return true;
} else if (expr_type == TypeManager.uint32_type){
//
// From uint to long, ulong, float, double
//
if ((target_type == TypeManager.int64_type) ||
(target_type == TypeManager.uint64_type) ||
(target_type == TypeManager.double_type) ||
(target_type == TypeManager.float_type) ||
(target_type == TypeManager.decimal_type))
return true;
} else if ((expr_type == TypeManager.uint64_type) ||
(expr_type == TypeManager.int64_type)) {
//
// From long/ulong to float, double
//
if ((target_type == TypeManager.double_type) ||
(target_type == TypeManager.float_type) ||
(target_type == TypeManager.decimal_type))
return true;
} else if (expr_type == TypeManager.char_type){
//
// From char to ushort, int, uint, long, ulong, float, double
//
if ((target_type == TypeManager.ushort_type) ||
(target_type == TypeManager.int32_type) ||
(target_type == TypeManager.uint32_type) ||
(target_type == TypeManager.uint64_type) ||
(target_type == TypeManager.int64_type) ||
(target_type == TypeManager.float_type) ||
(target_type == TypeManager.double_type) ||
(target_type == TypeManager.decimal_type))
return true;
} else if (expr_type == TypeManager.float_type){
//
// float to double
//
if (target_type == TypeManager.double_type)
return true;
}
return false;
}
//
// Horrible, horrible. But there is no other way we can pass the EmitContext
// to the recursive definition triggered by the evaluation of a forward
// expression
//
static EmitContext current_ec = null;
/// <summary>
/// This is used to lookup the value of an enum member. If the member is undefined,
/// it attempts to define it and return its value
/// </summary>
public object LookupEnumValue (EmitContext ec, string name, Location loc)
{
object default_value = null;
Constant c = null;
default_value = member_to_value [name];
if (default_value != null)
return default_value;
//
// This may happen if we're calling a method in System.Enum, for instance
// Enum.IsDefined().
//
if (!defined_names.Contains (name))
return null;
if (in_transit.Contains (name)) {
Report.Error (110, loc, "The evaluation of the constant value for `" +
Name + "." + name + "' involves a circular definition.");
return null;
}
//
// So if the above doesn't happen, we have a member that is undefined
// We now proceed to define it
//
Expression val = this [name];
if (val == null) {
int idx = ordered_enums.IndexOf (name);
if (idx == 0)
default_value = 0;
else {
for (int i = 0; i < idx; ++i) {
string n = (string) ordered_enums [i];
Location m_loc = (Mono.CSharp.Location)
member_to_location [n];
in_transit.Add (name, true);
EmitContext old_ec = current_ec;
current_ec = ec;
default_value = LookupEnumValue (ec, n, m_loc);
current_ec = old_ec;
in_transit.Remove (name);
if (default_value == null)
return null;
}
default_value = GetNextDefaultValue (default_value);
}
} else {
bool old = ec.InEnumContext;
ec.InEnumContext = true;
in_transit.Add (name, true);
EmitContext old_ec = current_ec;
current_ec = ec;
val = val.Resolve (ec);
current_ec = old_ec;
in_transit.Remove (name);
ec.InEnumContext = old;
if (val == null)
return null;
if (!IsValidEnumConstant (val)) {
Report.Error (
1008, loc,
"Type byte, sbyte, short, ushort, int, uint, long, or " +
"ulong expected (have: " + val + ")");
return null;
}
c = (Constant) val;
default_value = c.GetValue ();
if (default_value == null) {
Error_ConstantValueCannotBeConverted (c, loc);
return null;
}
if (val is EnumConstant){
Type etype = TypeManager.EnumToUnderlying (c.Type);
if (!ImplicitConversionExists (etype, UnderlyingType)){
Convert.Error_CannotImplicitConversion (
loc, c.Type, UnderlyingType);
return null;
}
}
}
EnumMember em = (EnumMember) defined_names [name];
em.DefineMember (TypeBuilder);
bool fail;
default_value = TypeManager.ChangeType (default_value, UnderlyingType, out fail);
if (fail){
Error_ConstantValueCannotBeConverted (c, loc);
return null;
}
em.builder.SetConstant (default_value);
field_builders.Add (em.builder);
member_to_value [name] = default_value;
if (!TypeManager.RegisterFieldValue (em.builder, default_value))
return null;
return default_value;
}
public override bool DefineMembers (TypeContainer parent)
{
return true;
}
public override bool Define ()
{
//
// If there was an error during DefineEnum, return
//
if (TypeBuilder == null)
return false;
ec = new EmitContext (this, this, Location, null, UnderlyingType, ModFlags, false);
object default_value = 0;
foreach (string name in ordered_enums) {
//
// Have we already been defined, thanks to some cross-referencing ?
//
if (member_to_value.Contains (name))
continue;
Location loc = (Mono.CSharp.Location) member_to_location [name];
if (this [name] != null) {
default_value = LookupEnumValue (ec, name, loc);
if (default_value == null)
return true;
} else {
if (name == "value__"){
Report.Error (76, loc, "The name `value__' is reserved for enumerations");
return false;
}
EnumMember em = (EnumMember) defined_names [name];
em.DefineMember (TypeBuilder);
FieldBuilder fb = em.builder;
if (default_value == null) {
Report.Error (543, loc, "Enumerator value for '" + name + "' is too large to " +
"fit in its type");
return false;
}
bool fail;
default_value = TypeManager.ChangeType (default_value, UnderlyingType, out fail);
if (fail){
Error_ConstantValueCannotBeConverted (default_value, loc);
return false;
}
fb.SetConstant (default_value);
field_builders.Add (fb);
member_to_value [name] = default_value;
if (!TypeManager.RegisterFieldValue (fb, default_value))
return false;
}
default_value = GetNextDefaultValue (default_value);
}
return true;
}
public override void Emit ()
{
if (OptAttributes != null) {
OptAttributes.Emit (ec, this);
}
foreach (EnumMember em in defined_names.Values) {
em.Emit (ec);
}
base.Emit ();
}
void VerifyClsName ()
{
Hashtable ht = new Hashtable ();
foreach (string name in ordered_enums) {
string locase = name.ToLower (System.Globalization.CultureInfo.InvariantCulture);
if (!ht.Contains (locase)) {
ht.Add (locase, defined_names [name]);
continue;
}
MemberCore conflict = (MemberCore)ht [locase];
Report.SymbolRelatedToPreviousError (conflict);
conflict = GetDefinition (name);
Report.Error (3005, conflict.Location, "Identifier '{0}' differing only in case is not CLS-compliant", conflict.GetSignatureForError ());
}
}
protected override bool VerifyClsCompliance (DeclSpace ds)
{
if (!base.VerifyClsCompliance (ds))
return false;
VerifyClsName ();
if (!AttributeTester.IsClsCompliant (UnderlyingType)) {
Report.Error (3009, Location, "'{0}': base type '{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (UnderlyingType));
}
return true;
}
/// <summary>
/// Returns full enum name.
/// </summary>
string GetEnumeratorName (string valueName)
{
return String.Concat (Name, ".", valueName);
}
//
// IMemberFinder
//
public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
MemberFilter filter, object criteria)
{
ArrayList members = new ArrayList ();
if ((mt & MemberTypes.Field) != 0) {
if (criteria is string){
if (member_to_value [criteria] == null && current_ec != null){
LookupEnumValue (current_ec, (string) criteria, Location.Null);
}
}
foreach (FieldBuilder fb in field_builders)
if (filter (fb, criteria) == true)
members.Add (fb);
}
return new MemberList (members);
}
public override MemberCache MemberCache {
get {
return null;
}
}
public ArrayList ValueNames {
get {
return ordered_enums;
}
}
// indexer
public Expression this [string name] {
get {
return ((EnumMember) defined_names [name]).Type;
}
}
public override AttributeTargets AttributeTargets {
get {
return AttributeTargets.Enum;
}
}
protected override void VerifyObsoleteAttribute()
{
// UnderlyingType is never obsolete
}
}
}
View File
Whitespace-only changes.
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
-13
View File
@@ -1,13 +0,0 @@
class Stack<T> {
}
class Test {
}
class T {
Stack<Test> a;
static void Main()
{
}
}
-100
View File
@@ -1,100 +0,0 @@
// gen-il.cs: Generates MSIL code from the CIR.Tree
//
// Author: Miguel de Icaza ([email protected])
//
// Licensed under the terms of the GNU GPL
//
// (C) 2001 Ximian, Inc. (http://www.ximian.com)
//
using System;
using System.IO;
using System.Collections;
using CIR;
namespace MSIL {
public class Generator : CIR.ITreeDump {
StreamWriter o;
int indent = 0;
void output (string s)
{
Console.Write (s);
o.Write (s);
}
void space ()
{
output (new String (' ', indent * 2));
}
void ioutput (string s)
{
space ();
output (s);
}
void ioutputl (string s)
{
ioutput (s + "\n");
}
string ClassAttributes (Class c)
{
// FIXME
return "";
}
string ILName (string name)
{
return name;
}
string ClassExtends (Class c)
{
return "";
}
void GenerateFromClass (Class c)
{
ioutputl (".class " + ClassAttributes (c) + " " + ILName (c.Name));
ioutputl (ClassExtends (c));
ioutputl ("{");
indent++;
indent--;
ioutputl ("}");
}
void GenerateFromTypes (TypeContainer types)
{
if (types.Types == null)
return;
foreach (DictionaryEntry de in types.Types){
TypeContainer type = (TypeContainer) de.Value;
if (type is Class)
GenerateFromClass ((Class) type);
}
}
public int GenerateFromTree (Tree tree, StreamWriter os)
{
this.o = os;
ioutputl (".assembly test.exe { }");
GenerateFromTypes (tree.Types);
return 0;
}
public void ParseOptions (string options)
{
}
}
}
-988
View File
@@ -1,988 +0,0 @@
// cs-treedump.cs: Dumps the parsed tree to standard output
//
// Author: Miguel de Icaza ([email protected])
//
// Licensed under the terms of the GNU GPL
//
// (C) 2001 Ximian, Inc. (http://www.ximian.com)
//
// TODO:
// Variable declarations
// Fix precedence rules to lower the number of parenthesis.
//
using System;
using System.IO;
using System.Collections;
using CIR;
namespace Generator {
public class TreeDump : CIR.ITreeDump {
StreamWriter o;
int indent;
bool indented;
bool tag_values;
void space ()
{
if (!indented)
output (new String (' ', indent * 8));
indented = true;
}
void output (string s)
{
Console.Write (s);
//o.Write (s);
}
void newline ()
{
output ("\n");
indented = false;
}
void output_newline (string s)
{
output (s);
newline ();
}
void ioutput (string s)
{
space ();
output (s);
}
string GetParameter (Parameter par)
{
Parameter.Modifier f = par.ModFlags;
string mod = "";
switch (f){
case Parameter.Modifier.REF:
mod = "ref "; break;
case Parameter.Modifier.OUT:
mod = "out "; break;
case Parameter.Modifier.PARAMS:
mod = "params "; break;
case Parameter.Modifier.NONE:
mod = ""; break;
}
return mod + par.Type + " " + par.Name;
}
string GetUnary (Unary u, int paren_level)
{
string e;
bool left = true;
string s = "0_ERROR>";
int prec = 0;
switch (u.Oper){
case Unary.Operator.UnaryPlus:
prec = 10;
s = "+";
break;
case Unary.Operator.UnaryNegation:
prec = 10;
s = "-";
break;
case Unary.Operator.LogicalNot:
s = "!";
prec = 10;
break;
case Unary.Operator.OnesComplement:
prec = 10;
s = "~";
break;
case Unary.Operator.Indirection:
prec = 10;
s = "*";
break;
case Unary.Operator.AddressOf:
prec = 10;
s = "&";
break;
case Unary.Operator.PreIncrement:
prec = 11;
s = "++";
break;
case Unary.Operator.PreDecrement:
prec = 11;
s = "--";
break;
case Unary.Operator.PostDecrement:
left = false;
prec = 12;
s = "--";
break;
case Unary.Operator.PostIncrement:
s = "++";
prec = 12;
left = false;
break;
}
e = GetExpression (u.Expr, prec);
if (left)
e = s + e;
else
e = e + s;
if (prec < paren_level)
return "(" + e + ")";
else
return e;
}
string GetBinary (Binary b, int paren_level)
{
string l, r;
string op = null;
bool assoc_left = true;
int prec = 0;
switch (b.Oper){
case Binary.Operator.Multiply:
prec = 9;
op = "*"; break;
case Binary.Operator.Division:
prec = 9;
op = "/"; break;
case Binary.Operator.Modulus:
prec = 9;
op = "%"; break;
case Binary.Operator.Addition:
prec = 8;
op = "+"; break;
case Binary.Operator.Subtraction:
prec = 8;
op = "-"; break;
case Binary.Operator.LeftShift:
prec = 7;
op = "<<"; break;
case Binary.Operator.RightShift:
prec = 7;
op = ">>"; break;
case Binary.Operator.LessThan:
prec = 6;
op = "<"; break;
case Binary.Operator.GreaterThan:
prec = 6;
op = ">"; break;
case Binary.Operator.LessThanOrEqual:
prec = 6;
op = "<="; break;
case Binary.Operator.GreaterThanOrEqual:
prec = 6;
op = ">="; break;
case Binary.Operator.Equality:
prec = 5;
op = "=="; break;
case Binary.Operator.Inequality:
prec = 5;
op = "!="; break;
case Binary.Operator.BitwiseAnd:
prec = 4;
op = "&"; break;
case Binary.Operator.BitwiseOr:
prec = 2;
op = "|"; break;
case Binary.Operator.LogicalAnd:
prec = 1;
op = "&&"; break;
case Binary.Operator.LogicalOr:
prec = 0;
op = "||"; break;
case Binary.Operator.ExclusiveOr:
prec = 3;
op = "^"; break;
}
l = GetExpression (b.Left, prec - (assoc_left ? 0 : 1));
r = GetExpression (b.Right, prec - (assoc_left ? 0 : 1));
if (prec <= paren_level)
return "(" + l + " " + op + " " + r + ")";
else
return l + " " + op + " " + r;
}
string GetCast (Cast c)
{
return "(" + c.TargetType + ") (" + GetExpression (c.Expr, 0) + ")";
}
string GetConditional (Conditional c)
{
return "(" + GetExpression (c.Expr, 0) + ") ? (" +
GetExpression (c.TrueExpr, 0) + ") : (" +
GetExpression (c.FalseExpr, 0) + ")";
}
string GetAssign (Assign a)
{
return GetExpression (a.Target, 0) + " = " + GetExpression (a.Source, 0);
}
string GetArguments (ArrayList args)
{
string r = "";
if (args != null){
int top = args.Count;
for (int i = 0; i < top; i++){
Argument arg = (Argument) args [i];
switch (arg.ArgType){
case Argument.AType.Ref:
r += "ref "; break;
case Argument.AType.Out:
r += "out "; break;
}
r += GetExpression (arg.Expr, 0);
if (i+1 != top)
r += ", ";
}
}
return "(" + r + ")";
}
string GetInvocation (Invocation i)
{
return GetExpression (i.Expr, 0) + " " + GetArguments (i.Arguments);
}
string GetNew (New n)
{
return "new " + n.RequestedType + GetArguments (n.Arguments);
}
string GetTypeOf (TypeOf t)
{
return "typeof (" + t.QueriedType + ")";
}
string GetSizeOf (SizeOf t)
{
return "sizeof (" + t.QueriedType + ")";
}
string GetMemberAccess (MemberAccess m)
{
return GetExpression (m.Expr, 0) +
(tag_values ? "/* member access */ . " : ".") +
m.Identifier;
}
string GetSimpleName (SimpleName n)
{
string s = n.Name;
if (s.StartsWith ("0_"))
return "id_" + s;
else
return s;
}
string GetProbe (Probe p)
{
string s = GetExpression (p.Expr, 6);
if (p.Oper == CIR.Probe.Operator.Is)
s += " is ";
else if (p.Oper == CIR.Probe.Operator.As)
s += " as ";
else
s += "UNHANDLED";
s += p.ProbeType;
return s;
}
string GetLocalVariableReference (LocalVariableReference l)
{
if (tag_values)
return "/* local var: */" + l.Name;
else
return l.Name;
}
string GetParameterReference (ParameterReference r)
{
if (tag_values)
return "/* par: */ " + r.Name;
else
return r.Name;
}
string GetExpression (Expression e, int paren_level)
{
if (e == null){
return "<NULL EXPRESSION>";
}
if (e is Unary)
return GetUnary ((Unary) e, paren_level);
else if (e is Binary)
return GetBinary ((Binary) e, paren_level);
else if (e is Cast)
return GetCast ((Cast) e);
else if (e is Conditional)
return GetConditional ((Conditional) e);
else if (e is SimpleName)
return GetSimpleName ((SimpleName)e);
else if (e is LocalVariableReference)
return GetLocalVariableReference ((LocalVariableReference) e);
else if (e is ParameterReference)
return GetParameterReference ((ParameterReference) e);
else if (e is Assign)
return GetAssign ((Assign) e);
else if (e is Literal)
return e.ToString ();
else if (e is Invocation)
return GetInvocation ((Invocation) e);
else if (e is New)
return GetNew ((New) e);
else if (e is This)
return "this";
else if (e is TypeOf)
return GetTypeOf ((TypeOf) e);
else if (e is SizeOf)
return GetSizeOf ((SizeOf) e);
else if (e is MemberAccess)
return GetMemberAccess ((MemberAccess) e);
else if (e is Probe)
return GetProbe ((Probe) e);
else
return "WARNING {" + e.ToString () + "} WARNING";
}
void GenerateParameters (Parameters pars)
{
Parameter [] pfixed;
Parameter parray;
pfixed = pars.FixedParameters;
if (pfixed != null){
for (int i = 0; i < pfixed.Length; i++){
output (GetParameter (pfixed [i]));
if (i+1 != pfixed.Length)
output (", ");
}
}
parray = pars.ArrayParameter;
if (parray != null){
output (GetParameter (parray));
}
}
void GenerateIf (If s)
{
bool do_indent;
output ("if (" + GetExpression (s.Expr, 0) + ") ");
do_indent = !(s.TrueStatement is Block);
if (do_indent)
indent++;
GenerateStatement (s.TrueStatement, true, false, false);
if (do_indent)
indent--;
if (s.FalseStatement != null){
ioutput ("else");
newline ();
GenerateStatement (s.FalseStatement, false, true, false);
}
}
void GenerateDo (Do s)
{
output ("do"); newline ();
indent++;
GenerateStatement (s.EmbeddedStatement, false, false, false);
indent--;
output (" while (" + GetExpression (s.Expr, 0) + ");");
newline ();
}
void GenerateWhile (While s)
{
output ("while (" + GetExpression (s.Expr, 0) + ")");
GenerateStatement (s.Statement, true, true, false);
}
void GenerateFor (For s)
{
output ("for (");
if (! (s.InitStatement == EmptyStatement.Value))
GenerateStatement (s.InitStatement, true, true, true);
output ("; ");
output (GetExpression (s.Test, 0));
output ("; ");
if (! (s.Increment == EmptyStatement.Value))
GenerateStatement (s.Increment, true, true, true);
output (") ");
GenerateStatement (s.Statement, true, true, false);
}
void GenerateReturn (Return s)
{
output ("return " +
(s.Expr != null ?
GetExpression (s.Expr, 0) : "" + ";") +
";");
newline ();
}
void GenerateGoto (Goto s)
{
output ("goto " + s.Target + ";");
newline ();
}
void GenerateThrow (Throw s)
{
}
void GenerateStatementExpression (StatementExpression s)
{
output (GetExpression (s.Expr, 0) + ";");
newline ();
}
void GenerateSwitchLabels (ArrayList labels)
{
foreach (SwitchLabel sl in labels){
Expression lab = sl.Label;
if (lab == null){
ioutput ("default:");
newline ();
} else {
ioutput ("case " + GetExpression (lab, 0) + ":");
newline ();
}
}
}
void GenerateSwitch (Switch s)
{
output_newline ("switch (" + GetExpression (s.Expr, 0) + ")");
foreach (SwitchSection ss in s.Sections){
GenerateSwitchLabels (ss.Labels);
GenerateBlock (ss.Block, false, false);
}
}
void GenerateChecked (Checked c)
{
output ("checked ");
GenerateBlock (c.Block, false, false);
}
void GenerateUnchecked (Unchecked c)
{
output ("unchecked ");
GenerateBlock (c.Block, false, false);
}
void GenerateCatchClauses (ArrayList list)
{
foreach (Catch c in list){
space ();
output ("catch ");
if (c.Type != null){
output ("(" + c.Type +
(c.Name != null ? " " + c.Name : "") + ")");
}
GenerateBlock (c.Block, false, false);
}
}
void GenerateTry (Try t)
{
output ("try");
GenerateBlock (t.Block, false, false);
if (t.Specific != null){
GenerateCatchClauses (t.Specific);
}
if (t.General != null){
space ();
output ("catch");
GenerateBlock (t.Block, false, false);
}
if (t.Fini != null){
GenerateBlock (t.Fini, false, false);
}
}
void GenerateStatement (Statement s, bool doPlacement, bool blockFlushesLine, bool embedded)
{
if (s == null){
output ("WARNING: got a null Statement");
newline ();
return;
}
if (doPlacement){
if (s is Block){
GenerateBlock ((Block) s, doPlacement, embedded);
return;
} else
newline ();
}
space ();
if (s is If)
GenerateIf ((If) s);
else if (s is Do)
GenerateDo ((Do) s);
else if (s is While)
GenerateWhile ((While) s);
else if (s is For)
GenerateFor ((For) s);
else if (s is Return)
GenerateReturn ((Return) s);
else if (s is Goto)
GenerateGoto ((Goto) s);
else if (s is Throw)
GenerateThrow ((Throw) s);
else if (s is Break)
output_newline ("break;");
else if (s is Continue)
output_newline ("continue;");
else if (s == EmptyStatement.Value)
output_newline ("/* empty statement */;");
else if (s is Block)
GenerateBlock ((Block) s, doPlacement, embedded);
else if (s is StatementExpression)
GenerateStatementExpression ((StatementExpression) s);
else if (s is Switch)
GenerateSwitch ((Switch) s);
else if (s is Checked)
GenerateChecked ((Checked) s);
else if (s is Unchecked)
GenerateUnchecked ((Unchecked) s);
else if (s is Try)
GenerateTry ((Try) s);
else {
System.Type t = s.GetType ();
output ("\n*****UNKNOWN Statement:" + t.ToString ());
}
}
//
// embedded is used only for things like the For thing
// that has blocks but for display purposes we want to keep
// without newlines.
void GenerateBlock (Block b, bool doPlacement, bool embedded)
{
if (b.Label != null)
output (b.Label + ":");
if (!b.Implicit){
if (!doPlacement)
space ();
output ("{");
if (!embedded)
newline ();
indent++;
}
if (b.Variables != null){
foreach (DictionaryEntry entry in b.Variables){
VariableInfo vi = (VariableInfo) entry.Value;
space ();
output_newline (
vi.Type + " " +
(string) entry.Key + ";");
}
newline ();
}
foreach (Statement s in b.Statements){
GenerateStatement (s, false, true, false);
}
if (!b.Implicit){
indent--;
ioutput ("}");
if (!embedded)
newline ();
}
}
void GenerateMethod (Method m)
{
ioutput (GetModifiers (m.ModFlags) +
m.ReturnType + " " +
m.Name + " (");
GenerateParameters (m.Parameters);
output_newline (")");
GenerateBlock (m.Block, false, false);
newline ();
}
void GenerateInterfaceMethod (InterfaceMethod imethod)
{
space ();
output (imethod.IsNew ? "new " : "");
output (imethod.ReturnType + " " + imethod.Name + " (");
GenerateParameters (imethod.Parameters);
output (");");
newline ();
}
void GenerateInterfaceProperty (InterfaceProperty iprop)
{
space ();
output (iprop.IsNew ? "new " : "");
output (iprop.Type + " " + iprop.Name + " { ");
if (iprop.HasGet) output ("get; ");
if (iprop.HasSet) output ("set; ");
output ("}");
newline ();
}
void GenerateInterfaceEvent (InterfaceEvent ievent)
{
space ();
output ((ievent.IsNew ? "new " : "") + "event ");
output (ievent.Type + " " + ievent.Name + ";");
newline ();
}
void GenerateInterfaceIndexer (InterfaceIndexer iindexer)
{
space ();
output (iindexer.IsNew ? "new " : "");
output (iindexer.Type + " this [");
output (iindexer.Parameters + "] {");
if (iindexer.HasGet) output ("get; ");
if (iindexer.HasSet) output ("set; ");
output ("}");
newline ();
}
string GenIfaceBases (Interface iface)
{
return GenBases (iface.Bases);
}
void GenerateInterface (Interface iface)
{
ioutput (GetModifiers (iface.ModFlags) + "interface " +
ClassName (iface.Name) + GenIfaceBases (iface) + " {");
newline ();
indent++;
if (iface.InterfaceMethods != null){
foreach (DictionaryEntry de in iface.InterfaceMethods){
InterfaceMethod method = (InterfaceMethod) de.Value;
GenerateInterfaceMethod (method);
}
}
if (iface.InterfaceProperties != null){
foreach (DictionaryEntry de in iface.InterfaceProperties){
InterfaceProperty iprop = (InterfaceProperty) de.Value;
GenerateInterfaceProperty (iprop);
}
}
if (iface.InterfaceEvents != null){
foreach (DictionaryEntry de in iface.InterfaceEvents){
InterfaceEvent ievent = (InterfaceEvent) de.Value;
GenerateInterfaceEvent (ievent);
}
}
if (iface.InterfaceIndexers != null){
foreach (DictionaryEntry de in iface.InterfaceIndexers){
InterfaceIndexer iindexer = (InterfaceIndexer) de.Value;
GenerateInterfaceIndexer (iindexer);
}
}
indent--;
ioutput ("}");
newline ();
newline ();
}
void GenerateField (Field f)
{
space ();
output (GetModifiers (f.ModFlags) +
f.Type + " " + f.Name);
if (f.Initializer != null){
if (f.Initializer is Expression)
output (" = " + GetExpression ((Expression) f.Initializer, 0));
else
output ("ADD SUPPORT FOR ARRAYS");
}
output (";");
newline ();
}
void GenerateConstructor (Constructor c)
{
ConstructorInitializer init = c.Initializer;
space ();
output (GetModifiers (c.ModFlags) + c.Name + " (");
GenerateParameters (c.Parameters);
output (")");
if (init != null){
if (init is ConstructorThisInitializer)
output (": this (");
else
output (": base (");
output (GetArguments (init.Arguments));
output (")");
}
newline ();
GenerateBlock (c.Block, false, false);
}
void GenerateProperty (Property prop)
{
space ();
output (GetModifiers (prop.ModFlags) + prop.Type +
" " + prop.Name + " {");
newline ();
indent++;
if (prop.Get != null){
space ();
output ("get ");
GenerateBlock (prop.Get, false, false);
newline ();
}
if (prop.Set != null){
space ();
output ("set ");
GenerateBlock (prop.Set, false, false);
}
indent--;
space ();
output ("}");
newline ();
}
void GenerateEnum (CIR.Enum e)
{
space ();
output ("enum " + e.Name + " {");
newline ();
indent++;
foreach (string name in e.ValueNames){
Expression expr = e [name];
space ();
output (name);
if (expr != null)
output (" = " + GetExpression (expr, 0));
output (",");
newline ();
}
indent--;
space ();
output_newline ("}");
}
void GenerateTypeContainerData (TypeContainer tc)
{
if (tc.Constants != null){
foreach (Constant c in tc.Constants){
space ();
output ("const " + c.ConstantType + " " + c.Name + " = " +
GetExpression (c.Expr, 0) + ";");
newline ();
}
newline ();
}
if (tc.Enums != null){
foreach (CIR.Enum e in tc.Enums)
GenerateEnum (e);
}
if (tc.Fields != null){
foreach (Field f in tc.Fields)
GenerateField (f);
newline ();
}
if (tc.Constructors != null){
foreach (Constructor c in tc.Constructors)
GenerateConstructor (c);
newline ();
}
if (tc.Properties != null){
foreach (Property prop in tc.Properties)
GenerateProperty (prop);
}
GenerateFromTypes (tc);
if (tc.Methods != null){
foreach (Method m in tc.Methods){
GenerateMethod (m);
}
}
}
string GetModifiers (int mod_flags)
{
string s = "";
for (int i = 1; i <= (int) CIR.Modifiers.TOP; i <<= 1){
if ((mod_flags & i) != 0)
s += Modifiers.Name (i) + " ";
}
return s;
}
string ClassName (string name)
{
return name;
//return name.Substring (1 + name.LastIndexOf ('.'));
}
string GenBases (ArrayList bases)
{
if (bases == null)
return "";
string res = ": ";
int top = bases.Count;
for (int i = 0; i < bases.Count; i++){
Type t = (Type) bases [i];
res += t.Name;
if (i + 1 != top)
res += ", ";
}
return res;
}
string GenClassBases (Class c)
{
return GenBases (c.Bases);
}
void GenerateFromClass (Class c)
{
ioutput (GetModifiers (c.ModFlags) + "class " + ClassName (c.Name) +
" " + GenClassBases (c) + " {");
newline ();
indent++;
GenerateTypeContainerData (c);
indent--;
ioutput ("}");
newline ();
newline ();
}
void GenerateFromStruct (Struct s)
{
GenerateTypeContainerData (s);
}
void GenerateFromTypes (TypeContainer types)
{
if (types.Types == null)
return;
foreach (DictionaryEntry de in types.Types){
TypeContainer type = (TypeContainer) de.Value;
if (type is Class)
GenerateFromClass ((Class) type);
if (type is Struct)
GenerateFromStruct ((Struct) type);
}
if (types.Interfaces != null){
foreach (DictionaryEntry de in types.Interfaces){
Interface iface = (Interface) de.Value;
GenerateInterface (iface);
}
}
}
public int Dump (Tree tree, StreamWriter output)
{
this.o = output;
indent = 0;
GenerateFromTypes (tree.Types);
return 0;
}
public void ParseOptions (string options)
{
if (options == "tag")
tag_values = true;
}
}
}
-1448
View File
File diff suppressed because it is too large. Load diff
-14
View File
@@ -1,14 +0,0 @@
<configuration>
<startup>
<supportedRuntime version="v2.0.40607"/>
</startup>
<system.diagnostics>
<trace autoflush="true" indentsize="4">
<listeners>
<add name="compilerLogListener" type="System.Diagnostics.TextWriterTraceListener,System"
initializeData="mcs.log" />
<remove type="System.Diagnostics.DefaultTraceListener,System"/>
</listeners>
</trace>
</system.diagnostics>
</configuration>
-983
View File
@@ -1,983 +0,0 @@
//
// iterators.cs: Support for implementing iterators
//
// Author:
// Miguel de Icaza ([email protected])
//
// (C) 2003 Ximian, Inc.
//
// TODO:
// Flow analysis for Yield.
// Emit calls to parent object constructor.
//
// Generics note:
// Current should be defined to return T, and IEnumerator.Current returns object
//
using System;
using System.Collections;
using System.Reflection;
using System.Reflection.Emit;
namespace Mono.CSharp {
public interface IIteratorContainer {
//
// Invoked if a yield statement is found in the body
//
void SetYields ();
}
public class Yield : Statement {
public Expression expr;
ArrayList finally_blocks;
public Yield (Expression expr, Location l)
{
this.expr = expr;
loc = l;
}
public static bool CheckContext (EmitContext ec, Location loc)
{
if (ec.CurrentBranching.InFinally (true)){
Report.Error (1625, loc, "Cannot yield in the body of a " +
"finally clause");
return false;
}
if (ec.CurrentBranching.InCatch ()){
Report.Error (1631, loc, "Cannot yield in the body of a " +
"catch clause");
return false;
}
if (ec.CurrentAnonymousMethod != null){
Report.Error (1621, loc, "yield statement can not appear inside an anonymoud method");
return false;
}
//
// FIXME: Missing check for Yield inside try block that contains catch clauses
//
return true;
}
public override bool Resolve (EmitContext ec)
{
expr = expr.Resolve (ec);
if (expr == null)
return false;
if (!CheckContext (ec, loc))
return false;
Iterator iterator = ec.CurrentIterator;
if (expr.Type != iterator.IteratorType){
expr = Convert.ImplicitConversionRequired (
ec, expr, iterator.IteratorType, loc);
if (expr == null)
return false;
}
ec.CurrentBranching.StealFinallyClauses (ref finally_blocks);
return true;
}
protected override void DoEmit (EmitContext ec)
{
ec.CurrentIterator.MarkYield (ec, expr, finally_blocks);
}
}
public class YieldBreak : Statement {
public YieldBreak (Location l)
{
loc = l;
}
public override bool Resolve (EmitContext ec)
{
if (!Yield.CheckContext (ec, loc))
return false;
ec.CurrentBranching.CurrentUsageVector.Goto ();
return true;
}
protected override void DoEmit (EmitContext ec)
{
ec.CurrentIterator.EmitYieldBreak (ec.ig);
}
}
public class Iterator : Class {
ToplevelBlock original_block;
ToplevelBlock block;
string original_name;
Type iterator_type;
TypeExpr iterator_type_expr;
bool is_enumerable;
bool is_static;
Hashtable fields;
//
// The state as we generate the iterator
//
Label move_next_ok, move_next_error;
ArrayList resume_points = new ArrayList ();
int pc;
//
// Context from the original method
//
TypeContainer container;
TypeExpr current_type;
Type this_type;
Type return_type;
Type [] param_types;
InternalParameters parameters;
Expression enumerator_type;
Expression enumerable_type;
Expression generic_enumerator_type;
Expression generic_enumerable_type;
TypeArguments generic_args;
protected enum State {
Uninitialized = -2,
After,
Running
}
static int proxy_count;
public void EmitYieldBreak (ILGenerator ig)
{
ig.Emit (OpCodes.Ldarg_0);
IntConstant.EmitInt (ig, (int) State.After);
ig.Emit (OpCodes.Stfld, pc_field.FieldBuilder);
ig.Emit (OpCodes.Br, move_next_error);
}
public void EmitMoveNext (EmitContext ec)
{
ILGenerator ig = ec.ig;
move_next_ok = ig.DefineLabel ();
move_next_error = ig.DefineLabel ();
LocalBuilder retval = ec.GetTemporaryLocal (TypeManager.int32_type);
ig.BeginExceptionBlock ();
Label dispatcher = ig.DefineLabel ();
ig.Emit (OpCodes.Br, dispatcher);
ResumePoint entry_point = new ResumePoint (null);
resume_points.Add (entry_point);
entry_point.Define (ig);
ec.EmitTopBlock (original_block, parameters, Location);
EmitYieldBreak (ig);
ig.MarkLabel (dispatcher);
Label [] labels = new Label [resume_points.Count];
for (int i = 0; i < labels.Length; i++)
labels [i] = ((ResumePoint) resume_points [i]).Label;
ig.Emit (OpCodes.Ldarg_0);
ig.Emit (OpCodes.Ldfld, pc_field.FieldBuilder);
ig.Emit (OpCodes.Switch, labels);
Label end = ig.DefineLabel ();
ig.MarkLabel (move_next_error);
ig.Emit (OpCodes.Ldc_I4_0);
ig.Emit (OpCodes.Stloc, retval);
ig.Emit (OpCodes.Leave, end);
ig.MarkLabel (move_next_ok);
ig.Emit (OpCodes.Ldc_I4_1);
ig.Emit (OpCodes.Stloc, retval);
ig.Emit (OpCodes.Leave, end);
ig.BeginFaultBlock ();
ig.Emit (OpCodes.Ldarg_0);
ig.Emit (OpCodes.Callvirt, dispose.MethodBuilder);
ig.EndExceptionBlock ();
ig.MarkLabel (end);
ig.Emit (OpCodes.Ldloc, retval);
ig.Emit (OpCodes.Ret);
}
public void EmitDispose (EmitContext ec)
{
ILGenerator ig = ec.ig;
Label end = ig.DefineLabel ();
Label dispatcher = ig.DefineLabel ();
ig.Emit (OpCodes.Br, dispatcher);
ec.RemapToProxy = true;
Label [] labels = new Label [resume_points.Count];
for (int i = 0; i < labels.Length; i++) {
ResumePoint point = (ResumePoint) resume_points [i];
if (point.FinallyBlocks == null) {
labels [i] = end;
continue;
}
labels [i] = ig.DefineLabel ();
ig.MarkLabel (labels [i]);
ig.BeginExceptionBlock ();
ig.BeginFinallyBlock ();
foreach (ExceptionStatement stmt in point.FinallyBlocks) {
if (stmt != null)
stmt.EmitFinally (ec);
}
ig.EndExceptionBlock ();
ig.Emit (OpCodes.Br, end);
}
ec.RemapToProxy = false;
ig.MarkLabel (dispatcher);
ig.Emit (OpCodes.Ldarg_0);
ig.Emit (OpCodes.Ldfld, pc_field.FieldBuilder);
ig.Emit (OpCodes.Switch, labels);
ig.Emit (OpCodes.Ldarg_0);
IntConstant.EmitInt (ig, (int) State.After);
ig.Emit (OpCodes.Stfld, pc_field.FieldBuilder);
ig.MarkLabel (end);
}
protected class ResumePoint
{
public Label Label;
public readonly ExceptionStatement[] FinallyBlocks;
public ResumePoint (ArrayList list)
{
if (list != null) {
FinallyBlocks = new ExceptionStatement [list.Count];
list.CopyTo (FinallyBlocks, 0);
}
}
public void Define (ILGenerator ig)
{
Label = ig.DefineLabel ();
ig.MarkLabel (Label);
}
}
//
// Invoked when a local variable declaration needs to be mapped to
// a field in our proxy class
//
// Prefixes registered:
// v_ for EmitContext.MapVariable
// s_ for Storage
//
public FieldBuilder MapVariable (string pfx, string name, Type t)
{
string full_name = pfx + name;
FieldBuilder fb = (FieldBuilder) fields [full_name];
if (fb != null)
return fb;
fb = TypeBuilder.DefineField (full_name, t, FieldAttributes.Private);
fields.Add (full_name, fb);
return fb;
}
//
// Called back from Yield
//
public void MarkYield (EmitContext ec, Expression expr,
ArrayList finally_blocks)
{
ILGenerator ig = ec.ig;
// Store the new current
ig.Emit (OpCodes.Ldarg_0);
expr.Emit (ec);
ig.Emit (OpCodes.Stfld, current_field.FieldBuilder);
// increment pc
pc++;
ig.Emit (OpCodes.Ldarg_0);
IntConstant.EmitInt (ig, pc);
ig.Emit (OpCodes.Stfld, pc_field.FieldBuilder);
// Return ok
ig.Emit (OpCodes.Br, move_next_ok);
ResumePoint point = new ResumePoint (finally_blocks);
resume_points.Add (point);
point.Define (ig);
}
public void MarkFinally (EmitContext ec, ArrayList finally_blocks)
{
ILGenerator ig = ec.ig;
// increment pc
pc++;
ig.Emit (OpCodes.Ldarg_0);
IntConstant.EmitInt (ig, pc);
ig.Emit (OpCodes.Stfld, pc_field.FieldBuilder);
ResumePoint point = new ResumePoint (finally_blocks);
resume_points.Add (point);
point.Define (ig);
}
private static MemberName MakeProxyName (string name)
{
int pos = name.LastIndexOf ('.');
if (pos > 0)
name = name.Substring (pos + 1);
return new MemberName ("<" + name + ">__" + (proxy_count++));
}
//
// Our constructor
//
public Iterator (TypeContainer container, string name, Type return_type,
Type [] param_types, InternalParameters parameters,
int modifiers, ToplevelBlock block, Location loc)
: base (container.NamespaceEntry, container, MakeProxyName (name),
Modifiers.PRIVATE, null, loc)
{
this.container = container;
this.return_type = return_type;
this.param_types = param_types;
this.parameters = parameters;
this.original_name = name;
this.original_block = block;
this.block = new ToplevelBlock (loc);
fields = new Hashtable ();
is_static = (modifiers & Modifiers.STATIC) != 0;
}
public bool DefineIterator ()
{
ec = new EmitContext (this, Mono.CSharp.Location.Null, null, null, ModFlags);
if (!CheckType (return_type)) {
Report.Error (
1624, Location,
"The body of `{0}' cannot be an iterator block " +
"because '{1}' is not an iterator interface type",
original_name, TypeManager.CSharpName (return_type));
return false;
}
for (int i = 0; i < parameters.Count; i++){
Parameter.Modifier mod = parameters.ParameterModifier (i);
if ((mod & (Parameter.Modifier.REF | Parameter.Modifier.OUT)) != 0){
Report.Error (
1623, Location,
"Iterators cannot have ref or out parameters");
return false;
}
}
if (container.CurrentType != null)
this_type = container.CurrentType.ResolveType (ec);
else
this_type = container.TypeBuilder;
generic_args = new TypeArguments (Location);
generic_args.Add (new TypeExpression (iterator_type, Location));
ArrayList list = new ArrayList ();
if (is_enumerable) {
enumerable_type = new TypeExpression (
TypeManager.ienumerable_type, Location);
list.Add (enumerable_type);
generic_enumerable_type = new ConstructedType (
TypeManager.generic_ienumerable_type,
generic_args, Location);
list.Add (generic_enumerable_type);
}
enumerator_type = new TypeExpression (
TypeManager.ienumerator_type, Location);
list.Add (enumerator_type);
list.Add (new TypeExpression (TypeManager.idisposable_type, Location));
generic_enumerator_type = new ConstructedType (
TypeManager.generic_ienumerator_type,
generic_args, Location);
list.Add (generic_enumerator_type);
iterator_type_expr = new TypeExpression (iterator_type, Location);
container.AddIterator (this);
Bases = list;
return true;
}
//
// Returns the new block for the method, or null on failure
//
protected override bool DefineNestedTypes ()
{
if (CurrentType != null)
current_type = CurrentType;
else
current_type = new TypeExpression (TypeBuilder, Location);
Define_Fields ();
Define_Constructor ();
Define_Current (false);
Define_Current (true);
Define_MoveNext ();
Define_Reset ();
Define_Dispose ();
if (is_enumerable) {
Define_GetEnumerator (false);
Define_GetEnumerator (true);
}
Create_Block ();
return base.DefineNestedTypes ();
}
Field pc_field;
Field current_field;
Method dispose;
public Field this_field;
public Field[] parameter_fields;
void Create_Block ()
{
int first = is_static ? 0 : 1;
ArrayList args = new ArrayList ();
if (!is_static) {
Type t = this_type;
args.Add (new Argument (
new ThisParameterReference (t, 0, Location)));
}
args.Add (new Argument (new BoolLiteral (false)));
for (int i = 0; i < parameters.Count; i++) {
Type t = parameters.ParameterType (i);
args.Add (new Argument (
new SimpleParameterReference (t, first + i, Location)));
}
Expression new_expr = new New (current_type, args, Location);
block.AddStatement (new NoCheckReturn (new_expr, Location));
}
void Define_Fields ()
{
Location loc = Location.Null;
pc_field = new Field (
this, TypeManager.system_int32_expr, Modifiers.PRIVATE, "PC",
null, null, loc);
AddField (pc_field);
current_field = new Field (
this, iterator_type_expr, Modifiers.PRIVATE, "current",
null, null, loc);
AddField (current_field);
if (!is_static) {
this_field = new Field (
this, new TypeExpression (this_type, loc),
Modifiers.PRIVATE, "this", null, null, loc);
AddField (this_field);
}
parameter_fields = new Field [parameters.Count];
for (int i = 0; i < parameters.Count; i++) {
string fname = String.Format (
"field{0}_{1}", i, parameters.ParameterName (i));
parameter_fields [i] = new Field (
this,
new TypeExpression (parameters.ParameterType (i), loc),
Modifiers.PRIVATE, fname, null, null, loc);
AddField (parameter_fields [i]);
}
}
void Define_Constructor ()
{
Parameters ctor_params;
ArrayList list = new ArrayList ();
if (!is_static)
list.Add (new Parameter (
new TypeExpression (this_type, Location),
"this", Parameter.Modifier.NONE, null));
list.Add (new Parameter (
TypeManager.system_boolean_expr, "initialized",
Parameter.Modifier.NONE, null));
Parameter[] old_fixed = parameters.Parameters.FixedParameters;
if (old_fixed != null)
list.AddRange (old_fixed);
Parameter[] fixed_params = new Parameter [list.Count];
list.CopyTo (fixed_params);
ctor_params = new Parameters (
fixed_params, parameters.Parameters.ArrayParameter,
Location);
Constructor ctor = new Constructor (
this, Name, Modifiers.PUBLIC, ctor_params,
new ConstructorBaseInitializer (
null, Parameters.EmptyReadOnlyParameters, Location),
Location);
AddConstructor (ctor);
ToplevelBlock block = ctor.Block = new ToplevelBlock (Location);
if (!is_static) {
Type t = this_type;
Assign assign = new Assign (
new FieldExpression (this_field),
new SimpleParameterReference (t, 1, Location),
Location);
block.AddStatement (new StatementExpression (assign, Location));
}
int first = is_static ? 2 : 3;
for (int i = 0; i < parameters.Count; i++) {
Type t = parameters.ParameterType (i);
Assign assign = new Assign (
new FieldExpression (parameter_fields [i]),
new SimpleParameterReference (t, first + i, Location),
Location);
block.AddStatement (new StatementExpression (assign, Location));
}
State initial = is_enumerable ? State.Uninitialized : State.Running;
block.AddStatement (new SetState (this, initial, Location));
block.AddStatement (new If (
new SimpleParameterReference (
TypeManager.bool_type, first - 1, Location),
new SetState (this, State.Running, Location),
Location));
}
Statement Create_ThrowInvalidOperation ()
{
TypeExpr ex_type = new TypeExpression (
TypeManager.invalid_operation_exception_type, Location);
return new Throw (new New (ex_type, null, Location), Location);
}
Statement Create_ThrowNotSupported ()
{
TypeExpr ex_type = new TypeExpression (
TypeManager.not_supported_exception_type, Location);
return new Throw (new New (ex_type, null, Location), Location);
}
void Define_Current (bool is_generic)
{
MemberName left;
Expression type;
if (is_generic) {
left = new MemberName (
"System.Collections.Generic.IEnumerator",
generic_args);
type = iterator_type_expr;
} else {
left = new MemberName ("System.Collections.IEnumerator");
type = TypeManager.system_object_expr;
}
MemberName name = new MemberName (left, "Current", null);
ToplevelBlock get_block = new ToplevelBlock (Location);
get_block.AddStatement (new If (
new Binary (
Binary.Operator.LessThanOrEqual,
new FieldExpression (pc_field),
new IntLiteral ((int) State.Running), Location),
Create_ThrowInvalidOperation (),
new Return (
new FieldExpression (current_field), Location),
Location));
Accessor getter = new Accessor (get_block, 0, null, Location);
Property current = new Property (
this, type, 0, false, name, null, getter, null, Location);
AddProperty (current);
}
void Define_MoveNext ()
{
Method move_next = new Method (
this, null, TypeManager.system_boolean_expr,
Modifiers.PUBLIC, false, new MemberName ("MoveNext"),
Parameters.EmptyReadOnlyParameters, null,
Location.Null);
AddMethod (move_next);
ToplevelBlock block = move_next.Block = new ToplevelBlock (Location);
MoveNextMethod inline = new MoveNextMethod (this, Location);
block.AddStatement (inline);
}
void Define_GetEnumerator (bool is_generic)
{
MemberName left;
Expression type;
if (is_generic) {
left = new MemberName (
"System.Collections.Generic.IEnumerable",
generic_args);
type = generic_enumerator_type;
} else {
left = new MemberName ("System.Collections.IEnumerable");
type = enumerator_type;
}
MemberName name = new MemberName (left, "GetEnumerator", null);
Method get_enumerator = new Method (
this, null, type, 0, false, name,
Parameters.EmptyReadOnlyParameters, null,
Location.Null);
AddMethod (get_enumerator);
get_enumerator.Block = new ToplevelBlock (Location);
Expression ce = new MemberAccess (
new SimpleName ("System.Threading.Interlocked", Location),
"CompareExchange", Location);
Expression pc = new FieldExpression (pc_field);
Expression before = new IntLiteral ((int) State.Running);
Expression uninitialized = new IntLiteral ((int) State.Uninitialized);
ArrayList args = new ArrayList ();
args.Add (new Argument (pc, Argument.AType.Ref));
args.Add (new Argument (before, Argument.AType.Expression));
args.Add (new Argument (uninitialized, Argument.AType.Expression));
get_enumerator.Block.AddStatement (new If (
new Binary (
Binary.Operator.Equality,
new Invocation (ce, args, Location),
uninitialized, Location),
new Return (new This (block, Location), Location),
Location));
args = new ArrayList ();
if (!is_static)
args.Add (new Argument (new FieldExpression (this_field)));
args.Add (new Argument (new BoolLiteral (true)));
for (int i = 0; i < parameters.Count; i++)
args.Add (new Argument (
new FieldExpression (parameter_fields [i])));
Expression new_expr = new New (current_type, args, Location);
get_enumerator.Block.AddStatement (new Return (new_expr, Location));
}
protected class SimpleParameterReference : Expression
{
int idx;
public SimpleParameterReference (Type type, int idx, Location loc)
{
this.idx = idx;
this.loc = loc;
this.type = type;
eclass = ExprClass.Variable;
}
public override Expression DoResolve (EmitContext ec)
{
return this;
}
public override void Emit (EmitContext ec)
{
DoEmit (ec);
}
protected virtual void DoEmit (EmitContext ec)
{
ParameterReference.EmitLdArg (ec.ig, idx);
}
}
protected class ThisParameterReference : SimpleParameterReference
{
public ThisParameterReference (Type type, int idx, Location loc)
: base (type, idx, loc)
{ }
protected override void DoEmit (EmitContext ec)
{
base.DoEmit (ec);
if (ec.TypeContainer is Struct)
ec.ig.Emit (OpCodes.Ldobj, type);
}
}
protected class FieldExpression : Expression
{
Field field;
public FieldExpression (Field field)
{
this.field = field;
}
public override Expression DoResolve (EmitContext ec)
{
FieldExpr fexpr = new FieldExpr (field.FieldBuilder, loc);
fexpr.InstanceExpression = ec.GetThis (loc);
return fexpr.Resolve (ec);
}
public override void Emit (EmitContext ec)
{
throw new InvalidOperationException ();
}
}
protected class MoveNextMethod : Statement {
Iterator iterator;
public MoveNextMethod (Iterator iterator, Location loc)
{
this.loc = loc;
this.iterator = iterator;
}
public override bool Resolve (EmitContext ec)
{
ec.CurrentBranching.CurrentUsageVector.Return ();
return true;
}
protected override void DoEmit (EmitContext ec)
{
int code_flags = Modifiers.METHOD_YIELDS;
if (iterator.is_static)
code_flags |= Modifiers.STATIC;
EmitContext new_ec = new EmitContext (
iterator.container, loc, ec.ig,
TypeManager.int32_type, code_flags);
new_ec.CurrentIterator = iterator;
iterator.EmitMoveNext (new_ec);
}
}
protected class DisposeMethod : Statement {
Iterator iterator;
public DisposeMethod (Iterator iterator, Location loc)
{
this.loc = loc;
this.iterator = iterator;
}
public override bool Resolve (EmitContext ec)
{
return true;
}
protected override void DoEmit (EmitContext ec)
{
iterator.EmitDispose (ec);
}
}
protected class StatementList : Statement {
ArrayList statements;
public StatementList (Location loc)
{
this.loc = loc;
statements = new ArrayList ();
}
public void Add (Statement statement)
{
statements.Add (statement);
}
public override bool Resolve (EmitContext ec)
{
foreach (Statement stmt in statements) {
if (!stmt.Resolve (ec))
return false;
}
return true;
}
protected override void DoEmit (EmitContext ec)
{
foreach (Statement stmt in statements)
stmt.Emit (ec);
}
}
protected class SetState : Statement
{
Iterator iterator;
State state;
public SetState (Iterator iterator, State state, Location loc)
{
this.iterator = iterator;
this.state = state;
this.loc = loc;
}
public override bool Resolve (EmitContext ec)
{
return true;
}
protected override void DoEmit (EmitContext ec)
{
ec.ig.Emit (OpCodes.Ldarg_0);
IntConstant.EmitInt (ec.ig, (int) state);
ec.ig.Emit (OpCodes.Stfld, iterator.pc_field.FieldBuilder);
}
}
void Define_Reset ()
{
Method reset = new Method (
this, null, TypeManager.system_void_expr, Modifiers.PUBLIC,
false, new MemberName ("Reset"),
Parameters.EmptyReadOnlyParameters, null, Location);
AddMethod (reset);
reset.Block = new ToplevelBlock (Location);
reset.Block.AddStatement (Create_ThrowNotSupported ());
}
void Define_Dispose ()
{
dispose = new Method (
this, null, TypeManager.system_void_expr, Modifiers.PUBLIC,
false, new MemberName ("Dispose"),
Parameters.EmptyReadOnlyParameters, null, Location);
AddMethod (dispose);
dispose.Block = new ToplevelBlock (Location);
dispose.Block.AddStatement (new DisposeMethod (this, Location));
}
public ToplevelBlock Block {
get { return block; }
}
public Type IteratorType {
get { return iterator_type; }
}
//
// This return statement tricks return into not flagging an error for being
// used in a Yields method
//
class NoCheckReturn : Return {
public NoCheckReturn (Expression expr, Location loc) : base (expr, loc)
{
}
public override bool Resolve (EmitContext ec)
{
ec.InIterator = false;
bool ret_val = base.Resolve (ec);
ec.InIterator = true;
return ret_val;
}
}
bool CheckType (Type t)
{
if (t == TypeManager.ienumerable_type) {
iterator_type = TypeManager.object_type;
is_enumerable = true;
return true;
} else if (t == TypeManager.ienumerator_type) {
iterator_type = TypeManager.object_type;
is_enumerable = false;
return true;
}
if (!t.IsGenericInstance)
return false;
Type[] args = TypeManager.GetTypeArguments (t);
if (args.Length != 1)
return false;
Type gt = t.GetGenericTypeDefinition ();
if (gt == TypeManager.generic_ienumerable_type) {
iterator_type = args [0];
is_enumerable = true;
return true;
} else if (gt == TypeManager.generic_ienumerator_type) {
iterator_type = args [0];
is_enumerable = false;
return true;
}
return false;
}
}
}
-240
View File
@@ -1,240 +0,0 @@
//
// literal.cs: Literal representation for the IL tree.
//
// Author:
// Miguel de Icaza ([email protected])
//
// (C) 2001 Ximian, Inc.
//
//
// Notice that during parsing we create objects of type Literal, but the
// types are not loaded (thats why the Resolve method has to assign the
// type at that point).
//
// Literals differ from the constants in that we know we encountered them
// as a literal in the source code (and some extra rules apply there) and
// they have to be resolved (since during parsing we have not loaded the
// types yet) while constants are created only after types have been loaded
// and are fully resolved when born.
//
using System;
using System.Reflection;
using System.Reflection.Emit;
//
// I put System.Null just so we do not have to special case it on
// TypeManager.CSharpName
//
namespace System {
//
// Represents the Null Type, just used as a placeholder for the type in NullLiteral
//
public class Null {
}
}
namespace Mono.CSharp {
public class NullLiteral : Constant {
public static readonly NullLiteral Null;
static NullLiteral ()
{
Null = new NullLiteral ();
}
public NullLiteral ()
{
eclass = ExprClass.Value;
}
override public string AsString ()
{
return "null";
}
public override object GetValue ()
{
return null;
}
public override Expression DoResolve (EmitContext ec)
{
type = typeof (System.Null);
return this;
}
public override void Emit (EmitContext ec)
{
ec.ig.Emit (OpCodes.Ldnull);
}
public override bool IsNegative {
get {
return false;
}
}
public override bool IsZeroInteger {
get { return true; }
}
}
//
// A null literal in a pointer context
//
public class NullPointer : NullLiteral {
public new static readonly NullLiteral Null;
static NullPointer ()
{
Null = new NullPointer ();
}
private NullPointer ()
{
type = TypeManager.object_type;
}
public override void Emit (EmitContext ec)
{
ILGenerator ig = ec.ig;
ig.Emit (OpCodes.Ldc_I4_0);
ig.Emit (OpCodes.Conv_U);
}
}
public class BoolLiteral : BoolConstant {
public BoolLiteral (bool val) : base (val)
{
}
public override Expression DoResolve (EmitContext ec)
{
type = TypeManager.bool_type;
return this;
}
}
public class CharLiteral : CharConstant {
public CharLiteral (char c) : base (c)
{
}
public override Expression DoResolve (EmitContext ec)
{
type = TypeManager.char_type;
return this;
}
}
public class IntLiteral : IntConstant {
public static IntLiteral One, Zero;
static IntLiteral ()
{
Zero = new IntLiteral (0);
One = new IntLiteral (1);
}
public IntLiteral (int l) : base (l)
{
}
public override Expression DoResolve (EmitContext ec)
{
type = TypeManager.int32_type;
return this;
}
}
public class UIntLiteral : UIntConstant {
public UIntLiteral (uint l) : base (l)
{
}
public override Expression DoResolve (EmitContext ec)
{
type = TypeManager.uint32_type;
return this;
}
}
public class LongLiteral : LongConstant {
public LongLiteral (long l) : base (l)
{
}
public override Expression DoResolve (EmitContext ec)
{
type = TypeManager.int64_type;
return this;
}
}
public class ULongLiteral : ULongConstant {
public ULongLiteral (ulong l) : base (l)
{
}
public override Expression DoResolve (EmitContext ec)
{
type = TypeManager.uint64_type;
return this;
}
}
public class FloatLiteral : FloatConstant {
public FloatLiteral (float f) : base (f)
{
}
public override Expression DoResolve (EmitContext ec)
{
type = TypeManager.float_type;
return this;
}
}
public class DoubleLiteral : DoubleConstant {
public DoubleLiteral (double d) : base (d)
{
}
public override Expression DoResolve (EmitContext ec)
{
type = TypeManager.double_type;
return this;
}
}
public class DecimalLiteral : DecimalConstant {
public DecimalLiteral (decimal d) : base (d)
{
}
public override Expression DoResolve (EmitContext ec)
{
type = TypeManager.decimal_type;
return this;
}
}
public class StringLiteral : StringConstant {
public StringLiteral (string s) : base (s)
{
}
public override Expression DoResolve (EmitContext ec)
{
type = TypeManager.string_type;
return this;
}
}
}
-232
View File
@@ -1,232 +0,0 @@
//
// location.cs: Keeps track of the location of source code entity
//
// Author:
// Miguel de Icaza
//
// (C) 2001 Ximian, Inc.
//
using System;
using System.IO;
using System.Collections;
using Mono.CompilerServices.SymbolWriter;
namespace Mono.CSharp {
/// <summary>
/// This is one single source file.
/// </summary>
/// <remarks>
/// This is intentionally a class and not a struct since we need
/// to pass this by reference.
/// </remarks>
public sealed class SourceFile : ISourceFile {
public readonly string Name;
public readonly string Path;
public readonly int Index;
public SourceFileEntry SourceFileEntry;
public bool HasLineDirective;
public SourceFile (string name, string path, int index)
{
this.Index = index;
this.Name = name;
this.Path = path;
}
SourceFileEntry ISourceFile.Entry {
get { return SourceFileEntry; }
}
public override string ToString ()
{
return String.Format ("SourceFile ({0}:{1}:{2}:{3})",
Name, Path, Index, SourceFileEntry);
}
}
/// <summary>
/// Keeps track of the location in the program
/// </summary>
///
/// <remarks>
/// This uses a compact representation and a couple of auxiliary
/// structures to keep track of tokens to (file,line) mappings.
///
/// We could probably also keep track of columns by storing those
/// in 8 bits (and say, map anything after char 255 to be `255+').
/// </remarks>
public struct Location {
public int token;
static ArrayList source_list;
static Hashtable source_files;
static int source_bits;
static int source_mask;
static int source_count;
static int current_source;
public readonly static Location Null;
static Location ()
{
source_files = new Hashtable ();
source_list = new ArrayList ();
current_source = 0;
Null.token = 0;
}
// <summary>
// This must be called before parsing/tokenizing any files.
// </summary>
static public void AddFile (string name)
{
string path = Path.GetFullPath (name);
if (source_files.Contains (path)){
Report.Warning (2002, name, "Source file '{0}' specified multiple times");
return;
}
source_files.Add (path, ++source_count);
source_list.Add (new SourceFile (name, path, source_count));
}
static public SourceFile[] SourceFiles {
get {
SourceFile[] retval = new SourceFile [source_list.Count];
source_list.CopyTo (retval, 0);
return retval;
}
}
static int log2 (int number)
{
int bits = 0;
while (number > 0) {
bits++;
number /= 2;
}
return bits;
}
// <summary>
// After adding all source files we want to compile with AddFile(), this method
// must be called to `reserve' an appropriate number of bits in the token for the
// source file. We reserve some extra space for files we encounter via #line
// directives while parsing.
// </summary>
static public void Initialize ()
{
source_bits = log2 (source_list.Count) + 2;
source_mask = (1 << source_bits) - 1;
}
// <remarks>
// This is used when we encounter a #line preprocessing directive.
// </remarks>
static public SourceFile LookupFile (string name)
{
string path = name == "" ? "" : Path.GetFullPath (name);
if (!source_files.Contains (path)) {
if (source_count >= (1 << source_bits))
return new SourceFile (name, path, 0);
source_files.Add (path, ++source_count);
SourceFile retval = new SourceFile (name, path, source_count);
source_list.Add (retval);
return retval;
}
int index = (int) source_files [path];
return (SourceFile) source_list [index - 1];
}
static public void Push (SourceFile file)
{
current_source = file.Index;
}
// <remarks>
// If we're compiling with debugging support, this is called between parsing
// and code generation to register all the source files with the
// symbol writer.
// </remarks>
static public void DefineSymbolDocuments (SymbolWriter symwriter)
{
foreach (SourceFile file in source_list) {
file.SourceFileEntry = symwriter.DefineDocument (file.Path);
}
}
public Location (int row)
{
if (row < 0)
token = 0;
else
token = current_source + (row << source_bits);
}
public override string ToString ()
{
return Name + ": (" + Row + ")";
}
/// <summary>
/// Whether the Location is Null
/// </summary>
static public bool IsNull (Location l)
{
return l.token == 0;
}
public string Name {
get {
int index = token & source_mask;
if ((token == 0) || (index == 0))
return "Internal";
SourceFile file = (SourceFile) source_list [index - 1];
return file.Name;
}
}
public int Row {
get {
if (token == 0)
return 1;
return token >> source_bits;
}
}
public int File {
get {
return token & source_mask;
}
}
// The ISymbolDocumentWriter interface is used by the symbol writer to
// describe a single source file - for each source file there's exactly
// one corresponding ISymbolDocumentWriter instance.
//
// This class has an internal hash table mapping source document names
// to such ISymbolDocumentWriter instances - so there's exactly one
// instance per document.
//
// This property returns the ISymbolDocumentWriter instance which belongs
// to the location's source file.
//
// If we don't have a symbol writer, this property is always null.
public SourceFile SourceFile {
get {
int index = token & source_mask;
if (index == 0)
return null;
return (SourceFile) source_list [index - 1];
}
}
}
}
-14
View File
@@ -1,14 +0,0 @@
<configuration>
<startup>
<supportedRuntime version="v1.1.4322"/>
</startup>
<system.diagnostics>
<trace autoflush="true" indentsize="4">
<listeners>
<add name="compilerLogListener" type="System.Diagnostics.TextWriterTraceListener,System"
initializeData="mcs.log" />
<remove type="System.Diagnostics.DefaultTraceListener,System"/>
</listeners>
</trace>
</system.diagnostics>
</configuration>
-248
View File
@@ -1,248 +0,0 @@
//
// modifiers.cs: Modifier handling.
//
using System;
using System.Reflection;
namespace Mono.CSharp {
public class Modifiers {
//
// The ordering of the following 4 constants
// has been carefully done.
//
public const int PROTECTED = 0x0001;
public const int PUBLIC = 0x0002;
public const int PRIVATE = 0x0004;
public const int INTERNAL = 0x0008;
public const int NEW = 0x0010;
public const int ABSTRACT = 0x0020;
public const int SEALED = 0x0040;
public const int STATIC = 0x0080;
public const int READONLY = 0x0100;
public const int VIRTUAL = 0x0200;
public const int OVERRIDE = 0x0400;
public const int EXTERN = 0x0800;
public const int VOLATILE = 0x1000;
public const int UNSAFE = 0x2000;
public const int TOP = 0x2000;
//
// We use this internally to flag that the method contains an iterator
//
public const int METHOD_YIELDS = 0x8000;
public const int METHOD_GENERIC = 0x10000;
public const int Accessibility =
PUBLIC | PROTECTED | INTERNAL | PRIVATE;
public const int AllowedExplicitImplFlags =
UNSAFE | EXTERN;
static public string Name (int i)
{
string s = "";
switch (i) {
case Modifiers.NEW:
s = "new"; break;
case Modifiers.PUBLIC:
s = "public"; break;
case Modifiers.PROTECTED:
s = "protected"; break;
case Modifiers.INTERNAL:
s = "internal"; break;
case Modifiers.PRIVATE:
s = "private"; break;
case Modifiers.ABSTRACT:
s = "abstract"; break;
case Modifiers.SEALED:
s = "sealed"; break;
case Modifiers.STATIC:
s = "static"; break;
case Modifiers.READONLY:
s = "readonly"; break;
case Modifiers.VIRTUAL:
s = "virtual"; break;
case Modifiers.OVERRIDE:
s = "override"; break;
case Modifiers.EXTERN:
s = "extern"; break;
case Modifiers.VOLATILE:
s = "volatile"; break;
case Modifiers.UNSAFE:
s = "unsafe"; break;
}
return s;
}
public static TypeAttributes TypeAttr (int mod_flags, bool is_toplevel)
{
TypeAttributes t = 0;
if (is_toplevel){
if ((mod_flags & PUBLIC) != 0)
t |= TypeAttributes.Public;
if ((mod_flags & PRIVATE) != 0)
t |= TypeAttributes.NotPublic;
} else {
if ((mod_flags & PUBLIC) != 0)
t |= TypeAttributes.NestedPublic;
if ((mod_flags & PRIVATE) != 0)
t |= TypeAttributes.NestedPrivate;
if ((mod_flags & PROTECTED) != 0 && (mod_flags & INTERNAL) != 0)
t |= TypeAttributes.NestedFamORAssem;
if ((mod_flags & PROTECTED) != 0)
t |= TypeAttributes.NestedFamily;
if ((mod_flags & INTERNAL) != 0)
t |= TypeAttributes.NestedAssembly;
}
if ((mod_flags & SEALED) != 0)
t |= TypeAttributes.Sealed;
if ((mod_flags & ABSTRACT) != 0)
t |= TypeAttributes.Abstract;
return t;
}
public static TypeAttributes TypeAttr (int mod_flags, TypeContainer caller)
{
TypeAttributes t = TypeAttr (mod_flags, caller.IsTopLevel);
// If we do not have static constructors, static methods
// can be invoked without initializing the type.
if (!caller.UserDefinedStaticConstructor &&
(caller.Kind != Kind.Interface))
t |= TypeAttributes.BeforeFieldInit;
return t;
}
public static FieldAttributes FieldAttr (int mod_flags)
{
FieldAttributes fa = 0;
if ((mod_flags & PUBLIC) != 0)
fa |= FieldAttributes.Public;
if ((mod_flags & PRIVATE) != 0)
fa |= FieldAttributes.Private;
if ((mod_flags & PROTECTED) != 0){
if ((mod_flags & INTERNAL) != 0)
fa |= FieldAttributes.FamORAssem;
else
fa |= FieldAttributes.Family;
} else {
if ((mod_flags & INTERNAL) != 0)
fa |= FieldAttributes.Assembly;
}
if ((mod_flags & STATIC) != 0)
fa |= FieldAttributes.Static;
if ((mod_flags & READONLY) != 0)
fa |= FieldAttributes.InitOnly;
return fa;
}
public static MethodAttributes MethodAttr (int mod_flags)
{
MethodAttributes ma = MethodAttributes.HideBySig;
if ((mod_flags & PUBLIC) != 0)
ma |= MethodAttributes.Public;
if ((mod_flags & PRIVATE) != 0)
ma |= MethodAttributes.Private;
if ((mod_flags & PROTECTED) != 0){
if ((mod_flags & INTERNAL) != 0)
ma |= MethodAttributes.FamORAssem;
else
ma |= MethodAttributes.Family;
} else {
if ((mod_flags & INTERNAL) != 0)
ma |= MethodAttributes.Assembly;
}
if ((mod_flags & STATIC) != 0)
ma |= MethodAttributes.Static;
if ((mod_flags & ABSTRACT) != 0){
ma |= MethodAttributes.Abstract | MethodAttributes.Virtual;
}
if ((mod_flags & SEALED) != 0)
ma |= MethodAttributes.Final;
if ((mod_flags & VIRTUAL) != 0)
ma |= MethodAttributes.Virtual;
if ((mod_flags & OVERRIDE) != 0)
ma |= MethodAttributes.Virtual;
else {
if ((ma & MethodAttributes.Virtual) != 0)
ma |= MethodAttributes.NewSlot;
}
return ma;
}
// <summary>
// Checks the object @mod modifiers to be in @allowed.
// Returns the new mask. Side effect: reports any
// incorrect attributes.
// </summary>
public static int Check (int allowed, int mod, int def_access, Location l)
{
int invalid_flags = (~allowed) & mod;
int i;
if (invalid_flags == 0){
int a = mod;
if ((mod & Modifiers.UNSAFE) != 0){
if (!RootContext.Unsafe){
Report.Error (227, l,
"Unsafe code requires the -unsafe command " +
"line option to be specified");
}
}
//
// If no accessibility bits provided
// then provide the defaults.
//
if ((mod & Accessibility) == 0){
mod |= def_access;
return mod;
}
//
// Make sure that no conflicting accessibility
// bits have been set. Protected+Internal is
// allowed, that is why they are placed on bits
// 1 and 4 (so the shift 3 basically merges them)
//
a &= 15;
a |= (a >> 3);
a = ((a & 2) >> 1) + (a & 5);
a = ((a & 4) >> 2) + (a & 3);
if (a > 1)
Report.Error (107, l, "More than one protection modifier specified");
return mod;
}
for (i = 1; i <= TOP; i <<= 1){
if ((i & invalid_flags) == 0)
continue;
Error_InvalidModifier (l, Name (i));
}
return allowed & mod;
}
public static void Error_InvalidModifier (Location l, string name)
{
Report.Error (106, l, "the modifier " + name + " is not valid for this item");
}
}
}
-643
View File
@@ -1,643 +0,0 @@
//
// namespace.cs: Tracks namespaces
//
// Author:
// Miguel de Icaza ([email protected])
//
// (C) 2001 Ximian, Inc.
//
using System;
using System.Collections;
namespace Mono.CSharp {
/// <summary>
/// Keeps track of the namespaces defined in the C# code.
/// </summary>
public class Namespace : IAlias {
static ArrayList all_namespaces = new ArrayList ();
static Hashtable namespaces_map = new Hashtable ();
Namespace parent;
string fullname;
ArrayList entries;
Hashtable namespaces;
Hashtable defined_names;
/// <summary>
/// Constructor Takes the current namespace and the
/// name. This is bootstrapped with parent == null
/// and name = ""
/// </summary>
public Namespace (Namespace parent, string name)
{
this.parent = parent;
string pname = parent != null ? parent.Name : "";
if (pname == "")
fullname = name;
else
fullname = parent.Name + "." + name;
entries = new ArrayList ();
namespaces = new Hashtable ();
defined_names = new Hashtable ();
all_namespaces.Add (this);
if (namespaces_map.Contains (fullname))
return;
namespaces_map [fullname] = true;
}
public static bool IsNamespace (string name)
{
return namespaces_map [name] != null;
}
public static Namespace Root = new Namespace (null, "");
public Namespace GetNamespace (string name, bool create)
{
int pos = name.IndexOf ('.');
Namespace ns;
string first;
if (pos >= 0)
first = name.Substring (0, pos);
else
first = name;
ns = (Namespace) namespaces [first];
if (ns == null) {
if (!create)
return null;
ns = new Namespace (this, first);
namespaces.Add (first, ns);
}
if (pos >= 0)
ns = ns.GetNamespace (name.Substring (pos + 1), create);
return ns;
}
public static Namespace LookupNamespace (string name, bool create)
{
return Root.GetNamespace (name, create);
}
public IAlias Lookup (DeclSpace ds, string name, Location loc)
{
IAlias o = Lookup (name);
Type t;
DeclSpace tdecl = o as DeclSpace;
if (tdecl != null) {
t = tdecl.DefineType ();
if ((ds == null) || ds.CheckAccessLevel (t))
return new TypeExpression (t, loc);
}
Namespace ns = GetNamespace (name, false);
if (ns != null)
return ns;
t = TypeManager.LookupType (DeclSpace.MakeFQN (fullname, name));
if ((t == null) || ((ds != null) && !ds.CheckAccessLevel (t)))
return null;
return new TypeExpression (t, loc);
}
public void AddNamespaceEntry (NamespaceEntry entry)
{
entries.Add (entry);
}
public void DefineName (string name, IAlias o)
{
defined_names.Add (name, o);
}
public IAlias Lookup (string name)
{
return (IAlias) defined_names [name];
}
static public ArrayList UserDefinedNamespaces {
get {
return all_namespaces;
}
}
/// <summary>
/// The qualified name of the current namespace
/// </summary>
public string Name {
get {
return fullname;
}
}
/// <summary>
/// The parent of this namespace, used by the parser to "Pop"
/// the current namespace declaration
/// </summary>
public Namespace Parent {
get {
return parent;
}
}
public static void DefineNamespaces (SymbolWriter symwriter)
{
foreach (Namespace ns in all_namespaces) {
foreach (NamespaceEntry entry in ns.entries)
entry.DefineNamespace (symwriter);
}
}
/// <summary>
/// Used to validate that all the using clauses are correct
/// after we are finished parsing all the files.
/// </summary>
public static void VerifyUsing ()
{
foreach (Namespace ns in all_namespaces) {
foreach (NamespaceEntry entry in ns.entries)
entry.VerifyUsing ();
}
}
public override string ToString ()
{
if (this == Root)
return "Namespace (<root>)";
else
return String.Format ("Namespace ({0})", Name);
}
bool IAlias.IsType {
get { return false; }
}
TypeExpr IAlias.Type {
get {
throw new InvalidOperationException ();
}
}
}
public class NamespaceEntry
{
Namespace ns;
NamespaceEntry parent, implicit_parent;
SourceFile file;
int symfile_id;
Hashtable aliases;
ArrayList using_clauses;
public bool DeclarationFound = false;
//
// This class holds the location where a using definition is
// done, and whether it has been used by the program or not.
//
// We use this to flag using clauses for namespaces that do not
// exist.
//
public class UsingEntry {
public readonly string Name;
public readonly NamespaceEntry NamespaceEntry;
public readonly Location Location;
public UsingEntry (NamespaceEntry entry, string name, Location loc)
{
Name = name;
NamespaceEntry = entry;
Location = loc;
}
Namespace resolved_ns;
public Namespace Resolve ()
{
if (resolved_ns != null)
return resolved_ns;
Namespace curr_ns = NamespaceEntry.NS;
while ((curr_ns != null) && (resolved_ns == null)) {
resolved_ns = curr_ns.GetNamespace (Name, false);
if (resolved_ns == null)
curr_ns = curr_ns.Parent;
}
return resolved_ns;
}
}
public class AliasEntry {
public readonly string Name;
public readonly MemberName Alias;
public readonly NamespaceEntry NamespaceEntry;
public readonly Location Location;
public AliasEntry (NamespaceEntry entry, string name, MemberName alias, Location loc)
{
Name = name;
Alias = alias;
NamespaceEntry = entry;
Location = loc;
}
IAlias resolved;
public IAlias Resolve ()
{
if (resolved != null)
return resolved;
//
// GENERICS: Cope with the expression and not with the string
// this will fail with `using A = Stack<int>'
//
string alias = Alias.GetTypeName ();
// According to section 16.3.1, the namespace-or-type-name is resolved
// as if the immediately containing namespace body has no using-directives.
resolved = NamespaceEntry.Lookup (
null, alias, Alias.CountTypeArguments, true, Location);
NamespaceEntry curr_ns = NamespaceEntry.Parent;
while ((curr_ns != null) && (resolved == null)) {
resolved = curr_ns.Lookup (
null, alias, Alias.CountTypeArguments,
false, Location);
if (resolved == null)
curr_ns = curr_ns.Parent;
}
if (resolved == null)
return null;
if (resolved.IsType)
resolved = new TypeAliasExpression (
resolved.Type, Alias.TypeArguments, Location);
return resolved;
}
}
public NamespaceEntry (NamespaceEntry parent, SourceFile file, string name, Location loc)
: this (parent, file, name, false, loc)
{ }
protected NamespaceEntry (NamespaceEntry parent, SourceFile file, string name, bool is_implicit, Location loc)
{
this.parent = parent;
this.file = file;
this.IsImplicit = is_implicit;
this.ID = ++next_id;
if (!is_implicit && (parent != null))
ns = parent.NS.GetNamespace (name, true);
else if (name != null)
ns = Namespace.LookupNamespace (name, true);
else
ns = Namespace.Root;
ns.AddNamespaceEntry (this);
if ((parent != null) && (parent.NS != ns.Parent))
implicit_parent = new NamespaceEntry (parent, file, ns.Parent.Name, true, loc);
else
implicit_parent = parent;
this.FullName = ns.Name;
}
static int next_id = 0;
public readonly string FullName;
public readonly int ID;
public readonly bool IsImplicit;
public Namespace NS {
get {
return ns;
}
}
public NamespaceEntry Parent {
get {
return parent;
}
}
public NamespaceEntry ImplicitParent {
get {
return implicit_parent;
}
}
public void DefineName (string name, IAlias o)
{
ns.DefineName (name, o);
}
/// <summary>
/// Records a new namespace for resolving name references
/// </summary>
public void Using (string ns, Location loc)
{
if (DeclarationFound){
Report.Error (1529, loc, "A using clause must precede all other namespace elements");
return;
}
if (ns == FullName)
return;
if (using_clauses == null)
using_clauses = new ArrayList ();
foreach (UsingEntry old_entry in using_clauses) {
if (old_entry.Name == ns) {
if (RootContext.WarningLevel >= 3)
Report.Warning (105, loc, "The using directive for '{0}' appeared previously in this namespace", ns);
return;
}
}
UsingEntry ue = new UsingEntry (this, ns, loc);
using_clauses.Add (ue);
}
public void UsingAlias (string name, MemberName alias, Location loc)
{
if (DeclarationFound){
Report.Error (1529, loc, "A using clause must precede all other namespace elements");
return;
}
if (aliases == null)
aliases = new Hashtable ();
if (aliases.Contains (name)){
Report.Error (1537, loc, "The using alias `" + name +
"' appeared previously in this namespace");
return;
}
aliases [name] = new AliasEntry (this, name, alias, loc);
}
protected AliasEntry GetAliasEntry (string alias)
{
AliasEntry entry = null;
if (aliases != null)
entry = (AliasEntry) aliases [alias];
if (entry == null && Parent != null)
entry = Parent.GetAliasEntry (alias);
return entry;
}
public IAlias LookupAlias (string alias)
{
AliasEntry entry = GetAliasEntry (alias);
if (entry == null)
return null;
return entry.Resolve ();
}
public IAlias Lookup (DeclSpace ds, string name, int num_type_params,
bool ignore_using, Location loc)
{
IAlias o;
Namespace ns;
//
// If name is of the form `N.I', first lookup `N', then search a member `I' in it.
//
int pos = name.IndexOf ('.');
if (pos >= 0) {
string first = name.Substring (0, pos);
string last = name.Substring (pos + 1);
o = Lookup (ds, first, 0, ignore_using, loc);
if (o == null)
return null;
ns = o as Namespace;
if (ns != null) {
o = ns.Lookup (ds, last, loc);
return o;
}
Type nested = TypeManager.LookupType (o.Name + "." + last);
if ((nested == null) || ((ds != null) && !ds.CheckAccessLevel (nested)))
return null;
return new TypeExpression (nested, loc);
}
//
// Check whether it's a namespace.
//
o = NS.Lookup (ds, name, loc);
if (o != null)
return o;
if (ignore_using)
return null;
//
// Check aliases.
//
AliasEntry entry = GetAliasEntry (name);
if (entry != null) {
IAlias alias = entry.Resolve ();
if (alias != null)
return alias;
}
if (name.IndexOf ('.') > 0)
return null;
//
// Check using entries.
//
IAlias t = null, match = null;
foreach (Namespace using_ns in GetUsingTable ()) {
match = using_ns.Lookup (ds, name, loc);
if ((match != null) && match.IsType){
if (t != null) {
DeclSpace.Error_AmbiguousTypeReference (loc, name, t.Name, match.Name);
return null;
} else {
t = match;
}
}
}
return t;
}
// Our cached computation.
Namespace [] namespace_using_table;
public Namespace[] GetUsingTable ()
{
if (namespace_using_table != null)
return namespace_using_table;
if (using_clauses == null)
return new Namespace [0];
ArrayList list = new ArrayList (using_clauses.Count);
foreach (UsingEntry ue in using_clauses) {
Namespace using_ns = ue.Resolve ();
if (using_ns == null)
continue;
list.Add (using_ns);
}
namespace_using_table = new Namespace [list.Count];
list.CopyTo (namespace_using_table, 0);
return namespace_using_table;
}
public void DefineNamespace (SymbolWriter symwriter)
{
if (symfile_id != 0)
return;
if (parent != null)
parent.DefineNamespace (symwriter);
string[] using_list;
if (using_clauses != null) {
using_list = new string [using_clauses.Count];
for (int i = 0; i < using_clauses.Count; i++)
using_list [i] = ((UsingEntry) using_clauses [i]).Name;
} else {
using_list = new string [0];
}
int parent_id = parent != null ? parent.symfile_id : 0;
if (file.SourceFileEntry == null)
return;
symfile_id = symwriter.DefineNamespace (
ns.Name, file.SourceFileEntry, using_list, parent_id);
}
public int SymbolFileID {
get {
return symfile_id;
}
}
static void Msgtry (string s)
{
Console.WriteLine (" Try using -r:" + s);
}
protected void error246 (Location loc, string name)
{
if (TypeManager.LookupType (name) != null)
Report.Error (138, loc, "The using keyword only lets you specify a namespace, " +
"`" + name + "' is a class not a namespace.");
else {
Report.Error (246, loc, "The namespace `" + name +
"' can not be found (missing assembly reference?)");
switch (name){
case "Gtk": case "GtkSharp":
Msgtry ("gtk-sharp");
break;
case "Gdk": case "GdkSharp":
Msgtry ("gdk-sharp");
break;
case "Glade": case "GladeSharp":
Msgtry ("glade-sharp");
break;
case "System.Drawing":
Msgtry ("System.Drawing");
break;
case "System.Web.Services":
Msgtry ("System.Web.Services");
break;
case "System.Web":
Msgtry ("System.Web");
break;
case "System.Data":
Msgtry ("System.Data");
break;
case "System.Windows.Forms":
Msgtry ("System.Windows.Forms");
break;
}
}
}
/// <summary>
/// Used to validate that all the using clauses are correct
/// after we are finished parsing all the files.
/// </summary>
public void VerifyUsing ()
{
TypeContainer dummy = new RootTypes ();
EmitContext ec = new EmitContext (
dummy, Location.Null, null, null, 0, false);
if (using_clauses != null){
foreach (UsingEntry ue in using_clauses){
if (ue.Resolve () != null)
continue;
error246 (ue.Location, ue.Name);
}
}
if (aliases != null){
foreach (DictionaryEntry de in aliases){
AliasEntry entry = (AliasEntry) de.Value;
IAlias alias = entry.Resolve ();
if (alias != null) {
if (alias.IsType)
alias.Type.ResolveType (ec);
continue;
}
error246 (entry.Location, entry.Alias.GetPartialName ());
}
}
}
public override string ToString ()
{
if (NS == Namespace.Root)
return "NamespaceEntry (<root>)";
else
return String.Format ("NamespaceEntry ({0},{1},{2})", FullName, IsImplicit, ID);
}
}
}
-217
View File
@@ -1,217 +0,0 @@
#else
bla bla bla
//
// This code is more conformant to the spec (it follows it step by step),
// but it has not been tested yet, and there is nothing here that is not
// caught by the above code. But it might be a better foundation to improve
// on in the future
//
public ResolveTypeMemberAccess (EmitContext ec, Expression member_lookup,
Expression left, Location loc)
{
if (member_lookup is TypeExpr){
member_lookup.Resolve (ec);
return member_lookup;
}
if (member_lookup is MethodGroupExpr){
if (!mg.RemoveStaticMethods ()){
SimpleName.Error120 (loc, mg.Methods [0].Name);
return null;
}
return member_lookup;
}
if (member_lookup is PropertyExpr){
PropertyExpr pe = (PropertyExpr) member_lookup;
if (!pe.IsStatic){
SimpleName.Error120 (loc, pe.PropertyInfo.Name);
return null;
}
return pe;
}
if (member_lookup is FieldExpr){
FieldExpr fe = (FieldExpr) member_lookup;
FieldInfo fi = fe.FieldInfo;
if (fi is FieldBuilder) {
Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
if (c != null) {
object o = c.LookupConstantValue (ec);
return Constantify (o, fi.FieldType);
}
}
if (fi.IsLiteral) {
Type t = fi.FieldType;
Type decl_type = fi.DeclaringType;
object o;
if (fi is FieldBuilder)
o = TypeManager.GetValue ((FieldBuilder) fi);
else
o = fi.GetValue (fi);
if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
Expression enum_member = MemberLookup (
ec, decl_type, "value__", loc);
Enum en = TypeManager.LookupEnum (decl_type);
Constant c;
if (en != null)
c = Constantify (o, en.UnderlyingType);
else
c = Constantify (o, enum_member.Type);
return new EnumConstant (c, decl_type);
}
Expression exp = Constantify (o, t);
return exp;
}
if (!fe.FieldInfo.IsStatic){
error176 (loc, fe.FieldInfo.Name);
return null;
}
return member_lookup;
}
if (member_lookup is EventExpr){
EventExpr ee = (EventExpr) member_lookup;
//
// If the event is local to this class, we transform ourselves into
// a FieldExpr
//
Expression ml = MemberLookup (
ec, ec.TypeContainer.TypeBuilder, ee.EventInfo.Name,
MemberTypes.Event, AllBindingFlags, loc);
if (ml != null) {
MemberInfo mi = ec.TypeContainer.GetFieldFromEvent ((EventExpr) ml);
ml = ExprClassFromMemberInfo (ec, mi, loc);
if (ml == null) {
Report.Error (-200, loc, "Internal error!!");
return null;
}
return ResolveMemberAccess (ec, ml, left, loc);
}
if (!ee.IsStatic) {
SimpleName.Error120 (loc, ee.EventInfo.Name);
return null;
}
return ee;
}
Console.WriteLine ("Left is: " + left);
Report.Error (-100, loc, "Support for [" + member_lookup + "] is not present yet");
Environment.Exit (0);
return null;
}
public ResolveInstanceMemberAccess (EmitContext ec, Expression member_lookup,
Expression left, Location loc)
{
if (member_lookup is MethodGroupExpr){
//
// Instance.MethodGroup
//
if (!mg.RemoveStaticMethods ()){
error176 (loc, mg.Methods [0].Name);
return null;
}
mg.InstanceExpression = left;
return member_lookup;
}
if (member_lookup is PropertyExpr){
PropertyExpr pe = (PropertyExpr) member_lookup;
if (pe.IsStatic){
error176 (loc, pe.PropertyInfo.Name);
return null;
}
Console.WriteLine ("HERE *************");
pe.InstanceExpression = left;
return pe;
}
Type left_type = left.type;
if (left_type.IsValueType){
} else {
}
}
public override Expression DoResolve (EmitContext ec)
{
//
// We are the sole users of ResolveWithSimpleName (ie, the only
// ones that can cope with it
//
expr = expr.ResolveWithSimpleName (ec);
if (expr == null)
return null;
if (expr is SimpleName){
SimpleName child_expr = (SimpleName) expr;
expr = new SimpleName (child_expr.Name + "." + Identifier, loc);
return expr.ResolveWithSimpleName (ec);
}
//
// Handle enums here when they are in transit.
// Note that we cannot afford to hit MemberLookup in this case because
// it will fail to find any members at all (Why?)
//
Type expr_type = expr.Type;
if (expr_type.IsSubclassOf (TypeManager.enum_type)) {
Enum en = TypeManager.LookupEnum (expr_type);
if (en != null) {
object value = en.LookupEnumValue (ec, Identifier, loc);
if (value == null)
return null;
Constant c = Constantify (value, en.UnderlyingType);
return new EnumConstant (c, expr_type);
}
}
member_lookup = MemberLookup (ec, expr.Type, Identifier, loc);
if (member_lookup == null)
return null;
if (expr is TypeExpr)
return ResolveTypeMemberAccess (ec, member_lookup, expr, loc);
else
return ResolveInstanceMemberAccess (ec, member_lookup, expr, loc);
}
#endif
-626
View File
@@ -1,626 +0,0 @@
//
// parameter.cs: Parameter definition.
//
// Author: Miguel de Icaza ([email protected])
//
// Licensed under the terms of the GNU GPL
//
// (C) 2001 Ximian, Inc (http://www.ximian.com)
//
//
//
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Collections;
namespace Mono.CSharp {
/// <summary>
/// Abstract Base class for parameters of a method.
/// </summary>
public abstract class ParameterBase : Attributable {
protected ParameterBuilder builder;
public ParameterBase (Attributes attrs)
: base (attrs)
{
}
public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
{
if (a.Type == TypeManager.marshal_as_attr_type) {
UnmanagedMarshal marshal = a.GetMarshal (this);
if (marshal != null) {
builder.SetMarshal (marshal);
}
return;
}
if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
a.Error_InvalidSecurityParent ();
return;
}
builder.SetCustomAttribute (cb);
}
public override bool IsClsCompliaceRequired(DeclSpace ds)
{
return false;
}
}
/// <summary>
/// Class for applying custom attributes on the return type
/// </summary>
public class ReturnParameter: ParameterBase {
public ReturnParameter (MethodBuilder mb, Location location):
base (null)
{
try {
builder = mb.DefineParameter (0, ParameterAttributes.None, "");
}
catch (ArgumentOutOfRangeException) {
Report.Warning (-28, location, "The Microsoft .NET Runtime 1.x does not permit setting custom attributes on the return type");
}
}
public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
{
// This occurs after Warning -28
if (builder == null)
return;
base.ApplyAttributeBuilder (a, cb);
}
public override AttributeTargets AttributeTargets {
get {
return AttributeTargets.ReturnValue;
}
}
/// <summary>
/// Is never called
/// </summary>
public override string[] ValidAttributeTargets {
get {
return null;
}
}
}
/// <summary>
/// Class for applying custom attributes on the implicit parameter type
/// of the 'set' method in properties, and the 'add' and 'remove' methods in events.
/// </summary>
public class ImplicitParameter: ParameterBase {
public ImplicitParameter (MethodBuilder mb):
base (null)
{
builder = mb.DefineParameter (1, ParameterAttributes.None, "");
}
public override AttributeTargets AttributeTargets {
get {
return AttributeTargets.Parameter;
}
}
/// <summary>
/// Is never called
/// </summary>
public override string[] ValidAttributeTargets {
get {
return null;
}
}
}
/// <summary>
/// Represents a single method parameter
/// </summary>
//TODO: Add location member to this or base class for better error location and all methods simplification.
public class Parameter : ParameterBase {
[Flags]
public enum Modifier : byte {
NONE = 0,
REF = 1,
OUT = 2,
PARAMS = 4,
// This is a flag which says that it's either REF or OUT.
ISBYREF = 8,
ARGLIST = 16
}
static string[] attribute_targets = new string [] { "param" };
public Expression TypeName;
public readonly Modifier ModFlags;
public readonly string Name;
GenericConstraints constraints;
Type parameter_type;
public Parameter (Expression type, string name, Modifier mod, Attributes attrs)
: base (attrs)
{
Name = name;
ModFlags = mod;
TypeName = type;
}
public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
{
if (a.Type == TypeManager.param_array_type) {
Report.Error (674, a.Location, "Do not use 'System.ParamArrayAttribute'. Use the 'params' keyword instead");
return;
}
base.ApplyAttributeBuilder (a, cb);
}
// <summary>
// Resolve is used in method definitions
// </summary>
public bool Resolve (EmitContext ec, Location l)
{
TypeExpr texpr = TypeName.ResolveAsTypeTerminal (ec, false);
if (texpr == null)
return false;
TypeParameterExpr tparam = texpr as TypeParameterExpr;
if (tparam != null)
constraints = tparam.TypeParameter.Constraints;
parameter_type = texpr.ResolveType (ec);
if (parameter_type.IsAbstract && parameter_type.IsSealed) {
Report.Error (721, l, "'{0}': static types cannot be used as parameters", GetSignatureForError ());
return false;
}
if (parameter_type == TypeManager.void_type){
Report.Error (1536, l, "`void' parameter is not permitted");
return false;
}
if ((ModFlags & Parameter.Modifier.ISBYREF) != 0){
if (parameter_type == TypeManager.typed_reference_type ||
parameter_type == TypeManager.arg_iterator_type){
Report.Error (1601, l,
"out or ref parameter can not be of type TypedReference or ArgIterator");
return false;
}
}
return parameter_type != null;
}
public Type ExternalType ()
{
if ((ModFlags & Parameter.Modifier.ISBYREF) != 0)
return TypeManager.GetReferenceType (parameter_type);
return parameter_type;
}
public Type ParameterType {
get {
return parameter_type;
}
}
public GenericConstraints GenericConstraints {
get {
return constraints;
}
}
public ParameterAttributes Attributes {
get {
int flags = ((int) ModFlags) & ~((int) Parameter.Modifier.ISBYREF);
switch ((Modifier) flags) {
case Modifier.NONE:
return ParameterAttributes.None;
case Modifier.REF:
return ParameterAttributes.None;
case Modifier.OUT:
return ParameterAttributes.Out;
case Modifier.PARAMS:
return 0;
}
return ParameterAttributes.None;
}
}
public override AttributeTargets AttributeTargets {
get {
return AttributeTargets.Parameter;
}
}
/// <summary>
/// Returns the signature for this parameter evaluating it on the
/// @tc context
/// </summary>
public string GetSignature (EmitContext ec, Location loc)
{
if (parameter_type == null){
if (!Resolve (ec, loc))
return null;
}
return ExternalType ().FullName;
}
public string GetSignatureForError ()
{
string typeName;
if (parameter_type != null)
typeName = TypeManager.CSharpName (parameter_type);
else if (TypeName.Type != null)
typeName = TypeManager.CSharpName (TypeName.Type);
else
typeName = TypeName.ToString ();
switch (ModFlags & unchecked (~Modifier.ISBYREF)) {
case Modifier.OUT:
return "out " + typeName;
case Modifier.PARAMS:
return "params " + typeName;
case Modifier.REF:
return "ref " + typeName;
}
return typeName;
}
public void DefineParameter (EmitContext ec, MethodBuilder mb, ConstructorBuilder cb, int index, Location loc)
{
ParameterAttributes par_attr = Attributes;
if (mb == null)
builder = cb.DefineParameter (index, par_attr, Name);
else
builder = mb.DefineParameter (index, par_attr, Name);
if (OptAttributes != null) {
OptAttributes.Emit (ec, this);
if (par_attr == ParameterAttributes.Out){
if (OptAttributes.Contains (TypeManager.in_attribute_type, ec))
Report.Error (36, loc, "Can not use [In] attribute on out parameter");
}
}
}
public override string[] ValidAttributeTargets {
get {
return attribute_targets;
}
}
}
/// <summary>
/// Represents the methods parameters
/// </summary>
public class Parameters {
public Parameter [] FixedParameters;
public readonly Parameter ArrayParameter;
public readonly bool HasArglist;
string signature;
Type [] types;
Location loc;
static Parameters empty_parameters;
public Parameters (Parameter [] fixed_parameters, Parameter array_parameter, Location l)
{
FixedParameters = fixed_parameters;
ArrayParameter = array_parameter;
loc = l;
}
public Parameters (Parameter [] fixed_parameters, bool has_arglist, Location l)
{
FixedParameters = fixed_parameters;
HasArglist = has_arglist;
loc = l;
}
/// <summary>
/// This is used to reuse a set of empty parameters, because they
/// are common
/// </summary>
public static Parameters EmptyReadOnlyParameters {
get {
if (empty_parameters == null)
empty_parameters = new Parameters (null, null, Location.Null);
return empty_parameters;
}
}
public bool Empty {
get {
return (FixedParameters == null) && (ArrayParameter == null);
}
}
public void ComputeSignature (EmitContext ec)
{
signature = "";
if (FixedParameters != null){
for (int i = 0; i < FixedParameters.Length; i++){
Parameter par = FixedParameters [i];
signature += par.GetSignature (ec, loc);
}
}
//
// Note: as per the spec, the `params' arguments (ArrayParameter)
// are not used in the signature computation for a method
//
}
void Error_DuplicateParameterName (string name)
{
Report.Error (
100, loc, "The parameter name `" + name + "' is a duplicate");
}
public bool VerifyArgs ()
{
int count;
int i, j;
if (FixedParameters == null)
return true;
count = FixedParameters.Length;
string array_par_name = ArrayParameter != null ? ArrayParameter.Name : null;
for (i = 0; i < count; i++){
string base_name = FixedParameters [i].Name;
for (j = i + 1; j < count; j++){
if (base_name != FixedParameters [j].Name)
continue;
Error_DuplicateParameterName (base_name);
return false;
}
if (base_name == array_par_name){
Error_DuplicateParameterName (base_name);
return false;
}
}
return true;
}
/// <summary>
/// Returns the signature of the Parameters evaluated in
/// the @ec EmitContext
/// </summary>
public string GetSignature (EmitContext ec)
{
if (signature == null){
VerifyArgs ();
ComputeSignature (ec);
}
return signature;
}
/// <summary>
/// Returns the paramenter information based on the name
/// </summary>
public Parameter GetParameterByName (string name, out int idx)
{
idx = 0;
int i = 0;
if (FixedParameters != null){
foreach (Parameter par in FixedParameters){
if (par.Name == name){
idx = i;
return par;
}
i++;
}
}
if (ArrayParameter != null){
if (name == ArrayParameter.Name){
idx = i;
return ArrayParameter;
}
}
return null;
}
public Parameter GetParameterByName (string name)
{
int idx;
return GetParameterByName (name, out idx);
}
bool ComputeParameterTypes (EmitContext ec)
{
int extra = (ArrayParameter != null) ? 1 : 0;
int i = 0;
int pc;
if (FixedParameters == null)
pc = extra;
else
pc = extra + FixedParameters.Length;
types = new Type [pc];
if (!VerifyArgs ()){
FixedParameters = null;
return false;
}
bool failed = false;
if (FixedParameters != null){
foreach (Parameter p in FixedParameters){
Type t = null;
if (p.Resolve (ec, loc))
t = p.ExternalType ();
else
failed = true;
types [i] = t;
i++;
}
}
if (extra > 0){
if (ArrayParameter.Resolve (ec, loc))
types [i] = ArrayParameter.ExternalType ();
else
failed = true;
}
if (failed){
types = null;
return false;
}
return true;
}
//
// This variant is used by Delegates, because they need to
// resolve/define names, instead of the plain LookupType
//
public bool ComputeAndDefineParameterTypes (EmitContext ec)
{
bool old_type_resolving = ec.ResolvingTypeTree;
ec.ResolvingTypeTree = true;
bool retval = ComputeParameterTypes (ec);
ec.ResolvingTypeTree = old_type_resolving;
return retval;
}
/// <summary>
/// Returns the argument types as an array
/// </summary>
static Type [] no_types = new Type [0];
public Type [] GetParameterInfo (EmitContext ec)
{
if (types != null)
return types;
if (FixedParameters == null && ArrayParameter == null)
return no_types;
if (ComputeParameterTypes (ec) == false){
types = null;
return null;
}
return types;
}
/// <summary>
/// Returns the type of a given parameter, and stores in the `is_out'
/// boolean whether this is an out or ref parameter.
///
/// Note that the returned type will not contain any dereference in this
/// case (ie, you get "int" for a ref int instead of "int&"
/// </summary>
public Type GetParameterInfo (EmitContext ec, int idx, out Parameter.Modifier mod)
{
mod = Parameter.Modifier.NONE;
if (!VerifyArgs ()){
FixedParameters = null;
return null;
}
if (FixedParameters == null && ArrayParameter == null)
return null;
if (types == null)
if (ComputeParameterTypes (ec) == false)
return null;
//
// If this is a request for the variable lenght arg.
//
int array_idx = (FixedParameters != null ? FixedParameters.Length : 0);
if (idx == array_idx)
return types [idx];
//
// Otherwise, it is a fixed parameter
//
Parameter p = FixedParameters [idx];
mod = p.ModFlags;
if ((mod & (Parameter.Modifier.REF | Parameter.Modifier.OUT)) != 0)
mod |= Parameter.Modifier.ISBYREF;
return p.ParameterType;
}
public CallingConventions GetCallingConvention ()
{
if (HasArglist)
return CallingConventions.VarArgs;
else
return CallingConventions.Standard;
}
//
// The method's attributes are passed in because we need to extract
// the "return:" attribute from there to apply on the return type
//
public void LabelParameters (EmitContext ec,
MethodBase builder,
Location loc) {
//
// Define each type attribute (in/out/ref) and
// the argument names.
//
int i = 0;
MethodBuilder mb = builder as MethodBuilder;
ConstructorBuilder cb = builder as ConstructorBuilder;
if (FixedParameters != null) {
for (i = 0; i < FixedParameters.Length; i++) {
FixedParameters [i].DefineParameter (ec, mb, cb, i + 1, loc);
}
}
if (ArrayParameter != null){
ParameterBuilder pb;
Parameter array_param = ArrayParameter;
if (mb == null)
pb = cb.DefineParameter (
i + 1, array_param.Attributes,
array_param.Name);
else
pb = mb.DefineParameter (
i + 1, array_param.Attributes,
array_param.Name);
CustomAttributeBuilder a = new CustomAttributeBuilder (
TypeManager.cons_param_array_attribute, new object [0]);
pb.SetCustomAttribute (a);
}
}
}
}
-166
View File
@@ -1,166 +0,0 @@
//
// System.CodeDOM CodeParameterCollection Class implementation
//
// Author:
// Miguel de Icaza ([email protected])
//
// (C) 2001 Ximian, Inc.
//
namespace Mono.CSharp {
using System.Collections;
using System;
public class ParameterCollection : IList, ICollection, IEnumerable {
ArrayList parameters;
//
// Constructors
//
public ParameterCollection ()
{
parameters = new ArrayList ();
}
//
// Properties
//
public int Count {
get {
return parameters.Count;
}
}
//
// Methods
//
public void Add (Parameter value)
{
parameters.Add (value);
}
public void AddRange (Parameter [] values)
{
foreach (Parameter ca in values)
parameters.Add (ca);
}
public void Clear ()
{
parameters.Clear ();
}
private class Enumerator : IEnumerator {
private ParameterCollection collection;
private int currentIndex = -1;
internal Enumerator (ParameterCollection collection)
{
this.collection = collection;
}
public object Current {
get {
if (currentIndex == collection.Count)
throw new InvalidOperationException ();
return collection [currentIndex];
}
}
public bool MoveNext ()
{
if (currentIndex > collection.Count)
throw new InvalidOperationException ();
return ++currentIndex < collection.Count;
}
public void Reset ()
{
currentIndex = -1;
}
}
public IEnumerator GetEnumerator ()
{
return new ParameterCollection.Enumerator (this);
}
//
// IList method implementations
//
public int Add (object value)
{
return parameters.Add (value);
}
public bool Contains (Object value)
{
return parameters.Contains (value);
}
public int IndexOf (Object value)
{
return parameters.IndexOf (value);
}
public void Insert (int index, Object value)
{
parameters [index] = value;
}
public object this[int index] {
get {
return parameters [index];
}
set {
parameters [index] = value;
}
}
public void Remove (object value)
{
parameters.Remove (value);
}
public void RemoveAt (int index)
{
parameters.RemoveAt (index);
}
//
// ICollection method implementations
//
public void CopyTo (Array array, int index)
{
parameters.CopyTo (array, index);
}
public object SyncRoot {
get {
return parameters.SyncRoot;
}
}
public bool IsReadOnly {
get {
return false;
}
}
public bool IsSynchronized {
get {
return parameters.IsSynchronized;
}
}
public bool IsFixedSize {
get {
return false;
}
}
}
}
-23
View File
@@ -1,23 +0,0 @@
namespace Compiler {
using System;
abstract public class Parser {
public string name;
public System.IO.Stream input;
public Parser (Mono.CSharp.Tree tree, string name, System.IO.Stream stream)
{
this.tree = tree;
this.name = name;
this.input = stream;
}
public string getName (){
return name;
}
abstract public int parse ();
}
}
-566
View File
@@ -1,566 +0,0 @@
//
// pending.cs: Pending method implementation
//
// Author:
// Miguel de Icaza ([email protected])
//
// Licensed under the terms of the GNU GPL
//
// (C) 2001, 2002 Ximian, Inc (http://www.ximian.com)
//
//
using System;
using System.Collections;
using System.Reflection;
using System.Reflection.Emit;
namespace Mono.CSharp {
struct TypeAndMethods {
public Type type;
public MethodInfo [] methods;
//
// Whether it is optional, this is used to allow the explicit/implicit
// implementation when a parent class already implements an interface.
//
// For example:
//
// class X : IA { } class Y : X, IA { IA.Explicit (); }
//
public bool optional;
// Far from ideal, but we want to avoid creating a copy
// of methods above.
public Type [][] args;
//
// This flag on the method says `We found a match, but
// because it was private, we could not use the match
//
public bool [] found;
// If a method is defined here, then we always need to
// create a proxy for it. This is used when implementing
// an interface's indexer with a different IndexerName.
public MethodInfo [] need_proxy;
//
// The name of the indexer (if it exists), precompute set/get, because
// they would be recomputed many times inside a loop later on.
//
public string set_indexer_name;
public string get_indexer_name;
}
public class PendingImplementation {
/// <summary>
/// The container for this PendingImplementation
/// </summary>
TypeContainer container;
/// <summary>
/// This filter is used by FindMembers, and it is used to
/// extract only virtual/abstract fields
/// </summary>
static MemberFilter virtual_method_filter;
/// <summary>
/// This is the array of TypeAndMethods that describes the pending implementations
/// (both interfaces and abstract methods in parent class)
/// </summary>
TypeAndMethods [] pending_implementations;
static bool IsVirtualFilter (MemberInfo m, object filterCriteria)
{
MethodInfo mi = m as MethodInfo;
return (mi == null) ? false : mi.IsVirtual;
}
/// <summary>
/// Inits the virtual_method_filter
/// </summary>
static PendingImplementation ()
{
virtual_method_filter = new MemberFilter (IsVirtualFilter);
}
// <remarks>
// Returns a list of the abstract methods that are exposed by all of our
// parents that we must implement. Notice that this `flattens' the
// method search space, and takes into account overrides.
// </remarks>
static ArrayList GetAbstractMethods (Type t)
{
ArrayList list = null;
bool searching = true;
Type current_type = t;
do {
MemberList mi;
mi = TypeContainer.FindMembers (
current_type, MemberTypes.Method,
BindingFlags.Public | BindingFlags.Instance |
BindingFlags.DeclaredOnly,
virtual_method_filter, null);
if (current_type == TypeManager.object_type)
searching = false;
else {
current_type = current_type.BaseType;
if (!current_type.IsAbstract)
searching = false;
}
if (mi.Count == 0)
continue;
if (mi.Count == 1 && !(mi [0] is MethodBase))
searching = false;
else
list = TypeManager.CopyNewMethods (list, mi);
} while (searching);
if (list == null)
return null;
for (int i = 0; i < list.Count; i++){
while (list.Count > i && !((MethodInfo) list [i]).IsAbstract)
list.RemoveAt (i);
}
if (list.Count == 0)
return null;
return list;
}
PendingImplementation (TypeContainer container, MissingInterfacesInfo [] missing_ifaces, ArrayList abstract_methods, int total)
{
TypeBuilder type_builder = container.TypeBuilder;
this.container = container;
pending_implementations = new TypeAndMethods [total];
int i = 0;
foreach (MissingInterfacesInfo missing in missing_ifaces){
MethodInfo [] mi;
Type t = missing.Type;
if (t is TypeBuilder){
TypeContainer iface;
iface = TypeManager.LookupInterface (t);
mi = iface.GetMethods ();
} else
mi = t.GetMethods ();
int count = mi.Length;
pending_implementations [i].type = t;
pending_implementations [i].optional = missing.Optional;
pending_implementations [i].methods = mi;
pending_implementations [i].args = new Type [count][];
pending_implementations [i].found = new bool [count];
pending_implementations [i].need_proxy = new MethodInfo [count];
string indexer_name = TypeManager.IndexerPropertyName (t);
pending_implementations [i].set_indexer_name = "set_" + indexer_name;
pending_implementations [i].get_indexer_name = "get_" + indexer_name;
int j = 0;
foreach (MethodInfo m in mi){
Type [] types = TypeManager.GetArgumentTypes (m);
pending_implementations [i].args [j] = types;
j++;
}
i++;
}
if (abstract_methods != null){
int count = abstract_methods.Count;
pending_implementations [i].methods = new MethodInfo [count];
pending_implementations [i].need_proxy = new MethodInfo [count];
abstract_methods.CopyTo (pending_implementations [i].methods, 0);
pending_implementations [i].found = new bool [count];
pending_implementations [i].args = new Type [count][];
pending_implementations [i].type = type_builder;
string indexer_name = TypeManager.IndexerPropertyName (type_builder);
pending_implementations [i].set_indexer_name = "set_" + indexer_name;
pending_implementations [i].get_indexer_name = "get_" + indexer_name;
int j = 0;
foreach (MemberInfo m in abstract_methods){
MethodInfo mi = (MethodInfo) m;
Type [] types = TypeManager.GetArgumentTypes (mi);
pending_implementations [i].args [j] = types;
j++;
}
}
}
struct MissingInterfacesInfo {
public Type Type;
public bool Optional;
public MissingInterfacesInfo (Type t)
{
Type = t;
Optional = false;
}
}
static MissingInterfacesInfo [] EmptyMissingInterfacesInfo = new MissingInterfacesInfo [0];
static MissingInterfacesInfo [] GetMissingInterfaces (TypeBuilder type_builder)
{
//
// Notice that TypeBuilders will only return the interfaces that the Type
// is supposed to implement, not all the interfaces that the type implements.
//
// Even better -- on MS it returns an empty array, no matter what.
//
// Completely broken. So we do it ourselves!
//
Type [] impl = TypeManager.GetExplicitInterfaces (type_builder);
if (impl == null || impl.Length == 0)
return EmptyMissingInterfacesInfo;
MissingInterfacesInfo [] ret = new MissingInterfacesInfo [impl.Length];
for (int i = 0; i < impl.Length; i++)
ret [i] = new MissingInterfacesInfo (impl [i]);
// we really should not get here because Object doesnt implement any
// interfaces. But it could implement something internal, so we have
// to handle that case.
if (type_builder.BaseType == null)
return ret;
Type [] parent_impls = TypeManager.GetInterfaces (type_builder.BaseType);
foreach (Type t in parent_impls) {
for (int i = 0; i < ret.Length; i ++) {
if (t == ret [i].Type) {
ret [i].Optional = true;
break;
}
}
}
return ret;
}
//
// Factory method: if there are pending implementation methods, we return a PendingImplementation
// object, otherwise we return null.
//
// Register method implementations are either abstract methods
// flagged as such on the base class or interface methods
//
static public PendingImplementation GetPendingImplementations (TypeContainer container)
{
TypeBuilder type_builder = container.TypeBuilder;
MissingInterfacesInfo [] missing_interfaces;
Type b = type_builder.BaseType;
missing_interfaces = GetMissingInterfaces (type_builder);
//
// If we are implementing an abstract class, and we are not
// ourselves abstract, and there are abstract methods (C# allows
// abstract classes that have no abstract methods), then allocate
// one slot.
//
// We also pre-compute the methods.
//
bool implementing_abstract = ((b != null) && b.IsAbstract && !type_builder.IsAbstract);
ArrayList abstract_methods = null;
if (implementing_abstract){
abstract_methods = GetAbstractMethods (b);
if (abstract_methods == null)
implementing_abstract = false;
}
int total = missing_interfaces.Length + (implementing_abstract ? 1 : 0);
if (total == 0)
return null;
return new PendingImplementation (container, missing_interfaces, abstract_methods, total);
}
public enum Operation {
//
// If you change this, review the whole InterfaceMethod routine as there
// are a couple of assumptions on these three states
//
Lookup, ClearOne, ClearAll
}
/// <summary>
/// Whether the specified method is an interface method implementation
/// </summary>
public MethodInfo IsInterfaceMethod (Type t, string name, Type ret_type, Type [] args)
{
return InterfaceMethod (t, name, ret_type, args, Operation.Lookup, null);
}
public MethodInfo IsInterfaceIndexer (Type t, Type ret_type, Type [] args)
{
return InterfaceMethod (t, null, ret_type, args, Operation.Lookup, null);
}
public void ImplementMethod (Type t, string name, Type ret_type, Type [] args, bool clear_one)
{
InterfaceMethod (t, name, ret_type, args,
clear_one ? Operation.ClearOne : Operation.ClearAll, null);
}
public void ImplementIndexer (Type t, MethodInfo mi, Type ret_type, Type [] args, bool clear_one)
{
InterfaceMethod (t, null, ret_type, args,
clear_one ? Operation.ClearOne : Operation.ClearAll, mi);
}
/// <remarks>
/// If a method in Type `t' (or null to look in all interfaces
/// and the base abstract class) with name `Name', return type `ret_type' and
/// arguments `args' implements an interface, this method will
/// return the MethodInfo that this method implements.
///
/// If `name' is null, we operate solely on the method's signature. This is for
/// instance used when implementing indexers.
///
/// The `Operation op' controls whether to lookup, clear the pending bit, or clear
/// all the methods with the given signature.
///
/// The `MethodInfo need_proxy' is used when we're implementing an interface's
/// indexer in a class. If the new indexer's IndexerName does not match the one
/// that was used in the interface, then we always need to create a proxy for it.
///
/// </remarks>
public MethodInfo InterfaceMethod (Type t, string name, Type ret_type, Type [] args,
Operation op, MethodInfo need_proxy)
{
int arg_len = args.Length;
if (pending_implementations == null)
return null;
foreach (TypeAndMethods tm in pending_implementations){
if (!(t == null || tm.type == t))
continue;
int method_count = tm.methods.Length;
MethodInfo m;
for (int i = 0; i < method_count; i++){
m = tm.methods [i];
if (m == null)
continue;
//
// `need_proxy' is not null when we're implementing an
// interface indexer and this is Clear(One/All) operation.
//
// If `name' is null, then we do a match solely based on the
// signature and not on the name (this is done in the Lookup
// for an interface indexer).
//
if (name == null){
if (m.Name != tm.get_indexer_name && m.Name != tm.set_indexer_name)
continue;
} else if ((need_proxy == null) && (name != m.Name))
continue;
if (!TypeManager.IsEqual (ret_type, m.ReturnType)){
if (!((ret_type == null && m.ReturnType == TypeManager.void_type) ||
(m.ReturnType == null && ret_type == TypeManager.void_type)))
continue;
}
//
// Check if we have the same parameters
//
if (tm.args [i].Length != arg_len)
continue;
int j, top = args.Length;
bool fail = false;
for (j = 0; j < top; j++){
if (!TypeManager.IsEqual (tm.args [i][j], args[j])){
fail = true;
break;
}
}
if (fail)
continue;
if (op != Operation.Lookup){
// If `t != null', then this is an explicitly interface
// implementation and we can always clear the method.
// `need_proxy' is not null if we're implementing an
// interface indexer. In this case, we need to create
// a proxy if the implementation's IndexerName doesn't
// match the IndexerName in the interface.
bool name_matches = false;
if (name == m.Name || m.Name == tm.get_indexer_name || m.Name == tm.set_indexer_name)
name_matches = true;
if ((t == null) && (need_proxy != null) && !name_matches)
tm.need_proxy [i] = need_proxy;
else
tm.methods [i] = null;
}
tm.found [i] = true;
//
// Lookups and ClearOne return
//
if (op != Operation.ClearAll)
return m;
}
// If a specific type was requested, we can stop now.
if (tm.type == t)
return null;
}
return null;
}
/// <summary>
/// C# allows this kind of scenarios:
/// interface I { void M (); }
/// class X { public void M (); }
/// class Y : X, I { }
///
/// For that case, we create an explicit implementation function
/// I.M in Y.
/// </summary>
void DefineProxy (Type iface, MethodInfo parent_method, MethodInfo iface_method,
Type [] args)
{
MethodBuilder proxy;
string proxy_name = iface.Name + "." + iface_method.Name;
proxy = container.TypeBuilder.DefineMethod (
proxy_name,
MethodAttributes.HideBySig |
MethodAttributes.NewSlot |
MethodAttributes.Virtual,
CallingConventions.Standard | CallingConventions.HasThis,
parent_method.ReturnType, args);
int top = args.Length;
ILGenerator ig = proxy.GetILGenerator ();
ig.Emit (OpCodes.Ldarg_0);
for (int i = 0; i < top; i++){
switch (i){
case 0:
ig.Emit (OpCodes.Ldarg_1); break;
case 1:
ig.Emit (OpCodes.Ldarg_2); break;
case 2:
ig.Emit (OpCodes.Ldarg_3); break;
default:
ig.Emit (OpCodes.Ldarg, i - 1); break;
}
}
ig.Emit (OpCodes.Call, parent_method);
ig.Emit (OpCodes.Ret);
container.TypeBuilder.DefineMethodOverride (proxy, iface_method);
}
/// <summary>
/// This function tells whether one of our parent classes implements
/// the given method (which turns out, it is valid to have an interface
/// implementation in a parent
/// </summary>
bool ParentImplements (Type iface_type, MethodInfo mi)
{
MethodSignature ms;
Type [] args = TypeManager.GetArgumentTypes (mi);
ms = new MethodSignature (mi.Name, mi.ReturnType, args);
MemberList list = TypeContainer.FindMembers (
container.TypeBuilder.BaseType, MemberTypes.Method | MemberTypes.Property,
BindingFlags.Public | BindingFlags.Instance,
MethodSignature.method_signature_filter, ms);
if (list.Count == 0)
return false;
MethodInfo parent = (MethodInfo) list [0];
if (!parent.IsAbstract)
DefineProxy (iface_type, parent, mi, args);
return true;
}
/// <summary>
/// Verifies that any pending abstract methods or interface methods
/// were implemented.
/// </summary>
public bool VerifyPendingMethods ()
{
int top = pending_implementations.Length;
bool errors = false;
int i;
for (i = 0; i < top; i++){
Type type = pending_implementations [i].type;
int j = 0;
foreach (MethodInfo mi in pending_implementations [i].methods){
if (mi == null)
continue;
if (type.IsInterface){
MethodInfo need_proxy =
pending_implementations [i].need_proxy [j];
if (need_proxy != null) {
Type [] args = TypeManager.GetArgumentTypes (mi);
DefineProxy (type, need_proxy, mi, args);
continue;
}
if (ParentImplements (type, mi))
continue;
if (pending_implementations [i].optional)
continue;
if (pending_implementations [i].found [j]) {
string[] methodLabel = TypeManager.CSharpSignature (mi).Split ('.');
Report.Error (536, container.Location, "'{0}' does not implement interface member '{1}'. '{2}.{3}' is either static, not public, or has the wrong return type",
container.Name, TypeManager.CSharpSignature (mi), container.Name, methodLabel[methodLabel.Length - 1]);
}
else {
Report.Error (535, container.Location, "'{0}' does not implement interface member '{1}'",
container.Name, TypeManager.CSharpSignature (mi));
}
} else {
Report.Error (534, container.Location, "'{0}' does not implement inherited abstract member '{1}'",
container.Name, TypeManager.CSharpSignature (mi));
}
errors = true;
j++;
}
}
return errors;
}
} /* end of class */
}
-661
View File
@@ -1,661 +0,0 @@
//
// report.cs: report errors and warnings.
//
// Author: Miguel de Icaza ([email protected])
//
// (C) 2001 Ximian, Inc. (http://www.ximian.com)
//
//
// FIXME: currently our class library does not support custom number format strings
//
using System;
using System.Text;
using System.Collections;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Reflection;
namespace Mono.CSharp {
/// <summary>
/// This class is used to report errors and warnings t te user.
/// </summary>
public class Report {
/// <summary>
/// Errors encountered so far
/// </summary>
static public int Errors;
/// <summary>
/// Warnings encountered so far
/// </summary>
static public int Warnings;
/// <summary>
/// Whether errors should be throw an exception
/// </summary>
static public bool Fatal;
/// <summary>
/// Whether warnings should be considered errors
/// </summary>
static public bool WarningsAreErrors;
/// <summary>
/// Whether to dump a stack trace on errors.
/// </summary>
static public bool Stacktrace;
//
// If the 'expected' error code is reported then the
// compilation succeeds.
//
// Used for the test suite to excercise the error codes
//
static int expected_error = 0;
//
// Keeps track of the warnings that we are ignoring
//
static Hashtable warning_ignore_table;
static Hashtable warning_regions_table;
/// <summary>
/// List of symbols related to reported error/warning. You have to fill it before error/warning is reported.
/// </summary>
static StringCollection related_symbols = new StringCollection ();
abstract class AbstractMessage {
static void Check (int code)
{
if (code == expected_error) {
Environment.Exit (0);
}
}
public abstract bool IsWarning { get; }
public abstract string MessageType { get; }
public virtual void Print (int code, string location, string text)
{
if (code < 0)
code = 8000-code;
StringBuilder msg = new StringBuilder ();
if (location.Length != 0) {
msg.Append (location);
msg.Append (' ');
}
msg.AppendFormat ("{0} CS{1:0000}: {2}", MessageType, code, text);
Console.WriteLine (msg.ToString ());
foreach (string s in related_symbols) {
Console.WriteLine (String.Concat (s, MessageType, ')'));
}
related_symbols.Clear ();
if (Stacktrace)
Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
if (Fatal) {
if (!IsWarning || WarningsAreErrors)
throw new Exception (text);
}
Check (code);
}
public virtual void Print (int code, Location location, string text)
{
if (location.Equals (Location.Null)) {
Print (code, "", text);
return;
}
Print (code, String.Format ("{0}({1})", location.Name, location.Row), text);
}
}
sealed class WarningMessage: AbstractMessage {
Location loc = Location.Null;
readonly int Level;
public WarningMessage ():
this (-1) {}
public WarningMessage (int level)
{
Level = level;
}
public override bool IsWarning {
get { return true; }
}
bool IsEnabled (int code)
{
if (RootContext.WarningLevel < Level)
return false;
if (warning_ignore_table != null) {
if (warning_ignore_table.Contains (code)) {
return false;
}
}
if (warning_regions_table == null || loc.Equals (Location.Null))
return true;
WarningRegions regions = (WarningRegions)warning_regions_table [loc.Name];
return regions.IsWarningEnabled (code, loc.Row);
}
public override void Print(int code, string location, string text)
{
if (!IsEnabled (code)) {
related_symbols.Clear ();
return;
}
if (WarningsAreErrors) {
new ErrorMessage ().Print (code, location, text);
return;
}
Warnings++;
base.Print (code, location, text);
}
public override void Print(int code, Location location, string text)
{
loc = location;
base.Print (code, location, text);
}
public override string MessageType {
get {
return "warning";
}
}
}
sealed class ErrorMessage: AbstractMessage {
public override void Print(int code, string location, string text)
{
Errors++;
base.Print (code, location, text);
}
public override bool IsWarning {
get { return false; }
}
public override string MessageType {
get {
return "error";
}
}
}
public static void FeatureIsNotStandardized (Location loc, string feature)
{
Report.Error (1644, loc, "Feature '{0}' cannot be used because it is not part of the standardized ISO C# language specification", feature);
}
public static string FriendlyStackTrace (Exception e)
{
return FriendlyStackTrace (new StackTrace (e, true));
}
static string FriendlyStackTrace (StackTrace t)
{
StringBuilder sb = new StringBuilder ();
bool foundUserCode = false;
for (int i = 0; i < t.FrameCount; i++) {
StackFrame f = t.GetFrame (i);
MethodBase mb = f.GetMethod ();
if (!foundUserCode && mb.ReflectedType == typeof (Report))
continue;
foundUserCode = true;
sb.Append ("\tin ");
if (f.GetFileLineNumber () > 0)
sb.AppendFormat ("(at {0}:{1}) ", f.GetFileName (), f.GetFileLineNumber ());
sb.AppendFormat ("{0}.{1} (", mb.ReflectedType.Name, mb.Name);
bool first = true;
foreach (ParameterInfo pi in mb.GetParameters ()) {
if (!first)
sb.Append (", ");
first = false;
sb.Append (TypeManager.CSharpName (pi.ParameterType));
}
sb.Append (")\n");
}
return sb.ToString ();
}
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// IF YOU ADD A NEW WARNING YOU HAVE TO DUPLICATE ITS ID HERE
public static bool IsValidWarning (int code)
{
int[] all_warnings = new int[] { 28, 67, 78, 105, 108, 109, 114, 192, 168, 169, 183, 184, 219, 251, 612, 618, 626, 628, 642, 649,
659, 660, 661, 672, 1030, 1522, 1616, 1691, 1692, 1901, 2002, 2023, 3012, 3019, 8024, 8028
};
foreach (int i in all_warnings) {
if (i == code)
return true;
}
return false;
}
static public void LocationOfPreviousError (Location loc)
{
Console.WriteLine (String.Format ("{0}({1}) (Location of symbol related to previous error)", loc.Name, loc.Row));
}
static public void RuntimeMissingSupport (Location loc, string feature)
{
Report.Error (-88, loc, "Your .NET Runtime does not support '{0}'. Please use the latest Mono runtime instead.", feature);
}
/// <summary>
/// In most error cases is very useful to have information about symbol that caused the error.
/// Call this method before you call Report.Error when it makes sense.
/// </summary>
static public void SymbolRelatedToPreviousError (Location loc, string symbol)
{
SymbolRelatedToPreviousError (String.Format ("{0}({1})", loc.Name, loc.Row), symbol);
}
static public void SymbolRelatedToPreviousError (MemberInfo mi)
{
TypeContainer temp_ds = TypeManager.LookupGenericTypeContainer (mi.DeclaringType);
if (temp_ds == null) {
SymbolRelatedToPreviousError (mi.DeclaringType.Assembly.Location, TypeManager.GetFullNameSignature (mi));
} else {
MethodBase mb = mi as MethodBase;
if (mb != null) {
while (mb.Mono_IsInflatedMethod)
mb = mb.GetGenericMethodDefinition ();
IMethodData md = TypeManager.GetMethod (mb);
SymbolRelatedToPreviousError (md.Location, md.GetSignatureForError (temp_ds));
return;
}
string name = String.Concat (temp_ds.Name, ".", mi.Name);
MemberCore mc = temp_ds.GetDefinition (name);
SymbolRelatedToPreviousError (mc);
}
}
static public void SymbolRelatedToPreviousError (MemberCore mc)
{
SymbolRelatedToPreviousError (mc.Location, mc.GetSignatureForError ());
}
static public void SymbolRelatedToPreviousError (Type type)
{
DeclSpace temp_ds = TypeManager.LookupDeclSpace (type);
if (temp_ds == null)
SymbolRelatedToPreviousError (type.Assembly.Location, TypeManager.CSharpName (type));
else
SymbolRelatedToPreviousError (temp_ds.Location, TypeManager.CSharpName (type));
}
static void SymbolRelatedToPreviousError (string loc, string symbol)
{
related_symbols.Add (String.Format ("{0}: '{1}' (name of symbol related to previous ", loc, symbol));
}
public static WarningRegions RegisterWarningRegion (Location location)
{
if (warning_regions_table == null)
warning_regions_table = new Hashtable ();
WarningRegions regions = (WarningRegions)warning_regions_table [location.Name];
if (regions == null) {
regions = new WarningRegions ();
warning_regions_table.Add (location.Name, regions);
}
return regions;
}
static public void Warning (int code, int level, Location loc, string format, params object[] args)
{
WarningMessage w = new WarningMessage (level);
w.Print (code, loc, String.Format (format, args));
}
static public void Warning (int code, Location loc, string format, params object[] args)
{
WarningMessage w = new WarningMessage ();
w.Print (code, loc, String.Format (format, args));
}
static public void Warning (int code, string format, params object[] args)
{
Warning (code, Location.Null, String.Format (format, args));
}
/// <summary>
/// Did you test your WarningLevel, that you use this method
/// </summary>
static public void Warning (int code, string text)
{
Warning (code, Location.Null, text);
}
static public void Error (int code, string format, params object[] args)
{
Error (code, Location.Null, String.Format (format, args));
}
static public void Error (int code, Location loc, string format, params object[] args)
{
ErrorMessage e = new ErrorMessage ();
e.Print (code, loc, String.Format (format, args));
}
static public void SetIgnoreWarning (int code)
{
if (warning_ignore_table == null)
warning_ignore_table = new Hashtable ();
warning_ignore_table [code] = true;
}
static public int ExpectedError {
set {
expected_error = value;
}
get {
return expected_error;
}
}
public static int DebugFlags = 0;
[Conditional ("MCS_DEBUG")]
static public void Debug (string message, params object[] args)
{
Debug (4, message, args);
}
[Conditional ("MCS_DEBUG")]
static public void Debug (int category, string message, params object[] args)
{
if ((category & DebugFlags) == 0)
return;
StringBuilder sb = new StringBuilder (message);
if ((args != null) && (args.Length > 0)) {
sb.Append (": ");
bool first = true;
foreach (object arg in args) {
if (first)
first = false;
else
sb.Append (", ");
if (arg == null)
sb.Append ("null");
else if (arg is ICollection)
sb.Append (PrintCollection ((ICollection) arg));
else
sb.Append (arg);
}
}
Console.WriteLine (sb.ToString ());
}
static public string PrintCollection (ICollection collection)
{
StringBuilder sb = new StringBuilder ();
sb.Append (collection.GetType ());
sb.Append ("(");
bool first = true;
foreach (object o in collection) {
if (first)
first = false;
else
sb.Append (", ");
sb.Append (o);
}
sb.Append (")");
return sb.ToString ();
}
}
public enum TimerType {
FindMembers = 0,
TcFindMembers = 1,
MemberLookup = 2,
CachedLookup = 3,
CacheInit = 4,
MiscTimer = 5,
CountTimers = 6
}
public enum CounterType {
FindMembers = 0,
MemberCache = 1,
MiscCounter = 2,
CountCounters = 3
}
public class Timer
{
static DateTime[] timer_start;
static TimeSpan[] timers;
static long[] timer_counters;
static long[] counters;
static Timer ()
{
timer_start = new DateTime [(int) TimerType.CountTimers];
timers = new TimeSpan [(int) TimerType.CountTimers];
timer_counters = new long [(int) TimerType.CountTimers];
counters = new long [(int) CounterType.CountCounters];
for (int i = 0; i < (int) TimerType.CountTimers; i++) {
timer_start [i] = DateTime.Now;
timers [i] = TimeSpan.Zero;
}
}
[Conditional("TIMER")]
static public void IncrementCounter (CounterType which)
{
++counters [(int) which];
}
[Conditional("TIMER")]
static public void StartTimer (TimerType which)
{
timer_start [(int) which] = DateTime.Now;
}
[Conditional("TIMER")]
static public void StopTimer (TimerType which)
{
timers [(int) which] += DateTime.Now - timer_start [(int) which];
++timer_counters [(int) which];
}
[Conditional("TIMER")]
static public void ShowTimers ()
{
ShowTimer (TimerType.FindMembers, "- FindMembers timer");
ShowTimer (TimerType.TcFindMembers, "- TypeContainer.FindMembers timer");
ShowTimer (TimerType.MemberLookup, "- MemberLookup timer");
ShowTimer (TimerType.CachedLookup, "- CachedLookup timer");
ShowTimer (TimerType.CacheInit, "- Cache init");
ShowTimer (TimerType.MiscTimer, "- Misc timer");
ShowCounter (CounterType.FindMembers, "- Find members");
ShowCounter (CounterType.MemberCache, "- Member cache");
ShowCounter (CounterType.MiscCounter, "- Misc counter");
}
static public void ShowCounter (CounterType which, string msg)
{
Console.WriteLine ("{0} {1}", counters [(int) which], msg);
}
static public void ShowTimer (TimerType which, string msg)
{
Console.WriteLine (
"[{0:00}:{1:000}] {2} (used {3} times)",
(int) timers [(int) which].TotalSeconds,
timers [(int) which].Milliseconds, msg,
timer_counters [(int) which]);
}
}
public class InternalErrorException : Exception {
public InternalErrorException ()
: base ("Internal error")
{
}
public InternalErrorException (string message)
: base (message)
{
}
}
/// <summary>
/// Handles #pragma warning
/// </summary>
public class WarningRegions {
abstract class PragmaCmd
{
public int Line;
protected PragmaCmd (int line)
{
Line = line;
}
public abstract bool IsEnabled (int code, bool previous);
}
class Disable: PragmaCmd
{
int code;
public Disable (int line, int code)
: base (line)
{
this.code = code;
}
public override bool IsEnabled (int code, bool previous)
{
return this.code == code ? false : previous;
}
}
class DisableAll: PragmaCmd
{
public DisableAll (int line)
: base (line) {}
public override bool IsEnabled(int code, bool previous)
{
return false;
}
}
class Enable: PragmaCmd
{
int code;
public Enable (int line, int code)
: base (line)
{
this.code = code;
}
public override bool IsEnabled(int code, bool previous)
{
return this.code == code ? true : previous;
}
}
class EnableAll: PragmaCmd
{
public EnableAll (int line)
: base (line) {}
public override bool IsEnabled(int code, bool previous)
{
return true;
}
}
ArrayList regions = new ArrayList ();
public void WarningDisable (int line)
{
regions.Add (new DisableAll (line));
}
public void WarningDisable (Location location, int code)
{
if (CheckWarningCode (code, location))
regions.Add (new Disable (location.Row, code));
}
public void WarningEnable (int line)
{
regions.Add (new EnableAll (line));
}
public void WarningEnable (Location location, int code)
{
if (CheckWarningCode (code, location))
regions.Add (new Enable (location.Row, code));
}
public bool IsWarningEnabled (int code, int src_line)
{
bool result = true;
foreach (PragmaCmd pragma in regions) {
if (src_line < pragma.Line)
break;
result = pragma.IsEnabled (code, result);
}
return result;
}
bool CheckWarningCode (int code, Location loc)
{
if (Report.IsValidWarning (code))
return true;
Report.Warning (1691, 1, loc, "'{0}' is not a valid warning number", code);
return false;
}
}
}
-801
View File
@@ -1,801 +0,0 @@
//
// rootcontext.cs: keeps track of our tree representation, and assemblies loaded.
//
// Author: Miguel de Icaza ([email protected])
// Ravi Pratap ([email protected])
//
// Licensed under the terms of the GNU GPL
//
// (C) 2001 Ximian, Inc (http://www.ximian.com)
using System;
using System.Collections;
using System.Reflection;
using System.Reflection.Emit;
using System.Diagnostics;
namespace Mono.CSharp {
public enum LanguageVersion
{
Default = 0,
ISO_1 = 1
}
public class RootContext {
//
// Contains the parsed tree
//
static Tree tree;
//
// This hashtable contains all of the #definitions across the source code
// it is used by the ConditionalAttribute handler.
//
public static Hashtable AllDefines = new Hashtable ();
//
// Whether we are being linked against the standard libraries.
// This is only used to tell whether `System.Object' should
// have a parent or not.
//
public static bool StdLib = true;
//
// This keeps track of the order in which classes were defined
// so that we can poulate them in that order.
//
// Order is important, because we need to be able to tell by
// examining the parent's list of methods which ones are virtual
// or abstract as well as the parent names (to implement new,
// override).
//
static ArrayList type_container_resolve_order;
static ArrayList attribute_types;
//
// Holds a reference to the Private Implementation Details
// class.
//
static ArrayList helper_classes;
static TypeBuilder impl_details_class;
public static int WarningLevel = 2;
public static Target Target = Target.Exe;
public static string TargetExt = ".exe";
public static bool VerifyClsCompliance = true;
public static LanguageVersion Version = LanguageVersion.Default;
//
// We keep strongname related info here because
// it's also used as complier options from CSC 8.x
//
public static string StrongNameKeyFile;
public static string StrongNameKeyContainer;
public static bool StrongNameDelaySign = false;
//
// Constructor
//
static RootContext ()
{
tree = new Tree ();
type_container_resolve_order = new ArrayList ();
}
public static bool NeedsEntryPoint {
get {
return RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe;
}
}
static public Tree Tree {
get {
return tree;
}
}
static public string MainClass;
public static void RegisterOrder (TypeContainer tc)
{
type_container_resolve_order.Add (tc);
}
public static void RegisterAttribute (TypeContainer tc)
{
if (attribute_types == null)
attribute_types = new ArrayList ();
attribute_types.Add (tc);
}
//
// The default compiler checked state
//
static public bool Checked = false;
//
// Whether to allow Unsafe code
//
static public bool Unsafe = false;
static string MakeFQN (string nsn, string name)
{
if (nsn == "")
return name;
return String.Concat (nsn, ".", name);
}
// <remarks>
// This function is used to resolve the hierarchy tree.
// It processes interfaces, structs and classes in that order.
//
// It creates the TypeBuilder's as it processes the user defined
// types.
// </remarks>
static public void ResolveTree ()
{
//
// Process the attribute types separately and before anything else
//
if (attribute_types != null)
foreach (TypeContainer tc in attribute_types)
tc.DefineType ();
//
// Interfaces are processed next, as classes and
// structs might inherit from an object or implement
// a set of interfaces, we need to be able to tell
// them appart by just using the TypeManager.
//
TypeContainer root = Tree.Types;
ArrayList ifaces = root.Interfaces;
if (ifaces != null){
foreach (Interface i in ifaces)
i.DefineType ();
}
foreach (TypeContainer tc in root.Types)
tc.DefineType ();
if (root.Delegates != null)
foreach (Delegate d in root.Delegates)
d.DefineType ();
if (root.Enums != null)
foreach (Enum e in root.Enums)
e.DefineType ();
}
static void Error_TypeConflict (string name, Location loc)
{
Report.Error (
520, loc, "`" + name + "' conflicts with a predefined type");
}
static void Error_TypeConflict (string name)
{
Report.Error (
520, "`" + name + "' conflicts with a predefined type");
}
//
// Resolves a single class during the corlib bootstrap process
//
static TypeBuilder BootstrapCorlib_ResolveClass (TypeContainer root, string name)
{
object o = root.GetDefinition (name);
if (o == null){
Report.Error (518, "The predefined type `" + name + "' is not defined");
return null;
}
if (!(o is Class)){
if (o is DeclSpace){
DeclSpace d = (DeclSpace) o;
Error_TypeConflict (name, d.Location);
} else
Error_TypeConflict (name);
return null;
}
return ((DeclSpace) o).DefineType ();
}
//
// Resolves a struct during the corlib bootstrap process
//
static void BootstrapCorlib_ResolveStruct (TypeContainer root, string name)
{
object o = root.GetDefinition (name);
if (o == null){
Report.Error (518, "The predefined type `" + name + "' is not defined");
return;
}
if (!(o is Struct)){
if (o is DeclSpace){
DeclSpace d = (DeclSpace) o;
Error_TypeConflict (name, d.Location);
} else
Error_TypeConflict (name);
return;
}
((DeclSpace) o).DefineType ();
}
//
// Resolves a struct during the corlib bootstrap process
//
static void BootstrapCorlib_ResolveInterface (TypeContainer root, string name)
{
object o = root.GetDefinition (name);
if (o == null){
Report.Error (518, "The predefined type `" + name + "' is not defined");
return;
}
if (!(o is Interface)){
if (o is DeclSpace){
DeclSpace d = (DeclSpace) o;
Error_TypeConflict (name, d.Location);
} else
Error_TypeConflict (name);
return;
}
((DeclSpace) o).DefineType ();
}
//
// Resolves a delegate during the corlib bootstrap process
//
static void BootstrapCorlib_ResolveDelegate (TypeContainer root, string name)
{
object o = root.GetDefinition (name);
if (o == null){
Report.Error (518, "The predefined type `" + name + "' is not defined");
Environment.Exit (1);
}
if (!(o is Delegate)){
Error_TypeConflict (name);
return;
}
((DeclSpace) o).DefineType ();
}
/// <summary>
/// Resolves the core types in the compiler when compiling with --nostdlib
/// </summary>
static public void ResolveCore ()
{
TypeContainer root = Tree.Types;
TypeManager.object_type = BootstrapCorlib_ResolveClass (root, "System.Object");
TypeManager.value_type = BootstrapCorlib_ResolveClass (root, "System.ValueType");
TypeManager.attribute_type = BootstrapCorlib_ResolveClass (root, "System.Attribute");
string [] interfaces_first_stage = {
"System.IComparable", "System.ICloneable",
"System.IConvertible",
"System.Collections.IEnumerable",
"System.Collections.ICollection",
"System.Collections.IEnumerator",
"System.Collections.IList",
"System.IAsyncResult",
"System.IDisposable",
"System.Runtime.Serialization.ISerializable",
"System.Reflection.IReflect",
"System.Reflection.ICustomAttributeProvider",
//
// Generic types
//
"System.Collections.Generic.IEnumerator`1",
"System.Collections.Generic.IEnumerable`1"
};
foreach (string iname in interfaces_first_stage)
BootstrapCorlib_ResolveInterface (root, iname);
//
// These are the base value types
//
string [] structs_first_stage = {
"System.Byte", "System.SByte",
"System.Int16", "System.UInt16",
"System.Int32", "System.UInt32",
"System.Int64", "System.UInt64",
};
foreach (string cname in structs_first_stage)
BootstrapCorlib_ResolveStruct (root, cname);
//
// Now, we can load the enumerations, after this point,
// we can use enums.
//
TypeManager.InitEnumUnderlyingTypes ();
string [] structs_second_stage = {
"System.Single", "System.Double",
"System.Char", "System.Boolean",
"System.Decimal", "System.Void",
"System.RuntimeFieldHandle",
"System.RuntimeArgumentHandle",
"System.RuntimeTypeHandle",
"System.IntPtr",
"System.TypedReference",
"System.ArgIterator"
};
foreach (string cname in structs_second_stage)
BootstrapCorlib_ResolveStruct (root, cname);
//
// These are classes that depends on the core interfaces
//
string [] classes_second_stage = {
"System.Reflection.MemberInfo",
"System.Type",
"System.Exception",
"System.Activator",
//
// These are not really important in the order, but they
// are used by the compiler later on (typemanager/CoreLookupType-d)
//
"System.Runtime.CompilerServices.RuntimeHelpers",
"System.Reflection.DefaultMemberAttribute",
"System.Threading.Monitor",
"System.AttributeUsageAttribute",
"System.Runtime.InteropServices.DllImportAttribute",
"System.Runtime.CompilerServices.MethodImplAttribute",
"System.Runtime.InteropServices.MarshalAsAttribute",
"System.Runtime.CompilerServices.NewConstraintAttribute",
"System.Diagnostics.ConditionalAttribute",
"System.ObsoleteAttribute",
"System.ParamArrayAttribute",
"System.CLSCompliantAttribute",
"System.Security.UnverifiableCodeAttribute",
"System.Security.Permissions.SecurityAttribute",
"System.Runtime.CompilerServices.IndexerNameAttribute",
"System.Runtime.InteropServices.InAttribute",
"System.Runtime.InteropServices.StructLayoutAttribute",
"System.Runtime.InteropServices.FieldOffsetAttribute",
"System.InvalidOperationException",
"System.NotSupportedException",
"System.MarshalByRefObject",
"System.Security.CodeAccessPermission"
};
// We must store them here before calling BootstrapCorlib_ResolveDelegate.
TypeManager.string_type = BootstrapCorlib_ResolveClass (root, "System.String");
TypeManager.enum_type = BootstrapCorlib_ResolveClass (root, "System.Enum");
TypeManager.array_type = BootstrapCorlib_ResolveClass (root, "System.Array");
TypeManager.multicast_delegate_type = BootstrapCorlib_ResolveClass (root, "System.MulticastDelegate");
TypeManager.delegate_type = BootstrapCorlib_ResolveClass (root, "System.Delegate");
foreach (string cname in classes_second_stage)
BootstrapCorlib_ResolveClass (root, cname);
BootstrapCorlib_ResolveDelegate (root, "System.AsyncCallback");
}
// <summary>
// Closes all open types
// </summary>
//
// <remarks>
// We usually use TypeBuilder types. When we are done
// creating the type (which will happen after we have added
// methods, fields, etc) we need to "Define" them before we
// can save the Assembly
// </remarks>
static public void CloseTypes ()
{
TypeContainer root = Tree.Types;
if (root.Enums != null)
foreach (Enum en in root.Enums)
en.CloseType ();
if (attribute_types != null)
foreach (TypeContainer tc in attribute_types)
tc.CloseType ();
//
// We do this in two passes, first we close the structs,
// then the classes, because it seems the code needs it this
// way. If this is really what is going on, we should probably
// make sure that we define the structs in order as well.
//
foreach (TypeContainer tc in type_container_resolve_order){
if (tc.Kind == Kind.Struct && tc.Parent == tree.Types){
tc.CloseType ();
}
}
foreach (TypeContainer tc in type_container_resolve_order){
if (!(tc.Kind == Kind.Struct && tc.Parent == tree.Types))
tc.CloseType ();
}
if (root.Delegates != null)
foreach (Delegate d in root.Delegates)
d.CloseType ();
//
// If we have a <PrivateImplementationDetails> class, close it
//
if (helper_classes != null){
foreach (TypeBuilder type_builder in helper_classes)
type_builder.CreateType ();
}
attribute_types = null;
type_container_resolve_order = null;
helper_classes = null;
//tree = null;
TypeManager.CleanUp ();
}
/// <summary>
/// Used to register classes that need to be closed after all the
/// user defined classes
/// </summary>
public static void RegisterHelperClass (TypeBuilder helper_class)
{
if (helper_classes == null)
helper_classes = new ArrayList ();
helper_classes.Add (helper_class);
}
//
// This idea is from Felix Arrese-Igor
//
// Returns : the implicit parent of a composite namespace string
// eg. Implicit parent of A.B is A
//
static public string ImplicitParent (string ns)
{
int i = ns.LastIndexOf ('.');
if (i < 0)
return null;
return ns.Substring (0, i);
}
static TypeExpr NamespaceLookup (DeclSpace ds, string name,
int num_type_args, Location loc)
{
//
// Try in the current namespace and all its implicit parents
//
for (NamespaceEntry ns = ds.NamespaceEntry; ns != null; ns = ns.ImplicitParent) {
IAlias result = ns.Lookup (ds, name, num_type_args, false, loc);
if (result == null)
continue;
if (!result.IsType)
return null;
return result.Type;
}
return null;
}
static public TypeExpr LookupType (DeclSpace ds, string name, bool silent,
Location loc)
{
return LookupType (ds, name, silent, 0, loc);
}
//
// Public function used to locate types, this can only
// be used after the ResolveTree function has been invoked.
//
// Returns: Type or null if they type can not be found.
//
// Come to think of it, this should be a DeclSpace
//
static public TypeExpr LookupType (DeclSpace ds, string name, bool silent,
int num_type_params, Location loc)
{
TypeExpr t;
if (ds.Cache.Contains (name)){
t = (TypeExpr) ds.Cache [name];
if (t != null)
return t;
} else {
//
// For the case the type we are looking for is nested within this one
// or is in any base class
//
DeclSpace containing_ds = ds;
while (containing_ds != null){
Type current_type = containing_ds.TypeBuilder;
while (current_type != null) {
//
// nested class
//
Type type = TypeManager.LookupType (current_type.FullName + "." + name);
if (type != null){
type = ds.ResolveNestedType (type, loc);
t = new TypeExpression (type, loc);
ds.Cache [name] = t;
return t;
}
current_type = current_type.BaseType;
}
containing_ds = containing_ds.Parent;
}
t = NamespaceLookup (ds, name, num_type_params, loc);
if (t != null){
ds.Cache [name] = t;
return t;
}
}
if (!silent)
Report.Error (246, loc, "Cannot find type `"+name+"'");
return null;
}
// <summary>
// This is the silent version of LookupType, you can use this
// to `probe' for a type
// </summary>
static public TypeExpr LookupType (TypeContainer tc, string name, Location loc)
{
return LookupType (tc, name, true, loc);
}
static void Report1530 (Location loc)
{
Report.Error (1530, loc, "Keyword new not allowed for namespace elements");
}
static public void PopulateCoreType (TypeContainer root, string name)
{
DeclSpace ds = (DeclSpace) root.GetDefinition (name);
ds.DefineMembers (root);
ds.Define ();
}
static public void BootCorlib_PopulateCoreTypes ()
{
TypeContainer root = tree.Types;
PopulateCoreType (root, "System.Object");
PopulateCoreType (root, "System.ValueType");
PopulateCoreType (root, "System.Attribute");
}
// <summary>
// Populates the structs and classes with fields and methods
// </summary>
//
// This is invoked after all interfaces, structs and classes
// have been defined through `ResolveTree'
static public void PopulateTypes ()
{
TypeContainer root = Tree.Types;
if (attribute_types != null)
foreach (TypeContainer tc in attribute_types)
tc.DefineMembers (root);
if (type_container_resolve_order != null){
if (RootContext.StdLib){
foreach (TypeContainer tc in type_container_resolve_order)
tc.DefineMembers (root);
} else {
foreach (TypeContainer tc in type_container_resolve_order) {
// When compiling corlib, these types have already been
// populated from BootCorlib_PopulateCoreTypes ().
if (((tc.Name == "System.Object") ||
(tc.Name == "System.Attribute") ||
(tc.Name == "System.ValueType")))
continue;
tc.DefineMembers (root);
}
}
}
ArrayList delegates = root.Delegates;
if (delegates != null){
foreach (Delegate d in delegates)
if ((d.ModFlags & Modifiers.NEW) == 0)
d.DefineMembers (root);
else
Report1530 (d.Location);
}
ArrayList enums = root.Enums;
if (enums != null){
foreach (Enum en in enums)
if ((en.ModFlags & Modifiers.NEW) == 0)
en.DefineMembers (root);
else
Report1530 (en.Location);
}
//
// Check for cycles in the struct layout
//
if (type_container_resolve_order != null){
Hashtable seen = new Hashtable ();
foreach (TypeContainer tc in type_container_resolve_order)
TypeManager.CheckStructCycles (tc, seen);
}
}
//
// A generic hook delegate
//
public delegate void Hook ();
//
// A hook invoked when the code has been generated.
//
public static event Hook EmitCodeHook;
//
// DefineTypes is used to fill in the members of each type.
//
static public void DefineTypes ()
{
TypeContainer root = Tree.Types;
if (attribute_types != null)
foreach (TypeContainer tc in attribute_types)
tc.Define ();
if (type_container_resolve_order != null){
foreach (TypeContainer tc in type_container_resolve_order) {
// When compiling corlib, these types have already been
// populated from BootCorlib_PopulateCoreTypes ().
if (!RootContext.StdLib &&
((tc.Name == "System.Object") ||
(tc.Name == "System.Attribute") ||
(tc.Name == "System.ValueType")))
continue;
if ((tc.ModFlags & Modifiers.NEW) == 0)
tc.Define ();
}
}
ArrayList delegates = root.Delegates;
if (delegates != null){
foreach (Delegate d in delegates)
if ((d.ModFlags & Modifiers.NEW) == 0)
d.Define ();
}
ArrayList enums = root.Enums;
if (enums != null){
foreach (Enum en in enums)
if ((en.ModFlags & Modifiers.NEW) == 0)
en.Define ();
}
}
static public void EmitCode ()
{
if (attribute_types != null)
foreach (TypeContainer tc in attribute_types)
tc.EmitType ();
CodeGen.Assembly.Emit (Tree.Types);
CodeGen.Module.Emit (Tree.Types);
if (Tree.Types.Enums != null) {
foreach (Enum e in Tree.Types.Enums)
e.Emit ();
}
if (type_container_resolve_order != null) {
foreach (TypeContainer tc in type_container_resolve_order)
tc.EmitType ();
}
if (Tree.Types.Delegates != null) {
foreach (Delegate d in Tree.Types.Delegates)
d.Emit ();
}
//
// Run any hooks after all the types have been defined.
// This is used to create nested auxiliary classes for example
//
if (EmitCodeHook != null)
EmitCodeHook ();
}
//
// Public Field, used to track which method is the public entry
// point.
//
static public MethodInfo EntryPoint;
//
// Track the location of the entry point.
//
static public Location EntryPointLocation;
//
// These are used to generate unique names on the structs and fields.
//
static int field_count;
//
// Makes an initialized struct, returns the field builder that
// references the data. Thanks go to Sergey Chaban for researching
// how to do this. And coming up with a shorter mechanism than I
// was able to figure out.
//
// This works but makes an implicit public struct $ArrayType$SIZE and
// makes the fields point to it. We could get more control if we did
// use instead:
//
// 1. DefineNestedType on the impl_details_class with our struct.
//
// 2. Define the field on the impl_details_class
//
static public FieldBuilder MakeStaticData (byte [] data)
{
FieldBuilder fb;
if (impl_details_class == null){
impl_details_class = CodeGen.Module.Builder.DefineType (
"<PrivateImplementationDetails>",
TypeAttributes.NotPublic,
TypeManager.object_type);
RegisterHelperClass (impl_details_class);
}
fb = impl_details_class.DefineInitializedData (
"$$field-" + (field_count++), data,
FieldAttributes.Static | FieldAttributes.Assembly);
return fb;
}
}
}
-29
View File
@@ -1,29 +0,0 @@
using System;
using Generics;
namespace Test
{
public class Bar : Foo
{
public void Hello (Stack<int> stack)
{
Console.WriteLine ("Hello Generic World!");
Console.WriteLine (stack);
Console.WriteLine (stack.GetType ());
}
public Stack<int> Test ()
{
return Driver.int_stack;
}
public static void Main ()
{
Foo foo = new Bar ();
Driver.Init (foo);
Stack<int> a = Driver.int_stack;
Console.WriteLine ("STACK: {0}", a);
foo.Hello (a);
}
}
}
-103
View File
@@ -1,103 +0,0 @@
.assembly sample-stack {}
.namespace Generics
{
.class interface public abstract Foo
{
.method public virtual hidebysig newslot abstract instance default void Hello(class Generics.Stack<int32> stack)
{
}
}
.class public beforefieldinit Driver extends [mscorlib]System.Object
{
.field static public class Generics.Stack<int32> int_stack
.field static public class Generics.Stack<string> string_stack
.method public hidebysig specialname rtspecialname instance default void .ctor()
{
ldarg.0
call instance void valuetype [corlib]System.Object::.ctor()
ret
}
.method public static void Init (class Generics.Foo foo)
{
newobj instance void class Generics.Stack<int32>::.ctor ()
stsfld class Generics.Stack<int32> Generics.Driver::int_stack
newobj instance void class Generics.Stack<string>::.ctor ()
stsfld class Generics.Stack<string> Generics.Driver::string_stack
ldarg.0
ldsfld class Generics.Stack<int32> Generics.Driver::int_stack
callvirt instance void class Generics.Foo::Hello(class Generics.Stack<int32>)
ret
}
}
.class public Stack<T> extends [mscorlib]System.Object
{
.field private int32 size
.field private !0[] data
.method public instance void .ctor ()
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor ()
ldarg.0
ldc.i4.s 100
newarr !0
stfld !0[] class Generics.Stack<!0>::data
ldarg.0
ldc.i4.m1
stfld int32 class Generics.Stack<!0>::size
ret
}
.method public instance void Push (!0 item)
{
.locals init (int32 temp)
ldarg.0
ldfld !0[] class Generics.Stack<!0>::data
ldarg.0
dup
ldfld int32 class Generics.Stack<!0>::size
ldc.i4.1
add
dup
stloc.0
stfld int32 class Generics.Stack<!0>::size
ldloc.0
ldarg.1
stelem !0
ret
}
.method public instance !0 Pop ()
{
.locals init (!0, int32)
ldarg.0
ldfld !0[] class Generics.Stack<!0>::data
ldarg.0
dup
ldfld int32 class Generics.Stack<!0>::size
dup
stloc.1
ldc.i4.1
sub
stfld int32 class Generics.Stack<!0>::size
ldloc.1
ldelem !0
stloc.0
ldloc.0
ret
}
}
}
File diff suppressed because it is too large. Load diff
-166
View File
@@ -1,166 +0,0 @@
//
// System.CodeDOM CodeStatementCollection Class implementation
//
// Author:
// Miguel de Icaza ([email protected])
//
// (C) 2001 Ximian, Inc.
//
namespace Mono.CSharp {
using System.Collections;
using System;
public class StatementCollection : IList, ICollection, IEnumerable {
ArrayList statements;
//
// Constructors
//
public StatementCollection ()
{
statements = new ArrayList ();
}
//
// Properties
//
public int Count {
get {
return statements.Count;
}
}
//
// Methods
//
public void Add (Statement value)
{
statements.Add (value);
}
public void AddRange (Statement [] values)
{
foreach (Statement ca in values)
statements.Add (ca);
}
public void Clear ()
{
statements.Clear ();
}
private class Enumerator : IEnumerator {
private StatementCollection collection;
private int currentIndex = -1;
internal Enumerator (StatementCollection collection)
{
this.collection = collection;
}
public object Current {
get {
if (currentIndex == collection.Count)
throw new InvalidOperationException ();
return collection [currentIndex];
}
}
public bool MoveNext ()
{
if (currentIndex > collection.Count)
throw new InvalidOperationException ();
return ++currentIndex < collection.Count;
}
public void Reset ()
{
currentIndex = -1;
}
}
public IEnumerator GetEnumerator ()
{
return new StatementCollection.Enumerator (this);
}
//
// IList method implementations
//
public int Add (object value)
{
return statements.Add (value);
}
public bool Contains (Object value)
{
return statements.Contains (value);
}
public int IndexOf (Object value)
{
return statements.IndexOf (value);
}
public void Insert (int index, Object value)
{
statements [index] = value;
}
public object this[int index] {
get {
return statements [index];
}
set {
statements [index] = value;
}
}
public void Remove (object value)
{
statements.Remove (value);
}
public void RemoveAt (int index)
{
statements.RemoveAt (index);
}
//
// ICollection method implementations
//
public void CopyTo (Array array, int index)
{
statements.CopyTo (array, index);
}
public object SyncRoot {
get {
return statements.SyncRoot;
}
}
public bool IsReadOnly {
get {
return false;
}
}
public bool IsSynchronized {
get {
return statements.IsSynchronized;
}
}
public bool IsFixedSize {
get {
return false;
}
}
}
}
-603
View File
@@ -1,603 +0,0 @@
//
// support.cs: Support routines to work around the fact that System.Reflection.Emit
// can not introspect types that are being constructed
//
// Author:
// Miguel de Icaza ([email protected])
//
// (C) 2001 Ximian, Inc (http://www.ximian.com)
//
using System;
using System.IO;
using System.Text;
using System.Reflection;
using System.Collections;
using System.Reflection.Emit;
using System.Globalization;
namespace Mono.CSharp {
public interface ParameterData {
Type ParameterType (int pos);
GenericConstraints GenericConstraints (int pos);
bool HasArrayParameter { get; }
int Count { get; }
string ParameterName (int pos);
string ParameterDesc (int pos);
Parameter.Modifier ParameterModifier (int pos);
}
public class ReflectionParameters : ParameterData {
ParameterInfo [] pi;
Type[] type_params;
bool last_arg_is_params = false;
bool is_varargs = false;
ParameterData gpd;
public ReflectionParameters (MethodBase mb)
{
object [] attrs;
ParameterInfo [] pi = mb.GetParameters ();
is_varargs = (mb.CallingConvention & CallingConventions.VarArgs) != 0;
this.pi = pi;
int count = pi.Length-1;
if (count < 0)
return;
if (mb.Mono_IsInflatedMethod) {
MethodInfo generic = mb.GetGenericMethodDefinition ();
gpd = Invocation.GetParameterData (generic);
last_arg_is_params = gpd.HasArrayParameter;
return;
}
if (mb.IsGenericMethodDefinition)
type_params = mb.GetGenericArguments ();
attrs = pi [count].GetCustomAttributes (TypeManager.param_array_type, true);
if (attrs == null)
return;
if (attrs.Length == 0)
return;
last_arg_is_params = true;
}
public bool HasArrayParameter {
get { return last_arg_is_params; }
}
public Type ParameterType (int pos)
{
if (last_arg_is_params && pos >= pi.Length - 1)
return pi [pi.Length - 1].ParameterType;
else if (is_varargs && pos >= pi.Length)
return TypeManager.runtime_argument_handle_type;
else {
Type t = pi [pos].ParameterType;
return t;
}
}
public GenericConstraints GenericConstraints (int pos)
{
if (gpd != null)
return gpd.GenericConstraints (pos);
if (type_params == null)
return null;
return new ReflectionConstraints (type_params [pos]);
}
public string ParameterName (int pos)
{
if (last_arg_is_params && pos >= pi.Length - 1)
return pi [pi.Length - 1].Name;
else if (is_varargs && pos >= pi.Length)
return "__arglist";
else
return pi [pos].Name;
}
public string ParameterDesc (int pos)
{
if (is_varargs && pos >= pi.Length)
return "";
StringBuilder sb = new StringBuilder ();
if (pi [pos].IsIn)
sb.Append ("in ");
Type partype = ParameterType (pos);
if (partype.IsByRef){
partype = TypeManager.GetElementType (partype);
if (pi [pos].IsOut)
sb.Append ("out ");
else
sb.Append ("ref ");
}
if (pos >= pi.Length - 1 && last_arg_is_params)
sb.Append ("params ");
sb.Append (TypeManager.CSharpName (partype));
return sb.ToString ();
}
public Parameter.Modifier ParameterModifier (int pos)
{
int len = pi.Length;
if (last_arg_is_params && pos >= pi.Length - 1)
return Parameter.Modifier.PARAMS;
else if (is_varargs && pos >= pi.Length)
return Parameter.Modifier.ARGLIST;
if (gpd != null)
return gpd.ParameterModifier (pos);
Type t = pi [pos].ParameterType;
if (t.IsByRef){
if ((pi [pos].Attributes & ParameterAttributes.Out) != 0)
return Parameter.Modifier.ISBYREF | Parameter.Modifier.OUT;
else
return Parameter.Modifier.ISBYREF | Parameter.Modifier.REF;
}
return Parameter.Modifier.NONE;
}
public int Count {
get {
return is_varargs ? pi.Length + 1 : pi.Length;
}
}
}
public class InternalParameters : ParameterData {
Type [] param_types;
bool has_varargs;
int count;
public readonly Parameters Parameters;
public readonly TypeParameter[] TypeParameters;
public InternalParameters (Type [] param_types, Parameters parameters)
{
this.param_types = param_types;
this.Parameters = parameters;
has_varargs = parameters.HasArglist;
if (param_types == null)
count = 0;
else
count = param_types.Length;
}
public InternalParameters (Type [] param_types, Parameters parameters,
TypeParameter [] type_params)
: this (param_types, parameters)
{
this.TypeParameters = type_params;
}
public int Count {
get {
return has_varargs ? count + 1 : count;
}
}
public bool HasArrayParameter {
get { return Parameters.ArrayParameter != null; }
}
Parameter GetParameter (int pos)
{
Parameter [] fixed_pars = Parameters.FixedParameters;
if (fixed_pars != null){
int len = fixed_pars.Length;
if (pos < len)
return Parameters.FixedParameters [pos];
}
return Parameters.ArrayParameter;
}
public Type ParameterType (int pos)
{
if (has_varargs && pos >= count)
return TypeManager.runtime_argument_handle_type;
if (param_types == null)
return null;
return GetParameter (pos).ExternalType ();
}
public GenericConstraints GenericConstraints (int pos)
{
if (TypeParameters == null)
return null;
return TypeParameters [pos].Constraints;
}
public string ParameterName (int pos)
{
if (has_varargs && pos >= count)
return "__arglist";
return GetParameter (pos).Name;
}
public string ParameterDesc (int pos)
{
if (has_varargs && pos >= count)
return "__arglist";
string tmp = String.Empty;
Parameter p = GetParameter (pos);
//
// We need to and for REF/OUT, because if either is set the
// extra flag ISBYREF will be set as well
//
if ((p.ModFlags & Parameter.Modifier.REF) != 0)
tmp = "ref ";
else if ((p.ModFlags & Parameter.Modifier.OUT) != 0)
tmp = "out ";
else if (p.ModFlags == Parameter.Modifier.PARAMS)
tmp = "params ";
Type t = ParameterType (pos);
return tmp + TypeManager.CSharpName (t);
}
public Parameter.Modifier ParameterModifier (int pos)
{
if (has_varargs && pos >= count)
return Parameter.Modifier.ARGLIST;
Parameter.Modifier mod = GetParameter (pos).ModFlags;
if ((mod & (Parameter.Modifier.REF | Parameter.Modifier.OUT)) != 0)
mod |= Parameter.Modifier.ISBYREF;
return mod;
}
}
public class ReflectionConstraints : GenericConstraints
{
GenericParameterAttributes attrs;
Type base_type;
Type class_constraint;
Type[] iface_constraints;
public ReflectionConstraints (Type t)
{
Type[] constraints = t.GetGenericParameterConstraints ();
if ((constraints.Length > 0) && !constraints [0].IsInterface) {
class_constraint = constraints [0];
iface_constraints = new Type [constraints.Length - 1];
Array.Copy (constraints, 1, iface_constraints, 0, constraints.Length - 1);
} else
iface_constraints = constraints;
attrs = t.GenericParameterAttributes;
if (HasValueTypeConstraint)
base_type = TypeManager.value_type;
else if (class_constraint != null)
base_type = class_constraint;
else
base_type = TypeManager.object_type;
}
public override GenericParameterAttributes Attributes {
get { return attrs; }
}
public override Type ClassConstraint {
get { return class_constraint; }
}
public override Type EffectiveBaseClass {
get { return base_type; }
}
public override Type[] InterfaceConstraints {
get { return iface_constraints; }
}
}
class PtrHashtable : Hashtable {
sealed class PtrComparer : IComparer {
private PtrComparer () {}
public static PtrComparer Instance = new PtrComparer ();
public int Compare (object x, object y)
{
if (x == y)
return 0;
else
return 1;
}
}
public PtrHashtable ()
{
comparer = PtrComparer.Instance;
}
}
/*
* Hashtable whose keys are character arrays with the same length
*/
class CharArrayHashtable : Hashtable {
sealed class ArrComparer : IComparer {
private int len;
public ArrComparer (int len) {
this.len = len;
}
public int Compare (object x, object y)
{
char[] a = (char[])x;
char[] b = (char[])y;
for (int i = 0; i < len; ++i)
if (a [i] != b [i])
return 1;
return 0;
}
}
private int len;
protected override int GetHash (Object key)
{
char[] arr = (char[])key;
int h = 0;
for (int i = 0; i < len; ++i)
h = (h << 5) - h + arr [i];
return h;
}
public CharArrayHashtable (int len)
{
this.len = len;
comparer = new ArrComparer (len);
}
}
struct Pair {
public object First;
public object Second;
public Pair (object f, object s)
{
First = f;
Second = s;
}
}
/// <summary>
/// This is a wrapper around StreamReader which is seekable.
/// </summary>
public class SeekableStreamReader
{
public SeekableStreamReader (StreamReader reader)
{
this.reader = reader;
this.buffer = new char [DefaultCacheSize];
// Compute the preamble size
// Let the StreamWriter autodetect the encoder
reader.Peek ();
reader.BaseStream.Position = 0;
Encoding enc = reader.CurrentEncoding;
// First of all, get at least a char
byte[] auxb = new byte [50];
int num_bytes = 0;
int num_chars = 0;
int br = 0;
do {
br = reader.BaseStream.Read (auxb, num_bytes, auxb.Length - num_bytes);
num_bytes += br;
num_chars = enc.GetCharCount (auxb, 0, num_bytes);
}
while (num_chars == 0 && br > 0);
if (num_chars != 0)
{
// Now, check which bytes at the beginning have no effect in the
// char count
int p = 0;
while (enc.GetCharCount (auxb, p, num_bytes-p) >= num_chars)
p++;
preamble_size = p - 1;
reader.BaseStream.Position = 0;
reader.DiscardBufferedData ();
buffer_start = preamble_size;
}
}
public SeekableStreamReader (Stream stream, Encoding encoding, bool detect_encoding_from_bytemarks)
: this (new StreamReader (stream, encoding, detect_encoding_from_bytemarks))
{ }
StreamReader reader;
private const int DefaultCacheSize = 1024;
char[] buffer;
int buffer_start; // in bytes
int buffer_size; // in bytes
int char_count; // count buffer[] valid characters
int pos; // index into buffer[]
int preamble_size;
/// <remarks>
/// The difference to the StreamReader's BaseStream.Position is that this one is reliable; ie. it
// always reports the correct position and if it's modified, it also takes care of the buffered data.
/// </remarks>
public int Position {
get {
return buffer_start + reader.CurrentEncoding.GetByteCount (buffer, 0, pos);
}
set {
// This one is easy: we're modifying the position within our current
// buffer.
if ((value >= buffer_start) && (value < buffer_start + buffer_size)) {
int byte_offset = value - buffer_start;
pos = byte_offset;
// encoded characters can take more than 1 byte length
while (reader.CurrentEncoding.GetByteCount (buffer, 0, pos) > byte_offset)
pos--;
return;
}
if (value == 0) // Skip preamble
value = preamble_size;
// Ok, now we need to seek.
reader.DiscardBufferedData ();
reader.BaseStream.Position = buffer_start = value;
char_count = buffer_size = pos = 0;
}
}
private bool ReadBuffer ()
{
pos = 0;
buffer_start += buffer_size;
char_count = reader.Read (buffer, 0, buffer.Length);
buffer_size = reader.CurrentEncoding.GetByteCount (buffer, 0, char_count);
return buffer_size > 0;
}
public int Peek ()
{
if ((pos >= char_count) && !ReadBuffer ())
return -1;
return buffer [pos];
}
public int Read ()
{
if ((pos >= char_count) && !ReadBuffer ())
return -1;
return buffer [pos++];
}
}
public class DoubleHash {
const int DEFAULT_INITIAL_BUCKETS = 100;
public DoubleHash () : this (DEFAULT_INITIAL_BUCKETS) {}
public DoubleHash (int size)
{
count = size;
buckets = new Entry [size];
}
int count;
Entry [] buckets;
int size = 0;
class Entry {
public object key1;
public object key2;
public int hash;
public object value;
public Entry next;
public Entry (object key1, object key2, int hash, object value, Entry next)
{
this.key1 = key1;
this.key2 = key2;
this.hash = hash;
this.next = next;
this.value = value;
}
}
public bool Lookup (object a, object b, out object res)
{
int h = (a.GetHashCode () ^ b.GetHashCode ()) & 0x7FFFFFFF;
for (Entry e = buckets [h % count]; e != null; e = e.next) {
if (e.hash == h && e.key1.Equals (a) && e.key2.Equals (b)) {
res = e.value;
return true;
}
}
res = null;
return false;
}
public void Insert (object a, object b, object value)
{
// Is it an existing one?
int h = (a.GetHashCode () ^ b.GetHashCode ()) & 0x7FFFFFFF;
for (Entry e = buckets [h % count]; e != null; e = e.next) {
if (e.hash == h && e.key1.Equals (a) && e.key2.Equals (b))
e.value = value;
}
int bucket = h % count;
buckets [bucket] = new Entry (a, b, h, value, buckets [bucket]);
// Grow whenever we double in size
if (size++ == count) {
count <<= 1;
count ++;
Entry [] newBuckets = new Entry [count];
foreach (Entry root in buckets) {
Entry e = root;
while (e != null) {
int newLoc = e.hash % count;
Entry n = e.next;
e.next = newBuckets [newLoc];
newBuckets [newLoc] = e;
e = n;
}
}
buckets = newBuckets;
}
}
}
}
-91
View File
@@ -1,91 +0,0 @@
//
// symbolwriter.cs: The symbol writer
//
// Author:
// Martin Baulig ([email protected])
//
// (C) 2003 Ximian, Inc.
//
using System;
using System.Collections;
using System.Reflection;
using System.Reflection.Emit;
using Mono.CompilerServices.SymbolWriter;
namespace Mono.CSharp {
public class SymbolWriter : MonoSymbolWriter {
delegate int GetILOffsetFunc (ILGenerator ig);
delegate Guid GetGuidFunc (ModuleBuilder mb);
GetILOffsetFunc get_il_offset_func;
GetGuidFunc get_guid_func;
ModuleBuilder module_builder;
protected SymbolWriter (ModuleBuilder module_builder, string filename)
: base (filename)
{
this.module_builder = module_builder;
}
bool Initialize ()
{
MethodInfo mi = typeof (ILGenerator).GetMethod (
"Mono_GetCurrentOffset",
BindingFlags.Static | BindingFlags.NonPublic);
if (mi == null)
return false;
get_il_offset_func = (GetILOffsetFunc) System.Delegate.CreateDelegate (
typeof (GetILOffsetFunc), mi);
mi = typeof (ModuleBuilder).GetMethod (
"Mono_GetGuid",
BindingFlags.Static | BindingFlags.NonPublic);
if (mi == null)
return false;
get_guid_func = (GetGuidFunc) System.Delegate.CreateDelegate (
typeof (GetGuidFunc), mi);
Location.DefineSymbolDocuments (this);
Namespace.DefineNamespaces (this);
return true;
}
public void DefineLocalVariable (string name, LocalBuilder builder)
{
SignatureHelper sighelper = SignatureHelper.GetLocalVarSigHelper (
module_builder);
sighelper.AddArgument (builder.LocalType);
byte[] signature = sighelper.GetSignature ();
DefineLocalVariable (name, signature);
}
public void MarkSequencePoint (ILGenerator ig, int row, int column)
{
int offset = get_il_offset_func (ig);
MarkSequencePoint (offset, row, column);
}
public void WriteSymbolFile ()
{
Guid guid = get_guid_func (module_builder);
WriteSymbolFile (guid);
}
public static SymbolWriter GetSymbolWriter (ModuleBuilder module,
string filename)
{
SymbolWriter writer = new SymbolWriter (module, filename);
if (!writer.Initialize ())
return null;
return writer;
}
}
}
-128
View File
@@ -1,128 +0,0 @@
//
// tree.cs: keeps a tree representation of the generated code
//
// Author: Miguel de Icaza ([email protected])
//
// Licensed under the terms of the GNU GPL
//
// (C) 2001 Ximian, Inc (http://www.ximian.com)
//
//
using System;
using System.Collections;
using System.Reflection;
using System.Reflection.Emit;
using System.IO;
namespace Mono.CSharp
{
public interface ITreeDump {
int Dump (Tree tree, StreamWriter output);
void ParseOptions (string options);
}
// <summary>
//
// We store here all the toplevel types that we have parsed,
// this is the root of all information we have parsed.
//
// </summary>
public class Tree {
TypeContainer root_types;
// <summary>
// Keeps track of all the types definied (classes, structs, ifaces, enums)
// </summary>
Hashtable decls;
public Tree ()
{
root_types = new RootTypes ();
decls = new Hashtable ();
}
DoubleHash decl_ns_name = new DoubleHash ();
public void RecordDecl (string name, DeclSpace ds)
{
DeclSpace other = (DeclSpace) decls [name];
if (other != null){
PartialContainer other_pc = other as PartialContainer;
if ((ds is TypeContainer) && (other_pc != null)) {
Report.Error (
260, ds.Location, "Missing partial modifier " +
"on declaration of type `{0}'; another " +
"partial implementation of this type exists",
name);
Report.LocationOfPreviousError (other.Location);
return;
}
Report.SymbolRelatedToPreviousError (
other.Location, other.GetSignatureForError ());
Report.Error (
101, ds.Location,
"There is already a definition for `" + name + "'");
return;
}
ds.RecordDecl ();
int p = name.LastIndexOf ('.');
if (p == -1)
decl_ns_name.Insert ("", name, ds);
else {
decl_ns_name.Insert (name.Substring (0, p), name.Substring (p+1), ds);
}
decls.Add (name, ds);
}
public DeclSpace LookupByNamespace (string ns, string name)
{
object res;
decl_ns_name.Lookup (ns, name, out res);
return (DeclSpace) res;
}
//
// FIXME: Why are we using Types?
//
public TypeContainer Types {
get {
return root_types;
}
}
public Hashtable Decls {
get {
return decls;
}
}
}
public class RootTypes : TypeContainer
{
public RootTypes ()
: base (null, null, MemberName.Null, null, Kind.Root,
new Location (-1))
{ }
public override void Register ()
{
throw new InvalidOperationException ();
}
public override PendingImplementation GetPendingImplementations ()
{
throw new InvalidOperationException ();
}
}
}
File diff suppressed because it is too large. Load diff
-16
View File
@@ -1,19 +1,3 @@
2004-08-30 Zoltan Varga <[email protected]>
* amd64/amd64-codegen.h (amd64_imul_reg_membase_size): Fix REX
generation.
2004-08-29 Zoltan Varga <[email protected]>
* amd64/amd64-codegen.h: More SSE work.
* amd64/amd64-codegen.h: Add SSE2 instructions.
2004-08-21 Zoltan Varga <[email protected]>
* amd64/amd64-codegen.h (X86_IS_BYTE_REG): Redefine X86_IS_BYTE_REG
since under amd64, all 16 registers have a low part.
2004-08-16 Zoltan Varga <[email protected]>
* x86/x86-codegen.h: Add macros for accessing the mod/rm byte.
+3 -73
View File
@@ -74,7 +74,7 @@ typedef enum
#define AMD64_IS_CALLEE_SAVED_REG(reg) (AMD64_CALLEE_SAVED_REGS & (1 << (reg)))
#define AMD64_REX(bits) ((unsigned char)(0x40 | (bits)))
#define amd64_emit_rex(inst, width, reg_modrm, reg_index, reg_rm_base_opcode) do \
#define amd64_emit_rex(inst, width, reg_modrm, reg_index, reg_rm_base_opcode) \
{ \
unsigned char _amd64_rex_bits = \
(((width) > 4) ? AMD64_REX_W : 0) | \
@@ -82,7 +82,7 @@ typedef enum
(((reg_index) > 7) ? AMD64_REX_X : 0) | \
(((reg_rm_base_opcode) > 7) ? AMD64_REX_B : 0); \
if (_amd64_rex_bits != 0) *(inst)++ = AMD64_REX(_amd64_rex_bits); \
} while (0)
}
typedef union {
long val;
@@ -91,8 +91,6 @@ typedef union {
#include "../x86/x86-codegen.h"
#undef X86_IS_BYTE_REG
#define X86_IS_BYTE_REG(reg) 1
/* Need to fill this info in for amd64. */
@@ -488,74 +486,6 @@ typedef union {
amd64_membase_emit ((inst), 0, (basereg), (disp)); \
} while (0)
/*
* SSE
*/
#define emit_opcode3(inst,op1,op2,op3) do { \
*(inst)++ = (unsigned char)(op1); \
*(inst)++ = (unsigned char)(op2); \
*(inst)++ = (unsigned char)(op3); \
} while (0)
#define emit_sse_reg_reg_size(inst,dreg,reg,op1,op2,op3,size) do { \
*(inst)++ = (unsigned char)(op1); \
amd64_emit_rex ((inst), size, (dreg), 0, (reg)); \
*(inst)++ = (unsigned char)(op2); \
*(inst)++ = (unsigned char)(op3); \
x86_reg_emit ((inst), (dreg), (reg)); \
} while (0)
#define emit_sse_reg_reg(inst,dreg,reg,op1,op2,op3) emit_sse_reg_reg_size ((inst), (dreg), (reg), (op1), (op2), (op3), 0)
#define emit_sse_membase_reg(inst,basereg,disp,reg,op1,op2,op3) do { \
*(inst)++ = (unsigned char)(op1); \
amd64_emit_rex ((inst), 0, (reg), 0, (basereg)); \
*(inst)++ = (unsigned char)(op2); \
*(inst)++ = (unsigned char)(op3); \
amd64_membase_emit ((inst), (reg), (basereg), (disp)); \
} while (0)
#define emit_sse_reg_membase(inst,dreg,basereg,disp,op1,op2,op3) do { \
*(inst)++ = (unsigned char)(op1); \
amd64_emit_rex ((inst), 0, (dreg), 0, (basereg) == AMD64_RIP ? 0 : (basereg)); \
*(inst)++ = (unsigned char)(op2); \
*(inst)++ = (unsigned char)(op3); \
amd64_membase_emit ((inst), (dreg), (basereg), (disp)); \
} while (0)
#define amd64_sse_xorpd_reg_reg(inst,dreg,reg) emit_sse_reg_reg ((inst),(dreg),(reg), 0x66, 0x0f, 0x57)
#define amd64_sse_xorpd_reg_membase(inst,dreg,basereg,disp) emit_sse_reg_membase ((inst),(dreg),(basereg), (disp), 0x66, 0x0f, 0x57)
#define amd64_sse_movsd_reg_reg(inst,dreg,reg) emit_sse_reg_reg ((inst), (dreg), (reg), 0xf2, 0x0f, 0x10)
#define amd64_sse_movsd_reg_membase(inst,dreg,basereg,disp) emit_sse_reg_membase ((inst), (dreg), (basereg), (disp), 0xf2, 0x0f, 0x10)
#define amd64_sse_movsd_membase_reg(inst,basereg,disp,reg) emit_sse_membase_reg ((inst), (basereg), (disp), (reg), 0xf2, 0x0f, 0x11)
#define amd64_sse_movss_membase_reg(inst,basereg,disp,reg) emit_sse_membase_reg ((inst), (basereg), (disp), (reg), 0xf3, 0x0f, 0x11)
#define amd64_sse_movss_reg_membase(inst,dreg,basereg,disp) emit_sse_reg_membase ((inst), (dreg), (basereg), (disp), 0xf3, 0x0f, 0x10)
#define amd64_sse_comisd_reg_reg(inst,dreg,reg) emit_sse_reg_reg ((inst),(dreg),(reg),0x66,0x0f,0x2f)
#define amd64_sse_cvtsd2si_reg_reg(inst,dreg,reg) emit_sse_reg_reg_size ((inst), (dreg), (reg), 0xf2, 0x0f, 0x2d, 0)
#define amd64_sse_cvtsi2sd_reg_reg(inst,dreg,reg) emit_sse_reg_reg_size ((inst), (dreg), (reg), 0xf2, 0x0f, 0x2a, 8)
#define amd64_sse_cvtsd2ss_reg_reg(inst,dreg,reg) emit_sse_reg_reg ((inst), (dreg), (reg), 0xf2, 0x0f, 0x5a)
#define amd64_sse_cvtss2sd_reg_reg(inst,dreg,reg) emit_sse_reg_reg ((inst), (dreg), (reg), 0xf3, 0x0f, 0x5a)
#define amd64_sse_addsd_reg_reg(inst,dreg,reg) emit_sse_reg_reg ((inst), (dreg), (reg), 0xf2, 0x0f, 0x58)
#define amd64_sse_subsd_reg_reg(inst,dreg,reg) emit_sse_reg_reg ((inst), (dreg), (reg), 0xf2, 0x0f, 0x5c)
#define amd64_sse_mulsd_reg_reg(inst,dreg,reg) emit_sse_reg_reg ((inst), (dreg), (reg), 0xf2, 0x0f, 0x59)
#define amd64_sse_divsd_reg_reg(inst,dreg,reg) emit_sse_reg_reg ((inst), (dreg), (reg), 0xf2, 0x0f, 0x5e)
/* Generated from x86-codegen.h */
#define amd64_breakpoint_size(inst,size) do { amd64_emit_rex ((inst),(size),0,0,0); x86_breakpoint(inst); } while (0)
@@ -617,7 +547,7 @@ typedef union {
#define amd64_mul_membase_size(inst,basereg,disp,is_signed,size) do { amd64_emit_rex ((inst),(size),0,0,(basereg)); x86_mul_membase((inst),((basereg)&0x7),(disp),(is_signed)); } while (0)
#define amd64_imul_reg_reg_size(inst,dreg,reg,size) do { amd64_emit_rex ((inst),(size),(dreg),0,(reg)); x86_imul_reg_reg((inst),((dreg)&0x7),((reg)&0x7)); } while (0)
#define amd64_imul_reg_mem_size(inst,reg,mem,size) do { amd64_emit_rex ((inst),(size),0,0,(reg)); x86_imul_reg_mem((inst),((reg)&0x7),(mem)); } while (0)
#define amd64_imul_reg_membase_size(inst,reg,basereg,disp,size) do { amd64_emit_rex ((inst),(size),(reg),0,(basereg)); x86_imul_reg_membase((inst),((reg)&0x7),((basereg)&0x7),(disp)); } while (0)
#define amd64_imul_reg_membase_size(inst,reg,basereg,disp,size) do { amd64_emit_rex ((inst),(size),0,0,(basereg)); x86_imul_reg_membase((inst),((reg)&0x7),((basereg)&0x7),(disp)); } while (0)
#define amd64_imul_reg_reg_imm_size(inst,dreg,reg,imm,size) do { amd64_emit_rex ((inst),(size),(dreg),0,(reg)); x86_imul_reg_reg_imm((inst),((dreg)&0x7),((reg)&0x7),(imm)); } while (0)
#define amd64_imul_reg_mem_imm_size(inst,reg,mem,imm,size) do { amd64_emit_rex ((inst),(size),0,0,(reg)); x86_imul_reg_mem_imm((inst),((reg)&0x7),(mem),(imm)); } while (0)
#define amd64_imul_reg_membase_imm_size(inst,reg,basereg,disp,imm,size) do { amd64_emit_rex ((inst),(size),(reg),0,(basereg)); x86_imul_reg_membase_imm((inst),((reg)&0x7),((basereg)&0x7),(disp),(imm)); } while (0)
Loaded 100 of 290 files, more files were not shown because too many files have changed in this diff. Show more