Showing posts with label Ruby. Show all posts
Showing posts with label Ruby. Show all posts

Monday, October 04, 2010

Techie Tidbits: Beef up the CMD Prompt

Are you a frequent Cygwin user and/or often ask yourself "Why is the CMD prompt so crap?!"? If so, you'll probably be interested to know how you can inject some or possibly all of that Linux/Bash goodness into your CMD prompt.
1st, Install Cygwin if you haven't already done so
2nd, Extend Your PATH
Create a bin (short for binary, but conventionally the home for anything executable) folder in your user directory, then add this directory to your PATH variable: Win+Pause > Advanced Settings > Environment Variables, probably best to add it to User variables for <You>
3rd, Create Your Associations
I've made an associations.cmd file in my personal bin directory with the following contents:
@echo off

assoc .sh=BashScript
ftype BashScript="C:\Cygwin\bin\env.exe" "CYGWIN=nodosfilewarning" "/bin/bash" -l "%%1" %%*

assoc .pl=PerlScript
ftype PerlScript="C:\Cygwin\bin\env.exe" "CYGWIN=nodosfilewarning" "/bin/perl" "%%1" %%*

assoc .py=PythonScript
ftype PythonScript="C:\Dev\Python\2.6(x86)\python.exe" "%%1" %%*

assoc .rb=RubyScript
ftype RubyScript="C:\Dev\Ruby\1.8.6\bin\ruby.exe" "%%1" %%*
Clearly I have Python and Ruby installed on Windows - if you don't omit the last and second to last command pairs. If you have installed the Perl package in Cygwin (which I recommend you do), then the second pair of commands wires that up. Now run this CMD file.
4th, Extend Your PATHEXT
Follow the instructions in step 2, but instead of changing the PATH variable, add the Bash, Python and Perl script file extensions (SH, PY and PL, respectively) to the semi-colon separated PATHEXT variable

This now allows you to run any Bash, Python or Perl script from anywhere on the CMD Prompt, JOY!

A Perl Example
Create prename.pl in your personal bin directory with the following contents:
#!/usr/bin/perl -w

$op = shift or die "Usage: rename expr [files]\n";
chomp(@ARGV = ) unless @ARGV;
for (@ARGV) {
    $was = $_;
    eval $op;
    die $@ if $@;
    rename($was,$_) unless $was eq $_;
}

Now if you have a file called file_123.txt and you wanted to rename it to file_abc.txt, you could run the following in a CMD Prompt:

prename "s,\d+,abc," file*

Tuesday, July 14, 2009

HOWTO: Configure Apache+Passenger with HTTPS/SSL

The following BASH commands assume you are in a root shell. It is quite convenient to switch using sudo -s; this should allow for plenty cut and paste action.
apt-get update
apt-get install -y ssh #... if like me you are working on a bare-bones VM
At this point I typically close my VM Server console (cause it's pants... until screw up my network and/or ssh config). I connect using keys from Cygwin; much more productive working this way.
apt-get install -y build-essential wget

Install Apache 2

apt-get -y install apache2 apache2-prefork-dev libreadline5-dev
cat > /etc/apache2/httpd.conf <<EOF
ServerName localhost
EOF

Install Enterprise Ruby (info) & Passenger

wget http://rubyforge.org/frs/download.php/58677/ruby-enterprise-1.8.6-20090610.tar.gz
tar -xzvf ruby-enterprise-1.8.6-20090610.tar.gz
./ruby-enterprise-1.8.6-20090610/installer <<EOF


EOF
/opt/ruby-enterprise-1.8.6-20090610/bin/gem install -y rails # specify version if necessary i.e. -v 2.1.0
cat > /etc/apache2/mods-available/passenger.load <<EOF
LoadModule passenger_module /opt/ruby-enterprise-1.8.6-20090610/lib/ruby/gems/1.8/gems/passenger-2.2.4/ext/apache2/mod_passenger.so
EOF

cat > /etc/apache2/mods-available/passenger.conf <<EOF
PassengerRoot /opt/ruby-enterprise-1.8.6-20090610/lib/ruby/gems/1.8/gems/passenger-2.2.4
PassengerRuby /opt/ruby-enterprise-1.8.6-20090610/bin/ruby
EOF
/opt/ruby-enterprise-1.8.6-20090610/bin/passenger-install-apache2-module <<EOF


EOF

Generate Certificate & Private Key

mkdir -p /etc/apache2/ssl/{crt,key}
openssl req -new -x509 -days 365 -keyout /etc/apache2/ssl/key/server.key -out /etc/apache2/ssl/crt/server.crt -nodes -subj '/O=Working With Mr.B, Ltd/OU=WWW Security Team/CN=workingwithmrb.blogspot.com'

Enable Apache Modules

a2enmod rewrite
a2enmod passenger
a2enmod ssl

Define & Install Virtual Host Rails

cat > /etc/apache2/sites-available/blog <<EOF
<VirtualHost *:80>
    ServerName workingwithmrb.blogspot.com
    DocumentRoot /var/www_rails/blog/current/public
    ErrorLog /var/www_rails/blog/current/log/apache.log

    <Location />
        RewriteEngine on
        RewriteCond %{HTTPS} off
        RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R]
    </Location>
