Rewrite your app in Rust, piece by piece, checked against the original at every step. Works with TypeScript, JavaScript, Python, Go, Ruby, Java, C, PHP, C#, Kotlin, PowerShell and Swift.
Rust agent-skillsclaude-codeclicode-migrationcodexffigolangjavajavascriptmcpmigrationnapiperformanceportingpyo3pythonrewriterubyrusttypescript
PowerShell: count a time-only [datetime] parse and a spaced [datetime]:: Now as clock reads (#1428)
jakalijeyf54946639002
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 706cd866..15c0378b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -296,6 +296,10 @@- PowerShell: a parameter typed `[decimal]`, `[uint64]` or `[ulong]` keeps its function inPowerShell, with the reasons C# gives for the same types, instead of bridging it as `f64` or`i64`. `[uint32]`, `[double]` and `[single]` bridge as before (#1341 by @jakalijey).+- PowerShell: `[datetime]::Parse('09:00')`, `ParseExact` and a `[datetime]'17:30'` cast of a string+ with a time and no date count as clock reads, since they take today's date, and `[datetime]:: Now`+ with a space after `::` is matched like `[datetime]::Now`, in `analyze` and `bridge`+ (#1404 by @jakalijey).- PHP and C: a method reached through `->` or `::` (`$request->date()`, `$config->getenv()`,`Calendar::time()`, `ops->time(0)`) is no longer taken for the global function of that name in`analyze` and `bridge` (#1397 by @jakalijey).diff --git a/src/lang/effects.rs b/src/lang/effects.rsindex 092a438c..6b397b24 100644--- a/src/lang/effects.rs+++ b/src/lang/effects.rs@@ -338,8 +338,10 @@ fn clock_and_random(lang: Lang) -> &'static [&'static str] {"Stopwatch.StartNew(","Stopwatch.GetElapsedTime(",],- // Only these static members of `[datetime]` read the clock; `IsLeapYear`, `DaysInMonth`- // and `Parse` compute from their arguments.+ // Only these static members of `[datetime]` read the clock; `IsLeapYear` and+ // `DaysInMonth` compute from their arguments, and so does `Parse` when the string has a+ // date. `Parse` of a time-only string (`'09:00'`) reads today's date: see+ // `powershell_time_only`.Lang::Powershell => &["get-date","get-random",@@ -1076,11 +1078,139 @@ pub fn reason(lang: Lang, params: &[&str], code: &str) -> Option<String> {/// [`reason`] for a top-level function: where the language [`observes`] a call's effects, changing/// an argument in place and printing to standard output are not reasons to keep it.+/// `[datetime]::Parse('09:00')`, `[datetime]::ParseExact('09:00', ...)` and a+/// `[datetime]'17:30'` cast in PowerShell: a string with a time and no date takes today's date+/// from the clock (#1404). `code` is `raw` blanked and lowered byte for byte, so a quote seen in+/// `code` opens the literal at the same place in `raw`.+fn powershell_time_only(raw: &str, code: &str) -> Option<String> {+ // Arguments may continue on the next line after `(` or `,`.+ let ws = |s: &str| s.trim_start_matches(char::is_whitespace).len();+ for ty in ["[system.datetime]", "[datetime]"] {+ for (i, _) in code.match_indices(ty) {+ let after = &code[i + ty.len()..];+ let spaced = &after[after.len() - ws(after)..];+ let (what, exact, rest) = match spaced.strip_prefix("::") {+ Some(member) => {+ let member = &member[member.len() - ws(member)..];+ let name: String = member.chars().take_while(|&c| is_ident(c)).collect();+ if name != "parse" && name != "parseexact" {+ continue;+ }+ let tail = &member[name.len()..];+ let Some(args) = tail[tail.len() - ws(tail)..].strip_prefix('(') else {+ continue;+ };+ (+ format!("{ty}::{name}"),+ name == "parseexact",+ &args[args.len() - ws(args)..],+ )+ }+ None => (ty.to_string(), false, spaced),+ };+ let Some((value, after_value)) = literal_at(raw, code, rest) else {+ continue;+ };+ // `NoCurrentDateDefault` fills in 0001-01-01, not today (#1404 review).+ if what.contains("::") {+ let mut depth = 1;+ let end = after_value+ .find(|c| {+ match c {+ '(' => depth += 1,+ ')' => depth -= 1,+ _ => {}+ }+ depth == 0+ })+ .unwrap_or(after_value.len());+ if after_value[..end].contains("nocurrentdatedefault") {+ continue;+ }+ }+ // `ParseExact` says what the string holds in its format; read that when it is written.+ let time_only = if exact {+ let next = after_value+ .trim_start_matches(char::is_whitespace)+ .strip_prefix(',')+ .map(|r| &r[r.len() - ws(r)..]);+ match next.and_then(|r| literal_at(raw, code, r)) {+ Some((format, _)) => is_time_only_format(format),+ None => is_time_only(value),+ }+ } else {+ is_time_only(value)+ };+ if time_only {+ return Some(what);+ }+ }+ }+ None+}++/// The string literal that starts `rest` (a tail of `code`), read from `raw` at the same place,+/// and the part of `code` after its closing quote.+fn literal_at<'a>(raw: &'a str, code: &'a str, rest: &'a str) -> Option<(&'a str, &'a str)> {+ let quote = rest.chars().next().filter(|c| matches!(c, '\'' | '"'))?;+ let open = code.len() - rest.len() + 1;+ let len = code[open..].find(quote)?;+ Some((raw.get(open..open + len)?, &code[open + len + 1..]))+}++/// Whether a date string holds a time and no date: `09:00`, `17:30:15`, but not `2024-02-29 09:00`,+/// `1/2/2024`, `29.02.2024`, `20240229 09:00` or `Sat, 18 Aug 2018 07:22:16 GMT`.+fn is_time_only(text: &str) -> bool {+ const MONTHS: [&str; 12] = [+ "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",+ ];+ let month = text+ .split(|c: char| !c.is_ascii_alphabetic())+ .map(str::to_ascii_lowercase)+ .any(|word| MONTHS.iter().any(|m| word.starts_with(m)));+ if month {+ return false;+ }+ let b = text.trim().as_bytes();+ let date_mark = b.windows(3).any(|w| {+ w[0].is_ascii_digit() && matches!(w[1], b'-' | b'/' | b'.') && w[2].is_ascii_digit()+ });+ // Six digits in a row are a compact date (`20240229`, `240229`).+ let compact_date = b.split(|c| !c.is_ascii_digit()).any(|run| run.len() >= 6);+ b.contains(&b':') && b.iter().any(u8::is_ascii_digit) && !date_mark && !compact_date+}++/// Whether a .NET date format reads a time and no date: `HH:mm`, `HHmm`, `h:mm tt`, or the+/// standard `t` and `T`. A day, month or year field (`d`, `M`, `y`) or any other standard+/// format gives a date.+fn is_time_only_format(format: &str) -> bool {+ let f = format.trim();+ if f.chars().count() == 1 {+ return matches!(f, "t" | "T");+ }+ let fields: String = f.chars().filter(char::is_ascii_alphabetic).collect();+ !fields.contains(['d', 'M', 'y', 'g']) && fields.contains(['H', 'h'])+}++/// PowerShell allows spaces between `::` and a static member (`[datetime]:: Now`); the lists+/// spell it without them.+fn squeeze_static_members(s: &str) -> String {+ let mut out = String::with_capacity(s.len());+ let mut rest = s;+ while let Some(i) = rest.find("::") {+ out.push_str(&rest[..i + 2]);+ rest = rest[i + 2..].trim_start_matches([' ', '\t']);+ }+ out.push_str(rest);+ out+}+pub fn function_reason(lang: Lang, params: &[&str], code: &str) -> Option<String> {reason_with(lang, params, code, observes(lang))}fn reason_with(lang: Lang, params: &[&str], code: &str, observed: bool) -> Option<String> {+ let raw = code;let code = blank(lang, code);// C records its arguments back after the call (`out` and `buffer` parameters), so only// printing is invisible there.@@ -1094,8 +1224,10 @@ fn reason_with(lang: Lang, params: &[&str], code: &str, observed: bool) -> Optio}let lowered;let lower_hay = code.to_ascii_lowercase();+ let squeezed;let state_hay = if lang == Lang::Powershell {- &lower_hay+ squeezed = squeeze_static_members(&lower_hay);+ &squeezed} else {&code};@@ -1122,7 +1254,11 @@ fn reason_with(lang: Lang, params: &[&str], code: &str, observed: bool) -> Optio));}if params.is_empty()- && let Some(what) = find(state_hay, clock_and_random(lang))+ && let Some(what) = find(state_hay, clock_and_random(lang)).or_else(|| {+ (lang == Lang::Powershell)+ .then(|| powershell_time_only(raw, &lower_hay))+ .flatten()+ }){return Some(format!("takes nothing and reads the clock or randomness (`{what}`): one recorded case is one moment"@@ -1180,8 +1316,18 @@ pub fn scan_risks(lang: Lang, source: &str, facts: &mut crate::ts::scan::FileFac(state, Risk::SharedState),(clock_and_random(lang), Risk::ClockAndRandom),];+ let raw_lines: Vec<&str> = source.lines().collect();for (n, line) in code.lines().enumerate() {let line_no = u32::try_from(n + 1).unwrap_or(u32::MAX);+ let squeezed;+ let hay = if lang == Lang::Powershell {+ squeezed = squeeze_static_members(line);+ squeezed.as_str()+ } else {+ line+ };+ let time_only = lang == Lang::Powershell+ && powershell_time_only(raw_lines.get(n).copied().unwrap_or(""), line).is_some();for (needles, risk) in &lists {let hit = needles.iter().any(|needle| {let needle = if lang == Lang::Powershell {@@ -1189,8 +1335,8 @@ pub fn scan_risks(lang: Lang, source: &str, facts: &mut crate::ts::scan::FileFac} else {(*needle).to_string()};- find_all(line, &needle).next().is_some()- });+ find_all(hay, &needle).next().is_some()+ }) || (*risk == Risk::ClockAndRandom && time_only);// The Swift and PowerShell syntax scans already add some of these calls (`Date(`,// `Get-Date`): one call is one hit, not one per pass (#1401).if hit {@@ -2189,6 +2335,15 @@ mod tests {"function F { [datetime]::DaysInMonth(2024, 2) }\n","function F { [datetime]::Parse('2024-02-29') }\n","function F { [datetime]::MinValue }\n",+ "function F { [datetime]::Parse('2024-02-29 09:00') }\n",+ "function F { [datetime]'1/2/2024' }\n",+ "function F($s) { [datetime]::Parse($s) }\n",+ "function F { # [datetime]::Parse('09:00')\n}\n",+ "function F { [datetime]::ParseExact('20240229 09:00', 'yyyyMMdd HH:mm', $null) }\n",+ "function F { [datetime]::ParseExact('09:00', 'HH:mm', $null, [Globalization.DateTimeStyles]::NoCurrentDateDefault) }\n",+ "function F { [datetime]::Parse('20240229 09:00') }\n",+ "function F { [datetime]::Parse('Sat, 18 Aug 2018 07:22:16 GMT') }\n",+ "function F { [datetime]::ParseExact('09:00', 'HH:mm', (Get-Culture), [Globalization.DateTimeStyles]::NoCurrentDateDefault) }\n",] {let facts = crate::lang::scan(Lang::Powershell, "x.ps1", code);assert!(@@ -2197,6 +2352,35 @@ mod tests {facts.risks);}+ // Arguments on the next line: `bridge` reads the whole function.+ assert!(+ reason(+ Lang::Powershell,+ &[],+ "function F {\n [datetime]::Parse(\n '09:00')\n}\n"+ )+ .is_some_and(|r| r.contains("clock"))+ );+ // A time with no date takes today's date, and a space after `::` is the same member (#1404).+ for code in [+ "function F { [datetime]::Parse('09:00') }\n",+ "function F { [datetime]'17:30' }\n",+ "function F { [datetime]:: Now }\n",+ "function F { [System.DateTime]::ParseExact(\"17:30:15\", 'HH:mm:ss', $null) }\n",+ "function F { [datetime]::ParseExact('0900', 'HHmm', $null) }\n",+ "function F { $t = [datetime]'17:30'; $NoCurrentDateDefault = 0; $t }\n",+ ] {+ let facts = crate::lang::scan(Lang::Powershell, "x.ps1", code);+ assert_eq!(+ facts.risks.get(&Risk::ClockAndRandom),+ Some(&vec![1]),+ "{code}"+ );+ assert!(+ reason(Lang::Powershell, &[], code).is_some_and(|r| r.contains("clock")),+ "{code}"+ );+ }let facts = crate::lang::scan(Lang::Ruby,"x.rb",