tuple 使用 PyCore::tuple() 进行强转,修复 Subscript 与 Slice 混淆的问题,部分 Slice 的逻辑应该是属于 Subscript

pull/1/head
韩天峰 2 years ago
parent 0799636082
commit 228049c859
  1. 17
      cases/fib.py
  2. 5
      cases/np_array.py
  3. 35
      src/Python/Translator.php

@ -0,0 +1,17 @@
def gen_fib(count):
i = 1
if count == 0:
fib = []
elif count == 1:
fib = [1]
elif count == 2:
fib = [1,1]
elif count > 2:
fib = [1,1]
while i < (count - 1):
fib.append(fib[i] + fib[i-1])
i += 1
return fib
print(gen_fib(10))

@ -0,0 +1,5 @@
import numpy as np
arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
print(arr[1, 1:4])

@ -175,7 +175,7 @@ class Translator extends \PhpAot\Core\Translator
foreach ($tuple->dims as $dim) { foreach ($tuple->dims as $dim) {
$ids[] = $this->parseTarget($dim); $ids[] = $this->parseTarget($dim);
} }
return '[' . implode(', ', $ids) . ']'; return 'PyCore::tuple([' . implode(', ', $ids) . '])';
} }
function parseListComp($listComp) function parseListComp($listComp)
@ -243,26 +243,15 @@ class Translator extends \PhpAot\Core\Translator
} }
} }
function parseSlice($slice, $op = 'Load') function parseSlice($slice): string
{ {
if ($slice->_type == 'Slice') { $_args[] = $slice->lower ? $this->parseTarget($slice->lower) : 'null';
$_args[] = $slice->lower ? $this->parseTarget($slice->lower) : 'null'; $_args[] = $slice->upper ? $this->parseTarget($slice->upper) : 'null';
$_args[] = $slice->upper ? $this->parseTarget($slice->upper) : 'null'; $_args[] = $slice->step ? $this->parseTarget($slice->step) : 'null';
$_args[] = $slice->step ? $this->parseTarget($slice->step) : 'null'; return 'PyCore::slice(' . implode(', ', $_args) . ')';
$target = 'PyCore::slice(' . implode(', ', $_args) . ')';
} else {
$target = $this->parseTarget($slice);
}
if ($op == 'Store') {
return $slice->id . '->__setitem__(' . $target . ', $__value)';
} elseif ($op == 'Del') {
return $slice->id . '->__delitem__(' . $target . ')';
} else {
return $slice->id . '[' . $target . ']';
}
} }
function parseImportFrom($node) function parseImportFrom($node): string
{ {
$module = $node->module; $module = $node->module;
$imports = []; $imports = [];
@ -469,7 +458,15 @@ class Translator extends \PhpAot\Core\Translator
$code .= $this->parseValue($node->value); $code .= $this->parseValue($node->value);
} }
if ($node->slice) { if ($node->slice) {
$code .= $this->parseSlice($node->slice, $node->ctx->_type); $target = $this->parseTarget($node->slice);
$op = $node->ctx->_type;
if ($node->ctx->_type == 'Store') {
$code .= $node->slice->id . '->__setitem__(' . $target . ', $__value)';
} elseif ($op == 'Del') {
$code .= $node->slice->id . '->__delitem__(' . $target . ')';
} else {
$code .= $node->slice->id . '[' . $target . ']';
}
} }
return $code; return $code;
} }

Loading…
Cancel
Save