</VirtualHost>

<VirtualHost *:443>
    ServerName workingwithmrb.blogspot.com
    DocumentRoot /var/www_rails/blog/current/public
    
    ErrorLog /var/www_rails/blog/current/log/apache-ssl.log

    SSLEngine On
    
    SSLProtocol -all +TLSv1 +SSLv3
    SSLCipherSuite HIGH:MEDIUM:!aNULL:+SHA1:+MD5:+HIGH:+MEDIUM
    
    SSLCertificateFile /etc/apache2/ssl/crt/server.crt
    SSLCertificateKeyFile /etc/apache2/ssl/key/server.key
    
    SSLVerifyClient optional
    SSLVerifyDepth 1
    
    SSLOptions +StdEnvVars +StrictRequire
    
    CustomLog /var/log/apache2/ssl_request_log "%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"
</VirtualHost>
EOF

a2ensite blog

Distinguish VirtualHosts Listening on Port 80 & 443

sed -i 's,VirtualHost \*,VirtualHost *:80,' /etc/apache2/sites-available/default
sed -i '/NameVirtualHost \*:80/ a NameVirtualHost *:443' /etc/apache2/sites-available/default

Give It A Spin

/etc/init.d/apache2 reload
netstat -napt
The output from netstat should show Apache listening on ports 80 and 443
Remember, if you install all this stuff as root, you must make sure that Apache+Passenger can access the rails application as www-data. Although it's a pretty stupid solution, you can achieve this by simply chmod -R o+rw <rails-app> in the parent directory. A better approach would be to create a user account e.g. called rails that belongs to the www-data group and with a umask of 0002, then anything to do with Rails you should do logged-in as that user.

Hope you find this simple and useful.

Friday, April 17, 2009

Darren on Ruby: Migrating Rails to Tomcat / JEE, Part 3: Using Warbler (Rack) to Deploy to Tomcat, Jetty or GlassFish

The Series So Far

Part 1: Switching to JRuby & Apache Derby showed you how to migrate from the Ruby+SQLite3 technology stack to JRuby+Derby.
Part 2: Migrating Your Data From SQLite3 to Derby showed you how to export your data out of your SQLite3 database and import that data into your new Apache Derby database.

Now I will take you through using Warbler to package your Rails app into a Web ARchive, ready for running on Tomcat, Jetty, Glassfish or whatever Servlet container you like.

Packaging Rails as a WAR

  1. Install Warbler:
    • jgem install warbler -y
  2. Configure Production Database:
    • Replace the production spec in RAILS_ROOT\config\database.yml with
      production:
        adapter: jdbc
        url: jdbc:derby:db\blog_ production;create=true
        driver: org.apache.derby.jdbc.EmbeddedDriver
        username: app
        password: app
      
  3. Satisfy Ruby Dependencies:
    • We need to make sure that all the Rails app's Ruby runtime dependencies are taken care of. We only need to worry about the dependencies that are required explicitly i.e. not provided transitively by Rails or Warbler. In our case it boils down to the JDBC/Derby stuff.
    • To specify the inclusion of these deps, we need to generate and modify the Warbler configuration; first run warble config, then edit the RAILS_ROOT\config\warble.rb file, replacing (or inserting after) this line
        # config.gems += ["activerecord-jdbcmysql-adapter", "jruby-openssl"]
      
      ...with this line
        config.gems += ["activerecord-jdbc-adapter", "activerecord-jdbcderby-adapter", "jdbc-derby", "jruby-openssl"]
      
  4. Satisfy Java Dependencies:
    • We need to make sure that all the Rails app's Java runtime dependencies are taken care of, that is, we must ensure the Derby jars will wind-up on the deployed applications CLASSPATH. Here are 3 ways to achieve this, in increasing scope:
      1. Copy derby.jar, derbyclient.jar and derbynet.jar in DERBY_HOME\lib to RAILS_ROOT\lib
      2. For Tomcat, copy these jars into TOMCAT_HOME\lib
      3. Copy them to JAVA_HOME\jre\lib\ext
      Taking the first option, Warbler will by default put these jars into WEB-INF\lib of the built WAR file.
  5. Rails 2.3.2 Session Management Issue:
    • We need to make few extra configuration changes due to an incompatibility with Warbler.
    • Uncomment the following line in RAILS_ROOT\config\initializers\session_store.rb
      # ActionController::Base.session_store = :active_record_store
      
    • Run the following commands to bring the database upto spec:
      jrake db:sessions:create RAILS_ENV=production
      jrake db:migrate RAILS_ENV=production
      
    • Now add the following line of code to the RAILS_ROOT\config\warble.rb file:
        config.webxml.jruby.session_store = 'db'
      
    • In RAILS_ROOT\config\environment.rb, just before
      Rails::Initializer.run do |config|
      
      ... add the following
      if defined?(JRUBY_VERSION)
        # hack to fix jruby-rack's incompatibility with rails edge
        module ActionController
          module Session
            class JavaServletStore
              def initialize(app, options={}); end
              def call(env); end
            end
          end
        end
      end
      
