aboutsummaryrefslogtreecommitdiffhomepage
path: root/crates/shirabe-php-shim/src/lib.rs
blob: 0edcc89737d55612dc4fcb10feacb236580194eb (plain)
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
mod array;
mod compress;
mod curl;
mod datetime;
mod env;
mod exception;
mod filter;
mod fs;
mod hash;
mod json;
mod math;
mod net;
mod openssl;
mod output;
mod phar;
mod preg;
mod process;
mod random;
mod rar;
mod runtime;
mod stream;
mod string;
mod url;
mod var;
mod xml;
mod zip;

pub use array::*;
pub use compress::*;
pub use curl::*;
pub use datetime::*;
pub use env::*;
pub use exception::*;
pub use filter::*;
pub use fs::*;
pub use hash::*;
pub use json::*;
pub use math::*;
pub use net::*;
pub use openssl::*;
pub use output::*;
pub use phar::*;
pub use preg::*;
pub use process::*;
pub use random::*;
pub use rar::*;
pub use runtime::*;
pub use stream::*;
pub use string::*;
pub use url::*;
pub use var::*;
pub use xml::*;
pub use zip::*;

use indexmap::IndexMap;

#[derive(Debug, Clone, Default)]
pub enum PhpMixed {
    #[default]
    Null,
    Bool(bool),
    Int(i64),
    Float(f64),
    String(String),
    List(Vec<PhpMixed>),
    Array(IndexMap<String, PhpMixed>),
    // TODO: consolidate Object to Array.
    Object(IndexMap<String, PhpMixed>),
}

impl serde::Serialize for PhpMixed {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        use serde::ser::{SerializeMap, SerializeSeq};
        match self {
            PhpMixed::Null => serializer.serialize_none(),
            PhpMixed::Bool(b) => serializer.serialize_bool(*b),
            PhpMixed::Int(i) => serializer.serialize_i64(*i),
            PhpMixed::Float(f) => serializer.serialize_f64(*f),
            PhpMixed::String(s) => serializer.serialize_str(s),
            PhpMixed::List(items) => {
                let mut seq = serializer.serialize_seq(Some(items.len()))?;
                for item in items {
                    seq.serialize_element(item)?;
                }
                seq.end()
            }
            PhpMixed::Array(entries) => {
                // PHP arrays do not distinguish an empty map from an empty list, and
                // `json_encode([])` always emits `[]`. Mirror that so an empty associative
                // array encodes as `[]` rather than `{}`.
                if entries.is_empty() {
                    return serializer.serialize_seq(Some(0))?.end();
                }
                let mut map = serializer.serialize_map(Some(entries.len()))?;
                for (k, v) in entries {
                    map.serialize_entry(k, v)?;
                }
                map.end()
            }
            PhpMixed::Object(entries) => {
                let mut map = serializer.serialize_map(Some(entries.len()))?;
                for (k, v) in entries {
                    map.serialize_entry(k, v)?;
                }
                map.end()
            }
        }
    }
}

/// PHP `===` semantics: type-strict and, for arrays, order-sensitive.
impl PartialEq for PhpMixed {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (PhpMixed::Null, PhpMixed::Null) => true,
            (PhpMixed::Bool(a), PhpMixed::Bool(b)) => a == b,
            (PhpMixed::Int(a), PhpMixed::Int(b)) => a == b,
            (PhpMixed::Float(a), PhpMixed::Float(b)) => a == b,
            (PhpMixed::String(a), PhpMixed::String(b)) => a == b,
            (PhpMixed::List(a), PhpMixed::List(b)) => a == b,
            (PhpMixed::Array(a), PhpMixed::Array(b)) => {
                a.len() == b.len()
                    && a.iter()
                        .zip(b.iter())
                        .all(|((ka, va), (kb, vb))| ka == kb && va == vb)
            }
            (PhpMixed::Object(a), PhpMixed::Object(b)) => {
                a.len() == b.len()
                    && a.iter()
                        .zip(b.iter())
                        .all(|((ka, va), (kb, vb))| ka == kb && va == vb)
            }
            _ => false,
        }
    }
}

impl PhpMixed {
    pub fn as_bool(&self) -> Option<bool> {
        match self {
            PhpMixed::Bool(b) => Some(*b),
            _ => None,
        }
    }

    pub fn as_int(&self) -> Option<i64> {
        match self {
            PhpMixed::Int(i) => Some(*i),
            _ => None,
        }
    }

    pub fn as_float(&self) -> Option<f64> {
        match self {
            PhpMixed::Float(f) => Some(*f),
            _ => None,
        }
    }

    pub fn as_string(&self) -> Option<&str> {
        match self {
            PhpMixed::String(s) => Some(s.as_str()),
            _ => None,
        }
    }

    pub fn as_list(&self) -> Option<&Vec<PhpMixed>> {
        match self {
            PhpMixed::List(l) => Some(l),
            _ => None,
        }
    }

    pub fn as_array(&self) -> Option<&IndexMap<String, PhpMixed>> {
        match self {
            PhpMixed::Array(a) => Some(a),
            _ => None,
        }
    }

