/src/org/rascalmpl/library/Prelude.java
Java | 3276 lines | 2864 code | 256 blank | 156 comment | 199 complexity | e246167e580352ac788e8e65641b2aef MD5 | raw file
Large files files are truncated, but you can click here to view the full file
- /*******************************************************************************
- * Copyright (c) 2009-2013 CWI
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * * Paul Klint - Paul.Klint@cwi.nl - CWI
- * * Jurgen J. Vinju - Jurgen.Vinju@cwi.nl - CWI
- * * Arnold Lankamp - Arnold.Lankamp@cwi.nl
- * * Davy Landman - Davy.Landman@cwi.nl
- * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI
- *******************************************************************************/
- /*******************************************************************************
- *
- * Warning this file is an experiment to determine the effect of collecting all
- * classes used by the Prelude in a single class. Overall effect seems to be circa 10%
- * reduction of import time.
- *
- * Do not edit/change this code, but use the original code instead.
- *
- */
- package org.rascalmpl.library;
- import java.io.BufferedInputStream;
- import java.io.BufferedReader;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.FileReader;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.io.OutputStream;
- import java.io.OutputStreamWriter;
- import java.io.PrintWriter;
- import java.io.Reader;
- import java.io.StringReader;
- import java.lang.ref.WeakReference;
- import java.math.BigInteger;
- import java.net.MalformedURLException;
- import java.nio.charset.Charset;
- import java.security.DigestInputStream;
- import java.security.MessageDigest;
- import java.security.NoSuchAlgorithmException;
- import java.text.ParseException;
- import java.util.Comparator;
- import java.util.HashMap;
- import java.util.HashSet;
- import java.util.Iterator;
- import java.util.LinkedList;
- import java.util.Locale;
- import java.util.Map;
- import java.util.Map.Entry;
- import java.util.PriorityQueue;
- import java.util.Random;
- import java.util.Set;
- import java.util.regex.Pattern;
- import org.apache.commons.lang.CharSetUtils;
- import org.apache.commons.lang.WordUtils;
- import org.eclipse.imp.pdb.facts.IBool;
- import org.eclipse.imp.pdb.facts.IConstructor;
- import org.eclipse.imp.pdb.facts.IDateTime;
- import org.eclipse.imp.pdb.facts.IInteger;
- import org.eclipse.imp.pdb.facts.IList;
- import org.eclipse.imp.pdb.facts.IListRelation;
- import org.eclipse.imp.pdb.facts.IListWriter;
- import org.eclipse.imp.pdb.facts.IMap;
- import org.eclipse.imp.pdb.facts.IMapWriter;
- import org.eclipse.imp.pdb.facts.INode;
- import org.eclipse.imp.pdb.facts.IRational;
- import org.eclipse.imp.pdb.facts.IRelation;
- import org.eclipse.imp.pdb.facts.IRelationWriter;
- import org.eclipse.imp.pdb.facts.ISet;
- import org.eclipse.imp.pdb.facts.ISetWriter;
- import org.eclipse.imp.pdb.facts.ISourceLocation;
- import org.eclipse.imp.pdb.facts.IString;
- import org.eclipse.imp.pdb.facts.ITuple;
- import org.eclipse.imp.pdb.facts.IValue;
- import org.eclipse.imp.pdb.facts.IValueFactory;
- import org.eclipse.imp.pdb.facts.exceptions.FactTypeUseException;
- import org.eclipse.imp.pdb.facts.io.ATermReader;
- import org.eclipse.imp.pdb.facts.io.BinaryValueReader;
- import org.eclipse.imp.pdb.facts.io.BinaryValueWriter;
- import org.eclipse.imp.pdb.facts.io.StandardTextReader;
- import org.eclipse.imp.pdb.facts.io.StandardTextWriter;
- import org.eclipse.imp.pdb.facts.type.Type;
- import org.eclipse.imp.pdb.facts.type.TypeFactory;
- import org.eclipse.imp.pdb.facts.type.TypeStore;
- import org.eclipse.imp.pdb.facts.visitors.VisitorException;
- import org.rascalmpl.interpreter.IEvaluatorContext;
- import org.rascalmpl.interpreter.TypeReifier;
- import org.rascalmpl.interpreter.asserts.ImplementationError;
- import org.rascalmpl.interpreter.control_exceptions.Throw;
- import org.rascalmpl.interpreter.result.ICallableValue;
- import org.rascalmpl.interpreter.staticErrors.UndeclaredNonTerminal;
- import org.rascalmpl.interpreter.types.FunctionType;
- import org.rascalmpl.interpreter.types.NonTerminalType;
- import org.rascalmpl.interpreter.types.ReifiedType;
- import org.rascalmpl.interpreter.utils.RuntimeExceptionFactory;
- import org.rascalmpl.parser.gtd.exception.ParseError;
- import org.rascalmpl.parser.gtd.exception.UndeclaredNonTerminalException;
- import org.rascalmpl.unicode.UnicodeDetector;
- import org.rascalmpl.unicode.UnicodeOutputStreamWriter;
- import org.rascalmpl.values.uptr.Factory;
- import org.rascalmpl.values.uptr.ProductionAdapter;
- import org.rascalmpl.values.uptr.SymbolAdapter;
- import org.rascalmpl.values.uptr.TreeAdapter;
- import org.rascalmpl.values.uptr.visitors.TreeVisitor;
- import com.ibm.icu.text.SimpleDateFormat;
- import com.ibm.icu.util.Calendar;
- import com.ibm.icu.util.TimeZone;
- import com.ibm.icu.util.ULocale;
- public class Prelude {
- private final TypeFactory types ;
- private final IValueFactory values;
- private final Random random;
-
- public Prelude(IValueFactory values){
- super();
-
- this.values = values;
- this.types = TypeFactory.getInstance();
- this.tr = new TypeReifier(values);
- random = new Random();
- }
- /* // Only here for test purposes:
- public IValue f1(IInteger x, IInteger y){
- return values.integer(x.intValue() + y.intValue());
- }
-
- public IValue f2(IInteger x, IList LS, IString y, IBool z){
- return values.string("x : " + x.intValue() + ", LS = " + LS + ", y ; " + y + ", z : " + z);
- }
- */
- /*
- * Boolean
- */
-
- public IValue arbBool() // get an arbitrary boolean value.}
- {
- return values.bool(random.nextInt(2) == 1);
- }
-
- /*
- * DateTime
- */
- public IValue now()
- //@doc{Get the current datetime.}
- {
- return values.datetime(Calendar.getInstance().getTimeInMillis());
- }
- public IValue createDate(IInteger year, IInteger month, IInteger day)
- //@doc{Create a new date.}
- {
- return values.date(year.intValue(), month.intValue(), day.intValue());
- }
-
- public IValue createTime(IInteger hour, IInteger minute, IInteger second,
- IInteger millisecond)
- //@doc{Create a new time.}
- {
- return values.time(hour.intValue(), minute.intValue(), second.intValue(), millisecond.intValue());
- }
- public IValue createTime(IInteger hour, IInteger minute, IInteger second,
- IInteger millisecond, IInteger timezoneHourOffset, IInteger timezoneMinuteOffset)
- //@doc{Create a new time with the given numeric timezone offset.}
- {
- return values.time(hour.intValue(), minute.intValue(), second.intValue(),
- millisecond.intValue(), timezoneHourOffset.intValue(), timezoneMinuteOffset.intValue());
- }
-
- public IValue createDateTime(IInteger year, IInteger month, IInteger day,
- IInteger hour, IInteger minute, IInteger second, IInteger millisecond)
- //@doc{Create a new datetime.}
- {
- return values.datetime(year.intValue(), month.intValue(), day.intValue(), hour.intValue(),
- minute.intValue(), second.intValue(), millisecond.intValue());
- }
- public IValue createDateTime(IInteger year, IInteger month, IInteger day,
- IInteger hour, IInteger minute, IInteger second, IInteger millisecond,
- IInteger timezoneHourOffset, IInteger timezoneMinuteOffset)
- //@doc{Create a new datetime with the given numeric timezone offset.}
- {
- return values.datetime(year.intValue(), month.intValue(), day.intValue(), hour.intValue(),
- minute.intValue(), second.intValue(), millisecond.intValue(), timezoneHourOffset.intValue(),
- timezoneMinuteOffset.intValue());
- }
-
- public IValue joinDateAndTime(IDateTime date, IDateTime time)
- //@doc{Create a new datetime by combining a date and a time.}
- {
- return values.datetime(date.getYear(), date.getMonthOfYear(), date.getDayOfMonth(),
- time.getHourOfDay(), time.getMinuteOfHour(), time.getSecondOfMinute(),
- time.getMillisecondsOfSecond(), time.getTimezoneOffsetHours(), time.getTimezoneOffsetMinutes());
- }
- public IValue splitDateTime(IDateTime dt)
- //@doc{Split an existing datetime into a tuple with the date and the time.}
- {
- return values.tuple(values.date(dt.getYear(), dt.getMonthOfYear(), dt.getDayOfMonth()),
- values.time(dt.getHourOfDay(), dt.getMinuteOfHour(), dt.getSecondOfMinute(),
- dt.getMillisecondsOfSecond(), dt.getTimezoneOffsetHours(), dt.getTimezoneOffsetMinutes()));
- }
-
-
- public IValue incrementYears(IDateTime dt, IInteger n)
- //@doc{Increment the years by a given amount.}
- {
- return incrementDate(dt, Calendar.YEAR, "years", n);
- }
-
- public IValue incrementMonths(IDateTime dt, IInteger n)
- //@doc{Increment the months by a given amount.}
- {
- return incrementDate(dt, Calendar.MONTH, "months", n);
- }
- public IValue incrementDays(IDateTime dt, IInteger n)
- //@doc{Increment the days by a given amount.}
- {
- return incrementDate(dt, Calendar.DAY_OF_MONTH, "days", n);
- }
- private String getTZString(int hourOffset, int minuteOffset) {
- String tzString = "GMT" +
- ((hourOffset < 0 || (0 == hourOffset && minuteOffset < 0)) ? "-" : "+") +
- String.format("%02d",hourOffset >= 0 ? hourOffset : hourOffset * -1) +
- String.format("%02d",minuteOffset >= 0 ? minuteOffset : minuteOffset * -1);
- return tzString;
- }
- private final int millisInAMinute = 1000 * 60;
- private final int millisInAnHour = millisInAMinute * 60;
- private IValue incrementDTField(IDateTime dt, int field, IInteger amount) {
- Calendar cal = null;
- cal = dateTimeToCalendar(dt);
-
- // Make sure lenient is true, since this allows wrapping of fields. For
- // instance, if you have $2012-05-15, and subtract 15 months, this is
- // an error if lenient is false, but gives $2012-02-15 (as expected)
- // if lenient is true.
- cal.setLenient(true);
- cal.add(field, amount.intValue());
- // Turn the calendar back into a date, time, or datetime value
- if (dt.isDate()) {
- return calendarToDate(cal);
- } else {
- if (dt.isTime()) {
- return calendarToTime(cal);
- } else {
- return calendarToDateTime(cal);
- }
- }
- }
- private IValue calendarToDateTime(Calendar cal) {
- int timezoneHours = cal.get(Calendar.ZONE_OFFSET) / millisInAnHour;
- int timezoneMinutes = cal.get(Calendar.ZONE_OFFSET) % millisInAnHour / millisInAMinute;
- return createDateTime(values.integer(cal.get(Calendar.YEAR)),
- values.integer(cal.get(Calendar.MONTH)+1),
- values.integer(cal.get(Calendar.DAY_OF_MONTH)),
- values.integer(cal.get(Calendar.HOUR_OF_DAY)),
- values.integer(cal.get(Calendar.MINUTE)),
- values.integer(cal.get(Calendar.SECOND)),
- values.integer(cal.get(Calendar.MILLISECOND)),
- values.integer(timezoneHours),
- values.integer(timezoneMinutes));
- }
- private IValue calendarToTime(Calendar cal) {
- int timezoneHours = cal.get(Calendar.ZONE_OFFSET) / millisInAnHour;
- int timezoneMinutes = cal.get(Calendar.ZONE_OFFSET) % millisInAnHour / millisInAMinute;
- return createTime(values.integer(cal.get(Calendar.HOUR_OF_DAY)),
- values.integer(cal.get(Calendar.MINUTE)),
- values.integer(cal.get(Calendar.SECOND)),
- values.integer(cal.get(Calendar.MILLISECOND)),
- values.integer(timezoneHours),
- values.integer(timezoneMinutes));
- }
- private IValue calendarToDate(Calendar cal) {
- return createDate(values.integer(cal.get(Calendar.YEAR)),
- values.integer(cal.get(Calendar.MONTH)+1),
- values.integer(cal.get(Calendar.DAY_OF_MONTH)));
- }
- private Calendar dateTimeToCalendar(IDateTime dt) {
- Calendar cal;
- if (dt.isDate()) {
- cal = Calendar.getInstance(TimeZone.getDefault(), Locale.getDefault());
- cal.set(dt.getYear(), dt.getMonthOfYear()-1, dt.getDayOfMonth());
- } else {
- cal = Calendar.getInstance(TimeZone.getTimeZone(getTZString(dt.getTimezoneOffsetHours(), dt.getTimezoneOffsetMinutes())),Locale.getDefault());
- if (dt.isTime()) {
- cal.set(1970, 0, 1, dt.getHourOfDay(), dt.getMinuteOfHour(), dt.getSecondOfMinute());
- } else {
- cal.set(dt.getYear(), dt.getMonthOfYear()-1, dt.getDayOfMonth(), dt.getHourOfDay(), dt.getMinuteOfHour(), dt.getSecondOfMinute());
- }
- cal.set(Calendar.MILLISECOND, dt.getMillisecondsOfSecond());
- }
- return cal;
- }
-
- private IValue incrementTime(IDateTime dt, int field, String fieldName, IInteger amount) {
- if (dt.isDate())
- throw RuntimeExceptionFactory.invalidUseOfDateException("Cannot increment the " + fieldName + " on a date value.", null, null);
-
- return incrementDTField(dt, field, amount);
- }
- private IValue incrementDate(IDateTime dt, int field, String fieldName, IInteger amount) {
- if (dt.isTime())
- throw RuntimeExceptionFactory.invalidUseOfDateException("Cannot increment the " + fieldName + " on a time value.", null, null);
-
- return incrementDTField(dt, field, amount);
- }
-
- public IValue incrementHours(IDateTime dt, IInteger n)
- //@doc{Increment the hours by a given amount.}
- {
- return incrementTime(dt, Calendar.HOUR_OF_DAY, "hours", n);
- }
- public IValue incrementMinutes(IDateTime dt, IInteger n)
- //@doc{Increment the minutes by a given amount.}
- {
- return incrementTime(dt, Calendar.MINUTE, "minutes", n);
- }
-
- public IValue incrementSeconds(IDateTime dt, IInteger n)
- //@doc{Increment the seconds by a given amount.}
- {
- return incrementTime(dt, Calendar.SECOND, "seconds", n);
- }
-
- public IValue incrementMilliseconds(IDateTime dt, IInteger n)
- //@doc{Increment the milliseconds by a given amount.}
- {
- return incrementTime(dt, Calendar.MILLISECOND, "milliseconds", n);
- }
- public IValue decrementYears(IDateTime dt, IInteger n)
- //@doc{Decrement the years by a given amount.}
- {
- return incrementDate(dt, Calendar.YEAR, "years", n.negate());
- }
- public IValue decrementMonths(IDateTime dt, IInteger n)
- //@doc{Decrement the months by a given amount.}
- {
- return incrementDate(dt, Calendar.MONTH, "months", n.negate()); }
- public IValue decrementDays(IDateTime dt, IInteger n)
- //@doc{Decrement the days by a given amount.}
- {
- return incrementDate(dt, Calendar.DAY_OF_MONTH, "days", n.negate());
- }
- public IValue decrementHours(IDateTime dt, IInteger n)
- //@doc{Decrement the hours by a given amount.}
- {
- return incrementTime(dt, Calendar.HOUR_OF_DAY, "hours", n.negate());
- }
- public IValue decrementMinutes(IDateTime dt, IInteger n)
- //@doc{Decrement the minutes by a given amount.}
- {
- return incrementTime(dt, Calendar.MINUTE, "minutes", n.negate());
- }
- public IValue decrementSeconds(IDateTime dt, IInteger n)
- //@doc{Decrement the seconds by a given amount.}
- {
- return incrementTime(dt, Calendar.SECOND, "seconds", n.negate());
- }
- public IValue decrementMilliseconds(IDateTime dt, IInteger n)
- //@doc{Decrement the milliseconds by a given amount.}
- {
- return incrementTime(dt, Calendar.MILLISECOND, "milliseconds", n.negate());
- }
- public IValue createDurationInternal(IDateTime dStart, IDateTime dEnd) {
- // dStart and dEnd both have to be dates, times, or datetimes
- Calendar startCal = Calendar.getInstance();
- startCal.setTimeInMillis(dStart.getInstant());
- Calendar endCal = Calendar.getInstance();
- endCal.setTimeInMillis(dEnd.getInstant());
-
- IValue duration = null;
- if (dStart.isDate()) {
- if (dEnd.isDate()) {
- duration = values.tuple(
- values.integer(startCal.fieldDifference(endCal.getTime(), Calendar.YEAR)),
- values.integer(startCal.fieldDifference(endCal.getTime(), Calendar.MONTH)),
- values.integer(startCal.fieldDifference(endCal.getTime(), Calendar.DAY_OF_MONTH)),
- values.integer(0), values.integer(0), values.integer(0),
- values.integer(0));
- } else if (dEnd.isTime()) {
- throw RuntimeExceptionFactory.invalidUseOfTimeException("Cannot determine the duration between a date with no time and a time with no date.", null, null);
- } else {
- throw RuntimeExceptionFactory.invalidUseOfDateTimeException("Cannot determine the duration between a date with no time and a datetime.", null, null);
- }
- } else if (dStart.isTime()) {
- if (dEnd.isTime()) {
- duration = values.tuple(
- values.integer(0),
- values.integer(0),
- values.integer(0),
- values.integer(startCal.fieldDifference(endCal.getTime(), Calendar.HOUR_OF_DAY)),
- values.integer(startCal.fieldDifference(endCal.getTime(), Calendar.MINUTE)),
- values.integer(startCal.fieldDifference(endCal.getTime(), Calendar.SECOND)),
- values.integer(startCal.fieldDifference(endCal.getTime(), Calendar.MILLISECOND)));
- } else if (dEnd.isDate()) {
- throw RuntimeExceptionFactory.invalidUseOfDateException("Cannot determine the duration between a time with no date and a date with no time.", null, null);
- } else {
- throw RuntimeExceptionFactory.invalidUseOfDateTimeException("Cannot determine the duration between a time with no date and a datetime.", null, null);
- }
- } else {
- if (dEnd.isDateTime()) {
- duration = values.tuple(
- values.integer(startCal.fieldDifference(endCal.getTime(), Calendar.YEAR)),
- values.integer(startCal.fieldDifference(endCal.getTime(), Calendar.MONTH)),
- values.integer(startCal.fieldDifference(endCal.getTime(), Calendar.DAY_OF_MONTH)),
- values.integer(startCal.fieldDifference(endCal.getTime(), Calendar.HOUR_OF_DAY)),
- values.integer(startCal.fieldDifference(endCal.getTime(), Calendar.MINUTE)),
- values.integer(startCal.fieldDifference(endCal.getTime(), Calendar.SECOND)),
- values.integer(startCal.fieldDifference(endCal.getTime(), Calendar.MILLISECOND)));
- } else if (dEnd.isDate()) {
- throw RuntimeExceptionFactory.invalidUseOfDateException("Cannot determine the duration between a datetime and a date with no time.", null, null);
- } else {
- throw RuntimeExceptionFactory.invalidUseOfTimeException("Cannot determine the duration between a datetime and a time with no date.", null, null);
- }
- }
- return duration;
- }
-
- public IValue parseDate(IString inputDate, IString formatString)
- //@doc{Parse an input date given as a string using the given format string}
- {
- try {
- java.text.SimpleDateFormat fmt = new java.text.SimpleDateFormat(formatString.getValue());
- fmt.parse(inputDate.getValue());
- java.util.Calendar cal = fmt.getCalendar();
- return values.date(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH) + 1, cal.get(Calendar.DATE));
- } catch (IllegalArgumentException iae) {
- throw RuntimeExceptionFactory.dateTimeParsingError("Cannot parse input date: " + inputDate.getValue() +
- " using format string: " + formatString.getValue(), null, null);
- } catch (ParseException e) {
- throw RuntimeExceptionFactory.dateTimeParsingError("Cannot parse input date: " + inputDate.getValue() +
- " using format string: " + formatString.getValue(), null, null);
- }
- }
-
- public IValue parseDateInLocale(IString inputDate, IString formatString, IString locale)
- //@doc{Parse an input date given as a string using a specific locale and format string}
- {
- try {
- java.text.SimpleDateFormat fmt = new java.text.SimpleDateFormat(formatString.getValue(), new Locale(locale.getValue()));
- fmt.parse(inputDate.getValue());
- java.util.Calendar cal = fmt.getCalendar();
- return values.date(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH) + 1, cal.get(Calendar.DATE));
- } catch (IllegalArgumentException iae) {
- throw RuntimeExceptionFactory.dateTimeParsingError("Cannot parse input date: " + inputDate.getValue() +
- " using format string: " + formatString.getValue() + " in locale: " + locale.getValue(), null, null);
- } catch (ParseException e) {
- throw RuntimeExceptionFactory.dateTimeParsingError("Cannot parse input date: " + inputDate.getValue() +
- " using format string: " + formatString.getValue() + " in locale: " + locale.getValue(), null, null);
- }
- }
- public IValue parseTime(IString inputTime, IString formatString)
- //@doc{Parse an input time given as a string using the given format string}
- {
- try {
- java.text.SimpleDateFormat fmt = new java.text.SimpleDateFormat(formatString.getValue());
- fmt.parse(inputTime.getValue());
- java.util.Calendar cal = fmt.getCalendar();
- // The value for zone offset comes back in milliseconds. The number of
- // hours is thus milliseconds / 1000 (to get to seconds) / 60 (to get to minutes)
- // / 60 (to get to hours). Minutes is this except for the last division,
- // but then we use mod 60 since this gives us total # of minutes, including
- // the hours we have already computed.
- int zoneHours = cal.get(Calendar.ZONE_OFFSET) / (1000 * 60 * 60);
- int zoneMinutes = (cal.get(Calendar.ZONE_OFFSET) / (1000 * 60)) % 60;
- return values.time(cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND), cal.get(Calendar.MILLISECOND), zoneHours, zoneMinutes);
- } catch (IllegalArgumentException iae) {
- throw RuntimeExceptionFactory.dateTimeParsingError("Cannot parse input date: " + inputTime.getValue() +
- " using format string: " + formatString.getValue(), null, null);
- } catch (ParseException e) {
- throw RuntimeExceptionFactory.dateTimeParsingError("Cannot parse input date: " + inputTime.getValue() +
- " using format string: " + formatString.getValue(), null, null);
- }
- }
-
- public IValue parseTimeInLocale(IString inputTime, IString formatString, IString locale)
- //@doc{Parse an input time given as a string using a specific locale and format string}
- {
- try {
- java.text.SimpleDateFormat fmt = new java.text.SimpleDateFormat(formatString.getValue(), new Locale(locale.getValue()));
- fmt.parse(inputTime.getValue());
- java.util.Calendar cal = fmt.getCalendar();
- // The value for zone offset comes back in milliseconds. The number of
- // hours is thus milliseconds / 1000 (to get to seconds) / 60 (to get to minutes)
- // / 60 (to get to hours). Minutes is this except for the last division,
- // but then we use mod 60 since this gives us total # of minutes, including
- // the hours we have already computed.
- int zoneHours = cal.get(Calendar.ZONE_OFFSET) / (1000 * 60 * 60);
- int zoneMinutes = (cal.get(Calendar.ZONE_OFFSET) / (1000 * 60)) % 60;
- return values.time(cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND), cal.get(Calendar.MILLISECOND), zoneHours, zoneMinutes);
- } catch (IllegalArgumentException iae) {
- throw RuntimeExceptionFactory.dateTimeParsingError("Cannot parse input time: " + inputTime.getValue() +
- " using format string: " + formatString.getValue() + " in locale: " + locale.getValue(), null, null);
- } catch (ParseException e) {
- throw RuntimeExceptionFactory.dateTimeParsingError("Cannot parse input time: " + inputTime.getValue() +
- " using format string: " + formatString.getValue() + " in locale: " + locale.getValue(), null, null);
- }
- }
- public IValue parseDateTime(IString inputDateTime, IString formatString)
- //@doc{Parse an input datetime given as a string using the given format string}
- {
- try {
- java.text.SimpleDateFormat fmt = new java.text.SimpleDateFormat(formatString.getValue());
- fmt.setLenient(false);
- fmt.parse(inputDateTime.getValue());
- java.util.Calendar cal = fmt.getCalendar();
- int zoneHours = cal.get(Calendar.ZONE_OFFSET) / (1000 * 60 * 60);
- int zoneMinutes = (cal.get(Calendar.ZONE_OFFSET) / (1000 * 60)) % 60;
- return values.datetime(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH) + 1, cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND), cal.get(Calendar.MILLISECOND), zoneHours, zoneMinutes);
- } catch (IllegalArgumentException iae) {
- throw RuntimeExceptionFactory.dateTimeParsingError("Cannot parse input datetime: " + inputDateTime.getValue() +
- " using format string: " + formatString.getValue(), null, null);
- } catch (ParseException e) {
- throw RuntimeExceptionFactory.dateTimeParsingError("Cannot parse input datetime: " + inputDateTime.getValue() +
- " using format string: " + formatString.getValue(), null, null);
- }
- }
-
- public IValue parseDateTimeInLocale(IString inputDateTime, IString formatString, IString locale)
- //@doc{Parse an input datetime given as a string using a specific locale and format string}
- {
- try {
- java.text.SimpleDateFormat fmt = new java.text.SimpleDateFormat(formatString.getValue(), new Locale(locale.getValue()));
- fmt.parse(inputDateTime.getValue());
- java.util.Calendar cal = fmt.getCalendar();
- int zoneHours = cal.get(Calendar.ZONE_OFFSET) / (1000 * 60 * 60);
- int zoneMinutes = (cal.get(Calendar.ZONE_OFFSET) / (1000 * 60)) % 60;
- return values.datetime(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH) + 1, cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND), cal.get(Calendar.MILLISECOND), zoneHours, zoneMinutes);
- } catch (IllegalArgumentException iae) {
- throw RuntimeExceptionFactory.dateTimeParsingError("Cannot parse input datetime: " + inputDateTime.getValue() +
- " using format string: " + formatString.getValue() + " in locale: " + locale.getValue(), null, null);
- } catch (ParseException e) {
- throw RuntimeExceptionFactory.dateTimeParsingError("Cannot parse input datetime: " + inputDateTime.getValue() +
- " using format string: " + formatString.getValue() + " in locale: " + locale.getValue(), null, null);
- }
- }
- private Calendar getCalendarForDate(IDateTime inputDate) {
- if (inputDate.isDate() || inputDate.isDateTime()) {
- Calendar cal = Calendar.getInstance(TimeZone.getDefault(),Locale.getDefault());
- cal.setLenient(false);
- cal.set(inputDate.getYear(), inputDate.getMonthOfYear()-1, inputDate.getDayOfMonth());
- return cal;
- } else {
- throw new IllegalArgumentException("Cannot get date for a datetime that only represents the time");
- }
- }
-
- private Calendar getCalendarForTime(IDateTime inputTime) {
- if (inputTime.isTime() || inputTime.isDateTime()) {
- Calendar cal = Calendar.getInstance(TimeZone.getTimeZone(getTZString(inputTime.getTimezoneOffsetHours(),inputTime.getTimezoneOffsetMinutes())),Locale.getDefault());
- cal.setLenient(false);
- cal.set(Calendar.HOUR_OF_DAY, inputTime.getHourOfDay());
- cal.set(Calendar.MINUTE, inputTime.getMinuteOfHour());
- cal.set(Calendar.SECOND, inputTime.getSecondOfMinute());
- cal.set(Calendar.MILLISECOND, inputTime.getMillisecondsOfSecond());
- return cal;
- } else {
- throw new IllegalArgumentException("Cannot get time for a datetime that only represents the date");
- }
- }
- private Calendar getCalendarForDateTime(IDateTime inputDateTime) {
- if (inputDateTime.isDateTime()) {
- Calendar cal = Calendar.getInstance(TimeZone.getTimeZone(getTZString(inputDateTime.getTimezoneOffsetHours(),inputDateTime.getTimezoneOffsetMinutes())),Locale.getDefault());
- cal.setLenient(false);
- cal.set(inputDateTime.getYear(), inputDateTime.getMonthOfYear()-1, inputDateTime.getDayOfMonth(), inputDateTime.getHourOfDay(), inputDateTime.getMinuteOfHour(), inputDateTime.getSecondOfMinute());
- cal.set(Calendar.MILLISECOND, inputDateTime.getMillisecondsOfSecond());
- return cal;
- } else {
- throw new IllegalArgumentException("Cannot get date and time for a datetime that only represents the date or the time");
- }
- }
- public IValue printDate(IDateTime inputDate, IString formatString)
- //@doc{Print an input date using the given format string}
- {
- try {
- SimpleDateFormat sd = new SimpleDateFormat(formatString.getValue());
- Calendar cal = getCalendarForDate(inputDate);
- sd.setCalendar(cal);
- return values.string(sd.format(cal.getTime()));
- } catch (IllegalArgumentException iae) {
- throw RuntimeExceptionFactory.dateTimePrintingError("Cannot print time with format " + formatString.getValue(), null, null);
- }
- }
- public IValue printDate(IDateTime inputDate)
- //@doc{Print an input date using a default format string}
- {
- SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
- Calendar cal = getCalendarForDate(inputDate);
- sd.setCalendar(cal);
- return values.string(sd.format(cal.getTime()));
- }
-
- public IValue printDateInLocale(IDateTime inputDate, IString formatString, IString locale)
- //@doc{Print an input date using a specific locale and format string}
- {
- try {
- SimpleDateFormat sd = new SimpleDateFormat(formatString.getValue(),new ULocale(locale.getValue()));
- Calendar cal = getCalendarForDate(inputDate);
- sd.setCalendar(cal);
- return values.string(sd.format(cal.getTime()));
- } catch (IllegalArgumentException iae) {
- throw RuntimeExceptionFactory.dateTimePrintingError("Cannot print time with format " + formatString.getValue() + ", in locale: " + locale.getValue(), null, null);
- }
- }
- public IValue printDateInLocale(IDateTime inputDate, IString locale)
- //@doc{Print an input date using a specific locale and a default format string}
- {
- try {
- SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd",new ULocale(locale.getValue()));
- Calendar cal = getCalendarForDate(inputDate);
- sd.setCalendar(cal);
- return values.string(sd.format(cal.getTime()));
- } catch (IllegalArgumentException iae) {
- throw RuntimeExceptionFactory.dateTimePrintingError("Cannot print time in locale: " + locale.getValue(), null, null);
- }
- }
- public IValue printTime(IDateTime inputTime, IString formatString)
- //@doc{Print an input time using the given format string}
- {
- try {
- SimpleDateFormat sd = new SimpleDateFormat(formatString.getValue());
- Calendar cal = getCalendarForTime(inputTime);
- sd.setCalendar(cal);
- return values.string(sd.format(cal.getTime()));
- } catch (IllegalArgumentException iae) {
- throw RuntimeExceptionFactory.dateTimePrintingError("Cannot print time with format: " + formatString.getValue(), null, null);
- }
- }
-
- public IValue printTime(IDateTime inputTime)
- //@doc{Print an input time using a default format string}
- {
- SimpleDateFormat sd = new SimpleDateFormat("HH:mm:ss.SSSZ");
- Calendar cal = getCalendarForTime(inputTime);
- sd.setCalendar(cal);
- return values.string(sd.format(cal.getTime()));
- }
-
- public IValue printTimeInLocale(IDateTime inputTime, IString formatString, IString locale)
- //@doc{Print an input time using a specific locale and format string}
- {
- try {
- SimpleDateFormat sd = new SimpleDateFormat(formatString.getValue(),new ULocale(locale.getValue()));
- Calendar cal = getCalendarForTime(inputTime);
- sd.setCalendar(cal);
- return values.string(sd.format(cal.getTime()));
- } catch (IllegalArgumentException iae) {
- throw RuntimeExceptionFactory.dateTimePrintingError("Cannot print time in locale: " + locale.getValue(), null, null);
- }
- }
- public IValue printTimeInLocale(IDateTime inputTime, IString locale)
- //@doc{Print an input time using a specific locale and a default format string}
- {
- try {
- SimpleDateFormat sd = new SimpleDateFormat("HH:mm:ss.SSSZ",new ULocale(locale.getValue()));
- Calendar cal = getCalendarForTime(inputTime);
- sd.setCalendar(cal);
- return values.string(sd.format(cal.getTime()));
- } catch (IllegalArgumentException iae) {
- throw RuntimeExceptionFactory.dateTimePrintingError("Cannot print time in locale: " + locale.getValue(), null, null);
- }
- }
- public IValue printDateTime(IDateTime inputDateTime, IString formatString)
- //@doc{Print an input datetime using the given format string}
- {
- try {
- SimpleDateFormat sd = new SimpleDateFormat(formatString.getValue());
- Calendar cal = getCalendarForDateTime(inputDateTime);
- sd.setCalendar(cal);
- return values.string(sd.format(cal.getTime()));
- } catch (IllegalArgumentException iae) {
- throw RuntimeExceptionFactory.dateTimePrintingError("Cannot print datetime using format string: " + formatString.getValue(), null, null);
- }
- }
- public IValue printDateTime(IDateTime inputDateTime)
- //@doc{Print an input datetime using a default format string}
- {
- SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSZ");
- Calendar cal = getCalendarForDateTime(inputDateTime);
- sd.setCalendar(cal);
- return values.string(sd.format(cal.getTime()));
- }
-
- public IValue printDateTimeInLocale(IDateTime inputDateTime, IString formatString, IString locale)
- //@doc{Print an input datetime using a specific locale and format string}
- {
- try {
- SimpleDateFormat sd = new SimpleDateFormat(formatString.getValue(),new ULocale(locale.getValue()));
- Calendar cal = getCalendarForDateTime(inputDateTime);
- sd.setCalendar(cal);
- return values.string(sd.format(cal.getTime()));
- } catch (IllegalArgumentException iae) {
- throw RuntimeExceptionFactory.dateTimePrintingError("Cannot print datetime using format string: " + formatString.getValue() +
- " in locale: " + locale.getValue(), null, null);
- }
- }
- public IValue printDateTimeInLocale(IDateTime inputDateTime, IString locale)
- //@doc{Print an input datetime using a specific locale and a default format string}
- {
- try {
- SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSZ",new ULocale(locale.getValue()));
- Calendar cal = getCalendarForDateTime(inputDateTime);
- sd.setCalendar(cal);
- return values.string(sd.format(cal.getTime()));
- } catch (IllegalArgumentException iae) {
- throw RuntimeExceptionFactory.dateTimePrintingError("Cannot print datetime in locale: " + locale.getValue(), null, null);
- }
- }
-
- /*
- * Graph
- */
-
- private HashMap<IValue,Distance> distance;
- private HashMap<IValue, IValue> pred;
- private HashSet<IValue> settled;
- private PriorityQueue<IValue> Q;
- private int MAXDISTANCE = 10000;
-
- private HashMap<IValue, LinkedList<IValue>> adjacencyList;
-
- private void buildAdjacencyListAndDistance(IRelation G){
- adjacencyList = new HashMap<IValue, LinkedList<IValue>> ();
- distance = new HashMap<IValue, Distance>();
-
- for(IValue v : G){
- ITuple tup = (ITuple) v;
- IValue from = tup.get(0);
- IValue to = tup.get(1);
-
- if(distance.get(from) == null)
- distance.put(from, new Distance(MAXDISTANCE));
- if(distance.get(to) == null)
- distance.put(to, new Distance(MAXDISTANCE));
-
- LinkedList<IValue> adjacencies = adjacencyList.get(from);
- if(adjacencies == null)
- adjacencies = new LinkedList<IValue>();
- adjacencies.add(to);
- adjacencyList.put(from, adjacencies);
- }
- }
-
- public IValue shortestPathPair(IRelation G, IValue From, IValue To){
- buildAdjacencyListAndDistance(G);
- distance.put(From, new Distance(0));
-
- pred = new HashMap<IValue, IValue>();
- settled = new HashSet<IValue>();
- Q = new PriorityQueue<IValue>(G.size(), new NodeComparator(distance));
- Q.add(From);
-
- while(!Q.isEmpty()){
- IValue u = Q.remove();
- if(u.isEqual(To))
- return extractPath(From, u);
- settled.add(u);
- relaxNeighbours(u);
- }
- return values.list();
- }
-
- private void relaxNeighbours(IValue u){
- LinkedList<IValue> adjacencies = adjacencyList.get(u);
- if(adjacencies != null) {
- for(IValue v : adjacencyList.get(u)){
- if(!settled.contains(v)){
- Distance dv = distance.get(v);
- Distance du = distance.get(u);
- if(dv.intval > du.intval + 1){ // 1 is default weight of each edge
- dv.intval = du.intval + 1;
- pred.put(v,u);
- Q.add(v);
- }
- }
- }
- }
- }
-
- private IList extractPath(IValue start, IValue u){
- Type listType = types.listType(start.getType());
- IListWriter w = listType.writer(values);
-
- if(!start.isEqual(u)){
- w.insert(u);
- while(!pred.get(u).isEqual(start)){
- u = pred.get(u);
- w.insert(u);
- }
- // TODO Check if a path was found at all; it could be that we just hit the root of the graph.
- }
- w.insert(start);
- return w.done();
- }
-
- public void print(IValue arg, IEvaluatorContext eval){
- PrintWriter currentOutStream = eval.getStdOut();
-
- try{
- if(arg.getType().isStringType()){
- currentOutStream.print(((IString) arg).getValue().toString());
- }
- else if(arg.getType().isSubtypeOf(Factory.Tree)){
- currentOutStream.print(TreeAdapter.yield((IConstructor) arg));
- }
- else if (arg.getType().isSubtypeOf(Factory.Type)) {
- currentOutStream.print(SymbolAdapter.toString((IConstructor) ((IConstructor) arg).get("symbol")));
- }
- else{
- currentOutStream.print(arg.toString());
- }
- }finally{
- currentOutStream.flush();
- }
- }
-
- public void iprint(IValue arg, IEvaluatorContext eval){
- StandardTextWriter w = new StandardTextWriter(true, 2);
-
- try {
- w.write(arg, eval.getStdOut());
- }
- catch (IOException e) {
- RuntimeExceptionFactory.io(values.string("Could not print indented value"), eval.getCurrentAST(), eval.getStackTrace());
- }
- finally{
- eval.getStdOut().flush();
- }
- }
-
- public void iprintln(IValue arg, IEvaluatorContext eval){
- StandardTextWriter w = new StandardTextWriter(true, 2);
-
- try {
- w.write(arg, eval.getStdOut());
- eval.getStdOut().println();
- }
- catch (IOException e) {
- RuntimeExceptionFactory.io(values.string("Could not print indented value"), eval.getCurrentAST(), eval.getStackTrace());
- }
- finally{
- eval.getStdOut().flush();
- }
- }
-
- public void println(IEvaluatorContext eval) {
- eval.getStdOut().println();
- eval.getStdOut().flush();
- }
-
- public void println(IValue arg, IEvaluatorContext eval){
- PrintWriter currentOutStream = eval.getStdOut();
-
- try{
- if(arg.getType().isStringType()){
- currentOutStream.print(((IString) arg).getValue());
- }
- else if(arg.getType().isSubtypeOf(Factory.Tree)){
- currentOutStream.print(TreeAdapter.yield((IConstructor) arg));
- }
- else if (arg.getType().isSubtypeOf(Factory.Type)) {
- currentOutStream.print(SymbolAdapter.toString((IConstructor) ((IConstructor) arg).get("symbol")));
- }
- else{
- currentOutStream.print(arg.toString());
- }
- currentOutStream.println();
- }finally{
- currentOutStream.flush();
- }
- }
-
- public void rprintln(IValue arg, IEvaluatorContext eval){
- PrintWriter currentOutStream = eval.getStdOut();
-
- try{
- currentOutStream.print(arg.toString());
- currentOutStream.println();
- }finally{
- currentOutStream.flush();
- }
- }
-
- public void rprint(IValue arg, IEvaluatorContext eval){
- PrintWriter currentOutStream = eval.getStdOut();
-
- try{
- currentOutStream.print(arg.toString());
- }finally{
- currentOutStream.flush();
- }
- }
- @Deprecated
- public IValue readFile(IString filename){
- IListWriter w = types.listType(types.stringType()).writer(values);
-
- BufferedReader in = null;
- try{
- in = new BufferedReader(new FileReader(filename.getValue()));
- java.lang.String line;
- do {
- line = in.readLine();
- if(line != null){
- w.append(values.string(line));
- }
- } while (line != null);
- }catch(FileNotFoundException fnfex){
- throw RuntimeExceptionFactory.pathNotFound(values.sourceLocation(filename.getValue()), null, null);
- }catch(IOException ioex){
- throw RuntimeExceptionFactory.io(values.string(ioex.getMessage()), null, null);
- }finally{
- if(in != null){
- try{
- in.close();
- }catch(IOException ioex){
- throw RuntimeExceptionFactory.io(values.string(ioex.getMessage()), null, null);
- }
- }
- }
- return w.done();
- }
-
- public IValue exists(ISourceLocation sloc, IEvaluatorContext ctx) {
- return values.bool(ctx.getResolverRegistry().exists(sloc.getURI()));
- }
-
- public IValue lastModified(ISourceLocation sloc, IEvaluatorContext ctx) {
- try {
- return values.datetime(ctx.getResolverRegistry().lastModified(sloc.getURI()));
- } catch(FileNotFoundException e){
- throw RuntimeExceptionFactory.pathNotFound(sloc, null, null);
- }
- catch (IOException e) {
- throw RuntimeExceptionFactory.io(values.string(e.getMessage()), ctx.getCurrentAST(), ctx.getStackTrace());
- }
- }
-
- public IValue isDirectory(ISourceLocation sloc, IEvaluatorContext ctx) {
- return values.bool(ctx.getResolverRegistry().isDirectory(sloc.getURI()));
- }
-
- public IValue isFile(ISourceLocation sloc, IEvaluatorContext ctx) {
- return values.bool(ctx.getResolverRegistry().isFile(sloc.getURI()));
- }
-
- public void mkDirectory(ISourceLocation sloc, IEvaluatorContext ctx) throws IOException {
- ctx.getResolverRegistry().mkDirectory(sloc.getURI());
- }
-
- public IValue listEntries(ISourceLocation sloc, IEvaluatorContext ctx) {
- try {
- java.lang.String [] entries = ctx.getResolverRegistry().listEntries(sloc.getURI());
- IListWriter w = values.listWriter(types.stringType());
- for(java.lang.String entry : entries){
- w.append(values.string(entry));
- }
- return w.done();
- } catch(FileNotFoundException e){
- throw RuntimeExceptionFactory.pathNotFound(sloc, ctx.getCurrentAST(), null);
- } catch (IOException e) {
- throw RuntimeExceptionFactory.io(values.string(e.getMessage()), ctx.getCurrentAST(), ctx.getStackTrace());
- }
- }
-
- public ISet charsets() {
- ISetWriter w = values.setWriter();
- for (String s : Charset.availableCharsets().keySet()) {
- w.insert(values.string(s));
- }
- return w.done();
- }
-
- public IValue readFile(ISourceLocation sloc, IEvaluatorContext ctx){
- try {
- Charset c = ctx.getResolverRegistry().getCharset(sloc.getURI());
- if (c != null)
- return readFileEnc(sloc, values.string(c.name()), ctx);
- return consumeInputStream(sloc, ctx.getResolverRegistry().getCharacterReader(sloc.getURI()), ctx);
- } catch(FileNotFoundException e){
- throw RuntimeExceptionFactory.pathNotFound(sloc, ctx.getCurrentAST(), null);
- }
- catch (IOException e) {
- throw RuntimeExceptionFactory.io(values.string(e.getMessage()), null, null);
- }
- }
-
- public IValue readFileEnc(ISourceLocation sloc, IString charset, IEvaluatorContext ctx){
- try {
- return consumeInputStream(sloc, ctx.getResolverRegistry().getCharacterReader(sloc.getURI(), charset.getValue()), ctx);
- } catch(FileNotFoundException e){
- throw RuntimeExceptionFactory.pathNotFound(sloc, ctx.getCurrentAST(), null);
- } catch (IOException e) {
- throw RuntimeExceptionFactory.io(values.string(e.getMessage()), null, null);
- }
- }
- private IValue consumeInputStream(ISourceLocation sloc, Reader in, IEvaluatorContext ctx) {
- StringBuilder result = new StringBuilder(1024 * 1024);
- try{
- char[] buf = new char[4096];
- int count;
- while((count = in.read(buf)) != -1) {
- result.append(new java.lang.String(buf, 0, count));
- }
-
- java.lang.String str = result.toString();
-
- if(sloc.hasOffsetLength() && sloc.getOffset() != -1){
- str = str.substring(sloc.getOffset(), sloc.getOffset() + sloc.getLength());
- }
-
- return values.string(str);
- }catch(FileNotFoundException fnfex){
- throw RuntimeExceptionFactory.pathNotFound(sloc, ctx.getCurrentAST(), null);
- }catch(IOException ioex){
- throw RuntimeExceptionFactory.io(values.string(ioex.getMessage()), ctx.getCurrentAST(), null);
- }finally{
- if(in != null){
- try{
- in.close();
- }catch(IOException ioex){
- throw RuntimeExceptionFactory.io(values.string(ioex.getMessage()), ctx.getCurrentAST(), null);
- }
- }
- }
- }
-
- public IValue md5HashFile(ISourceLocation sloc, IEvaluatorContext ctx){
- StringBuilder result = new StringBuilder(1024 * 1024);
-
- InputStream in = null;
- try{
- in = ctx.getResolverRegistry().getInputStream(sloc.getURI());
- MessageDigest md = MessageDigest.getInstance("MD5");
- in = new DigestInputStream(in, md);
- byte[] buf = new byte[4096];
- int count;
- while((count = in.read(buf)) != -1){
- result.append(new java.lang.String(buf, 0, count));
- }
-
- return values.string(new String(md.digest()));
- }catch(FileNotFoundException fnfex){
- throw RuntimeExceptionFactory.pathNotFound(sloc, ctx.getCurrentAST(), null);
- }catch(IOException ioex){
- throw RuntimeExceptionFactory.io(values.string(ioex.getMessage()), ctx.getCurrentAST(), null);
- } catch (NoSuchAlgorithmException e) {
- throw RuntimeExceptionFactory.io(values.string("Cannot load MD5 digest algorithm"), ctx.getCurrentAST(), null);
- }finally{
- if(in != null){
- try{
- in.close();
- }catch(IOException ioex){
- throw RuntimeExceptionFactory.io(values.string(ioex.getMessage()), ctx.getCurrentAST(), null);
- }
- }
- }
- }
- public void writeFile(ISourceLocation sloc, IList V, IEvaluatorContext ctx) {
- writeFile(sloc, V, false, ctx);
- }
-
- public void writeFileEnc(ISourceLocation sloc, IString charset, IList V, IEvaluatorContext ctx) {
- writeFileEnc(sloc, charset, V, false, ctx);
- }
-
- private void writeFile(ISourceLocation sloc, IList V, boolean append, IEvaluatorContext ctx){
- IString charset = values.string("UTF8");
- if (append) {
- // in case the file already has a encoding, we have to correctly append that.
- InputStream in = null;
- Charset detected = null;
- try {
- detected = ctx.getResolverRegistry().getCharset(sloc.getURI());
- if (detected == null) {
- in = ctx.getResolverRegistry().getInputStream(sloc.getURI());
- detected = UnicodeDetector.estimateCharset(in);
- }
- }catch(FileNotFoundException fnfex){
- throw RuntimeExceptionFactory.pathNotFound(sloc, ctx.getCurrentAST(), null);
- } catch (IOException e) {
- throw RuntimeExceptionFactory.io(values.string(e.getMessage()), ctx.getCurrentAST(), null);
- }
- finally {
- if (in != null) {
- try {
- in.close();
- } catch (IOException e) {
- throw RuntimeExceptionFactory.io(values.string(e.getMessage()), ctx.getCurrentAST(), null);
- }
- }
- }
- if (detected != null)
- charset = values.string(detected.name());
- else {
- charset = values.string(Charset.defaultCharset().name());
- }
- }
- writeFileEnc(sloc, charset, V, append, ctx);
- }
-
- public IBool canEncode(IString charset) {
- return values.bool(Charset.forName(charset.getValue()).canEncode());
- }
-
- private void writeFileEnc(ISourceLocation sloc, IString charset, IList V, boolean append, IEvaluatorContext ctx){
- OutputStreamWriter out = null;
-
- if (!Charset.forName(charset.getValue()).canEncode()) {
- throw RuntimeExceptionFactory.illegalArgument(charset, null, null);
- }
-
- try{
- out = new UnicodeOutputStreamWriter(ctx.getResolverRegistry().getOutputStream(sloc.getURI(), append), charset.getValue(), append);
-
- for(IValue elem : V){
- if (elem.getType().isStringType()) {
- out.append(((IString) elem).getValue());
- }else if (elem.getType().isSubtypeOf(Factory.Tree)) {
- out.append(TreeAdapter.yield((IConstructor) elem));
- }else{
- out.append(elem.toString());
- }
- }
- }catch(FileNotFoundException fnfex){
- throw RuntimeExceptionFactory.pathNotFound(sloc, ctx.getCurrentAST(), null);
- }catch(IOException ioex){
- throw RuntimeExceptionFactory.io(values.string(ioex.getMessage()), ctx.getCurrentAST(), null);
- }finally{
- if(out != null){
- try{
- out.close();
- }catch(IOException ioex){
- throw RuntimeExceptionFactory.io(values.string(ioex.getMessage()), ctx.getCurrentAST(), null);
- }
- }
- }
- return;
- }
-
- public void appendToFile(ISourceLocation sloc, IList V, IEvaluatorContext ctx){
- writeFile(sloc, V, true, ctx);
- }
- public void appendToFileEnc(ISourceLocation sloc, IString charset, IList V, IEvaluatorContext ctx){
- writeFileEnc(sloc, charset, V, true, ctx);
- }
-
- public IList readFileLines(ISourceLocation sloc, IEvaluatorContext ctx){
- try {
- Charset detected = ctx.getResolverRegistry().getCharset(sloc.getURI());
- if (detected != null)
- return readFileLinesEnc(sloc, values.string(detected.name()), ctx);
- return consumeInputStreamLines(sloc, ctx.getResolverRegistry().getCharacterReader(sloc.getURI()), ctx);
- }catch(MalformedURLException e){
- throw RuntimeExceptionFactory.malformedURI(sloc.toString(), null, null);
- }catch(FileNotFoundException e){
- throw RuntimeExceptionFactory.pathNotFound(sloc, ctx.getCurrentAST(), null);
- }catch(IOException e){
- throw RuntimeExceptionFactory.io(values.string(e.getMessage()), ctx.getCurrentAST(), null);
- }
- }
-
- public IList readFileLinesEnc(ISourceLocation sloc, IString charset, IEvaluatorContext ctx){
- try {
- return consumeInputStreamLines(sloc, ctx.getResolverRegistry().getCharacterReader(sloc.getURI(),charset.getValue()), ctx);
- }catch(MalformedURLException e){
- throw RuntimeExceptionFactory.malformedURI(sloc.toString(), null, null);
- }catch(FileNotFoundException e){
- throw RuntimeExceptionFactory.pathNotFound(sloc, ctx.getCurrentAST(), null);
- }catch(IOException e){
- throw RuntimeExceptionFactory.io(values.string(e.getMessage()), ctx.getCurrentAST(), null);
- }
- }
- private IList consumeInputStreamLines(ISourceLocation sloc, Reader stream, IEvaluatorContext ctx ) {
- IListWriter w = types.listType(types.stringType()).writer(values);
-
- BufferedReader in = null;
- try{
- in = new BufferedReader(stream);
- java.lang.String line;
-
- int i = 0;
- // int offset = sloc.getOffset();
- int beginLine = sloc.hasLineColumn() ? sloc.getBeginLine() : -1;
- int beginColumn = sloc.hasLineColumn() ? sloc.getBeginColumn() : -1;
- int endLine = sloc.hasLineColumn() ? sloc.getEndLine() : -1;
- int endColumn = sloc.hasLineColumn() ? sloc.getEndColumn() : -1;
- do{
- line = in.readLine();
- i++;
- if(line != null){
- if(!sloc.hasOffsetLength()){
- w.append(values.string(line));
- }else{
- if(!sloc.hasLineColumn()){
- endColumn = line.length();
- }
- if(i == beginLine){
- if(i == endLine){
- w.append(values.string(line.substring(beginColumn, endColumn)));
- }else{
- w.append(values.string(line.substring(beginColumn)));
- }
- }else if(i > beginLine){
- if(i == endLine){
- w.append(values.string(line.substring(0, endColumn)));
- }
- else if(i < endLine){
- w.append(values.string(line));
- }
- }
- }
- }
- }while(line != null);
- }catch(IOException e){
- throw RuntimeExceptionFactory.io(values.string(e.getMessage()), ctx.getCurrentAST(), null);
- }finally{
- if(in != null){
- try{
- in.close();
- }catch(IOException ioex){
- throw RuntimeExceptionFactory.io(values.string(ioex.getMessage()), ctx.getCurrentAST(), null);
- }
- }
- }
- return w.done();
- }
-
- public IList readFileBytes(ISourceLocation sloc, IEvaluatorContext ctx){
- IListWriter w = types.listType(types.integerType()).writer(values);
-
- BufferedInputStream in = null;
- try{
- InputStream stream = ctx.getResolverRegistry().getInputStream(sloc.getURI());
- in = new BufferedInputStream(stream);
- int read;
- final int size = 256;
- byte bytes[] = new byte[size];
-
- do{
- read = in.read(bytes);
- for (…
Large files files are truncated, but you can click here to view the full file