this repo has no description
1// Copyright (c) Facebook, Inc. and its affiliates. (http://www.facebook.com)
2#include "slice-builtins.h"
3
4#include "builtins.h"
5#include "frame.h"
6#include "int-builtins.h"
7#include "objects.h"
8#include "runtime.h"
9#include "type-builtins.h"
10
11namespace py {
12
13static const BuiltinAttribute kSliceAttributes[] = {
14 {ID(start), RawSlice::kStartOffset, AttributeFlags::kReadOnly},
15 {ID(stop), RawSlice::kStopOffset, AttributeFlags::kReadOnly},
16 {ID(step), RawSlice::kStepOffset, AttributeFlags::kReadOnly},
17};
18
19void initializeSliceType(Thread* thread) {
20 addBuiltinType(thread, ID(slice), LayoutId::kSlice,
21 /*superclass_id=*/LayoutId::kObject, kSliceAttributes,
22 Slice::kSize, /*basetype=*/false);
23}
24
25bool tryUnpackSlice(const RawObject& key, word* start, word* stop) {
26 if (!key.isSlice()) {
27 return false;
28 }
29
30 RawSlice slice = Slice::cast(key);
31 if (!slice.step().isNoneType()) {
32 return false;
33 }
34
35 RawObject start_obj = slice.start();
36 if (start_obj.isNoneType()) {
37 *start = 0;
38 } else if (start_obj.isSmallInt()) {
39 *start = SmallInt::cast(start_obj).value();
40 } else {
41 return false;
42 }
43
44 RawObject stop_obj = slice.stop();
45 if (stop_obj.isNoneType()) {
46 *stop = kMaxWord;
47 } else if (stop_obj.isSmallInt()) {
48 *stop = SmallInt::cast(stop_obj).value();
49 } else {
50 return false;
51 }
52
53 return true;
54}
55
56RawObject METH(slice, __new__)(Thread* thread, Arguments args) {
57 HandleScope scope(thread);
58 Object type_obj(&scope, args.get(0));
59 Runtime* runtime = thread->runtime();
60 if (!runtime->isInstanceOfType(*type_obj)) {
61 return thread->raiseWithFmt(LayoutId::kTypeError,
62 "'__new__' requires a type object");
63 }
64 Type type(&scope, *type_obj);
65 Layout layout(&scope, type.instanceLayout());
66 if (layout.id() != LayoutId::kSlice) {
67 return thread->raiseWithFmt(LayoutId::kTypeError,
68 "slice.__new__ requires the slice type");
69 }
70 Object start(&scope, NoneType::object());
71 Object stop(&scope, NoneType::object());
72 Object step(&scope, NoneType::object());
73 if (args.get(2).isUnbound()) {
74 stop = args.get(1);
75 return runtime->newSlice(start, stop, step);
76 }
77 start = args.get(1);
78 stop = args.get(2);
79 step = args.get(3); // defaults to None
80 return runtime->newSlice(start, stop, step);
81}
82
83} // namespace py