/
Invocation.scala
750 lines (674 loc) · 26.1 KB
/
Invocation.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
package querki.ql
import scala.reflect.ClassTag
import querki.values.SpaceState
import models.{AsOID, Collection, PType, Property, PropertyBundle, Thing, ThingId}
import querki.ecology._
import querki.globals._
import querki.types.ModelTypeBase
import querki.util.PublicException
import querki.values.{QLContext, QValue, SpaceState}
/**
* Extra information that can get picked up and carried along with the InvocationValue. Pulled out to here,
* to keep it from clogging up the logic of the main InvocationValueImpl.
*/
private[ql] case class IVMetadata(
// Allows the Function to declare which PType it expects to return. This allows us to preserve type safety
// even when we return QNone.
returnType: Option[PType[_]] = None,
preferredColl: Option[Collection] = None
) {
/**
* This method is the heart of IVMetadata, allowing us to combine metadatas in flatMap(). The copy
* should account for all parameters.
*/
def +(other: IVMetadata) = {
this.copy(
returnType = this.returnType.orElse(other.returnType),
preferredColl = this.preferredColl.orElse(other.preferredColl)
)
}
}
private[ql] case class IVData[T](
vs: Iterable[T],
metadata: IVMetadata = IVMetadata()
)
private[ql] case class InvocationValueImpl[T](
inv: Invocation,
fut: Future[IVData[T]]
)(implicit
val ecology: Ecology
) extends InvocationValue[T]
with EcologyMember { self =>
def map[R](f: T => R): InvocationValue[R] = {
val maps = fut.map(data => IVData(data.vs.map(v => f(v)), data.metadata))
InvocationValueImpl(inv, maps)
}
def flatMap[R](f: T => InvocationValue[R]): InvocationValue[R] = {
val results = fut.flatMap { data =>
// Check for timeouts. This is decidedly rough and ready, but should generally suffice to shut things down
// if they get pathological. When the QL pipeline gets rewritten to be properly monadic, we should be able
// to do this much more cleanly:
val timeProvider = ecology.api[querki.time.TimeProvider]
if (timeProvider.now.getMillis > inv.context.endTime.getMillis) {
Future.failed(PublicException("QL.timeout"))
} else {
val subs = data.vs.map(f(_)).map(_.asInstanceOf[InvocationValueImpl[R]])
val subFuts = subs.map(_.fut)
Future.sequence(subFuts).map { subDatas =>
val resultVs = subDatas.map(_.vs).flatten
val resultMetas = (data.metadata /: subDatas.map(_.metadata))(_ + _)
IVData(resultVs, resultMetas)
}
}
}
InvocationValueImpl(inv, results)
}
/**
* Our implementation of withFilter, for "if" statements in for comprehensions.
*/
class WithFilterImpl(f: T => Boolean) extends WithFilter[T] {
def map[R](mf: T => R): InvocationValue[R] =
new InvocationValueImpl(inv, self.fut.map(data => IVData(data.vs.filter(f), data.metadata))).map(mf)
def flatMap[R](mf: T => InvocationValue[R]): InvocationValue[R] =
new InvocationValueImpl(inv, self.fut.map(data => IVData(data.vs.filter(f), data.metadata))).flatMap(mf)
def withFilter(g: T => Boolean): WithFilter[T] = new WithFilterImpl((x => f(x) && g(x)))
}
def withFilter(f: T => Boolean): WithFilter[T] = new WithFilterImpl(f)
def get: Future[Iterable[T]] = fut.map(_.vs)
def all: InvocationValue[Iterable[T]] = {
val allFut = fut.map { ivd =>
IVData(List(ivd.vs), ivd.metadata)
}
InvocationValueImpl(inv, allFut)
}
def one: InvocationValue[T] = {
val oneFut = fut.map { ivd =>
IVData(ivd.vs.headOption, ivd.metadata)
}
InvocationValueImpl(inv, oneFut)
}
}
object InvocationValueImpl {
def apply[T](
ex: PublicException
)(implicit
inv: Invocation,
ecology: Ecology
): InvocationValueImpl[T] =
InvocationValueImpl[T](inv, Future.failed(ex))
def apply[T](
vs: Iterable[T]
)(implicit
inv: Invocation,
ecology: Ecology
): InvocationValueImpl[T] =
InvocationValueImpl[T](inv, Future.successful(IVData(vs)))
def apply(
meta: IVMetadata
)(implicit
inv: Invocation,
ecology: Ecology
): InvocationValueImpl[Boolean] =
InvocationValueImpl(inv, Future.successful(IVData(Some(true), meta)))
}
private[ql] case class InvocationImpl(
invokedOn: Thing,
method: Thing,
receivedContext: QLContext,
val definingContext: Option[QLContext],
paramsOpt: Option[Seq[QLParam]]
)(implicit
val ecology: Ecology
) extends Invocation
with EcologyMember {
lazy val Basic = interface[querki.basic.Basic]
lazy val Core = interface[querki.core.Core]
lazy val QL = interface[querki.ql.QL]
lazy val SignatureInternal = interface[SignatureInternal]
lazy val Tags = interface[querki.tags.Tags]
lazy val Types = interface[querki.types.Types]
lazy val displayName = invokedOn.displayName
lazy val ExactlyOne = Core.ExactlyOne
lazy val LinkType = Core.LinkType
implicit val inv = this
/**
* The signature for this function, which we use to extract specific params.
*/
lazy val sig = SignatureInternal.getSignature(method, context.state, paramsOpt)
def error[VT](
name: String,
params: String*
) = InvocationValueImpl[VT](PublicException(name, params: _*))
def test(
predicate: => Boolean,
errorName: String,
params: => Seq[Any]
): InvocationValue[Boolean] = {
if (predicate)
InvocationValueImpl(Some(true))
else
InvocationValueImpl(PublicException(errorName, params: _*))
}
def returnsType(pt: PType[_]): InvocationValue[Boolean] = {
InvocationValueImpl(IVMetadata(returnType = Some(pt)))
}
def preferCollection(coll: Collection): InvocationValue[Boolean] = {
InvocationValueImpl(IVMetadata(preferredColl = Some(coll)))
}
def preferDefiningContext: Invocation = {
definingContext match {
case Some(c) => this.copy(receivedContext = c)
case None => this.copy(definingContext = Some(receivedContext))
}
}
def contextTypeAs[T : ClassTag]: InvocationValue[T] = {
val clazz = implicitly[ClassTag[T]].runtimeClass
if (clazz.isInstance(context.value.pType))
InvocationValueImpl(Some(context.value.pType.asInstanceOf[T]))
else
error("Func.wrongType", displayName, context.value.pType.displayName)
}
def contextElements: InvocationValue[QLContext] = {
if (context.useCollection) {
InvocationValueImpl(Some(context))
} else {
val contexts = context.value.cv.map(elem => context.next(Core.ExactlyOne(elem)))
InvocationValueImpl(contexts)
}
}
def contextValue: InvocationValue[QValue] = {
InvocationValueImpl(Some(context.value))
}
def wrap[T](v: T): InvocationValue[T] = {
InvocationValueImpl(Some(v))
}
def fut[T](fut: Future[T]): InvocationValue[T] = {
InvocationValueImpl(this, fut.map(t => IVData(Some(t))))
}
def opt[T](
opt: Option[T],
errOpt: Option[PublicException] = None
): InvocationValue[T] = {
opt match {
case Some(v) => InvocationValueImpl(Some(v))
case None => {
errOpt match {
case Some(err) => InvocationValueImpl(err)
// No error specified if this isn't true, so we're simply passing Empty along:
case None => InvocationValueImpl(None)
}
}
}
}
def iter[T](
it: Iterable[T],
errOpt: Option[PublicException] = None
): InvocationValue[T] = {
errOpt match {
case Some(ex) => InvocationValueImpl(ex)
case None => InvocationValueImpl(it)
}
}
def contextFirstAs[VT](pt: PType[VT]): InvocationValue[VT] = {
context.value.firstAs(pt) match {
case Some(v) => InvocationValueImpl(Some(v))
case None => error("Func.notThing", displayName)
}
}
def contextAllAs[VT](pt: PType[VT]): InvocationValue[VT] = {
if (!context.value.matchesType(pt))
error("Func.notThing", displayName)
else {
val vs = context.value.flatMap(pt)(Some(_))
InvocationValueImpl(vs)
}
}
def contextAllAsList[VT](pt: PType[VT]): InvocationValue[List[VT]] = {
if (!context.value.matchesType(pt))
error("Func.notThing", displayName)
else {
val vs = Some(context.value.rawList(pt)) //context.value.flatMap(pt)(Some(_))
InvocationValueImpl(vs)
}
}
def contextFirstThing: InvocationValue[Thing] = {
contextFirstAs(Core.LinkType).flatMap { oid =>
state.anything(oid) match {
case Some(thing) => InvocationValueImpl(Some(thing))
case None => error("Func.unknownThing", displayName)
}
}
}
def contextAllThings(ctx: QLContext = context): InvocationValue[Thing] = {
if (ctx.value.matchesType(Core.UnknownType)) {
InvocationValueImpl(None)
} else if (!ctx.value.matchesType(Core.LinkType)) {
error("Func.notThing", displayName)
} else {
val ids = ctx.value.flatMap(Core.LinkType)(Some(_))
val thingsOpt = ids.map(state.anything(_))
if (thingsOpt.forall(_.isDefined))
InvocationValueImpl(thingsOpt.flatten)
else
error("Func.unknownThing", displayName)
}
}
def contextAllBundles: InvocationValue[PropertyBundle] = {
if (context.value.matchesType(Core.LinkType)) {
val ids = context.value.flatMap(Core.LinkType)(Some(_))
val thingsOpt = ids.map(state.anything(_))
if (thingsOpt.forall(_.isDefined))
InvocationValueImpl(thingsOpt.flatten)
else
error("Func.unknownThing", displayName)
} else if (context.value.matchesType(Core.UnknownType)) {
InvocationValueImpl(None)
} else context.value.pType match {
case mt: ModelTypeBase => {
val bundles = context.value.flatMap(mt)(Some(_))
InvocationValueImpl(bundles)
}
case _ => error("Func.notThing", displayName)
}
}
def contextBundlesAndContexts: InvocationValue[(PropertyBundle, QLContext)] = {
if (context.value.matchesType(Core.LinkType)) {
val ids = context.value.flatMap(Core.LinkType)(Some(_))
val thingsOpt = ids.map(state.anything(_))
if (thingsOpt.forall(_.isDefined))
InvocationValueImpl(thingsOpt.flatten.map(t => (t, context.next(Core.ExactlyOne(Core.LinkType(t))))))
else
error("Func.unknownThing", displayName)
} else if (context.value.matchesType(Core.UnknownType)) {
InvocationValueImpl(None)
} else context.value.pType match {
case mt: ModelTypeBase => {
val pairs = context.value.cv.map(elem => (elem.get(mt), context.next(Core.ExactlyOne(elem))))
InvocationValueImpl(pairs)
}
case _ => error("Func.notThing", displayName)
}
}
def bundlesAndContextsForProp(prop: Property[_, _]): InvocationValue[(PropertyBundle, QLContext)] = {
def wrapContexts(bundle: PropertyBundle): Iterable[(PropertyBundle, QLContext)] = {
context.value.cv.map(elem => (bundle, context.next(Core.ExactlyOne(elem))))
}
def withLexicalContext: Option[PropertyBundle] = {
for {
parser <- context.parser
lex <- parser.lexicalThing
} yield lex
}
// Note that the elemContexts returned here are the same as the bundles. It isn't strictly clear that
// that is correct -- conceptually, when we've walked back up the stack, we should be using the received
// context as the elemContexts, I think. But things get weirdly multiplicative when we do that, and I'm
// not sure how to correctly tame that.
def withCurrentContext(current: QLContext): Option[InvocationValue[(PropertyBundle, QLContext)]] = {
if (current.value.matchesType(Core.LinkType)) {
val ids = current.value.flatMap(Core.LinkType)(Some(_))
val thingsOpt = ids.map(state.anything(_))
val things = thingsOpt.flatten
val pairs = things.map(t => (t, context.next(Core.ExactlyOne(Core.LinkType(t)))))
if (things.exists(_.hasProp(prop)))
Some(InvocationValueImpl(pairs))
else
None
} else if (current.value.pType == Tags.NewTagSetType) {
// Tags do have one or two pseudo-properties, so we should turn them into pseudo-Things
// and treat them that way:
val tags = current.value.rawList(Tags.NewTagSetType)
val things = tags.map(tag => Tags.getTag(tag.text, state))
if (things.exists(_.hasPropLocal(prop))) {
// This Property exists on the Tag pseudo-Things, so return the pseudo-Things:
Some(InvocationValueImpl(things.map(t => (t, context.next(ExactlyOne(Tags.NewTagSetType(t.displayName)))))))
} else {
// Hmm. Do these Tags point to actual Things in the Space?
val realThings = tags.map(tag => state.anythingByName(tag.text)).flatten
if (realThings.exists(_.hasProp(prop))) {
// Yes, and some of those Things have this Property, so return those real Things:
Some(InvocationValueImpl(realThings.map(t => (t, context.next(ExactlyOne(LinkType(t)))))))
} else {
// Nope, these Tags just don't seem to have this Property. Note that we are intentionally treating this
// as legit, so that you can feed a mixed collection of defined and undefined Tags to a Property. This
// is different from UnknownNameType (below), which we are *always* treating as an error to feed to
// a Property.
None
}
}
} else if (current.value.pType == QL.UnknownNameType) {
// QI.9v5kemx: Unknown Names can't be used with Properties:
val tags = current.value.rawList(QL.UnknownNameType)
Some(InvocationValueImpl(Tags.tagPropError(tags.mkString(", "), prop.displayName)))
} else current.value.pType match {
case mt: ModelTypeBase => {
val pairs = current.value.cv.map(elem => (elem.get(mt), context.next(ExactlyOne(elem))))
if (pairs.exists(_._1.hasProp(prop)))
Some(InvocationValueImpl(pairs))
else
None
}
case _ => None
}
}
// Walk recursively back the Context chain, until we find one that was a Thing (that is, a LinkType), or
// we run out of Contexts. Note that we start with the one that was *already* tried, because we need to
// inject lexical checking into this pathway:
def walkNonThingContexts(previous: QLContext): InvocationValue[(PropertyBundle, QLContext)] = {
if (previous.parentOpt.isEmpty || previous.value.matchesType(LinkType)) {
// Either we hit the end of the chain, or we hit a Link -- either way, time to stop:
InvocationValueImpl(this, Future.successful(IVData(None, IVMetadata(returnType = Some(LinkType)))))
} else {
// Keep walking back up the chain, to see if we find something:
val current = previous.parent
withCurrentContext(current) match {
case Some(result) => result
case None => walkNonThingContexts(current)
}
}
}
if (definingContext.isDefined) {
// If there is a defining context, that is where we should be working from:
val result = for {
dc <- definingContext
id <- dc.value.firstAs(Core.LinkType)
thing <- state.anything(id)
} yield InvocationValueImpl(wrapContexts(thing))
result.getOrElse(error("Func.notThing", displayName))
} else {
// No defining context -- does the received context have the property?
withCurrentContext(context) match {
case Some(result) => result
case None => {
// Nope. Does the lexical context?
withLexicalContext match {
// IMPORTANT SUBTLETY: note that we're passing through the *bundle* of the lexical context, but the actual contexts are the received context!
case Some(bundle) if (bundle.hasProp(prop)) => InvocationValueImpl(wrapContexts(bundle))
case _ => {
context.value.pType match {
case mt: ModelTypeBase => {
// If this bundle is a Model Value, walk up the context chain.
walkNonThingContexts(context)
}
case _ => {
InvocationValueImpl(this, Future.successful(IVData(None, IVMetadata(returnType = Some(LinkType)))))
}
}
}
}
}
}
}
}
def definingContextAsProperty: InvocationValue[Property[_, _]] = {
definingContext match {
case Some(defining) => {
if (!defining.value.matchesType(Core.LinkType))
error("Func.notThing", displayName)
else {
val ids: Iterable[ThingId] = defining.value.flatMap(Core.LinkType)(oid => Some(AsOID(oid)))
val propOpts: Iterable[Option[Property[_, _]]] = ids.map(state.prop(_))
if (propOpts.forall(_.isDefined)) {
InvocationValueImpl(propOpts.flatten)
} else
error("Func.notProp", displayName)
}
}
case None => error("Func.missingDefiningContext", displayName)
}
}
def definingContextAsPropertyOf[VT](targetType: PType[VT]): InvocationValue[Property[VT, _]] = {
definingContext match {
case Some(defining) => {
if (!defining.value.matchesType(Core.LinkType))
error("Func.notThing", displayName)
else {
val ids: Iterable[ThingId] = defining.value.flatMap(Core.LinkType)(oid => Some(AsOID(oid)))
val propOpts: Iterable[Option[Property[VT, _]]] =
ids.map(state.prop(_).flatMap(prop => prop.confirmType(targetType)))
if (propOpts.forall(_.isDefined)) {
InvocationValueImpl(propOpts.flatten)
} else
error("Func.notProp", displayName)
}
}
case None => error("Func.missingDefiningContext", displayName)
}
}
def definingContextAsOptionalPropertyOf[VT](targetType: PType[VT]): InvocationValue[Option[Property[VT, _]]] = {
definingContext match {
case Some(defining) => {
if (!defining.value.matchesType(Core.LinkType))
error("Func.notThing", displayName)
else {
val ids: Iterable[ThingId] = defining.value.flatMap(Core.LinkType)(oid => Some(AsOID(oid)))
val propOpts: Iterable[Option[Property[VT, _]]] =
ids.map(state.prop(_).flatMap(prop => prop.confirmType(targetType)))
if (propOpts.forall(_.isDefined)) {
InvocationValueImpl(propOpts)
} else
error("Func.notProp", displayName)
}
}
case None => InvocationValueImpl(Some(None))
}
}
def processParamFrom(
name: String,
context: QLContext,
processContext: QLContext
): Future[QLContext] = {
sig.getParam(name).process(getProcessor(context), processContext)
}
def process(
name: String,
processContext: QLContext = context
): InvocationValue[QValue] = {
val resultFut = processParamFrom(name, context, processContext).flatMap { raw =>
val processed = raw.value
processed.firstAs(QL.ErrorTextType) match {
// If there was an error, keep the error, and stop processing:
case Some(errorText) => Future.failed(new PublicException("General.public", errorText.text))
case None => Future.successful(Some(processed))
}
}
InvocationValueImpl(inv, resultFut.map(IVData(_)))
}
private def processAsBase[VT](
name: String,
typeName: => String,
ret: QValue => Seq[VT],
processContext: QLContext = context
): InvocationValue[VT] = {
val resultFut = processParamFrom(name, context, processContext).flatMap { raw =>
val processed = raw.value
processed.firstAs(QL.ErrorTextType) match {
// If there was an error, keep the error, and stop processing:
case Some(errorText) => Future.failed(new PublicException("General.public", errorText))
case None => {
try {
Future.successful(ret(processed))
} catch {
case ex: Exception => Future.failed(PublicException(
"Func.paramWrongType",
displayName,
name,
typeName,
processed.pType.displayName
))
}
}
}
}
InvocationValueImpl(inv, resultFut.map(IVData(_)))
}
def processAs[VT](
name: String,
pt: PType[VT],
processContext: QLContext = context
): InvocationValue[VT] = {
processAsBase(name, pt.displayName, (_.rawList(pt)), processContext)
}
def processAsOpt[VT](
name: String,
pt: PType[VT],
processContext: QLContext = context
): InvocationValue[Option[VT]] = {
processAsBase(name, pt.displayName, (qv => Some(qv.firstAs(pt)).toSeq), processContext)
}
def processAsList[VT](
name: String,
pt: PType[VT],
processContext: QLContext = context
): InvocationValue[List[VT]] = {
processAsBase(name, pt.displayName, (qv => List(qv.rawList(pt))), processContext)
}
def rawParam(name: String): InvocationValue[Option[QLExp]] = {
InvocationValueImpl(inv, Future.successful(IVData(Some(sig.getParam(name).exp))))
}
def rawRequiredParam(name: String): InvocationValue[QLExp] = {
sig.getParam(name).exp match {
case Some(exp) => InvocationValueImpl(inv, Future.successful(IVData(Some(exp))))
case None => error("Func.missingNamedParam", displayName, name)
}
}
def getProcessor(context: QLContext): QLProcessor = {
context.parser.map(_.processor).getOrElse(new QLProcessor(context))
}
def processExp(
exp: QLExp,
context: QLContext,
processContext: QLContext
): Future[QLContext] = {
getProcessor(context).processExp(exp, processContext)
}
def processParam(
paramNum: Int,
processContext: QLContext = context
): InvocationValue[QValue] = {
paramsOpt match {
case Some(params) if (params.length >= (paramNum + 1)) => {
val resultFut = processExp(params(paramNum).exp, context, processContext).flatMap { raw =>
val processed = raw.value
processed.firstAs(QL.ErrorTextType) match {
// If there was an error, keep the error, and stop processing:
case Some(errorText) => Future.failed(new PublicException("General.public", errorText))
case None => Future.successful(Some(processed))
}
}
InvocationValueImpl(inv, resultFut.map(IVData(_)))
}
case _ => error("Func.missingParam", displayName)
}
}
private def processParamFirstGuts[VT](
paramNum: Int,
pt: PType[VT],
processContext: QLContext = context
)(
onEmpty: => Future[Iterable[VT]]
): InvocationValue[VT] = {
paramsOpt match {
case Some(params) if (params.length >= (paramNum + 1)) => {
val resultFut: Future[Iterable[VT]] =
processExp(params(paramNum).exp, context, processContext).flatMap { raw =>
val processed = raw.value
if (processed.isEmpty)
onEmpty
else processed.firstAs(QL.ErrorTextType) match {
case Some(errorText) => Future.failed(new PublicException("General.public", errorText))
case None => processed.firstAs(pt) match {
case Some(v) => Future.successful(Some(v))
case None => Future.failed(PublicException(
"Func.paramWrongType",
displayName,
paramNum.toString,
pt.displayName,
processed.pType.displayName
))
}
}
}
InvocationValueImpl(inv, resultFut.map(IVData(_)))
}
case _ => error("Func.missingParam", displayName)
}
}
def processParamFirstAs[VT](
paramNum: Int,
pt: PType[VT],
processContext: QLContext = context
): InvocationValue[VT] = {
processParamFirstGuts(paramNum, pt, processContext) {
Future.failed(PublicException("Func.emptyParamValue", displayName))
}
}
def processParamFirstOr[VT](
paramNum: Int,
pt: PType[VT],
default: VT,
processContext: QLContext = context
): InvocationValue[VT] = {
paramsOpt match {
case Some(params) if (params.length >= (paramNum + 1)) =>
processParamFirstGuts(paramNum, pt, processContext) {
// Iff the result of the param was empty, return the default
Future(Some(default))
}
case _ => wrap(default)
}
}
def processParamNofM(
paramNum: Int,
expectedParams: Int,
processContext: QLContext = context
): InvocationValue[QValue] = {
if (numParams < (expectedParams - 1))
InvocationValueImpl(new PublicException("Func.insufficientParams", displayName, (expectedParams - 1)))
else {
if (numParams >= expectedParams)
processParam(paramNum, processContext)
else if (paramNum == 0)
contextValue
else
processParam(paramNum - 1, processContext)
}
}
def rawParam(paramNum: Int): InvocationValue[QLExp] = {
paramsOpt match {
case Some(params) if (params.length >= (paramNum - 1)) => InvocationValueImpl(Some(params(paramNum).exp))
case _ => error("Func.missingParam", displayName)
}
}
def WarningValue(msg: String) = QL.WarningValue(msg)
/**
* The "primary" context of this invocation. This is an exact synonym for receivedContext, and is the
* one you usually care about.
*/
def context: QLContext = receivedContext
implicit lazy val state: SpaceState = {
val param = sig.getParam("_space")
param.exp match {
case Some(exp) => {
// HACK: is there any decent way around this? We don't really want to force inv.state to
// always be a Future, and 99.99% of the time when we use _space it's going to be synchronous,
// but we can't actually guarantee that. Hmm. Is there any way to force synchrony here -- to
// only allow synchronous functions?
val processed = awaitHack(param.process(getProcessor(context), context)).value
processed.firstAs(LinkType) match {
case Some(link) => {
context.state.getApp(link).getOrElse(throw new PublicException("QL.invocation.notASpace"))
}
case _ => throw new PublicException("QL.invocation.notASpace")
}
}
// The normal case: use the current context's Space:
case _ => context.state
}
}
def parser = context.parser
def lexicalThing = parser.flatMap(_.lexicalThing)
def numParams: Int = paramsOpt match {
case Some(params) => params.length
case None => 0
}
}