Now we should be good to go. Run warble which should produce blog.war. Now take this and drop it into TOMCAT_HOME\webapps. Restart Tomcat if it does not auto-deploy the application then navigate to your blog. This concludes this 3 part series on migrating from Ruby on Rails+SQLite3+WEBrick to JRuby on Rails+Derby+Tomcat. I hope through this blog I can spare you the pain I have gone through in figuring out how to get all this to work.

Epilogue

Next step for me is to get this procedure (of constructing the WAR file) mavenized. Maven handles WAR artifacts seemlessly; furthermore it knows how to 'overlay' WAR archives, reducing multiple WARs to one. This obviously simplifies the deployment and maintenance effort, a benefit I hope to reap in my current project that (now) produces three WAR achives. Good luck in your next steps. Cheers

Tuesday, April 14, 2009

Darren on Ruby: Migrating Rails to Tomcat / JEE, Part 2: Migrating Your Data From SQLite3 to Derby

The Series So Far

Part 1: Switching to JRuby & Apache Derby showed you how to migrate from the Ruby+SQLite3 technology stack to JRuby+Derby.

Now we will take a look at migrating the important stuff: your data. I found two ways to do a data migration: the easy way and the hard way. And unfortunately for me, I found the hard way first.

Update, 01/05/2009: You Don't Really Need to Migrate to Derby

You can continue to use SQLite3 if it so pleases you. You just need to install the necessary gems i.e. jdbc-adapter:
jgem install activerecord-jdbcsqlite3-adapter -y
The other thing is that it seems that SQLite3 allows you to use names for entities that are keywords in Derby e.g. min or max. Check here for a list of keywords used by Derby.

Do It The Easy Way, Do It The Ruby Way

