use std::collections::{HashMap, HashSet};
use crate::{
backends::powershell::ps_quote,
compiler::diagnostics::CompileError,
ir::{Class, Command, Expr, ExprKind, Function, Method, Place, Program, Stmt, Type},
};
pub fn emit_program(program: &Program) -> Result<String, CompileError> {
validate_program(program)?;
let metadata = Metadata::new(program);
let mut emitter = Emitter::new(&metadata);
let mut output = String::from(
"# Generated by tsh. Requires PowerShell 7.4 or newer.\n$ErrorActionPreference = 'Continue'\n",
);
for class in &program.classes {
output.push_str(&emitter.emit_class(class)?);
output.push('\n');
}
for function in &program.functions {
output.push_str(&emitter.emit_function(function)?);
output.push('\n');
}
output.push_str(&emitter.emit_top_level(&program.body)?);
Ok(output)
}
#[derive(Debug, Clone)]
struct Value {
expr: String,
var: Option<String>,
ty: Type,
}
impl Value {
fn plain(expr: impl Into<String>, ty: Type) -> Self {
Self {
expr: expr.into(),
var: None,
ty,
}
}
fn temp(name: String, ty: Type) -> Self {
Self {
expr: format!("${name}"),
var: Some(name),
ty,
}
}
}
#[derive(Debug, Clone)]
struct Metadata<'a> {
classes: HashMap<&'a str, &'a Class>,
statics: HashSet<(&'a str, &'a str)>,
properties: HashMap<(&'a str, &'a str), String>,
globals: HashSet<&'a str>,
}
impl<'a> Metadata<'a> {
fn new(program: &'a Program) -> Self {
let mut classes = HashMap::new();
let mut statics = HashSet::new();
for class in &program.classes {
classes.insert(class.name.as_str(), class);
for method in &class.methods {
if method.is_static {
statics.insert((class.name.as_str(), method.function.name.as_str()));
}
}
}
let mut properties = HashMap::new();
for class in &program.classes {
let mut used: HashSet<String> = HashSet::new();
for field in &class.fields {
let mut candidate = if is_safe_member(&field.name) {
field.name.clone()
} else {
format!("__tsh_field_{}", hex_bytes(field.name.as_bytes()))
};
while !used.insert(candidate.to_ascii_lowercase()) {
candidate.push('_');
}
properties.insert((class.name.as_str(), field.name.as_str()), candidate);
}
}
let mut globals = HashSet::new();
for statement in &program.body {
if let Stmt::Let { name, .. } = statement {
globals.insert(name.as_str());
}
}
Self {
classes,
statics,
properties,
globals,
}
}
fn property(&self, class: &str, field: &str) -> Result<String, CompileError> {
self.properties
.get(&(class, field))
.cloned()
.ok_or_else(|| {
CompileError::plain(format!("unknown field `{class}.{field}` in PowerShell IR"))
})
}
fn is_static(&self, class: &str, method: &str) -> Result<bool, CompileError> {
self.classes.get(class).map(|_| ()).ok_or_else(|| {
CompileError::plain(format!("unknown class `{class}` in PowerShell IR"))
})?;
Ok(self.statics.contains(&(class, method)))
}
}
#[derive(Debug, Clone)]
enum LoopMode {
While,
For(Vec<Stmt>),
}
struct Emitter<'a> {
metadata: &'a Metadata<'a>,
code: String,
indent: usize,
next_temp: usize,
in_function: bool,
loops: Vec<LoopMode>,
}
impl<'a> Emitter<'a> {
fn new(metadata: &'a Metadata<'a>) -> Self {
Self {
metadata,
code: String::new(),
indent: 0,
next_temp: 0,
in_function: false,
loops: Vec::new(),
}
}
fn block(
&mut self,
in_function: bool,
indent: usize,
emit: impl FnOnce(&mut Self) -> Result<(), CompileError>,
) -> Result<String, CompileError> {
let saved_code = std::mem::take(&mut self.code);
let saved_indent = self.indent;
let saved_function = self.in_function;
let saved_loops = std::mem::take(&mut self.loops);
self.indent = indent;
self.in_function = in_function;
let result = emit(self);
let block = std::mem::replace(&mut self.code, saved_code);
self.indent = saved_indent;
self.in_function = saved_function;
self.loops = saved_loops;
result.map(|()| block)
}
fn line(&mut self, text: &str) {
for _ in 0..self.indent {
self.code.push_str(" ");
}
self.code.push_str(text);
self.code.push('\n');
}
fn fresh_temp(&mut self) -> String {
let name = format!("__tsh_tmp_{}", self.next_temp);
self.next_temp += 1;
name
}
fn variable(&self, name: &str) -> String {
if name == "__tsh_this" {
return "$this".to_owned();
}
if self.in_function && self.metadata.globals.contains(name) {
format!("$script:{name}")
} else {
format!("${name}")
}
}
fn emit_top_level(&mut self, statements: &[Stmt]) -> Result<String, CompileError> {
let mut emitter = Emitter::new(self.metadata);
emitter.next_temp = self.next_temp;
emitter.emit_statements(statements)?;
self.next_temp = emitter.next_temp;
Ok(emitter.code)
}
fn emit_class(&mut self, class: &Class) -> Result<String, CompileError> {
let mut output = format!("class {} {{\n", class.name);
for field in &class.fields {
let property = self.metadata.property(&class.name, &field.name)?;
output.push_str(&format!(
" [{}]${}\n",
ps_class_type(&field.ty)?,
property
));
}
let mut sub = Emitter::new(self.metadata);
sub.next_temp = self.next_temp;
let constructor = sub.emit_constructor(class)?;
let mut methods = Vec::new();
for method in &class.methods {
methods.push(sub.emit_method(class, method)?);
}
self.next_temp = sub.next_temp;
output.push_str(&constructor);
for method in methods {
output.push_str(&method);
}
output.push_str("}\n");
Ok(output)
}
fn emit_constructor(&mut self, class: &Class) -> Result<String, CompileError> {
let mut params = Vec::new();
for param in &class.constructor.params {
params.push(format!("[{}]${}", ps_class_type(¶m.ty)?, param.name));
}
let body = self.block(true, 2, |emitter| {
for field in &class.fields {
let property = emitter
.metadata
.property(&class.name, &field.name)?
.to_owned();
if let Some(initial) = &field.initial {
let value = emitter.emit_expr(initial)?;
emitter.line(&format!("$this.{property} = {}", value.expr));
} else {
emitter.line(&format!("$this.{property} = {}", default_value(&field.ty)));
}
}
emitter.emit_statements(&class.constructor.body)
})?;
Ok(format!(
" {}({}) {{\n{} }}\n",
class.name,
params.join(", "),
body
))
}
fn emit_method(&mut self, _class: &Class, method: &Method) -> Result<String, CompileError> {
let function = &method.function;
let mut params = Vec::new();
for param in &function.params {
params.push(format!("[{}]${}", ps_class_type(¶m.ty)?, param.name));
}
let body = self.block(true, 2, |emitter| emitter.emit_statements(&function.body))?;
let prefix = if method.is_static { "static " } else { "" };
Ok(format!(
" {}[{}] {}({}) {{\n{} }}\n",
prefix,
ps_class_type(&function.return_type)?,
function.name,
params.join(", "),
body
))
}
fn emit_function(&mut self, function: &Function) -> Result<String, CompileError> {
let mut sub = Emitter::new(self.metadata);
sub.next_temp = self.next_temp;
let body = sub.block(true, 1, |emitter| emitter.emit_statements(&function.body))?;
self.next_temp = sub.next_temp;
let mut output = format!("function __tsh_fn_{} {{\n", function.name);
if function.params.is_empty() {
output.push_str(&body);
} else {
let mut params = Vec::new();
for param in &function.params {
params.push(format!("[{}]${}", ps_class_type(¶m.ty)?, param.name));
}
output.push_str(&format!(" param({})\n", params.join(", ")));
output.push_str(&body);
}
output.push_str("}\n");
Ok(output)
}
fn emit_statements(&mut self, statements: &[Stmt]) -> Result<(), CompileError> {
for statement in statements {
self.emit_statement(statement)?;
}
Ok(())
}
fn emit_statement(&mut self, statement: &Stmt) -> Result<(), CompileError> {
match statement {
Stmt::Let { name, value } => {
let value = self.emit_expr(value)?;
self.line(&format!("{} = {}", self.variable(name), value.expr));
}
Stmt::Assign { place, value } => self.emit_assignment(place, value)?,
Stmt::Expr(expression) => {
let value = self.emit_expr(expression)?;
self.line(&format!("$null = {}", value.expr));
}
Stmt::If {
condition,
then_body,
else_body,
} => {
let condition = self.emit_expr(condition)?;
self.ensure_boolean(&condition)?;
self.line(&format!("if ({}) {{", condition.expr));
self.indent += 1;
self.emit_statements(then_body)?;
self.indent -= 1;
if else_body.is_empty() {
self.line("}");
} else {
self.line("} else {");
self.indent += 1;
self.emit_statements(else_body)?;
self.indent -= 1;
self.line("}");
}
}
Stmt::While { condition, body } => {
self.line("while ($true) {");
self.indent += 1;
let condition = self.emit_expr(condition)?;
self.ensure_boolean(&condition)?;
self.line(&format!("if (-not ({})) {{ break }}", condition.expr));
self.loops.push(LoopMode::While);
self.emit_statements(body)?;
self.loops.pop();
self.indent -= 1;
self.line("}");
}
Stmt::For {
init,
condition,
update,
body,
} => {
self.emit_statements(init)?;
self.line("while ($true) {");
self.indent += 1;
if let Some(condition) = condition {
let condition = self.emit_expr(condition)?;
self.ensure_boolean(&condition)?;
self.line(&format!("if (-not ({})) {{ break }}", condition.expr));
}
self.loops.push(LoopMode::For(update.clone()));
self.emit_statements(body)?;
self.loops.pop();
self.emit_statements(update)?;
self.indent -= 1;
self.line("}");
}
Stmt::Return(value) => {
if let Some(value) = value {
let value = self.emit_expr(value)?;
self.line(&format!("return {}", value.expr));
} else {
self.line("return");
}
}
Stmt::Break => {
if self.loops.is_empty() {
return Err(CompileError::plain(
"`break` is not inside a loop in PowerShell IR",
));
}
self.line("break");
}
Stmt::Continue => {
let mode = self.loops.last().cloned().ok_or_else(|| {
CompileError::plain("`continue` is not inside a loop in PowerShell IR")
})?;
if let LoopMode::For(update) = mode {
self.emit_statements(&update)?;
}
self.line("continue");
}
Stmt::Command {
kind,
args,
recursive,
} => self.emit_command(*kind, args, *recursive)?,
Stmt::Raw(raw) => {
self.code.push_str(raw);
if !raw.ends_with('\n') {
self.code.push('\n');
}
}
Stmt::Comment(comment) => self.emit_comment(comment),
Stmt::Block(body) => self.emit_statements(body)?,
}
Ok(())
}
fn emit_comment(&mut self, comment: &str) {
let lines = crate::backends::shell_comment_lines(comment);
if lines.is_empty() {
self.line("#");
return;
}
for text in lines {
self.line(&format!("# {text}"));
}
}
fn emit_assignment(&mut self, place: &Place, expression: &Expr) -> Result<(), CompileError> {
match place {
Place::Variable(name) => {
let value = self.emit_expr(expression)?;
self.line(&format!("{} = {}", self.variable(name), value.expr));
}
Place::Field {
object,
class,
field,
} => {
let property = self.metadata.property(class, field)?.to_owned();
let object_value = self.emit_expr(object)?;
let object = self.capture_if_variable(object, object_value);
let value = self.emit_expr(expression)?;
self.line(&format!("{}.{property} = {}", object.expr, value.expr));
}
}
Ok(())
}
fn emit_expr(&mut self, expression: &Expr) -> Result<Value, CompileError> {
match &expression.kind {
ExprKind::String(value) => Ok(Value::plain(ps_quote(value), expression.ty.clone())),
ExprKind::Number(value) => {
if *value == i64::MIN {
Ok(Value::plain("([long]::MinValue)", expression.ty.clone()))
} else {
Ok(Value::plain(value.to_string(), expression.ty.clone()))
}
}
ExprKind::Boolean(value) => Ok(Value::plain(
if *value { "$true" } else { "$false" },
expression.ty.clone(),
)),
ExprKind::Variable(name) => {
Ok(Value::plain(self.variable(name), expression.ty.clone()))
}
ExprKind::Template(parts) => self.emit_template(parts, expression.ty.clone()),
ExprKind::Binary { op, left, right } => {
self.emit_binary(op, left, right, expression.ty.clone())
}
ExprKind::Unary { op, value } => self.emit_unary(op, value, expression.ty.clone()),
ExprKind::Call { function, args } => {
self.emit_call(function, args, expression.ty.clone())
}
ExprKind::New { class, args } => self.emit_new(class, args),
ExprKind::Field {
object,
class,
field,
} => {
let property = self.metadata.property(class, field)?.to_owned();
let object_value = self.emit_expr(object)?;
let object = self.capture_if_variable(object, object_value);
let temp = self.fresh_temp();
self.line(&format!("${temp} = {}.{property}", object.expr));
Ok(Value::temp(temp, expression.ty.clone()))
}
ExprKind::Method {
object,
class,
method,
args,
} => self.emit_method_call(
object.as_deref(),
class,
method,
args,
expression.ty.clone(),
),
ExprKind::Env(key) => self.emit_env(key, expression.ty.clone()),
}
}
fn emit_template(&mut self, parts: &[Expr], result_type: Type) -> Result<Value, CompileError> {
let result = self.fresh_temp();
self.line(&format!("${result} = ''"));
for part in parts {
if matches!(part.ty, Type::Void) {
return Err(CompileError::plain(
"cannot interpolate a void expression in PowerShell IR",
));
}
let mut value = self.emit_expr(part)?;
if matches!(value.ty, Type::Boolean) {
value = self.boolean_as_text(value)?;
}
self.line(&format!("${result} = (${result} + {})", value.expr));
}
Ok(Value::temp(result, result_type))
}
fn emit_binary(
&mut self,
op: &str,
left: &Expr,
right: &Expr,
result_type: Type,
) -> Result<Value, CompileError> {
if op == "&&" || op == "||" {
return self.emit_logical(op, left, right, result_type);
}
let left_value = self.emit_expr(left)?;
let mut left = self.capture_if_variable(left, left_value);
if op == "+" && matches!(result_type, Type::String) && matches!(left.ty, Type::Boolean) {
left = self.boolean_as_text(left)?;
}
let right_value = self.emit_expr(right)?;
let mut right = self.capture_if_variable(right, right_value);
if op == "+" && matches!(result_type, Type::String) && matches!(right.ty, Type::Boolean) {
right = self.boolean_as_text(right)?;
}
if op == "+" && matches!(result_type, Type::String) {
return Ok(Value::plain(
format!("({} + {})", left.expr, right.expr),
result_type,
));
}
if is_comparison(op) {
return Ok(Value::plain(
format!("({} {} {})", left.expr, ps_comparison(op)?, right.expr),
result_type,
));
}
match op {
"+" | "-" | "*" | "%" => Ok(Value::plain(
format!("({} {} {})", left.expr, op, right.expr),
result_type,
)),
"/" => {
let result = self.fresh_temp();
let remainder = self.fresh_temp();
self.line(&format!("${remainder} = 0"));
self.line(&format!(
"${result} = [Math]::DivRem({}, {}, [ref]${remainder})",
left.expr, right.expr
));
Ok(Value::temp(result, result_type))
}
_ => Err(CompileError::plain(format!(
"unsupported PowerShell binary operator `{op}`"
))),
}
}
fn emit_logical(
&mut self,
op: &str,
left: &Expr,
right: &Expr,
result_type: Type,
) -> Result<Value, CompileError> {
if !matches!(result_type, Type::Boolean) {
return Err(CompileError::plain(
"logical PowerShell IR expression must have boolean type",
));
}
let left = self.emit_expr(left)?;
self.ensure_boolean(&left)?;
let result = self.fresh_temp();
match op {
"&&" => {
self.line(&format!("${result} = $false"));
self.line(&format!("if ({}) {{", left.expr));
self.indent += 1;
let right = self.emit_expr(right)?;
self.ensure_boolean(&right)?;
self.line(&format!("${result} = {}", right.expr));
self.indent -= 1;
self.line("}");
}
"||" => {
self.line(&format!("${result} = $true"));
self.line(&format!("if (-not ({})) {{", left.expr));
self.indent += 1;
let right = self.emit_expr(right)?;
self.ensure_boolean(&right)?;
self.line(&format!("${result} = {}", right.expr));
self.indent -= 1;
self.line("}");
}
_ => unreachable!(),
}
Ok(Value::temp(result, result_type))
}
fn emit_unary(
&mut self,
op: &str,
expression: &Expr,
result_type: Type,
) -> Result<Value, CompileError> {
let value = self.emit_expr(expression)?;
let value = self.capture_if_variable(expression, value);
match op {
"!" => Ok(Value::plain(format!("(-not {})", value.expr), result_type)),
"-" => Ok(Value::plain(format!("(-{})", value.expr), result_type)),
"+" => Ok(Value::plain(format!("(+{})", value.expr), result_type)),
_ => Err(CompileError::plain(format!(
"unsupported PowerShell unary operator `{op}`"
))),
}
}
fn emit_call(
&mut self,
function: &str,
args: &[Expr],
result_type: Type,
) -> Result<Value, CompileError> {
let args = self.capture_arguments(args)?;
let mut call = format!("__tsh_fn_{function}");
for argument in &args {
call.push(' ');
call.push_str(&argument.expr);
}
let result = self.fresh_temp();
self.line(&format!("${result} = {call}"));
Ok(Value::temp(result, result_type))
}
fn emit_new(&mut self, class: &str, args: &[Expr]) -> Result<Value, CompileError> {
if !self.metadata.classes.contains_key(class) {
return Err(CompileError::plain(format!(
"unknown class `{class}` in PowerShell IR"
)));
}
let args = self.capture_arguments(args)?;
let rendered: Vec<&str> = args.iter().map(|argument| argument.expr.as_str()).collect();
let result = self.fresh_temp();
self.line(&format!(
"${result} = [{class}]::new({})",
rendered.join(", ")
));
Ok(Value::temp(result, Type::Class(class.to_owned())))
}
fn emit_method_call(
&mut self,
object: Option<&Expr>,
class: &str,
method: &str,
args: &[Expr],
result_type: Type,
) -> Result<Value, CompileError> {
let is_static = self.metadata.is_static(class, method)?;
let object = match (object, is_static) {
(Some(object), false) => {
let object_value = self.emit_expr(object)?;
Some(self.capture_if_variable(object, object_value))
}
(None, false) => {
return Err(CompileError::plain(format!(
"instance method `{class}.{method}` has no receiver in PowerShell IR"
)));
}
(Some(_), true) => {
return Err(CompileError::plain(format!(
"static method `{class}.{method}` unexpectedly has a receiver in PowerShell IR"
)));
}
(None, true) => None,
};
let args = self.capture_arguments(args)?;
let rendered: Vec<&str> = args.iter().map(|argument| argument.expr.as_str()).collect();
let joined = rendered.join(", ");
let result = self.fresh_temp();
if let Some(object) = object {
self.line(&format!("${result} = {}.{method}({joined})", object.expr));
} else {
self.line(&format!("${result} = [{class}]::{method}({joined})"));
}
Ok(Value::temp(result, result_type))
}
fn emit_env(&mut self, expression: &Expr, result_type: Type) -> Result<Value, CompileError> {
let key = self.emit_expr(expression)?;
let key = self.capture(key);
let lookup = self.fresh_temp();
let result = self.fresh_temp();
self.line(&format!("${result} = ''"));
self.line(&format!(
"${lookup} = [System.Environment]::GetEnvironmentVariable({})",
key.expr
));
self.line(&format!(
"if ($null -ne ${lookup}) {{ ${result} = ${lookup} }}"
));
Ok(Value::temp(result, result_type))
}
fn emit_command(
&mut self,
kind: Command,
args: &[Expr],
recursive: bool,
) -> Result<(), CompileError> {
match kind {
Command::Exit => {
if args.len() > 1 {
return Err(CompileError::plain(
"`exit` accepts at most one argument in PowerShell IR",
));
}
if let Some(value) = args.first() {
let value = self.emit_expr(value)?;
let value = self.capture(value);
self.line(&format!("exit {}", value.expr));
} else {
self.line("exit 0");
}
}
Command::Echo => {
let values = self.capture_arguments(args)?;
if values.is_empty() {
self.line("[Console]::WriteLine('')");
return Ok(());
}
let result = self.fresh_temp();
self.line(&format!("${result} = ''"));
for (index, value) in values.iter().enumerate() {
let value = if matches!(value.ty, Type::Boolean) {
self.boolean_as_text(value.clone())?
} else {
value.clone()
};
if index > 0 {
self.line(&format!("${result} = (${result} + ' ')"));
}
self.line(&format!("${result} = (${result} + {})", value.expr));
}
self.line(&format!("[Console]::WriteLine(${result})"));
}
Command::Mkdir => {
if args.is_empty() {
return Err(CompileError::plain(
"`mkdir` expects at least one path in PowerShell IR",
));
}
let values = self.capture_arguments(args)?;
for value in values {
self.ensure_string(&value, "mkdir")?;
let flag = if recursive { " -Force" } else { "" };
self.line(&format!(
"$null = New-Item -ItemType Directory -Path {}{flag}",
value.expr
));
self.checked("mkdir");
}
}
Command::Rm => {
if args.is_empty() {
return Err(CompileError::plain(
"`rm` expects at least one path in PowerShell IR",
));
}
let values = self.capture_arguments(args)?;
for value in values {
self.ensure_string(&value, "rm")?;
if recursive {
self.line(&format!(
"Remove-Item -LiteralPath {} -Recurse -Force -Confirm:$false",
value.expr
));
} else {
self.line(&format!(
"if (Test-Path -LiteralPath {} -PathType Container) {{ exit 1 }}",
value.expr
));
self.line(&format!(
"Remove-Item -LiteralPath {} -Force -Confirm:$false",
value.expr
));
}
self.checked("rm");
}
}
Command::Cp => {
if args.len() != 2 {
return Err(CompileError::plain(
"`cp` expects exactly two paths in PowerShell IR",
));
}
let values = self.capture_arguments(args)?;
for value in &values {
self.ensure_string(value, "cp")?;
}
self.line(&format!(
"Copy-Item -LiteralPath {} -Destination {} -Force -Confirm:$false",
values[0].expr, values[1].expr
));
self.checked("cp");
}
Command::Mv => {
if args.len() != 2 {
return Err(CompileError::plain(
"`mv` expects exactly two paths in PowerShell IR",
));
}
let values = self.capture_arguments(args)?;
for value in &values {
self.ensure_string(value, "mv")?;
}
self.line(&format!(
"Move-Item -LiteralPath {} -Destination {} -Force -Confirm:$false",
values[0].expr, values[1].expr
));
self.checked("mv");
}
Command::Cd => {
if args.len() != 1 {
return Err(CompileError::plain(
"`cd` expects exactly one path in PowerShell IR",
));
}
let values = self.capture_arguments(args)?;
self.ensure_string(&values[0], "cd")?;
self.line(&format!("Set-Location -LiteralPath {}", values[0].expr));
self.checked("cd");
self.line("[Environment]::CurrentDirectory = (Get-Location).Path");
}
Command::Run => {
if args.is_empty() {
return Err(CompileError::plain(
"`run` needs a command in PowerShell IR",
));
}
let mut values = Vec::with_capacity(args.len());
for argument in args {
let value = self.emit_expr(argument)?;
self.ensure_string(&value, "run")?;
values.push(self.capture_if_variable(argument, value));
}
let rendered: Vec<&str> = values[1..]
.iter()
.map(|value| value.expr.as_str())
.collect();
let info = self.fresh_temp();
let process = self.fresh_temp();
let item = self.fresh_temp();
self.line(&format!(
"${info} = New-Object System.Diagnostics.ProcessStartInfo"
));
self.line(&format!("${info}.FileName = {}", values[0].expr));
self.line(&format!("${info}.UseShellExecute = $false"));
self.line(&format!(
"foreach (${item} in @({})) {{ ${info}.ArgumentList.Add(${item}) }}",
rendered.join(", ")
));
self.line("try {");
self.indent += 1;
self.line(&format!(
"${process} = [System.Diagnostics.Process]::Start(${info})"
));
self.indent -= 1;
self.line("} catch {");
self.indent += 1;
self.line("exit 1");
self.indent -= 1;
self.line("}");
self.line(&format!("${process}.WaitForExit()"));
self.line(&format!(
"if (${process}.ExitCode -ne 0) {{ exit ${process}.ExitCode }}"
));
}
Command::Chmod => {
if args.len() != 2 {
return Err(CompileError::plain(
"`chmod` expects path and mode arguments in PowerShell IR",
));
}
if recursive {
return Err(CompileError::plain(
"recursive `chmod` is not supported on the PowerShell target",
));
}
self.ensure_string_arg(&args[0], "chmod")?;
let path_value = self.emit_expr(&args[0])?;
let path = self.capture_if_variable(&args[0], path_value);
if let ExprKind::Number(decimal) = &args[1].kind {
if *decimal < 0 {
return Err(CompileError::plain(
"chmod mode cannot be negative in PowerShell IR",
));
}
self.line(&format!(
"[System.IO.File]::SetUnixFileMode({}, {decimal})",
path.expr
));
} else if matches!(args[1].ty, Type::String) {
return Err(CompileError::plain(
"string `chmod` modes are not supported on the PowerShell target; use a numeric mode",
));
} else {
let mode_value = self.emit_expr(&args[1])?;
let mode = self.capture_if_variable(&args[1], mode_value);
self.line(&format!(
"[System.IO.File]::SetUnixFileMode({}, {})",
path.expr, mode.expr
));
}
self.checked("chmod");
}
}
Ok(())
}
fn checked(&mut self, command: &str) {
let _ = command;
self.line("if (-not $?) { exit 1 }");
}
fn capture_arguments(&mut self, args: &[Expr]) -> Result<Vec<Value>, CompileError> {
let mut values = Vec::with_capacity(args.len());
for argument in args {
let value = self.emit_expr(argument)?;
values.push(self.capture_if_variable(argument, value));
}
Ok(values)
}
fn capture_if_variable(&mut self, expression: &Expr, value: Value) -> Value {
if matches!(expression.kind, ExprKind::Variable(_)) {
self.capture(value)
} else {
value
}
}
fn capture(&mut self, value: Value) -> Value {
let temp = self.fresh_temp();
self.line(&format!("${temp} = {}", value.expr));
Value::temp(temp, value.ty)
}
fn boolean_as_text(&mut self, value: Value) -> Result<Value, CompileError> {
if !matches!(value.ty, Type::Boolean) {
return Ok(value);
}
if value.var.is_none() {
if value.expr == "$true" {
return Ok(Value::plain(ps_quote("true"), Type::String));
}
if value.expr == "$false" {
return Ok(Value::plain(ps_quote("false"), Type::String));
}
}
let source = if value.var.is_some() {
value
} else {
self.capture(value)
};
let result = self.fresh_temp();
self.line(&format!("${result} = ''"));
self.line(&format!("if ({}) {{ ${result} = 'true' }}", source.expr));
self.line(&format!("else {{ ${result} = 'false' }}"));
Ok(Value::temp(result, Type::String))
}
fn ensure_boolean(&self, value: &Value) -> Result<(), CompileError> {
if matches!(value.ty, Type::Boolean) {
Ok(())
} else {
Err(CompileError::plain(
"PowerShell condition must have boolean type",
))
}
}
fn ensure_string(&self, value: &Value, command: &str) -> Result<(), CompileError> {
if matches!(value.ty, Type::String) {
Ok(())
} else {
Err(CompileError::plain(format!(
"`{command}` expects string arguments in PowerShell IR"
)))
}
}
fn ensure_string_arg(&mut self, expression: &Expr, command: &str) -> Result<(), CompileError> {
if matches!(expression.ty, Type::String) {
Ok(())
} else {
Err(CompileError::plain(format!(
"`{command}` expects string arguments in PowerShell IR"
)))
}
}
}
fn ps_type(ty: &Type) -> Result<&'static str, CompileError> {
match ty {
Type::String => Ok("string"),
Type::Number => Ok("long"),
Type::Boolean => Ok("bool"),
Type::Void => Ok("void"),
Type::Class(_) => Err(CompileError::plain(
"class-typed PowerShell declarations need their class name",
)),
}
}
fn ps_class_type(ty: &Type) -> Result<String, CompileError> {
match ty {
Type::Class(name) => Ok(name.clone()),
other => ps_type(other).map(str::to_owned),
}
}
fn default_value(ty: &Type) -> &'static str {
match ty {
Type::Number => "0",
Type::Boolean => "$false",
Type::String => "''",
Type::Void => "$null",
Type::Class(_) => "$null",
}
}
fn is_comparison(op: &str) -> bool {
matches!(op, "==" | "===" | "!=" | "!==" | "<" | "<=" | ">" | ">=")
}
fn ps_comparison(op: &str) -> Result<&'static str, CompileError> {
match op {
"==" | "===" => Ok("-ceq"),
"!=" | "!==" => Ok("-cne"),
"<" => Ok("-clt"),
"<=" => Ok("-cle"),
">" => Ok("-cgt"),
">=" => Ok("-cge"),
_ => Err(CompileError::plain(format!(
"unsupported PowerShell comparison operator `{op}`"
))),
}
}
fn is_safe_member(name: &str) -> bool {
let mut bytes = name.bytes();
match bytes.next() {
Some(byte) if byte == b'_' || byte.is_ascii_alphabetic() => {}
_ => return false,
}
bytes.all(|byte| byte == b'_' || byte.is_ascii_alphanumeric())
}
fn hex_bytes(bytes: &[u8]) -> String {
bytes.iter().map(|byte| format!("{byte:02x}")).collect()
}
fn is_safe_identifier(name: &str) -> bool {
let mut bytes = name.bytes();
let valid_start = bytes
.next()
.is_some_and(|byte| byte == b'_' || byte.is_ascii_alphabetic());
valid_start && bytes.all(|byte| byte == b'_' || byte.is_ascii_alphanumeric())
}
fn validate_program(program: &Program) -> Result<(), CompileError> {
for function in &program.functions {
validate_function(function)?;
}
for class in &program.classes {
if !is_safe_identifier(&class.name) {
return Err(CompileError::plain(format!(
"unsafe PowerShell class name `{}`",
class.name
)));
}
for field in &class.fields {
if let Some(initial) = &field.initial {
validate_expr(initial)?;
}
}
validate_function(&class.constructor)?;
for method in &class.methods {
validate_function(&method.function)?;
}
}
validate_statements(&program.body)
}
fn validate_function(function: &crate::ir::Function) -> Result<(), CompileError> {
if !is_safe_identifier(&function.name) {
return Err(CompileError::plain(format!(
"unsafe PowerShell function name `{}`",
function.name
)));
}
for param in &function.params {
if !is_safe_identifier(¶m.name) {
return Err(CompileError::plain(format!(
"unsafe PowerShell parameter name `{}`",
param.name
)));
}
}
validate_statements(&function.body)
}
fn validate_statements(statements: &[Stmt]) -> Result<(), CompileError> {
for statement in statements {
match statement {
Stmt::Let { name, value } => {
if !is_safe_identifier(name) {
return Err(CompileError::plain(format!(
"unsafe PowerShell variable name `{name}`"
)));
}
validate_expr(value)?;
}
Stmt::Assign { place, value } => {
match place {
Place::Variable(name) => {
if !is_safe_identifier(name) {
return Err(CompileError::plain(format!(
"unsafe PowerShell variable name `{name}`"
)));
}
}
Place::Field { object, class, .. } => {
if !is_safe_identifier(class) {
return Err(CompileError::plain(format!(
"unsafe PowerShell class name `{class}`"
)));
}
validate_expr(object)?;
}
}
validate_expr(value)?;
}
Stmt::Expr(expression) | Stmt::Return(Some(expression)) => validate_expr(expression)?,
Stmt::If {
condition,
then_body,
else_body,
} => {
validate_expr(condition)?;
validate_statements(then_body)?;
validate_statements(else_body)?;
}
Stmt::While { condition, body } => {
validate_expr(condition)?;
validate_statements(body)?;
}
Stmt::For {
init,
condition,
update,
body,
} => {
validate_statements(init)?;
if let Some(condition) = condition {
validate_expr(condition)?;
}
validate_statements(update)?;
validate_statements(body)?;
}
Stmt::Command { args, .. } => {
for argument in args {
validate_expr(argument)?;
}
}
Stmt::Block(body) => validate_statements(body)?,
Stmt::Return(None) | Stmt::Break | Stmt::Continue | Stmt::Raw(_) | Stmt::Comment(_) => {
}
}
}
Ok(())
}
fn validate_expr(expression: &Expr) -> Result<(), CompileError> {
match &expression.kind {
ExprKind::String(_) | ExprKind::Number(_) | ExprKind::Boolean(_) => {}
ExprKind::Variable(name) => {
if name != "__tsh_this" && !is_safe_identifier(name) {
return Err(CompileError::plain(format!(
"unsafe PowerShell variable name `{name}`"
)));
}
}
ExprKind::Template(parts) => {
for part in parts {
validate_expr(part)?;
}
}
ExprKind::Binary { left, right, .. } => {
validate_expr(left)?;
validate_expr(right)?;
}
ExprKind::Unary { value, .. } | ExprKind::Env(value) => validate_expr(value)?,
ExprKind::Call { function, args } => {
if !is_safe_identifier(function) {
return Err(CompileError::plain(format!(
"unsafe PowerShell function name `{function}`"
)));
}
for argument in args {
validate_expr(argument)?;
}
}
ExprKind::New { class, args } => {
if !is_safe_identifier(class) {
return Err(CompileError::plain(format!(
"unsafe PowerShell class name `{class}`"
)));
}
for argument in args {
validate_expr(argument)?;
}
}
ExprKind::Field { object, class, .. } => {
if !is_safe_identifier(class) {
return Err(CompileError::plain(format!(
"unsafe PowerShell class name `{class}`"
)));
}
validate_expr(object)?;
}
ExprKind::Method {
object,
class,
method,
args,
} => {
if !is_safe_identifier(class) {
return Err(CompileError::plain(format!(
"unsafe PowerShell class name `{class}`"
)));
}
if !is_safe_identifier(method) {
return Err(CompileError::plain(format!(
"unsafe PowerShell method name `{method}`"
)));
}
if let Some(object) = object {
validate_expr(object)?;
}
for argument in args {
validate_expr(argument)?;
}
}
}
Ok(())
}