    pub fn as_array_mut(&mut self) -> Option<&mut IndexMap<String, PhpMixed>> {
        match self {
            PhpMixed::Array(a) => Some(a),
            _ => None,
        }
    }

    pub fn as_list_mut(&mut self) -> Option<&mut Vec<PhpMixed>> {
        match self {
            PhpMixed::List(l) => Some(l),
            _ => None,
        }
    }

    pub fn as_object(&self) -> Option<&IndexMap<String, PhpMixed>> {
        match self {
            PhpMixed::Object(o) => Some(o),
            _ => None,
        }
    }

    pub fn is_null(&self) -> bool {
        matches!(self, PhpMixed::Null)
    }

    /// PHP loose boolean cast `(bool) $value`.
    pub fn to_bool(&self) -> bool {
        php_truthy(self)
    }

    pub fn get(&self, key: &str) -> Option<&PhpMixed> {
        self.as_array().and_then(|m| m.get(key))
    }

    /// Treats PhpMixed::Null as None, everything else as Some.
    pub fn as_opt(&self) -> Option<&PhpMixed> {
        if self.is_null() { None } else { Some(self) }
    }

    pub fn unwrap_or(self, default: PhpMixed) -> PhpMixed {
        if self.is_null() { default } else { self }
    }

    pub fn unwrap_or_default(self) -> PhpMixed {
        if self.is_null() { PhpMixed::Null } else { self }
    }

    pub fn unwrap(self) -> PhpMixed {
        if self.is_null() {
            panic!("called `PhpMixed::unwrap()` on a `Null` value");
        }
        self
    }

    /// Treats PhpMixed::Null as None and applies the function for chaining.
    pub fn and_then<U, F: FnOnce(&PhpMixed) -> Option<U>>(&self, f: F) -> Option<U> {
        self.as_opt().and_then(f)
    }

    /// Treats `Null` and `Bool(false)` as the falsy case, anything else as Some.
    pub fn ok_or_else<E, F: FnOnce() -> E>(self, err: F) -> Result<PhpMixed, E> {
        match self {
            PhpMixed::Null | PhpMixed::Bool(false) => Err(err()),
            v => Ok(v),
        }
    }
}

impl From<()> for PhpMixed {
    fn from(_value: ()) -> Self {
        PhpMixed::Null
    }
}

impl From<bool> for PhpMixed {
    fn from(value: bool) -> Self {
        PhpMixed::Bool(value)
    }
}

/// Blanket downcast helper so trait objects (`dyn Command`, `dyn OutputInterface`,
/// etc.) can be downcast to their concrete type, mirroring PHP `instanceof`.
pub trait AsAny {
    fn as_any(&self) -> &dyn std::any::Any;
    fn as_any_mut(&mut self) -> &mut dyn std::any::Any;
}

impl<T: std::any::Any> AsAny for T {
    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
    fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
        self
    }
}

impl From<i64> for PhpMixed {
    fn from(value: i64) -> Self {
        PhpMixed::Int(value)
    }
}

impl From<f64> for PhpMixed {
    fn from(value: f64) -> Self {
        PhpMixed::Float(value)
    }
}

impl From<String> for PhpMixed {
    fn from(value: String) -> Self {
        PhpMixed::String(value)
    }
}

impl From<&str> for PhpMixed {
    fn from(value: &str) -> Self {
        PhpMixed::String(value.to_string())
    }
}

impl<T> From<IndexMap<String, T>> for PhpMixed
where
    T: Into<PhpMixed>,
{
    fn from(value: IndexMap<String, T>) -> Self {
        PhpMixed::Array(value.into_iter().map(|(k, v)| (k, v.into())).collect())
    }
}

impl<T> From<Vec<T>> for PhpMixed
where
    T: Into<PhpMixed>,
{
    fn from(value: Vec<T>) -> Self {
        PhpMixed::List(value.into_iter().map(|v| v.into()).collect())
    }
}

impl<T> From<Option<T>> for PhpMixed
where
    T: Into<PhpMixed>,
{
    fn from(value: Option<T>) -> Self {
        match value {
            Some(v) => v.into(),
            None => PhpMixed::Null,
        }
    }
}

impl<T> From<Box<T>> for PhpMixed
where
    T: Into<PhpMixed>,
{
    fn from(value: Box<T>) -> Self {
        (*value).into()
    }
}

impl std::fmt::Display for PhpMixed {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.pad(&php_to_string(self))
    }
}

#[derive(Debug, Clone)]
pub enum PhpResource {
    Stdin,
    Stdout,
    Stderr,
    Stream(std::rc::Rc<std::cell::RefCell<StreamState>>),
    Process(std::rc::Rc<std::cell::RefCell<process::ProcessState>>),
}

