From: Adam Chlipala Date: Sat, 2 Aug 2003 15:02:38 +0000 (+0000) Subject: Initial revision X-Git-Tag: start~1 X-Git-Url: https://git.hcoop.net/bpt/mlt.git/commitdiff_plain/c0a3b4882df1afe4a0155654c1102bd0f9729993 Initial revision --- c0a3b4882df1afe4a0155654c1102bd0f9729993 diff --git a/BUILDING b/BUILDING new file mode 100644 index 0000000..919e906 --- /dev/null +++ b/BUILDING @@ -0,0 +1,98 @@ +=================== +System requirements +=================== + +Compiling the mlt tool requires a "working version" of SML/NJ. I've +tested it with 110.42. You'll need to get the SML/NJ source code +package and modify some of the included .cm files to make a few +additional internal structures visible. The necessary changes to make +are described below, with paths given relative to your base SML/NJ +directory. The lines listed for each file should be added right before +the "is" keyword at the end of the exports list for a library. The +"is" is on the first non-indented line after the initial "Library" +line in each of these files. + +The following lines to src/compiler/core.cm: + structure Types + structure EntityEnv + structure Modules + structure Stamps + structure Bindings + structure TypesUtil + structure VarCon + structure ModuleUtil + structure II + structure BasicTypes + structure PPType + structure Access + +The following lines to both src/system/smlnj/compiler/current.cm +and src/system/smlnj/compiler/x86.cm: + structure Types + structure EntityEnv + structure Modules + structure Stamps + structure Bindings + structure TypesUtil + structure VarCon + structure ModuleUtil + structure II + structure BasicTypes + structure PPType + structure Access + structure Unify + +The following line to src/compiler/Elaborator/elaborate.cm: + structure Unify + +Finally, add the following line somewhere _below_ the "is" in +src/system/smlnj/compiler/x86.cm: + $smlnj/viscomp/elaborate.cm + +After making these changes, you can rebuild and install the compiler +with the following sequence of commands: + +cd $smlnjdir/src/system +sml +CM.autoload "$smlnj/cmb.cm"; +CMB.make (); + +./makeml +./installml + + +============= +Configuration +============= + +If it is possible for you to modify a file /etc/mlt.conf, then you +can edit this file to set various options related to locations of +important files on your file system. In particular, you may want to +set the 'compiler', 'lib', and 'sml' options (documented in the +manual) if you have SML/NJ installed somewhere besides /usr/local/sml +or the mlt src directory somewhere besides /usr/local/share/mlt/src. +If you can't modify /etc/mlt.conf, then you can change the first +variable definition in src/config.sml to a different path, or you can +leave it as is and provide all configuration in the local mlt.conf +file for each project. + +You should also edit the paths in the simple install script in this +directory if you want to install system-wide binaries and scripts to +somewhere besides /usr/local/bin. + +These changes may be made for you by a fancy configuration program in +a future release. + + +======== +Building +======== + +All sources may be built by running the build script in this +directory. It does a clean re-build of all source files and stabilizes +all libraries produced. The build script is not appropriate for use +during development. Use the standard SML/NJ CM mechanisms if you are +changing the code and don't want to recompile everything each time. + +[There is probably a better way to do this, but I haven't figured one +out yet.] diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..b1e3f5a --- /dev/null +++ b/LICENSE @@ -0,0 +1,504 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! + + diff --git a/build b/build new file mode 100755 index 0000000..9d48509 --- /dev/null +++ b/build @@ -0,0 +1,29 @@ +#!/bin/sh + +SMLBIN=/usr/local/sml/bin + +cd src + +if [ -f mlt.x86-linux ] ; then + rm mlt.x86-linux +fi +if [ -d CM ] ; then + rm -rf CM +fi +if [ -d lib/CM ] ; then + rm -rf lib/CM +fi + +if ! cat build.sml | $SMLBIN/sml ; then + exit 1 +fi + +if ! $SMLBIN/ml-build sources.cm Main.main mlt ; then + exit 1 +fi + +cd lib + +if ! cat build.sml | $SMLBIN/sml ; then + exit 1 +fi \ No newline at end of file diff --git a/doc/.cvsignore b/doc/.cvsignore new file mode 100644 index 0000000..8e7d85c --- /dev/null +++ b/doc/.cvsignore @@ -0,0 +1,4 @@ +*.aux +*.log +*.dvi +*.ps diff --git a/doc/Makefile b/doc/Makefile new file mode 100644 index 0000000..77428b8 --- /dev/null +++ b/doc/Makefile @@ -0,0 +1,10 @@ +all: manual.ps + +clean: + rm *.aux *.dvi *.ps *.log + +manual.ps: manual.dvi + dvips -o manual.ps manual.dvi + +manual.dvi: manual.tex + latex manual.tex \ No newline at end of file diff --git a/doc/manual.tex b/doc/manual.tex new file mode 100644 index 0000000..b86c295 --- /dev/null +++ b/doc/manual.tex @@ -0,0 +1,197 @@ +\documentclass{article} +\usepackage{fullpage} + +\title{mlt manual} +\author{Adam Chlipala} + +\begin{document} + +\maketitle + +\section{Introduction} + +This system is currently in need of a good name. I will use either ``mlt'' or generic terms to refer to it for now. + +mlt is a system for the creation of dynamic web sites based around Standard ML. The meat of the system deals with compiling a template language. This language is purposely simplistic. It's not possible to create a non-terminating template without the complicity of SML code that it calls. Templates look like HTML source files with SML-like code inserted in strategic places. They are capable of full interaction with all types and values in any SML structures. The current implementation interfaces with web servers via the standard CGI protocol. + +\section{Tool usage} + +\begin{enumerate} + \item Choose a directory to hold the sources for the dynamic web site project. + \item Edit a {\tt mlt.conf} file in that directory to set project options, including which SML/NJ CM libraries to use, where to put some generated SML sources and binary files, and where to publish the actual CGI scripts. + \item Create a set of Standard ML support files. + \item Create a set of templates with {\tt .mlt} filename extensions. Each {\tt {\it page}.mlt} will become a CGI script named {\tt {\it page}}, and they may interact with libraries and project SML sources. + \item Run the {\tt mlt} command-line program with no arguments. + \item If it reports any errors, correct them and repeat the last step. + \item Access your site from the base URL corresponding to the directory you chose for script output. (Probably a ``cgi-bin'' directory of some sort) +\end{enumerate} + +\section{{\tt mlt.conf} files} + +Settings concerning compilation and publishing of projects are controlled by {\tt mlt.conf} files. There will generally be two files that influence a particular project: a system-wide file (probably in {\tt /etc/mlt.conf}) and the {\tt mlt.conf} file in the project directory. Single-value option settings from the project configuration override the system-wide configuration when there is a conflict. + +Files consist of a sequence of the following kinds of lines in any order: + +\begin{itemize} + \item {\tt in {\it directory}}: Treat {\it directory} as the project directory. This defaults to the current working directory. + + \item {\tt out {\it directory}}: Use {\it directory} as the working directory. Among other things, a {\tt heap.x86-linux} file will be placed here that must be readable by the web server that you intend to use. (If the server runs your CGI scripts as your user, like Apache does with suexec, then you probably don't need to worry about this.) This defaults to the current working directory. + + \item {\tt pub {\it directory}}: Publish CGI scripts to {\it directory}. Each will be a {\tt sh} shell script that runs SML/NJ with the generated {\tt heap.x86-linux} and appropriate arguments. This defaults to the current working directory. + + \item {\tt lib {\it file}}: {\it file} is the path to the {\tt .cm} file for the mlt template library. This is the library built from the {\tt src/lib/} tree. It defaults to {\tt /usr/local/share/mlt/src/lib/sources.cm}. + + \item {\tt compiler {\it file}}: {\it file} is the path to the {\tt .cm} file for the mlt compiler library. This is the library built from the {\tt src/} tree. It defaults to {\tt /usr/local/share/mlt/src/sources.cm}. + + \item {\tt sml {\it directory}}: {\it directory} is the path to the SML/NJ {\tt bin} directory. It defaults to {\tt /usr/local/sml/bin}. + + \item {\tt cm {\it file}}: {\it file} is the path to a file that the SML/NJ Compilation Manager understands (i.e., {\tt .cm}, {\tt .sml}, {\tt .sig}, {\tt .grm}, {\tt .lex}). This file is to be made available to templates in the project. + + \item {\tt print {\it type} = {\it code}}: This declares that the given {\it code} is an SML expression that evaluates to an appropriate function for printing values of the SML {\it type}. The {\it code} should usually be the name of a function defined in a library or project SML source file. +\end{itemize} + +\section{The template language} + +The template language at the moment is a somewhat ad-hoc mixture of SML-style and Java-style syntax. The exact typing rules for the constructs described below should be clear to anyone with a good knowledge of SML. + +\subsection{Grammar} + +Template files (denoted by the filename extension {\tt .mlt}) are HTML source files with embedded declarations and statements in an SML-like language. Statements and declarations are separated by semicolons where necessary to disambiguate. The exact grammar can be found in ml-yacc form in {\tt src/mlt.grm}. + +\subsection{Expressions} + +\subsubsection{Constants} + +Base type constants such as 1, $\sim 2$, and {\tt "some string"} are available, with identical types and meanings as in Standard ML. Character constants are denoted like 'x'. + +\subsubsection{Variables} + +User-defined variables are denoted the same way as in SML, except that the apostrophe character is disallowed in their identifiers. + +\subsubsection{Paths} + +While templates cannot define their own structures, they may access structures from imported libraries and project SML sources. The syntax for this is identical to the SML syntax, i.e., {\tt Posix.FileSys.opendir} or {\tt valOf}. The second example is treated as a path projecting the {\tt valOf} function from the top-level environment. + +\subsubsection{Binary operators} + +There is no mechanism for user definition of infix operators, but the following binary operators are supported: $+$, $-$, $*$, $/$, $\%$, $=$, $<>$, $<$, $<=$, $>$, $>=$, $::$, \^{}, {\tt and}, and {\tt or}. They are identical to SML operators, save that SML {\tt div} becomes $/$, {\tt mod} becomes $\%$, {\tt andalso} becomes {\tt and}, and {\tt orelse} becomes {\tt or}. + +\subsubsection{Unary operators} + +In addition to SML's $\sim$ prefix negation operator, there is a \$ operator for CGI parameter extraction. \$ has type {\tt string -> string}, so you can use it like {\tt \$"name"} to retrieve the value of the form field {\tt name}. \$ returns {\tt ""} for unset parameters. + +\subsubsection{Applications} + +Function application is like SML application. + +\subsection{Tuples} + +Tuple and {\tt ()} expressions are handled identically to how they are in SML. + +\subsubsection{Records} + +The syntax for creating records and extracting their fields is identical to SML's, with a few added conveniences. Record fields given in a record constructor without values are assigned the values of variables of the same names. For example, if there is a variable {\tt x} in scope, then the expressions {\tt \{x = x\}} and {\tt \{x\}} are equivalent. There are also O'Caml style functional record update expressions, such as {\tt \{myRecord with a = 1, b = 2\}} to construct a record identical to {\tt myRecord} except for the given field replacements. + +\subsubsection{Template calls} + +Where {\tt temp} is the name of a template in the current project, {\tt @temp} evaluates to a function {\tt (string * string) list -> unit} that takes in a list of name-value pairs for CGI parameters to modify and runs {\tt temp} with those changes. The Compilation Manager will prevent template calls from being used to implement any sort of recursion. + +\subsection{Patterns} + +Patterns are identical to SML patterns without support for user-defined infix constructors, though {\tt ::} is supported. Record patterns can include field names with no assigned patterns (the pattern for such a field is taken to be the field name) and "flex record" {\tt ...}'s to stand for unused fields. + +\subsection{Statements and declarations} + +\subsubsection{\tt Expressions} + +An expression appearing in a statement position is evaluated and printed into the web page output. The function used to print it is found among the {\tt print} directives in {\tt mlt.conf} files. + +\subsubsection{\tt open} + +This construct is identical to SML's and is used as a convenience to import all bindings from a list of structures into the environment for the enclosing block. + +\subsubsection{\tt val} + +{\tt val} bindings are identical to those in SML. + +\subsubsection{References} + +Variables with reference type are introduced with {\tt ref} declarations, which give lists of identifiers and their initial values. An example is {\tt ref x = 1, y = 2}. Where such a definition is in scope, the defined reference variables are used like normal variables with no need to explicitly dereference them. The value of a reference variable is updated with the usual {\tt :=} operator, with the difference that such update assignments are separate kinds of statements, not expressions with {\tt unit} type. + +\subsubsection{{\tt if}..{\tt then}..{\tt else}} + +If statements are in the usual imperative style, meaning that else clauses are optional. They are of the form: + +\begin{verbatim} +if (condition1) +{ + block1 +} +else if (condition 2) +{ + block 2 +} +else +{ + block 3 +} +\end{verbatim} + +The {\tt block}s are sequences of statements and declarations. Every {\tt if} statement is followed by zero or more {\tt else if}'s and one or zero {\tt else}'s. Conditions must be enclosed in parentheses. + +\subsubsection{\tt foreach} + +All looping is done via {\tt foreach} statements, which have two forms. One is: + +\begin{verbatim} +foreach (var in exp) +{ + block +} +\end{verbatim} + +Where {\tt exp} has type {\tt t list}, {\tt block} is executed for each of {\tt exp}'s elements, binding {\tt var} to each of them in order from first to last. + +There is also a shortcut integer iteration form: + +\begin{verbatim} +foreach (var in fromExp .. toExp) +{ + block +} +\end{verbatim} + +{\tt fromExp} and {\tt toExp} must have type {\tt int}. {\tt block} is evaluated with {\tt var} bound in sequence to each integer in the range defined by {\tt fromExp} and {\tt toExp}. + +\subsubsection{\tt case} + +{\tt case} statements are straightforward imperative modifications of SML {\tt case} expressions, such as: + +\begin{verbatim} +case (exp) +(pat1) { block1 } +(pat2) { block2 } +\end{verbatim} + +The case object and patterns must be enclosed in parentheses. + +\subsubsection{{\tt try}..{\tt catch}} + +This construction is to SML's {\tt handle} what template {\tt case} is to SML {\tt case}. For example: + +\begin{verbatim} +try +{ + block1 +} +catch (pat1) +{ + block2 +} +catch (pat2) +{ + block3 +} +\end{verbatim} + +\end{document} \ No newline at end of file diff --git a/install b/install new file mode 100755 index 0000000..853a70d --- /dev/null +++ b/install @@ -0,0 +1,2 @@ +cp src/mlt /usr/local/bin/ +cp src/mlt.x86-linux /usr/local/bin/ \ No newline at end of file diff --git a/src/.cvsignore b/src/.cvsignore new file mode 100644 index 0000000..30087d6 --- /dev/null +++ b/src/.cvsignore @@ -0,0 +1,4 @@ +CM +*.x86-linux +*.grm.* +*.lex.* diff --git a/src/build.sml b/src/build.sml new file mode 100644 index 0000000..10e2f3c --- /dev/null +++ b/src/build.sml @@ -0,0 +1,4 @@ +(if CM.recomp "sources.cm" andalso CM.stabilize true "sources.cm" then + OS.Process.exit OS.Process.success + else + OS.Process.exit OS.Process.failure) : unit; diff --git a/src/build2.sml b/src/build2.sml new file mode 100644 index 0000000..4689d2e --- /dev/null +++ b/src/build2.sml @@ -0,0 +1,2 @@ +SMLofNJ.exportFn ("mlt", Main.main); +OS.Process.exit OS.Process.failure; \ No newline at end of file diff --git a/src/common.sml b/src/common.sml new file mode 100644 index 0000000..b9e8920 --- /dev/null +++ b/src/common.sml @@ -0,0 +1,228 @@ +(* + * Dynamic web page generation with Standard ML + * Copyright (C) 2003 Adam Chlipala + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + *) + +(* Common convenience stuff to open in several places *) + +structure Common = +struct + exception Skip + exception Format of string + + fun error (pos, msg) = (ErrorMsg.error pos msg; + raise Skip) + + fun error' (pos, msg) = ErrorMsg.error pos msg + + type 'a map = 'a StringMap.map + + val insert = StringMap.insert + fun contains x = isSome (StringMap.find x) + + fun lookup (D, v, pos) = + (case StringMap.find (D, v) of + NONE => error (pos, "Unbound tycon " ^ v) + | SOME r => r) + + type 'a nmap = 'a IntBinaryMap.map + + val ninsert = IntBinaryMap.insert + fun ncontains x = isSome (IntBinaryMap.find x) + + fun nlookup (D, v, pos) = + (case IntBinaryMap.find (D, v) of + NONE => error (pos, "BAD: Unbound tyname or tvname " ^ Int.toString v) + | SOME r => r) + + type ident = string + + fun indexAfter (str, i, ch) = + let + val sz = size str + fun search i = + if i >= sz then + NONE + else if String.sub(str, i) = ch then + SOME i + else + search (i+1) + in + search i + end + + fun indexDoubleAfter (str, i, ch) = + let + val sz = size str-1 + fun search i = + if i >= sz then + NONE + else if String.sub(str, i) = ch andalso String.sub(str, i+1) = ch then + SOME i + else + search (i+1) + in + search i + end + + fun index (str, ch) = indexAfter (str, 0, ch) + + fun strLower str = String.implode (map Char.toLower (String.explode str)) + + fun trim str = + let + fun killFront L = + (case L of + ch::rest => + if Char.isSpace ch then + killFront rest + else + L + | [] => []) + in + String.implode (rev (killFront (rev (killFront (String.explode str))))) + end + + fun copyFile (src, dst) = + if src = dst then + () + else + let + val inf = TextIO.openIn src + val outf = TextIO.openOut dst + + fun copy () = + (case TextIO.inputLine inf of + "" => () + | line => (TextIO.output (outf, line); + copy ())) + in + copy (); + TextIO.closeIn inf; + TextIO.closeOut outf + end + + fun writeToFile (fname, txt) = + let + val outf = TextIO.openOut fname + in + TextIO.output (outf, txt); + TextIO.closeOut outf + end + + fun readFromFile fname = + let + val inf = TextIO.openIn fname + fun read acc = + (case TextIO.inputLine inf of + "" => String.concat (rev acc) + | line => read (line::acc)) + in + read [] + before TextIO.closeIn inf + end + + + fun listToString (f, F, L) [] = "" + | listToString (f, F, L) [id] = F ^ f id ^ L + | listToString (f, F, L) (h::t) = foldl (fn (id, s) => s ^ ", " ^ f id) (F ^ f h) t ^ L + + fun idListToString (F, L) list = listToString (fn x => x, F, L) list + + val stringListToString = idListToString ("[", "]") + + fun urlDecode s = + let + fun decode (L, acc) = + (case L of + [] => String.implode (rev acc) + | #"+"::L => decode (L, #" "::acc) + | #"%"::MS::LS::L => + (case StringCvt.scanString (Int.scan StringCvt.HEX) (str MS ^ str LS) of + NONE => decode (L, LS::MS:: #"%"::acc) + | SOME n => decode (L, chr n :: acc)) + | ch::L => decode (L, ch::acc)) + in + decode (String.explode s, []) + end + + fun pad (s, n) = + if size s < n then + pad ("0" ^ s, n) + else + s + + fun urlEncode s = + let + fun xch ch = + if Char.isAlphaNum ch orelse ch = #"_" orelse ch = #"." orelse ch = #"-" then + str ch + else if ch = #" " then + "+" + else + "%" ^ pad (Int.fmt StringCvt.HEX (ord ch), 2) + in + String.concat (map xch (String.explode s)) + end + + fun stoiOpt s = Int.fromString s + fun stoi s = + (case Int.fromString s of + NONE => raise Format s + | SOME i => i) + fun itos n = + if n < 0 then + "-" ^ Int.toString (~n) + else + Int.toString n + + fun storOpt s = Real.fromString s + fun stor s = + (case Real.fromString s of + NONE => raise Format s + | SOME r => r) + fun rtos r = + if r < 0.0 then + "-" ^ Real.toString (~r) + else + Real.toString r + + fun html s = + let + fun xch #"<" = "<" + | xch #">" = ">" + | xch #"&" = "&" + | xch #"\"" = """ + | xch ch = str ch + in + foldr op^ "" (map xch (String.explode s)) + end + + fun htmlNl s = + let + fun xch #"<" = "<" + | xch #">" = ">" + | xch #"&" = "&" + | xch #"\"" = """ + | xch #"\n" = "
" + | xch ch = str ch + in + foldr op^ "" (map xch (String.explode s)) + end + + fun killLf s = String.implode (List.filter (fn ch => ch <> #"\r") (String.explode s)) +end \ No newline at end of file diff --git a/src/compiler.sig b/src/compiler.sig new file mode 100644 index 0000000..441daaa --- /dev/null +++ b/src/compiler.sig @@ -0,0 +1,35 @@ +(* + * Dynamic web page generation with Standard ML + * Copyright (C) 2003 Adam Chlipala + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + *) + +(* Template compiler interface *) + +signature COMPILER = +sig + exception Error + + val compileTemplate : Config.config * StaticEnv.staticEnv * StringSet.set -> string -> string * string + (* [compileTemplate (env, fname, templates)] compiles the template stored in file fname in the environment env. + * templates lists the templates that may be called. This returns the structure name used and the actual code. *) + + val compileDirectory : Config.config -> OS.Process.status + (* [compileDirectory path] compiles all templates in directory path *) + + val compileTemplates : Config.config -> string list * string list -> OS.Process.status + (* Compile a list of template files and SML files using the given config *) +end diff --git a/src/compiler.sml b/src/compiler.sml new file mode 100644 index 0000000..6ef2807 --- /dev/null +++ b/src/compiler.sml @@ -0,0 +1,240 @@ +(* + * Dynamic web page generation with Standard ML + * Copyright (C) 2003 Adam Chlipala + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + *) + +(* Template compiler interface *) + +structure Compiler :> COMPILER = +struct + exception Error + + val cgiMode = Posix.FileSys.S.flags [Posix.FileSys.S.irwxu, + Posix.FileSys.S.iroth, + Posix.FileSys.S.ixoth] + + val consumer = {consumer = TextIO.print, + flush = fn () => TextIO.flushOut TextIO.stdOut, + linewidth = 80} + + fun getFname path = + let + fun look i = + if i < 0 then + path + else if String.sub (path, i) = #"/" then + String.extract (path, i+1, NONE) + else + look (i-1) + in + look (size path - 1) + end + + fun removeExt path = + let + val len = size path + + fun look i = + if i >= len then + path + else if String.sub (path, i) = #"." then + String.substring (path, 0, i) + else + look (i+1) + in + look 0 + end + + fun getExt path = + let + val len = size path + + fun look i = + if i >= len then + path + else if String.sub (path, i) = #"." then + String.extract (path, i+1, NONE) + else + look (i+1) + in + look 0 + end + + val upperOffset = ord #"A" - ord #"a" + fun toUpper ch = + if Char.isLower ch then + chr (ord ch + upperOffset) + else + ch + + fun compileTemplate (config, env, templates) path = + let + val fname = getFname path + val name = removeExt fname + val name = + if size name >= 1 then + str (toUpper (String.sub (name, 0))) ^ String.extract (name, 1, NONE) + else + raise Error + in + (name, Mlt.trans (config, env, templates, name, Parse.parse path)) + end + + fun compileDirectory config = + let + val path = Config.inPath config + val outPath = Config.outPath config + val sml = Config.sml config + + val dir = Posix.FileSys.opendir path + + fun loop (smls, mlts) = + (case Posix.FileSys.readdir dir of + "" => (smls, mlts) + | fname => + (case getExt fname of + "mlt" => loop (smls, (path ^ "/" ^ fname) :: mlts) + | ("sml"|"sig") => + let + val mltName = removeExt fname ^ ".mlt" + in + if getFname fname = "_main.sml" orelse Posix.FileSys.access (mltName, []) then + loop (smls, mlts) + else + loop ((path ^ "/" ^ fname) :: smls, mlts) + end + | _ => loop (smls, mlts))) + + val (smls, mlts) = loop ([], []) + + val outf = TextIO.openOut (outPath ^ "/libs.cm") + val printNames = app (fn name => TextIO.output (outf, "\t" ^ name ^ "\n")) + val _ = TextIO.output (outf, "Group is\n\t"); + val _ = TextIO.output (outf, Config.lib config) + val _ = TextIO.output (outf, "\n") + val _ = TextIO.output (outf, "\n\t(* Extra libraries and such *)\n\n") + val _ = printNames (Config.cm config) + val _ = TextIO.output (outf, "\n\t(* Project SML sources *)\n\n") + val _ = printNames smls + val _ = TextIO.closeOut outf + + val outf = TextIO.openOut (outPath ^ "/.build.sml") + fun printMlts [] = () + | printMlts (h::t) = + (TextIO.output (outf, "\"" ^ h ^ "\""); + List.app (fn n => TextIO.output (outf, ", \"" ^ n ^ "\"")) t) + + val libList = foldl (fn (l, s) => s ^ "if CM.make \"" ^ l ^ "\" then () else OS.Process.exit OS.Process.failure;\n") "" (Config.cm config) + in + TextIO.output (outf, "if CM.make \"" ^ outPath ^ "/libs.cm\" then () else OS.Process.exit OS.Process.failure;\nif CM.make \"" ^ Config.compiler config ^ "\" then () else OS.Process.exit OS.Process.failure;\n"); + TextIO.output (outf, libList); + TextIO.output (outf, "Compiler.compileTemplates (Config.read \"mlt.conf\" (Config.default ())) (["); + printMlts mlts; + TextIO.output (outf, "], ["); + printMlts smls; + TextIO.output (outf, "]);\n"); + TextIO.closeOut outf; + OS.Process.system ("cat " ^ outPath ^ "/.build.sml | " ^ sml ^ "/sml") + end + + fun compileTemplates config (mlts, smls) = + let + val _ = ErrorMsg.reset () + + val path = Config.inPath config + val outPath = Config.outPath config + val pubPath = Config.pubPath config + val sml = Config.sml config + val arch = "x86-linux" + + val loc = Environment.staticPart (#get (EnvRef.loc ()) ()) + val base = Environment.staticPart (#get (EnvRef.base ()) ()) + val env = StaticEnv.atop (base, loc) + + (*fun penv env = (print "I know about these symbols:\n"; + StaticEnv.app (fn (sym, _) => print (Symbol.describe sym ^ "\n")) env) + + val _ = penv base + val _ = penv loc*) + + val templates = StringSet.addList (StringSet.empty, map (getFname o removeExt) mlts) + val _ = print "Templates: " + val _ = StringSet.app (fn s => print (s ^ "; ")) templates + val _ = print "\n" + + fun ct (fname, (exports, outputs, scripts)) = + let + val _ = print ("Compiling " ^ fname ^ "....\n") + val (name, output) = compileTemplate (config, env, templates) fname + val scriptName = removeExt (getFname fname) + val outName = scriptName ^ ".sml" + val outf = TextIO.openOut (outPath ^ "/" ^ outName) + in + TextIO.output (outf, output); + TextIO.closeOut outf; + (name :: exports, outName :: outputs, (pubPath ^ "/" ^ scriptName) :: scripts) + end + + val _ = print "Compiling templates....\n" + + val (exports, outputs, scripts) = foldl ct ([], [], []) mlts + + val outf = TextIO.openOut (outPath ^ "/_main.sml") + + val _ = TextIO.output (outf, "structure Templates :> TEMPLATES =\nstruct\n\tval templates = [") + val _ = (case exports of + [] => () + | (exp::rest) => (TextIO.output (outf, "(\"" ^ exp ^ "\", " ^ exp ^ ".exec)"); + app (fn exp => TextIO.output (outf, ",\n\t\t(\"" ^ exp ^ "\", " ^ exp ^ ".exec)")) + rest)) + val _ = TextIO.output (outf, "]\nend\n\nstructure Main = MainFn(Templates)\n") + val _ = TextIO.closeOut outf + + val outf = TextIO.openOut (outPath ^ "/sources.cm") + val printNames = app (fn name => TextIO.output (outf, "\t" ^ name ^ "\n")) + + fun makeScript (name, str) = + let + val outf = TextIO.openOut name + in + TextIO.output (outf, "#!/bin/sh\n\n"); + TextIO.output (outf, sml ^ "/sml @SMLload=" ^ outPath ^ "/heap." ^ arch ^ " " ^ str ^ " $*\n"); + TextIO.closeOut outf; + Posix.FileSys.chmod (name, cgiMode) + end + in + if !ErrorMsg.anyErrors then + (TextIO.print "Errors compiling templates.\n"; + OS.Process.failure) + else + (TextIO.output (outf, "(* Automatic generate web fun happyness *)\n\nLibrary\n\tstructure Main\nis\n\t(* Web library *)\n\t"); + TextIO.output (outf, Config.lib config); + TextIO.output (outf, "\n\n\t(* Libraries *)\n\n"); + printNames (Config.cm config); + TextIO.output (outf, "\n\t(* SML sources *)\n\n"); + printNames smls; + TextIO.output (outf, "\n\t(* Templates *)\n\n"); + printNames outputs; + TextIO.output (outf, "\n\t(* Driver *)\n\n\t_main.sml\n"); + TextIO.closeOut outf; + if OS.Process.system (sml ^ "/ml-build " ^ outPath ^ "/sources.cm Main.main " ^ outPath ^ "/heap") = OS.Process.success then + (ListPair.app makeScript (scripts, exports); + OS.Process.success) + else + OS.Process.failure) + end +end diff --git a/src/config.sig b/src/config.sig new file mode 100644 index 0000000..57c0f86 --- /dev/null +++ b/src/config.sig @@ -0,0 +1,38 @@ +(* + * Dynamic web page generation with Standard ML + * Copyright (C) 2003 Adam Chlipala + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + *) + +(* User-specified runtime configuration *) + +signature CONFIG = +sig + type config + + val default : unit -> config + val read : string -> config -> config + + val inPath : config -> string + val outPath : config -> string + val pubPath : config -> string + val lib : config -> string + val compiler : config -> string + val cm : config -> string list + val sml : config -> string + + val printFn : config -> string -> string option +end \ No newline at end of file diff --git a/src/config.sml b/src/config.sml new file mode 100644 index 0000000..d021359 --- /dev/null +++ b/src/config.sml @@ -0,0 +1,124 @@ +(* + * Dynamic web page generation with Standard ML + * Copyright (C) 2003 Adam Chlipala + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + *) + +(* User-specifed runtime configuration *) + +structure Config :> CONFIG = +struct + val defaultFile = "/etc/mlt.conf" + + datatype config = + CONFIG of {inPath : string, (* Directory for input sources *) + outPath : string, (* Working directory *) + pubPath : string, (* Directory in which to put actual CGI scripts *) + lib : string, (* Path to runtime library .cm file *) + compiler : string, (* Path to compiler library .cm file *) + sml : string, (* Path to sml program *) + printFn : string StringMap.map, (* Map from SML type names to text for functions to print + * their values *) + cm : string list (* List of extra SML/CM files to use with this project *)} + + fun inPath (CONFIG {inPath, ...}) = inPath + fun outPath (CONFIG {outPath, ...}) = outPath + fun pubPath (CONFIG {pubPath, ...}) = pubPath + fun lib (CONFIG {lib, ...}) = lib + fun sml (CONFIG {sml, ...}) = sml + fun compiler (CONFIG {compiler, ...}) = compiler + fun cm (CONFIG {cm, ...}) = cm + fun printFn (CONFIG {printFn, ...}) s = StringMap.find (printFn, s) + + fun expandPath path = + if size path >= 1 andalso String.sub (path, 0) <> #"/" then + OS.FileSys.getDir () ^ "/" ^ path + else + path + + fun read fname (config as CONFIG fields) = + let + val inf = TextIO.openIn fname + + fun read (fields as {inPath, outPath, pubPath, lib, compiler, cm, sml, printFn}) = + (case TextIO.inputLine inf of + "" => CONFIG fields + | line => + (case String.tokens Char.isSpace line of + [] => read fields + | ["in", inPath] => read {inPath = expandPath inPath, outPath = outPath, pubPath = pubPath, + lib = lib, compiler = compiler, printFn = printFn, + cm = cm, sml = sml} + | ["out", outPath] => read {inPath = inPath, outPath = expandPath outPath, pubPath = pubPath, + lib = lib, compiler = compiler, printFn = printFn, + cm = cm, sml = sml} + | ["pub", pubPath] => read {inPath = inPath, outPath = outPath, pubPath = expandPath pubPath, + lib = lib, compiler = compiler, printFn = printFn, + cm = cm, sml = sml} + | ["lib", lib] => read {inPath = inPath, outPath = outPath, pubPath = pubPath, + lib = lib, compiler = compiler, printFn = printFn, + cm = cm, sml = sml} + | ["compiler", compiler] => read {inPath = inPath, outPath = outPath, pubPath = pubPath, + lib = lib, compiler = compiler, printFn = printFn, + cm = cm, sml = sml} + | ["sml", sml] => read {inPath = inPath, outPath = outPath, pubPath = pubPath, + lib = lib, compiler = compiler, printFn = printFn, + cm = cm, sml = sml} + | "print"::rest => + let + fun split ([], _) = (print "Bad printFn directive\n"; + read fields) + | split ("="::after, befor) = + let + val befor = rev befor + fun toS [] = "" + | toS (h::t) = foldl (fn (s, acc) => acc ^ " " ^ s) h t + val printFn = StringMap.insert (printFn, toS befor, toS after) + in + read {inPath = inPath, outPath = outPath, pubPath = pubPath, + lib = lib, compiler = compiler, printFn = printFn, + cm = cm, sml = sml} + end + | split (h::after, befor) = split (after, h::befor) + in + split (rest, []) + end + | ["cm", fname] => read {inPath = inPath, outPath = outPath, pubPath = pubPath, + lib = lib, compiler = compiler, printFn = printFn, + cm = fname::cm, sml = sml} + | _ => (print "Unknown config directive\n"; + read fields))) + in + read fields + before TextIO.closeIn inf + end handle Io => config + + fun default () = + let + val cwd = OS.FileSys.getDir () + + val base = CONFIG {lib = "/usr/local/share/mlt/src/lib/sources.cm", + compiler = "/usr/local/share/mlt/src/sources.cm", + sml = "/usr/local/sml/bin", + inPath = cwd, + outPath = cwd, + pubPath = cwd, + printFn = StringMap.empty, + cm = []} + in + read defaultFile base + end +end \ No newline at end of file diff --git a/src/errormsg.sml b/src/errormsg.sml new file mode 100644 index 0000000..fba0a86 --- /dev/null +++ b/src/errormsg.sml @@ -0,0 +1,63 @@ +(* This file comes mostly from "Modern Compiler Implementation in ML," by Andrew Appel + * http://www.cs.princeton.edu/~appel/modern/ml/ + *) + +signature ERRORMSG = + sig + val reset : unit -> unit + + val anyErrors : bool ref + val errorText : string ref + + val fileName : string ref + val sourceStream : TextIO.instream ref + + val lineNum : int ref + val linePos : int list ref + + val error : (int * int) option -> string -> unit + + exception Error +end + +structure ErrorMsg :> ERRORMSG = + struct + (* Initial values of compiler state variables *) + val anyErrors = ref false + val errorText = ref "" + val fileName = ref "" + val lineNum = ref 1 + val linePos = ref [1] + val sourceStream = ref TextIO.stdIn + + fun print msg = (errorText := !errorText ^ msg; + TextIO.print msg) + + (* Reset compiler to initial state *) + fun reset() = (anyErrors:=false; + errorText:=""; + fileName:=""; + lineNum:=1; + linePos:=[1]; + sourceStream:=TextIO.stdIn) + + (* Print the given error message *) + fun error posopt (msg:string) = + let + val (startpos, endpos) = Option.getOpt (posopt, (0, 0)) + fun look(pos,a::rest,n) = + if a diff --git a/src/lib/build.sml b/src/lib/build.sml new file mode 100644 index 0000000..782b4b6 --- /dev/null +++ b/src/lib/build.sml @@ -0,0 +1,4 @@ +(if CM.recomp "sources.cm" andalso CM.stabilize true "sources.cm" then + OS.Process.exit OS.Process.success + else + OS.Process.exit OS.Process.failure) : unit; \ No newline at end of file diff --git a/src/lib/cgi.sig b/src/lib/cgi.sig new file mode 100644 index 0000000..124a468 --- /dev/null +++ b/src/lib/cgi.sig @@ -0,0 +1,183 @@ +(* Mosmlcgi -- Support for writing CGI scripts in Moscow ML + + (c) Jonas Barklund, Computing Science Dept., Uppsala University, 1996. + Documentation and support for file upload added by Peter Sestoft. + + -------- + Ported to SML/NJ by Dave MacQueen (7 Apr 1998). + Tweaked to work with a saved heap image by Adam Chlipala (2003). + +*) + +signature CGI = +sig + +val init : unit -> unit + +(* 1. Accessing the fields or parameters of a CGI call *) + +val cgi_fieldnames : unit -> string list +val cgi_field_strings : string -> string list; +val cgi_field_string : string -> string option; +val cgi_field_integer : string * int -> int; + +(* 2. Accessing parts in multipart/form-data; form-based file upload *) + +val cgi_partnames : unit -> string list + +type part +val cgi_part : string -> part option +val cgi_parts : string -> part list + +val part_fieldnames : part -> string list +val part_type : part -> string option +val part_data : part -> string +val part_field_strings : part -> string -> string list +val part_field_string : part -> string -> string option +val part_field_integer : part -> string * int -> int + +(* 3. Administrative information *) + +val cgi_server_software : unit -> string option; +val cgi_server_name : unit -> string option; +val cgi_gateway_interface : unit -> string option; +val cgi_server_protocol : unit -> string option; +val cgi_server_port : unit -> string option; +val cgi_request_method : unit -> string option; +val cgi_http_accept : unit -> string option; +val cgi_http_user_agent : unit -> string option; +val cgi_http_referer : unit -> string option; +val cgi_path_info : unit -> string option; +val cgi_path_translated : unit -> string option; +val cgi_script_name : unit -> string option; +val cgi_query_string : unit -> string option; +val cgi_remote_host : unit -> string option; +val cgi_remote_addr : unit -> string option; +val cgi_remote_user : unit -> string option; +val cgi_remote_ident : unit -> string option; +val cgi_auth_type : unit -> string option; +val cgi_content_type : unit -> string option; +val cgi_content_length : unit -> string option; +val cgi_annotation_server : unit -> string option; + +end (* signature CGI *) + +(* The Mosmlcgi library is for writing CGI programs in Moscow ML. A + CGI program may be installed on a WWW server and is invoked in + response to HTTP requests sent to the server from a web browser, + typically from an HTML FORM element. + + + 1. Obtaining field values sent from an ordinary HTML form + --------------------------------------------------------- + + [cgi_fieldnames] is a list of the names of fields present in the + CGI call message. If field name fnm is in cgi_fieldnames, then + cgi_field_string fnm <> NONE. + + [cgi_field_strings fnm] is a (possibly empty) list of the strings + bound to field fnm. + + [cgi_field_string fnm] returns SOME(s) where s is a string bound to + field name fnm, if any; otherwise NONE. Equivalent to + case cgi_field_strings fnm of + [] => NONE + | s :: _ => SOME s + + [cgi_field_integer (fnm, deflt)] attempts to parse an integer from + field fnm. Returns i if cgi_field_string(fnm) = SOME(s) and an + integer i can be parsed from a prefix of s; otherwise returns deflt. + + + 2. Obtaining field values sent with ENCTYPE="multipart/form-data" + ----------------------------------------------------------------- + + [cgi_partnames] is a list of the names of the parts of the + multipart/form-data message. + + The type part is the abstract type of parts of a message. Each part + may have several fields. In this implementation, the field of a + part cannot be a another part itself. + + [cgi_parts pnm] is a (possibly empty) list of the parts called pnm. + + [cgi_part pnm] is SOME(prt) where prt is a part called pnm, if any; + otherwise NONE. Equivalent to + case cgi_parts pnm of + [] => NONE + | prt :: _ => SOME prt + + [part_fieldnames prt] is the list of field names in part pnm. + + [part_type prt] is SOME(typ) if the part prt contains a specification + `Context-Type: typ'; otherwise NONE. + + [part_data prt] is the data contain in part prt; for instance, the + contents of a file uploaded via form-based file upload. + + [part_field_strings prt fnm] is a (possibly empty) list of the + strings bound to field fnm in part prt. + + [part_field_string prt fnm] returns SOME(s) where s is a string + bound to field name fnm in part prt, if any; otherwise NONE. + Equivalent to + case part_field_strings prt fnm of + [] => NONE + | s :: _ => SOME s + + [part_field_integer prt (fnm, deflt)] attempts to parse an integer + from field fnm of part prt. Returns i if part_field_string prt fnm + = SOME(s) and an integer i can be parsed from a prefix of s; + otherwise returns deflt. + + + 3. Administrative and server information + ---------------------------------------- + + Each of the following variables has the value SOME(s) if the + corresponding CGI environment variable is bound to string s; + otherwise NONE: + + [cgi_server_software] is the value of SERVER_SOFTWARE + + [cgi_server_name] is the value of SERVER_NAME + + [cgi_gateway_interface] is the value of GATEWAY_INTERFACE + + [cgi_server_protocol] is the value of SERVER_PROTOCOL + + [cgi_server_port] is the value of SERVER_PORT + + [cgi_request_method] is the value of REQUEST_METHOD + + [cgi_http_accept] is the value of HTTP_ACCEPT + + [cgi_http_user_agent] is the value of HTTP_USER_AGENT + + [cgi_http_referer] is the value of HTTP_REFERER + + [cgi_path_info] is the value of PATH_INFO + + [cgi_path_translated] is the value of PATH_TRANSLATED + + [cgi_script_name] is the value of SCRIPT_NAME + + [cgi_query_string] is the value of QUERY_STRING + + [cgi_remote_host] is the value of REMOTE_HOST + + [cgi_remote_addr] is the value of REMOTE_ADDR + + [cgi_remote_user] is the value of REMOTE_USER + + [cgi_remote_ident] is the value of REMOTE_IDENT + + [cgi_auth_type] is the value of AUTH_TYPE + + [cgi_content_type] is the value of CONTENT_TYPE + + [cgi_content_length] is the value of CONTENT_LENGTH, that is, the + length of the data transmitted in the CGI call. + + [cgi_annotation_server] is the value of ANNOTATION_SERVER +*) diff --git a/src/lib/cgi.sml b/src/lib/cgi.sml new file mode 100644 index 0000000..842ea56 --- /dev/null +++ b/src/lib/cgi.sml @@ -0,0 +1,303 @@ +(* + + Mosmlcgi.sml + + (c) Jonas Barklund, Computing Science Dept., Uppsala University, 1996. + + Support for form-based file upload via multipart/form-data, + by Peter Sestoft (sestoft@dina.kvl.dk) December 1996. + + Anyone is granted the right to copy and/or use this code, provided + that this note is retained, also in modified versions. The code is + provided as is with no guarantee about any functionality. I take no + responsibility for its proper function. + + -------- + Ported to SML/NJ by Dave MacQueen (7 Apr 1998). + Tweaked to work with a saved heap image by Adam Chlipala (2003). + +*) + +structure Cgi : CGI = +struct + +val cgi_server_software = ref (NONE : string option) +val cgi_server_name = ref (NONE : string option) +val cgi_gateway_interface = ref (NONE : string option) +val cgi_server_protocol = ref (NONE : string option) +val cgi_server_port = ref (NONE : string option) +val cgi_request_method = ref (NONE : string option) +val cgi_http_accept = ref (NONE : string option) +val cgi_http_user_agent = ref (NONE : string option) +val cgi_http_referer = ref (NONE : string option) +val cgi_path_info = ref (NONE : string option) +val cgi_path_translated = ref (NONE : string option) +val cgi_script_name = ref (NONE : string option) +val cgi_query_string = ref (NONE : string option) +val cgi_remote_host = ref (NONE : string option) +val cgi_remote_addr = ref (NONE : string option) +val cgi_remote_user = ref (NONE : string option) +val cgi_remote_ident = ref (NONE : string option) +val cgi_auth_type = ref (NONE : string option) +val cgi_content_type = ref (NONE : string option) +val cgi_content_length = ref (NONE : string option) +val cgi_annotation_server = ref (NONE : string option) + +structure Splaymap = SplayMapFn(struct type ord_key = string + val compare = String.compare + end) + +local + open Option TextIO + + fun intOf NONE = NONE + | intOf (SOME s) = Int.fromString s + + val query_string = ref "" + + fun isn't c1 c2 = c1 <> c2 + fun is c1 c2 = c1 = c2 + + (* For debugging, one may log to the httpd error_log: *) + + fun err s = TextIO.output(TextIO.stdErr, s); + + (* val _ = err query_string; + val _ = err (Int.toString (getOpt(intOf cgi_content_length, 0))); + *) + + (* Get the line starting with string s *) + + fun line s sus = + let open Substring + val (_, fullline) = position s sus + val after = triml (String.size s) fullline + in takel (fn c => c <> #"\r" andalso c <> #"\n") after end + + (* Get the value of boundary *) + + fun getboundary line = + let open Substring + val (_, bndeqn) = position "boundary=" line + in + if isEmpty bndeqn then NONE + else SOME (string (triml 1 (dropl (isn't #"=") bndeqn))) + end + handle Option => NONE + + (* If CGI request type is multipart/form-data, then SOME(boundary): *) + + val multipart_boundary = ref (NONE : string option) + + val the_fields = ref ([] : substring list) + + val dict_with_codes = ref ([] : substring list list) + + (* Decode CGI parameters: *) + + fun decode(sus) = + let + val sz = Substring.size(sus); + exception Dehex; + fun dehex(ch) = + if #"0" <= ch andalso ch <= #"9" + then Char.ord(ch) - Char.ord(#"0") + else if #"A" <= ch andalso ch <= #"F" + then (Char.ord(ch) - Char.ord(#"A")) + 10 + else if #"a" <= ch andalso ch <= #"f" + then (Char.ord(ch) - Char.ord(#"a")) + 10 + else raise Dehex; + fun decode_one(i) = + Char.chr(16*dehex(Substring.sub(sus,i+1))+ + dehex(Substring.sub(sus,i+2))); + fun dec(i) = + if i>=sz then [] + else case Substring.sub(sus,i) + of #"+" => #" "::dec(i+1) + | #"%" => decode_one(i)::dec(i+3) + | ch => ch::dec(i+1); + in + String.implode(dec(0)) + end handle exn => + (err ("decode failed on " ^ Substring.string sus ^ "\n"); "") + + fun 'a addItem ((key, value: 'a), dict: 'a list Splaymap.map) = + Splaymap.insert(dict, key, case Splaymap.find(dict, key) of + SOME vs => value :: vs + | NONE => [value]) + + fun addField ([keysrc, valsrc], dict) = + addItem ((decode keysrc, decode valsrc), dict) + | addField (_, dict) = dict + + val cgi_dict = ref (Splaymap.empty : string list Splaymap.map) + + fun keys dict : string list = + Splaymap.foldri (fn (key,_,res) => key :: res) [] dict + + (* Decode multipart messages: *) + + fun part_fields dict name = + case Splaymap.find (dict, name) of + NONE => [] + | SOME vals => vals + + fun part_field dict name = + case Splaymap.find (dict, name) of + SOME (v :: _) => SOME v + | _ => NONE + + fun getint NONE default = default + | getint (SOME str) default = + case Int.scan StringCvt.DEC Substring.getc (Substring.all str) of + NONE => default + | SOME(i, rest) => if Substring.isEmpty rest then i else default + + val multiparts = ref ([] : substring list) + + fun decodepart (part : Substring.substring) = + let open Char Substring + val crlf2 = "\r\n\r\n" + val (header, rest) = position crlf2 part + val eqnsrc = line "Content-Disposition: form-data;" header + val typ = line "Content-Type: " header + val equations = List.map (fn f => dropl isSpace (dropr isSpace f)) + (fields (is #";") eqnsrc) + + fun addField (eqn, dict) = + let val (name, v) = splitl (isn't #"=") eqn + (* Drop equals sign and quotes from value *) + val value = triml 2 (trimr 1 v) + in addItem((string name, string value), dict) end + + val dict : string list Splaymap.map = + List.foldr addField Splaymap.empty equations + + val partname = + case part_field dict "name" of + NONE => "[Anonymous]" (* Is this is good idea? *) + | SOME n => n + in + (partname, + { fieldnames = keys dict, + tyOpt = if isEmpty typ then NONE else SOME (string typ), + dict = dict, + (* Strip off CRLFCRLF and CRLF *) + data = string (trimr 2 (triml 4 rest)) + }) + end + + type part = {fieldnames : string list, + tyOpt : string option, + dict : (string list) Splaymap.map, + data : string} + + val part_dict = ref (Splaymap.empty : (part list) Splaymap.map) +in + type part = part + fun cgi_partnames () = keys (!part_dict) + fun cgi_part name = part_field (!part_dict) name + fun cgi_parts name = part_fields (!part_dict) name + + fun part_fieldnames (p : part) = #fieldnames p + fun part_type (p : part) = #tyOpt p + fun part_data (p : part) = #data p + fun part_field_strings (p : part) name = part_fields (#dict p) name + fun part_field_string (p : part) name = part_field (#dict p) name + fun part_field_integer (p : part) (name, default) = + getint (part_field (#dict p) name) default + + fun cgi_fieldnames () = keys (!cgi_dict) + fun cgi_field_strings name = part_fields (!cgi_dict) name + fun cgi_field_string name = part_field (!cgi_dict) name + fun cgi_field_integer (name, default) = + getint (cgi_field_string name) default + + fun init () = + (cgi_server_software := OS.Process.getEnv("SERVER_SOFTWARE"); + cgi_server_name := OS.Process.getEnv("SERVER_NAME"); + cgi_gateway_interface := OS.Process.getEnv("GATEWAY_INTERFACE"); + cgi_server_protocol := OS.Process.getEnv("SERVER_PROTOCOL"); + cgi_server_port := OS.Process.getEnv("SERVER_PORT"); + cgi_request_method := OS.Process.getEnv("REQUEST_METHOD"); + cgi_http_accept := OS.Process.getEnv("HTTP_ACCEPT"); + cgi_http_user_agent := OS.Process.getEnv("HTTP_USER_AGENT"); + cgi_http_referer := OS.Process.getEnv("HTTP_REFERER"); + cgi_path_info := OS.Process.getEnv("PATH_INFO"); + cgi_path_translated := OS.Process.getEnv("PATH_TRANSLATED"); + cgi_script_name := OS.Process.getEnv("SCRIPT_NAME"); + cgi_query_string := OS.Process.getEnv("QUERY_STRING"); + cgi_remote_host := OS.Process.getEnv("REMOTE_HOST"); + cgi_remote_addr := OS.Process.getEnv("REMOTE_ADDR"); + cgi_remote_user := OS.Process.getEnv("REMOTE_USER"); + cgi_remote_ident := OS.Process.getEnv("REMOTE_IDENT"); + cgi_auth_type := OS.Process.getEnv("AUTH_TYPE"); + cgi_content_type := OS.Process.getEnv("CONTENT_TYPE"); + cgi_content_length := OS.Process.getEnv("CONTENT_LENGTH"); + cgi_annotation_server := OS.Process.getEnv("ANNOTATION_SERVER"); + + multipart_boundary := + (let open Substring + val content_type = all (valOf (!cgi_content_type)) + in + if isPrefix "multipart/form-data;" content_type then + getboundary content_type + else + NONE + end handle Option => NONE); + + query_string := + (case !cgi_request_method of + SOME ("GET") => getOpt(!cgi_query_string,"") + | SOME ("POST") => inputN(stdIn, getOpt(intOf (!cgi_content_length), 0)) + | _ => getOpt(!cgi_query_string,"")); + + the_fields := + (case !multipart_boundary of + NONE => Substring.tokens (is #"&") (Substring.all (!query_string)) + | _ => []); + + dict_with_codes := List.map (Substring.fields (is #"=")) (!the_fields); + + cgi_dict := List.foldr addField Splaymap.empty (!dict_with_codes); + + multiparts := + (let open Substring + val boundary = "--" ^ valOf (!multipart_boundary) + val skipbnd = dropl (isn't #"\n") + val (_, contents) = position boundary (all (!query_string)) + fun loop rest = + let val (pref, suff) = position boundary rest + in + if isEmpty pref orelse isEmpty suff then [] + else pref :: loop (skipbnd suff) + end + in loop (skipbnd contents) end + handle Option => []); + + part_dict := List.foldr addItem Splaymap.empty (List.map decodepart (!multiparts))) + + val cgi_server_software = fn () => !cgi_server_software + val cgi_server_name = fn () => !cgi_server_name + val cgi_gateway_interface = fn () => !cgi_gateway_interface + val cgi_server_protocol = fn () => !cgi_server_protocol + val cgi_server_port = fn () => !cgi_server_port + val cgi_request_method = fn () => !cgi_request_method + val cgi_http_accept = fn () => !cgi_http_accept + val cgi_http_user_agent = fn () => !cgi_http_user_agent + val cgi_http_referer = fn () => !cgi_http_referer + val cgi_path_info = fn () => !cgi_path_info + val cgi_path_translated = fn () => !cgi_path_translated + val cgi_script_name = fn () => !cgi_script_name + val cgi_query_string = fn () => !cgi_query_string + val cgi_remote_host = fn () => !cgi_remote_host + val cgi_remote_addr = fn () => !cgi_remote_addr + val cgi_remote_user = fn () => !cgi_remote_user + val cgi_remote_ident = fn () => !cgi_remote_ident + val cgi_auth_type = fn () => !cgi_auth_type + val cgi_content_type = fn () => !cgi_content_type + val cgi_content_length = fn () => !cgi_content_length + val cgi_annotation_server = fn () => !cgi_annotation_server +end (* local *) + +end (* structure Cgi *) diff --git a/src/lib/main.sig b/src/lib/main.sig new file mode 100644 index 0000000..de7c0bb --- /dev/null +++ b/src/lib/main.sig @@ -0,0 +1,25 @@ +(* + * Dynamic web page generation with Standard ML + * Copyright (C) 2003 Adam Chlipala + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + *) + +(* Main CGI program interface *) + +signature MAIN = +sig + val main : string * string list -> OS.Process.status +end \ No newline at end of file diff --git a/src/lib/main.sml b/src/lib/main.sml new file mode 100644 index 0000000..0533912 --- /dev/null +++ b/src/lib/main.sml @@ -0,0 +1,46 @@ +(* + * Dynamic web page generation with Standard ML + * Copyright (C) 2003 Adam Chlipala + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + *) + +(* Main CGI program interface *) + +functor MainFn (Templates : TEMPLATES) :> MAIN = +struct + val templates = foldl StringMap.insert' StringMap.empty Templates.templates + + fun main (_, args) = + let + val _ = Cgi.init () + val cgiFields = Cgi.cgi_fieldnames () + fun mapper name = (name, valOf (Cgi.cgi_field_string name)) + in + Web.pushParams (map mapper cgiFields); + case args of + [] => (print "Status: 500\nContent-type: text/html\n\n500 error

500 error

No template was specified\n"; + OS.Process.failure) + | (name::_) => + (case StringMap.find (templates, name) of + NONE => (print "Status: 404\nContent-type: text/html\n\n404 error

404 error

Template not found\n"; + OS.Process.failure) + | SOME f => (f (); + Web.output (); + OS.Process.success)) + end handle ex => (print "Status: 500\nContent-type: text/plain\n\nAn exception!\n\n"; + app (fn s => print (s ^ "\n")) (SMLofNJ.exnHistory ex); + OS.Process.failure) +end \ No newline at end of file diff --git a/src/lib/sources.cm b/src/lib/sources.cm new file mode 100644 index 0000000..d1e717c --- /dev/null +++ b/src/lib/sources.cm @@ -0,0 +1,45 @@ +(* + * Dynamic web page generation with Standard ML + * Copyright (C) 2003 Adam Chlipala + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + *) + +Library + signature TEMPLATE + signature TEMPLATES + signature MAIN + signature WEB + + structure Web + + functor MainFn +is + $/basis.cm + $/smlnj-lib.cm + string_map.sml + + cgi.sig + cgi.sml + + template.sig + templates.sig + main.sig + + web.sig + web.sml + + main.sml + \ No newline at end of file diff --git a/src/lib/string-map.sml b/src/lib/string-map.sml new file mode 100644 index 0000000..bbbf968 --- /dev/null +++ b/src/lib/string-map.sml @@ -0,0 +1,8 @@ +structure StringKey :> ORD_KEY where type ord_key = string = +struct + type ord_key = string + val compare = String.compare +end + +structure StringMap = BinaryMapFn(StringKey) +structure StringSet = BinarySetFn(StringKey) \ No newline at end of file diff --git a/src/lib/string_map.sml b/src/lib/string_map.sml new file mode 100644 index 0000000..4746991 --- /dev/null +++ b/src/lib/string_map.sml @@ -0,0 +1,27 @@ +(* + * Dynamic web page generation with Standard ML + * Copyright (C) 2003 Adam Chlipala + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + *) + +structure StringKey :> ORD_KEY where type ord_key = string = +struct + type ord_key = string + val compare = String.compare +end + +structure StringMap = BinaryMapFn(StringKey) +structure StringSet = BinarySetFn(StringKey) \ No newline at end of file diff --git a/src/lib/template.sig b/src/lib/template.sig new file mode 100644 index 0000000..9a5f22a --- /dev/null +++ b/src/lib/template.sig @@ -0,0 +1,25 @@ +(* + * Dynamic web page generation with Standard ML + * Copyright (C) 2003 Adam Chlipala + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + *) + +(* Signature for a single compiled template *) + +signature TEMPLATE = +sig + val exec: unit -> unit +end diff --git a/src/lib/templates.sig b/src/lib/templates.sig new file mode 100644 index 0000000..54650ae --- /dev/null +++ b/src/lib/templates.sig @@ -0,0 +1,25 @@ +(* + * Dynamic web page generation with Standard ML + * Copyright (C) 2003 Adam Chlipala + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + *) + +(* Database of available templates *) + +signature TEMPLATES = +sig + val templates : (string * (unit -> unit)) list +end \ No newline at end of file diff --git a/src/lib/web.sig b/src/lib/web.sig new file mode 100644 index 0000000..c22603e --- /dev/null +++ b/src/lib/web.sig @@ -0,0 +1,33 @@ +(* + * Dynamic web page generation with Standard ML + * Copyright (C) 2003 Adam Chlipala + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + *) + +(* CGI interaction *) + +signature WEB = +sig + val print : string -> unit + val output : unit -> unit + + val setParam : string * string -> unit + val getParam : string -> string + + val pushParams : (string * string) list -> unit + val popParams : unit -> unit + val withParams : (unit -> 'a) -> (string * string) list -> 'a +end \ No newline at end of file diff --git a/src/lib/web.sml b/src/lib/web.sml new file mode 100644 index 0000000..4b256a5 --- /dev/null +++ b/src/lib/web.sml @@ -0,0 +1,57 @@ +(* + * Dynamic web page generation with Standard ML + * Copyright (C) 2003 Adam Chlipala + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + *) + +(* CGI interaction *) + +structure Web :> WEB = +struct + val params : string StringMap.map ref = ref StringMap.empty + + val paramStack : string StringMap.map list ref = ref [] + + fun setParam (n, v) = params := StringMap.insert (!params, n, v) + + fun getParam v = + (case StringMap.find (!params, v) of + NONE => "" + | SOME s => s) + + fun pushParams nvs = + (paramStack := (!params) :: (!paramStack); + app setParam nvs) + + fun popParams () = + (case !paramStack of + [] => raise Fail "Empty params stack in popParams" + | h::t => (params := h; + paramStack := t)) + + fun withParams f nvs = + (pushParams nvs; + ((f ()) handle ex => (popParams (); raise ex)) + before popParams ()) + + val text = ref ([] : string list) + + fun print x = text := x :: (!text) + + fun output () = + (TextIO.print "Status: 200\nContent-type: text/html\n\n"; + TextIO.print (String.concat (List.rev (!text)))) +end \ No newline at end of file diff --git a/src/main.sml b/src/main.sml new file mode 100644 index 0000000..80b8eaf --- /dev/null +++ b/src/main.sml @@ -0,0 +1,37 @@ +(* + * Dynamic web page generation with Standard ML + * Copyright (C) 2003 Adam Chlipala + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + *) + +(* Command-line interface *) + +structure Main = +struct + fun main (_, args) = + (case args of + [] => Compiler.compileDirectory (Config.read "mlt.conf" (Config.default ())) + (*| [path] => (Compiler.compileDirectory {inPath = path, outPath = path}; + OS.Process.success) + | [inPath, outPath] => (Compiler.compileDirectory {inPath = inPath, outPath = outPath}; + OS.Process.success)*) + | _ => (print "Too many arguments.\n"; + OS.Process.failure)) + handle Fail msg => (print "FATAL ERROR: "; + print msg; + print "\n"; + OS.Process.failure) +end \ No newline at end of file diff --git a/src/mlt b/src/mlt new file mode 100644 index 0000000..d85e607 --- /dev/null +++ b/src/mlt @@ -0,0 +1 @@ +/usr/local/sml/bin/sml @SMLload=/usr/local/bin/mlt.x86-linux diff --git a/src/mlt.grm b/src/mlt.grm new file mode 100644 index 0000000..a559649 --- /dev/null +++ b/src/mlt.grm @@ -0,0 +1,249 @@ +(* *) +(* Dynamic web page generation with Standard ML *) +(* Copyright (C) 2003 Adam Chlipala *) +(* *) +(* This library is free software; you can redistribute it and/or *) +(* modify it under the terms of the GNU Lesser General Public *) +(* License as published by the Free Software Foundation; either *) +(* version 2.1 of the License, or (at your option) any later version. *) +(* *) +(* This library is distributed in the hope that it will be useful, *) +(* but WITHOUT ANY WARRANTY; without even the implied warranty of *) +(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *) +(* Lesser General Public License for more details. *) +(* *) +(* You should have received a copy of the GNU Lesser General Public *) +(* License along with this library; if not, write to the Free Software *) +(* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) + +(* Grammar for ML template language *) + +open Tree + +fun rcomp ((a, _), (b, _)) = String.compare (a, b) = GREATER +fun sortRcs x = ListMergeSort.sort rcomp x + +fun addNumbers L = + let + fun addNum (_, []) = [] + | addNum (n, h::t) = (Int.toString n, h)::(addNum(n+1,t)) + in + addNum (1, L) + end + + +%% +%header (functor MltLrValsFn(structure Token : TOKEN)) + +%term + EOF + | HTML of string + | IF | THEN | ELSE | AS | WITH | OPEN | VAL | REF | TRY | CATCH + | FOREACH | IN | CASE | ORELSE | ANDALSO + | LPAREN | RPAREN | LBRACK | RBRACK | LBRACE | RBRACE | HASH | SEMI | CONS + | PLUS | MINUS | TIMES | DIVIDE | MOD | NEG | DOLLAR | AT | STRCAT + | ASN | EQ | NEQ | GT | GTE | LT | LTE + | IDENT of string | DOT | DOTDOT | DOTDOTDOT | COMMA | COLON | CARET | TILDE | UNDER + | INT of int | STRING of string | CHAR of string + +%nonterm + file of block + | block of block + | exp of exp + | appsL of exp list + | apps of exp + | term of exp + | pterm of pat + | papp of pat + | pat of pat + | path of ident list + | pathList of ident list list + | blockItem of blockItem + | ifte of ((exp * block) list * block option) withext + | matches of (pat * block) list withext + | pexp of exp + | ppat of pat + | pseq of pat list + | rseq of (ident * pat) list + | frseq of (ident * pat) list + | eseq of exp list + | elseq of exp list + | plseq of pat list + | erseq of (ident * exp) list + | ilist of ident list + | ivlist of (ident * exp) list + | catch of pat * block + | catches of (pat * block) list + +%verbose (* print summary of errors *) +%pos int (* positions *) +%start file +%pure +%eop EOF +%noshift EOF + +%name Mlt + +%left ANDALSO +%left ORELSE +%nonassoc EQ NEQ GT GTE LT LTE +%left PLUS MINUS +%left TIMES DIVIDE MOD +%left STRCAT +%nonassoc NEG +%right CONS + +%% + +file : block (block) + +ilist : IDENT ilist (IDENT :: ilist) + | IDENT ([IDENT]) + +ivlist : IDENT EQ exp COMMA ivlist ((IDENT, exp) :: ivlist) + | IDENT EQ exp ([(IDENT, exp)]) + +catch : CATCH ppat LBRACE block RBRACE (ppat, block) + +catches : catch catches (catch::catches) + | catch ([catch]) + +blockItem : HTML (BITEM (Html_i HTML, (HTMLleft, HTMLright))) + | REF ivlist (BITEM (Ref_i ivlist, (REFleft, ivlistright))) + | OPEN pathList (BITEM (Open_i pathList, (OPENleft, pathListright))) + | VAL pat EQ exp (BITEM (Val_i (pat, exp), (patleft, expright))) + | IDENT ASN exp (BITEM (Assn_i (IDENT, exp), (IDENTleft, expright))) + | exp (BITEM (Exp_i exp, (expleft, expright))) + | IF LPAREN exp RPAREN LBRACE block RBRACE ifte + (let val ((L, O), _) = ifte in + BITEM (Ifthenelse_i((exp, block) :: L, O), + (IFleft, ifteright)) + end) + | FOREACH LPAREN IDENT IN exp RPAREN LBRACE block RBRACE + (BITEM (Foreach_i (IDENT, exp, block), + (FOREACHleft, RBRACEright))) + | FOREACH LPAREN IDENT IN exp DOTDOT exp RPAREN LBRACE block RBRACE + (BITEM (For_i (IDENT, exp1, exp2, block), + (FOREACHleft, RBRACEright))) + | CASE pexp matches + (BITEM (Case_i (pexp, #1 matches), (CASEleft, matchesright))) + | TRY LBRACE block RBRACE catches + (BITEM (TryCatch_i (block, catches), (TRYleft, catchesright))) + +ifte : ELSE LBRACE block RBRACE (([], SOME block), (ELSEleft, RBRACEright)) + | ELSE IF LPAREN exp RPAREN LBRACE block RBRACE ifte (let val ((L, O), _) = ifte in + (((exp, block) :: L, O), (ELSEleft, ifteright)) + end) + | (([], NONE), (0, 0)) + +block : blockItem (BLOCK ([blockItem], (blockItemleft, blockItemright))) + | blockItem SEMI block (BLOCK (blockItem :: (unblock block), (blockItemleft, blockright))) + | blockItem block (BLOCK (blockItem :: (unblock block), (blockItemleft, blockright))) + | SEMI block (block) + | (BLOCK ([], (0, 0))) + +appsL : term appsL (term::appsL) + | term ([term]) + +apps : appsL (let + val e::r = appsL + in + foldl (fn (e, a) => EXP (App_e (a, e), (appsLleft, appsLright))) e r + end) + + +path : IDENT DOT path (IDENT::path) + | IDENT ([IDENT]) + +pathList: path pathList (path::pathList) + | path ([path]) + +eseq : exp COMMA eseq (exp :: eseq) + | exp COMMA exp ([exp1, exp2]) + +elseq : eseq (eseq) + | exp ([exp]) + | ([]) + +erseq : IDENT EQ exp COMMA erseq ((IDENT, exp) :: erseq) + | IDENT COMMA erseq ((IDENT, EXP (Ident_e [IDENT], (IDENTleft, IDENTright))) :: erseq) + | IDENT ([(IDENT, EXP (Ident_e [IDENT], (IDENTleft, IDENTright)))]) + | IDENT EQ exp ([(IDENT, exp)]) + +pexp : LPAREN eseq RPAREN (EXP (Record_e (true, addNumbers eseq), (LPARENleft, LPARENright))) + | LPAREN RPAREN (EXP (Record_e (true, []), (LPARENleft, RPARENright))) + | LPAREN exp RPAREN (exp) + +term : LBRACE erseq RBRACE (EXP (Record_e (false, sortRcs erseq), (LBRACEleft, RBRACEright))) + | LBRACE RBRACE (EXP (Record_e (false, []), (LBRACEleft, RBRACEright))) + | LBRACE term WITH erseq RBRACE (EXP (RecordUpd_e (term, erseq), (LBRACEleft, RBRACEright))) + | pexp (pexp) + | STRING (EXP (String_e STRING, (STRINGleft, STRINGright))) + | CHAR (EXP (Char_e CHAR, (CHARleft, CHARright))) + | path (EXP (Ident_e path, (pathleft, pathright))) + | INT (EXP (Int_e INT, (INTleft, INTright))) + | NEG (EXP (Neg_e, (NEGleft, NEGright))) + | DOLLAR (EXP (Param_e, (DOLLARleft, DOLLARright))) + | AT IDENT (EXP (Template_e IDENT, (ATleft, IDENTright))) + | HASH INT (EXP (Proj_e (Int.toString INT), (HASHleft, INTright))) + | HASH IDENT (EXP (Proj_e IDENT, (HASHleft, IDENTright))) + | LBRACK elseq RBRACK (foldr (fn x => EXP (Cons_e x, (LBRACKleft, RBRACKright))) + (EXP (Ident_e ["nil"], (0, 0))) elseq) + +exp : apps (apps) + | exp PLUS exp (EXP (Plus_e (exp1, exp2), (exp1left, exp2right))) + | exp MINUS exp (EXP (Minus_e (exp1, exp2), (exp1left, exp2right))) + | exp TIMES exp (EXP (Times_e (exp1, exp2), (exp1left, exp2right))) + | exp DIVIDE exp (EXP (Divide_e (exp1, exp2), (exp1left, exp2right))) + | exp MOD exp (EXP (Mod_e (exp1, exp2), (exp1left, exp2right))) + | exp EQ exp (EXP (Eq_e (exp1, exp2), (exp1left, exp2right))) + | exp NEQ exp (EXP (Neq_e (exp1, exp2), (exp1left, exp2right))) + | exp LT exp (EXP (Lt_e (exp1, exp2), (exp1left, exp2right))) + | exp LTE exp (EXP (Lte_e (exp1, exp2), (exp1left, exp2right))) + | exp GT exp (EXP (Gt_e (exp1, exp2), (exp1left, exp2right))) + | exp GTE exp (EXP (Gte_e (exp1, exp2), (exp1left, exp2right))) + | exp CONS exp (EXP (Cons_e (exp1, exp2), (exp1left, exp2right))) + | exp STRCAT exp (EXP (StrCat_e (exp1, exp2), (exp1left, exp2right))) + | exp ORELSE exp (EXP (Orelse_e (exp1, exp2), (exp1left, exp2right))) + | exp ANDALSO exp (EXP (Andalso_e (exp1, exp2), (exp1left, exp2right))) + +matches : ppat LBRACE block RBRACE matches (((ppat, block) :: (#1 matches), (ppatleft, matchesright))) + | ([], (0, 0)) + +rseq : IDENT EQ pat COMMA rseq ((IDENT, pat) :: rseq) + | IDENT COMMA rseq ((IDENT, PAT (Ident_p [IDENT], (IDENTleft, IDENTright))) :: rseq) + | IDENT ([(IDENT, PAT (Ident_p [IDENT], (IDENTleft, IDENTright)))]) + | IDENT EQ pat ([(IDENT, pat)]) + +frseq : IDENT EQ pat COMMA frseq ((IDENT, pat) :: frseq) + | IDENT COMMA frseq ((IDENT, PAT (Ident_p [IDENT], (IDENTleft, IDENTright))) :: frseq) + | DOTDOTDOT ([]) + +ppat : LPAREN pat RPAREN (PAT (unpat pat, (LPARENleft, RPARENright))) + | LPAREN pseq RPAREN (PAT (Record_p (true, addNumbers pseq), (LPARENleft, LPARENright))) + | LPAREN RPAREN (PAT (Record_p (true, []), (LPARENleft, RPARENright))) + +pseq : pat COMMA pseq (pat :: pseq) + | pat COMMA pat ([pat1, pat2]) + +plseq : pseq (pseq) + | pat ([pat]) + | ([]) + +pterm : path (PAT (Ident_p path, (pathleft, pathright))) + | UNDER (PAT (Wild_p, (UNDERleft, UNDERright))) + | INT (PAT (Int_p INT, (INTleft, INTright))) + | STRING (PAT (String_p STRING, (STRINGleft, STRINGright))) + | LBRACE rseq RBRACE (PAT (Record_p (false, sortRcs rseq), (LBRACEleft, RBRACEright))) + | LBRACE RBRACE (PAT (Record_p (false, []), (LBRACEleft, RBRACEright))) + | LBRACE frseq RBRACE (PAT (FlexRecord_p (sortRcs frseq), (LBRACEleft, RBRACEright))) + | ppat (ppat) + +papp : path papp (PAT (App_p (path, papp), (pathleft, pappright))) + | pterm (pterm) + +pat : papp CONS papp (PAT (Cons_p (papp1, papp2), (papp1left, papp2right))) + | papp (papp) + | IDENT AS pat (PAT (As_p (IDENT, pat), (IDENTleft, patright))) + | LBRACK plseq RBRACK (foldr (fn x => PAT (Cons_p x, (LBRACKleft, RBRACKright))) + (PAT (Ident_p ["nil"], (0, 0))) plseq) \ No newline at end of file diff --git a/src/mlt.lex b/src/mlt.lex new file mode 100644 index 0000000..568c1a3 --- /dev/null +++ b/src/mlt.lex @@ -0,0 +1,177 @@ +(* + * Dynamic web page generation with Standard ML + * Copyright (C) 2003 Adam Chlipala + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + *) + +(* Lexing info for ML template language *) + +type pos = int +type svalue = Tokens.svalue +type ('a,'b) token = ('a,'b) Tokens.token +type lexresult = (svalue,pos) Tokens.token + +val lineNum = ErrorMsg.lineNum +val linePos = ErrorMsg.linePos + +fun strip s = String.extract (s, 1, SOME (String.size s - 2)) + +local + val commentLevel = ref 0 + val commentPos = ref 0 + val linCom = ref false +in + fun enterComment yypos = (commentLevel := !commentLevel + 1; commentPos := yypos) + + fun linComStart yypos = (linCom := true; commentPos := yypos) + fun isLinCom () = !linCom + fun linComEnd () = linCom := false + + fun exitComment () = + let val _ = commentLevel := !commentLevel - 1 in + !commentLevel = 0 + end + + fun eof () = + let + val pos = hd (!linePos) + in + if (!commentLevel > 0) then + (ErrorMsg.error (SOME (!commentPos,!commentPos)) "Unterminated comment") + else (); + Tokens.EOF (pos,pos) + end +end + +val str = ref "" +val strStart = ref 0 + +%% +%header (functor MltLexFn(structure Tokens : Mlt_TOKENS)); +%full +%s COMMENT STRING CHAR CODE; + +id = ([A-Za-z_][A-Za-z0-9_]*)|([:]+); +intconst = [0-9]+; +ws = [\ \t\012]; +bo = [^<]+; + +%% + +\n => (if isLinCom () then (linComEnd (); YYBEGIN INITIAL) else (); + lineNum := !lineNum + 1; + linePos := yypos :: ! linePos; + continue ()); + + {ws}+ => (Tokens.HTML (" ", yypos, yypos + size yytext); lex ()); + + "<%" => (YYBEGIN CODE; Tokens.SEMI(yypos, yypos + size yytext)); + "%>" => (YYBEGIN INITIAL; Tokens.SEMI(yypos, yypos + size yytext)); + + "(*" => (YYBEGIN COMMENT; enterComment yypos; continue()); + "*)" => (ErrorMsg.error (SOME (yypos, yypos)) "Unbalanced comments"; + continue()); + + "(*" => (if not (isLinCom ()) then enterComment yypos else (); continue()); + "*)" => (if not (isLinCom ()) andalso exitComment () then YYBEGIN INITIAL else (); + continue()); + + "//" => (YYBEGIN COMMENT; linComStart yypos; continue()); + + {ws}+ => (lex ()); + + "\"" => (YYBEGIN STRING; strStart := yypos; str := ""; continue()); + "\\\"" => (str := !str ^ "\\\""; continue()); + "\"" => (YYBEGIN CODE; Tokens.STRING (!str, !strStart, yypos + 1)); + . => (str := !str ^ yytext; continue()); + + "#\"" => (YYBEGIN CHAR; strStart := yypos; str := ""; continue()); + "\\\"" => (str := !str ^ "\\\""; continue()); + "\"" => (YYBEGIN CODE; if size (!str) = 1 then + Tokens.CHAR (!str, !strStart, yypos + 1) + else + (ErrorMsg.error (SOME (yypos, yypos)) "Invalid character constant"; + continue())); + . => (str := !str ^ yytext; continue()); + + "{" => (Tokens.LBRACE (yypos, yypos + size yytext)); + "}" => (Tokens.RBRACE (yypos, yypos + size yytext)); + "(" => (Tokens.LPAREN (yypos, yypos + size yytext)); + ")" => (Tokens.RPAREN (yypos, yypos + size yytext)); + "[" => (Tokens.LBRACK (yypos, yypos + size yytext)); + "]" => (Tokens.RBRACK (yypos, yypos + size yytext)); + + "=" => (Tokens.EQ (yypos, yypos + size yytext)); + "<>" => (Tokens.NEQ (yypos, yypos + size yytext)); + "<" => (Tokens.LT (yypos, yypos + size yytext)); + "<=" => (Tokens.LTE (yypos, yypos + size yytext)); + ">" => (Tokens.GT (yypos, yypos + size yytext)); + ">=" => (Tokens.GTE (yypos, yypos + size yytext)); + + ":=" => (Tokens.ASN (yypos, yypos + size yytext)); + + "/" => (Tokens.DIVIDE (yypos, yypos + size yytext)); + "*" => (Tokens.TIMES (yypos, yypos + size yytext)); + "+" => (Tokens.PLUS (yypos, yypos + size yytext)); + "-" => (Tokens.MINUS (yypos, yypos + size yytext)); + "%" => (Tokens.MOD (yypos, yypos + size yytext)); + "^" => (Tokens.STRCAT (yypos, yypos + size yytext)); + + "~" => (Tokens.NEG (yypos, yypos + size yytext)); + "," => (Tokens.COMMA (yypos, yypos + size yytext)); + ":" => (Tokens.COLON (yypos, yypos + size yytext)); + "..." => (Tokens.DOTDOTDOT (yypos, yypos + 3)); + ".." => (Tokens.DOTDOT (yypos, yypos + 2)); + "." => (Tokens.DOT (yypos, yypos + 1)); + "_" => (Tokens.UNDER (yypos, yypos + 1)); + "#" => (Tokens.HASH (yypos, yypos + 1)); + ";" => (Tokens.SEMI (yypos, yypos + 1)); + "$" => (Tokens.DOLLAR (yypos, yypos + size yytext)); + "@" => (Tokens.AT (yypos, yypos + size yytext)); + + "if" => (Tokens.IF (yypos, yypos + 2)); + "else" => (Tokens.ELSE (yypos, yypos + 4)); + "foreach" => (Tokens.FOREACH (yypos, yypos + 7)); + "in" => (Tokens.IN (yypos, yypos + 2)); + "case" => (Tokens.CASE (yypos, yypos + 4)); + "as" => (Tokens.AS (yypos, yypos + 2)); + "with" => (Tokens.WITH (yypos, yypos + 4)); + "open" => (Tokens.OPEN (yypos, yypos + 4)); + "val" => (Tokens.VAL (yypos, yypos + 3)); + "ref" => (Tokens.REF (yypos, yypos + 3)); + "try" => (Tokens.TRY (yypos, yypos + 3)); + "catch" => (Tokens.CATCH (yypos, yypos + 5)); + "or" => (Tokens.ORELSE (yypos, yypos + 5)); + "and" => (Tokens.ANDALSO (yypos, yypos + 5)); + + "::" => (Tokens.CONS (yypos, yypos + 2)); + {id} => (Tokens.IDENT (yytext, yypos, yypos + size yytext)); + {intconst} => (case Int.fromString yytext of + SOME (x) => Tokens.INT (x, yypos, yypos + size yytext) + | NONE => (ErrorMsg.error (SOME (yypos, yypos)) + ("Expected number, received: " ^ yytext); + continue ())); + + "\"" {id} "\"" => (Tokens.STRING (String.substring(yytext, 1, String.size yytext - 2), yypos, yypos + size yytext)); + + . => (continue()); + + {bo} => (Tokens.HTML (yytext, yypos, yypos + size yytext)); + . => (Tokens.HTML (yytext, yypos, yypos + 1)); + + . => (ErrorMsg.error (SOME (yypos,yypos)) + ("illegal character: \"" ^ yytext ^ "\""); + continue ()); diff --git a/src/mlt.sig b/src/mlt.sig new file mode 100644 index 0000000..5af7b12 --- /dev/null +++ b/src/mlt.sig @@ -0,0 +1,28 @@ +(* + * Dynamic web page generation with Standard ML + * Copyright (C) 2003 Adam Chlipala + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + *) + +(* Translation of templates into SML source *) + +signature MLT = +sig + val trans : Config.config * StaticEnv.staticEnv * StringSet.set * string * Tree.block -> string + (* trans (config, env, templates, name, block) ==> + * SML source code corresponding to the block of code in template name, run in env with the given set of + * existent templates *) +end diff --git a/src/mlt.sml b/src/mlt.sml new file mode 100644 index 0000000..38848e7 --- /dev/null +++ b/src/mlt.sml @@ -0,0 +1,796 @@ +(* + * Dynamic web page generation with Standard ML + * Copyright (C) 2003 Adam Chlipala + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + *) + +(* Translation of templates into SML source *) + +structure Mlt :> MLT = +struct + open Tree + + exception Skip + + fun error (pos, msg) = (ErrorMsg.error pos msg; + raise Skip) + + type varid = int + + datatype var = VAR of Types.ty | REF of Types.ty + + val errorTy = Types.WILDCARDty + + val ppstream = PrettyPrint.mk_ppstream {consumer = TextIO.print, flush = fn () => TextIO.flushOut TextIO.stdOut, + linewidth = 80} + + (* States to thread throughout translation *) + local + datatype state = STATE of {env: StaticEnv.staticEnv, + vars : var StringMap.map, + config : Config.config, + templates : StringSet.set} + + datatype strct = STRCT of {elements: Modules.elements, + eenv: EntityEnv.entityEnv} + + fun getElements (Modules.SIG {elements, ...}) = elements + | getElements _ = raise Fail "Unexpected Signature in getElements" + + val bogusStamp = Stamps.special "" + val errorStrct = STRCT {elements = [], eenv = EntityEnv.empty} + in + fun mkState (config, env, templates) = + STATE {config = config, + env = env, + vars = StringMap.empty, + templates = templates} + + fun addVar (STATE {config, env, vars, templates}, v, ty) = + STATE {config = config, env = env, vars = StringMap.insert (vars, v, ty), templates = templates} + fun addVars (state, vars) = StringMap.foldli (fn (v, ty, state) => addVar (state, v, ty)) state vars + + fun getVar (STATE {vars, ...}, v, pos) = StringMap.find (vars, v) + fun lookVal (STATE {env, ...}, v, pos) = + (case StaticEnv.look (env, Symbol.varSymbol v) of + Bindings.VALbind var => + (case var of + VarCon.VALvar {typ, ...} => #1 (TypesUtil.instantiatePoly (!typ)) + | _ => raise Fail "Unexpected var in lookVal") + | Bindings.CONbind (Types.DATACON {typ, ...}) => #1 (TypesUtil.instantiatePoly typ) + | _ => raise Fail "Unexpected binding in lookVal") + handle StaticEnv.Unbound => (error (SOME pos, "Unbound variable " ^ v); + errorTy) + + fun lookCon' (STATE {env, ...}, v) = + (case StaticEnv.look (env, Symbol.varSymbol v) of + Bindings.CONbind (Types.DATACON {typ, ...}) => #1 (TypesUtil.instantiatePoly typ) + | _ => raise Fail "Unexpected binding in lookVal") + fun lookCon (env, v, pos) = (lookCon' (env, v)) + handle ModuleUtil.Unbound _ => (error (SOME pos, "Unbound constructor " ^ v); + errorTy) + fun lookStr (STATE {env, ...}, v, pos) = + (case StaticEnv.look (env, Symbol.strSymbol v) of + Bindings.STRbind modl => + (case modl of + Modules.STR {rlzn = {entities, ...}, sign, ...} => STRCT {elements = getElements sign, + eenv = entities} + | _=> raise Fail "Unexpected module in lookStr") + | _ => raise Fail "Unexpected binding in lookStr") + handle StaticEnv.Unbound => (error (SOME pos, "Unbound structure " ^ v); + errorStrct) + + fun getStr (STRCT {elements, eenv, ...}, v, pos) = + (case ModuleUtil.getStr (elements, eenv, Symbol.strSymbol v, Access.nullAcc, II.Null) of + (Modules.STR {rlzn = {entities, ...}, sign = Modules.SIG {elements, ...}, ...}, _) => + STRCT {elements = elements, eenv = entities} + | _ => raise Fail "Unexpected spec in getStr") + handle ModuleUtil.Unbound _ => (error (SOME pos, "Unbound structure " ^ v); + errorStrct) + fun getVal (STRCT {elements, ...}, v, pos) = + (case ModuleUtil.getSpec (elements, Symbol.varSymbol v) of + Modules.VALspec {spec, ...} => #1 (TypesUtil.instantiatePoly spec) + | _ => raise Fail "Unexpected spec in getVal") + handle ModuleUtil.Unbound _ => (case ModuleUtil.getSpec (elements, Symbol.tycSymbol v) of + Modules.CONspec {spec = Types.DATACON {typ, ...}, ...} => #1 (TypesUtil.instantiatePoly typ) + | _ => raise Fail "Unexpected spec in getVal") + handle ModuleUtil.Unbound _ => (error (SOME pos, "Unbound variable " ^ v); + errorTy) + fun getCon (STRCT {elements, ...}, v, pos) = + (case ModuleUtil.getSpec (elements, Symbol.varSymbol v) of + Modules.CONspec {spec = Types.DATACON {typ, ...}, ...} => #1 (TypesUtil.instantiatePoly typ) + | _ => raise Fail "Unexpected spec in getVal") + handle ModuleUtil.Unbound _ => (error (SOME pos, "Unbound constructor " ^ v); + errorTy) + + fun unify (STATE {env, ...}) (pos, t1, t2) = + (*let + val t1 = ModuleUtil.transType eenv t1 + val t2 = ModuleUtil.transType eenv t2 + in*) + Unify.unifyTy (t1, t2) + (*end*) + handle Unify.Unify msg => + (PrettyPrint.begin_block ppstream PrettyPrint.CONSISTENT 0; + PrettyPrint.add_string ppstream "Error unifying\n\t"; + PrettyPrint.add_break ppstream (0, 0); + PrettyPrint.begin_block ppstream PrettyPrint.CONSISTENT 5; + PPType.ppType env ppstream t1; + PrettyPrint.end_block ppstream; + PrettyPrint.add_break ppstream (0, 0); + PrettyPrint.add_string ppstream "\nand\n\t"; + PrettyPrint.add_break ppstream (0, 0); + PrettyPrint.begin_block ppstream PrettyPrint.CONSISTENT 5; + PPType.ppType env ppstream t2; + PrettyPrint.end_block ppstream; + PrettyPrint.add_string ppstream "\n"; + PrettyPrint.end_block ppstream; + PrettyPrint.flush_ppstream ppstream; + error (SOME pos, Unify.failMessage msg)) + + fun resolvePath (getter, transer) (pos, state, path) = + let + fun traverse ([], _, _) = raise Fail "Impossible empty variable path in pat traverse" + | traverse ([v], str as STRCT {eenv, ...}, path) = + let + val ty = getter (str, v, pos) + val ty = transer eenv ty + fun folder (STRCT {eenv, ...}, ty) = transer eenv ty + in + foldl folder ty path + end + | traverse (s::rest, str, path) = traverse (rest, getStr (str, s, pos), str::path) + in + case path of + [] => raise Fail "Empty path to resolvePath" + | [_] => raise Fail "Singleton path to resolvePath" + | (first::rest) => traverse (rest, lookStr (state, first, pos), []) + end + + fun resolveStructure (pos, state, path) = + let + fun look (STATE {env, ...}, v, pos) = + (case StaticEnv.look (env, Symbol.strSymbol v) of + Bindings.STRbind modl => + (case modl of + Modules.STR {rlzn = {entities, ...}, sign, ...} => (getElements sign, entities, modl) + | _=> raise Fail "Unexpected module in lookStr") + | _ => raise Fail "Unexpected binding in lookStr") + handle ModuleUtil.Unbound _ => (error (SOME pos, "Unbound structure " ^ v); + ([], EntityEnv.empty, Modules.ERRORstr)) + + fun get (elements, eenv, v) = + let + val sym = Symbol.strSymbol v + in + (case ModuleUtil.getStr (elements, eenv, sym, Access.nullAcc, II.Null) of + (str as Modules.STR {rlzn = {entities, ...}, sign = Modules.SIG {elements, ...}, ...}, _) => + (elements, entities, str) + | _ => raise Fail "Unexpected spec in resolveStructure") + handle ModuleUtil.Unbound _ => (error (SOME pos, "Unbound structure " ^ v); + ([], EntityEnv.empty, Modules.ERRORstr)) + end + + fun traverse ([], (_, _, str)) = str + | traverse ([v], (elements, eenv, _)) = #3 (get (elements, eenv, v)) + | traverse (s::rest, (elements, eenv, _)) = traverse (rest, get (elements, eenv, s)) + in + case path of + [] => raise Fail "Empty path to resolveStructure" + | (first::rest) => traverse (rest, look (state, first, pos)) + end + + fun openStructure (pos, state as STATE {config, env, vars, templates}, path) = + let + val str = resolveStructure (pos, state, path) + val env = ModuleUtil.openStructure (env, str) + in + STATE {config = config, env = env, vars = vars, templates = templates} + end + + fun tyToString (STATE {env, ...}) ty = + PrettyPrint.pp_to_string 65535 (PPType.ppType env) ty + + fun printFn (state as STATE {config, env, ...}) ty = + let + val tyname = tyToString state ty + in + Config.printFn config tyname + end + + fun isTemplate (STATE {templates, ...}) s = StringSet.member (templates, s) + end + + fun twiddleType f ty = + (case TypesUtil.headReduceType ty of + Types.WILDCARDty => ty + | _ => f ty) + + val domain = twiddleType BasicTypes.domain + val range = twiddleType BasicTypes.range + + (*val _ = (Unify.debugging := true; + EntityEnv.debugging := true; + ModuleUtil.debugging := true)*) + + fun newTyvar eq = Types.VARty (Types.mkTyvar (Types.OPEN {depth = 0, eq = eq, kind = Types.META})) + fun newFlex elms = Types.VARty (Types.mkTyvar (Types.OPEN {depth = 0, eq = false, kind = Types.FLEX elms})) + + val resolveVal = resolvePath (getVal, ModuleUtil.transType) + val resolveCon = resolvePath (getCon, ModuleUtil.transType) + + fun escapeString s = + let + val chars = String.explode s + val escd = map (fn #"\"" => "\\\"" + | #"\n" => "\\n" + | #"\r" => "" + | #"\t" => "\\t" + | x => str x) chars + in + String.concat escd + end + + val mkTuple = BasicTypes.tupleTy + + val templateTy = BasicTypes.--> (Types.CONty (BasicTypes.listTycon, + [mkTuple [BasicTypes.stringTy, + BasicTypes.stringTy]]), BasicTypes.unitTy) + + fun xexp state (EXP (e, pos)) = + (case e of + Int_e n => + (BasicTypes.intTy, Int.toString n) + | String_e s => + (BasicTypes.stringTy, "\"" ^ s ^ "\"") + | Char_e s => + (BasicTypes.charTy, "#\"" ^ s ^ "\"") + | Cons_e (e1, e2) => + let + val (ty1, es1) = xexp state e1 + val (ty2, es2) = xexp state e2 + + val parm = newTyvar false + val ran = Types.CONty (BasicTypes.listTycon, [parm]) + val dom = mkTuple [parm, ran] + + val xt = mkTuple [ty1, ty2] + in + unify state (pos, dom, xt); + (ran, "(" ^ es1 ^ ") :: (" ^ es2 ^ ")") + end + | StrCat_e (e1, e2) => + let + val (ty1, es1) = xexp state e1 + val (ty2, es2) = xexp state e2 + in + unify state (pos, ty1, BasicTypes.stringTy); + unify state (pos, ty2, BasicTypes.stringTy); + (BasicTypes.stringTy, "(" ^ es1 ^ ") ^ (" ^ es2 ^ ")") + end + | Orelse_e (e1, e2) => + let + val (ty1, es1) = xexp state e1 + val (ty2, es2) = xexp state e2 + in + unify state (pos, ty1, BasicTypes.boolTy); + unify state (pos, ty2, BasicTypes.boolTy); + (BasicTypes.boolTy, "(" ^ es1 ^ ") orelse (" ^ es2 ^ ")") + end + | Andalso_e (e1, e2) => + let + val (ty1, es1) = xexp state e1 + val (ty2, es2) = xexp state e2 + in + unify state (pos, ty1, BasicTypes.boolTy); + unify state (pos, ty2, BasicTypes.boolTy); + (BasicTypes.boolTy, "(" ^ es1 ^ ") andalso (" ^ es2 ^ ")") + end + | Plus_e (e1, e2) => + let + val (ty1, es1) = xexp state e1 + val (ty2, es2) = xexp state e2 + in + unify state (pos, ty1, BasicTypes.intTy); + unify state (pos, ty2, BasicTypes.intTy); + (BasicTypes.intTy, "(" ^ es1 ^ ") + (" ^ es2 ^ ")") + end + | Minus_e (e1, e2) => + let + val (ty1, es1) = xexp state e1 + val (ty2, es2) = xexp state e2 + in + unify state (pos, ty1, BasicTypes.intTy); + unify state (pos, ty2, BasicTypes.intTy); + (BasicTypes.intTy, "(" ^ es1 ^ ") - (" ^ es2 ^ ")") + end + | Times_e (e1, e2) => + let + val (ty1, es1) = xexp state e1 + val (ty2, es2) = xexp state e2 + in + unify state (pos, ty1, BasicTypes.intTy); + unify state (pos, ty2, BasicTypes.intTy); + (BasicTypes.intTy, "(" ^ es1 ^ ") * (" ^ es2 ^ ")") + end + | Divide_e (e1, e2) => + let + val (ty1, es1) = xexp state e1 + val (ty2, es2) = xexp state e2 + in + unify state (pos, ty1, BasicTypes.intTy); + unify state (pos, ty2, BasicTypes.intTy); + (BasicTypes.intTy, "(" ^ es1 ^ ") div (" ^ es2 ^ ")") + end + | Mod_e (e1, e2) => + let + val (ty1, es1) = xexp state e1 + val (ty2, es2) = xexp state e2 + in + unify state (pos, ty1, BasicTypes.intTy); + unify state (pos, ty2, BasicTypes.intTy); + (BasicTypes.intTy, "(" ^ es1 ^ ") mod (" ^ es2 ^ ")") + end + | Lt_e (e1, e2) => + let + val (ty1, es1) = xexp state e1 + val (ty2, es2) = xexp state e2 + in + unify state (pos, ty1, BasicTypes.intTy); + unify state (pos, ty2, BasicTypes.intTy); + (BasicTypes.boolTy, "(" ^ es1 ^ ") < (" ^ es2 ^ ")") + end + | Lte_e (e1, e2) => + let + val (ty1, es1) = xexp state e1 + val (ty2, es2) = xexp state e2 + in + unify state (pos, ty1, BasicTypes.intTy); + unify state (pos, ty2, BasicTypes.intTy); + (BasicTypes.boolTy, "(" ^ es1 ^ ") <= (" ^ es2 ^ ")") + end + | Gt_e (e1, e2) => + let + val (ty1, es1) = xexp state e1 + val (ty2, es2) = xexp state e2 + in + unify state (pos, ty1, BasicTypes.intTy); + unify state (pos, ty2, BasicTypes.intTy); + (BasicTypes.boolTy, "(" ^ es1 ^ ") > (" ^ es2 ^ ")") + end + | Gte_e (e1, e2) => + let + val (ty1, es1) = xexp state e1 + val (ty2, es2) = xexp state e2 + in + unify state (pos, ty1, BasicTypes.intTy); + unify state (pos, ty2, BasicTypes.intTy); + (BasicTypes.boolTy, "(" ^ es1 ^ ") >= (" ^ es2 ^ ")") + end + | Param_e => (BasicTypes.--> (BasicTypes.stringTy, BasicTypes.stringTy), "Web.getParam") + | Neg_e => (BasicTypes.--> (BasicTypes.intTy, BasicTypes.intTy), "~") + | Template_e name => + if isTemplate state name then + let + fun toUpper ch = chr (ord ch + ord #"A" - ord #"a") + val name = str (toUpper (String.sub (name, 0))) ^ String.extract (name, 1, NONE) + in + (templateTy, "(Web.withParams " ^ name ^ ".exec)") + end + else + (error (SOME pos, "Unknown template " ^ name); + (errorTy, "")) + | Proj_e field => + let + val carried = newTyvar false + in + (BasicTypes.--> (newFlex [(Symbol.labSymbol field, carried)], carried), "#" ^ field) + end + | Eq_e (e1, e2) => + let + val (ty1, s1) = xexp state e1 + val (ty2, s2) = xexp state e2 + in + unify state (pos, ty1, ty2); + unify state (pos, ty1, newTyvar true); + (BasicTypes.boolTy, "(" ^ s1 ^ ") = (" ^ s2 ^ ")") + end + | Neq_e (e1, e2) => + let + val (ty1, s1) = xexp state e1 + val (ty2, s2) = xexp state e2 + in + unify state (pos, ty1, ty2); + unify state (pos, ty1, newTyvar true); + (BasicTypes.boolTy, "(" ^ s1 ^ ") <> (" ^ s2 ^ ")") + end + | Ident_e [] => raise Fail "Impossible empty variable path" + | Ident_e [id] => + (case getVar (state, id, SOME pos) of + NONE => (lookVal (state, id, pos), id) + | SOME (VAR ty) => (ty, id) + | SOME (REF ty) => (ty, "!" ^ id)) + | Ident_e (path as (s::rest)) => + (resolveVal (pos, state, path), foldl (fn (v, st) => st ^ "." ^ v) s rest) + | App_e (f, x) => + let + val (ft, fs) = xexp state f + val (xt, xs) = xexp state x + + (*val (ft, _) = TypesUtil.instantiatePoly ft*) + val dom = domain ft + val ran = range ft + in + unify state (pos, dom, xt); + (ran, "(" ^ fs ^ ") (" ^ xs ^ ")") + end + | Record_e (ist, cs) => + let + val (cs, str) = foldl (fn ((id, e), (cs, str)) => + let + val idSym = Symbol.labSymbol id + val _ = List.all (fn (id', _) => idSym <> id') cs + orelse error (SOME pos, "Duplicate label " ^ id ^ " in record") + val (ty, s) = xexp state e + in + ((idSym, ty) :: cs, str ^ ", " ^ id ^ " = " ^ s) + end) ([], "") cs + val cs = rev cs + val str = + case str of + "" => str + | _ => String.extract(str, 2, NONE) + val str = "{" ^ str ^ "}" + in + (BasicTypes.recordTy cs, str) + end + | RecordUpd_e (e, cs) => + let + val (ty, es) = xexp state e + + val cs' = + case TypesUtil.headReduceType ty of + Types.CONty (Types.RECORDtyc labs, tys) => ListPair.zip (labs, tys) + | _ => error (SOME pos, "Record update on non-record") + + val (n, str) = foldl (fn ((id, ty), (n, str)) => + case List.find (fn (id', _) => id = Symbol.labSymbol id') cs of + NONE => (n, str ^ ", " ^ Symbol.name id ^ " = #" ^ + Symbol.name id ^ " " ^ "UPD'") + | SOME (_, e) => + let + val (ty', s) = xexp state e + in + unify state (pos, ty, ty'); + (n + 1, str ^ ", " ^ Symbol.name id ^ " = " ^ s) + end) (0, "") cs' + + val _ = n = length cs + orelse error (SOME pos, "Updated fields in record update not found in starting expression") + + val str = + case str of + "" => str + | _ => String.extract(str, 2, NONE) + val str = "let val UPD' = " ^ es ^ " in {" ^ str ^ "} end" + in + (ty, str) + end) + handle Skip => (errorTy, "") + + fun mergePatVars pos (vars1, vars2) = + StringMap.foldli (fn (v, ty, vars) => + (case StringMap.find (vars, v) of + NONE => StringMap.insert (vars, v, ty) + | SOME _ => error (SOME pos, "Duplicate variable " ^ v ^ " in pattern"))) vars1 vars2 + + fun xpat state (PAT (p, pos)) = + (case p of + Ident_p [] => raise Fail "Impossible empty Ident_p" + | Ident_p [id] => + ((lookCon' (state, id), StringMap.empty, id) + handle StaticEnv.Unbound => + let + val ty = newTyvar false + in + (ty, StringMap.insert (StringMap.empty, id, VAR ty), id) + end) + | Ident_p (path as (s::rest)) => + (resolveCon (pos, state, path), StringMap.empty, foldl (fn (v, st) => st ^ "." ^ v) s rest) + | Wild_p => (newTyvar false, StringMap.empty, "_") + | Int_p n => (BasicTypes.intTy, StringMap.empty, Int.toString n) + | String_p s => (BasicTypes.stringTy, StringMap.empty, "\"" ^ s ^ "\"") + | App_p ([], _) => raise Fail "Impossible App_p" + | App_p ([id], p) => + let + val (ty, vars, s) = xpat state p + val tyc = lookCon (state, id, pos) + val dom = domain tyc + in + unify state (pos, dom, ty); + (range tyc, vars, id ^ " (" ^ s ^ ")") + end + | App_p (path as (fst::rest), p) => + let + val (ty, vars, s) = xpat state p + val tyc = resolveCon (pos, state, path) + val dom = domain tyc + in + unify state (pos, dom, ty); + (range tyc, vars, foldl (fn (n, st) => st ^ "." ^ n) fst rest ^ " (" ^ s ^ ")") + end + | Cons_p (p1, p2) => + let + val (ty1, vars', s1) = xpat state p1 + val (ty2, vars'', s2) = xpat state p2 + + val resty = Types.CONty (BasicTypes.listTycon, [ty1]) + in + unify state (pos, ty2, resty); + (resty, mergePatVars pos (vars', vars''), "(" ^ s1 ^ ")::(" ^ s2 ^ ")") + end + | As_p (id, p) => + let + val (ty, vars, s) = xpat state p + in + not (Option.isSome (StringMap.find(vars, id))) + orelse error (SOME pos, "Duplicate variable " ^ id ^ " in pattern"); + (ty, StringMap.insert (vars, id, VAR ty), id ^ " as (" ^ s ^ ")") + end + | Record_p (ist, cs) => + let + val (cs, vars, str) = foldl (fn ((id, p), (cs, vars, str)) => + let + val (ty, vars', s) = xpat state p + in + ((Symbol.labSymbol id, ty)::cs, mergePatVars pos (vars, vars'), + str ^ ", " ^ id ^ " = " ^ s) + end) ([], StringMap.empty, "") cs + val cs = rev cs + val str = + if String.size str >= 2 then + String.extract(str, 2, NONE) + else + str + val str = "{" ^ str ^ "}" + in + (BasicTypes.recordTy cs, vars, str) + end + | FlexRecord_p cs => + let + val (cs, vars, str) = foldl (fn ((id, p), (cs, vars, str)) => + let + val (ty, vars', s) = xpat state p + in + ((Symbol.labSymbol id, ty)::cs, mergePatVars pos (vars, vars'), + str ^ ", " ^ id ^ " = " ^ s) + end) ([], StringMap.empty, "") cs + val cs = rev cs + val str = + if String.size str >= 2 then + String.extract(str, 2, NONE) + else + str + val str = "{" ^ str ^ ", ...}" + in + (newFlex cs, vars, str) + end + (*| _ => + error (SOME pos, "Not done yet!!!")*)) + handle Skip => (errorTy, StringMap.empty, "") + + fun xblock state (BLOCK (blocks, pos)) = + let + fun folder (BITEM (bi, pos), (state, str)) = + (case bi of + Html_i s => + (state, str ^ "val _ = Web.print (\"" ^ escapeString s ^ "\")\n") + | Ref_i rs => + let + fun folder ((id, e), (state, str)) = + let + val (ty, es) = xexp state e + + val state = addVar (state, id, REF ty) + in + (state, str ^ "val " ^ id ^ " = ref (" ^ es ^ ")\n") + end + in + foldl folder (state, str) rs + end + | Assn_i (id, e) => + let + val vty = + case getVar (state, id, SOME pos) of + NONE => error (SOME pos, "Unbound variable " ^ id) + | SOME (REF vty) => vty + | _ => error (SOME pos, "Can't assign to non-ref variable " ^ id) + + val (ty, es) = xexp state e + in + unify state (pos, ty, vty); + (state, str ^ "val _ = " ^ id ^ " := (" ^ es ^ ")\n") + end + | Val_i (p, e) => + let + val (pty, vars, ps) = xpat state p + val state' = addVars (state, vars) + val (ty, es) = xexp state e + in + unify state (pos, pty, ty); + (state', str ^ "val " ^ ps ^ " = (" ^ es ^ ")\n") + end + | Exp_i e => + let + val (ty, s) = xexp state e + val ty = TypesUtil.headReduceType ty + val printFn = + case printFn state ty of + NONE => (if tyToString state ty = "_" then + () + else + error (SOME pos, "Unable to convert value of type " ^ + tyToString state ty ^ " to string"); + "") + | SOME v => v + in + (state, str ^ "val _ = " ^ printFn ^ " (" ^ s ^ ")\n") + end + | Ifthenelse_i (ifs, els) => + let + val str = str ^ "val _ = " + fun folder ((e, b), (first, str)) = + let + val (ty, s) = xexp state e + val (_, str') = xblock state b + in + unify state (pos, ty, BasicTypes.boolTy); + (false, str ^ (if first then "" else "else ") ^ "if (" ^ s ^ ") then let\n" ^ + str' ^ + "in () end\n") + end + val (_, str) = foldl folder (true, str) ifs + val str = + case els of + NONE => + str ^ "else ()\n" + | SOME els => + let + val (_, str') = xblock state els + in + str ^ "else let\n" ^ + str' ^ + "in () end\n" + end + in + (state, str) + end + | Foreach_i (id, e, b) => + let + val parm = newTyvar false + + val (ty, es) = xexp state e + + val _ = unify state (pos, ty, Types.CONty (BasicTypes.listTycon, [parm])) + + (*val _ = print ("... to " ^ tyToString (context, ivmap, pty) ^ "\n")*) + + val state = addVar (state, id, VAR parm) + val (_, bs) = xblock state b + in + (state, str ^ "fun foreach (" ^ id ^ (*" : " ^ + Elab.tyToString (context, ivmap, pty) ^*) ") = let\n" ^ + bs ^ + "in () end\n" ^ + "val _ = app foreach (" ^ es ^ ")\n") + end + | For_i (id, eFrom, eTo, b) => + let + val (ty1, es1) = xexp state eFrom + val _ = unify state (pos, ty1, BasicTypes.intTy) + + val (ty2, es2) = xexp state eTo + val _ = unify state (pos, ty2, BasicTypes.intTy) + + val state = addVar (state, id, VAR BasicTypes.intTy) + val (_, bs) = xblock state b + in + (state, str ^ "fun forFunc " ^ id ^ " = let\n" ^ + bs ^ + "in () end\n" ^ + "val _ = for forFunc (" ^ es1 ^ ", " ^ es2 ^ ")\n") + end + | Case_i (e, matches) => + let + val (ty, s) = xexp state e + + fun folder ((p, b), (first, str)) = + let + val (pty, vars', ps) = xpat state p + + val _ = unify state (pos, ty, pty) + + val (_, str') = xblock (addVars (state, vars')) b + + (*val _ = print ("Pattern type: " ^ tyToString (context, ivmap, pty) ^ " vs. " ^ tyToString (context, ivmap, ty) ^ "\n")*) + in + (false, + str ^ (if first then " " else " | ") ^ "(" ^ ps ^ ") => let\n" ^ + str' ^ + "in () end\n") + end + val (_, str) = + foldl folder (true, str ^ "val _ = (case (" ^ s ^ ") of\n") matches + val str = str ^ ") handle Match => ()\n" + in + (state, str) + end + | TryCatch_i (b, matches) => + let + val (_, bs) = xblock state b + + fun folder ((p, b), (first, str)) = + let + val (pty, vars, ps) = xpat state p + val state = addVars (state, vars) + val (_, str') = xblock state b + in + unify state (pos, BasicTypes.exnTy, pty); + (false, + str ^ (if first then " " else " | ") ^ "(" ^ ps ^ ") => let\n" ^ + str' ^ + "in () end\n") + end + val (_, str) = + foldl folder (true, + str ^ "val _ = (let\n" ^ + bs ^ + "in () end handle\n") matches + val str = str ^ ")\n" + in + (state, str) + end + | Open_i paths => + let + fun folder (path, state) = openStructure (pos, state, path) + + val str = foldl (fn (path, str) => str ^ " " ^ Tree.pathString path) (str ^ "open") paths + val str = str ^ "\n" + in + (foldl folder state paths, str) + end) + handle Skip => (state, str) + in + foldl folder (state, "") blocks + end + + fun trans (config, env, templates, name, block) = + let + val state = mkState (config, env, templates) + val (_, str) = xblock state block + in + "(* This file generated automatically by something or other *)\n" ^ + "\n" ^ + "structure " ^ name ^ " :> TEMPLATE =\n" ^ + "struct\n" ^ + "fun exec () = let\n" ^ + str ^ + "in () end\n" ^ + "end\n" + end +end + + diff --git a/src/parse.sml b/src/parse.sml new file mode 100644 index 0000000..021bb64 --- /dev/null +++ b/src/parse.sml @@ -0,0 +1,49 @@ +(* + * Dynamic web page generation with Standard ML + * Copyright (C) 2003 Adam Chlipala + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + *) + +(* Template language parser *) + +signature PARSE = + sig + val parse : string -> Tree.block + end + +structure Parse :> PARSE = + struct + + structure MltLrVals = MltLrValsFn(structure Token = LrParser.Token) + structure Lex = MltLexFn(structure Tokens = MltLrVals.Tokens) + structure MltP = Join(structure ParserData = MltLrVals.ParserData + structure Lex = Lex + structure LrParser = LrParser) + + (* The main parsing routine *) + fun parse filename = + let val _ = (ErrorMsg.reset(); ErrorMsg.fileName := filename) + val file = TextIO.openIn filename + fun get _ = TextIO.input file + fun parseerror(s,p1,p2) = ErrorMsg.error (SOME (p1,p2)) s + val lexer = LrParser.Stream.streamify (Lex.makeLexer get) + val (absyn, _) = MltP.parse(30,lexer, parseerror, ()) + in + TextIO.closeIn file; + absyn + end + handle LrParser.ParseError => raise ErrorMsg.Error +end diff --git a/src/sources.cm b/src/sources.cm new file mode 100644 index 0000000..f59dcb2 --- /dev/null +++ b/src/sources.cm @@ -0,0 +1,53 @@ +(* + * Dynamic web page generation with Standard ML + * Copyright (C) 2003 Adam Chlipala + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + *) + +Library + structure Compiler + structure Main + structure Config +is + $/basis.cm + $/smlnj-lib.cm + $/ml-yacc-lib.cm + + $smlnj/compiler/current.cm + + string_map.sml + common.sml + + tree.sml + + mlt.lex + mlt.grm + errormsg.sml + parse.sml + + mlt.sig + mlt.sml + + config.sig + config.sml + compiler.sig + compiler.sml + + main.sml + + + + diff --git a/src/string_map.sml b/src/string_map.sml new file mode 100644 index 0000000..4746991 --- /dev/null +++ b/src/string_map.sml @@ -0,0 +1,27 @@ +(* + * Dynamic web page generation with Standard ML + * Copyright (C) 2003 Adam Chlipala + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + *) + +structure StringKey :> ORD_KEY where type ord_key = string = +struct + type ord_key = string + val compare = String.compare +end + +structure StringMap = BinaryMapFn(StringKey) +structure StringSet = BinarySetFn(StringKey) \ No newline at end of file diff --git a/src/tokens.sml b/src/tokens.sml new file mode 100644 index 0000000..cfd440b --- /dev/null +++ b/src/tokens.sml @@ -0,0 +1,33 @@ +(* + * Dynamic web page generation with Standard ML + * Copyright (C) 2003 Adam Chlipala + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + *) + +(* Tokens for mls template language *) + +structure Tokens = +struct + datatype token = + HTML of string + | BEGIN_CODE | END_CODE + | IF | THEN | ELSE + | FOREACH | CASE + | LPAREN | RPAREN | LBRACK | RBRACK | LBRACE | RBRACE + | PLUS | MINUS | TIMES | DIV | MOD + | EQ | NEQ | GT | GTE | LT | LTE + | ID of string | DOT | COMMA | COLON | CARET | TILDE +end diff --git a/src/tree.sml b/src/tree.sml new file mode 100644 index 0000000..05b84d6 --- /dev/null +++ b/src/tree.sml @@ -0,0 +1,114 @@ +(* + * Dynamic web page generation with Standard ML + * Copyright (C) 2003 Adam Chlipala + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + *) + +(* Template language abstract syntax trees *) + +structure Tree = +struct + open Common + + type ident = string + type path = ident list + + type 'a withext = 'a * (int * int) + + (* Pattern *) + datatype pat' = + Wild_p | Int_p of int | String_p of string + | Ident_p of path + | Record_p of bool * (ident * pat) list + | FlexRecord_p of (ident * pat) list + | App_p of path * pat | Cons_p of pat * pat + | As_p of ident * pat + and pat = PAT of pat' withext + + (* Expression *) + and exp' = + Int_e of int | String_e of string | Char_e of string | Ident_e of path + | Plus_e of exp * exp | Minus_e of exp * exp | Times_e of exp * exp + | Divide_e of exp * exp | Mod_e of exp * exp | Neg_e | Param_e + | Template_e of ident + | Orelse_e of exp * exp | Andalso_e of exp * exp + | StrCat_e of exp * exp + | Eq_e of exp * exp | Neq_e of exp * exp + | Gt_e of exp * exp | Gte_e of exp * exp + | Lt_e of exp * exp | Lte_e of exp * exp + | Cons_e of exp * exp + | Record_e of bool * (ident * exp) list + | RecordUpd_e of exp * (ident * exp) list + | Proj_e of ident | App_e of exp * exp + and exp = EXP of exp' withext + + and blockItem' = + Html_i of string (* literal HTML code to be sent *) + | Ref_i of (ident * exp) list (* define some new refs *) + | Val_i of pat * exp (* val binding *) + | Assn_i of ident * exp (* assignment to ref *) + | Exp_i of exp (* expression to be evaluated *) + | Open_i of path list (* imports to top level *) + | Ifthenelse_i of (exp * block) list * block option (* if statement *) + | Case_i of exp * (pat * block) list (* case statement *) + | Foreach_i of ident * exp * block (* foreach statement with list *) + | For_i of ident * exp * exp * block (* foreach statement with integer range *) + | TryCatch_i of block * (pat * block) list (* try...catch exception handlers w/ pattern matching *) + and blockItem = BITEM of blockItem' withext + (* Block of thingers to twiddle *) + and block = BLOCK of block' withext + withtype block' = blockItem list + and path = ident list + + fun unblock (BLOCK (x, _)) = x + fun unpat (PAT (x, _)) = x + fun unexp (EXP (x, _)) = x + + + fun expString (EXP (e, _)) = + (case e of + Int_e n => Int.toString n + | String_e s => "\"" ^ s ^ "\"" + | Ident_e [id] => id + | Ident_e [sn, id] => sn ^ "." ^ id + | Plus_e (e1, e2) => expString e1 ^ " + " ^ expString e2 + | Minus_e (e1, e2) => expString e1 ^ " - " ^ expString e2 + | Orelse_e (e1, e2) => expString e1 ^ " || " ^ expString e2 + | Andalso_e (e1, e2) => expString e1 ^ " && " ^ expString e2 + | Times_e (e1, e2) => expString e1 ^ " * " ^ expString e2 + | Divide_e (e1, e2) => expString e1 ^ " / " ^ expString e2 + | Mod_e (e1, e2) => expString e1 ^ " % " ^ expString e2 + | Eq_e (e1, e2) => expString e1 ^ " = " ^ expString e2 + | Neq_e (e1, e2) => expString e1 ^ " <> " ^ expString e2 + | Gt_e (e1, e2) => expString e1 ^ " > " ^ expString e2 + | Gte_e (e1, e2) => expString e1 ^ " >= " ^ expString e2 + | Lt_e (e1, e2) => expString e1 ^ " < " ^ expString e2 + | Lte_e (e1, e2) => expString e1 ^ " <= " ^ expString e2 + | Neg_e => "-" + | Param_e => "$" + | Template_e id => "@" ^ id + | Cons_e (e1, e2) => expString e1 ^ " :: " ^ expString e2 + | Record_e (true, elms) => foldl (fn ((_, e), s) => s ^ ", " ^ expString e) "(" elms ^ ")" + | Record_e (false, elms) => foldl (fn ((lab, e), s) => s ^ ", " ^ lab ^ " = " ^ expString e) "(" elms ^ ")" + | RecordUpd_e _ => "" + | Proj_e id => "#" ^ id + | App_e (e1, e2) => expString e1 ^ "(" ^ expString e2 ^ ")" + | _ => "") + + fun pathString [] = "" + | pathString [id] = id + | pathString (h::t) = h ^ "." ^ pathString t +end \ No newline at end of file