To facilitate the easy way, we need to install the AR_Fixtures Rails plugin (not quite sure why this isn't a Gem, thus making it available to all Rails apps).
ruby script\plugin install http://topfunky.net/svn/plugins/ar_fixtures
This plugin gives us the db:fixtures:dump Rake task. As you'll see next it understands the MODEL and RAILS_ENV commandline/environment variables. It can't dump the entire database, strangely enough.

For this first step you need to go back to RAILS_ROOT\config\database.yml, disable (prepend an underscore) the jdbc development spec and re-enable the sqlite3 development spec. Then run the following commands:

rake db:fixtures:dump MODEL=Post
rake db:fixtures:dump MODEL=Comment
rake db:fixtures:dump MODEL=Tag
Take a look in RAILS_ROOT\test\fixtures; you should see posts.yml, comments.yml and tags.yml.

Now change you RAILS_ROOT\config\database.yml file to point to the jdbc development spec again, then run:

jrake db:migrate
jrake db:fixtures:load
You should now be good to go - start up your app using JRuby and test the blog data was migrated by going here.

Do It The Hard Way, Do It The Way I Did It When I Didn't Know The Easy Way

...Also The Way To Do It If Your Data Isn't Entirely Managed By ActiveRecord
  1. Export SQLite3 Data:
    • Run sqlite3 development.sqlite3 .dump >> development_dump.sql in RAILS_ROOT\db
  2. Tidy-up SQL Dump:
    • Open development_dump.sql in a text editor and make the following changes:
    • Remove any DDL or DML commands to do with the sqlite_sequence table
    • Remove any DDL or DML commands to do with the schema_migrations table, including the index
    • Unquote all table names e.g. change CREATE TABLE "posts" ... to CREATE TABLE posts ...
    • Replace AUTOINCREMENT NOT NULL with NOT NULL GENERATED BY DEFAULT AS IDENTITY
    • Replace datetime with timestamp
    • Replace integer\([0-9]*\) with integer
    • Replace text with long varchar
    • Replace DEFAULT ([0-9]*|NULL) NULL with DEFAULT NULL
    • Also be sure that any varchar(255) table columns only have that many characters, or else the import will complain and truncate your data (in this case, your precious blogs).
      If varchar(255) is not big enough, just switch it to long varchar
  3. Import into Derby:
    • Run ij (the Derby command-line client) in RAILS_ROOT\db
    • Run the following commands in ij:
      connect 'jdbc:derby:blog_development;create=true' as dev;
      run 'development_dump.sql';
      exit;
      

That should be it; you should have seen each model-table being created followed by the corresponding blog data going into Derby. You might see some 'Table already exists' errors when the DDL statements execute; these will occur if you previously ran jrake db:migrate, which creates the tables for you - just ignore them. Run the server again using JRuby and you should be able to access your blogs again.

What's Next?

Next I will step through the procedure to package your Rails application to a Web ARchive file, ready to deploy to Tomcat, Jetty or any JEE/Servlet container of your choice. You can catch that blog here

Cheers

Saturday, April 11, 2009

Darren on Ruby: Migrating Rails to Tomcat / JEE, Part 1: Switching to JRuby & Apache Derby

Prologue

Complete this tutorial as a prelude to this blog. This is less about you learning RoR, but more about giving you a convenient starting point to proceed. If you already have a project in mind that you want to migrate, make a copy and work with that. Note for Windows users: When you get to the point of installing the SQLite3 gem, use version 1.2.3 as at the time of this writing, it is the most recent version compatible with Windows; gem install sqlite3-ruby -v 1.2.3 -y. For your convenience, here are some links you might find useful while completing that tutorial: http://localhost:3000
http://localhost:3000/home/index

Run it on Ruby

So you should now be at a point where you can successfully run your application on Mongrel or WEBrick using MRI. If you haven't done that already, give that a whirl and test it by going here. You should see the 'Hello, Rails!' home page. Now get you hands on the default generated index.html file and put it back in the public folder and hit refresh/F5. You should now see the 'Welcome aboard... You’re riding Ruby on Rails!' welcome page. Click on the 'About your application’s environment' link and you should see a flash message (I think that's what they call it) describing you environment; you should observe two things:
Ruby Version
1.8.6 (i386-mswin32)
Database adapter
sqlite3
Now shut down the web server.

Prepare for JRuby

  1. Setup JRuby
    • Download and install JRuby 1.2.0 from here
    • Set your JRUBY_HOME environment variable and add JRUBY_HOME\bin to your PATH environment variable.
    • Checkout this blog for jgem and jrake
  2. Install Rails (currently 2.3.2)
    • jgem install rails -y
  3. Setup Apache Derby
    • Download and install Derby 10.4.2 from here.
    • Set your DERBY_HOME environment variable and add DERBY_HOME\bin to your PATH environment variable.
    • Copy derby.jar, derbyclient.jar and derbynet.jar in DERBY_HOME\lib to JRUBY_HOME\lib.
    • jgem install activerecord-jdbcderby-adapter-0.9.0 -y (I had an issue with version 0.9.1; something about an uninitialized constant...)
  4. Prepare Development DB
    • Update the RAILS_ROOT\config\database.yml file; comment out the default development database definition (or just prepend an underscore or something) and paste in the following below it:
      development:
        adapter: jdbc
        url: jdbc:derby:db\blog_development;create=true
        driver: org.apache.derby.jdbc.EmbeddedDriver
        username: app
        password: app
      
    • Run the following commands:
      jrake db:sessions:create
      jrake db:migrate
      

Run it on JRuby

Now you should be at a point where you can run your application on Mongrel or WEBrick using JRuby. Start it up, this time running jruby script\server and test it again by going here. Click on the 'About your application’s environment' link; this time you'll observe two significant differences:
Ruby Version
1.8.6 (java)
Database adapter
jdbc
Well that's all folks - You have now migrated to JRuby!. But where are all your blogs?!

What's Next?

