Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 37 additions & 7 deletions interpreter/src/ir/lower.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,17 @@ mod utils;

use std::{
fmt::{self, Display},
mem::{DropGuard, replace},
mem::{DropGuard, replace, take},
ops::{Deref, DerefMut},
vec::Vec as StdVec,
};

use bumpalo::{Bump, collections::Vec};
use parser::{
ArrayPlace, Ast, Atom, BinaryOperator, BinaryPlaceOperator, Body, Command, Expr, ExprNode,
Function as AstFunction, FunctionTable, Getline, Identifier, MetaId, Place, PlacingFunction,
Rule, RulePattern, SimpleStatement, Statement, StaticInterner, UnaryOperator,
UnaryPlaceOperator, Variable,
AriadneSpan, ArrayPlace, Ast, Atom, BinaryOperator, BinaryPlaceOperator, Body, Command,
Diagnostic, Expr, ExprNode, Function as AstFunction, FunctionTable, Getline, Identifier,
MetaId, ParsingError, Place, PlacingFunction, Rule, RulePattern, SimpleStatement, Statement,
StaticInterner, UnaryOperator, UnaryPlaceOperator, Variable,
};
use smallvec::SmallVec;

Expand Down Expand Up @@ -56,6 +56,10 @@ pub struct CodeGen<'a> {
break_exits: Option<SmallVec<[Label; 4]>>,
continue_label: Option<Label>,
local_args: SmallVec<[UserNonLocal; 4]>,
/// Uses of a function name as a variable (they share a namespace), found
/// while lowering. Each is the name and the metadata of the statement that
/// used it; reported as diagnostics once lowering finishes.
name_conflicts: StdVec<(Identifier, MetaId)>,
}

impl<'a> CodeGen<'a> {
Expand All @@ -76,11 +80,19 @@ impl<'a> CodeGen<'a> {
break_exits: None,
continue_label: None,
local_args: SmallVec::new(),
name_conflicts: StdVec::new(),
}
}

