value.go 26 KB

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