impl PhpResource {
    /// Returns the underlying OS file descriptor backing this resource, when it has one.
    /// Used by `stream_set_blocking`/`stream_select` to drive `fcntl(2)`/`select(2)`. In-memory
    /// streams (`php://memory`/`php://temp`) and process handles have no fd and return `None`.
    pub(crate) fn raw_fd(&self) -> Option<std::os::unix::io::RawFd> {
        use std::os::unix::io::AsRawFd;
        match self {
            PhpResource::Stdin => Some(std::io::stdin().as_raw_fd()),
            PhpResource::Stdout => Some(std::io::stdout().as_raw_fd()),
            PhpResource::Stderr => Some(std::io::stderr().as_raw_fd()),
            PhpResource::Process(_) => None,
            PhpResource::Stream(state) => {
                let state = state.borrow();
                if state.closed {
                    return None;
                }
                match &state.backing {
                    StreamBacking::File(f) => Some(f.as_raw_fd()),
                    StreamBacking::Pipe(p) => Some(p.as_raw_fd()),
                    StreamBacking::Memory(_) => None,
                }
            }
        }
    }
}

/// Combined capability of every seekable byte stream backing. Both `std::fs::File`
/// and `std::io::Cursor<Vec<u8>>` satisfy it, so a stream can be driven uniformly.
pub trait ReadWriteSeek: std::io::Read + std::io::Write + std::io::Seek {}
impl<T: std::io::Read + std::io::Write + std::io::Seek> ReadWriteSeek for T {}

#[derive(Debug)]
pub enum StreamBacking {
    /// A real file on disk (also `/dev/null`); the OS tracks the position.
    File(std::fs::File),
    /// `php://memory` and `php://temp` — an in-memory growable buffer.
    /// TODO(phase-d): `php://temp/maxmemory:N` spills to a temp file past N bytes;
    /// the threshold is ignored here and everything stays in memory.
    Memory(std::io::Cursor<Vec<u8>>),
    /// A child process pipe created by `proc_open`. Half-duplex and not seekable.
    Pipe(ChildPipe),
}

impl StreamBacking {
    pub(crate) fn as_rws(&mut self) -> &mut dyn ReadWriteSeek {
        match self {
            StreamBacking::File(f) => f,
            StreamBacking::Memory(c) => c,
            StreamBacking::Pipe(p) => p,
        }
    }
}

/// One end of a child process pipe. Each variant supports only the direction PHP
/// allows for it; the unsupported operations return `ErrorKind::Unsupported` so the
/// `ReadWriteSeek` contract is satisfied without pretending pipes are seekable.
#[derive(Debug)]
pub enum ChildPipe {
    In(std::process::ChildStdin),
    Out(std::process::ChildStdout),
    Err(std::process::ChildStderr),
}

impl std::io::Read for ChildPipe {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        match self {
            ChildPipe::Out(o) => o.read(buf),
            ChildPipe::Err(e) => e.read(buf),
            ChildPipe::In(_) => Err(std::io::Error::from(std::io::ErrorKind::Unsupported)),
        }
    }
}

impl std::io::Write for ChildPipe {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        match self {
            ChildPipe::In(i) => i.write(buf),
            ChildPipe::Out(_) | ChildPipe::Err(_) => {
                Err(std::io::Error::from(std::io::ErrorKind::Unsupported))
            }
        }
    }

    fn flush(&mut self) -> std::io::Result<()> {
        match self {
            ChildPipe::In(i) => i.flush(),
            ChildPipe::Out(_) | ChildPipe::Err(_) => Ok(()),
        }
    }
}

impl std::io::Seek for ChildPipe {
    fn seek(&mut self, _pos: std::io::SeekFrom) -> std::io::Result<u64> {
        Err(std::io::Error::from(std::io::ErrorKind::Unsupported))
    }
}

impl std::os::unix::io::AsRawFd for ChildPipe {
    fn as_raw_fd(&self) -> std::os::unix::io::RawFd {
        match self {
            ChildPipe::In(i) => i.as_raw_fd(),
            ChildPipe::Out(o) => o.as_raw_fd(),
            ChildPipe::Err(e) => e.as_raw_fd(),
        }
    }
}

#[derive(Debug)]
pub struct StreamState {
    pub(crate) backing: StreamBacking,
    /// Whether the mode opened the stream for reading.
    pub(crate) readable: bool,
    /// Whether the mode opened the stream for writing.
    pub(crate) writable: bool,
    /// Set once a read attempt sees end-of-stream, mirroring PHP's `feof()` which
    /// only reports true after a read has hit the end; cleared by a seek.
    pub(crate) eof: bool,
    pub(crate) closed: bool,
    /// The mode string passed to `fopen`, reported back by `stream_get_meta_data`.
    pub(crate) mode: String,
    /// The path/URI the stream was opened from, reported back by `stream_get_meta_data`.
    pub(crate) uri: String,
}

impl StreamState {
    pub(crate) fn new(
        backing: StreamBacking,
        readable: bool,
        writable: bool,
        mode: String,
        uri: String,
    ) -> StreamState {
        StreamState {
            backing,
            readable,
            writable,
            eof: false,
            closed: false,
            mode,
            uri,
        }
    }
}