Next I will run through a couple of ways of migrating your SQLite3 data to Derby; when it's ready you can catch that blog here. Cheers.

Tuesday, March 03, 2009

Darren on Flex: Typed Literals, Paving The Way For Truly Embedded DSLs

What are they and what do they have to do with embedded DSLs?

After undertaking several Fit(Library) framework development projects and listening to various speakers on DSLs at SPA2008 (DSLs clearly being the hype for 2008, or at least at that conference), I started thinking about what DSLs exist and what support we have for them and what support we have for new ones. We are all familiar with the concept of primitive types and String literals? Having a Java background, things don't get much simpler than that. Those who are now feeling the urge to say something like, "Language X does not have primitive types, everything is an object..." please, pipe down, it doesn't really matter. The important thing to note is that there are types of variable you can define a value for without using the new operator (switch the keyword, operator, construct to suit your language of choice).

String Literal Abuse...

Strings are used to express eeeevverything... well, almost everything: SQL statements, XML fragments/documents and Regular Expressions. Even regular language expressions are made executable by the infamous eval('<string-embedded-language-expressions>') method, where supported. There maybe more types expressable by strings but we will focus on these for now, but if you know of any other interesting cases, I'd be interested to learn of them.

... Invites String Literal Pain!

The pain suffered as result of abusing string literals often goes unnoticed and can be derived, in part, from the fact that they are commonly used to embed full-blown languages, as in the highlighted cases for SQL and XML. While coding in this manner i.e. string-embedding, a benefit of formal languages becomes less obvious; these languages have their own set of rules i.e. their formal grammar, that apply as a matter of well-formedness. In fact we completely loose the benefit (real, potential or otherwise) of the well-formedness of these formal languages. In other words, the earliest possible point in time that one can determine for sure that some embedded SQL is correct, or in fact wrong, is when your code hits reality i.e. at run-time. For some poor sods (or fools, depending on your p.o.v.), that could be when an livid customer is ranting and raving about some dodgy transaction that takes too long or doesn't yield the... or when some XML document that is spat out chokes some down stream system, which always has teh effect of upsetting a lot of people. Let's consider escaping: How annoying does it get when one arrives (worse, has to write) at a ridiculously long regular expression string, let's say in Java. There are so many meta-characters that are frequently used to control the semantics of a RegExp that are escaped with a '\' (backslash) and thus must be doubly escaped in Java. In particular managing the namespace overlap for Java (symbols and characters) strings and embedded RegExp (escape-sequences), none more troublesome than '\n', which means insert new-line and match new-line, respectively, where the former takes precedence thus breaking the latter. The comprehensibility of escaped backslashes can be argued i.e. you know you are writing Java so you know what '\\\\' means, but what I can almost guarantee is that as the number of escaped-backslashes increases the more likely you are to go boss-eyed, recount them n times and ultimatly write the wrong RegExp before getting it right.

Ruby's Enhanced String Notation

Just as an aside, while we are discussing the use of strings, Ruby is quite extraordinary w.r.t. to how one instantiates strings. I have read that Ruby in someways is designed to mimic the Linux shell e.g. in its creation of strings: ' (single-quote) strings are different to " (double-quote) strings. Like in the Linux shell, using the double-quote notation expands referenced varibles; one can inject values from locally (lexically) scoped variables in the literal string value using Ruby's # and {} notation when embebbed in double-quoted strings. For example:
a = 2
puts "the variable a = #{a}"
This yields The variable a = 2.
# ...
puts 'the variable a = #{a}'
And this yields The variable a = \#{a}. There will be plenty programmers out there that are familiar with C's printf()-family of procedures, where it has features in many post-C languages. String.printf() was introduced in Java 5, leveraging the introduction of varargs. I was once on a Python project too and grew extremely fond of the overloaded % String operator; coming from Java, I was quite blown away by that back then.

Using Strings Responsibly Might Mean Not Using Them At All

So it seems that some language authors have felt the pain and reacted appropriatly by introducing real types for these things that might otherwise be embedded in strings. Here are a few cases that I know about; if I've missed any, which I am sure I have, please let me know.

RegExp - JavaScript, ActionScript, Ruby, Python

The common syntax for these languages, with the exception of Python, is to use the '/' (forward-slash) as the RegExp delimiter, in exactly the same way single-quotes or double-quotes are used to delimit strings. Foe example:
/regular expression/
JavaScript and ActionScript behave almost the same (in my experience, correct me if I am wrong) which suggests to me this maybe a feature ECMAScript; I am not clued up on ECMAScript directly, so I can only speculate. By 'behave' I mean in reference to the flags you can specify to alter the way the RegExp processes the target string. For example:
/regular expression/gimsx;

