public Range(IokeObject from, IokeObject to, bool inclusive, bool inverted) { this.from = from; this.to = to; this.inclusive = inclusive; this.inverted = inverted; }
public static object ToRational(object on, IokeObject context, IokeObject message) { string tvalue = GetText(on); try { return context.runtime.NewNumber(tvalue); } catch(Exception) { Runtime runtime = context.runtime; IokeObject condition = IokeObject.As(IokeObject.GetCellChain(runtime.Condition, message, context, "Error", "Arithmetic", "NotParseable"), context).Mimic(message, context); condition.SetCell("message", message); condition.SetCell("context", context); condition.SetCell("receiver", on); condition.SetCell("text", on); object[] newCell = new object[]{null}; runtime.WithRestartReturningArguments(()=>{runtime.ErrorCondition(condition);}, context, new IokeObject.UseValue("rational", newCell), new TakeLongestRational(tvalue, newCell)); return newCell[0]; } }
public LexicalBlock(IokeObject context, DefaultArgumentsDefinition arguments, IokeObject message) : base(IokeData.TYPE_LEXICAL_BLOCK) { this.context = context; this.arguments = arguments; this.message = message; }
public static object ActivateWithCallAndDataFixed(IokeObject self, IokeObject dynamicContext, IokeObject message, object on, object call, IDictionary<string, object> data) { LexicalMacro lm = (LexicalMacro)self.data; if(lm.code == null) { IokeObject condition = IokeObject.As(IokeObject.GetCellChain(dynamicContext.runtime.Condition, message, dynamicContext, "Error", "Invocation", "NotActivatable"), dynamicContext).Mimic(message, dynamicContext); condition.SetCell("message", message); condition.SetCell("context", dynamicContext); condition.SetCell("receiver", on); condition.SetCell("method", self); condition.SetCell("report", dynamicContext.runtime.NewText("You tried to activate a method without any code - did you by any chance activate the LexicalMacro kind by referring to it without wrapping it inside a call to cell?")); dynamicContext.runtime.ErrorCondition(condition); return null; } IokeObject c = self.runtime.NewLexicalContext(on, "Lexical macro activation context", lm.context); c.SetCell("outerScope", lm.context); c.SetCell("call", call); foreach(var d in data) { string s = d.Key; c.SetCell(s.Substring(0, s.Length-1), d.Value); } return self.runtime.interpreter.Evaluate(lm.code, c, on, c); }
public override void Init(IokeObject obj) { Runtime runtime = obj.runtime; obj.Kind = "DateTime"; // obj.mimics(IokeObject.as(runtime.mixins.getCell(null, null, "Comparing")), runtime.nul, runtime.nul); obj.RegisterMethod(runtime.NewNativeMethod("Returns a new DateTime representing the current instant in time in the default TimeZone.", new TypeCheckingNativeMethod.WithNoArguments("now", obj, (method, on, args, keywords, context, message) => { return method.runtime.NewDateTime(System.DateTime.Now); }))); obj.RegisterMethod(runtime.NewNativeMethod("Expects to get one DateTime as argument, and returns the difference between this instant and that instant, in milliseconds.", new TypeCheckingNativeMethod("-", TypeCheckingArgumentsDefinition.builder() .ReceiverMustMimic(obj) .WithRequiredPositional("subtrahend").WhichMustMimic(obj) .Arguments, (method, on, args, keywords, context, message) => { long diff = System.Convert.ToInt64(GetDateTime(on).Subtract(GetDateTime(args[0])).TotalMilliseconds); return context.runtime.NewNumber(diff); }))); obj.RegisterMethod(runtime.NewNativeMethod("Returns a text inspection of the object", new TypeCheckingNativeMethod.WithNoArguments("inspect", obj, (method, on, args, keywords, context, message) => { return method.runtime.NewText(DateTime.GetInspect(on)); }))); obj.RegisterMethod(runtime.NewNativeMethod("Returns a brief text inspection of the object", new TypeCheckingNativeMethod.WithNoArguments("notice", obj, (method, on, args, keywords, context, message) => { return method.runtime.NewText(DateTime.GetNotice(on)); }))); }
public IokeParser(Runtime runtime, TextReader reader, IokeObject context, IokeObject message) { this.runtime = runtime; this.reader = reader; this.context = context; this.message = message; }
internal Level(int precedence, IokeObject op, Level parent, Type type) { this.precedence = precedence; this.operatorMessage = op; this.parent = parent; this.type = type; }
public object GetValidatedArgumentsAndReceiver(IokeObject context, IokeObject message, object on, IList argumentsWithoutKeywords, IDictionary<string, object> givenKeywords) { if(!restUneval) { GetEvaluatedArguments(context, message, on, argumentsWithoutKeywords, givenKeywords); int ix = 0; for (int i = 0, j = this.arguments.Count; i < j; i++) { Argument a = this.arguments[i]; if (a is KeywordArgument) { string name = a.Name + ":"; object given = givenKeywords[name]; if (given != null) { givenKeywords[name] = mustMimic[0].ConvertToMimic(given, message, context, true); } } else { if(ix < argumentsWithoutKeywords.Count) { argumentsWithoutKeywords[ix] = mustMimic[i].ConvertToMimic(argumentsWithoutKeywords[ix], message, context, true); ix++; } } } } else { foreach(object o in message.Arguments) argumentsWithoutKeywords.Add(o); } return receiverMustMimic.ConvertToMimic(on, message, context, true); }
public static new object ActivateFixed(IokeObject self, IokeObject dynamicContext, IokeObject message, object on) { LexicalMacro lm = (LexicalMacro)self.data; if(lm.code == null) { IokeObject condition = IokeObject.As(IokeObject.GetCellChain(dynamicContext.runtime.Condition, message, dynamicContext, "Error", "Invocation", "NotActivatable"), dynamicContext).Mimic(message, dynamicContext); condition.SetCell("message", message); condition.SetCell("context", dynamicContext); condition.SetCell("receiver", on); condition.SetCell("method", self); condition.SetCell("report", dynamicContext.runtime.NewText("You tried to activate a method without any code - did you by any chance activate the LexicalMacro kind by referring to it without wrapping it inside a call to cell?")); dynamicContext.runtime.ErrorCondition(condition); return null; } IokeObject c = self.runtime.NewLexicalContext(on, "Lexical macro activation context", lm.context); c.SetCell("outerScope", lm.context); c.SetCell("call", dynamicContext.runtime.NewCallFrom(c, message, dynamicContext, IokeObject.As(on, dynamicContext))); return self.runtime.interpreter.Evaluate(lm.code, c, on, c); }
public override object Activate(IokeObject self, IokeObject dynamicContext, IokeObject message, object on) { if(code == null) { IokeObject condition = IokeObject.As(IokeObject.GetCellChain(dynamicContext.runtime.Condition, message, dynamicContext, "Error", "Invocation", "NotActivatable"), dynamicContext).Mimic(message, dynamicContext); condition.SetCell("message", message); condition.SetCell("context", dynamicContext); condition.SetCell("receiver", on); condition.SetCell("method", self); condition.SetCell("report", dynamicContext.runtime.NewText("You tried to activate a method without any code - did you by any chance activate the LexicalMacro kind by referring to it without wrapping it inside a call to cell?")); dynamicContext.runtime.ErrorCondition(condition); return null; } LexicalContext c = new LexicalContext(self.runtime, on, "Lexical macro activation context", message, this.context); c.SetCell("outerScope", context); c.SetCell("call", dynamicContext.runtime.NewCallFrom(c, message, dynamicContext, IokeObject.As(on, dynamicContext))); return ((Message)IokeObject.dataOf(this.code)).EvaluateCompleteWith(this.code, c, on); }
private static object TypeCheckingRawActivate(IokeObject self, IokeObject context, IokeObject message, object on, NativeMethod outer) { IList args = new SaneArrayList(); IDictionary<string, object> keywords = new SaneDictionary<string, object>(); object receiver = ((TypeCheckingArgumentsDefinition)outer.ArgumentsDefinition).GetValidatedArgumentsAndReceiver(context, message, on, args, keywords); return outer.argsActivator(self, receiver, args, keywords, context, message); }
private static object ArgumentActivator(IokeObject self, IokeObject context, IokeObject message, object on, NativeMethod outer) { IList args = new SaneArrayList(); IDictionary<string, object> keywords = new SaneDictionary<string, object>(); outer.ArgumentsDefinition.GetEvaluatedArguments(context, message, on, args, keywords); return outer.argsActivator(self, on, args, keywords, context, message); }
public Call(IokeObject ctx, IokeObject message, IokeObject surroundingContext, IokeObject on) { this.ctx = ctx; this.message = message; this.surroundingContext = surroundingContext; this.on = on; }
public override void Init(IokeObject obj) { Runtime runtime = obj.runtime; obj.Kind = "Pair"; obj.Mimics(IokeObject.As(runtime.Mixins.GetCell(null, null, "Enumerable"), null), runtime.nul, runtime.nul); obj.Mimics(IokeObject.As(runtime.Mixins.GetCell(null, null, "Comparing"), null), runtime.nul, runtime.nul); obj.RegisterMethod(runtime.NewNativeMethod("returns true if the left hand side pair is equal to the right hand side pair.", new TypeCheckingNativeMethod("==", TypeCheckingArgumentsDefinition.builder() .ReceiverMustMimic(runtime.Pair) .WithRequiredPositional("other") .Arguments, (method, on, args, keywords, context, message) => { Pair d = (Pair)IokeObject.dataOf(on); object other = args[0]; return ((other is IokeObject) && (IokeObject.dataOf(other) is Pair) && d.first.Equals(((Pair)IokeObject.dataOf(other)).first) && d.second.Equals(((Pair)IokeObject.dataOf(other)).second)) ? context.runtime.True : context.runtime.False; }))); obj.RegisterMethod(runtime.NewNativeMethod("Returns the first value", new TypeCheckingNativeMethod.WithNoArguments("first", obj, (method, on, args, keywords, context, message) => { return ((Pair)IokeObject.dataOf(on)).first; }))); obj.RegisterMethod(runtime.NewNativeMethod("Returns the first value", new TypeCheckingNativeMethod.WithNoArguments("key", obj, (method, on, args, keywords, context, message) => { return ((Pair)IokeObject.dataOf(on)).first; }))); obj.RegisterMethod(runtime.NewNativeMethod("Returns the second value", new TypeCheckingNativeMethod.WithNoArguments("second", obj, (method, on, args, keywords, context, message) => { return ((Pair)IokeObject.dataOf(on)).second; }))); obj.RegisterMethod(runtime.NewNativeMethod("Returns the second value", new TypeCheckingNativeMethod.WithNoArguments("value", obj, (method, on, args, keywords, context, message) => { return ((Pair)IokeObject.dataOf(on)).second; }))); obj.RegisterMethod(runtime.NewNativeMethod("Returns a text inspection of the object", new TypeCheckingNativeMethod.WithNoArguments("inspect", obj, (method, on, args, keywords, context, message) => { return method.runtime.NewText(Pair.GetInspect(on)); }))); obj.RegisterMethod(runtime.NewNativeMethod("Returns a brief text inspection of the object", new TypeCheckingNativeMethod.WithNoArguments("notice", obj, (method, on, args, keywords, context, message) => { return method.runtime.NewText(Pair.GetNotice(on)); }))); }
public override object ActivateWithCall(IokeObject self, IokeObject dynamicContext, IokeObject message, object on, object call) { LexicalContext c = new LexicalContext(self.runtime, on, "Lexical activation context", message, this.context); arguments.AssignArgumentValues(c, dynamicContext, message, on, ((Call)IokeObject.dataOf(call))); return ((Message)IokeObject.dataOf(this.message)).EvaluateCompleteWith(this.message, c, on); }
public static string GetContextMessageName(IokeObject ctx) { if("Locals".Equals(ctx.GetKind())) { return ":in `" + IokeObject.As(ctx.Cells["currentMessage"], ctx).Name + "'"; } else { return ""; } }
public override IokeObject Invoke(IokeObject context, IList arguments) { IList result = new SaneArrayList(); for(int i=0; i<repeat; i++) { result.Add(value); } return context.runtime.NewList(result); }
public static int ExtractInt(object number, IokeObject m, IokeObject context) { if(!(IokeObject.dataOf(number) is Number)) { number = IokeObject.ConvertToNumber(number, m, context); } return IntValue(number).intValue(); }
public override void Assign(string name, object value, IokeObject context, IokeObject message) { object place = FindPlace(name); if(place == runtime.nul) { place = this; } IokeObject.SetCell(place, name, value, context); }
public static new object ActivateFixed(IokeObject self, IokeObject dynamicContext, IokeObject message, object on) { LexicalBlock lb = (LexicalBlock)self.data; IokeObject c = self.runtime.NewLexicalContext(on, "Lexical activation context", lb.context); lb.arguments.AssignArgumentValues(c, dynamicContext, message, on); return self.runtime.interpreter.Evaluate(lb.message, c, on, c); }
public LexicalContext(Runtime runtime, object ground, string documentation, IokeObject message, IokeObject surroundingContext) : base(runtime, documentation) { this.ground = IokeObject.GetRealContext(ground); this.message = message; this.surroundingContext = surroundingContext; Kind = "LexicalContext"; }
protected override object MarkingFindSuperCell(IokeObject early, IokeObject message, IokeObject context, string name, bool[] found) { object nn = base.MarkingFindSuperCell(early, message, context, name, found); if(nn == runtime.nul) { return IokeObject.FindSuperCellOn(surroundingContext, early, message, context, name); } else { return nn; } }
public static Regexp Create(string pattern, string flags, IokeObject context, IokeObject message) { try { return new Regexp(pattern, new Pattern(pattern, flags), flags); } catch(System.Exception e) { System.Console.Error.WriteLine(e.StackTrace); return null; } }
public override object FindSuperCell(IokeObject early, IokeObject message, IokeObject context, string name, bool[] found, IDictionary visited) { object nn = base.FindSuperCell(early, message, context, name, found, visited); if(nn == runtime.nul) { return IokeObject.FindSuperCellOn(surroundingContext, early, message, context, name); } else { return nn; } }
public static IokeObject GetDefaultValue(object on, IokeObject context, IokeObject message) { Dict dict = (Dict)IokeObject.dataOf(on); if(dict.defaultValue == null) { return context.runtime.nil; } else { return dict.defaultValue; } }
public static object CellNames(IokeObject context, IokeObject message, object on, bool includeMimics, object cutoff) { if(includeMimics) { var visited = IdentityHashTable.Create(); var names = new SaneArrayList(); var visitedNames = new SaneHashSet<object>(); var undefined = new SaneHashSet<string>(); Runtime runtime = context.runtime; var toVisit = new SaneArrayList(); toVisit.Add(on); while(toVisit.Count > 0) { IokeObject current = IokeObject.As(toVisit[0], context); toVisit.RemoveAt(0); if(!visited.Contains(current)) { visited[current] = null; if(cutoff != current) { foreach(IokeObject o in current.GetMimics()) toVisit.Add(o); } Cell c = current.body.firstAdded; while(c != null) { string s = c.name; if(!undefined.Contains(s)) { if(c.value == runtime.nul) { undefined.Add(s); } else { object x = runtime.GetSymbol(s); if(!visitedNames.Contains(x)) { visitedNames.Add(x); names.Add(x); } } } c = c.orderedNext; } } } return runtime.NewList(names); } else { var names = new SaneArrayList(); Runtime runtime = context.runtime; Cell c = IokeObject.As(on, context).body.firstAdded; while(c != null) { string s = c.name; if(c.value != runtime.nul) { names.Add(runtime.GetSymbol(s)); } c = c.orderedNext; } return runtime.NewList(names); } }
public static void FireMimicked(IokeObject on, IokeObject message, IokeObject context, IokeObject mimickingObject) { List<IokeObject> hooks = on.hooks; if(hooks != null) { IokeObject mimickedMessage = context.runtime.mimickedMessage; foreach(IokeObject h in hooks) { ((Message)IokeObject.dataOf(mimickedMessage)).SendTo(mimickedMessage, context, h, on, mimickingObject); } } }
public static IokeObject GetArity(IokeObject self, DefaultArgumentsDefinition def) { if(def == null || def.IsEmpty) { return IokeObject.As(TakingNothing(self), self.runtime.Arity); } IokeObject obj = self.runtime.Arity.AllocateCopy(null, null); obj.MimicsWithoutCheck(self.runtime.Arity); obj.Data = new Arity(def); return obj; }
public override object FindCell(IokeObject m, IokeObject context, string name, IDictionary visited) { object nn = base.FindCell(m, context, name, visited); if(nn == runtime.nul) { return IokeObject.FindCell(surroundingContext, m, context, name, visited); } else { return nn; } }
public static void FireMimicked(IokeObject on, IokeObject message, IokeObject context, IokeObject mimickingObject) { List<IokeObject> hooks = on.body.hooks; if(hooks != null) { IokeObject mimickedMessage = context.runtime.mimickedMessage; foreach(IokeObject h in hooks) { Interpreter.Send(mimickedMessage, context, h, on, mimickingObject); } } }
public static object ActivateWithDataFixed(IokeObject self, IokeObject dynamicContext, IokeObject message, object on, IDictionary <string, object> data) { LexicalBlock lb = (LexicalBlock)self.data; IokeObject c = self.runtime.NewLexicalContext(on, "Lexical activation context", lb.context); foreach (var d in data) { string s = d.Key; c.SetCell(s.Substring(0, s.Length - 1), d.Value); } lb.arguments.AssignArgumentValues(c, dynamicContext, message, on); return(self.runtime.interpreter.Evaluate(lb.message, c, on, c)); }
private static int FormatString(string format, int index, IokeObject message, IokeObject context, IList positionalArgs, StringBuilder result) { int argIndex = 0; int formatIndex = index; int justify = 0; bool splat = false; bool splatPairs = false; bool negativeJustify = false; bool doAgain = false; int formatLength = format.Length; object arg = null; StringBuilder missingText = new StringBuilder(); object seq = null; IList args = null; while (formatIndex < formatLength) { char c = format[formatIndex++]; switch (c) { case '%': justify = 0; missingText.Append(c); do { doAgain = false; if (formatIndex < formatLength) { c = format[formatIndex++]; missingText.Append(c); switch (c) { case '*': splat = true; doAgain = true; break; case ':': splatPairs = true; doAgain = true; break; case ']': return(formatIndex); case '[': arg = positionalArgs[argIndex++]; int endLoop = -1; seq = Interpreter.Send(context.runtime.seqMessage, context, arg); while (IokeObject.IsObjectTrue(Interpreter.Send(context.runtime.nextPMessage, context, seq))) { object receiver = Interpreter.Send(context.runtime.nextMessage, context, seq); if (splat) { args = IokeList.GetList(receiver); } else if (splatPairs) { args = new SaneArrayList() { Pair.GetFirst(receiver), Pair.GetSecond(receiver) }; } else { args = new SaneArrayList() { receiver }; } int newVal = FormatString(format, formatIndex, message, context, args, result); endLoop = newVal; } splat = false; splatPairs = false; if (endLoop == -1) { int opened = 1; while (opened > 0 && formatIndex < formatLength) { char c2 = format[formatIndex++]; if (c2 == '%' && formatIndex < formatLength) { c2 = format[formatIndex++]; if (c2 == '[') { opened++; } else if (c2 == ']') { opened--; } } } } else { formatIndex = endLoop; } break; case 's': arg = positionalArgs[argIndex++]; object txt = IokeObject.TryConvertToText(arg, message, context); if (txt == null) { txt = Interpreter.Send(context.runtime.asText, context, arg); } string outTxt = Text.GetText(txt); if (outTxt.Length < justify) { int missing = justify - outTxt.Length; char[] spaces = new char[missing]; for (int ixx = 0; ixx < spaces.Length; ixx++) { spaces[ixx] = ' '; } if (negativeJustify) { result.Append(outTxt); result.Append(spaces); } else { result.Append(spaces); result.Append(outTxt); } } else { result.Append(outTxt); } break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': justify *= 10; justify += (c - '0'); doAgain = true; break; case '-': negativeJustify = !negativeJustify; doAgain = true; break; default: result.Append(missingText); missingText = new StringBuilder(); break; } } else { result.Append(missingText); missingText = new StringBuilder(); } } while(doAgain); break; default: result.Append(c); break; } } return(formatLength); }
public static string GetText(object on) { return(((Text)(IokeObject.dataOf(on))).GetText()); }
public static bool IsText(object on) { return(IokeObject.dataOf(on) is Text); }
public override string ToString(IokeObject self) { return(text); }
public override void Init(IokeObject obj) { Runtime runtime = obj.runtime; obj.Kind = "Text"; obj.Mimics(IokeObject.As(IokeObject.FindCell(runtime.Mixins, "Comparing"), null), runtime.nul, runtime.nul); obj.RegisterMethod(runtime.NewNativeMethod("returns a hash for the text", new NativeMethod.WithNoArguments("hash", (method, context, message, on, outer) => { outer.ArgumentsDefinition.CheckArgumentCount(context, message, on); return(context.runtime.NewNumber(((Text)IokeObject.dataOf(on)).text.GetHashCode())); }))); obj.RegisterMethod(runtime.NewNativeMethod("returns true if the left hand side text is equal to the right hand side text.", new TypeCheckingNativeMethod("==", TypeCheckingArgumentsDefinition.builder() .ReceiverMustMimic(runtime.Text) .WithRequiredPositional("other") .Arguments, (method, on, args, keywords, context, message) => { Text d = (Text)IokeObject.dataOf(on); object other = args[0]; return(((other is IokeObject) && (IokeObject.dataOf(other) is Text) && ((on == context.runtime.Text || other == context.runtime.Text) ? on == other : d.text.Equals(((Text)IokeObject.dataOf(other)).text))) ? context.runtime.True : context.runtime.False); }))); obj.RegisterMethod(runtime.NewNativeMethod("Returns a text representation of the object", new NativeMethod.WithNoArguments("asText", (method, context, message, on, outer) => { outer.ArgumentsDefinition.GetEvaluatedArguments(context, message, on, new SaneArrayList(), new SaneDictionary <string, object>()); return(on); }))); obj.RegisterMethod(runtime.NewNativeMethod("Takes any number of arguments, and expects the text receiver to contain format specifications. The currently supported specifications are only %s and %{, %}. These have several parameters that can be used. See the spec for more info about these. The format method will return a new text based on the content of the receiver, and the arguments given.", new TypeCheckingNativeMethod("format", TypeCheckingArgumentsDefinition.builder() .ReceiverMustMimic(obj) .WithRest("replacements") .Arguments, (self, on, args, keywords, context, message) => { StringBuilder result = new StringBuilder(); Format(on, message, context, args, result); return(context.runtime.NewText(result.ToString())); }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("Converts the content of this text into a rational value", new TypeCheckingNativeMethod.WithNoArguments("toRational", obj, (self, on, args, keywords, context, message) => { return(Text.ToRational(on, context, message)); }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("Converts the content of this text into a decimal value", new TypeCheckingNativeMethod.WithNoArguments("toDecimal", obj, (self, on, args, keywords, context, message) => { return(Text.ToDecimal(on, context, message)); }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("Returns a text inspection of the object", new TypeCheckingNativeMethod.WithNoArguments("inspect", obj, (self, on, args, keywords, context, message) => { return(self.runtime.NewText(Text.GetInspect(on))); }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("Returns a brief text inspection of the object", new TypeCheckingNativeMethod.WithNoArguments("notice", obj, (self, on, args, keywords, context, message) => { return(self.runtime.NewText(Text.GetInspect(on))); }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("Returns a text where all non-safe characters have been replaced with safe ones", new TypeCheckingNativeMethod.WithNoArguments("makeXMLSafe", obj, (self, on, args, keywords, context, message) => { return(self.runtime.NewText(new StringUtils().XmlSafe(Text.GetText(on)))); }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("Returns a lower case version of this text", new TypeCheckingNativeMethod.WithNoArguments("lower", obj, (self, on, args, keywords, context, message) => { return(self.runtime.NewText(Text.GetText(on).ToLower())); }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("Returns an upper case version of this text", new TypeCheckingNativeMethod.WithNoArguments("upper", obj, (self, on, args, keywords, context, message) => { return(self.runtime.NewText(Text.GetText(on).ToUpper())); }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("Returns a version of this text with leading and trailing whitespace removed", new TypeCheckingNativeMethod.WithNoArguments("trim", obj, (self, on, args, keywords, context, message) => { return(self.runtime.NewText(Text.GetText(on).Trim())); }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("Returns an array of texts split around the argument", new TypeCheckingNativeMethod("split", TypeCheckingArgumentsDefinition.builder() .ReceiverMustMimic(obj) .WithOptionalPositional("splitAround", "") .Arguments, (self, on, args, keywords, context, message) => { string real = Text.GetText(on); var r = new SaneArrayList(); Pattern p = null; if (args.Count == 0) { p = new Pattern("\\s"); } else { object arg = args[0]; if (IokeObject.dataOf(arg) is Regexp) { p = Regexp.GetRegexp(arg); } else { string around = Text.GetText(arg); p = new Pattern(Pattern.Quote(around)); } } RETokenizer tok = new RETokenizer(p, real); tok.EmptyEnabled = false; while (tok.HasMore) { r.Add(context.runtime.NewText(tok.NextToken)); } return(context.runtime.NewList(r)); }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("Takes two text arguments where the first is the substring to replace, and the second is the replacement to insert. Will only replace the first match, if any is found, and return a new Text with the result.", new TypeCheckingNativeMethod("replace", TypeCheckingArgumentsDefinition.builder() .ReceiverMustMimic(obj) .WithRequiredPositional("pattern") .WithRequiredPositional("replacement") .Arguments, (self, on, args, keywords, context, message) => { string initial = Text.GetText(on); string repl = Text.GetText(args[1]); object arg = args[0]; Pattern pat = null; if (IokeObject.dataOf(arg) is Regexp) { pat = Regexp.GetRegexp(arg); } else { string around = Text.GetText(arg); pat = new Pattern(Pattern.Quote(around)); } Replacer r = pat.Replacer(repl); string result = r.ReplaceFirst(initial); return(context.runtime.NewText(result)); }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("Takes two text arguments where the first is the substring to replace, and the second is the replacement to insert. Will replace all matches, if any is found, and return a new Text with the result.", new TypeCheckingNativeMethod("replaceAll", TypeCheckingArgumentsDefinition.builder() .ReceiverMustMimic(obj) .WithRequiredPositional("pattern") .WithRequiredPositional("replacement") .Arguments, (self, on, args, keywords, context, message) => { string initial = Text.GetText(on); string repl = Text.GetText(args[1]); object arg = args[0]; Pattern pat = null; if (IokeObject.dataOf(arg) is Regexp) { pat = Regexp.GetRegexp(arg); } else { string around = Text.GetText(arg); pat = new Pattern(Pattern.Quote(around)); } Replacer r = pat.Replacer(repl); String result = r.Replace(initial); return(context.runtime.NewText(result)); }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("Returns the length of this text", new TypeCheckingNativeMethod.WithNoArguments("length", obj, (self, on, args, keywords, context, message) => { return(context.runtime.NewNumber(GetText(on).Length)); }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("compares this text against the argument, returning -1, 0 or 1 based on which one is lexically larger", new TypeCheckingNativeMethod("<=>", TypeCheckingArgumentsDefinition.builder() .ReceiverMustMimic(obj) .WithRequiredPositional("other") .Arguments, (self, on, args, keywords, context, message) => { object arg = args[0]; if (!(IokeObject.dataOf(arg) is Text)) { arg = IokeObject.ConvertToText(arg, message, context, false); if (!(IokeObject.dataOf(arg) is Text)) { // Can't compare, so bail out return(context.runtime.nil); } } if (on == context.runtime.Text || arg == context.runtime.Text) { if (on == arg) { return(context.runtime.NewNumber(0)); } return(context.runtime.nil); } int result = string.CompareOrdinal(Text.GetText(on), Text.GetText(arg)); if (result < 0) { result = -1; } else if (result > 0) { result = 1; } return(context.runtime.NewNumber(result)); }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("takes one argument, that can be either an index or a range of two indicis. this slicing works the same as for Lists, so you can index from the end, both with the single index and with the range.", new TypeCheckingNativeMethod("[]", TypeCheckingArgumentsDefinition.builder() .ReceiverMustMimic(obj) .WithRequiredPositional("index") .Arguments, (self, on, args, keywords, context, message) => { object arg = args[0]; IokeData data = IokeObject.dataOf(arg); if (data is Range) { int first = Number.ExtractInt(Range.GetFrom(arg), message, context); if (first < 0) { return(context.runtime.NewText("")); } int last = Number.ExtractInt(Range.GetTo(arg), message, context); bool inclusive = Range.IsInclusive(arg); string str = GetText(on); int size = str.Length; if (last < 0) { last = size + last; } if (last < 0) { return(context.runtime.NewText("")); } if (last >= size) { last = inclusive ? size - 1 : size; } if (first > last || (!inclusive && first == last)) { return(context.runtime.NewText("")); } if (!inclusive) { last--; } return(context.runtime.NewText(str.Substring(first, (last + 1) - first))); } else if (data is Number) { string str = GetText(on); int len = str.Length; int ix = ((Number)data).AsNativeInteger(); if (ix < 0) { ix = len + ix; } if (ix >= 0 && ix < len) { return(context.runtime.NewNumber(str[ix])); } else { return(context.runtime.nil); } } return(on); }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("Returns a symbol representing the Unicode category of the character", new TypeCheckingNativeMethod.WithNoArguments("category", obj, (self, on, args, keywords, context, message) => { string character = GetText(on); if (character.Length == 1) { return(context.runtime.GetSymbol(UnicodeBlock.Of(character[0]))); } IokeObject condition = IokeObject.As(IokeObject.GetCellChain(runtime.Condition, message, context, "Error", "Default"), context).Mimic(message, context); condition.SetCell("message", message); condition.SetCell("context", context); condition.SetCell("receiver", on); condition.SetCell("text", context.runtime.NewText("Text does not contain exactly one character")); runtime.ErrorCondition(condition); return(null); }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("Returns a new text where all the escapes in the current text have been evaluated - exactly as if another parsing step had been applied. This does not evaluate embedded code, though.", new TypeCheckingNativeMethod.WithNoArguments("evaluateEscapes", obj, (self, on, args, keywords, context, message) => { return(context.runtime.NewText(new StringUtils().ReplaceEscapes(GetText(on)))); }))); }
public override IokeObject TryConvertToText(IokeObject self, IokeObject m, IokeObject context) { return(self); }
public static void Format(object on, IokeObject message, IokeObject context, IList positionalArgs, StringBuilder result) { FormatString(Text.GetText(on), 0, message, context, positionalArgs, result); }
public LexicalBlock(IokeObject context) : this(context, DefaultArgumentsDefinition.Empty(), context.runtime.nilMessage) { }
public static string GetNotice(object on) { return(((Inspectable)(IokeObject.dataOf(on))).Notice(on)); }
public override void Init(IokeObject obj) { obj.Kind = "LexicalBlock"; obj.RegisterMethod(obj.runtime.NewNativeMethod("takes two evaluated arguments, where this first one is a list of messages which will be used as the arguments and the code, and the second is the context where this lexical scope should be created in", new NativeMethod("createFrom", DefaultArgumentsDefinition.builder() .WithRequiredPositional("messageList") .WithRequiredPositional("lexicalContext") .Arguments, (method, _context, _message, on, outer) => { Runtime runtime = _context.runtime; var positionalArgs = new SaneArrayList(); outer.ArgumentsDefinition.GetEvaluatedArguments(_context, _message, on, positionalArgs, new SaneDictionary <string, object>()); var args = IokeList.GetList(positionalArgs[0]); IokeObject ground = IokeObject.As(positionalArgs[1], _context); IokeObject code = IokeObject.As(args[args.Count - 1], _context); DefaultArgumentsDefinition def = DefaultArgumentsDefinition.CreateFrom(args, 0, args.Count - 1, _message, on, _context); return(runtime.NewLexicalBlock(null, runtime.LexicalBlock, new LexicalBlock(ground, def, code))); }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("invokes the block with the arguments provided, returning the result of the last expression in the block", new NativeMethod("call", DefaultArgumentsDefinition.builder() .WithRestUnevaluated("arguments") .Arguments, (method, _context, _message, on, outer) => { return(Interpreter.Activate(IokeObject.As(on, _context), _context, _message, on)); }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("returns the full code of this lexical block, as a Text", new TypeCheckingNativeMethod.WithNoArguments("code", obj, (method, on, args, keywords, _context, _message) => { IokeObject objx = IokeObject.As(on, _context); string x = objx.IsActivatable ? "x" : ""; string argstr = ((LexicalBlock)IokeObject.dataOf(on)).arguments.GetCode(); return(_context.runtime.NewText("fn" + x + "(" + argstr + Message.Code(((LexicalBlock)IokeObject.dataOf(on)).message) + ")")); }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("returns the code for the argument definition", new TypeCheckingNativeMethod.WithNoArguments("argumentsCode", obj, (method, on, args, keywords, _context, _message) => { return(_context.runtime.NewText(((AssociatedCode)IokeObject.dataOf(on)).ArgumentsCode)); }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("returns a list of the keywords this block takes", new TypeCheckingNativeMethod.WithNoArguments("keywords", obj, (method, on, args, keywords, _context, _message) => { var keywordList = new SaneArrayList(); foreach (string keyword in ((LexicalBlock)IokeObject.dataOf(on)).arguments.Keywords) { keywordList.Add(_context.runtime.GetSymbol(keyword.Substring(0, keyword.Length - 1))); } return(_context.runtime.NewList(keywordList)); }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("returns a list of the argument names the positional arguments this block takes", new TypeCheckingNativeMethod.WithNoArguments("argumentNames", obj, (method, on, args, keywords, _context, _message) => { var names = new SaneArrayList(); foreach (var arg in ((LexicalBlock)IokeObject.dataOf(on)).arguments.Arguments) { if (!(arg is DefaultArgumentsDefinition.KeywordArgument)) { names.Add(_context.runtime.GetSymbol(arg.Name)); } } return(_context.runtime.NewList(names)); }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("returns the message chain for this block", new TypeCheckingNativeMethod.WithNoArguments("message", obj, (method, on, args, keywords, _context, _message) => { return(((AssociatedCode)IokeObject.dataOf(on)).Code); }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("Returns a text inspection of the object", new TypeCheckingNativeMethod.WithNoArguments("inspect", obj, (method, on, args, keywords, _context, message) => { return(_context.runtime.NewText(LexicalBlock.GetInspect(on))); }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("Returns a brief text inspection of the object", new TypeCheckingNativeMethod.WithNoArguments("notice", obj, (method, on, args, keywords, _context, message) => { return(_context.runtime.NewText(LexicalBlock.GetNotice(on))); }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("returns idiomatically formatted code for this lexical block", new TypeCheckingNativeMethod.WithNoArguments("formattedCode", obj, (method, on, args, keywords, _context, message) => { return(_context.runtime.NewText(((AssociatedCode)IokeObject.dataOf(on)).FormattedCode(method))); }))); }
public static void Init(IokeObject obj) { Runtime runtime = obj.runtime; obj.Kind = "DefaultBehavior Definitions"; obj.RegisterMethod(runtime.NewNativeMethod("expects any number of unevaluated arguments. if no arguments at all are given, will just return nil. creates a new method based on the arguments. this method will be evaluated using the context of the object it's called on, and thus the definition can not refer to the outside scope where the method is defined. (there are other ways of achieving this). all arguments except the last one is expected to be names of arguments that will be used in the method. there will possible be additions to the format of arguments later on - including named parameters and optional arguments. the actual code is the last argument given.", new NativeMethod("method", DefaultArgumentsDefinition.builder() .WithOptionalPositionalUnevaluated("documentation") .WithRestUnevaluated("argumentsAndBody") .Arguments, (method, context, message, on, outer) => { outer.ArgumentsDefinition.CheckArgumentCount(context, message, on); var args = message.Arguments; if (args.Count == 0) { Message mx = new Message(context.runtime, "nil", null, false); mx.File = Message.GetFile(message); mx.Line = Message.GetLine(message); mx.Position = Message.GetPosition(message); IokeObject mmx = context.runtime.CreateMessage(mx); return(runtime.NewMethod(null, runtime.DefaultMethod, new DefaultMethod(context, DefaultArgumentsDefinition.Empty(), mmx))); } string doc = null; int start = 0; if (args.Count > 1 && ((IokeObject)Message.GetArguments(message)[0]).Name.Equals("internal:createText")) { start++; string s = (string)((IokeObject)args[0]).Arguments[0]; doc = s; } DefaultArgumentsDefinition def = DefaultArgumentsDefinition.CreateFrom(args, start, args.Count - 1, message, on, context); return(runtime.NewMethod(doc, runtime.DefaultMethod, new DefaultMethod(context, def, (IokeObject)args[args.Count - 1]))); }))); obj.RegisterMethod(runtime.NewNativeMethod("expects one code argument, optionally preceeded by a documentation string. will create a new DefaultMacro based on the code and return it.", new NativeMethod("macro", DefaultArgumentsDefinition.builder() .WithOptionalPositionalUnevaluated("documentation") .WithOptionalPositionalUnevaluated("body") .Arguments, (method, context, message, on, outer) => { outer.ArgumentsDefinition.CheckArgumentCount(context, message, on); var args = message.Arguments; if (args.Count == 0) { Message mx = new Message(context.runtime, "nil", null, false); mx.File = Message.GetFile(message); mx.Line = Message.GetLine(message); mx.Position = Message.GetPosition(message); IokeObject mmx = context.runtime.CreateMessage(mx); return(runtime.NewMacro(null, runtime.DefaultMacro, new DefaultMacro(context, mmx))); } string doc = null; int start = 0; if (args.Count > 1 && ((IokeObject)Message.GetArguments(message)[0]).Name.Equals("internal:createText")) { start++; string s = (string)(((IokeObject)args[0]).Arguments[0]); doc = s; } return(runtime.NewMacro(doc, runtime.DefaultMacro, new DefaultMacro(context, (IokeObject)args[start]))); }))); obj.RegisterMethod(runtime.NewNativeMethod("creates a new lexical block that can be executed at will, while retaining a reference to the lexical closure it was created in. it will always update variables if they exist. there is currently no way of introducing shadowing variables in the local context. new variables can be created though, just like in a method. a lexical block mimics LexicalBlock, and can take arguments. at the moment these are restricted to required arguments, but support for the same argument types as DefaultMethod will come.", new NativeMethod("fn", DefaultArgumentsDefinition.builder() .WithOptionalPositionalUnevaluated("documentation") .WithRestUnevaluated("argumentsAndBody") .Arguments, (method, context, message, on, outer) => { outer.ArgumentsDefinition.CheckArgumentCount(context, message, on); var args = message.Arguments; if (args.Count == 0) { return(runtime.NewLexicalBlock(null, runtime.LexicalBlock, new LexicalBlock(context, DefaultArgumentsDefinition.Empty(), method.runtime.nilMessage))); } string doc = null; int start = 0; if (args.Count > 1 && ((IokeObject)Message.GetArguments(message)[0]).Name.Equals("internal:createText")) { start++; string s = ((string)((IokeObject)args[0]).Arguments[0]); doc = s; } IokeObject code = IokeObject.As(args[args.Count - 1], context); DefaultArgumentsDefinition def = DefaultArgumentsDefinition.CreateFrom(args, start, args.Count - 1, message, on, context); return(runtime.NewLexicalBlock(doc, runtime.LexicalBlock, new LexicalBlock(context, def, code))); }))); obj.RegisterMethod(runtime.NewNativeMethod("expects one code argument, optionally preceeded by a documentation string. will create a new LexicalMacro based on the code and return it.", new NativeMethod("lecro", DefaultArgumentsDefinition.builder() .WithOptionalPositionalUnevaluated("documentation") .WithOptionalPositionalUnevaluated("body") .Arguments, (method, context, message, on, outer) => { outer.ArgumentsDefinition.CheckArgumentCount(context, message, on); var args = message.Arguments; if (args.Count == 0) { Message mx = new Message(context.runtime, "nil", null, false); mx.File = Message.GetFile(message); mx.Line = Message.GetLine(message); mx.Position = Message.GetPosition(message); IokeObject mmx = context.runtime.CreateMessage(mx); return(runtime.NewMacro(null, runtime.LexicalMacro, new LexicalMacro(context, mmx))); } string doc = null; int start = 0; if (args.Count > 1 && ((IokeObject)Message.GetArguments(message)[0]).Name.Equals("internal:createText")) { start++; string s = ((string)((IokeObject)args[0]).Arguments[0]); doc = s; } return(runtime.NewMacro(doc, runtime.LexicalMacro, new LexicalMacro(context, (IokeObject)args[start]))); }))); obj.RegisterMethod(runtime.NewNativeMethod("expects one code argument, optionally preceeded by a documentation string. will create a new DefaultSyntax based on the code and return it.", new NativeMethod("syntax", DefaultArgumentsDefinition.builder() .WithOptionalPositionalUnevaluated("documentation") .WithOptionalPositionalUnevaluated("body") .Arguments, (method, context, message, on, outer) => { outer.ArgumentsDefinition.CheckArgumentCount(context, message, on); var args = message.Arguments; if (args.Count == 0) { Message mx = new Message(context.runtime, "nil", null, false); mx.File = Message.GetFile(message); mx.Line = Message.GetLine(message); mx.Position = Message.GetPosition(message); IokeObject mmx = context.runtime.CreateMessage(mx); return(runtime.NewMacro(null, runtime.DefaultSyntax, new DefaultSyntax(context, mmx))); } string doc = null; int start = 0; if (args.Count > 1 && ((IokeObject)Message.GetArguments(message)[0]).Name.Equals("internal:createText")) { start++; string s = (string)((IokeObject)args[0]).Arguments[0]; doc = s; } return(runtime.NewMacro(doc, runtime.DefaultSyntax, new DefaultSyntax(context, (IokeObject)args[start]))); }))); obj.RegisterMethod(runtime.NewNativeMethod("Takes two evaluated text or symbol arguments that name the method to alias, and the new name to give it. returns the receiver.", new NativeMethod("aliasMethod", DefaultArgumentsDefinition.builder() .WithRequiredPositional("oldName") .WithRequiredPositional("newName") .Arguments, (method, context, message, on, outer) => { var args = new SaneArrayList(); outer.ArgumentsDefinition.GetEvaluatedArguments(context, message, on, args, new SaneDictionary <string, object>()); string fromName = Text.GetText(Interpreter.Send(runtime.asText, context, args[0])); string toName = Text.GetText(Interpreter.Send(runtime.asText, context, args[1])); IokeObject.As(on, context).AliasMethod(fromName, toName, message, context); return(on); }))); }
public override IokeObject ConvertToText(IokeObject self, IokeObject m, IokeObject context, bool signalCondition) { return(self); }
public new static object ActivateFixed(IokeObject self, IokeObject dynamicContext, IokeObject message, object on) { LexicalBlock lb = (LexicalBlock)self.data; IokeObject c = self.runtime.NewLexicalContext(on, "Lexical activation context", lb.context); lb.arguments.AssignArgumentValues(c, dynamicContext, message, on); return(self.runtime.interpreter.Evaluate(lb.message, c, on, c)); }