value.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014
  1. package otto
  2. import (
  3. "fmt"
  4. "math"
  5. "reflect"
  6. "strconv"
  7. "unicode/utf16"
  8. )
  9. type _valueKind int
  10. const (
  11. valueUndefined _valueKind = iota
  12. valueNull
  13. valueNumber
  14. valueString
  15. valueBoolean
  16. valueObject
  17. // These are invalid outside of the runtime
  18. valueEmpty
  19. valueResult
  20. valueReference
  21. )
  22. // Value is the representation of a JavaScript value.
  23. type Value struct {
  24. kind _valueKind
  25. value interface{}
  26. }
  27. func (value Value) safe() bool {
  28. return value.kind < valueEmpty
  29. }
  30. var (
  31. emptyValue = Value{kind: valueEmpty}
  32. nullValue = Value{kind: valueNull}
  33. falseValue = Value{kind: valueBoolean, value: false}
  34. trueValue = Value{kind: valueBoolean, value: true}
  35. )
  36. // ToValue will convert an interface{} value to a value digestible by otto/JavaScript
  37. //
  38. // This function will not work for advanced types (struct, map, slice/array, etc.) and
  39. // you should use Otto.ToValue instead.
  40. func ToValue(value interface{}) (Value, error) {
  41. result := Value{}
  42. err := catchPanic(func() {
  43. result = toValue(value)
  44. })
  45. return result, err
  46. }
  47. func (value Value) isEmpty() bool {
  48. return value.kind == valueEmpty
  49. }
  50. // Undefined
  51. // UndefinedValue will return a Value representing undefined.
  52. func UndefinedValue() Value {
  53. return Value{}
  54. }
  55. // IsDefined will return false if the value is undefined, and true otherwise.
  56. func (value Value) IsDefined() bool {
  57. return value.kind != valueUndefined
  58. }
  59. // IsUndefined will return true if the value is undefined, and false otherwise.
  60. func (value Value) IsUndefined() bool {
  61. return value.kind == valueUndefined
  62. }
  63. // NullValue will return a Value representing null.
  64. func NullValue() Value {
  65. return Value{kind: valueNull}
  66. }
  67. // IsNull will return true if the value is null, and false otherwise.
  68. func (value Value) IsNull() bool {
  69. return value.kind == valueNull
  70. }
  71. // ---
  72. func (value Value) isCallable() bool {
  73. v, ok := value.value.(*_object)
  74. return ok && v.isCall()
  75. }
  76. // Call the value as a function with the given this value and argument list and
  77. // return the result of invocation. It is essentially equivalent to:
  78. //
  79. // value.apply(thisValue, argumentList)
  80. //
  81. // An undefined value and an error will result if:
  82. //
  83. // 1. There is an error during conversion of the argument list
  84. // 2. The value is not actually a function
  85. // 3. An (uncaught) exception is thrown
  86. //
  87. func (value Value) Call(this Value, argumentList ...interface{}) (Value, error) {
  88. result := Value{}
  89. err := catchPanic(func() {
  90. // FIXME
  91. result = value.call(nil, this, argumentList...)
  92. })
  93. if !value.safe() {
  94. value = Value{}
  95. }
  96. return result, err
  97. }
  98. func (value Value) call(rt *_runtime, this Value, argumentList ...interface{}) Value {
  99. if function, ok := value.value.(*_object); ok {
  100. return function.call(this, function.runtime.toValueArray(argumentList...), false, nativeFrame)
  101. }
  102. if rt == nil {
  103. panic("FIXME TypeError")
  104. }
  105. panic(rt.panicTypeError())
  106. }
  107. func (value Value) constructSafe(rt *_runtime, this Value, argumentList ...interface{}) (Value, error) {
  108. result := Value{}
  109. err := catchPanic(func() {
  110. result = value.construct(rt, this, argumentList...)
  111. })
  112. return result, err
  113. }
  114. func (value Value) construct(rt *_runtime, this Value, argumentList ...interface{}) Value {
  115. if fn, ok := value.value.(*_object); ok {
  116. return fn.construct(fn.runtime.toValueArray(argumentList...))
  117. }
  118. if rt == nil {
  119. panic("FIXME TypeError")
  120. }
  121. panic(rt.panicTypeError())
  122. }
  123. // IsPrimitive will return true if value is a primitive (any kind of primitive).
  124. func (value Value) IsPrimitive() bool {
  125. return !value.IsObject()
  126. }
  127. // IsBoolean will return true if value is a boolean (primitive).
  128. func (value Value) IsBoolean() bool {
  129. return value.kind == valueBoolean
  130. }
  131. // IsNumber will return true if value is a number (primitive).
  132. func (value Value) IsNumber() bool {
  133. return value.kind == valueNumber
  134. }
  135. // IsNaN will return true if value is NaN (or would convert to NaN).
  136. func (value Value) IsNaN() bool {
  137. switch value := value.value.(type) {
  138. case float64:
  139. return math.IsNaN(value)
  140. case float32:
  141. return math.IsNaN(float64(value))
  142. case int, int8, int32, int64:
  143. return false
  144. case uint, uint8, uint32, uint64:
  145. return false
  146. }
  147. return math.IsNaN(value.float64())
  148. }
  149. // IsString will return true if value is a string (primitive).
  150. func (value Value) IsString() bool {
  151. return value.kind == valueString
  152. }
  153. // IsObject will return true if value is an object.
  154. func (value Value) IsObject() bool {
  155. return value.kind == valueObject
  156. }
  157. // IsFunction will return true if value is a function.
  158. func (value Value) IsFunction() bool {
  159. if value.kind != valueObject {
  160. return false
  161. }
  162. return value.value.(*_object).class == classFunction
  163. }
  164. // Class will return the class string of the value or the empty string if value is not an object.
  165. //
  166. // The return value will (generally) be one of:
  167. //
  168. // Object
  169. // Function
  170. // Array
  171. // String
  172. // Number
  173. // Boolean
  174. // Date
  175. // RegExp
  176. //
  177. func (value Value) Class() string {
  178. if value.kind != valueObject {
  179. return ""
  180. }
  181. return value.value.(*_object).class
  182. }
  183. func (value Value) isArray() bool {
  184. if value.kind != valueObject {
  185. return false
  186. }
  187. return isArray(value.value.(*_object))
  188. }
  189. func (value Value) isStringObject() bool {
  190. if value.kind != valueObject {
  191. return false
  192. }
  193. return value.value.(*_object).class == classString
  194. }
  195. func (value Value) isBooleanObject() bool {
  196. if value.kind != valueObject {
  197. return false
  198. }
  199. return value.value.(*_object).class == classBoolean
  200. }
  201. func (value Value) isNumberObject() bool {
  202. if value.kind != valueObject {
  203. return false
  204. }
  205. return value.value.(*_object).class == classNumber
  206. }
  207. func (value Value) isDate() bool {
  208. if value.kind != valueObject {
  209. return false
  210. }
  211. return value.value.(*_object).class == classDate
  212. }
  213. func (value Value) isRegExp() bool {
  214. if value.kind != valueObject {
  215. return false
  216. }
  217. return value.value.(*_object).class == classRegExp
  218. }
  219. func (value Value) isError() bool {
  220. if value.kind != valueObject {
  221. return false
  222. }
  223. return value.value.(*_object).class == classError
  224. }
  225. // ---
  226. func toValue_reflectValuePanic(value interface{}, kind reflect.Kind) {
  227. // FIXME?
  228. switch kind {
  229. case reflect.Struct:
  230. panic(newError(nil, "TypeError", 0, "invalid value (struct): missing runtime: %v (%T)", value, value))
  231. case reflect.Map:
  232. panic(newError(nil, "TypeError", 0, "invalid value (map): missing runtime: %v (%T)", value, value))
  233. case reflect.Slice:
  234. panic(newError(nil, "TypeError", 0, "invalid value (slice): missing runtime: %v (%T)", value, value))
  235. }
  236. }
  237. func toValue(value interface{}) Value {
  238. switch value := value.(type) {
  239. case Value:
  240. return value
  241. case bool:
  242. return Value{valueBoolean, value}
  243. case int:
  244. return Value{valueNumber, value}
  245. case int8:
  246. return Value{valueNumber, value}
  247. case int16:
  248. return Value{valueNumber, value}
  249. case int32:
  250. return Value{valueNumber, value}
  251. case int64:
  252. return Value{valueNumber, value}
  253. case uint:
  254. return Value{valueNumber, value}
  255. case uint8:
  256. return Value{valueNumber, value}
  257. case uint16:
  258. return Value{valueNumber, value}
  259. case uint32:
  260. return Value{valueNumber, value}
  261. case uint64:
  262. return Value{valueNumber, value}
  263. case float32:
  264. return Value{valueNumber, float64(value)}
  265. case float64:
  266. return Value{valueNumber, value}
  267. case []uint16:
  268. return Value{valueString, value}
  269. case string:
  270. return Value{valueString, value}
  271. // A rune is actually an int32, which is handled above
  272. case *_object:
  273. return Value{valueObject, value}
  274. case *Object:
  275. return Value{valueObject, value.object}
  276. case Object:
  277. return Value{valueObject, value.object}
  278. case _reference: // reference is an interface (already a pointer)
  279. return Value{valueReference, value}
  280. case _result:
  281. return Value{valueResult, value}
  282. case nil:
  283. // TODO Ugh.
  284. return Value{}
  285. case reflect.Value:
  286. for value.Kind() == reflect.Ptr {
  287. // We were given a pointer, so we'll drill down until we get a non-pointer
  288. //
  289. // These semantics might change if we want to start supporting pointers to values transparently
  290. // (It would be best not to depend on this behavior)
  291. // FIXME: UNDEFINED
  292. if value.IsNil() {
  293. return Value{}
  294. }
  295. value = value.Elem()
  296. }
  297. switch value.Kind() {
  298. case reflect.Bool:
  299. return Value{valueBoolean, bool(value.Bool())}
  300. case reflect.Int:
  301. return Value{valueNumber, int(value.Int())}
  302. case reflect.Int8:
  303. return Value{valueNumber, int8(value.Int())}
  304. case reflect.Int16:
  305. return Value{valueNumber, int16(value.Int())}
  306. case reflect.Int32:
  307. return Value{valueNumber, int32(value.Int())}
  308. case reflect.Int64:
  309. return Value{valueNumber, int64(value.Int())}
  310. case reflect.Uint:
  311. return Value{valueNumber, uint(value.Uint())}
  312. case reflect.Uint8:
  313. return Value{valueNumber, uint8(value.Uint())}
  314. case reflect.Uint16:
  315. return Value{valueNumber, uint16(value.Uint())}
  316. case reflect.Uint32:
  317. return Value{valueNumber, uint32(value.Uint())}
  318. case reflect.Uint64:
  319. return Value{valueNumber, uint64(value.Uint())}
  320. case reflect.Float32:
  321. return Value{valueNumber, float32(value.Float())}
  322. case reflect.Float64:
  323. return Value{valueNumber, float64(value.Float())}
  324. case reflect.String:
  325. return Value{valueString, string(value.String())}
  326. default:
  327. toValue_reflectValuePanic(value.Interface(), value.Kind())
  328. }
  329. default:
  330. return toValue(reflect.ValueOf(value))
  331. }
  332. // FIXME?
  333. panic(newError(nil, "TypeError", 0, "invalid value: %v (%T)", value, value))
  334. }
  335. // String will return the value as a string.
  336. //
  337. // This method will make return the empty string if there is an error.
  338. func (value Value) String() string {
  339. result := ""
  340. catchPanic(func() {
  341. result = value.string()
  342. })
  343. return result
  344. }
  345. // ToBoolean will convert the value to a boolean (bool).
  346. //
  347. // ToValue(0).ToBoolean() => false
  348. // ToValue("").ToBoolean() => false
  349. // ToValue(true).ToBoolean() => true
  350. // ToValue(1).ToBoolean() => true
  351. // ToValue("Nothing happens").ToBoolean() => true
  352. //
  353. // If there is an error during the conversion process (like an uncaught exception), then the result will be false and an error.
  354. func (value Value) ToBoolean() (bool, error) {
  355. result := false
  356. err := catchPanic(func() {
  357. result = value.bool()
  358. })
  359. return result, err
  360. }
  361. func (value Value) numberValue() Value {
  362. if value.kind == valueNumber {
  363. return value
  364. }
  365. return Value{valueNumber, value.float64()}
  366. }
  367. // ToFloat will convert the value to a number (float64).
  368. //
  369. // ToValue(0).ToFloat() => 0.
  370. // ToValue(1.1).ToFloat() => 1.1
  371. // ToValue("11").ToFloat() => 11.
  372. //
  373. // If there is an error during the conversion process (like an uncaught exception), then the result will be 0 and an error.
  374. func (value Value) ToFloat() (float64, error) {
  375. result := float64(0)
  376. err := catchPanic(func() {
  377. result = value.float64()
  378. })
  379. return result, err
  380. }
  381. // ToInteger will convert the value to a number (int64).
  382. //
  383. // ToValue(0).ToInteger() => 0
  384. // ToValue(1.1).ToInteger() => 1
  385. // ToValue("11").ToInteger() => 11
  386. //
  387. // If there is an error during the conversion process (like an uncaught exception), then the result will be 0 and an error.
  388. func (value Value) ToInteger() (int64, error) {
  389. result := int64(0)
  390. err := catchPanic(func() {
  391. result = value.number().int64
  392. })
  393. return result, err
  394. }
  395. // ToString will convert the value to a string (string).
  396. //
  397. // ToValue(0).ToString() => "0"
  398. // ToValue(false).ToString() => "false"
  399. // ToValue(1.1).ToString() => "1.1"
  400. // ToValue("11").ToString() => "11"
  401. // ToValue('Nothing happens.').ToString() => "Nothing happens."
  402. //
  403. // If there is an error during the conversion process (like an uncaught exception), then the result will be the empty string ("") and an error.
  404. func (value Value) ToString() (string, error) {
  405. result := ""
  406. err := catchPanic(func() {
  407. result = value.string()
  408. })
  409. return result, err
  410. }
  411. func (value Value) _object() *_object {
  412. if v, ok := value.value.(*_object); ok {
  413. return v
  414. }
  415. return nil
  416. }
  417. // Object will return the object of the value, or nil if value is not an object.
  418. //
  419. // This method will not do any implicit conversion. For example, calling this method on a string primitive value will not return a String object.
  420. func (value Value) Object() *Object {
  421. if object, ok := value.value.(*_object); ok {
  422. return _newObject(object, value)
  423. }
  424. return nil
  425. }
  426. func (value Value) reference() _reference {
  427. if value, ok := value.value.(_reference); ok {
  428. return value
  429. }
  430. return nil
  431. }
  432. func (value Value) resolve() Value {
  433. if value, ok := value.value.(_reference); ok {
  434. return value.getValue()
  435. }
  436. return value
  437. }
  438. var (
  439. __NaN__ float64 = math.NaN()
  440. __PositiveInfinity__ float64 = math.Inf(+1)
  441. __NegativeInfinity__ float64 = math.Inf(-1)
  442. __PositiveZero__ float64 = 0
  443. __NegativeZero__ float64 = math.Float64frombits(0 | (1 << 63))
  444. )
  445. func positiveZero() float64 {
  446. return __PositiveZero__
  447. }
  448. func negativeZero() float64 {
  449. return __NegativeZero__
  450. }
  451. // NaNValue will return a value representing NaN.
  452. //
  453. // It is equivalent to:
  454. //
  455. // ToValue(math.NaN())
  456. //
  457. func NaNValue() Value {
  458. return Value{valueNumber, __NaN__}
  459. }
  460. func positiveInfinityValue() Value {
  461. return Value{valueNumber, __PositiveInfinity__}
  462. }
  463. func negativeInfinityValue() Value {
  464. return Value{valueNumber, __NegativeInfinity__}
  465. }
  466. func positiveZeroValue() Value {
  467. return Value{valueNumber, __PositiveZero__}
  468. }
  469. func negativeZeroValue() Value {
  470. return Value{valueNumber, __NegativeZero__}
  471. }
  472. // TrueValue will return a value representing true.
  473. //
  474. // It is equivalent to:
  475. //
  476. // ToValue(true)
  477. //
  478. func TrueValue() Value {
  479. return Value{valueBoolean, true}
  480. }
  481. // FalseValue will return a value representing false.
  482. //
  483. // It is equivalent to:
  484. //
  485. // ToValue(false)
  486. //
  487. func FalseValue() Value {
  488. return Value{valueBoolean, false}
  489. }
  490. func sameValue(x Value, y Value) bool {
  491. if x.kind != y.kind {
  492. return false
  493. }
  494. switch x.kind {
  495. case valueUndefined, valueNull:
  496. return true
  497. case valueNumber:
  498. x := x.float64()
  499. y := y.float64()
  500. if math.IsNaN(x) && math.IsNaN(y) {
  501. return true
  502. }
  503. if x == y {
  504. if x == 0 {
  505. // Since +0 != -0
  506. return math.Signbit(x) == math.Signbit(y)
  507. }
  508. return true
  509. }
  510. return false
  511. case valueString:
  512. return x.string() == y.string()
  513. case valueBoolean:
  514. return x.bool() == y.bool()
  515. case valueObject:
  516. return x._object() == y._object()
  517. default:
  518. panic(hereBeDragons())
  519. }
  520. }
  521. func strictEqualityComparison(x Value, y Value) bool {
  522. if x.kind != y.kind {
  523. return false
  524. }
  525. switch x.kind {
  526. case valueUndefined, valueNull:
  527. return true
  528. case valueNumber:
  529. x := x.float64()
  530. y := y.float64()
  531. if math.IsNaN(x) && math.IsNaN(y) {
  532. return false
  533. }
  534. return x == y
  535. case valueString:
  536. return x.string() == y.string()
  537. case valueBoolean:
  538. return x.bool() == y.bool()
  539. case valueObject:
  540. return x._object() == y._object()
  541. default:
  542. panic(hereBeDragons())
  543. }
  544. }
  545. // Export will attempt to convert the value to a Go representation
  546. // and return it via an interface{} kind.
  547. //
  548. // Export returns an error, but it will always be nil. It is present
  549. // for backwards compatibility.
  550. //
  551. // If a reasonable conversion is not possible, then the original
  552. // value is returned.
  553. //
  554. // undefined -> nil (FIXME?: Should be Value{})
  555. // null -> nil
  556. // boolean -> bool
  557. // number -> A number type (int, float32, uint64, ...)
  558. // string -> string
  559. // Array -> []interface{}
  560. // Object -> map[string]interface{}
  561. //
  562. func (self Value) Export() (interface{}, error) {
  563. return self.export(), nil
  564. }
  565. func (self Value) export() interface{} {
  566. switch self.kind {
  567. case valueUndefined:
  568. return nil
  569. case valueNull:
  570. return nil
  571. case valueNumber, valueBoolean:
  572. return self.value
  573. case valueString:
  574. switch value := self.value.(type) {
  575. case string:
  576. return value
  577. case []uint16:
  578. return string(utf16.Decode(value))
  579. }
  580. case valueObject:
  581. object := self._object()
  582. switch value := object.value.(type) {
  583. case *_goStructObject:
  584. return value.value.Interface()
  585. case *_goMapObject:
  586. return value.value.Interface()
  587. case *_goArrayObject:
  588. return value.value.Interface()
  589. case *_goSliceObject:
  590. return value.value.Interface()
  591. }
  592. if object.class == classArray {
  593. result := make([]interface{}, 0)
  594. lengthValue := object.get(propertyLength)
  595. length := lengthValue.value.(uint32)
  596. kind := reflect.Invalid
  597. state := 0
  598. var t reflect.Type
  599. for index := uint32(0); index < length; index += 1 {
  600. name := strconv.FormatInt(int64(index), 10)
  601. if !object.hasProperty(name) {
  602. continue
  603. }
  604. value := object.get(name).export()
  605. t = reflect.TypeOf(value)
  606. var k reflect.Kind
  607. if t != nil {
  608. k = t.Kind()
  609. }
  610. if state == 0 {
  611. kind = k
  612. state = 1
  613. } else if state == 1 && kind != k {
  614. state = 2
  615. }
  616. result = append(result, value)
  617. }
  618. if state != 1 || kind == reflect.Interface || t == nil {
  619. // No common type
  620. return result
  621. }
  622. // Convert to the common type
  623. val := reflect.MakeSlice(reflect.SliceOf(t), len(result), len(result))
  624. for i, v := range result {
  625. val.Index(i).Set(reflect.ValueOf(v))
  626. }
  627. return val.Interface()
  628. } else {
  629. result := make(map[string]interface{})
  630. // TODO Should we export everything? Or just what is enumerable?
  631. object.enumerate(false, func(name string) bool {
  632. value := object.get(name)
  633. if value.IsDefined() {
  634. result[name] = value.export()
  635. }
  636. return true
  637. })
  638. return result
  639. }
  640. }
  641. if self.safe() {
  642. return self
  643. }
  644. return Value{}
  645. }
  646. func (self Value) evaluateBreakContinue(labels []string) _resultKind {
  647. result := self.value.(_result)
  648. if result.kind == resultBreak || result.kind == resultContinue {
  649. for _, label := range labels {
  650. if label == result.target {
  651. return result.kind
  652. }
  653. }
  654. }
  655. return resultReturn
  656. }
  657. func (self Value) evaluateBreak(labels []string) _resultKind {
  658. result := self.value.(_result)
  659. if result.kind == resultBreak {
  660. for _, label := range labels {
  661. if label == result.target {
  662. return result.kind
  663. }
  664. }
  665. }
  666. return resultReturn
  667. }
  668. func (self Value) exportNative() interface{} {
  669. switch self.kind {
  670. case valueUndefined:
  671. return self
  672. case valueNull:
  673. return nil
  674. case valueNumber, valueBoolean:
  675. return self.value
  676. case valueString:
  677. switch value := self.value.(type) {
  678. case string:
  679. return value
  680. case []uint16:
  681. return string(utf16.Decode(value))
  682. }
  683. case valueObject:
  684. object := self._object()
  685. switch value := object.value.(type) {
  686. case *_goStructObject:
  687. return value.value.Interface()
  688. case *_goMapObject:
  689. return value.value.Interface()
  690. case *_goArrayObject:
  691. return value.value.Interface()
  692. case *_goSliceObject:
  693. return value.value.Interface()
  694. }
  695. }
  696. return self
  697. }
  698. // Make a best effort to return a reflect.Value corresponding to reflect.Kind, but
  699. // fallback to just returning the Go value we have handy.
  700. func (value Value) toReflectValue(kind reflect.Kind) (reflect.Value, error) {
  701. if kind != reflect.Float32 && kind != reflect.Float64 && kind != reflect.Interface {
  702. switch value := value.value.(type) {
  703. case float32:
  704. _, frac := math.Modf(float64(value))
  705. if frac > 0 {
  706. return reflect.Value{}, fmt.Errorf("RangeError: %v to reflect.Kind: %v", value, kind)
  707. }
  708. case float64:
  709. _, frac := math.Modf(value)
  710. if frac > 0 {
  711. return reflect.Value{}, fmt.Errorf("RangeError: %v to reflect.Kind: %v", value, kind)
  712. }
  713. }
  714. }
  715. switch kind {
  716. case reflect.Bool: // Bool
  717. return reflect.ValueOf(value.bool()), nil
  718. case reflect.Int: // Int
  719. // We convert to float64 here because converting to int64 will not tell us
  720. // if a value is outside the range of int64
  721. tmp := toIntegerFloat(value)
  722. if tmp < float_minInt || tmp > float_maxInt {
  723. return reflect.Value{}, fmt.Errorf("RangeError: %f (%v) to int", tmp, value)
  724. } else {
  725. return reflect.ValueOf(int(tmp)), nil
  726. }
  727. case reflect.Int8: // Int8
  728. tmp := value.number().int64
  729. if tmp < int64_minInt8 || tmp > int64_maxInt8 {
  730. return reflect.Value{}, fmt.Errorf("RangeError: %d (%v) to int8", tmp, value)
  731. } else {
  732. return reflect.ValueOf(int8(tmp)), nil
  733. }
  734. case reflect.Int16: // Int16
  735. tmp := value.number().int64
  736. if tmp < int64_minInt16 || tmp > int64_maxInt16 {
  737. return reflect.Value{}, fmt.Errorf("RangeError: %d (%v) to int16", tmp, value)
  738. } else {
  739. return reflect.ValueOf(int16(tmp)), nil
  740. }
  741. case reflect.Int32: // Int32
  742. tmp := value.number().int64
  743. if tmp < int64_minInt32 || tmp > int64_maxInt32 {
  744. return reflect.Value{}, fmt.Errorf("RangeError: %d (%v) to int32", tmp, value)
  745. } else {
  746. return reflect.ValueOf(int32(tmp)), nil
  747. }
  748. case reflect.Int64: // Int64
  749. // We convert to float64 here because converting to int64 will not tell us
  750. // if a value is outside the range of int64
  751. tmp := toIntegerFloat(value)
  752. if tmp < float_minInt64 || tmp > float_maxInt64 {
  753. return reflect.Value{}, fmt.Errorf("RangeError: %f (%v) to int", tmp, value)
  754. } else {
  755. return reflect.ValueOf(int64(tmp)), nil
  756. }
  757. case reflect.Uint: // Uint
  758. // We convert to float64 here because converting to int64 will not tell us
  759. // if a value is outside the range of uint
  760. tmp := toIntegerFloat(value)
  761. if tmp < 0 || tmp > float_maxUint {
  762. return reflect.Value{}, fmt.Errorf("RangeError: %f (%v) to uint", tmp, value)
  763. } else {
  764. return reflect.ValueOf(uint(tmp)), nil
  765. }
  766. case reflect.Uint8: // Uint8
  767. tmp := value.number().int64
  768. if tmp < 0 || tmp > int64_maxUint8 {
  769. return reflect.Value{}, fmt.Errorf("RangeError: %d (%v) to uint8", tmp, value)
  770. } else {
  771. return reflect.ValueOf(uint8(tmp)), nil
  772. }
  773. case reflect.Uint16: // Uint16
  774. tmp := value.number().int64
  775. if tmp < 0 || tmp > int64_maxUint16 {
  776. return reflect.Value{}, fmt.Errorf("RangeError: %d (%v) to uint16", tmp, value)
  777. } else {
  778. return reflect.ValueOf(uint16(tmp)), nil
  779. }
  780. case reflect.Uint32: // Uint32
  781. tmp := value.number().int64
  782. if tmp < 0 || tmp > int64_maxUint32 {
  783. return reflect.Value{}, fmt.Errorf("RangeError: %d (%v) to uint32", tmp, value)
  784. } else {
  785. return reflect.ValueOf(uint32(tmp)), nil
  786. }
  787. case reflect.Uint64: // Uint64
  788. // We convert to float64 here because converting to int64 will not tell us
  789. // if a value is outside the range of uint64
  790. tmp := toIntegerFloat(value)
  791. if tmp < 0 || tmp > float_maxUint64 {
  792. return reflect.Value{}, fmt.Errorf("RangeError: %f (%v) to uint64", tmp, value)
  793. } else {
  794. return reflect.ValueOf(uint64(tmp)), nil
  795. }
  796. case reflect.Float32: // Float32
  797. tmp := value.float64()
  798. tmp1 := tmp
  799. if 0 > tmp1 {
  800. tmp1 = -tmp1
  801. }
  802. if tmp1 > 0 && (tmp1 < math.SmallestNonzeroFloat32 || tmp1 > math.MaxFloat32) {
  803. return reflect.Value{}, fmt.Errorf("RangeError: %f (%v) to float32", tmp, value)
  804. } else {
  805. return reflect.ValueOf(float32(tmp)), nil
  806. }
  807. case reflect.Float64: // Float64
  808. value := value.float64()
  809. return reflect.ValueOf(float64(value)), nil
  810. case reflect.String: // String
  811. return reflect.ValueOf(value.string()), nil
  812. case reflect.Invalid: // Invalid
  813. case reflect.Complex64: // FIXME? Complex64
  814. case reflect.Complex128: // FIXME? Complex128
  815. case reflect.Chan: // FIXME? Chan
  816. case reflect.Func: // FIXME? Func
  817. case reflect.Ptr: // FIXME? Ptr
  818. case reflect.UnsafePointer: // FIXME? UnsafePointer
  819. default:
  820. switch value.kind {
  821. case valueObject:
  822. object := value._object()
  823. switch vl := object.value.(type) {
  824. case *_goStructObject: // Struct
  825. return reflect.ValueOf(vl.value.Interface()), nil
  826. case *_goMapObject: // Map
  827. return reflect.ValueOf(vl.value.Interface()), nil
  828. case *_goArrayObject: // Array
  829. return reflect.ValueOf(vl.value.Interface()), nil
  830. case *_goSliceObject: // Slice
  831. return reflect.ValueOf(vl.value.Interface()), nil
  832. }
  833. return reflect.ValueOf(value.exportNative()), nil
  834. case valueEmpty, valueResult, valueReference:
  835. // These are invalid, and should panic
  836. default:
  837. return reflect.ValueOf(value.value), nil
  838. }
  839. }
  840. // FIXME Should this end up as a TypeError?
  841. panic(fmt.Errorf("invalid conversion of %v (%v) to reflect.Kind: %v", value.kind, value, kind))
  842. }
  843. func stringToReflectValue(value string, kind reflect.Kind) (reflect.Value, error) {
  844. switch kind {
  845. case reflect.Bool:
  846. value, err := strconv.ParseBool(value)
  847. if err != nil {
  848. return reflect.Value{}, err
  849. }
  850. return reflect.ValueOf(value), nil
  851. case reflect.Int:
  852. value, err := strconv.ParseInt(value, 0, 0)
  853. if err != nil {
  854. return reflect.Value{}, err
  855. }
  856. return reflect.ValueOf(int(value)), nil
  857. case reflect.Int8:
  858. value, err := strconv.ParseInt(value, 0, 8)
  859. if err != nil {
  860. return reflect.Value{}, err
  861. }
  862. return reflect.ValueOf(int8(value)), nil
  863. case reflect.Int16:
  864. value, err := strconv.ParseInt(value, 0, 16)
  865. if err != nil {
  866. return reflect.Value{}, err
  867. }
  868. return reflect.ValueOf(int16(value)), nil
  869. case reflect.Int32:
  870. value, err := strconv.ParseInt(value, 0, 32)
  871. if err != nil {
  872. return reflect.Value{}, err
  873. }
  874. return reflect.ValueOf(int32(value)), nil
  875. case reflect.Int64:
  876. value, err := strconv.ParseInt(value, 0, 64)
  877. if err != nil {
  878. return reflect.Value{}, err
  879. }
  880. return reflect.ValueOf(int64(value)), nil
  881. case reflect.Uint:
  882. value, err := strconv.ParseUint(value, 0, 0)
  883. if err != nil {
  884. return reflect.Value{}, err
  885. }
  886. return reflect.ValueOf(uint(value)), nil
  887. case reflect.Uint8:
  888. value, err := strconv.ParseUint(value, 0, 8)
  889. if err != nil {
  890. return reflect.Value{}, err
  891. }
  892. return reflect.ValueOf(uint8(value)), nil
  893. case reflect.Uint16:
  894. value, err := strconv.ParseUint(value, 0, 16)
  895. if err != nil {
  896. return reflect.Value{}, err
  897. }
  898. return reflect.ValueOf(uint16(value)), nil
  899. case reflect.Uint32:
  900. value, err := strconv.ParseUint(value, 0, 32)
  901. if err != nil {
  902. return reflect.Value{}, err
  903. }
  904. return reflect.ValueOf(uint32(value)), nil
  905. case reflect.Uint64:
  906. value, err := strconv.ParseUint(value, 0, 64)
  907. if err != nil {
  908. return reflect.Value{}, err
  909. }
  910. return reflect.ValueOf(uint64(value)), nil
  911. case reflect.Float32:
  912. value, err := strconv.ParseFloat(value, 32)
  913. if err != nil {
  914. return reflect.Value{}, err
  915. }
  916. return reflect.ValueOf(float32(value)), nil
  917. case reflect.Float64:
  918. value, err := strconv.ParseFloat(value, 64)
  919. if err != nil {
  920. return reflect.Value{}, err
  921. }
  922. return reflect.ValueOf(float64(value)), nil
  923. case reflect.String:
  924. return reflect.ValueOf(value), nil
  925. }
  926. // FIXME This should end up as a TypeError?
  927. panic(fmt.Errorf("invalid conversion of %q to reflect.Kind: %v", value, kind))
  928. }