XML Notation - ActionScript

ActionScript overloads the < and > operators to be used as XML delimiters(obvious choice, no?).
var tagname:String = "item"; 
var attributename:String = "id"; 
var attributevalue:String = "5"; 
var content:String = "Chicken"; 
var x:XML = <{tagname} {attributename}={attributevalue}>{content}</{tagname}>; 
trace(x.toXMLString())
    // Output: Chicken
This was borrowed from the Flex 3 Developer Guide. As you can see, you can reference variables inline to construct any part of the XML fragment.

Binary & Bit Notation - Erlang

Erlang has the tidiest notation for bits and bytes I've ever seen... excuse me if this a blatant show of ignorance:
Binary = <<98,105,110,97,114,121>>.
Each comma-separated value represents a byte and so must fall in the inclusive range 0-255. This example shows a 6-byte binary.
Binary = <<"binary">>.
This happens to be valid Erlang as the patterns match. This second example shows a 6-byte binary represented as a string (ironically) as all byte values represent printable ASCII character codes. The first example is matched as the values specified are the corresponding ASCII character codes for binary. I believe Erlang will prefer to display the string form when possible.
B = 98.
I = 105.
N = 110.
A = 97.
R = 114.
Y = 121.
Binary = <<B,I,N,A,R,Y>>.
Erlang also allows you to reference variables/constants/terms (whatever they are called in Erlang) inline as well. The bit notation is only a minor variation on this theme.
MangledBinary = <<B:4,I:4,N:4,A:4,R:4,Y:4>>.
The :4 says to take the 4 least significant bits, in this case chopping each byte in half, which incidentally still yields a printable binary, but now only 3-bytes long (<<")รก)">>)

So The Part Relevant to DSLs

LINQ-to-SQL - C#

C#'s LINQ-to-SQL, coupled with LINQ Expression (comprehension) syntax, is the closest thing I've seen to an embedded DSL that is strongly typed. That is, you can express a literal and assign it inline to a specialized type, relevant to its domain of use.
enum Food { Fruit, Veg }

var fruitAndVeg = {
    new { Type=Fruit, Name="Apple" },
    new { Type=Fruit, Name="Banana" },
    new { Type=Fruit, Name="Cherry" },
    new { Type=Veg, Name="Artichoke" },
    new { Type=Veg, Name="Asparagus" },
    new { Type=Veg, Name="Broccoli" },
    new { Type=Veg, Name="Carrot" }
};

from food in fruitAndVeg
where food.Type == Veg
where food.Name.StartsWith ("A")
select food.Name
This yields Artichoke and Asparagus. While this is not SQL-92 (nor does it actually link to SQL [read: database, although it can]), you can clearly see the resemblance and can therefore immediately identify the comprehension syntax as a query language.

Make the Tools Do The Work!

For those that appreciate type-safety (i.e. those that use [and like] strongly-type languages), compile-time support for these typed literals would come as standard. Typed literals would also permit enhanced IDE support: literal validation; syntax highlighting; code completion (if appropriate). These are not ideas of my own, rather a very brief account of my experience with Visual Studio and LINQ with its comprehension syntax. The problem is the implementation for this is quite involved and limited to querying IEnumerable type things. AFAIK, there is no general mechanism for providing such a feature, a feature which essentially allows you to extend the syntax of you embedding language e.g. C#. Many text editors provide a mechanism to specify information about your language, so that it can usefully provide syntax highlighting. However what we are getting at with typed literals goes beyond this and really needs to extend the compiler and/or the IDE; I envisage some sort of plugin, that either or both compiler and IDE can understand, which has some sort of Type -> Expression syntax mapping. But once we've done all this, how far away would we be from the effort to do all this using Bison, Flex, JavaCC, YACC or whatever other parser/compile-generator? I'm willing to bet it would be a similar effort, but what we gain by embedding/inlining, aside form the features and support that the IDE would typically provide, is:
  • The opportunity for value injection, as per Ruby strings and ActionScript XML fragments.
  • The opportunity to simplify tasks that are typically more painful or less compact in the main language e.g. C# and LINQ.
  • The oppurtunity to do all the above where you need it, in the code i.e. not in some external file, thus incurring no maintenance penalty.
Well, that's about all I have to say/muse on the subject. With closures and dynamic constructs becoming more popular, I wait to see what other developments materialise next in the language space. Cheers.