Compare commits

..
1 Commits
Author SHA1 Message Date
nobody 0ed4ed7b6a This commit was manufactured by cvs2svn to create tag 'MONO_BETA2'.
svn path=/tags/MONO_BETA2/mcs/; revision=28524
2004-05-31 02:31:16 +00:00
430 changed files with 80661 additions and 93114 deletions

No files matched your search

-2
View File
@@ -21,5 +21,3 @@ autom4te.cache
mint.pc
stamp-h1
config.h.in
_tmpinst
tmpinst-dir.stamp
-248
View File
@@ -1,251 +1,3 @@
2004-08-14 Zoltan Varga <[email protected]>
* configure.in (HAVE_KW_THREAD): Pass USE_COMPILER_TLS to libgc if
__thread works.
2004-08-11 Zoltan Varga <[email protected]>
* configure.in: Fix __thread test.
2004-08-07 Zoltan Varga <[email protected]>
* configure.in: Add proper checks for the 'undefined reference to '__tls_get_addr' problem.
2004-08-06 Geoff Norton <[email protected]>
* configure.in: Add a kqueue check
2004-08-03 Neale Ferguson <[email protected]>
* configure.in: Enable S/390 64-bit JIT.
2004-07-31 Zoltan Varga <[email protected]>
* configure.in: Enable AMD64 JIT.
2004-07-30 Martin Baulig <[email protected]>
* Makefile.am: The symbol writer is now called
Mono.CompilerServices.SymbolWriter.dll.
2004-07-30 Raja R Harinath <[email protected]>
* runtime/Makefile.am (monoone_DATA): Add mcs.exe.config.
(gmcs_exe): Add gmcs.exe.config.
($(monoone_DATA) $(monotwo_DATA) ...): Add location of the .config
files too.
2004-07-29 Lluis Sanchez Gual <[email protected]>
* Makefile.am: Copy machine.config in the correct _tmpinst subdirectory.
2004-07-28 Lluis Sanchez Gual <[email protected]>
* configure.in: Added data/net_1_1 and data/net_2_0 to the build.
* data/Makefile.am: Removed installation of machine.config and
DefaultWsdlHelpGenerator.aspx. Those now are in a version-specific
directory.
* data/net_1_1/Makefile.am, data/net_2_0/Makefile.am: new makefiles for
installing 1.1 and 2.0 makefiles.
* runtime/net_1_1/Makefile.am, runtime/net_2_0/Makefile.am: Install mscorlib
at the correct version specific directory.
2004-07-27 John Merryweather Cooper <[email protected]>
* configure.in: Disable __thread test (TLS) for FreeBSD as
it succeeds on FreeBSD 5.x when it should fail. Fix pthread
library detection for FreeBSD 4.x since pthread is embedded
in libc_r on this platform. Fix some typos in my host
regexes for freebsd.
2004-07-23 Dick Porter <[email protected]>
* configure.in: Changes for FreeBSD thread support by John
Merryweather Cooper <[email protected]>.
2004-07-15 Jackson Harper <[email protected]>
* man/gacutil.1: MONO_GAC_PREFIX not MONO_GAC_PATH
2004-07-12 Massimiliano Mantione <[email protected]>
* docs/abc-removal.txt: Updated documentation for ABC removal.
2004-07-12 Massimiliano Mantione <[email protected]>
* mono/mini/abcremoval.c: Rewritten most of ABC removal.
* mono/mini/abcremoval.h: Rewritten most of ABC removal.
* mono/mini/build_relations_propagation_table.pl: Deleted (unneeded after the rewrite).
* mono/mini/propagated_relations_table.def: Deleted (unneeded after the rewrite).
2004-07-03 Zoltan Varga <[email protected]>
* configure.in: Add --with-tls option to replace the misnamed
--with-nptl option.
2004-07-02 Raja R Harinath <[email protected]>
* Makefile.am (mcs-do-basic-build, mcs-do-short-build):
Pass NO_SIGN_ASSEMBLY=yes to sub-make.
($(tmpinst)/bin/mono) [PLATFORM_WIN32]: Make it work.
2004-07-02 Zoltan Varga <[email protected]>
* man/mono.1: Added 'aot' to trace options.
2004-06-30 Zoltan Varga <[email protected]>
* configure.in: Fix trunc check + add SPARC64 defines.
2004-06-29 Jackson Harper <[email protected]>
* man/gacutil.1: Update man with new command line options.
2004-06-29 Raja R Harinath <[email protected]>
Atsushi Enomoto <[email protected]>
* runtime/net_1_1/Makefile.am (GAC_ROOT_DIR): Renamed from GAC_DIR.
(GAC_DIR): New define that doesn't include $(DESTDIR).
(install-data-local,uninstall-local): Use them. Use in-tree mono
runtime, not the installed one.
2004-06-29 Raja R Harinath <[email protected]>
* runtime/Makefile.am (gmcs_exe): New. Set only if not W32.
(monotwo_DATA): Use it.
From Atsushi Enomoto.
2004-06-24 Raja R Harinath <[email protected]>
* runtime/net_2_0/Makefile.am (gac_assemblies_list): Put back
ICSharpCode.SharpZipLib, not that it has a different version.
2004-06-24 Raja R Harinath <[email protected]>
* Makefile.am (MCS_DIRS, MCS_FILES): Add back Mono.CSharp.Debugger.
(tmpinst-dir-contents, $(tmpinst)/bin/mono.bat): Remove mono.bat
in W32. Use 'mono' and 'mcs' in W32 too.
(bootstrap) [PLATFORM_WIN32]: Back to single stage bootstrap.
* runtime/net_2_0/Makefile.am (gac_assemblies_list): Don't mention
nunit.*, IBM.Data.DB2, ICSharpCode.SharpZipLib.
Fix for #60443, the GAC .DLL-Hell.
2004-06-22 Raja R Harinath <[email protected]>
* Makefile.am (bootstrap) [PLATFORM_WIN32]: Make two-stage.
2004-06-18 Jackson Harper <[email protected]>
* man/mono.1: Add MONO_LOG_LEVEL and MONO_LOG_MASK. Add
instructions on setting multiple mask values.
Fri Jun 18 19:39:09 CEST 2004 Paolo Molaro <[email protected]>
* Makefile.am: process data before runtime, so the config file is
installed and gacutil has a chance to work (finding symlink).
2004-06-18 Raja R Harinath <[email protected]>
* runtime/Makefile.am ($(monoone_DATA) $(monotwo_DATA) $(monobins_DATA)):
Test if files exist in the mcs/ tree before creating symlinks.
Remove symlinks before creating them again.
* runtime/net_1_1/Makefile.am (mscorlib.dll $(gac_assemblies)): Likewise.
* runtime/net_2_0/Makefile.am (mscorlib.dll $(gac_assemblies)): Likewise.
2004-06-18 Raja R Harinath <[email protected]>
* scripts/Makefile.am (REWRITE): New. Common rewriting 'sed' command.
(bin_SCRIPTS): Unify all the script generating rules into one.
2004-06-16 Raja R Harinath <[email protected]>
* Makefile.am (bootstrap) [PLATFORM_WIN32]: Open code. Don't
build and populate net_2_0 profile.
(populate-runtime-subdir): Make into subroutine that takes list of
profiles to populate.
(faststrap): Update.
(MCS_DIRS, MCS_FILES, MONO_CSHARP_DEBUGGER_DIR, MONO_CSHARP_DEBUGGER_FILE):
Avoid automake conditional/+= problems.
(populate-runtime-subdir): Rewrite sanity check.
2004-06-16 Raja R Harinath <[email protected]>
Include prototype completely-untested 'make bootstrap' support for W32.
* Makefile.am (bootstrap): Define to fasterstrap for W32.
(MCS_DIRS, MCS_FILES): Don't refer to Mono.CSharp.Debugger in W32.
(tmpinst-dir): Change sub-make invoke to ...
(tmpinst-dir-contents): ... this. Build 'mono.bat' in W32 instead
of 'mono' and 'mcs'.
($(tmpinst)/bin/mono.bat): New.
2004-06-15 Dick Porter <[email protected]>
* configure.in: Check for struct ip_mreqn and struct ip_mreq on
windows too. Fixes bug 55040.
Mon Jun 14 18:38:34 CEST 2004 Paolo Molaro <[email protected]>
* configure.in: better explain that --with-nptl is not related to
NPTL, but to __thread support. Set sigaltstack support to off by
default.
2004-06-12 Raja R Harinath <[email protected]>
* Makefile.am (populate-runtime-subdir): Add _tmpinst directory
to the PATH.
2004-06-11 Jackson Harper <[email protected]>
* runtime/net_2_0/Makefile.am:
* runtime/net_1_1/Makefile.am: Remove signing patches
2004-06-11 Jackson Harper <[email protected]>
* man/mono.1: Add documentation for MONO_GAC_PREFIX.
* runtime/net_2_0/Makefile.am:
* runtime/net_1_1/Makefile.am: Sign assemblies before
installing. Do not sign ziplib, npgsql, or nunit assemblies. Sign mscorlib.
2004-06-11 Raja R Harinath <[email protected]>
* Makefile.am (populate-runtime-subdir): New target. Does a
controlled "make install" in the 'mcs/' directory to populate the
'runtime' directory.
(fasterstrap): Use it.
2004-06-10 Raja R Harinath <[email protected]>
* runtime/Makefile.am ($(monoone_DATA),$(monotwo_DATA),$(monobins_DATA)):
Don't copy from prefix. Use $(LN_S) to point to the mcs/ tree.
* runtime/net_1_1/Makefile.am (mscorlib.dll,$(gac_assemblies)):
Use $(LN_S) to point to the mcs/ tree, rather than copying.
* runtime/net_2_0/Makefile.am (mscorlib.dll,$(gac_assemblies)): Likewise.
2004-06-10 Raja R Harinath <[email protected]>
Support the new assembly signing setup in mcs/.
* Makefile.am (mcs-do-basic-build): Pass 'USE_BOOT_COMPILE' to sub-makes.
($(tmpinst)/etc/mono/machine.config): New target.
(tmpinst-dir.stamp): Remove and rewrite into ...
($(tmpinst)/bin/mcs): ... this and ...
($(tmpinst)/bin/mono): ... this. Update to use the in-tree machine.config.
(tmpinst-dir): Rewrite to invoke above $(tmpinst)/... targets directly.
* configure.in (AC_PROG_LN_S): New check to define $(LN_S).
Thu Jun 3 14:39:17 CEST 2004 Paolo Molaro <[email protected]>
* configure.in: libc setting for NetBSD (patch from [email protected]).
2004-06-01 Raja R Harinath <[email protected]>
* Makefile.am (bootstrap,faststrap,fasterstrap): Refactor.
Fix 'faststrap' to be corlib-version-change-safe.
(one-stage-strap,two-stage-strap,three-stage-strap): Remove.
(monolite-bootstrap): Update.
2004-05-31 Gonzalo Paniagua Javier <[email protected]>
* configure.in: fixlets for windows.
2004-05-29 Zoltan Varga <[email protected]>
* configure.in: export CC instead of passing it to libgc/configure.
+82 -128
View File
@@ -1,11 +1,10 @@
AUTOMAKE_OPTIONS = foreign
ACLOCAL_AMFLAGS = -I .
SUBDIRS = $(libgc_dir) mono $(ikvm_jni_dir) docs data runtime scripts man samples support web
SUBDIRS = @libgc_dir@ mono @ikvm_jni_dir@ docs runtime scripts man data samples support web
# Keep in sync with SUBDIRS
## 'tools' is not normally built
DIST_SUBDIRS = libgc mono ikvm-jni docs data runtime scripts man samples support web tools
DIST_SUBDIRS = libgc mono ikvm-jni docs runtime scripts man data samples support web tools
EXTRA_DIST= mono.pc.in mono.spec.in mint.pc.in
@@ -18,17 +17,16 @@ endif
DISTCLEANFILES= mono.pc mint.pc
#
# The following targets are used to compile and install
# The following target is used to compile and install
# mono and mcs without running into the out-of-sync
# 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
.PHONY: populate-runtime-subdir
.PHONY: tmpinst-dir tmpinst-basic-build tmpinst-short-build tmpinst-full-build
.PHONY: bootstrap faststrap fasterstrap one-stage-strap two-stage-strap three-stage-strap bootstrap-clean bootstrap-check
.PHONY: mono-do-basic-build mcs-do-basic-build mcs-do-short-build mcs-do-full-build mcs-do-clean-profiles mcs-do-run-test
if USE_JIT
mono_runtime = mono/mini/mono
@@ -36,100 +34,74 @@ else
mono_runtime = mono/interpreter/mint
endif
# Minimal set of directories to build, and files used to run the 'mcs' compiler
MCS_BASIC_DIRS = jay mcs class/corlib class/System
MCS_BASIC_FILES = \
$(mcs_topdir)/mcs/mcs.exe \
$(mcs_topdir)/class/lib/default/mscorlib.dll \
$(mcs_topdir)/class/lib/default/System.dll
bootstrap: three-stage-strap
# Set of directories and files the 'mcs' compiler can use
## We build class/System twice to resolve the cyclic dependency of class/System.XML
MCS_DIRS = $(MCS_BASIC_DIRS) class/System.XML class/System class/Mono.CSharp.Debugger
MCS_FILES = $(MCS_BASIC_FILES) \
$(mcs_topdir)/class/lib/default/System.Xml.dll \
$(mcs_topdir)/class/lib/default/Mono.CompilerServices.SymbolWriter.dll
faststrap: mono-do-basic-build
$(MAKE) two-stage-strap
tmpinst = _tmpinst
fasterstrap: mono-do-basic-build
$(MAKE) one-stage-strap
if PLATFORM_WIN32
three-stage-strap: tmpinst-basic-build
$(MAKE) two-stage-strap
populate_profiles = default:net_1_1
two-stage-strap: tmpinst-short-build
$(MAKE) one-stage-strap
# bootstraps using the .NET C# compiler
bootstrap: tmpinst-dir mono-do-runtime-only
$(MAKE) fasterstrap
else
populate_profiles = default:net_1_1 net_2_0:net_2_0
bootstrap: tmpinst-mcs-basic-build mono-do-runtime-only
$(MAKE) tmpinst-mcs-short-build
$(MAKE) fasterstrap
endif
faststrap: tmpinst-mcs-short-build
$(MAKE) mono-do-runtime-only
$(MAKE) fasterstrap
fasterstrap: tmpinst-mcs-full-build
$(MAKE) populate-runtime-subdir
one-stage-strap: tmpinst-full-build
rm -f $(top_srcdir)/runtime/*/*.dll $(top_srcdir)/runtime/*.exe
$(MAKE)
bootstrap-clean: clean mcs-do-clean-profiles
bootstrap-check: check mcs-do-run-test
# building with monolite
# (takes advantage of 'make -j': independent subtasks are separate dependencies)
tmpinst-basic-build: mcs-do-basic-build mono-do-basic-build tmpinst-dir
mv -f $(mcs_topdir)/mcs/mcs.exe \
$(mcs_topdir)/class/lib/default/mscorlib.dll \
$(mcs_topdir)/class/lib/default/System.dll \
_tmpinst/lib
get-monolite-latest:
wget -O $(srcdir)/../monolite-latest.tar.gz http://www.go-mono.com/daily/monolite-latest.tar.gz
tmpinst-short-build: mcs-do-short-build
mv -f $(mcs_topdir)/mcs/mcs.exe \
$(mcs_topdir)/class/lib/default/mscorlib.dll \
$(mcs_topdir)/class/lib/default/System.dll \
$(mcs_topdir)/class/lib/default/System.Xml.dll \
$(mcs_topdir)/class/lib/default/Mono.CSharp.Debugger.dll \
_tmpinst/lib
monolite-bootstrap: tmpinst-monolite mono-do-runtime-only
rm -f $(MCS_FILES)
$(MAKE) tmpinst-mcs-short-build
$(MAKE) fasterstrap
# internal targets
tmpinst-mcs-basic-build: mcs-do-basic-build tmpinst-dir
mv -f $(MCS_BASIC_FILES) $(tmpinst)/lib
tmpinst-mcs-short-build: mcs-do-short-build tmpinst-dir
mv -f $(MCS_FILES) $(tmpinst)/lib
tmpinst-mcs-full-build: mcs-do-full-build tmpinst-dir
cp -f $(MCS_FILES) $(tmpinst)/lib
tmpinst-monolite: tmpinst-dir
-rm -f $(tmpinst)/lib/mcs.exe $(tmpinst)/lib/*.dll
-rm -fr $(tmpinst)/monolite-*
srcdir=`cd $(srcdir) && pwd` && cd $(tmpinst) && ( gzip -d -c $$srcdir/../monolite-latest.tar.gz | tar xf - )
mv -f $(tmpinst)/monolite-*/mcs.exe $(tmpinst)/monolite-*/*.dll $(tmpinst)/lib
rm -fr $(tmpinst)/monolite-*
tmpinst-full-build: mcs-do-full-build
cp -f $(mcs_topdir)/mcs/mcs.exe \
$(mcs_topdir)/class/lib/default/mscorlib.dll \
$(mcs_topdir)/class/lib/default/System.dll \
$(mcs_topdir)/class/lib/default/System.Xml.dll \
$(mcs_topdir)/class/lib/default/Mono.CSharp.Debugger.dll \
_tmpinst/lib
# Build enough of 'mono' to run the stage1 mcs.exe
mono-do-runtime-only: $(CONFIG_HEADER)
for dir in $(libgc_dir) mono data; do \
(cd $$dir && $(MAKE)) || exit 1 ; \
done
mono-do-basic-build: $(CONFIG_HEADER)
if test -z "$(libgc_dir)"; then :; else cd libgc && $(MAKE) ; fi
cd mono && $(MAKE)
mcs-do-basic-build:
rm -f $(MCS_FILES)
for dir in $(MCS_BASIC_DIRS); do \
(cd $(mcs_topdir)/$$dir && $(MAKE) PROFILE=default NO_SIGN_ASSEMBLY=yes USE_BOOT_COMPILE=yes BOOTSTRAP_MCS="mcs -d:BOOTSTRAP_WITH_OLDLIB") || exit 1 ; \
done
# Build stripped down versions of 'mcs', 'mscorlib.dll' and 'System.dll' with installed 'mcs'
## remove System.Xml.dll since it's a soft-dependency of System.dll
mcs-do-basic-build:
rm -f $(mcs_topdir)/mcs/mcs.exe $(mcs_topdir)/class/lib/default/mscorlib.dll
rm -f $(mcs_topdir)/class/lib/default/System.dll $(mcs_topdir)/class/lib/default/System.Xml.dll
cd $(mcs_topdir)/jay && $(MAKE)
cd $(mcs_topdir)/mcs && $(MAKE) PROFILE=default BOOTSTRAP_MCS="mcs -d:BOOTSTRAP_WITH_OLDLIB"
cd $(mcs_topdir)/class/corlib && $(MAKE) PROFILE=default BOOTSTRAP_MCS="mcs -d:BOOTSTRAP_WITH_OLDLIB"
cd $(mcs_topdir)/class/System && $(MAKE) PROFILE=default BOOTSTRAP_MCS="mcs -d:BOOTSTRAP_WITH_OLDLIB"
mcs-do-short-build:
tmpinst=`cd $(tmpinst) && pwd` ; \
tmpinst=`cd _tmpinst && pwd` ; \
PATH=$$tmpinst/bin:$$PATH; export PATH ; \
for dir in $(MCS_DIRS); do \
(cd $(mcs_topdir)/$$dir && $(MAKE) PROFILE=default NO_SIGN_ASSEMBLY=yes) || exit 1 ; \
for dir in jay mcs class/corlib class/System class/System.XML class/System class/Mono.CSharp.Debugger; do \
(cd $(mcs_topdir)/$$dir && $(MAKE) PROFILE=default) || exit 1 ; \
done
mcs-do-full-build:
tmpinst=`cd $(tmpinst) && pwd` ; \
tmpinst=`cd _tmpinst && pwd` ; \
PATH=$$tmpinst/bin:$$PATH ; export PATH ; \
cd $(mcs_topdir) && $(MAKE) all-profiles
@@ -137,62 +109,44 @@ mcs-do-clean-profiles:
cd $(mcs_topdir) && $(MAKE) clean-profiles
mcs-do-run-test: tmpinst-dir
tmpinst=`cd $(tmpinst) && pwd` ; \
tmpinst=`cd _tmpinst && pwd` ; \
PATH=$$tmpinst/bin:$$PATH ; export PATH ; \
cd $(mcs_topdir) && $(MAKE) PROFILE=default run-test
populate-runtime-subdir:
test -n '$(populate_profiles)'
@srcdir=`cd $(srcdir) && pwd`; tmpinst=`pwd`/$(tmpinst) ; \
PATH=$$tmpinst/bin:$$PATH ; export PATH ; \
for profile in $(populate_profiles); do \
( set fnord `echo $$profile | sed 's,:, ,g'` && \
echo "cd $(mcs_topdir) && $(MAKE) PROGRAM_INSTALL_DIR=$$srcdir/runtime PROFILE=$$2 LIBRARY_INSTALL_DIR=$$srcdir/runtime/$$3 prefix=$$tmpinst/prefix install" && \
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 -path '*/jay*' -exec rm -f '{}' ';'
test -z "`find $(tmpinst)/prefix -type f -print`"
rm -rf $(tmpinst)/prefix
tmpinst-dir.stamp: Makefile.am
set -e ; \
rootme=`pwd`; tmpinst=$$rootme/_tmpinst ; \
mkdir -p $$tmpinst $$tmpinst/bin $$tmpinst/lib ; \
echo '#! /bin/sh' > $$tmpinst/bin/mono ; \
echo 'if test -z "$$MONO_PATH" ; then MONO_PATH="'"$$tmpinst/lib"'"' >> $$tmpinst/bin/mono ; \
echo 'else MONO_PATH=$${MONO_PATH}:"'"$$tmpinst/lib"'" ; fi' >> $$tmpinst/bin/mono ; \
echo 'export MONO_PATH' >> $$tmpinst/bin/mono ; \
echo 'exec "'"$$rootme/libtool"'" --mode=execute "'"$$rootme/$(mono_runtime)"'" "$$@"' >> $$tmpinst/bin/mono ; \
echo '#! /bin/sh' > $$tmpinst/bin/mcs ; \
echo 'exec "'"$$tmpinst/bin/mono"'" "'"$$tmpinst/lib/mcs.exe"'" "$$@"' >> $$tmpinst/bin/mcs ; \
chmod +x $$tmpinst/bin/mono $$tmpinst/bin/mcs
echo "stamp" > $@
tmpinst-dir:
mkdir -p $(tmpinst) $(tmpinst)/bin $(tmpinst)/lib $(tmpinst)/etc/mono/1.0
$(MAKE) tmpinst-dir-contents
tmpinst-dir: tmpinst-dir.stamp
@if test -d _tmpinst; then :; else rm -f tmpinst-dir.stamp; $(MAKE) tmpinst-dir.stamp; fi
tmpinst-dir-contents: $(tmpinst)/bin/mono $(tmpinst)/bin/mcs $(tmpinst)/etc/mono/1.0/machine.config
if PLATFORM_WIN32
# building with monolite
$(tmpinst)/bin/mono: $(srcdir)/Makefile.am
echo '#! /bin/sh' > $@
echo 'builddir="'`pwd`'"; win_builddir="'`cygpath -w -a .`'"' >> $@
echo 'tmpinst="$$win_builddir\\$(tmpinst)"' >> $@
echo 'if test -z "$$MONO_PATH" ; then MONO_PATH="$$tmpinst\\lib"; else MONO_PATH="$${MONO_PATH};$$tmpinst\\lib" ; fi' >> $@
echo 'MONO_CFG_DIR="$$tmpinst\\etc"' >> $@
echo 'export MONO_PATH MONO_CFG_DIR' >> $@
echo 'exec "$$builddir/libtool" --mode=execute "$$builddir/$(mono_runtime).exe" "$$@"' >> $@
chmod +x $@
get-monolite-latest:
wget -O $(srcdir)/../monolite-latest.tar.gz http://www.go-mono.com/daily/monolite-latest.tar.gz
else
tmpinst-monolite: tmpinst-dir
-rm -f _tmpinst/lib/mcs.exe _tmpinst/lib/*.dll
-rm -fr _tmpinst/monolite-*
srcdir=`cd $(srcdir) && pwd` && cd _tmpinst && ( gzip -d -c $$srcdir/../monolite-latest.tar.gz | tar xf - )
mv -f _tmpinst/monolite-*/mcs.exe _tmpinst/monolite-*/*.dll _tmpinst/lib
rm -fr _tmpinst/monolite-*
$(tmpinst)/bin/mono: $(srcdir)/Makefile.am
echo '#! /bin/sh' > $@
echo 'builddir="'`pwd`'"; tmpinst=$$builddir/$(tmpinst)' >> $@
echo 'if test -z "$$MONO_PATH" ; then MONO_PATH=$$tmpinst/lib; else MONO_PATH=$${MONO_PATH}:$$tmpinst/lib ; fi' >> $@
echo 'MONO_CFG_DIR=$$tmpinst/etc' >> $@
echo 'export MONO_PATH MONO_CFG_DIR' >> $@
echo 'exec "$$builddir/libtool" --mode=execute "$$builddir/$(mono_runtime)" --config "$$builddir/data/config" "$$@"' >> $@
chmod +x $@
endif
$(tmpinst)/bin/mcs: $(srcdir)/Makefile.am
(t=`cd $(tmpinst) && pwd`; echo '#! /bin/sh'; echo 'exec "'"$$t/bin/mono"'" "'"$$t/lib/mcs.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
monolite-bootstrap: tmpinst-monolite mono-do-basic-build
rm -f $(mcs_topdir)/mcs/mcs.exe $(mcs_topdir)/class/lib/default/mscorlib.dll
rm -f $(mcs_topdir)/class/lib/default/System.dll $(mcs_topdir)/class/lib/default/System.Xml.dll Mono.CSharp.Debugger.dll
$(MAKE) two-stage-strap
# Obsolete target -- don't use.
.PHONY: fullbuild
+22 -208
View File
@@ -1,11 +1,9 @@
AC_INIT(README)
AC_CANONICAL_SYSTEM
AM_CONFIG_HEADER(config.h)
AM_INIT_AUTOMAKE(mono,1.1.1)
AM_INIT_AUTOMAKE(mono,0.94)
AM_MAINTAINER_MODE
AC_PROG_LN_S
dnl
dnl libgc checks
dnl
@@ -52,10 +50,6 @@ case "$host" in
libdl=
libgc_threads=win32
gc_default=boehm
with_nptl=no
with_sigaltstack=no
LN_S=cp
;;
*-*-*netbsd*)
platform_win32=no
@@ -67,62 +61,7 @@ case "$host" in
libdl=
libgc_threads=no
;;
# these flags will work for all versions of -STABLE
#
*-*-*freebsd4*)
platform_win32=no
if test "x$PTHREAD_CFLAGS" = "x"; then
CPPFLAGS="$CPPFLAGS -D_THREAD_SAFE -DGC_FREEBSD_THREADS"
libmono_cflags="-D_THREAD_SAFE"
else
CPPFLAGS="$CPPFLAGS $PTHREAD_CFLAGS -DGC_FREEBSD_THREADS"
libmono_cflags="$PTHREAD_CFLAGS"
fi
if test "x$PTHREAD_LIBS" = "x"; then
LDFLAGS="$LDFLAGS -pthread"
libmono_ldflags="-pthread"
else
LDFLAGS="$LDFLAGS $PTHREAD_LIBS"
libmono_ldflags="$PTHREAD_LIBS"
fi
need_link_unlink=yes
AC_DEFINE(PTHREAD_POINTER_ID)
libdl=
libgc_threads=pthreads
# TLS isn't implemented at all on -STABLE
with_nptl=no
with_tls=pthread
;;
# older versions of -CURRENT will break with these flags but testing
# indicates these older versions won't run Mono anyway
#
*-*-*freebsd5*)
platform_win32=no
if test "x$PTHREAD_CFLAGS" = "x"; then
CPPFLAGS="$CPPFLAGS -DGC_FREEBSD_THREADS"
libmono_cflags=
else
CPPFLAGS="$CPPFLAGS $PTHREAD_CFLAGS -DGC_FREEBSD_THREADS"
libmono_cflags="$PTHREAD_CFLAGS"
fi
if test "x$PTHREAD_LIBS" = "x"; then
LDFLAGS="$LDFLAGS -lpthread"
libmono_ldflags="-lpthread"
else
LDFLAGS="$LDFLAGS $PTHREAD_LIBS"
libmono_ldflags="$PTHREAD_LIBS"
fi
need_link_unlink=yes
AC_DEFINE(PTHREAD_POINTER_ID)
libdl=
libgc_threads=pthreads
# TLS is only partially implemented on -CURRENT (compiler support
# but NOT library support)
#
with_nptl=no
with_tls=pthread
;;
*-*-*openbsd*)
*-*-*freebsd*|*-*-*openbsd*)
platform_win32=no
CPPFLAGS="$CPPFLAGS -D_THREAD_SAFE -DGC_FREEBSD_THREADS"
libmono_cflags="-D_THREAD_SAFE"
@@ -231,6 +170,9 @@ 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)
# for mono/mini/tramp-x86.c
AC_CHECK_HEADERS(valgrind/memcheck.h)
# for mono/metadata/debug-symfile.c
AC_CHECK_HEADERS(elf.h)
@@ -298,27 +240,14 @@ AC_SUBST(GMODULE_LIBS)
AC_ARG_WITH(gc, [ --with-gc=boehm,included,none],[gc=$with_gc],[gc=$gc_default])
# Enable support for fast thread-local storage
# Some systems have broken support, so we allow to disable it.
AC_ARG_WITH(tls, [ --with-tls=__thread,pthread select Thread Local Storage implementation],[],[with_tls=__thread])
# Kept for compatibility
AC_ARG_WITH(nptl, [ --with-nptl=yes,no deprecated, use --with-tls instead],[],[with_nptl=default])
if test "x$with_nptl" != "xdefault"; then
if test "x$with_nptl" = "xyes"; then
AC_MSG_WARN([--with-nptl=yes is deprecated, use --with-tls=__thread option instead.])
with_tls=__thread
fi
if test "x$with_nptl" = "xno"; then
AC_MSG_WARN([--with-nptl=no is deprecated, use --with-tls=pthread option instead.])
with_tls=pthread
fi
fi
# Enable support for NPTL only features like fast thread-local storage
# We can't reliably detect nptl at compile & run time
# so this option will stay until nptl becomes more widespread
AC_ARG_WITH(nptl, [ --with-nptl=yes,no enable/disable support for NPTL],[],[with_nptl=yes])
# Enable support for using sigaltstack for SIGSEGV and stack overflow handling
# This does not work on some platforms (bug #55253)
AC_ARG_WITH(sigaltstack, [ --with-sigaltstack=yes,no enable/disable support for sigaltstack],[],[with_sigaltstack=no])
AC_ARG_WITH(sigaltstack, [ --with-sigaltstack=yes,no enable/disable support for sigaltstack],[],[with_sigaltstack=yes])
# assembly bundle support, see metadata/make-bundle.pl for more info
AC_ARG_WITH(bundle, [ --with-bundle=bundle_template],[
@@ -463,7 +392,6 @@ if test x$platform_win32 = xno; then
AC_CHECK_FUNCS(getpwuid_r)
AC_CHECK_FUNCS(getresuid)
AC_CHECK_FUNCS(setresuid)
AC_CHECK_FUNCS(kqueue)
dnl ******************************************************************
dnl *** Check for large file support ***
@@ -706,17 +634,7 @@ if test x$platform_win32 = xno; then
dnl *****************************
dnl *** Checks for libpthread ***
dnl *****************************
# on FreeBSD -STABLE, the pthreads functions all reside in libc_r
# and libpthread does not exist
#
case "${host}" in
*-*-*freebsd4*)
AC_CHECK_LIB(pthread, main, LIBS="$LIBS -pthread")
;;
*)
AC_CHECK_LIB(pthread, main, LIBS="$LIBS -lpthread")
;;
esac
AC_CHECK_LIB(pthread, main, LIBS="$LIBS -lpthread")
AC_CHECK_HEADERS(pthread.h)
AC_CHECK_FUNCS(pthread_mutex_timedlock)
AC_CHECK_FUNCS(pthread_getattr_np pthread_attr_get_np)
@@ -737,7 +655,7 @@ if test x$platform_win32 = xno; then
dnl *** Checks for working __thread ***
dnl ***********************************
AC_MSG_CHECKING(for working __thread)
if test "x$with_tls" != "x__thread"; then
if test "x$with_nptl" != "xyes"; then
AC_MSG_RESULT(disabled)
else
AC_TRY_RUN([
@@ -771,9 +689,9 @@ if test x$platform_win32 = xno; then
}
], [
AC_MSG_RESULT(yes)
AC_DEFINE(HAVE_KW_THREAD)
], [
AC_MSG_RESULT(no)
with_tls=pthread
])
fi
@@ -980,37 +898,8 @@ if test x$platform_win32 = xno; then
AC_DEFINE_UNQUOTED(SIGVAL_PTR,$SIGVAL_PTR,[Pointer field name in 'union sigval'])
fi
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?))
dnl *********************************
dnl *** Check for struct ip_mreqn ***
dnl *********************************
AC_MSG_CHECKING(for struct ip_mreqn)
AC_TRY_COMPILE([#include <ws2tcpip.h>], [
struct ip_mreqn mreq;
mreq.imr_address.s_addr = 0;
], [
# Yes, we have it...
AC_MSG_RESULT(yes)
AC_DEFINE(HAVE_STRUCT_IP_MREQN)
], [
# We'll just have to try and use struct ip_mreq
AC_MSG_RESULT(no)
AC_MSG_CHECKING(for struct ip_mreq)
AC_TRY_COMPILE([#include <ws2tcpip.h>], [
struct ip_mreq mreq;
mreq.imr_interface.s_addr = 0;
], [
# Yes, we have it...
AC_MSG_RESULT(yes)
AC_DEFINE(HAVE_STRUCT_IP_MREQ)
], [
# No multicast support
AC_MSG_RESULT(no)
])
])
fi
dnl socklen_t check
@@ -1028,22 +917,9 @@ ac_cv_c_socklen_t=yes
AC_MSG_RESULT(no)
])
AC_MSG_CHECKING(for array element initalizer support)
AC_TRY_COMPILE([#include <sys/socket.h>], [
const int array[] = {[1] = 2,};
], [
# Yes, we have it...
AC_MSG_RESULT(yes)
AC_DEFINE(HAVE_ARRAY_ELEM_INIT,1,[Supports C99 array initialization])
], [
# We'll have to use signals
AC_MSG_RESULT(no)
])
AC_CHECK_FUNCS(trunc, , AC_MSG_CHECKING(for trunc in math.h)
# Simply calling trunc (0.0) is no good since gcc will optimize the call away
AC_TRY_LINK([#include <math.h>],
[ static void *p = &trunc; ],
[ trunc(0.0); ],
[
AC_DEFINE(HAVE_TRUNC)
AC_MSG_RESULT(yes)
@@ -1073,7 +949,7 @@ case "{$target}" in
dnl Win32 does not have /dev/random, they have their own method...
*-*-mingw*|*-*-cygwin*)
ac_cv_have_dev_random=no
ac_cv_have_dev_random = no
;;
dnl Everywhere else, it's /dev/random
@@ -1164,7 +1040,6 @@ ACCESS_UNALIGNED="yes"
JIT_SUPPORTED=no
LIBC="libc.so.6"
INTL="libc.so.6"
jit_wanted=false
case "$host" in
@@ -1181,28 +1056,20 @@ case "$host" in
x86_64-*-* | amd64-*-*)
TARGET=AMD64;
arch_target=amd64;
JIT_SUPPORTED=yes
jit_wanted=true
JIT_SUPPORTED=no
;;
sparc*-*-*)
if test "x$ac_cv_sizeof_void_p" = "x8"; then
TARGET=SPARC64
else
TARGET=SPARC
fi
TARGET=SPARC;
arch_target=sparc;
JIT_SUPPORTED=yes
ACCESS_UNALIGNED="no"
LIBC="libc.so"
INTL="libintl.so"
jit_wanted=true
;;
alpha*-*-linux* | alpha*-*-osf*)
TARGET=ALPHA;
ACCESS_UNALIGNED="no"
JIT_SUPPORTED=no
arch_target=alpha;
;;
# alpha*-*-linux* | alpha*-*-osf*)
# TARGET=ALPHA;
# ACCESS_UNALIGNED="no"
# ;;
# ia64-*-linux* | ia64-*-hpux*)
# TARGET=IA64;
# arch_target=ia64;
@@ -1222,11 +1089,6 @@ case "$host" in
LIBC="libc.sl"
ACCESS_UNALIGNED="no"
;;
hppa*linux*)
TARGET=HPPA;
arch_target=hppa;
ACCESS_UNALIGNED="no"
;;
macppc-*-openbsd* | powerpc-*-linux* | powerpc-*-openbsd* | \
powerpc-*-sysv* | powerpc-*-darwin*)
TARGET=POWERPC;
@@ -1245,12 +1107,6 @@ case "$host" in
ACCESS_UNALIGNED="no"
JIT_SUPPORTED=yes
;;
s390x-*-linux*)
TARGET=S390x;
arch_target=s390x;
ACCESS_UNALIGNED="no"
JIT_SUPPORTED=yes
;;
esac
AC_ARG_WITH(jit, [ --with-jit=yes,no If you want to build scripts that default to the JIT],[
@@ -1277,46 +1133,10 @@ case "$host" in
powerpc-*-darwin*)
libsuffix=".dylib"
LIBC="libc.dylib"
INTL="libintl.dylib"
;;
*-*-*netbsd*)
LIBC="libc.so.12"
INTL="libintl.so.0"
;;
esac
AC_SUBST(libsuffix)
if test "x$TARGET" != "xAMD64"; then
# valgrind headers don't compile under x86-64
AC_CHECK_HEADERS(valgrind/memcheck.h)
fi
if test "x$TARGET" = "xAMD64" -o "x$TARGET" = "xX86"; then
if test "x$with_tls" = "x__thread"; then
#
# On some linux distributions, TLS works in executables, but linking
# against a shared library containing TLS fails with:
# undefined reference to `__tls_get_addr'
#
rm -f conftest.c conftest.so conftest
echo "static __thread int foo; void main () { foo = 5; }" > conftest.c
gcc -fPIC --shared -o conftest.so conftest.c > /dev/null 2>&1
gcc -o conftest conftest.so > /dev/null 2>&1
if test ! -f conftest; then
AC_MSG_WARN([Disabling usage of __thread.]);
with_tls=pthread
fi
rm -f conftest.c conftest.so conftest
fi
fi
if test "x$with_tls" = "x__thread"; then
AC_DEFINE(HAVE_KW_THREAD)
# Pass the information to libgc
CPPFLAGS="$CPPFLAGS -DUSE_COMPILER_TLS"
export CPPFLAGS
fi
if test ${TARGET} = ARM; then
dnl ******************************************
dnl *** Check to see what FPU is available ***
@@ -1357,7 +1177,6 @@ AM_CONDITIONAL(INSTALL_2_0, test x$PREVIEW = xyes)
AM_CONDITIONAL(MIPS_GCC, test ${TARGET}${ac_cv_prog_gcc} = MIPSyes)
AM_CONDITIONAL(MIPS_SGI, test ${TARGET}${ac_cv_prog_gcc} = MIPSno)
AM_CONDITIONAL(SPARC, test x$TARGET = xSPARC)
AM_CONDITIONAL(SPARC64, test x$TARGET = xSPARC64)
AM_CONDITIONAL(X86, test x$TARGET = xX86)
AM_CONDITIONAL(AMD64, test x$TARGET = xAMD64)
AM_CONDITIONAL(ALPHA, test x$TARGET = xALPHA)
@@ -1366,13 +1185,11 @@ AM_CONDITIONAL(M68K, test x$TARGET = xM68K)
AM_CONDITIONAL(POWERPC, test x$TARGET = xPOWERPC)
AM_CONDITIONAL(ARM, test x$TARGET = xARM)
AM_CONDITIONAL(S390, test x$TARGET = xS390)
AM_CONDITIONAL(S390x, test x$TARGET = xS390x)
AM_CONDITIONAL(HPPA, test x$TARGET = xHPPA)
AM_CONDITIONAL(JIT_SUPPORTED, test x$JIT_SUPPORTED = xyes)
AC_SUBST(LIBC)
AC_SUBST(INTL)
AC_SUBST(arch_target)
AC_SUBST(CFLAGS)
@@ -1398,7 +1215,6 @@ mono/arch/hppa/Makefile
mono/arch/ppc/Makefile
mono/arch/sparc/Makefile
mono/arch/s390/Makefile
mono/arch/s390x/Makefile
mono/arch/arm/Makefile
mono/arch/alpha/Makefile
mono/interpreter/Makefile
@@ -1420,8 +1236,6 @@ man/Makefile
web/Makefile
docs/Makefile
data/Makefile
data/net_1_1/Makefile
data/net_2_0/Makefile
samples/Makefile
support/Makefile
data/config
@@ -1434,7 +1248,7 @@ echo "
GC: $gc
ICU: $enable_icu
TLS: $with_tls
NPTL: $with_nptl
SIGALTSTACK: $with_sigaltstack
Engine: $jit_status
2.0 Alpha: $PREVIEW
+1
View File
@@ -2,3 +2,4 @@ Makefile.in
Makefile
config
.cvsignore
browscap.ini
+10 -3
View File
@@ -1,10 +1,17 @@
SUBDIRS = net_1_1 net_2_0
monodir = $(sysconfdir)/mono
EXTRA_DIST = config.in \
browscap.ini
machine.config \
DefaultWsdlHelpGenerator.aspx \
browscap.ini.gz
mono_DATA = config \
machine.config \
DefaultWsdlHelpGenerator.aspx \
browscap.ini
CLEANFILES = browscap.ini
browscap.ini: browscap.ini.gz
gunzip -c $^ > $@
-13082
View File
File diff suppressed because it is too large. Load diff
Binary file not shown.
-1
View File
@@ -1,7 +1,6 @@
<configuration>
<dllmap dll="cygwin1.dll" target="@LIBC@" />
<dllmap dll="libc" target="@LIBC@" />
<dllmap dll="libintl" target="@INTL@" />
<dllmap dll="libxslt.dll" target="libxslt@libsuffix@" />
<dllmap dll="libmySQL.dll" target="libmysqlclient@libsuffix@" />
<dllmap dll="odbc32.dll" target="libodbc@libsuffix@" />
-21
View File
@@ -35,8 +35,6 @@
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"
@@ -152,12 +150,6 @@
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>
@@ -198,19 +190,6 @@
</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
View File
@@ -1,2 +0,0 @@
Makefile
Makefile.in
File diff suppressed because it is too large. Load diff
-8
View File
@@ -1,8 +0,0 @@
monodir = $(sysconfdir)/mono/1.0
EXTRA_DIST = machine.config \
DefaultWsdlHelpGenerator.aspx
mono_DATA = machine.config \
DefaultWsdlHelpGenerator.aspx
-216
View File
@@ -1,216 +0,0 @@
<?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
View File
@@ -1,2 +0,0 @@
Makefile
Makefile.in
File diff suppressed because it is too large. Load diff
-8
View File
@@ -1,8 +0,0 @@
monodir = $(sysconfdir)/mono/2.0
EXTRA_DIST = machine.config \
DefaultWsdlHelpGenerator.aspx
mono_DATA = machine.config \
DefaultWsdlHelpGenerator.aspx
-216
View File
@@ -1,216 +0,0 @@
<?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>
+301 -78
View File
@@ -30,10 +30,8 @@ Unfortunately, analyzing complex expressions is not so easy (see below for
details), so the capabilities of this "abc remover" are limited.
These are simple guidelines:
- Only expressions of the following kinds are handled:
- constant
- variable [+/- constant]
- Only comparisons between "handled" expressions are understood.
- Only simple comparisons between variables are understood.
- Only increment-decrement operations are handled.
- "switch" statements are not yet handled.
This means that code like this will be handled well:
@@ -61,24 +59,16 @@ for (int i = l; i > 0; i--) {
a [i] = .....
}
The following two examples would work:
for (int i = 0; i < (a.Length -1); i++) .....
for (int i = 0; i < a.Length; i += 2) .....
But just something like this
int delta = -1;
for (int i = 0; i < (a.Length + delta); i++) .....
for (int i = 0; i < (a.Length -1); i++) .....
or like this
int delta = +2;
for (int i = 0; i < a.Length; i += delta) .....
for (int i = 0; i < a.Length; i += 2) .....
would not work, the check would stay there, sorry :-(
(unless a combination of cfold, consprop and copyprop is used, too, which
would make the constant value of "delta" explicit).
Just to make you understand how things are tricky... this would work!
@@ -91,9 +81,26 @@ for (int i = 0; i < limit; i++) {
A detailed explanation of the reason why things are done like this is given
below...
All in all, the compiling phase is generally non so fast, and the abc removed
are so few, that there is hardly a performance gain in using the "abcrem"
flag in the compiling options for short programs like the ones I tried.
Anyway, various bound checks *are* removed, and this is good :-)
------------------------------------------------------------------------------
THE ALGORITHM
Unfortunately, this time google has not been my friend, and I did not
find an algorithm I could reasonably implement in the time frame I had,
so I had to invent one. The two cleasses of algorithms I found were either
simply an analisys of variable ranges (which is not very different from
what I'm doing), or they were based on type systems richer than the .NET
one (particularly, they required integer types to have an explicit range,
which could be related to array ranges). By the way, it seems that the
gcj people do not have an array bound check removal optimization (they
just have a compiler flag that unconditionally removes all the checks,
but this is not what we want).
This array bound check removal (abc removal) algorithm is based on
symbolic execution concepts. I handle the removal like an "unreachable
code elimination" (and in fact the optimization could be extended to remove
@@ -195,9 +202,9 @@ one of the definitions of i is a PHI that can be either 0 or "i + 1".
Now, we know that mathematically "i = i + 1" does not make sense, and in
fact symbolic values are not "equations", they are "symbolic definitions".
The actual symbolic value of i is a generic "n", where "n" is the number of
The symbolic value of i is a generic "n", where "n" is the number of
iterations of the loop, but this is terrible to handle (and in more complex
examples the symbolic value of i simply cannot be written, because i is
examples the symbolic definition of i simply cannot be written, because i is
calculated in an iterative way).
However, the definition "i = i + 1" tells us something about i: it tells us
@@ -220,25 +227,13 @@ conditions that could have caused to the removal of an abc, but will
not remove checks "by mistake" (so the resulting code will be in any case
correct).
The expressions we handle are the following (all of integer type):
- constant
- variable
- variable + constant
- constant + variable
- variable - constant
In a first attempt, we can consider only conditions that have the simple
possible form, which is "(compare simpleExpression simpleExpression)",
where "simpleExpression" is either "(ldind.* local[*])" or
"(ldlen (ldind.ref local[*]))" (or a constant, of course).
And, of course, PHI definitions.
Any other expression causes the introduction of an "any" value in the
evaluation, which makes all values that depend from it unknown as well.
We will call these kind of definitions "summarizable" definitions.
In a first attempt, we can consider only branch conditions that have the
simplest possible form (the comparison of two summarizable expressions).
We can also simplify the effect of variable definitions, keeping only
what is relevant to know: their value range with respect to zero and with
respect to the length of the array we are currently handling.
We can also "summarize" variable definitions, keeping only what is relevant
to know: if they are greater or smaller than zero or other variables.
One particular note on PHI functions: they work (obviously) like the logical
"or" of their definitions, and therefore are equivalent to the "logical or"
@@ -250,53 +245,281 @@ if the recursive definition (which, as we said above, must happen because
of a loop) always "grows" or "gets smaller". In all other cases, we decide
we cannot handle it.
So, the algorithm to optimize one method could be something like:
One critical thing, once we have defined all these data structures, is how
the evaluation is actually performed.
In a first attempt I coded a "brute force" approach, which for each BB
tried to examine all possible conditions between all variables, filling
a sort of "evaluation matrix". The problem was that the complexity of this
evaluation was quadratic (or worse) on the number of variables, and that
many wariables were examined even if they were not involved in any array
access.
Following the ABCD paper (http://citeseer.ist.psu.edu/bodik00abcd.html),
I rewrote the algorithm in a more "sparse" way.
Now, the main data structure is a graph of relations between variables, and
each attempt to remove a check performs a traversal of the graph, looking
for a path from the index to the array length that satisfies the properties
"index >= 0" and "index < length". If such a path is found, the check is
removed. It is true that in theory *each* traversal has a complexity which
is exponential on the number of variables, but in practice the graph is not
very connected, so the traversal terminates quickly.
[1] Build the SSA representation.
[2] Analyze each BB. Particularly, do the following:
[2a] summarize its exit conditions
[2b] summarize all the variable definitions occurring in the BB
[2c] check if it contains array accesses (only as optimization, so that
step 3 will be performed only when necessary)
[3] Perform the removal. For each BB that contains array accesses, do:
[3a] build an evaluation area where for each variable we keep track
of its relations with zero and with each other variable.
[3b] populate the evaluation area with the initial data (the variable
definitions and the complete entry condition of the BB)
[3c] propagate the relations between variables (so that from "a<b" and
"b<c" we know that "a<c") in the evaluation area
[3d] for each array access in the BB, use the evaluation area to "match
conditions", to see if the goal functions are satisfied
Then, the algorithm to optimize one method looks like this:
------------------------------------------------------------------------------
LOW LEVEL DESIGN DECISIONS
[1] Preparation:
[1a] Build the SSA representation.
[1b] Prepare the evaluation graph (empty)
[1b] Summarize each varible definition, and put the resulting relations
in the evaluation graph
[2] Analyze each BB, starting from the entry point and following the
dominator tree:
[2a] Summarize its entry condition, and put the resulting relations
in the evaluation graph (this is the reason why the BBs are examined
following the dominator tree, so that conditions are added to the
graph in a "cumulative" way)
[2b] Scan the BB instructions, and for each array access perform step [3]
[2c] Process children BBs following the dominator tree (step [2])
[2d] Remove from the evaluation area the conditions added at step [2a]
(so that backtracking along the tree the area is properly cleared)
[3] Attempt the removal:
[3a] Summarize the index expression, to see if we can handle it; there
are three cases: the index is either a constant, or a variable (with
an optional delta) or cannot be handled (is a "any")
[3b] If the index can be handled, traverse the evaluation area searching
a path from the index variable to the array length (if the index is
a constant, just examine the array length to see if it has some
relation with this constant)
[3c] Use the results of step [3b] to decide if the check is redundant
One of the problems I had to solve was the representation of the relations
between symbolic values.
The "canonical" solution would be to have a complex, potentially recursive
data structure, somewhat similar to MonoInst, and use it all the time (maybe
MonoInst could be used "as is").
The problem is that, at this point, the software would have to "play" with
these structures, for instance to deduce "b < a-1" from "a > b+1", because we
are interested in what value b has, and not a. And maybe the software should
be able to do this without modifying the original condition, because it was
used elsewhere (or could be reused).
Then, the software should also be able to apply logical relations to
conditions (like "(a>0)||(c<1)"), and manipulate them, too.
In my opinion, an optimizer written in this way risks to be too complex, and
its performance not acceptable in a JIT compiler.
Therefore, I decided to represent values in a "summarized" way.
For instance, "x = a + 1" becomes "x > a" (and, by the way, "x = x + 1"
would look like "x > x", which means that "x grows").
So, each variable value is simply a "relation" of the variable with other
variables or constants. Anything more complex is ignored.
Relations are represented with flags (EQ, LT and GT), so that it is easy
to combine them logically (it is enough to perform the bitwise operations
on the flags). The condition (EQ|LT|GT) means we know nothing special, any
value is possible. The empty condition would mean an unreachable statement
(because no value is acceptable).
There is still the problem of identifying variables, and where to store all
these relations. After some thinking, I decided that a "brute force" approach
is the easier, and probably also the fastest. In practice, I keep in memory
an array of "variable relations", where for each variable I record its
relation with the constants 0 and 1 and an array of its relations with all
other variables. The evaluation area, therefore, looks like a square matrix
as large as the number of variables. I *know* that the matrix is rather sparse
(in the sense that only few of its cells are significant), but I decided that
this data structure was the simplest and more efficient anyway. After all,
each cell takes just one byte, and any other data structure must be some
kind of associative array (like a g_hash_table). Such a data structue is
difficult to use with a MonoMemPool, and in the end is slower than a plain
array, and has the storage overhead of all the pointers... in the end, maybe
the full matrix is not a waste at all.
<note>
After a few benchmarks, I clearly see that the matrix works well if the
variables are not too much, otherwise it gets "too sparse", and much time
is wasted in the propagation phase. Maybe the data structure could be changed
after a more careful evaluation of the problem...
</note>
With these assumptions, all the memory used to represent values, conditions
and the evaluation area can be allocated in advance (from a MonoMemPool), and
used for all the analysis of one method. Moreover, the performance of logical
operations is high (they are simple bitwise operations on bytes).
<note>
For the propagation phase, there was a function I could not easily code
with bitwise operations. As that phase is a real pain for the performance
(the complexity is quadratic, and it must be executed iteratively until
nothing changes), I decided to code it in perl, and generate a precomputed
table then used by the C code (just 64 bytes). I think this is faster than
all those branches... Really, I could think again to phases 3c and 3d (see
above), maybe there is a better way to do them.
</note>
Of course not all expressions can be handled by the summarization, so the
optimizer is not as effective as a full blown theorem prover...
Another thing related to design... the implementation is as less intrusive
as possible.
I "patched" the main files to add an option for abc removal, and handle it
just like any other option, and then wrote all the relevant code in two
separated files (one header for data structures, and a C file for the code).
If the patch turns out to be useful also for other pourposes (like a more
generic "unreachable code elimination", that detects branches that will never
be taken using the analysis of variable values), it will not be difficult
to integrate the branch summarizations into the BasicBlock data structures,
and so on.
One last thing... in some places, I knowingly coded in an inefficient way.
For instance, "remove_abc_from_block" does something only if the flag
"has_array_access_instructions" is true, but I call it anyway, letting it
do nothing (calling it conditionally would be better). There are several
things like this in the code, but I was in a hurry, and preferred to make
the code more readable (it is already difficult to understand as it is).
------------------------------------------------------------------------------
WHEN IS ABC REMOVAL POSSIBLE? WHEN IS IT USEFUL?
Warning! Random ideas ahead!
In general, managed code should be safe, so abc removal is possible only if
there already is some branch in the method that does the check.
So, one check on the index is "mandatory", the abc removal can only avoid a
second one (which is useless *because* of the first one).
If in the code there is not a conditional branch that "avoids" to access
an array out of its bounds, in general the abc removal cannot occur.
It could happen, however, that one method is called from another one, and
the check on the index is performed in the caller.
For instance:
void
caller( int[] a, int n ) {
if ( n <= a.Length ) {
for ( int i = 0; i < n; i++ ) {
callee( a, i );
}
}
}
void callee( int[] a, int i ) {
Console.WriteLine( "a [i] = " + a [i] );
}
In this case, it should be possible to have two versions of the callee, one
without checks, to be called from methods that do the check themselves, and
another to be called otherwise.
This kind of optimization could be profile driven: if one method is executed
several times, wastes CPU time for bound checks, and is mostly called from
another one, it could make sense to analyze the situation in detail.
However, one simple way to perform this optimization would be to inline
the callee (so that the abc removal algorithm can see both methods at once).
The biggest benefits of abc removal can be seen for array accesses that
occur "often", like the ones inside inner loops. This is why I tried to
handle "recursive" variable definitions, because without them you cannot
optimize inside loops, which is also where you need it most.
Another possible optimization (alwais related to loops) is the following:
void method( int[] a, int n ) {
for ( int i = 0; i < n; i++ ) {
Console.WriteLine( "a [i] = " + a [i] );
}
}
In this case, the check on n is missing, so the abc could not be removed.
However, this would mean that i will be checked twice at each loop iteration,
one against n, and the other against a.Length. The code could be transformed
like this:
void method( int[] a, int n ) {
if ( n < a.Length ) {
for ( int i = 0; i < n; i++ ) {
Console.WriteLine( "a [i] = " + a [i] ); // Remove abc
}
} else {
for ( int i = 0; i < n; i++ ) {
Console.WriteLine( "a [i] = " + a [i] ); // Leave abc
}
}
}
This could result in performance improvements (again, probably this
optimization should be profile driven).
------------------------------------------------------------------------------
OPEN ISSUES
There are several issues that should still be addressed...
One is related to aliasing. For now, I decided to operate only on local
variables, and ignore aliasing problems (and alias analisys has not yet
been implemented anyway).
Actually, I identified the local arrays with their length, because I
totally ignore the contents of arrays (and objects in general).
Also, in several places in the code I only handle some cases, and ignore
other more complex ones, which could anyway work (there are comments where
this happens). Anyway, this is not harmful (the code is not as effective
as it could be).
Another possible improvement is the explicit handling of all constants.
For now, code like
void
method () {
int[] a = new int [16];
for ( int i = 0; i < 16; i++ ) {
a [i] = i;
}
}
is not handled, because the two constants "16" are lost when variable
relations are summarized (actually they are not lost, they are stored in the
summarized values, but they are not yet used correctly).
The worst thing, anyway, is that for now I fail completely in distinguishing
between signed and unsigned variables/operations/conditions, and between
different integer sizes (in bytes). I did this on pourpose, just for lack of
time, but this can turn out to be terribly wrong.
The problem is caused by the fact that I handle arithmetical operations and
conditions as "ideal" operations, but actually they can overflow and/or
underflow, giving "surprising" results.
For instance, look at the following two methods:
public static void testSignedOverflow()
{
Console.WriteLine( "Testing signed overflow..." );
int[] ia = new int[70000];
int i = 1;
while ( i <ia.Length )
{
try
{
Console.WriteLine( " i = " + i );
ia[i] = i;
}
catch ( IndexOutOfRangeException e )
{
Console.WriteLine( "Yes, we had an overflow (i = " + i + ")" );
}
i *= 60000;
}
Console.WriteLine( "Testing signed overflow done." );
}
public static void testUnsignedOverflow()
{
Console.WriteLine( "Testing unsigned overflow..." );
int[] ia = new int[70000];
uint i = 1;
while ( i <ia.Length )
{
try
{
Console.WriteLine( " i = " + i );
ia[i] = (int) i;
}
catch ( IndexOutOfRangeException e )
{
Console.WriteLine( "Yes, we had an overflow (i = " + i + ")" );
}
i *= 60000;
}
Console.WriteLine( "Testing unsigned overflow done." );
}
In the "testSignedOverflow" method, the exception will be thrown, while
in the "testUnsignedOverflow" everything will go on smoothly.
The problem is that the test "i <ia.Length" is a signed comparison in the
first case, and will not exit from the loop if the index is negative.
Therefore, in the first method, the abc should not be removed.
In practice, the abc removal code should try to predict if any given
expression could over/under-flow, and act accordingly.
For now, I made so that the only accepted expressions are plain increments
and decrements of variables (which cannot over/under-flow without being
trapped by the existing conditions). Anyway, this issue should be analyzed
better.
By the way, in summarizations there is a field that keeps track of the
relation with "1", which I planned to use exactly to summarize products and
quotients, but it is never used (as I said, only increment and decrement
operations are properly summarized).
-96
View File
@@ -1,96 +0,0 @@
Handling GC allocated objects in C
As part of an effort to improve our GC, we need to keep track
precisely of where objects are stored, so we can incrementally move
from the current conservative GC to a more advanced precise and moving GC.
Previously, all global C variables were considered GC roots, but this makes
the GC less efficient and increases the chances false references are found
to GC memory, hence retaining more memory than needed.
We need to tell the GC that some object is supposed to be kept alive
as if it was referenced in a global variable.
For Mono embedders
------------------
In C#, if you say:
class T {
static object o;
}
Any object which is stored in `o' is considered to be alive -- it will
not be collected. `o' is a member of the root set for the GC.
However, in C code, this is not the case. If you have:
static MonoObject* o = NULL;
The object in `o' will *NOT* be scanned.
If you need to store an object in a C variable and prevent it from being
collected, you need to acquire a GC handle for it.
guint32 handle = mono_gchandle_new (my_object, TRUE);
TRUE means the object will be pinned, so it won't move in memory
when we'll use a moving GC. You can access the MonoObject* referenced by
a handle with:
MonoObject* obj = mono_gchandle_get_target (handle);
When you don't need the handle anymore you need to call:
mono_gchandle_free (handle);
Note that if you assign a new object to the C var, you need to get a new
handle, it's not enough to store a new object in the C var.
So code that looked like this:
static MonoObject* o = NULL;
...
o = mono_object_new (...);
/* use o */
...
/* when done to allow the GC to collect o */
o = NULL;
should now be changed to:
static guint32 o_handle;
...
MonoObject *o = mono_object_new (...);
o_handle = mono_gchandle_new (o, TRUE);
/* use o or mono_gchandle_get_target (o_handle) */
...
/* when done to allow the GC to collect o */
mono_gchandle_free (o_handle);
For Mono runtime developers
---------------------------
There are two kinds of static vars used to store pointers to GC memory
that we need to consider:
*) objects
*) other memory chunks allocated with GC_MALLOC().
Objects should be dealt with the GC handle support as detailed above.
Other items should register the static pointer as an area to be considered
part of the root set with the following:
static gpointer my_gc_data = NULL;
...
MONO_GC_REGISTER_ROOT (my_gc_data);
my_gc_data = GC_MALLOC (...);
Note that this registration is not necessary for *LOCAL* variables,
as they are stored on the stack. It is only necessary for global variables,
as they are not a part of the GC's root set.
Once you have done the MONO_GC_REGISTER_ROOT, the variable is just like
a static variable in C#. To keep an object alive, you have the variable reference
the GC memory, to remove the reference, set the variable to NULL.
As we prepare the code for a precise GC, GC_MALLOC () will not be used anymore
in this way in most cases: we'll have a mechanism to specify exactly where
references to GC memory is stored.
-27
View File
@@ -422,30 +422,3 @@
we replace one or more instructions with others that perform
better for the given architecture or CPU.
* 64 bit support tips, by Zoltan Varga ([email protected])
For a 64-bit port of the Mono runtime, you will typically do
the following:
* need to use inssel-long.brg instead of
inssel-long32.brg.
* need to implement lots of new opcodes:
OP_I<OP> is 32 bit op
OP_L<OP> and CEE_<OP> are 64 bit ops
The 64 bit version of an existing port might share the code
with the 32 bit port (for example SPARC/SPARV9), or it might
be separate (x86/AMD64).
That will depend on the similarities of the two instructions
sets/ABIs etc.
The runtime and most parts of the JIT are 64 bit clean
at this point, so the only parts which require changing are
the arch dependent files.
-68
View File
@@ -1,68 +0,0 @@
We need to switch to a new register allocator.
The current one is split in a global and a local register allocator.
The global one can assign only callee-saves registers and happens
on the tree-based internal representation: it assigns local variables
to hardware registers.
The local one happens on the linear representation on a per basic
block basis and assigns hard registers to virtual registers (which
hold temporary values during expression executions) and it deals also
with the platform-specific issues (fixed registers, call conventions).
Moving to a different register will help solve some of the performance
issues introduced by the above split, make the register more easily
portable and solve some of the issues generated by dealing with trees.
The general design ideas are below.
The new allocator should have a global view of all the method, so it can be
able to assign variables also to some of the volatile registers if possible,
even across basic blocks (this would improve performance).
The allocator would be driven by per-arch declarative data, so porting
should be easier: an architecture needs to specify register classes,
call convention and instructions requirements (similar to the gcc code).
The allocator should operate on the linear representation, this way it's
easier and faster to track usages more correctly. We need to assign virtual
registers on a per-method basis instead of per basic block. We can assign
virtual registers to variables, too. Note that since we fix the stack offset
of local vars only after this step (which happens after the burg rules are run),
some of the burg rules that try to optimize the code won't apply anymore:
the peephole code may need to be enhanced to do the optimizations instead.
We need to handle floating point registers in the global allocator, too.
The new allocator also needs to keep track precisely of which registers
contain references or managed pointers to allow us to move to a precise GC.
It may be worth to use a single increasing set of integers for the virtual
registers, with the class of the register stored separately (unless the
current local allocator which keeps interger and fp registers separate).
Since this is a large task, we need to do it in steps as much as possible.
The first is to run the register allocator _after_ the burg rules: this
requires a rewrite of the liveness code, too, to use linear indexes instead
of basic-block/tree number combinations. This can be done by:
*) allocating virtual regs to all the locals that can be register allocated
*) running the burg rules (some may require adjustments): the local virtual
registers are assigned starting from global-virt-regs+1, instead of the current
hardware-regs+1, so we can tell apart global and local virt regs.
*) running the liveness/whatever code is needed to allocate the global registers
*) allocate the rest of the local variables to stack slots
*) continue with the current local allocator
This work could take 2-3 weeks.
The next step is to define the kind of declarative data an architecture needs
and assigning virtual regs to all the registers and making the allocator
assign from the volatile registers, too.
Note that some of the code that is currently emitted in the arch-specific
code, will need to be emitted as instructions that the reg allocator
can inspect: think of a method that returns the first argument which is
received in a register: the current code copies it to either a local slot or
to a global reg in the prolog an copies it back to the return register
int he basic block, but since neither the regallocator nor the peephole code
knows about the prolog code, the first store cannot be optimized away.
The gcc code has some example of how to specify register classes in a
declarative way.
-77
View File
@@ -1,77 +0,0 @@
While the Boehm GC is quite good, we need to move to a
precise, generational GC for better performance and smaller
memory usage (no false-positives memory retentions with big
allocations).
This is a large task, but it can be done in steps.
1) use the GCJ support to mark reference fields in objects, so
scanning the heap is faster. This is mostly done already, needs
checking that it is always used correctly (big objects, arrays).
There are also some data structures we use in the runtime that are
currently untyped that are allocated in the Gc heap and used to
keep references to GC objects. We need to make them typed as to
precisely track GC references or make them non-GC memory,
by using more the GC hnadle support code (MonoGHashTable, MonoDomain,
etc).
2) don't include in the static roots the .bss and .data segments
to save in scanning time and limit false-positives. This is mostly
done already.
3) keep track precisely of stack locations and registers in native
code generation. This basically requires the regalloc rewrite code
first, if we don't want to duplicate much of it. This is the hardest
task of all, since proving it's correctness is very hard. Some tricks,
like having a build that injects GC.Collect() after every few simple
operations may help. We also need to decide if we want to handle safe
points at calls and back jumps only or at every instruction. The latter
case is harder to implement and requires we keep around much more data
(it potentially makes for faster stop-the-world phases).
The first case requires us to be able to advance a thread until it
reaches the next safe point: this can be done with the same techniques
used by a debugger. We already need something like this to handle
safely aborts happening in the middle of a prolog in managed code,
for example, so this could be an additional sub-task that can be done
separately from the GC work.
Note that we can adapt the libgc code to use the info we collect
when scanning the stack in managed methods and still use the conservative
approach for the unmanaged stack, until we have our own collector,
which requires we define a proper icall interface to switch from managed
to unmanaged code (hwo to we handle object references in the icall
implementations, for example).
4) we could make use of the generational capabilities of the
Boehm GC, but not with the current method involving signals which
may create incompatibilities and is not supported on all platforms.
We need to start using write barriers: they will be required anyway
for the generational GC we'll use. When a field holding a reference
is changed in an object (or an item in an array), we mark the card
or page where the field is stored as dirty. Later, when a collection
is run, only objects in pages marked as dirty are scanned for
references instead of the whole heap. This could take a few days to
implement and probably much more time to debug if all the cases were
not catched:-)
5) actually write the new generational and precise collector. There are
several examples out there as open source projects, though the CLR
needs some specific semantics so the code needs to be written from
scratch anyway. Compared to item 3 this is relatively easer and it can
be tested outside of mono, too, until mono is ready to use it.
The important features needed:
*) precise, so there is no false positive memory retention
*) generational to reduce collection times
*) pointer-hopping allocation to reduce alloc time
*) possibly per-thread lock-free allocation
*) handle weakrefs and finalizers with the CLR semantics
Note: some GC engines use a single mmap area, because it makes
handling generations and the implementation much easier, but this also
limits the expension of the heap, so people may need to use a command-line
option to set the max heap size etc. It would be better to have a design
that allows mmapping a few megabytes chunks at a time.
The different tasks can be done in parallel. 1, 2 and 4 can be done in time
for the mono 1.2 release. Parts of 3 and 5 could be done as well.
The complete switch is supposed to happen with the mono 2.0 release.
-8
View File
@@ -1,11 +1,3 @@
2004-06-24 David Waite <[email protected]>
* mono-jni.c: change to C90-style comments from C99/C++-style
Fri Jun 18 13:46:05 CEST 2004 Paolo Molaro <[email protected]>
* mono-jni.c: updates for the API cleanups.
2004-05-05 Zoltan Varga <[email protected]>
* mono-jni.c: Implement some missing JNI functions.
+25 -25
View File
@@ -149,8 +149,8 @@ StringFromUTF8 (const char* psz)
/* TODO: */
return mono_string_new (mono_domain_get (), psz);
#if 0
/* Sun's modified UTF8 encoding is not compatible with System::Text::Encoding::UTF8, so */
/* we need to roll our own */
// Sun's modified UTF8 encoding is not compatible with System::Text::Encoding::UTF8, so
// we need to roll our own
int len, res_len, i;
int *res;
@@ -163,16 +163,16 @@ StringFromUTF8 (const char* psz)
switch (c >> 4)
{
case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
/* 0xxxxxxx */
// 0xxxxxxx
break;
case 12: case 13:
/* 110x xxxx 10xx xxxx */
// 110x xxxx 10xx xxxx
char2 = *psz++;
i++;
c = (((c & 0x1F) << 6) | (char2 & 0x3F));
break;
case 14:
/* 1110 xxxx 10xx xxxx 10xx xxxx */
// 1110 xxxx 10xx xxxx 10xx xxxx
char2 = *psz++;
char3 = *psz++;
i++;
@@ -263,50 +263,50 @@ static jobject JNICALL CallObjectMethodA (JNIEnv *env, jobject obj, jmethodID me
static MonoObject *
box_Boolean (jboolean val)
{
return mono_value_box (mono_domain_get (), mono_get_boolean_class (), &val);
return mono_value_box (mono_domain_get (), mono_defaults.boolean_class, &val);
}
static MonoObject *
box_Byte (jbyte val)
{
/* Sbyte ! */
return mono_value_box (mono_domain_get (), mono_get_sbyte_class (), &val);
return mono_value_box (mono_domain_get (), mono_defaults.sbyte_class, &val);
}
static MonoObject *
box_Char (jchar val)
{
return mono_value_box (mono_domain_get (), mono_get_char_class (), &val);
return mono_value_box (mono_domain_get (), mono_defaults.char_class, &val);
}
static MonoObject *
box_Short (jshort val)
{
return mono_value_box (mono_domain_get (), mono_get_int16_class (), &val);
return mono_value_box (mono_domain_get (), mono_defaults.int16_class, &val);
}
static MonoObject *
box_Int (jint val)
{
return mono_value_box (mono_domain_get (), mono_get_int32_class (), &val);
return mono_value_box (mono_domain_get (), mono_defaults.int32_class, &val);
}
static MonoObject *
box_Long (jlong val)
{
return mono_value_box (mono_domain_get (), mono_get_int64_class (), &val);
return mono_value_box (mono_domain_get (), mono_defaults.int64_class, &val);
}
static MonoObject *
box_Float (jfloat val)
{
return mono_value_box (mono_domain_get (), mono_get_single_class (), &val);
return mono_value_box (mono_domain_get (), mono_defaults.single_class, &val);
}
static MonoObject *
box_Double (jdouble val)
{
return mono_value_box (mono_domain_get (), mono_get_double_class (), &val);
return mono_value_box (mono_domain_get (), mono_defaults.double_class, &val);
}
static int
@@ -327,7 +327,7 @@ InvokeHelper (JNIEnv *env, jobject object, jmethodID methodID, jvalue* args)
MonoObject **argarray;
MonoArray *args2;
/* assert(!pLocalRefs->PendingException); */
// assert(!pLocalRefs->PendingException);
g_assert(methodID);
argc = GetMethodArgs(methodID, sig);
@@ -368,7 +368,7 @@ InvokeHelper (JNIEnv *env, jobject object, jmethodID methodID, jvalue* args)
}
}
args2 = mono_array_new (mono_domain_get (), mono_get_object_class (), argc);
args2 = mono_array_new (mono_domain_get (), mono_defaults.object_class, argc);
for (i = 0; i < argc; ++i)
mono_array_set (args2, MonoObject*, i, argarray [i]);
@@ -475,7 +475,7 @@ METHOD_IMPL(Double,jdouble)
/* TODO: These should be put into the macros above... */
// TODO: These should be put into the macros above...
static void JNICALL CallVoidMethodA (JNIEnv *env, jobject obj, jmethodID methodID, jvalue * args) {
InvokeHelper(env, obj, methodID, args);
}
@@ -581,7 +581,7 @@ static type JNICALL GetStatic##Type##Field(JNIEnv *env, jclass clazz, jfieldID f
/* return *(cpptype*)BOXED_VALUE (jniFuncs.GetFieldValue (fieldID, jniFuncs.UnwrapRef (obj))); */
// return *(cpptype*)BOXED_VALUE (jniFuncs.GetFieldValue (fieldID, jniFuncs.UnwrapRef (obj)));
GET_SET_FIELD(Boolean,jboolean,gboolean)
GET_SET_FIELD(Byte,jbyte, gchar)
@@ -734,42 +734,42 @@ static jobjectArray JNICALL NewObjectArray (JNIEnv *env, jsize len, jclass clazz
static jbooleanArray JNICALL NewBooleanArray (JNIEnv *env, jsize len)
{
return (jbooleanArray)new_java_array (env, mono_get_boolean_class (), len);
return (jbooleanArray)new_java_array (env, mono_defaults.boolean_class, len);
}
static jbyteArray JNICALL NewByteArray (JNIEnv *env, jsize len)
{
return (jbyteArray)new_java_array (env, mono_get_sbyte_class (), len);
return (jbyteArray)new_java_array (env, mono_defaults.sbyte_class, len);
}
static jcharArray JNICALL NewCharArray (JNIEnv *env, jsize len)
{
return (jcharArray)new_java_array (env, mono_get_char_class (), len);
return (jcharArray)new_java_array (env, mono_defaults.char_class, len);
}
static jshortArray JNICALL NewShortArray (JNIEnv *env, jsize len)
{
return (jshortArray)new_java_array (env, mono_get_int16_class (), len);
return (jshortArray)new_java_array (env, mono_defaults.int16_class, len);
}
static jintArray JNICALL NewIntArray (JNIEnv *env, jsize len)
{
return (jintArray)new_java_array (env, mono_get_int32_class (), len);
return (jintArray)new_java_array (env, mono_defaults.int32_class, len);
}
static jlongArray JNICALL NewLongArray (JNIEnv *env, jsize len)
{
return (jlongArray)new_java_array (env, mono_get_int64_class (), len);
return (jlongArray)new_java_array (env, mono_defaults.int64_class, len);
}
static jfloatArray JNICALL NewFloatArray (JNIEnv *env, jsize len)
{
return (jfloatArray)new_java_array (env, mono_get_single_class (), len);
return (jfloatArray)new_java_array (env, mono_defaults.single_class, len);
}
static jdoubleArray JNICALL NewDoubleArray (JNIEnv *env, jsize len)
{
return (jdoubleArray)new_java_array (env, mono_get_double_class (), len);
return (jdoubleArray)new_java_array (env, mono_defaults.double_class, len);
}
/* Original version with copy */
+14 -48
View File
@@ -24,17 +24,20 @@ convention is that assemblies must also be placed in a separate
directory for being accessed to the compiler. This is done with the
-package directive to gacutil.
.PP
The tool allows for installation, removal, and listing of the
The tool allows for installationl, removal, and listing of the
contents of the assembly cache.
.PP
The GAC is relative to the Mono installation prefix:
mono_prefix/lib/mono.
.SH FLAGS
The "-user" flag enables you to install/remove the assembly into the
user's assembly cache, as opposed to the global one.
.PP
.SH COMMANDS
.I -i <assembly_path> [-check_refs] [-package NAME] [-root ROOTDIR] [-gacdir GACDIR]
.I "-i path_to_assembly" [-f] [-root ROOTDIR] [-package NAME]
.Sp
Installs an assembly into the global assembly cache. <assembly_path>
is the name of the file that contains the assembly manifest
The above installs the assembly into the GAC, use the -f flag to force
an installation an overwrite anything in there.
.Sp
The -package option can be used to also create a directory in in
prefix/lib/mono with the name NAME, and a symlink is created from
@@ -44,32 +47,18 @@ developers can reference a set of libraries at once.
The -root option is used by developers integrating this with automake
tools or packaging tools that require a prefix directory to be
specified. The root represents the "libdir" component of a prefix
(typically prefix/lib).
.Sp
The -gacdir option is used to specify the GACs base directory. Once an
assembly has been installed to a non standard gacdir the MONO_GAC_PREFIX
environment variable must be used to access the assembly.
.Sp
The -check_refs option is used to ensure that the assembly being
installed into the GAC does not reference any non strong named
assemblies. Assemblies being installed to the GAC should not reference
non strong named assemblies, however the is an optional check.
(typically prefix/lib).
.fi
.PP
.I "-l" [assembly_name] [-root ROOTDIR] [-gacdir GACDIR]
.I "-l"
.Sp
Lists the contents of the global assembly cache. When the
<assembly_name> parameter is specified only matching assemblies are
listed.
Lists the contents of the Global Assembly Cache
.PP
.I "-u" <assembly_display_name> [-package NAME] [-root ROOTDIR] [-gacdir GACDIR]
.I "-u assembly_name [-root]"
.Sp
Uninstalls an assembly from the global assembly cache.
<assembly_display_name> is the name of the assembly (partial or
fully qualified) to remove from the global assembly cache. If a
partial name is specified all matching assemblies will be
uninstalled. As opposed to the install option that takes a filename,
this takes as an argument the assembly name, which looks like this:
The above removes the given assembly name from the Global Assembly
Cache. As opposed to the install option that takes a filename, this
takes as an argument the assembly name, which looks like this:
.nf
MyLibrary.Something, version=1.0.0.0, publicKeyToken=xxxx,culture=neutral
.fi
@@ -80,29 +69,6 @@ to quote them.
The removal performs a greedy removal, if you only specifiy one
component like, "MyLibrary.Something", it will remove all versions of
the library.
.Sp
.I "-us" <assembly_path> [-package NAME] [-root ROOTDIR] [-gacdir GACDIR]
Uninstalls an assembly using the specifed assemblies full name.
<assembly path> is the path to an assembly. The full assembly name
is retrieved from the specified assembly if there is an assembly in
the GAC with a matching name, it is removed. Unlike the -u option this
option takes a file name, like this:
.nf
Example: -us myDll.dll
.fi
.Sp
.I "-ul" <assembly_list_file> [-package NAME] [-root ROOTDIR] [-gacdir GACDIR]
Uninstalls one or more assemblies from the global assembly cache.
<assembly_list_file> is the path to a test file containing a list of
assembly names on separate lines.
.nf
Example -ul assembly_list.txt
.fi
.nf
assembly_list.txt contents:
assembly1,Version=1.0.0.0,Culture=en,PublicKeyToken=0123456789abcdef
assembly2,Version=2.0.0.0,Culture=en,PublicKeyToken=0123456789abcdef
.fi
.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
+2 -55
View File
@@ -1,9 +1,8 @@
.\"
.\" mono-config configuration page.
.\" mono configuration page.
.\" (C) Ximian, Inc.
.\" Author:
.\" Miguel de Icaza ([email protected])
.\" Paolo Molaro ([email protected])
.\"
.TH Mono "Mono 1.0"
.SH NAME
@@ -13,9 +12,6 @@ The Mono runtime will load configuration data from the
installation prefix /etc/mono/config file, the ~/.mono/config or from
the file pointed by the MONO_CONFIG environment variable.
.PP
For each assembly loaded a config file with the name:
/path/to/the/assembly.exe.config is loaded, too.
.PP
This file controls the behavior of the runtime.
.PP
The file contains an XML-like file with various sections, all of them
@@ -28,37 +24,6 @@ You use the dllmap directive to map shared libraries referenced by
P/Invoke in your assemblies to a different shared library.
.PP
This is typically used to map Windows libraries to Unix library names.
The
.B dllmap
element takes two attributes:
.TP
.I dll
This should be the same string used in the DllImport attribute
.TP
.I target
This should be the name of the library where the function can be found:
this name should be suitable for use with the platform native shared library
loading routines (dlopen etc.), so you may want to check the manpages for that, too.
.SH <dllentry> directive
This directive can be used to map a specific dll/function pair to a different
library and also a different function name. It should appear inside a
.B dllmap
element with only the dll attribute specified.
.PP
The
.B dllentry
element takes 3 attributes:
.TP
.I dll
This is the target library, where the function can be found.
.TP
.I name
This is the name of the fuction as it appears in the metadata: it is the name
of the P/Invoke method.
.TP
.I target
This is the name of the function to lookup instead of the name specified in the
P/Invoke method.
.SH EXAMPLES
The following example maps references to the `cygwin1.dll' shared
library to the `libc.so.6' file.
@@ -67,23 +32,5 @@ library to the `libc.so.6' file.
<dllmap dll="cygwin1.dll" target="libc.so.6"/>
</configuration>
.fi
.PP
This one maps the following C# method:
.nf
[DllImport ("libc")]
static extern void somefunction ();
.fi
to
.B differentfunction
in
.B libdifferent.so.
.nf
<configuration>
<dllmap dll="libc">
<dllentry dll="libdifferent.so" name="somefunction" target="differentfunction" />
</dllmap>
</configuration>
.fi
.SH SEE ALSO
.BR mono(1), monodis(1), mint(1)
.BR mono(1), monodis(1), mint(1)
+27 -41
View File
@@ -238,10 +238,10 @@ Finally, namespaces can be specified using the N: prefix:
Turns off the garbage collection in Mono. This should be only used
for debugging purposes
.TP
.I "MONO_ASPNET_NODELETE"
If set to any value, temporary source files generated by ASP.NET support
classes will not be removed. They will be kept in the user's temporary
directory.
.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_CFG_DIR"
If set, this variable overrides the default system configuration directory
@@ -252,21 +252,6 @@ 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
@@ -284,23 +269,33 @@ Windows I/O Emulation layer, and handles (files, events, mutexes,
pipes) will not be shared across processes. Process creation is also
disabled. This option is only available on Unix.
.TP
.I "MONO_EGD_SOCKET"
For platforms that do not otherwise have a way of obtaining random bytes
this can be set to the name of a file system socket on which an egd or
prngd daemon is listening.
.TP
.I "MONO_EXTERNAL_ENCODINGS"
If set, contains a colon-separated list of text encodings to try when
turning externally-generated text (e.g. command-line arguments or
filenames) into Unicode. The encoding names come from the list
provided by iconv, and the special case "default_locale" which refers
to the current locale's default encoding.
.IP
.TP
When reading externally-generated text strings UTF-8 is tried first,
and then this list is tried in order with the first successful
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_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_UNMANAGED_XSLT"
If set any value, System.Xml.Xsl.XslTransform uses libxslt-based
transformation engine (a.k.a Unmanaged XSLT). Unmanaged XSLT has
long been used for XSLT engine while Managed XSLT engine is so
new and might have some bugs. Basically we recommend Managed XSLT
solution, but if it contains some blocking bugs, then you can also
use traditional libxslt. If you want to use msxsl:script, you have
to select Managed XSLT.
.TP
.I "MONO_MANAGED_WATCHER"
If set to any value, System.IO.FileSystemWatcher will use the default
@@ -308,23 +303,14 @@ 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_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
.I "MONO_CODEDOM_NODELETE"
If set to any value, the C# CodeDom compiler will not remove the temporary
source files generated.
.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_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.
.I "MONO_EGD_SOCKET"
For platforms that do not otherwise have a way of obtaining random bytes
this can be set to the name of a file system socket on which an egd or
prngd daemon is listening.
.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
+10 -48
View File
@@ -1,9 +1,8 @@
.\"
.\" sn manual page.
.\" Copyright 2003 Motus Technologies
.\" Copyright 2004 Novell
.\" Author:
.\" Sebastien Pouliot <sebastien@ximian.com>
.\" Sebastien Pouliot (spouliot@motus.com)
.\"
.TH Mono "sn"
.SH NAME
@@ -14,33 +13,24 @@ sn \- Digitally sign/verify/compare strongname on CLR assemblies.
.SH DESCRIPTION
Digitally sign, verify or compare, CLR assemblies using strongnames.
.SH CONFIGURATION OPTIONS
Configuration options are stored in the machine.config configuration file
under /configuration/strongNames.
.TP
.I "-c provider"
Change the default CSP (Crypto Service Provider). Currently not supported
in Mono.
Change the default CSP (Crypto Service Provider).
.TP
.I "-m [y|n]"
Use a machine [y] key container or a user [n] key container. Currently not
supported in Mono.
Use a machine [y] key container or a user [n] key container.
.TP
.I "-Vl"
List the verification options. The list is kept under /configuration/
strongNames/verificationSettings in machine.config.
List the verification options.
.TP
.I "-Vr assembly [userlist]"
Exempt the specified assembly from verification for the specified user list.
Currently not supported by sn, you must edit machine.config manually if you
require this.
.TP
.I "-Vu assembly"
Remove the exemption entry for the specified assembly. Currently not
supported by sn, you must edit machine.config manually if you require this.
Remove the exemption entry for the specified assembly.
.TP
.I "-Vx"
Remove all exemptions entries. Currently not supported by sn, you must edit
machine.config manually if you require this.
Remove all exemptions entries.
.SH CSP RELATED OPTIONS
.TP
.I "-d container"
@@ -72,14 +62,11 @@ Compare if assembly1 and assembly are the same exception for their signature.
This is done by comparing the hash of the metadata of both assembly.
.TP
.I "-k keypair.snk"
Create a new strongname keypair (a 1024 bits RSA keypair) in the specified
file.
Create a new strongname keypair in the specified file.
.TP
.I "-R assembly keypair.snk"
Resign the specified assembly using the specified strongname keypair file
(SNK). You can only sign an assembly with the private key (SNK) that match
the public key inside the assembly (unless it's public key token has been
remapped in machine.config).
(SNK).
.TP
.I "-Rc assembly container"
Resign the specified assembly using the specified strongname container.
@@ -96,10 +83,10 @@ Show the public key from the specified assembly.
.I "-Tp assembly"
Show the public key and the public key token from the specified assembly.
.TP
.I "-v assembly"
.I "-V assembly"
Verify the specified assembly signature.
.TP
.I "-vf assembly"
.I "-Vf assembly"
Verify the specified assembly signature (even if disabled).
.SH HELP OPTIONS
.TP
@@ -117,35 +104,10 @@ Display convertion related help about this tool.
.TP
.I "-h sn", "-? sn"
Display strongname related help about this tool.
.SH CONFIGURATION FILE
.TP
Strongnames configuration is kept in "machine.config" file. Currently two
features can be configured.
.TP
.I "/configuration/strongNames/pubTokenMapping"
This mechanism let Mono remap a public key token, like the ECMA token, to
another public key for verification. This is useful in two scenarios. First
assemblies signed with the "ECMA key" needs to be verified by the "runtime"
key (as the ECMA key isn't a public key). Second, many assemblies are signed
with private keys that Mono can't use (e.g. System.Security.dll assembly).
A new key cannot be used because it should change thr strongname (a new key
pair would have a new public key which would produce a new token). Public
key token remapping is the solution for both problems. Each token must be
configured in a "map" entry similar to this one: <map Token="b77a5c561934e089"
PublicKey="00..." />
.TP
.I "/configuration/strongNames/verificationSettings"
It is often useful during development to use delay signed assemblies.
Normally* the runtime wouldn't allow delay-signed assemblies to be loaded.
This feature allows some delay-signed assemblies (based on their public key
token, optionally assembly name and user name) to be used like they were
fully signed assemblies. [*] Note that Mono 1.0 "runtime" doesn't validate
strongname signatures so this option shouldn't be required in most scenarios.
.SH AUTHOR
Written by Sebastien Pouliot
.SH COPYRIGHT
Copyright (C) 2003 Motus Technologies.
Copyright (C) 2004 Novell.
Released under BSD license.
.SH MAILING LISTS
Visit http://mail.ximian.com/mailman/mono-list for details.
+1 -1
View File
@@ -50,7 +50,7 @@ Specifies the namespace of the XML schema element for which a class or a dataset
Specifies the programming language to use for the generated code. The only supported languages are CS (C#) and VB (Visual Basic.NET).
.TP
.I "/generator:type,assembly" "/g:type,assembly"
Indicates xsd.exe to use custom CodeDomProvider to generate code. The type name must be full name. Assembly name is a local file name that is going to be loaded. The specified Type must have the default constructor.
Indicates xsd.exe to use custom CodeDomProvider to generate code. Type name must be full name. Assembly name is file name that xsd.exe tries to load.
.TP
.I "/outputdir:path" "/o:path"
Specifies the directory where to generate the code or schemas.
-79
View File
@@ -1,79 +0,0 @@
/*
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
@@ -1,344 +0,0 @@
/*
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
@@ -1,124 +0,0 @@
<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
@@ -1,59 +0,0 @@
<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
@@ -1,469 +0,0 @@
/*
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
@@ -1,19 +0,0 @@
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
@@ -1,636 +0,0 @@
/*
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
@@ -1,492 +0,0 @@
/*
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
}
}
@@ -1,70 +0,0 @@
/*
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
@@ -1,568 +0,0 @@
/*
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
@@ -1 +0,0 @@
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
@@ -1,134 +0,0 @@
/*
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
@@ -1,25 +0,0 @@
#!/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";
+14
View File
@@ -0,0 +1,14 @@
compiler.pdb
compiler.exe
compiler.suo
compiler.csproj
compiler.csproj.user
cs-parser.cs
y.output
*.pdb
mcs
Web References
bin
obj
Web References
Web References
+8
View File
@@ -0,0 +1,8 @@
using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyVersion("0.94")]
[assembly: AssemblyTitle ("Mono C# Compiler")]
[assembly: AssemblyDescription ("Mono C# Compiler")]
[assembly: AssemblyCopyright ("2001, 2002, 2003 Ximian, Inc.")]
[assembly: AssemblyCompany ("Ximian, Inc.")]
+15266
View File
File diff suppressed because it is too large. Load diff
+406
View File
@@ -0,0 +1,406 @@
//
// 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;
}
}
}
+70
View File
@@ -0,0 +1,70 @@
thisdir := mcs
SUBDIRS :=
include ../build/rules.make
BUILT_SOURCES = cs-parser.cs
EXTRA_DISTFILES = \
compiler.csproj \
compiler.doc \
compiler.sln \
cs-parser.jay \
mcs.exe.config \
NOTES \
TODO
PROGRAM = mcs.exe
PROGRAM_COMPILE = $(BOOT_COMPILE)
PROGRAM_INSTALL_DIR = $(prefix)/lib/mono/1.0
CLEAN_FILES = y.output
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 $@
include ../build/executable.make
# Testing targets
TIME = time
# This used to be called test, but that conflicts with the global
# recursive target.
btest: mcs2.exe mcs3.exe
ls -l mcs2.exe mcs3.exe
mcs2.exe: mcs.exe
$(TIME) $(RUNTIME) ./mcs.exe $(USE_MCS_FLAGS) /target:exe /out:$@ $(BUILT_SOURCES) @$(response)
mcs3.exe: mcs2.exe
$(TIME) $(RUNTIME) ./mcs2.exe $(USE_MCS_FLAGS) /target:exe /out:$@ $(BUILT_SOURCES) @$(response)
wc:
wc -l $(BUILT_SOURCES) `cat $(sourcefile)`
ctest:
rm -f mcs2.exe mcs3.exe
$(MAKE) USE_MCS_FLAGS= btest
# 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: "
@ rm -f mcs2.exe
@ $(MAKE) TIME="$(FRIENDLY_TIME)" mcs2.exe > /dev/null || (echo FAILED; exit 1)
@ echo -n "Run 2: "
@ rm -f mcs3.exe
@ $(MAKE) TIME="$(FRIENDLY_TIME)" mcs3.exe > /dev/null || (echo FAILED; exit 1)
@ $(MAKE) do-corlib
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 : mcs.exe
$(RUNTIME) --profile=$(PROFILER) ./mcs.exe $(USE_MCS_FLAGS) /target:exe /out:mcs2.exe $(BUILT_SOURCES) @$(response)
+38
View File
@@ -0,0 +1,38 @@
* Notes on improving error handling in MCS
(from Axel Schreiner <[email protected]>)
I included the 'recover' example with C# as well. Currently the package
is at <http://www.cs.rit.edu/~ats/projects/jay/>. I did change some
names and the embedding that the user does somewhat, i.e., it is not
directly compatible with what you did.
Here is the important part about error recovery. To make the typical
iterations bullet-proof, code them as follows:
opt : // null
| opt WORD { yyErrorFlag = 0; }
| opt error
seq : WORD
| seq WORD { yyErrorFlag = 0; }
| error
| seq error
list : WORD
| list ',' WORD { yyErrorFlag = 0; }
| error
| list error
| list error WORD { yyErrorFlag = 0; }
| list ',' error
i.e., throw in 'error' wherever a token can be. 'yyErrorFlag' need not
be set to zero, but if it is done this way, second errors are caught
earlier. This may introduce s/r conflicts, but they tend to be harmless.
In your case -- the comment concerning error recovery at the beginning
of your compiler jay file -- just adding 'error' to the different
global things won't work. Your example will already have started to
advance in one of the rules and 'error' is then not in the lookahead of
wherever the parse then is. You need to put 'error' into the iteration
above those global things.
+58
View File
@@ -0,0 +1,58 @@
These are the sources to the Mono C# compiler
---------------------------------------------
Read the mcs/docs/compiler.txt for an overview of the compiler.
Testing the Compiler
--------------------
You might want to use the `make btest' in this directory to
have the compiler bootstrap itself, this is the basic regression
test.
Before commiting changes to MCS, make sure that all the tests
in `mcs/tests' pass, type:
cd mcs/tests
make run-test-local
There is a new set of negative tests (errors that the compiler
should flag), but not all of them pass currently:
cd mcs/errors
make run-test-local
Full Bootstrap
==============
To finally ensure the state of the compiler, it is ideal to do
a full bootstrap, to do this, do:
cd mcs
make clean;
make
make install
That installs the compiler and assemblies compiled by the new compiler.
Then, repeat that step again:
make clean
make
If things work, the compiler has not added a new regression
while building the mscorlib and the compiler itself.
Tests
=====
When bugs are fixed, new tests must be added to the
`mcs/tests' directory to excercise the problem and to guarantee
that we keep the compiler in a good state.
When an error is reported, it should be added to mcs/errors.
We try to make the errors numbers be the same as the ones in
Microsoft C#, if this is not possible, allocate a negative error
number, and list it in mcs/errors/errors.txt
+433
View File
@@ -0,0 +1,433 @@
Error Reporting:
----------------
* Make yyerror show a nice syntax error, instead of the current mess.
Iterators
---------
* `yield' is no longer a keyword, it only has special
meaning before a return or break keywords.
* Study side effects with assign
* Study TemporaryStorage/LocalStorage -> Merge/rename
* Reset should throw not implemented now.
Instance idea
-------------
It would be nice to have things that can be "instances" to have an
EmitInstance method (this would default to nothing).
The idea is to be able to use efficiently the instance data on stack
manipulations, as opposed to the current scheme, where we basically have
a few special cases.
Optimization ideas
------------------
Currently when we build a type cache, it contains private members,
internal members, and internal protected members; We should trim
these out, as it shows up on the profile.
We create too many Arraylists; When we know the size, we should create
an array;
During parsing we use arraylists to accumulate data, like this:
thing:
thing_list
: thing { $$ =new ArrayList (); $$.Add ($1); }
| thing_list thing { ArrayList a = $1; a.Add ($2); $$ = a; }
We probably could start using "Pairs" there:
thing_list
: thing { $$ = new Pair ($1, null); }
| thing_list thing { Pair p = $1; $$ = new Pair ($2, $1); }
Anonymous Methods
-----------------
Plan:
* Resolve anonymous methods before.
* Each time a Local matches, if the mode is `InAnonymous', flag
the VariableInfo for `proxying'.
* During Resolve track the depth required for local variables.
* Before Emit, create proxy classes with proper depth.
* Emit.
Open question:
Create a toplevel block for anonymous methods?
EmitContext.ResolveTypeTree
---------------------------
We should investigate its usage. The problem is that by default
this will be set when calling FindType, that triggers a more expensive
lookup.
I believe we should pass the current EmitContext (which has this turned off
by default) to ResolveType/REsolveTypeExpr and then have the routines that
need ResolveType to pass null as the emit context.
DeclareLocal audit
------------------
DeclareLocal is used in various statements. The audit should be done
in two steps:
* Identify all the declare locals.
* Identify its uses.
* Find if we can make wrapper functions for all of them.
Then we can move DeclareLocal into a helper class.
This is required to fix foreach in iterators.
Large project:
--------------
Drop FindMembers as our API and instead extract all the data
out of a type the first time into our own datastructures, and
use that to navigate and search the type instead of the
callback based FindMembers.
Martin has some some of this work with his TypeHandle code
that we could use for this.
Notes on memory allocation
--------------------------
Outdated:
A run of the AllocationProfile shows that the compiler allocates roughly
30 megabytes of strings. From those, 20 megabytes come from
LookupType.
See the notes on current_container problems below on memory usage.
LookupTypeReflection:
---------------------
With something like `System.Object', LookupTypeReflection will be called
twice: once to find out that `System' is not a type and once
for System.Object.
This is required because System.Reflection requires that the type/nested types are
not separated by a dot but by a plus sign.
A nested class would be My+Class (My being the toplevel, Class the nested one).
It is interesting to look at the most called lookups when bootstrapping MCS:
647 LTR: ArrayList
713 LTR: System.Globalization
822 LTR: System.Object+Expression
904 LTR: Mono.CSharp.ArrayList
976 LTR: System.Runtime.CompilerServices
999 LTR: Type
1118 LTR: System.Runtime
1208 LTR: Mono.CSharp.Type
1373 LTR: Mono.Languages
1599 LTR: System.Diagnostics
2036 LTR: System.Text
2302 LTR: System.Reflection.Emit
2515 LTR: System.Collections
4527 LTR: System.Reflection
22273 LTR: Mono.CSharp
24245 LTR: System
27005 LTR: Mono
Analysis:
The top 9 lookups are done for things which are not types.
Mono.CSharp.Type happens to be a common lookup: the class Type
used heavily in the compiler in the default namespace.
RED FLAG:
Then `Type' is looked up alone a lot of the time, this happens
in parameter declarations and am not entirely sure that this is
correct (FindType will pass to LookupInterfaceOrClass a the current_type.FullName,
which for some reason is null!). This seems to be a problem with a lost
piece of context during FindType.
System.Object is also used a lot as a toplevel class, and we assume it will
have children, we should just shortcut this.
A cache:
Adding a cache and adding a catch for `System.Object' to flag that it wont be the
root of a hierarchy reduced the MCS bootstrap time from 10.22 seconds to 8.90 seconds.
This cache is currently enabled with SIMPLE_SPEEDUP in typemanager.cs. Memory consumption
went down from 74 megs to 65 megs with this change.
Ideas:
------
Instead of the hack that *knows* about System.Object not having any children classes,
we should just make it simple for a probe to know that there is no need for it.
The use of DottedName
---------------------
We could probably use a different system to represent names, like this:
class Name {
string simplename;
Name parent;
}
So `System.ComponentModel' becomes:
x: (System, null)
y: (ComponentModel, x)
The problem is that we would still need to construct the name to pass to
GetType.
This has been now implemented, its called "QualifiedIdentifier"
current_container/current_namespace and the DeclSpace
-----------------------------------------------------
We are storing fully qualified names in the DeclSpace instead of the node,
this is because `current_namespace' (Namepsace) is not a DeclSpace like
`current_container'.
The reason for storing the full names today is this:
namespace X {
class Y {
}
}
namespace A {
class Y {
}
}
The problem is that we only use the namespace stack to track the "prefix"
for typecontainers, but they are not typecontainers themselves, so we have
to use fully qualified names, because both A.X and A.Y would be entered
in the toplevel type container. If we use the short names, there would be
a name clash.
To fix this problem, we have to make namespaces DeclSpaces.
The full size, contrasted with the size that could be stored is:
corlib:
Size of strings held: 368901
Size of strings short: 147863
System:
Size of strings held: 212677
Size of strings short: 97521
System.XML:
Size of strings held: 128055
Size of strings short: 35782
System.Data:
Size of strings held: 117896
Size of strings short: 36153
System.Web:
Size of strings held: 194527
Size of strings short: 58064
System.Windows.Forms:
Size of strings held: 220495
Size of strings short: 64923
TODO:
1. Create a "partial" emit context for each TypeContainer..
2. EmitContext should be partially constructed. No IL Generator.
interface_type review.
parameter_array, line 952: `note: must be a single dimension array type'. Validate this
Dead Code Elimination bugs:
---------------------------
I should also resolve all the children expressions in Switch, Fixed, Using.
Major tasks:
------------
Pinned and volatile require type modifiers that can not be encoded
with Reflection.Emit.
Properties and 17.6.3: Finish it.
Implement base indexer access.
readonly variables and ref/out
BUGS
----
* Check for Final when overriding, if the parent is Final, then we cant
allow an override.
* Interface indexers
I have not figured out why the Microsoft version puts an
`instance' attribute, and I am not generating this `instance' attribute.
Explanation: The reason for the `instance' attribute on
indexers is that indexers only apply to instances
* Break/Continue statements
A finally block should reset the InLoop/LoopBegin/LoopEnd, as
they are logically outside the scope of the loop.
* Break/continue part 2.
They should transfer control to the finally block if inside a try/catch
block.
* Method Registration and error CS111
The way we use the method registration to signal 111 is wrong.
Method registration should only be used to register methodbuilders,
we need an alternate method of checking for duplicates.
*
> // CSC sets beforefieldinit
> class X {
> // .cctor will be generated by compiler
> public static readonly object O = new System.Object ();
> public static void Main () {}
> }
>
PENDING TASKS
-------------
* Merge test 89 and test-34
* Revisit
Primary-expression, as it has now been split into
non-array-creation-expression and array-creation-expression.
* Code cleanup
The information when registering a method in InternalParameters
is duplicated, you can always get the types from the InternalParameters
* Emit modreq for volatiles
Handle modreq from public apis.
* Emit `pinned' for pinned local variables.
Both `modreq' and pinned will require special hacks in the compiler.
* Make sure that we are pinning the right variable
* Merge tree.cs, rootcontext.cs
OPTIMIZATIONS
-------------
* User Defined Conversions is doing way too many calls to do union sets that are not needed
* Add test case for destructors
* Places that use `Ldelema' are basically places where I will be
initializing a value type. I could apply an optimization to
disable the implicit local temporary from being created (by using
the method in New).
* Dropping TypeContainer as an argument to EmitContext
My theory is that I can get rid of the TypeBuilder completely from
the EmitContext, and have typecasts where it is used (from
DeclSpace to where it matters).
The only pending problem is that the code that implements Aliases
is on TypeContainer, and probably should go in DeclSpace.
* Use of local temporary in UnaryMutator
We should get rid of the Localtemporary there for some cases
This turns out to be very complex, at least for the post-version,
because this case:
a = i++
To produce optimal code, it is necessary for UnaryMutator to know
that it is being assigned to a variable (the way the stack is laid
out using dup requires the store to happen inside UnaryMutator).
* Tests
Write tests for the various reference conversions. We have
test for all the numeric conversions.
* Optimizations
In Indexers and Properties, probably support an EmitWithDup
That emits the code to call Get and then leaves a this pointer
in the stack, so that later a Store can be emitted using that
this pointer (consider Property++ or Indexer++)
* Optimizations: variable allocation.
When local variables of a type are required, we should request
the variable and later release it when we are done, so that
the same local variable slot can be reused later on.
* Add a cache for the various GetArrayMethod operations.
* MakeUnionSet Callers
If the types are the same, there is no need to compute the unionset,
we can just use the list from one of the types.
* Factor the lookup code for class declarations an interfaces
(interface.cs:GetInterfaceByName)
RECOMMENDATIONS
---------------
* Use of lexer.Location in the parser
Currently we do:
TOKEN nt TERMINAL nt TERMINAL nt3 {
$$ = new Blah ($2, $4, $6, lexer.Location);
}
This is bad, because the lexer.Location is for the last item in `nt3'
We need to change that to use this pattern:
TOKEN { oob_stack.Push (lexer.Location) } nt TERMINAL nt TERMINAL nt3 {
$$ = new Blah ($3, $5, $7, (Location) oob_stack.Pop ());
}
Notice how numbering of the arguments changes as the
{ oob_stack.Push (lexer.Location) } takes a "slot" in the productions.
* local_variable_declaration
Not sure that this grammar is correct, we might have to
resolve this during semantic analysis.
+52
View File
@@ -0,0 +1,52 @@
//
// anonymous.cs: Support for anonymous methods
//
// Author:
// Miguel de Icaza ([email protected])
//
// (C) 2003 Ximian, Inc.
//
using System;
using System.Collections;
using System.Reflection;
using System.Reflection.Emit;
namespace Mono.CSharp {
public class AnonymousMethod : Expression {
// An array list of AnonymousMethodParameter or null
Parameters parameters;
Block block;
public AnonymousMethod (Parameters parameters, Block block, Location l)
{
this.parameters = parameters;
this.block = block;
loc = l;
}
public override Expression DoResolve (EmitContext ec)
{
//
// Set class type, set type
//
eclass = ExprClass.Value;
//
// This hack means `The type is not accessible
// anywhere', we depend on special conversion
// rules.
//
type = typeof (AnonymousMethod);
return this;
}
public override void Emit (EmitContext ec)
{
// nothing, as we only exist to not do anything.
}
}
}
+501
View File
@@ -0,0 +1,501 @@
//
// 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 method will emit the code for the actual assignment
//
void EmitAssign (EmitContext ec, Expression source);
//
// This method is invoked before any code generation takes
// place, and it is a mechanism to inform that the expression
// will be invoked more than once, and that the method should
// use temporary values to avoid having side effects
//
// Example: a [ g () ] ++
//
void CacheTemporaries (EmitContext ec);
}
/// <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.
/// </remarks>
public class LocalTemporary : Expression, IMemoryLocation {
LocalBuilder builder;
public LocalTemporary (EmitContext ec, Type t)
{
type = t;
eclass = ExprClass.Value;
loc = Location.Null;
builder = ec.GetTemporaryLocal (t);
}
public void Release (EmitContext ec)
{
ec.FreeTemporaryLocal (builder, type);
builder = null;
}
public LocalTemporary (LocalBuilder b, Type t)
{
type = t;
eclass = ExprClass.Value;
loc = Location.Null;
builder = b;
}
public override Expression DoResolve (EmitContext ec)
{
return this;
}
public override void Emit (EmitContext ec)
{
ec.ig.Emit (OpCodes.Ldloc, builder);
}
public void Store (EmitContext ec)
{
ec.ig.Emit (OpCodes.Stloc, builder);
}
public void AddressOf (EmitContext ec, AddressOp mode)
{
ec.ig.Emit (OpCodes.Ldloca, builder);
}
}
/// <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 (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;
}
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");
return null;
} else if (!RootContext.V2 && (source is MethodGroupExpr)){
((MethodGroupExpr) source).ReportUsageError ();
return null;
}
if (target_type == source_type)
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 (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);
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;
}
bool use_temporaries = false;
//
// FIXME! We need a way to "probe" if the process can
// just use `dup' to propagate the result
//
IAssignMethod am = (IAssignMethod) target;
if (this is CompoundAssign)
am.CacheTemporaries (ec);
if (!is_statement)
use_temporaries = true;
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;
if (use_temporaries){
//
// Doing this for every path is too expensive
// I wonder if we can work around this and have a less
// expensive path
//
LocalTemporary tempo;
tempo = new LocalTemporary (ec, source.Type);
temp_source.Emit (ec);
tempo.Store (ec);
am.EmitAssign (ec, tempo);
if (!is_statement)
tempo.Emit (ec);
tempo.Release (ec);
} else {
am.EmitAssign (ec, temp_source);
}
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);
}
}
}
+1370
View File
File diff suppressed because it is too large. Load diff
+1191
View File
File diff suppressed because it is too large. Load diff
+6489
View File
File diff suppressed because it is too large. Load diff
+1029
View File
File diff suppressed because it is too large. Load diff
+258
View File
@@ -0,0 +1,258 @@
<VisualStudioProject>
<CSHARP
ProjectType = "Local"
ProductVersion = "7.10.3077"
SchemaVersion = "2.0"
ProjectGuid = "{896D1461-B76B-41C0-ABE6-ACA2BB4F7B5A}"
>
<Build>
<Settings
ApplicationIcon = ""
AssemblyKeyContainerName = ""
AssemblyName = "mcs"
AssemblyOriginatorKeyFile = ""
DefaultClientScript = "JScript"
DefaultHTMLPageLayout = "Grid"
DefaultTargetSchema = "IE50"
DelaySign = "false"
OutputType = "Exe"
PreBuildEvent = ""
PostBuildEvent = ""
RootNamespace = "CIR"
RunPostBuildEvent = "OnBuildSuccess"
StartupObject = ""
>
<Config
Name = "Debug"
AllowUnsafeBlocks = "false"
BaseAddress = "285212672"
CheckForOverflowUnderflow = "false"
ConfigurationOverrideFile = ""
DefineConstants = "DEBUG;TRACE"
DocumentationFile = ""
DebugSymbols = "true"
FileAlignment = "4096"
IncrementalBuild = "false"
NoStdLib = "false"
NoWarn = ""
Optimize = "false"
OutputPath = ".\"
RegisterForComInterop = "false"
RemoveIntegerChecks = "false"
TreatWarningsAsErrors = "false"
WarningLevel = "4"
/>
<Config
Name = "Release"
AllowUnsafeBlocks = "false"
BaseAddress = "285212672"
CheckForOverflowUnderflow = "false"
ConfigurationOverrideFile = ""
DefineConstants = "TRACE"
DocumentationFile = ""
DebugSymbols = "false"
FileAlignment = "4096"
IncrementalBuild = "true"
NoStdLib = "false"
NoWarn = ""
Optimize = "true"
OutputPath = "bin\Release\"
RegisterForComInterop = "false"
RemoveIntegerChecks = "false"
TreatWarningsAsErrors = "false"
WarningLevel = "4"
/>
</Settings>
<References>
<Reference
Name = "System"
AssemblyName = "System"
/>
</References>
</Build>
<Files>
<Include>
<File
RelPath = "anonymous.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "AssemblyInfo.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "assign.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "attribute.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "cfold.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "class.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "codegen.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "const.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "constant.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "convert.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "CryptoConvert.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "cs-parser.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "cs-tokenizer.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "decl.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "delegate.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "driver.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "ecore.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "enum.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "expression.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "flowanalysis.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "genericparser.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "iterators.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "literal.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "location.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "modifiers.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "namespace.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "parameter.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "pending.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "report.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "rootcontext.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "statement.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "support.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "symbolwriter.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "tree.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<File
RelPath = "typemanager.cs"
SubType = "Code"
BuildAction = "Compile"
/>
<Folder
RelPath = "Web References\"
WebReferences = "TRUE"
/>
</Include>
</Files>
</CSHARP>
</VisualStudioProject>
+114
View File
@@ -0,0 +1,114 @@
Compiler operation
The compiler has a number of phases:
* Parsing.
Initially the compiler parses all the source files and keeps a
parsed representation in memory. Very syntax error checking
is performed at this point.
The compiler stores the information in classes whose names
represent the language construct, for example, the "if"
construct is stored in an `If' class. A class is stored in a
`Class'.
* The TypeManager
The TypeManager loads all the assemblies that were referenced
by the programmer. The CLR type system is used as our
repository for types defined as well.
So the same interface that is used to query the types,
properties and flags about system types is the same interface
that we use for our types.
As we work our way through the code generation and semantic
analysis, new types are entered into the Type system through
the use of System.Reflection.Emit. The TypeManager will
lookup types on both the user defined types and on the system
defined ones.
So special care has to be used. The order in which we
proceeed from here is important.
* Base class resolution and type definition.
Once the parsing has happened, the compiler resolves the
inheritance tree for interfaces. This is done recursively
and we catch recursive interface definitions here.
After this is done, we continue on with classes. Classes have
can have an optional "parent" inherit from or the implicit
System.Object class (for normal builds, builds with /nostdlib
will allow you to compile class System.Object with no parent).
At this point we do some error checking and verify that the
inherits/implements section of a class is correct (since we
have previously built the interface inheritance).
By the time we are done, all classes, structs and interfaces
have been created using System.Reflection.Emit and registered
with the Type Manager.
This allows us to define fields and resolve argument names for
methods, properties, indexers and events.
* Field generation
Fields are generated next, we go through all the type
containers (classes and structs) and enter the fields into
their types.
* Method, Properties, Indexers and events definitions
Now all the methods, constructors, properties, indexers and
events are entered. They are only `defined' using
System.Reflection.Emit. No code generation will happen until
everything has been entered into System.Reflection.Emit.
This is important because to actually generate code we need to
know everything about the environment in which the code is
being generated.
* Code Generation
At this point all the definitions have been entered into the
type manager through System.Reflection.Emit. We can now use
System.Reflection to query all the information about the
types.
Your normal semantic analysis and code generation phase lives
here.
* Statements
Most of the statements are handled in the codegen.cs file.
* Expressions
* Error reporting
We should try to use the `Report.Error' and `Report.Warning'
classes which are part of the RootContext (there is even a
property to access it).
Error reporting should try to use the same codes that the
Microsoft compiler uses (if only so we can track which errors
we handle and which ones we dont).
If there is an error which is specific to MSC, use negative
numbers, and register the number in mcs/errors/errors.txt
Try to write a test case for any error that you run into the
code of the compiler if there is none already.
Put your test case in a file called csNNNN.cs in the
mcs/errors directory, and have the first two lines be:
// csNNNN.cs: This is the description.
// Line: XXX
Where `XXX' is the line where the error ocurrs. We will later
use this as a regression test suite for catching errors in the
compiler.
+21
View File
@@ -0,0 +1,21 @@
Microsoft Visual Studio Solution File, Format Version 8.00
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "compiler", "compiler.csproj", "{896D1461-B76B-41C0-ABE6-ACA2BB4F7B5A}"
ProjectSection(ProjectDependencies) = postProject
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfiguration) = preSolution
Debug = Debug
Release = Release
EndGlobalSection
GlobalSection(ProjectConfiguration) = postSolution
{896D1461-B76B-41C0-ABE6-ACA2BB4F7B5A}.Debug.ActiveCfg = Debug|.NET
{896D1461-B76B-41C0-ABE6-ACA2BB4F7B5A}.Debug.Build.0 = Debug|.NET
{896D1461-B76B-41C0-ABE6-ACA2BB4F7B5A}.Release.ActiveCfg = Release|.NET
{896D1461-B76B-41C0-ABE6-ACA2BB4F7B5A}.Release.Build.0 = Release|.NET
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
EndGlobalSection
GlobalSection(ExtensibilityAddIns) = postSolution
EndGlobalSection
EndGlobal
+307
View File
@@ -0,0 +1,307 @@
//
// 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 : FieldBase {
public Expression Expr;
EmitContext const_ec;
bool resolved = false;
object ConstantValue = null;
Type type;
bool in_transit = false;
public const int AllowedModifiers =
Modifiers.NEW |
Modifiers.PUBLIC |
Modifiers.PROTECTED |
Modifiers.INTERNAL |
Modifiers.PRIVATE;
public Const (Expression constant_type, string name, Expression expr, int mod_flags,
Attributes attrs, Location loc)
: base (constant_type, mod_flags, AllowedModifiers, name, null, attrs, loc)
{
Expr = expr;
}
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 (TypeContainer parent)
{
type = parent.ResolveType (Type, false, Location);
if (type == null)
return false;
const_ec = new EmitContext (parent, Location, null, type, ModFlags);
Type ttype = type;
while (ttype.IsArray)
ttype = TypeManager.GetElementType (ttype);
if (!TypeManager.IsBuiltinType (ttype) &&
(!ttype.IsSubclassOf (TypeManager.enum_type))) {
Report.Error (
-3, Location,
"Constant type is not valid (only system types are allowed)");
return false;
}
Type ptype = parent.TypeBuilder.BaseType;
if (ptype != null) {
MemberList list = TypeContainer.FindMembers (
ptype, MemberTypes.Field, BindingFlags.Public,
System.Type.FilterName, Name);
if (list.Count == 0)
if ((ModFlags & Modifiers.NEW) != 0)
WarningNotHiding (parent);
} else if ((ModFlags & Modifiers.NEW) != 0)
WarningNotHiding (parent);
FieldBuilder = parent.TypeBuilder.DefineField (Name, type, 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 (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) {
ArrayCreation ac = (ArrayCreation) Expr;
Expr = ac.TurnIntoConstant ();
if (Expr == null){
Report.Error (150, Location, "A constant value is expected");
value = null;
return false;
}
} else {
if (errors == Report.Errors)
Report.Error (150, Location, "A constant value is expected");
value = null;
return false;
}
ce = Expr as Constant;
}
if (type != real_expr.Type) {
ce = ChangeType (Location, ce, type);
if (ce == null){
value = null;
return false;
}
Expr = ce;
}
ConstantValue = ce.GetValue ();
if (type.IsEnum){
//
// This sadly does not work for our user-defined enumerations types ;-(
//
try {
ConstantValue = System.Enum.ToObject (
type, 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 (TypeContainer parent)
{
object value;
LookupConstantValue (out value);
if (OptAttributes != null) {
OptAttributes.Emit (const_ec, this);
}
base.Emit (parent);
}
}
}
+1025
View File
File diff suppressed because it is too large. Load diff
+1775
View File
File diff suppressed because it is too large. Load diff
+4305
View File
File diff suppressed because it is too large. Load diff
+1960
View File
File diff suppressed because it is too large. Load diff
+1931
View File
File diff suppressed because it is too large. Load diff
+947
View File
@@ -0,0 +1,947 @@
//
// delegate.cs: Delegate Handler
//
// Authors:
// Ravi Pratap ([email protected])
// 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.Text;
namespace Mono.CSharp {
/// <summary>
/// Holds Delegates
/// </summary>
public class Delegate : DeclSpace {
public Expression ReturnType;
public Parameters Parameters;
public ConstructorBuilder ConstructorBuilder;
public MethodBuilder InvokeBuilder;
public MethodBuilder BeginInvokeBuilder;
public MethodBuilder EndInvokeBuilder;
Type [] param_types;
Type ret_type;
static string[] attribute_targets = new string [] { "type", "return" };
Expression instance_expr;
MethodBase delegate_method;
ReturnParameter return_attributes;
const int AllowedModifiers =
Modifiers.NEW |
Modifiers.PUBLIC |
Modifiers.PROTECTED |
Modifiers.INTERNAL |
Modifiers.UNSAFE |
Modifiers.PRIVATE;
public Delegate (NamespaceEntry ns, TypeContainer parent, Expression type,
int mod_flags, string name, Parameters param_list,
Attributes attrs, Location l)
: base (ns, parent, name, attrs, l)
{
this.ReturnType = type;
ModFlags = Modifiers.Check (AllowedModifiers, mod_flags,
IsTopLevel ? Modifiers.INTERNAL :
Modifiers.PRIVATE, l);
Parameters = param_list;
}
public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
{
if (a.Target == "return") {
if (return_attributes == null)
return_attributes = new ReturnParameter (InvokeBuilder, Location);
return_attributes.ApplyAttributeBuilder (a, cb);
return;
}
base.ApplyAttributeBuilder (a, cb);
}
public override TypeBuilder DefineType ()
{
if (TypeBuilder != null)
return TypeBuilder;
TypeAttributes attr = Modifiers.TypeAttr (ModFlags, IsTopLevel) |
TypeAttributes.Class | TypeAttributes.Sealed;
if (IsTopLevel) {
if (TypeManager.NamespaceClash (Name, Location))
return null;
ModuleBuilder builder = CodeGen.Module.Builder;
TypeBuilder = builder.DefineType (
Name, attr, TypeManager.multicast_delegate_type);
} else {
TypeBuilder builder = Parent.TypeBuilder;
string name = Name.Substring (1 + Name.LastIndexOf ('.'));
TypeBuilder = builder.DefineNestedType (
name, attr, TypeManager.multicast_delegate_type);
}
TypeManager.AddDelegateType (Name, TypeBuilder, this);
return TypeBuilder;
}
public override bool DefineMembers (TypeContainer container)
{
return true;
}
public override bool Define (TypeContainer container)
{
MethodAttributes mattr;
int i;
EmitContext ec = new EmitContext (this, this, Location, null,
null, ModFlags, false);
// FIXME: POSSIBLY make this static, as it is always constant
//
Type [] const_arg_types = new Type [2];
const_arg_types [0] = TypeManager.object_type;
const_arg_types [1] = TypeManager.intptr_type;
mattr = MethodAttributes.RTSpecialName | MethodAttributes.SpecialName |
MethodAttributes.HideBySig | MethodAttributes.Public;
ConstructorBuilder = TypeBuilder.DefineConstructor (mattr,
CallingConventions.Standard,
const_arg_types);
ConstructorBuilder.DefineParameter (1, ParameterAttributes.None, "object");
ConstructorBuilder.DefineParameter (2, ParameterAttributes.None, "method");
//
// HACK because System.Reflection.Emit is lame
//
//
// FIXME: POSSIBLY make these static, as they are always the same
Parameter [] fixed_pars = new Parameter [2];
fixed_pars [0] = new Parameter (null, null, Parameter.Modifier.NONE, null);
fixed_pars [1] = new Parameter (null, null, Parameter.Modifier.NONE, null);
Parameters const_parameters = new Parameters (fixed_pars, null, Location);
TypeManager.RegisterMethod (
ConstructorBuilder,
new InternalParameters (const_arg_types, const_parameters),
const_arg_types);
ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
//
// Here the various methods like Invoke, BeginInvoke etc are defined
//
// First, call the `out of band' special method for
// defining recursively any types we need:
if (!Parameters.ComputeAndDefineParameterTypes (this))
return false;
param_types = Parameters.GetParameterInfo (this);
if (param_types == null)
return false;
//
// Invoke method
//
// Check accessibility
foreach (Type partype in param_types){
if (!container.AsAccessible (partype, ModFlags)) {
Report.Error (59, Location,
"Inconsistent accessibility: parameter type `" +
TypeManager.CSharpName (partype) + "` is less " +
"accessible than delegate `" + Name + "'");
return false;
}
if (partype.IsPointer && !UnsafeOK (container))
return false;
}
ReturnType = ResolveTypeExpr (ReturnType, false, Location);
if (ReturnType == null)
return false;
ret_type = ReturnType.Type;
if (ret_type == null)
return false;
if (!container.AsAccessible (ret_type, ModFlags)) {
Report.Error (58, Location,
"Inconsistent accessibility: return type `" +
TypeManager.CSharpName (ret_type) + "` is less " +
"accessible than delegate `" + Name + "'");
return false;
}
if (ret_type.IsPointer && !UnsafeOK (container))
return false;
//
// We don't have to check any others because they are all
// guaranteed to be accessible - they are standard types.
//
CallingConventions cc = Parameters.GetCallingConvention ();
mattr = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual;
InvokeBuilder = TypeBuilder.DefineMethod ("Invoke",
mattr,
cc,
ret_type,
param_types);
//
// Define parameters, and count out/ref parameters
//
int out_params = 0;
i = 0;
if (Parameters.FixedParameters != null){
int top = Parameters.FixedParameters.Length;
Parameter p;
for (; i < top; i++) {
p = Parameters.FixedParameters [i];
p.DefineParameter (ec, InvokeBuilder, null, i + 1, Location);
if ((p.ModFlags & Parameter.Modifier.ISBYREF) != 0)
out_params++;
}
}
if (Parameters.ArrayParameter != null){
Parameter p = Parameters.ArrayParameter;
p.DefineParameter (ec, InvokeBuilder, null, i + 1, Location);
}
InvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
TypeManager.RegisterMethod (InvokeBuilder,
new InternalParameters (container, Parameters),
param_types);
//
// BeginInvoke
//
int params_num = param_types.Length;
Type [] async_param_types = new Type [params_num + 2];
param_types.CopyTo (async_param_types, 0);
async_param_types [params_num] = TypeManager.asynccallback_type;
async_param_types [params_num + 1] = TypeManager.object_type;
mattr = MethodAttributes.Public | MethodAttributes.HideBySig |
MethodAttributes.Virtual | MethodAttributes.NewSlot;
BeginInvokeBuilder = TypeBuilder.DefineMethod ("BeginInvoke",
mattr,
cc,
TypeManager.iasyncresult_type,
async_param_types);
i = 0;
if (Parameters.FixedParameters != null){
int top = Parameters.FixedParameters.Length;
Parameter p;
for (i = 0 ; i < top; i++) {
p = Parameters.FixedParameters [i];
p.DefineParameter (ec, BeginInvokeBuilder, null, i + 1, Location);
}
}
if (Parameters.ArrayParameter != null){
Parameter p = Parameters.ArrayParameter;
p.DefineParameter (ec, BeginInvokeBuilder, null, i + 1, Location);
i++;
}
BeginInvokeBuilder.DefineParameter (i + 1, ParameterAttributes.None, "callback");
BeginInvokeBuilder.DefineParameter (i + 2, ParameterAttributes.None, "object");
BeginInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
Parameter [] async_params = new Parameter [params_num + 2];
int n = 0;
if (Parameters.FixedParameters != null){
Parameters.FixedParameters.CopyTo (async_params, 0);
n = Parameters.FixedParameters.Length;
}
if (Parameters.ArrayParameter != null)
async_params [n] = Parameters.ArrayParameter;
async_params [params_num] = new Parameter (
TypeManager.system_asynccallback_expr, "callback",
Parameter.Modifier.NONE, null);
async_params [params_num + 1] = new Parameter (
TypeManager.system_object_expr, "object",
Parameter.Modifier.NONE, null);
Parameters async_parameters = new Parameters (async_params, null, Location);
async_parameters.ComputeAndDefineParameterTypes (this);
async_parameters.ComputeAndDefineParameterTypes (this);
TypeManager.RegisterMethod (BeginInvokeBuilder,
new InternalParameters (container, async_parameters),
async_param_types);
//
// EndInvoke is a bit more interesting, all the parameters labeled as
// out or ref have to be duplicated here.
//
Type [] end_param_types = new Type [out_params + 1];
Parameter [] end_params = new Parameter [out_params + 1];
int param = 0;
if (out_params > 0){
int top = Parameters.FixedParameters.Length;
for (i = 0; i < top; i++){
Parameter p = Parameters.FixedParameters [i];
if ((p.ModFlags & Parameter.Modifier.ISBYREF) == 0)
continue;
end_param_types [param] = param_types [i];
end_params [param] = p;
param++;
}
}
end_param_types [out_params] = TypeManager.iasyncresult_type;
end_params [out_params] = new Parameter (TypeManager.system_iasyncresult_expr, "result", Parameter.Modifier.NONE, null);
//
// Create method, define parameters, register parameters with type system
//
EndInvokeBuilder = TypeBuilder.DefineMethod ("EndInvoke", mattr, cc, ret_type, end_param_types);
EndInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
//
// EndInvoke: Label the parameters
//
EndInvokeBuilder.DefineParameter (out_params + 1, ParameterAttributes.None, "result");
for (i = 0; i < end_params.Length-1; i++){
EndInvokeBuilder.DefineParameter (i + 1, end_params [i].Attributes, end_params [i].Name);
}
Parameters end_parameters = new Parameters (end_params, null, Location);
end_parameters.ComputeAndDefineParameterTypes (this);
TypeManager.RegisterMethod (
EndInvokeBuilder,
new InternalParameters (container, end_parameters),
end_param_types);
return true;
}
public override void Emit (TypeContainer tc)
{
if (OptAttributes != null) {
EmitContext ec = new EmitContext (tc, this, Location, null, null, ModFlags, false);
Parameters.LabelParameters (ec, InvokeBuilder, Location);
OptAttributes.Emit (ec, this);
}
base.Emit (tc);
}
protected override string[] ValidAttributeTargets {
get {
return attribute_targets;
}
}
//TODO: duplicate
protected override bool VerifyClsCompliance (DeclSpace ds)
{
if (!base.VerifyClsCompliance (ds)) {
return false;
}
AttributeTester.AreParametersCompliant (Parameters.FixedParameters, Location);
if (!AttributeTester.IsClsCompliant (ReturnType.Type)) {
Report.Error_T (3002, Location, GetSignatureForError ());
}
return true;
}
/// <summary>
/// Verifies whether the method in question is compatible with the delegate
/// Returns the method itself if okay and null if not.
/// </summary>
public static MethodBase VerifyMethod (EmitContext ec, Type delegate_type, MethodBase mb,
Location loc)
{
ParameterData pd = Invocation.GetParameterData (mb);
int pd_count = pd.Count;
Expression ml = Expression.MemberLookup (
ec, delegate_type, "Invoke", loc);
if (!(ml is MethodGroupExpr)) {
Report.Error (-100, loc, "Internal error: could not find Invoke method!");
return null;
}
MethodBase invoke_mb = ((MethodGroupExpr) ml).Methods [0];
ParameterData invoke_pd = Invocation.GetParameterData (invoke_mb);
if (invoke_pd.Count != pd_count)
return null;
for (int i = pd_count; i > 0; ) {
i--;
if (invoke_pd.ParameterType (i) == pd.ParameterType (i) &&
invoke_pd.ParameterModifier (i) == pd.ParameterModifier (i))
continue;
else {
return null;
}
}
if (((MethodInfo) invoke_mb).ReturnType == ((MethodInfo) mb).ReturnType)
return mb;
else
return null;
}
// <summary>
// Verifies whether the invocation arguments are compatible with the
// delegate's target method
// </summary>
public static bool VerifyApplicability (EmitContext ec,
Type delegate_type,
ArrayList args,
Location loc)
{
int arg_count;
if (args == null)
arg_count = 0;
else
arg_count = args.Count;
Expression ml = Expression.MemberLookup (
ec, delegate_type, "Invoke", loc);
if (!(ml is MethodGroupExpr)) {
Report.Error (-100, loc, "Internal error: could not find Invoke method!" + delegate_type);
return false;
}
MethodBase mb = ((MethodGroupExpr) ml).Methods [0];
ParameterData pd = Invocation.GetParameterData (mb);
int pd_count = pd.Count;
bool params_method = (pd_count != 0) &&
(pd.ParameterModifier (pd_count - 1) == Parameter.Modifier.PARAMS);
if (!params_method && pd_count != arg_count) {
Report.Error (1593, loc,
"Delegate '" + delegate_type.ToString ()
+ "' does not take '" + arg_count + "' arguments");
return false;
}
//
// Consider the case:
// delegate void FOO(param object[] args);
// FOO f = new FOO(...);
// f(new object[] {1, 2, 3});
//
// This should be treated like f(1,2,3). This is done by ignoring the
// 'param' modifier for that invocation. If that fails, then the
// 'param' modifier is considered.
//
// One issue is that 'VerifyArgumentsCompat' modifies the elements of
// the 'args' array. However, the modifications appear idempotent.
// Normal 'Invocation's also have the same behaviour, implicitly.
//
bool ans = false;
if (arg_count == pd_count)
ans = Invocation.VerifyArgumentsCompat (ec, args, arg_count, mb, false, delegate_type, loc);
if (!ans && params_method)
ans = Invocation.VerifyArgumentsCompat (ec, args, arg_count, mb, true, delegate_type, loc);
return ans;
}
/// <summary>
/// Verifies whether the delegate in question is compatible with this one in
/// order to determine if instantiation from the same is possible.
/// </summary>
public static bool VerifyDelegate (EmitContext ec, Type delegate_type, Type probe_type, Location loc)
{
Expression ml = Expression.MemberLookup (
ec, delegate_type, "Invoke", loc);
if (!(ml is MethodGroupExpr)) {
Report.Error (-100, loc, "Internal error: could not find Invoke method!");
return false;
}
MethodBase mb = ((MethodGroupExpr) ml).Methods [0];
ParameterData pd = Invocation.GetParameterData (mb);
Expression probe_ml = Expression.MemberLookup (
ec, delegate_type, "Invoke", loc);
if (!(probe_ml is MethodGroupExpr)) {
Report.Error (-100, loc, "Internal error: could not find Invoke method!");
return false;
}
MethodBase probe_mb = ((MethodGroupExpr) probe_ml).Methods [0];
ParameterData probe_pd = Invocation.GetParameterData (probe_mb);
if (((MethodInfo) mb).ReturnType != ((MethodInfo) probe_mb).ReturnType)
return false;
if (pd.Count != probe_pd.Count)
return false;
for (int i = pd.Count; i > 0; ) {
i--;
if (pd.ParameterType (i) != probe_pd.ParameterType (i) ||
pd.ParameterModifier (i) != probe_pd.ParameterModifier (i))
return false;
}
return true;
}
public static string FullDelegateDesc (Type del_type, MethodBase mb, ParameterData pd)
{
StringBuilder sb = new StringBuilder (TypeManager.CSharpName (((MethodInfo) mb).ReturnType));
sb.Append (" " + del_type.ToString ());
sb.Append (" (");
int length = pd.Count;
for (int i = length; i > 0; ) {
i--;
sb.Append (pd.ParameterDesc (length - i - 1));
if (i != 0)
sb.Append (", ");
}
sb.Append (")");
return sb.ToString ();
}
// Hack around System.Reflection as found everywhere else
public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
MemberFilter filter, object criteria)
{
ArrayList members = new ArrayList ();
if ((mt & MemberTypes.Method) != 0) {
if (ConstructorBuilder != null)
if (filter (ConstructorBuilder, criteria))
members.Add (ConstructorBuilder);
if (InvokeBuilder != null)
if (filter (InvokeBuilder, criteria))
members.Add (InvokeBuilder);
if (BeginInvokeBuilder != null)
if (filter (BeginInvokeBuilder, criteria))
members.Add (BeginInvokeBuilder);
if (EndInvokeBuilder != null)
if (filter (EndInvokeBuilder, criteria))
members.Add (EndInvokeBuilder);
}
return new MemberList (members);
}
public override MemberCache MemberCache {
get {
return null;
}
}
public Expression InstanceExpression {
get {
return instance_expr;
}
set {
instance_expr = value;
}
}
public MethodBase TargetMethod {
get {
return delegate_method;
}
set {
delegate_method = value;
}
}
public Type TargetReturnType {
get {
return ret_type;
}
}
public Type [] ParameterTypes {
get {
return param_types;
}
}
public override AttributeTargets AttributeTargets {
get {
return AttributeTargets.Delegate | AttributeTargets.ReturnValue;
}
}
}
//
// Base class for `NewDelegate' and `ImplicitDelegateCreation'
//
public abstract class DelegateCreation : Expression {
protected MethodBase constructor_method;
protected MethodBase delegate_method;
protected Expression delegate_instance_expr;
public DelegateCreation () {}
public static void Error_NoMatchingMethodForDelegate (EmitContext ec, MethodGroupExpr mg, Type type, Location loc)
{
string method_desc;
if (mg.Methods.Length > 1)
method_desc = mg.Methods [0].Name;
else
method_desc = Invocation.FullMethodDesc (mg.Methods [0]);
Expression invoke_method = Expression.MemberLookup (
ec, type, "Invoke", MemberTypes.Method,
Expression.AllBindingFlags, loc);
MethodBase method = ((MethodGroupExpr) invoke_method).Methods [0];
ParameterData param = Invocation.GetParameterData (method);
string delegate_desc = Delegate.FullDelegateDesc (type, method, param);
Report.Error (123, loc, "Method '" + method_desc + "' does not " +
"match delegate '" + delegate_desc + "'");
}
public override void Emit (EmitContext ec)
{
if (delegate_instance_expr == null ||
delegate_method.IsStatic)
ec.ig.Emit (OpCodes.Ldnull);
else
delegate_instance_expr.Emit (ec);
if (delegate_method.IsVirtual) {
ec.ig.Emit (OpCodes.Dup);
ec.ig.Emit (OpCodes.Ldvirtftn, (MethodInfo) delegate_method);
} else
ec.ig.Emit (OpCodes.Ldftn, (MethodInfo) delegate_method);
ec.ig.Emit (OpCodes.Newobj, (ConstructorInfo) constructor_method);
}
protected bool ResolveConstructorMethod (EmitContext ec)
{
Expression ml = Expression.MemberLookup (
ec, type, ".ctor", loc);
if (!(ml is MethodGroupExpr)) {
Report.Error (-100, loc, "Internal error: Could not find delegate constructor!");
return false;
}
constructor_method = ((MethodGroupExpr) ml).Methods [0];
return true;
}
protected Expression ResolveMethodGroupExpr (EmitContext ec, MethodGroupExpr mg)
{
foreach (MethodInfo mi in mg.Methods){
delegate_method = Delegate.VerifyMethod (ec, type, mi, loc);
if (delegate_method != null)
break;
}
if (delegate_method == null) {
Error_NoMatchingMethodForDelegate (ec, mg, type, loc);
return null;
}
//
// Check safe/unsafe of the delegate
//
if (!ec.InUnsafe){
ParameterData param = Invocation.GetParameterData (delegate_method);
int count = param.Count;
for (int i = 0; i < count; i++){
if (param.ParameterType (i).IsPointer){
Expression.UnsafeError (loc);
return null;
}
}
}
if (mg.InstanceExpression != null)
delegate_instance_expr = mg.InstanceExpression.Resolve (ec);
else {
if (ec.IsStatic){
if (!delegate_method.IsStatic){
Report.Error (120, loc,
"An object reference is required for the non-static method " +
delegate_method.Name);
return null;
}
delegate_instance_expr = null;
} else
delegate_instance_expr = ec.GetThis (loc);
}
if (delegate_instance_expr != null)
if (delegate_instance_expr.Type.IsValueType)
delegate_instance_expr = new BoxedCast (delegate_instance_expr);
eclass = ExprClass.Value;
return this;
}
}
//
// Created from the conversion code
//
public class ImplicitDelegateCreation : DelegateCreation {
ImplicitDelegateCreation (Type t, Location l)
{
type = t;
loc = l;
}
public override Expression DoResolve (EmitContext ec)
{
return this;
}
static public Expression Create (EmitContext ec, MethodGroupExpr mge, Type target_type, Location loc)
{
ImplicitDelegateCreation d = new ImplicitDelegateCreation (target_type, loc);
if (d.ResolveConstructorMethod (ec))
return d.ResolveMethodGroupExpr (ec, mge);
else
return null;
}
}
//
// A delegate-creation-expression, invoked from the `New' class
//
public class NewDelegate : DelegateCreation {
public ArrayList Arguments;
//
// This constructor is invoked from the `New' expression
//
public NewDelegate (Type type, ArrayList Arguments, Location loc)
{
this.type = type;
this.Arguments = Arguments;
this.loc = loc;
}
public override Expression DoResolve (EmitContext ec)
{
if (Arguments == null || Arguments.Count != 1) {
Report.Error (149, loc,
"Method name expected");
return null;
}
if (!ResolveConstructorMethod (ec))
return null;
Argument a = (Argument) Arguments [0];
Expression invoke_method = Expression.MemberLookup (
ec, type, "Invoke", MemberTypes.Method,
Expression.AllBindingFlags, loc);
if (invoke_method == null) {
Report.Error (-200, loc, "Internal error ! Could not find Invoke method!");
return null;
}
if (!a.ResolveMethodGroup (ec, loc))
return null;
Expression e = a.Expr;
MethodGroupExpr mg = e as MethodGroupExpr;
if (mg != null)
return ResolveMethodGroupExpr (ec, mg);
Type e_type = e.Type;
if (!TypeManager.IsDelegateType (e_type)) {
e.Error_UnexpectedKind ("method");
return null;
}
// This is what MS' compiler reports. We could always choose
// to be more verbose and actually give delegate-level specifics
if (!Delegate.VerifyDelegate (ec, type, e_type, loc)) {
Report.Error (29, loc, "Cannot implicitly convert type '" + e_type + "' " +
"to type '" + type + "'");
return null;
}
delegate_instance_expr = e;
delegate_method = ((MethodGroupExpr) invoke_method).Methods [0];
eclass = ExprClass.Value;
return this;
}
public override void Emit (EmitContext ec)
{
if (delegate_instance_expr == null || delegate_method.IsStatic)
ec.ig.Emit (OpCodes.Ldnull);
else
delegate_instance_expr.Emit (ec);
if (delegate_method.IsVirtual) {
ec.ig.Emit (OpCodes.Dup);
ec.ig.Emit (OpCodes.Ldvirtftn, (MethodInfo) delegate_method);
} else
ec.ig.Emit (OpCodes.Ldftn, (MethodInfo) delegate_method);
ec.ig.Emit (OpCodes.Newobj, (ConstructorInfo) constructor_method);
}
}
public class DelegateInvocation : ExpressionStatement {
public Expression InstanceExpr;
public ArrayList Arguments;
MethodBase method;
public DelegateInvocation (Expression instance_expr, ArrayList args, Location loc)
{
this.InstanceExpr = instance_expr;
this.Arguments = args;
this.loc = loc;
}
public override Expression DoResolve (EmitContext ec)
{
if (InstanceExpr is EventExpr) {
EventInfo ei = ((EventExpr) InstanceExpr).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
// cannot be accessed directly
//
// 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.
//
Assign.error70 (ei, loc);
return null;
}
}
Type del_type = InstanceExpr.Type;
if (del_type == null)
return null;
if (Arguments != null){
foreach (Argument a in Arguments){
if (!a.Resolve (ec, loc))
return null;
}
}
if (!Delegate.VerifyApplicability (ec, del_type, Arguments, loc))
return null;
Expression lookup = Expression.MemberLookup (ec, del_type, "Invoke", loc);
if (!(lookup is MethodGroupExpr)) {
Report.Error (-100, loc, "Internal error: could not find Invoke method!");
return null;
}
method = ((MethodGroupExpr) lookup).Methods [0];
type = ((MethodInfo) method).ReturnType;
eclass = ExprClass.Value;
return this;
}
public override void Emit (EmitContext ec)
{
//
// Invocation on delegates call the virtual Invoke member
// so we are always `instance' calls
//
Invocation.EmitCall (ec, false, false, InstanceExpr, method, Arguments, loc);
}
public override void EmitStatement (EmitContext ec)
{
Emit (ec);
//
// Pop the return value if there is one
//
if (method is MethodInfo){
if (((MethodInfo) method).ReturnType != TypeManager.void_type)
ec.ig.Emit (OpCodes.Pop);
}
}
}
}
+1732
View File
File diff suppressed because it is too large. Load diff
+3365
View File
File diff suppressed because it is too large. Load diff
+779
View File
@@ -0,0 +1,779 @@
//
// 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: Attributable {
string name;
Enum parent;
Location loc;
static string[] attribute_targets = new string [] { "field" };
public FieldBuilder builder;
public EnumMember (string name, Enum parent, Location loc, Attributes attrs):
base (attrs)
{
this.name = name;
this.parent = parent;
this.loc = loc;
}
public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
{
if (a.Type == TypeManager.marshal_as_attr_type) {
UnmanagedMarshal marshal = a.GetMarshal ();
if (marshal != null) {
builder.SetMarshal (marshal);
return;
}
Report.Warning_T (-24, a.Location);
return;
}
builder.SetCustomAttribute (cb);
}
public override AttributeTargets AttributeTargets {
get {
return AttributeTargets.Field;
}
}
public override bool IsClsCompliaceRequired(DeclSpace ds)
{
return parent.IsClsCompliaceRequired (ds);
}
public void DefineMember (TypeBuilder tb)
{
FieldAttributes attr = FieldAttributes.Public | FieldAttributes.Static
| FieldAttributes.Literal;
builder = tb.DefineField (name, tb, attr);
}
public void Emit (EmitContext ec)
{
if (OptAttributes != null)
OptAttributes.Emit (ec, this);
}
protected override string[] ValidAttributeTargets {
get {
return attribute_targets;
}
}
}
/// <summary>
/// Enumeration container
/// </summary>
public class Enum : DeclSpace {
ArrayList ordered_enums;
public Expression BaseType;
public Type UnderlyingType;
Hashtable member_to_location;
Hashtable member_to_attributes;
//
// 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;
Hashtable name_to_member;
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,
string 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 ();
name_to_member = new Hashtable ();
}
/// <summary>
/// Adds @name to the enumeration space, with @expr
/// being its definition.
/// </summary>
public AdditionResult AddEnumMember (string name, Expression expr, Location loc,
Attributes opt_attrs)
{
if (defined_names.Contains (name))
return AdditionResult.NameExists;
if (name == "value__") {
Report.Error (76, loc, "An item in an enumeration can't have an identifier `value__'");
return AdditionResult.Error;
}
DefineName (name, expr);
ordered_enums.Add (name);
member_to_location.Add (name, loc);
if (member_to_attributes == null)
member_to_attributes = new Hashtable ();
member_to_attributes.Add (name, opt_attrs);
name_to_member.Add (name, new EnumMember (name, this, loc, opt_attrs));
return AdditionResult.Success;
}
//
// 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 = name_to_member [name] as EnumMember;
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 (TypeContainer parent)
{
//
// If there was an error during DefineEnum, return
//
if (TypeBuilder == null)
return false;
EmitContext 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 = name_to_member [name] as EnumMember;
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 (TypeContainer tc)
{
EmitContext ec = new EmitContext (tc, this, Location, null, null, ModFlags, false);
if (OptAttributes != null) {
OptAttributes.Emit (ec, this);
}
foreach (EnumMember em in name_to_member.Values) {
em.Emit (ec);
}
base.Emit (tc);
}
protected override bool IsIdentifierClsCompliant (DeclSpace ds)
{
if (!base.IsIdentifierClsCompliant (ds))
return false;
for (int i = 1; i < ordered_enums.Count; ++i) {
string checked_name = ordered_enums [i] as string;
for (int ii = 0; ii < ordered_enums.Count; ++ii) {
if (ii == i)
continue;
string enumerator_name = ordered_enums [ii] as string;
if (String.Compare (checked_name, enumerator_name, true, CultureInfo.InvariantCulture) == 0) {
Report.SymbolRelatedToPreviousError ((Location)member_to_location [enumerator_name], enumerator_name);
Report.Error_T (3005, (Location)member_to_location [checked_name], GetEnumeratorName (checked_name));
break;
}
}
}
return true;
}
protected override bool VerifyClsCompliance (DeclSpace ds)
{
if (!base.VerifyClsCompliance (ds))
return false;
if (!AttributeTester.IsClsCompliant (UnderlyingType)) {
Report.Error_T (3009, Location, 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 (Expression) defined_names [name];
}
}
public override AttributeTargets AttributeTargets {
get {
return AttributeTargets.Enum;
}
}
}
}
View File
Whitespace-only changes.
+8369
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+100
View File
@@ -0,0 +1,100 @@
// 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
@@ -0,0 +1,988 @@
// 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;
}
}
}
+56
View File
@@ -0,0 +1,56 @@
//
// generic.cs: Support classes for generics
//
// Author:
// Miguel de Icaza ([email protected])
//
// (C) 2003 Ximian, Inc.
//
using System;
using System.Collections;
namespace Mono.CSharp {
//
// Tracks the constraints for a type parameter
//
class Constraints {
string type_parameter;
ArrayList constraints;
//
// type_parameter is the identifier, constraints is an arraylist of
// Expressions (with types) or `true' for the constructor constraint.
//
public Constraints (string type_parameter, ArrayList constraints)
{
this.type_parameter = type_parameter;
this.constraints = constraints;
}
}
//
// This type represents a generic type parameter reference.
//
// These expressions are born in a fully resolved state.
//
public class TypeParameterExpr : TypeExpr {
string type_parameter;
public TypeParameterExpr (string type_parameter, Location l)
: base (typeof (object), l)
{
this.type_parameter = type_parameter;
}
public override string ToString ()
{
return "TypeParameter[" + type_parameter + "]";
}
public void Error_CannotUseAsUnmanagedType (Location loc)
{
Report.Error (-203, loc, "Can not use type parameter as unamanged type");
}
}
}
+61
View File
@@ -0,0 +1,61 @@
//
// GenericParser.cs: The Base Parser for the Mono compilers
//
// Author: A Rafael D Teixeira ([email protected])
//
// Licensed under the terms of the GNU GPL
//
// Copyright (C) 2001 Ximian, Inc.
//
using System;
using System.Text;
namespace Mono.Languages
{
using System.Collections;
/// <summary>
/// Base class to support multiple Jay generated parsers
/// </summary>
public abstract class GenericParser
{
// Name of the file we are parsing
public string name;
// Input stream to parse from.
public System.IO.Stream input;
public abstract void parse ();
public virtual string[] extensions()
{
string [] list = { ".cs" };
return list;
}
public GenericParser()
{
//
// DO NOTHING: Derived classes should do their iniatilization here duties
//
}
protected bool yacc_verbose_flag = false;
public bool yacc_verbose
{
set
{
yacc_verbose_flag = value;
}
get
{
return yacc_verbose_flag;
}
}
}
}
+694
View File
@@ -0,0 +1,694 @@
//
// 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;
bool in_exc;
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 (-208, loc, "yield statement can not appear in finally clause");
return false;
}
if (ec.CurrentBranching.InCatch ()){
Report.Error (-209, loc, "yield statement can not appear in the catch clause");
return false;
}
if (ec.InAnonymousMethod){
Report.Error (-209, 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;
in_exc = ec.CurrentBranching.InTryOrCatch (false);
Type iterator_type = IteratorHandler.Current.IteratorType;
if (expr.Type != iterator_type){
expr = Convert.ImplicitConversionRequired (ec, expr, iterator_type, loc);
if (expr == null)
return false;
}
return true;
}
protected override void DoEmit (EmitContext ec)
{
IteratorHandler.Current.MarkYield (ec, expr, in_exc);
}
}
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)
{
IteratorHandler.Current.EmitYieldBreak (ec.ig, true);
}
}
public class IteratorHandler {
//
// Points to the current iterator handler, will be probed by
// Yield and YieldBreak to get their context information
//
public static IteratorHandler Current;
//
// The typebuilder to the proxy class we create
//
TypeBuilder enumerator_proxy_class;
TypeBuilder enumerable_proxy_class;
//
// The type of this iterator, object by default.
//
public Type IteratorType;
//
// The members we create on the proxy class
//
MethodBuilder move_next_method;
MethodBuilder reset_method;
MethodBuilder get_current_method;
MethodBuilder dispose_method;
MethodBuilder getenumerator_method;
PropertyBuilder current_property;
ConstructorBuilder enumerator_proxy_constructor;
ConstructorBuilder enumerable_proxy_constructor;
//
// The PC for the state machine.
//
FieldBuilder pc_field;
//
// The value computed for Current
//
FieldBuilder current_field;
//
// Used to reference fields on the container class (instance methods)
//
public FieldBuilder this_field;
public FieldBuilder enumerable_this_field;
//
// References the parameters
//
public FieldBuilder [] parameter_fields;
FieldBuilder [] enumerable_parameter_fields;
//
// The state as we generate the iterator
//
ArrayList resume_labels = new ArrayList ();
int pc;
//
// Context from the original method
//
string name;
TypeContainer container;
Type return_type;
Type [] param_types;
InternalParameters parameters;
Block original_block;
Location loc;
int modifiers;
static int proxy_count;
public void EmitYieldBreak (ILGenerator ig, bool add_return)
{
ig.Emit (OpCodes.Ldarg_0);
IntConstant.EmitInt (ig, -1);
ig.Emit (OpCodes.Stfld, pc_field);
if (add_return){
ig.Emit (OpCodes.Ldc_I4_0);
ig.Emit (OpCodes.Ret);
}
}
void EmitThrowInvalidOp (ILGenerator ig)
{
ig.Emit (OpCodes.Newobj, TypeManager.invalid_operation_ctor);
ig.Emit (OpCodes.Throw);
}
void Create_MoveNext ()
{
move_next_method = enumerator_proxy_class.DefineMethod (
"System.IEnumerator.MoveNext",
MethodAttributes.HideBySig | MethodAttributes.NewSlot |
MethodAttributes.Virtual,
CallingConventions.HasThis, TypeManager.bool_type, TypeManager.NoTypes);
enumerator_proxy_class.DefineMethodOverride (move_next_method, TypeManager.bool_movenext_void);
ILGenerator ig = move_next_method.GetILGenerator ();
EmitContext ec = new EmitContext (
container, loc, ig,
TypeManager.void_type, modifiers);
Label dispatcher = ig.DefineLabel ();
ig.Emit (OpCodes.Br, dispatcher);
Label entry_point = ig.DefineLabel ();
ig.MarkLabel (entry_point);
resume_labels.Add (entry_point);
Current = this;
SymbolWriter sw = CodeGen.SymbolWriter;
if ((sw != null) && !Location.IsNull (loc) && !Location.IsNull (original_block.EndLocation)) {
sw.OpenMethod (container, move_next_method, loc, original_block.EndLocation);
ec.EmitTopBlock (original_block, parameters, loc);
sw.CloseMethod ();
} else {
ec.EmitTopBlock (original_block, parameters, loc);
}
Current = null;
EmitYieldBreak (ig, true);
//
// FIXME: Split the switch in blocks that can be consumed by switch.
//
ig.MarkLabel (dispatcher);
Label [] labels = new Label [resume_labels.Count];
resume_labels.CopyTo (labels);
ig.Emit (OpCodes.Ldarg_0);
ig.Emit (OpCodes.Ldfld, pc_field);
ig.Emit (OpCodes.Switch, labels);
ig.Emit (OpCodes.Ldc_I4_0);
ig.Emit (OpCodes.Ret);
}
//
// 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)
{
return enumerator_proxy_class.DefineField (pfx + name, t, FieldAttributes.Public);
}
void Create_Reset ()
{
reset_method = enumerator_proxy_class.DefineMethod (
"System.IEnumerator.Reset",
MethodAttributes.HideBySig | MethodAttributes.NewSlot |
MethodAttributes.Virtual,
CallingConventions.HasThis, TypeManager.void_type, TypeManager.NoTypes);
enumerator_proxy_class.DefineMethodOverride (reset_method, TypeManager.void_reset_void);
ILGenerator ig = reset_method.GetILGenerator ();
EmitThrowInvalidOp (ig);
}
void Create_Current ()
{
get_current_method = enumerator_proxy_class.DefineMethod (
"System.IEnumerator.get_Current",
MethodAttributes.HideBySig | MethodAttributes.SpecialName |
MethodAttributes.NewSlot | MethodAttributes.Virtual,
CallingConventions.HasThis, TypeManager.object_type, TypeManager.NoTypes);
enumerator_proxy_class.DefineMethodOverride (get_current_method, TypeManager.object_getcurrent_void);
current_property = enumerator_proxy_class.DefineProperty (
"Current",
PropertyAttributes.RTSpecialName | PropertyAttributes.SpecialName,
TypeManager.object_type, null);
current_property.SetGetMethod (get_current_method);
ILGenerator ig = get_current_method.GetILGenerator ();
ig.Emit (OpCodes.Ldarg_0);
ig.Emit (OpCodes.Ldfld, pc_field);
ig.Emit (OpCodes.Ldc_I4_0);
Label return_current = ig.DefineLabel ();
ig.Emit (OpCodes.Bgt, return_current);
EmitThrowInvalidOp (ig);
ig.MarkLabel (return_current);
ig.Emit (OpCodes.Ldarg_0);
ig.Emit (OpCodes.Ldfld, current_field);
ig.Emit (OpCodes.Ret);
}
void Create_Dispose ()
{
dispose_method = enumerator_proxy_class.DefineMethod (
"System.IDisposable.Dispose",
MethodAttributes.HideBySig | MethodAttributes.SpecialName |
MethodAttributes.NewSlot | MethodAttributes.Virtual,
CallingConventions.HasThis, TypeManager.void_type, TypeManager.NoTypes);
enumerator_proxy_class.DefineMethodOverride (dispose_method, TypeManager.void_dispose_void);
ILGenerator ig = dispose_method.GetILGenerator ();
EmitYieldBreak (ig, false);
ig.Emit (OpCodes.Ret);
}
void Create_GetEnumerator ()
{
getenumerator_method = enumerable_proxy_class.DefineMethod (
"IEnumerable.GetEnumerator",
MethodAttributes.HideBySig | MethodAttributes.SpecialName |
MethodAttributes.NewSlot | MethodAttributes.Virtual,
CallingConventions.HasThis, TypeManager.ienumerator_type, TypeManager.NoTypes);
enumerable_proxy_class.DefineMethodOverride (getenumerator_method, TypeManager.ienumerable_getenumerator_void);
ILGenerator ig = getenumerator_method.GetILGenerator ();
ig.Emit (OpCodes.Newobj, (ConstructorInfo) enumerator_proxy_constructor);
if (enumerable_this_field != null || parameters.Count > 0){
LocalBuilder obj = ig.DeclareLocal (enumerator_proxy_class);
ig.Emit (OpCodes.Stloc, obj);
if (enumerable_this_field != null){
ig.Emit (OpCodes.Ldloc, obj);
ig.Emit (OpCodes.Ldarg_0);
ig.Emit (OpCodes.Ldfld, enumerable_this_field);
ig.Emit (OpCodes.Stfld, this_field);
}
for (int i = 0; i < parameters.Count; i++){
ig.Emit (OpCodes.Ldloc, obj);
ig.Emit (OpCodes.Ldarg_0);
ig.Emit (OpCodes.Ldfld, enumerable_parameter_fields [i]);
ig.Emit (OpCodes.Stfld, parameter_fields [i]);
}
ig.Emit (OpCodes.Ldloc, obj);
}
ig.Emit (OpCodes.Ret);
}
//
// Called back from Yield
//
public void MarkYield (EmitContext ec, Expression expr, bool in_exc)
{
ILGenerator ig = ec.ig;
// Store the new current
ig.Emit (OpCodes.Ldarg_0);
expr.Emit (ec);
ig.Emit (OpCodes.Stfld, current_field);
// increment pc
pc++;
ig.Emit (OpCodes.Ldarg_0);
IntConstant.EmitInt (ig, pc);
ig.Emit (OpCodes.Stfld, pc_field);
// Return ok
ig.Emit (OpCodes.Ldc_I4_1);
// Find out how to "leave"
if (in_exc || !ec.IsLastStatement){
Type old = ec.ReturnType;
ec.ReturnType = TypeManager.int32_type;
ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
ec.ReturnType = old;
}
if (in_exc){
ec.NeedReturnLabel ();
ig.Emit (OpCodes.Leave, ec.ReturnLabel);
} else if (ec.IsLastStatement){
ig.Emit (OpCodes.Ret);
} else {
ec.NeedReturnLabel ();
ig.Emit (OpCodes.Br, ec.ReturnLabel);
}
Label resume_point = ig.DefineLabel ();
ig.MarkLabel (resume_point);
resume_labels.Add (resume_point);
}
//
// Creates the IEnumerator Proxy class
//
void MakeEnumeratorProxy ()
{
TypeExpr [] proxy_base_interfaces = new TypeExpr [2];
proxy_base_interfaces [0] = new TypeExpression (TypeManager.ienumerator_type, loc);
proxy_base_interfaces [1] = new TypeExpression (TypeManager.idisposable_type, loc);
Type [] proxy_base_itypes = new Type [2];
proxy_base_itypes [0] = TypeManager.ienumerator_type;
proxy_base_itypes [1] = TypeManager.idisposable_type;
TypeBuilder container_builder = container.TypeBuilder;
//
// Create the class
//
enumerator_proxy_class = container_builder.DefineNestedType (
"<Enumerator:" + name + ":" + (proxy_count++) + ">",
TypeAttributes.AutoLayout | TypeAttributes.Class |TypeAttributes.NestedPrivate,
TypeManager.object_type, proxy_base_itypes);
TypeManager.RegisterBuilder (enumerator_proxy_class, proxy_base_interfaces);
//
// Define our fields
//
pc_field = enumerator_proxy_class.DefineField ("PC", TypeManager.int32_type, FieldAttributes.Assembly);
current_field = enumerator_proxy_class.DefineField ("current", IteratorType, FieldAttributes.Assembly);
if ((modifiers & Modifiers.STATIC) == 0)
this_field = enumerator_proxy_class.DefineField ("THIS", container.TypeBuilder, FieldAttributes.Assembly);
parameter_fields = new FieldBuilder [parameters.Count];
for (int i = 0; i < parameters.Count; i++){
parameter_fields [i] = enumerator_proxy_class.DefineField (
String.Format ("tor{0}_{1}", i, parameters.ParameterName (i)),
parameters.ParameterType (i), FieldAttributes.Assembly);
}
//
// Define a constructor
//
enumerator_proxy_constructor = enumerator_proxy_class.DefineConstructor (
MethodAttributes.Public | MethodAttributes.HideBySig |
MethodAttributes.SpecialName | MethodAttributes.RTSpecialName,
CallingConventions.HasThis, TypeManager.NoTypes);
InternalParameters parameter_info = new InternalParameters (
TypeManager.NoTypes, Parameters.EmptyReadOnlyParameters);
TypeManager.RegisterMethod (enumerator_proxy_constructor, parameter_info, TypeManager.NoTypes);
//
// Our constructor
//
ILGenerator ig = enumerator_proxy_constructor.GetILGenerator ();
ig.Emit (OpCodes.Ldarg_0);
ig.Emit (OpCodes.Call, TypeManager.object_ctor);
ig.Emit (OpCodes.Ret);
}
//
// Creates the IEnumerable proxy class
//
void MakeEnumerableProxy ()
{
TypeBuilder container_builder = container.TypeBuilder;
Type [] proxy_base_interfaces = new Type [1];
proxy_base_interfaces [0] = TypeManager.ienumerable_type;
//
// Creates the Enumerable proxy class.
//
enumerable_proxy_class = container_builder.DefineNestedType (
"<Enumerable:" + name + ":" + (proxy_count++)+ ">",
TypeAttributes.AutoLayout | TypeAttributes.Class |TypeAttributes.NestedPublic,
TypeManager.object_type, proxy_base_interfaces);
//
// Constructor
//
if ((modifiers & Modifiers.STATIC) == 0){
enumerable_this_field = enumerable_proxy_class.DefineField (
"THIS", container.TypeBuilder, FieldAttributes.Assembly);
}
enumerable_parameter_fields = new FieldBuilder [parameters.Count];
for (int i = 0; i < parameters.Count; i++){
enumerable_parameter_fields [i] = enumerable_proxy_class.DefineField (
String.Format ("able{0}_{1}", i, parameters.ParameterName (i)),
parameters.ParameterType (i), FieldAttributes.Assembly);
}
enumerable_proxy_constructor = enumerable_proxy_class.DefineConstructor (
MethodAttributes.Public | MethodAttributes.HideBySig |
MethodAttributes.SpecialName | MethodAttributes.RTSpecialName,
CallingConventions.HasThis, TypeManager.NoTypes);
InternalParameters parameter_info = new InternalParameters (
TypeManager.NoTypes, Parameters.EmptyReadOnlyParameters);
TypeManager.RegisterMethod (enumerable_proxy_constructor, parameter_info, TypeManager.NoTypes);
ILGenerator ig = enumerable_proxy_constructor.GetILGenerator ();
ig.Emit (OpCodes.Ldarg_0);
ig.Emit (OpCodes.Call, TypeManager.object_ctor);
ig.Emit (OpCodes.Ret);
}
//
// Populates the Enumerator Proxy class
//
void PopulateProxy ()
{
RootContext.RegisterHelperClass (enumerator_proxy_class);
Create_MoveNext ();
Create_Reset ();
Create_Current ();
Create_Dispose ();
if (IsIEnumerable (return_type)){
Create_GetEnumerator ();
RootContext.RegisterHelperClass (enumerable_proxy_class);
}
}
//
// This is invoked by the EmitCode hook
//
void SetupIterator ()
{
PopulateProxy ();
}
//
// Our constructor
//
public IteratorHandler (string name, TypeContainer container, Type return_type, Type [] param_types,
InternalParameters parameters, int modifiers, Location loc)
{
this.name = name;
this.container = container;
this.return_type = return_type;
this.param_types = param_types;
this.parameters = parameters;
this.modifiers = modifiers;
this.loc = loc;
IteratorType = TypeManager.object_type;
RootContext.EmitCodeHook += new RootContext.Hook (SetupIterator);
}
//
// This class is just an expression that evaluates to a type, and the
// type is our internal proxy class. Used in the generated new body
// of the original method
//
class NewInnerType : Expression {
IteratorHandler handler;
public NewInnerType (IteratorHandler handler, Location l)
{
this.handler = handler;
eclass = ExprClass.Value;
loc = l;
}
public override Expression DoResolve (EmitContext ec)
{
// Create the proxy class type.
handler.MakeEnumeratorProxy ();
if (IsIEnumerable (handler.return_type))
handler.MakeEnumerableProxy ();
type = handler.return_type;
return this;
}
public override Expression ResolveAsTypeStep (EmitContext ec)
{
return DoResolve (ec);
}
public override void Emit (EmitContext ec)
{
ILGenerator ig = ec.ig;
FieldBuilder this_field = null;
bool is_ienumerable = IsIEnumerable (handler.return_type);
Type temp_type;
if (is_ienumerable){
temp_type = handler.enumerable_proxy_class;
ig.Emit (OpCodes.Newobj, (ConstructorInfo) handler.enumerable_proxy_constructor);
this_field = handler.enumerable_this_field;
} else {
temp_type = handler.enumerator_proxy_class;
ig.Emit (OpCodes.Newobj, (ConstructorInfo) handler.enumerator_proxy_constructor);
this_field = handler.this_field;
}
if (this_field == null && handler.parameters.Count == 0)
return;
LocalBuilder temp = ec.GetTemporaryLocal (temp_type);
ig.Emit (OpCodes.Stloc, temp);
//
// Initialize This
//
int first = 0;
if (this_field != null){
ig.Emit (OpCodes.Ldloc, temp);
ig.Emit (OpCodes.Ldarg_0);
if (handler.container is Struct)
ig.Emit (OpCodes.Ldobj, handler.container.TypeBuilder);
ig.Emit (OpCodes.Stfld, this_field);
first = 1;
}
for (int i = 0; i < handler.parameters.Count; i++){
ig.Emit (OpCodes.Ldloc, temp);
ParameterReference.EmitLdArg (ig, i + first);
if (is_ienumerable)
ig.Emit (OpCodes.Stfld, handler.enumerable_parameter_fields [i]);
else
ig.Emit (OpCodes.Stfld, handler.parameter_fields [i]);
}
//
// Initialize fields
//
ig.Emit (OpCodes.Ldloc, temp);
ec.FreeTemporaryLocal (temp, handler.container.TypeBuilder);
}
}
//
// 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;
}
}
static bool IsIEnumerable (Type t)
{
return t == TypeManager.ienumerable_type || TypeManager.ImplementsInterface (t, TypeManager.ienumerable_type);
}
static bool IsIEnumerator (Type t)
{
return t == TypeManager.ienumerator_type || TypeManager.ImplementsInterface (t, TypeManager.ienumerator_type);
}
//
// Returns the new block for the method, or null on failure
//
public Block Setup (Block block)
{
if (!(IsIEnumerator (return_type) || IsIEnumerable (return_type))){
Report.Error (
-205, loc, String.Format (
"The method `{0}' contains a yield statement, but has an invalid return type for an iterator `{1}'",
name, TypeManager.CSharpName (return_type)));
return null;
}
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 (-207, loc, String.Format (
"Parameter {0} of `{1}' is {2} and not allowed for an iterator method",
i+1, name, parameters.ParameterDesc (i)));
return null;
}
}
original_block = block;
Block b = new Block (null);
// return new InnerClass ()
b.AddStatement (new NoCheckReturn (new NewInnerType (this, loc), loc));
return b;
}
}
}
+222
View File
@@ -0,0 +1,222 @@
//
// 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;
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 = TypeManager.object_type;
return this;
}
public override void Emit (EmitContext ec)
{
ec.ig.Emit (OpCodes.Ldnull);
}
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;
}
}
}
+226
View File
@@ -0,0 +1,226 @@
//
// 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 System.Diagnostics.SymbolStore;
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 {
public readonly string Name;
public readonly string Path;
public readonly int Index;
public ISymbolDocumentWriter SymbolDocument;
public bool HasLineDirective;
public SourceFile (string name, string path, int index)
{
this.Index = index;
this.Name = name;
this.Path = path;
}
}
/// <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,
"Source file `" + name + "' 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) {
if (file.HasLineDirective)
continue;
file.SymbolDocument = 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 ISymbolDocumentWriter SymbolDocument {
get {
int index = token & source_mask;
if (index == 0)
return null;
SourceFile file = (SourceFile) source_list [index - 1];
return file.SymbolDocument;
}
}
}
}
+11
View File
@@ -0,0 +1,11 @@
<configuration>
<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>
+34
View File
@@ -0,0 +1,34 @@
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
genericparser.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
+247
View File
@@ -0,0 +1,247 @@
//
// 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 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 is 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");
}
}
}
+599
View File
@@ -0,0 +1,599 @@
//
// 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 {
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 object Lookup (DeclSpace ds, string name)
{
object o = Lookup (name);
Type t;
DeclSpace tdecl = o as DeclSpace;
if (tdecl != null) {
t = tdecl.DefineType ();
if ((ds == null) || ds.CheckAccessLevel (t))
return t;
}
Namespace ns = GetNamespace (name, false);
if (ns != null)
return ns;
//
// The type is not a nested type here
//
t = TypeManager.LookupTypeDirect (DeclSpace.MakeFQN (fullname, name));
if ((t == null) || ((ds != null) && !ds.CheckAccessLevel (t)))
return null;
return t;
}
public void AddNamespaceEntry (NamespaceEntry entry)
{
entries.Add (entry);
}
public void DefineName (string name, object o)
{
defined_names.Add (name, o);
}
public object Lookup (string name)
{
return 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);
}
}
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 Expression Alias;
public readonly NamespaceEntry NamespaceEntry;
public readonly Location Location;
public AliasEntry (NamespaceEntry entry, string name, Expression alias, Location loc)
{
Name = name;
Alias = alias;
NamespaceEntry = entry;
Location = loc;
}
object resolved;
public object Resolve ()
{
if (resolved != null)
return resolved;
NamespaceEntry curr_ns = NamespaceEntry;
string alias = Alias.ToString ();
while ((curr_ns != null) && (resolved == null)) {
resolved = curr_ns.Lookup (null, alias, false, Location);
if (resolved == null)
curr_ns = curr_ns.Parent;
}
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, object 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){
Report.Warning (105, loc, "The using directive for '" + ns +
"' appeared previously in this namespace");
return;
}
}
UsingEntry ue = new UsingEntry (this, ns, loc);
using_clauses.Add (ue);
}
public void UsingAlias (string alias, Expression namespace_or_type, Location loc)
{
if (aliases == null)
aliases = new Hashtable ();
if (aliases.Contains (alias)){
Report.Error (1537, loc, "The using alias `" + alias +
"' appeared previously in this namespace");
return;
}
aliases [alias] = new AliasEntry (this, alias, namespace_or_type, 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 string LookupAlias (string alias)
{
AliasEntry entry = GetAliasEntry (alias);
if (entry == null)
return null;
object resolved = entry.Resolve ();
if (resolved == null)
return null;
else if (resolved is Namespace)
return ((Namespace) resolved).Name;
else
return ((Type) resolved).FullName;
}
public object Lookup (DeclSpace ds, string name, bool silent, Location loc)
{
object 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, silent, loc);
if (o == null)
return null;
ns = o as Namespace;
if (ns != null)
return ns.Lookup (ds, last);
Type nested = TypeManager.LookupType ((((Type) o).Name + "." + last));
if ((nested == null) || ((ds != null) && !ds.CheckAccessLevel (nested)))
return null;
return nested;
}
//
// Check whether it's a namespace.
//
o = NS.Lookup (ds, name);
if (o != null)
return o;
//
// Check aliases.
//
AliasEntry entry = GetAliasEntry (name);
if (entry != null) {
o = entry.Resolve ();
if (o != null)
return o;
}
if (name.IndexOf ('.') > 0)
return null;
//
// Check using entries.
//
Type t = null, match = null;
foreach (Namespace using_ns in GetUsingTable ()) {
match = using_ns.Lookup (ds, name) as Type;
if (match != null){
if (t != null) {
if (!silent)
DeclSpace.Error_AmbiguousTypeReference (loc, name, t, match);
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;
symfile_id = symwriter.DefineNamespace (ns.Name, file, 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 ()
{
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 alias = (AliasEntry) de.Value;
if (alias.Resolve () != null)
continue;
error246 (alias.Location, alias.Alias.ToString ());
}
}
}
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
@@ -0,0 +1,217 @@
#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
+611
View File
@@ -0,0 +1,611 @@
//
// 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 ();
if (marshal != null) {
builder.SetMarshal (marshal);
return;
}
Report.Warning_T (-24, a.Location);
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_T (-28, location);
}
}
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>
protected 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>
protected 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
}
static string[] attribute_targets = new string [] { "param" };
public readonly Expression TypeName;
public readonly Modifier ModFlags;
public readonly string Name;
Type parameter_type;
public Parameter (Expression type, string name, Modifier mod, Attributes attrs)
: base (attrs)
{
Name = name;
ModFlags = mod;
TypeName = type;
}
// <summary>
// Resolve is used in method definitions
// </summary>
public bool Resolve (DeclSpace ds, Location l)
{
parameter_type = ds.ResolveType (TypeName, false, l);
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 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 (DeclSpace ds, Location loc)
{
if (parameter_type == null){
if (!Resolve (ds, loc))
return null;
}
return ExternalType ().FullName;
}
public string GetSignatureForError ()
{
string typeName = TypeManager.CSharpName (parameter_type);
switch (ModFlags & ~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");
}
}
}
protected override string[] ValidAttributeTargets {
get {
return attribute_targets;
}
}
}
/// <summary>
/// Represents the methods parameters
/// </summary>
public class Parameters {
public Parameter [] FixedParameters;
public readonly Parameter ArrayParameter;
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;
}
/// <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 (DeclSpace ds)
{
signature = "";
if (FixedParameters != null){
for (int i = 0; i < FixedParameters.Length; i++){
Parameter par = FixedParameters [i];
signature += par.GetSignature (ds, 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 @tc environment
/// </summary>
public string GetSignature (DeclSpace ds)
{
if (signature == null){
VerifyArgs ();
ComputeSignature (ds);
}
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;
}
bool ComputeParameterTypes (DeclSpace ds)
{
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 (ds, loc))
t = p.ExternalType ();
else
failed = true;
types [i] = t;
i++;
}
}
if (extra > 0){
if (ArrayParameter.Resolve (ds, 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 (DeclSpace ds)
{
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 ok_flag = true;
if (FixedParameters != null){
foreach (Parameter p in FixedParameters){
Type t = null;
if (p.Resolve (ds, loc))
t = p.ExternalType ();
else
ok_flag = false;
types [i] = t;
i++;
}
}
if (extra > 0){
if (ArrayParameter.Resolve (ds, loc))
types [i] = ArrayParameter.ExternalType ();
else
ok_flag = false;
}
//
// invalidate the cached types
//
if (!ok_flag){
types = null;
}
return ok_flag;
}
/// <summary>
/// Returns the argument types as an array
/// </summary>
static Type [] no_types = new Type [0];
public Type [] GetParameterInfo (DeclSpace ds)
{
if (types != null)
return types;
if (FixedParameters == null && ArrayParameter == null)
return no_types;
if (ComputeParameterTypes (ds) == 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 (DeclSpace ds, 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 (ds) == 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 ()
{
// For now this is the only correc thing to do
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);
}
}
}
}
Loaded 100 of 430 files, more files were not shown because too many files have changed in this diff. Show more