pub fn lower_ast(&mut self, ast: &Ast) {
pub fn lower_ast(&mut self, ast: &mut Ast) {
self.bc.funs_label = Label(self.bc.len());
// Function names must all be registered before any body is lowered, so
// that `TypedPlace::new_user` can detect a function name used as a
// variable no matter where the function is declared. The bodies are
// lowered right after, filling in each function's bytecode location.
for &name in ast.functions.keys() {
self.symbols.get_user_fun(name);
}
self.lower_functions(&ast.functions);

self.bc.begin_label = self.lower_special_rules(&ast.begin);
Expand All @@ -92,6 +104,17 @@ impl<'a> CodeGen<'a> {
for rule in &ast.rules {
self.lower_rule(rule);
}

// Function names and variable names share a single namespace (like
// gawk's "function `f' used as variable name"). Report every conflict
// found while lowering, pointing at the offending statement's span.
let Ast { loc_metadata, diagnostics, .. } = ast;
for (ident, meta) in take(&mut self.name_conflicts) {
if let Some((_, AriadneSpan(file, span))) = loc_metadata.get(meta) {
ParsingError::FunctionNameAsVariable(*span, format!("{ident:?}"))
.add_diagnostic_cached(diagnostics, AriadneSpan(file.clone(), *span));
}
}
}

fn lower_special_rules(&mut self, rules: &[Body]) -> Label {
Expand All @@ -107,7 +130,14 @@ impl<'a> CodeGen<'a> {
if let Some(pattern) = pattern {
match pattern {
RulePattern::Expression(expr) => {
self.emit_branch(expr, |this| this.lower_actions(actions.as_ref()));
// Statements carry their own metadata, but a bare pattern
// is lowered without one; use the pattern's span so name
// conflicts (and bytecode metadata) point at it.
let meta = match expr {
Expr::Leaf(_, meta) | Expr::Node(_, meta) => *meta,
};
let this = &mut *self.with_metadata(meta);
this.emit_branch(expr, |this| this.lower_actions(actions.as_ref()));
}
RulePattern::Range(_, _) => todo!(),
}
Expand Down
9 changes: 9 additions & 0 deletions interpreter/src/ir/lower/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,15 @@ impl TypedPlace {
}

pub fn new_user(code: &mut CodeGen, ident: Identifier) -> Self {
// Function names and variable names share a single namespace, so a

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

6 lines of comment, please make it shorter :)
same for the ones in lower_ast and on is_user_fun

// declared function name may not be used as a variable or array (like
// gawk's "function `f' used as variable name"). All function names are
// registered up-front in `CodeGen::lower_ast`, so this catches uses in
// every rule and function body without another AST walk; the conflict
// is reported once lowering finishes.
if code.symbols.is_user_fun(ident) {
code.name_conflicts.push((ident, code.current_metadata));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

f = f + 1 will push two conflicts for the same statement, so the error is printed twice, no?

}
let usr = code.symbols.register_user_var(ident);
if let Some(reg) = code.get_local_arg(usr) {
Self(Arg { reg }, PlaceTy::Reg)
Expand Down
40 changes: 40 additions & 0 deletions interpreter/src/ir/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,46 @@ fn with_lower(source: &str, f: impl FnOnce(&CodeGen)) {
f(&cg);
}

/// Function names and variable names share a single namespace: using a
/// declared function name as a variable or array is reported while lowering,
/// wherever the name is used, like gawk's "used as variable name" error.
#[test]
fn function_name_used_as_variable_is_reported_while_lowering() {
for source in [
"function f() { return 1 } BEGIN { f = 2; print f }",
"BEGIN { g[1] = 1 } function g() { }",
"function h() { } BEGIN { h += 1 }",
"function i() { } $0 == i { print }",
] {
let arena = Bump::new();
let mut parser = Parser::new(&arena, false);
let ast = parser
.parse(FileCache(None), source.as_bytes())
.expect("parse must succeed; the conflict is found while lowering");
let mut cg = CodeGen::new(&arena);
cg.lower_ast(ast);
assert!(
ast.diagnostics.is_unrecoverable(),
"expected a function name used as a variable to be reported: {source}"
);
}
}

#[test]
fn lowering_a_program_without_name_conflicts_reports_nothing() {
let arena = Bump::new();
let mut parser = Parser::new(&arena, false);
let ast = parser
.parse(
FileCache(None),
b"function f(x) { return x } BEGIN { y = f(3); print y }",
)
.expect("parse");
let mut cg = CodeGen::new(&arena);
cg.lower_ast(ast);
assert!(!ast.diagnostics.is_unrecoverable());
}

#[test]
fn switch_lowers_case_comparisons() {
with_lower(
Expand Down
14 changes: 14 additions & 0 deletions interpreter/src/vm/symbols.rs
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,11 @@ impl<'a, T> RawSymbolTable<'a, T> {
.get_index_of(&ident)
.map(|ix| (UserNonLocal(ix.try_into().unwrap()), &mut self.0[ix]))
}

#[inline(always)]
pub(super) fn contains(&self, ident: Identifier) -> bool {
self.0.get_index_of(&ident).is_some()
}
}

impl<'a> SymbolTable<'a> {
Expand Down Expand Up @@ -262,6 +267,15 @@ impl<'a> SymbolTable<'a> {
self.functions.register(name, None)
}

/// Whether `name` is a user function name, either already defined or
/// referenced by a call. Function names and variable names share a single
/// namespace, so [`Self::register_user_var`] must never be fed one of
/// these without reporting a name conflict first.
#[inline(always)]
pub fn is_user_fun(&self, name: Identifier) -> bool {
self.functions.contains(name)
}

pub fn get_btin(&self, var: BuiltInVar) -> &Value<'a> {
match var {
BuiltInVar::Nr => &self.nr,
Expand Down
11 changes: 10 additions & 1 deletion parser/src/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,10 @@ pub enum ParsingError {
NextInForbiddenCtx(Span),
#[error("`nextfile` is forbidden in BEGIN, END, and ENDFILE rules!")]
NextFileInForbiddenCtx(Span),
#[error("Function name `{}` cannot be used as a variable or array.", .1)]
FunctionNameAsVariable(Span, String),
#[error("Function name `{}` cannot be used as a parameter of function `{}`.", .1, .2)]
FunctionNameAsParameter(Span, String, String),
}

impl ParsingError {
Expand Down Expand Up @@ -226,12 +230,17 @@ impl ParsingError {
| &Self::ReturnOutsideFunction(span)
| &Self::CommandDoubleCall(span, _)
| &Self::NextInForbiddenCtx(span)
| &Self::NextFileInForbiddenCtx(span) => Some(span),
| &Self::NextFileInForbiddenCtx(span)
| &Self::FunctionNameAsVariable(span, _)
| &Self::FunctionNameAsParameter(span, _, _) => Some(span),
}
}
const fn hint(&self) -> Option<&'static str> {
match self {
Self::DuplicatedArgument(_, _, _) => Some("Consider giving the argument another name."),
Self::FunctionNameAsParameter(_, _, _) => {
Some("Consider giving the parameter another name.")
}
Self::ExpectedStatementEnd(_) => Some(
"Valid statement ends are newlines, semicolons `;` and right brackets `}` if on a block.",
),
Expand Down
24 changes: 23 additions & 1 deletion parser/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -542,8 +542,20 @@ impl<'a> Parser<'a> {
{
let node = Box::into_inner(node);
if let ExprNode::InArray(array, expr) = node
&& let [Expr::Leaf(Atom::Variable(var), _)] = expr.as_slice()
&& let [Expr::Leaf(Atom::Variable(var), meta)] = expr.as_slice()
{
// `for (var in array)` may not reuse a function name as
// the loop variable (gawk rejects it too). Report it at
// the span stored for the variable.
if let Variable::User(ident) = var
&& self.ast.functions.contains_key(ident)
{
let AriadneSpan(_, span) = &self.ast.loc_metadata[*meta];
return Err(ParsingError::FunctionNameAsVariable(
*span,
format!("{ident:?}"),
));
}
(*var, array)
} else {
return Err(ParsingError::InvalidForLoop(lex.span()));
Expand Down Expand Up @@ -778,6 +790,16 @@ impl<'a> Parser<'a> {
format!("{name:?}"),
));
}
// Function names and variable names share a single namespace, so a
// function name is not a valid parameter name (like gawk's
// "cannot use function name as parameter name").
if arg == name || self.ast.functions.contains_key(&arg) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this only sees the functions declared before, so function f(g) { } function g() { } is still accepted.
now that all the names are registered up-front in lower_ast, could you please do the check in lower_fun_body and keep only arg == name here?

return Err(ParsingError::FunctionNameAsParameter(
lex.span(),
format!("{arg:?}"),
format!("{name:?}"),
));
}
args.push(arg);

if !lex.consume(&Token::Comma) {
Expand Down
36 changes: 36 additions & 0 deletions parser/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -558,6 +558,42 @@ fn test_parser_pratt_error_spans() {
assert_eq!(spanned_snippet(source, span), "a[1 }");
}

#[test]
fn test_function_name_cannot_be_used_as_parameter() {
let source = "function f(f) { return f } BEGIN { print f(3) }";
assert!(matches!(
parse(source, &Bump::new()),
Err(ParsingError::FunctionNameAsParameter(_, _, _))
));

// A parameter reusing an already declared function name is rejected too.
assert!(matches!(
parse("function g() { } function h(g) { return g }", &Bump::new()),
Err(ParsingError::FunctionNameAsParameter(_, _, _))
));

// Parameter names of other functions are unaffected.
assert!(
parse(
"function f(x) { return x } function g(y) { return f(y) }",
&Bump::new()
)
.is_ok()
);
}

#[test]
fn test_function_name_cannot_be_used_as_foreach_variable() {
let source = "function f() { } BEGIN { for (f in a) { print } }";
assert!(matches!(
parse(source, &Bump::new()),
Err(ParsingError::FunctionNameAsVariable(_, _))
));

// A regular variable as the loop variable stays valid.
assert!(parse("BEGIN { for (x in a) { print } }", &Bump::new()).is_ok());
}

#[test]
fn test_parser_switch() {
let source = r#"
Expand Down
7 changes: 7 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,13 @@ fn uu_main() -> Result<(), Box<dyn Error>> {

let mut cg = CodeGen::new(&rt_arena);
cg.lower_ast(ast);
// Lowering reports uses of a function name as a variable (function and
// variable names share one namespace) before the program gets to run.
if ast.diagnostics.is_unrecoverable() {
ast.diagnostics.flush()?;
// The program is invalid: exit like on any parse error.
exit_err(Option::<&str>::None, EXIT_FAILURE)
}
(cg, take(&mut ast.loc_metadata), take(&mut ast.diagnostics))
};

Expand Down
41 changes: 41 additions & 0 deletions tests/by-util/test_awk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1386,6 +1386,47 @@ fn syntax_error_does_not_run_the_program() {
.no_stdout();
}

#[test]
fn function_name_as_variable_exits_one() {
// Function and variable names share one namespace; gawk rejects these.
ucmd()
.arg("function f() { return 1 } BEGIN { f = 2; print f }")
.fails_with_code(1)
.no_stdout()
.stderr_contains("cannot be used as a variable");
ucmd()
.arg("BEGIN { g[1] = 1 } function g() { }")
.fails_with_code(1)
.no_stdout()
.stderr_contains("cannot be used as a variable");
ucmd()
.arg("function h() { } BEGIN { h += 1 }")
.fails_with_code(1)
.no_stdout();
}

#[test]
fn function_name_as_parameter_exits_one() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

#169 also lists calling a parameter as a function (paramasfunc1/2), e.g. function f(a) { a() } BEGIN { f(1) }. Is it handled? please add a test

ucmd()
.arg("function f(f) { return f } BEGIN { print f(3) }")
.fails_with_code(1)
.no_stdout()
.stderr_contains("cannot be used as a parameter");
ucmd()
.arg("function h(h) { } BEGIN { }")
.fails_with_code(1)
.no_stdout();
}

#[test]
fn function_name_as_foreach_variable_exits_one() {
ucmd()
.arg("function f() { } BEGIN { for (f in a) { print } }")
.fails_with_code(1)
.no_stdout()
.stderr_contains("cannot be used as a variable");
}

#[test]
fn variables_not_clobbered_by_side_effects() {
ucmd()
Expand Down