The unify code was a bit dumb here where we always set emit_error to false for any
subtypes for example in comparing tuples we always emitted the whole tuple didnt
match the other tuple but really its much better to say expected bool got i32 because
the element types didn't match.
gcc/rust/ChangeLog:
* typecheck/rust-coercion.cc (TypeCoercionRules::coerce_unsized): dont emit error here
* typecheck/rust-unify.cc (UnifyRules::resolve_subtype): new helper to handle emit error
(UnifyRules::expect_adt): call resolve_subtype
(UnifyRules::expect_reference): likewise
(UnifyRules::expect_pointer): likewise
(UnifyRules::expect_array): likewise
(UnifyRules::expect_slice): likewise
(UnifyRules::expect_fndef): likewise
(UnifyRules::expect_fnptr): likewise
(UnifyRules::expect_tuple): likewise
(UnifyRules::expect_closure): likewise
(UnifyRules::expect_opaque): likeiwse
* typecheck/rust-unify.h: add new helper to header
gcc/testsuite/ChangeLog:
* rust/compile/traits9.rs: update errors
* rust/compile/unify-errors1.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
gcc/rust/ChangeLog:
* resolve/rust-default-resolver.cc
(DefaultResolver::visit_if_let_patterns): New function
definition.
(DefaultResolver::visit): New IfLetExpr visitor definition.
* resolve/rust-default-resolver.h
(DefaultResolver::visit_if_let_patterns): New function
declaration.
(DefaultResolver::visit): New IfLetExpr visitor declaration.
* resolve/rust-late-name-resolver-2.0.cc (Late::visit): Remove
IfLetExpr visitor definition.
(Late::visit_if_let_patterns): New function definition.
* resolve/rust-late-name-resolver-2.0.h (Late::visit): Remove
IfLetExpr visitor declaration.
(Late::visit_if_let_patterns): New function declaration.
* resolve/rust-name-resolution-context.h (BindingSource::IfLet):
New enumerator.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
This was upstreamed as part of ea34614225
but never made it to our downstream repo. I've added Philip as a
co-author, since he wrote the upstream commit.
gcc/rust/ChangeLog:
* rust-lang.cc: Remove direct inclusion of "config.h" and
"system.h", move inclusion of "rust-system.h" upwards.
Co-authored-by: Philip Herron <herron.philip@googlemail.com>
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
This is the initial patch for RPIT, we can build on this to handle the
more complex cases but there are enough distinct changes going on here
that it should just get merged now.
RPIT is really a sneaky generic so for example:
fn foo() -> impl Bar {
Baz
}
This is represented as: fn () -> OpaqueType Bar. But when we handle the
coercion site for Baz on impl Bar when we type resolve the function we
know that the underlying type is Baz. Note this function is _not_ generic
so its using this special OpaqueType and keeping track of the underlying type
in its ty_ref reference hir-id which will resolve to Baz.
This also means if we have a case where maybe this was in an if statement:
fn foo(a: i32) -> impl Bar {
if a > 10 {
Baz
} else {
Qux
}
}
The rules of impl Bar is that Baz is handled but Baz and Qux are different
underlying types so this is not allowed. The reason is impl traits are not
generic and although from a programmer perspective the callers dont know what
the underlying type is, the compiler _knows_ what it is. So really when
you call a function and get its return position impl trait the compiler knows
what to do and does all whats nessecary to handle calling functions using that
type etc.
gcc/rust/ChangeLog:
* backend/rust-compile-type.cc (TyTyResolveCompile::visit): we need to resolve the
underlying type
* typecheck/rust-substitution-mapper.cc (SubstMapperInternal::visit): just clone
* typecheck/rust-tyty-call.cc (TypeCheckCallExpr::visit):
ensure we monomphize to get the underlying
* typecheck/rust-tyty.cc (BaseType::destructure): handle opaque types
(OpaqueType::resolve): this is much simpler now
(OpaqueType::handle_substitions): no longer needed
* typecheck/rust-tyty.h: update header
* typecheck/rust-unify.cc (UnifyRules::expect_opaque): unify rules for opaque
gcc/testsuite/ChangeLog:
* rust/compile/bad-rpit1.rs: New test.
* rust/execute/torture/impl_rpit1.rs: New test.
* rust/execute/torture/impl_rpit2.rs: New test.
* rust/execute/torture/impl_rpit3.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
When working on rpit we needed to change to use a monomorphized clone of
the result of function calls. This ended up causing a verify gimple issue
with tuples because:
fn test<A, B>(a: A, b: B) -> (A, B)
When passing for example:
let a = test::<i32, i32> (123, 456) -> (A=i32, B=i32)
The resulting gimple types became:
const struct (A=i32, B=i32) vs struct (i32, i32)
We removed the VIEW_CONVERT_EXPR support to auto fix this stuff a good
while ago because it hides these kinds of issues because the type hasher
included the A=i32, B=i32 vs the i32, i32 name so updating this to use
get_name instead keeps the naming the same as well as the fields meaning
these types are 100% equivilant and therefore no conversion is required.
This only occurs because tuples are not named types we should really add
more rust specific info on our gimple TYPES.
gcc/rust/ChangeLog:
* backend/rust-compile-type.cc (TyTyResolveCompile::visit): use get_name
* typecheck/rust-tyty.cc (TupleType::get_name): likewise
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
Cloning inference variables is very expensive because it means we are indirectly
creating an implicit new inference variable added to the reference chain.
gcc/rust/ChangeLog:
* checks/errors/privacy/rust-privacy-reporter.cc (PrivacyReporter::check_base_type_privacy):
no need for unreachable here
* typecheck/rust-unify.cc (UnifyRules::commit): dont clone infer vars
(UnifyRules::expect_inference_variable): likewise
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
This is just a simple refactor to pull all the logic outside of the
closure which makes it more readable.
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check.h: new function
* typecheck/rust-typecheck-context.cc (TypeCheckContext::compute_inference_variables):
call the new helper
(TypeCheckContext::compute_infer_var): refactored code
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
This is similar to 9faba024ef, but it
applies to execute tests.
gcc/testsuite/ChangeLog:
* rust/execute/torture/for-loop1.rs: Adjust paths.
* rust/execute/torture/for-loop2.rs: Likewise.
* rust/execute/torture/iter1.rs: Likewise.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
Undefined attribute macros have no proc macro definition, which results
in a failing `rust_assert`. This changes that assert to an if statement,
that returns early if there is no proc macro definition. Fixes#3661.
gcc/rust/ChangeLog:
* resolve/rust-early-name-resolver-2.0.cc (Early::visit_attributes): rust_assert to if
gcc/testsuite/ChangeLog:
* rust/compile/issue-3661.rs: Test NR2 has expected behavior
Signed-off-by: Tom Schollenberger <tss2344@g.rit.edu>
This should be unnecessary, since even C++11 has implicit move.
gcc/rust/ChangeLog:
* parse/rust-parse-impl.h (Parser::parse_expr_stmt): Avoid
reference binding and remove std::move in return statements.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
gcc/rust/ChangeLog:
* ast/rust-ast-visitor.cc
(DefaultASTVisitor::visit): Only visit the path of an instance
of Visibility if the instance has a path.
* ast/rust-ast.h
(SimplePath::SimplePath): Make sure constructors are explicit.
* resolve/rust-early-name-resolver-2.0.cc
(Early::visit_attributes): Pass entire paths to
NameResolutionContext::resolve_path.
(Early::visit): Likewise and avoid copying a path.
* resolve/rust-forever-stack.hxx
(ForeverStack::resolve_path): Assert that at least one path
segment has been passed in.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
gcc/rust/ChangeLog:
* checks/errors/borrowck/rust-bir-builder-internal.h: Include
"rust-immutable-name-resolution-context.h" and "options.h".
(AbstractBuilder::resolve_label): Use the 2.0 name resolver when
it's enabled.
(AbstractBuilder::resolve_variable): Likewise.
(AbstractBuilder::resolve_variable_or_fn): Likewise.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
This patch ensuers we reuse the Builder for new type to
ensure we create a new type from scratch ensuring consistent
new node-ids.
gcc/rust/ChangeLog:
* expand/rust-derive-default.cc (DeriveDefault::visit_struct): use builder
(DeriveDefault::visit_tuple): likewise
* expand/rust-derive-eq.cc (DeriveEq::visit_tuple): likewise
(DeriveEq::visit_struct): likewise
(DeriveEq::visit_enum): likewise
(DeriveEq::visit_union): likewise
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude: these are fixed now
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
Since r14-6076, the LANG_HOOKS_COMMON_ATTRIBUTE_TABLE should not be used and
LANG_HOOKS_ATTRIBUTE_TABLE replaces it.
Add the "cold" attribute to fix PR120018 (and the matching "hot" attribute).
Replace some gcc_assert() by explicit warnings (same as D frontend).
Add some clang-format off/on comment around code that's not correctly
formatted.
gcc/rust/ChangeLog:
PR rust/120018
* rust-attribs.cc (handle_noreturn_attribute): Reindent declaration.
(handle_leaf_attribute): Likewise.
(handle_const_attribute): Likewise.
(handle_malloc_attribute): Likewise.
(handle_pure_attribute): Likewise.
(handle_novops_attribute): Likewise.
(handle_nonnull_attribute): Likewise.
(handle_nothrow_attribute): Likewise.
(handle_type_generic_attribute): Likewise.
(handle_transaction_pure_attribute): Likewise.
(handle_returns_twice_attribute): Likewise.
(handle_fnspec_attribute): Likewise.
(handle_omp_declare_simd_attribute): Likewise.
(handle_cold_attribute): New.
(handle_hot_attribute): New.
(attribute_spec::exclusions attr_cold_hot_exclusions): New.
(grs_langhook_common_attributes): Make it static.
(grs_langhook_common_attribute_table): New.
(grs_langhook_gnu_attributes): New.
(grs_langhook_gnu_attribute_table): New.
(handle_malloc_attribute): Make it static.
(handle_fnspec_attribute): Likewise.
(handle_pure_attribute): Replace gcc_assert by explicit warning.
(handle_novops_attribute): Likewise.
(handle_nothrow_attribute): Likewise.
(handle_returns_twice_attribute): Likewise.
(handle_omp_declare_simd_attribute): Likewise and make it static.
* rust-lang.cc (grs_langhook_gnu_attribute_table): New.
(grs_langhook_common_attribute_table): Adjust type to new hook.
(LANG_HOOKS_COMMON_ATTRIBUTE_TABLE): Remove.
(LANG_HOOKS_ATTRIBUTE_TABLE): New.
Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
Empty loops have no body which means this is a NULL_TREE during const
evaluation which needs a check. Fixes Rust-GCC #3618.
gcc/rust/ChangeLog:
* backend/rust-constexpr.cc (eval_constant_expression): Check if t is a NULL_TREE
gcc/testsuite/ChangeLog:
* rust/compile/issue-3618.rs: Test empty loops error properly.
Signed-off-by: Tom Schollenberger <tss2344@g.rit.edu>
When using impl traits in argument position (APIT), they are desugared into generics,
and supplying explicit generic arguments is not allowed. This commit adds the error
diagnostic E0632 for attempting to pass generic arguments to impl traits, completing
the implementation of the APIT feature.
gcc/rust/ChangeLog:
* ast/rust-desugar-apit.cc: track if this is a impl-trait generic
* ast/rust-item.h (class TypeParam): add field to track if from impl trait
* hir/rust-ast-lower-type.cc (ASTLowerGenericParam::visit): likewise
* hir/tree/rust-hir-item.cc (TypeParam::TypeParam): upate hir as well
(TypeParam::operator=): likewise
* hir/tree/rust-hir-item.h (class TypeParam): likewise
* typecheck/rust-tyty-subst.cc (SubstitutionParamMapping::get_generic_param): add error
* typecheck/rust-tyty-subst.h: add const getter for the associated TypeParm
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude: nr2 cant handle this
* rust/compile/impl_trait_generic_arg.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
gcc/rust/ChangeLog:
* backend/rust-compile-pattern.cc
(CompilePatternCheckExpr::visit): Fix GENERIC generation in
light of enum layout changes since this code was written.
(CompilePatternBindings::handle_struct_pattern_ident_pat):
Delegate handling of child patterns to another
CompilePatternBindings::Compile call.
(CompilePatternBindings::make_struct_access): Make field name
parameter const qualified.
* backend/rust-compile-pattern.h
(CompilePatternBindings::make_struct_access): Likewise.
gcc/testsuite/ChangeLog:
* rust/execute/torture/struct-pattern-match.rs: New test.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
gcc/rust/ChangeLog:
* resolve/rust-ast-resolve-item.cc
(ResolveItem::visit): Use the return values of
CanonicalPath::inherent_impl_seg and
CanonicalPath::trait_impl_projection_seg more directly.
* util/rust-canonical-path.h
(CanonicalPath::trait_impl_projection_seg): Append "<impl "
instead of "<" to the beginning of the returned path segment.
(CanonicalPath::inherent_impl_seg): Likewise.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
Argument position impl traits are simply syntatic sugar for generics. This
adds a new desugar pass to do this. So for example:
fn foo(a: impl Value, b: impl Value) -> i32
Is desugared into:
fn foo<T: Value, U: Value> (a: T, b: U) -> i32
So it just works like any normal generic function. There are more complex cases such as:
fn foo(_value: impl Bar<Baz = impl Foo>) -> i32
Which has a generic argument binding which needs to be turned into a where constraint:
fn foo<T, U>(_value: T) -> i32
where
T: Bar<Baz = U>,
U: Foo,
Fixes Rust-GCC#2015
Fixes Rust-GCC#1487
Fixes Rust-GCC#3454
Fixes Rust-GCC#1482
gcc/rust/ChangeLog:
* Make-lang.in: new desugar file
* ast/rust-ast.cc (ImplTraitTypeOneBound::as_string): its a unique_ptr now
(FormatArgs::set_outer_attrs): reformat
* ast/rust-path.h: remove has_generic_args assertion (can be empty because of desugar)
* ast/rust-type.h (class ImplTraitTypeOneBound): add copy ctor and use unique_ptr
* hir/rust-ast-lower-type.cc (ASTLoweringType::visit): update to use unique_ptr
* parse/rust-parse-impl.h (Parser::parse_type): reuse the existing unique_ptr instead
(Parser::parse_type_no_bounds): likewise
(Parser::parse_pattern): likewise
* resolve/rust-ast-resolve-type.cc (ResolveType::visit): its a unique_ptr now
* rust-session-manager.cc (Session::compile_crate): call desugar
* ast/rust-desugar-apit.cc: New file.
* ast/rust-desugar-apit.h: New file.
gcc/testsuite/ChangeLog:
* rust/compile/issue-2015.rs: fully supported now
* rust/compile/nr2/exclude: nr2 cant handle some of these
* rust/compile/issue-1487.rs: New test.
* rust/compile/issue-3454.rs: New test.
* rust/execute/torture/impl_desugar-2.rs: New test.
* rust/execute/torture/impl_desugar.rs: New test.
* rust/execute/torture/impl_trait1.rs: New test.
* rust/execute/torture/impl_trait2.rs: New test.
* rust/execute/torture/impl_trait3.rs: New test.
* rust/execute/torture/impl_trait4.rs: New test.
* rust/execute/torture/issue-1482.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
Rust only allows impl traits to be used in the return position of
functions.
Fixes Rust-GCC#1485
gcc/rust/ChangeLog:
* hir/rust-ast-lower-implitem.cc (ASTLowerImplItem::visit): allow impl type
* hir/rust-ast-lower-item.cc (ASTLoweringItem::visit): likewise
* hir/rust-ast-lower-type.cc (ASTLoweringType::ASTLoweringType): new flag for impl trait
(ASTLoweringType::translate): pass flag
(ASTLoweringType::visit): track impl trait tag
(ASTLoweringType::emit_impl_trait_error): new diagnostic
* hir/rust-ast-lower-type.h: add new field
gcc/testsuite/ChangeLog:
* rust/compile/impl_trait_diag.rs: New test.
* rust/compile/issue-1485.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
Allow matching on a struct instance and rebinding its fields to new names:
match X {
Foo {
field0: new_name0,
field1: new_name1,
} => {
do_something(new_name0, new_name1);
},
}
This will enable us to finish derives for PartialEq and PartialOrd but
isn't a complete implementation of these patterns yet.
gcc/rust/ChangeLog:
* backend/rust-compile-pattern.cc (CompilePatternBindings::make_struct_access):
New function.
(CompilePatternBindings::visit): Properly implement patterns mentioned above
and call make_struct_accesss.
* backend/rust-compile-pattern.h: New declaration.
gcc/testsuite/ChangeLog:
* rust/execute/torture/struct_pattern1.rs: New test.
Fixes PR#119641
gcc/rust/ChangeLog:
* checks/errors/borrowck/rust-bir-place.h
(IndexVec::size_type): Add.
(IndexVec::MAX_INDEX): Add.
(IndexVec::size): Change the return type to the type of the
internal value used by the index type.
(PlaceDB::lookup_or_add_variable): Use the return value from the
PlaceDB::add_place call.
* checks/errors/borrowck/rust-bir.h
(struct BasicBlockId): Move this definition before the
definition of the struct Function.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
gcc/rust/ChangeLog:
* ast/rust-ast-visitor.cc
(DefaultASTVisitor::visit): Visit the loop labels of
WhileLetLoopExpr instances before visiting their scrutinee
expressions.
* resolve/rust-early-name-resolver-2.0.cc
(Early::resolve_glob_import): Pass the glob import's path
directly to NameResolutionContext::resolve_path.
* resolve/rust-toplevel-name-resolver-2.0.cc
(TopLevel::visit): Remove unnecessary call to
Identifier::as_string.
(flatten_glob): Improve handling of cases where a glob use tree
has no path.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
Both nodes had the same id, this led to a resolution conflict.
gcc/rust/ChangeLog:
* expand/rust-derive-clone.cc (DeriveClone::clone_enum_struct): Clone
path to avoid using the same nodeid.
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude: Remove now passing test from exclusion
list.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
This commit introduce a new public function to visit function parameters
in the default visitor. It allows visitors derived from DefaultVisitor
to override only a small part of the default visitor.
gcc/rust/ChangeLog:
* ast/rust-ast-visitor.cc (DefaultASTVisitor::visit_function_params):
Add specialized function to visit function parameters.
(DefaultASTVisitor::visit): Remove parameter visit and call specialized
function instead.
* ast/rust-ast-visitor.h: Add function prototye.
* resolve/rust-late-name-resolver-2.0.cc (Late::visit): Remove
function.
(Late::visit_function_params): Override specialized visit function.
* resolve/rust-late-name-resolver-2.0.h: Add overriden function
prototype.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Binding context may be stacked when a new binding group is introduced
within a const expression.
gcc/rust/ChangeLog:
* resolve/rust-name-resolution-context.h: Use BindingLayer instead.
* resolve/rust-name-resolution-context.cc (BindingLayer::BindingLayer):
Add new constructor for binding layer.
(BindingLayer::bind_test): Add a function to test a binding constraint.
(BindingLayer::push): Push a new binding group.
(BindingLayer::and_binded): Add function to test and-binding
constraint.
(BindingLayer::or_binded): Add function to test or-binding constraints.
(BindingLayer::insert_ident): Insert a new identifier in the current
binding group.
(BindingLayer::merge): Merge current binding group with it's parent.
(BindingLayer::get_source): Get the source of the current binding
group.
* resolve/rust-late-name-resolver-2.0.cc: Use stacked context for
binding group.
* util/rust-stacked-contexts.h: Add mutable peek function.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
We need to differentiate bindings types, so the same binding cannot be
reused multiple time in a product binding.
gcc/rust/ChangeLog:
* resolve/rust-name-resolution-context.h (struct Binding): Add Binding
struct to differentiate Or and Product bindings in patterns.
(enum class): Add Binding kind.
(class BindingContext): Add binding context with Binding stack.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Name resolution 2.0 message describes the context around the unresolved
items and should therefore be kept.
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude: Remove test from exclusion list.
* rust/compile/use_1.rs: Change expected output and remove test from
nr1.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
..., using the standard idiom. This '*.exp' file doesn't adhere to the
parallel testing protocol as defined in 'gcc/testsuite/lib/gcc-defs.exp'.
This also restores proper behavior for '*.exp' files executing after (!) this
one, which erroneously caused hundreds or even thousands of individual test
cases get duplicated vs. skipped, randomly, depending on the '-jN' level.
PR testsuite/119508
gcc/testsuite/
* rust/compile/nr2/compile.exp: Disable parallel testing.
(cherry picked from commit 79d2c3089f)
There are two cases when initilizing an array, this is the
const context which means we need to build the array ctor,
which means using lots of memory, its super inefficient
because we are using a big wrapper over the GCC internals here
but preallocating the vectors here causes a:
terminate called after throwing an instance of 'std::bad_alloc'
So this is a handy error condition to rely on for this senario.
Fixes Rust-GCC#3713
Fixes Rust-GCC#3727
gcc/rust/ChangeLog:
* backend/rust-compile-expr.cc (CompileExpr::array_copied_expr): prealloc the vector
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
We have an assertion when accessing generic args if there are any which
is really useful so this adds the missing guards for the case where
they are specified but empty.
Fixes Rust-GCC#3649
gcc/rust/ChangeLog:
* ast/rust-ast-visitor.cc (DefaultASTVisitor::visit): add guard
* expand/rust-expand-visitor.cc (ExpandVisitor::visit): add guard
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude: nr2 is missing error for this
* rust/compile/issue-3649.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
We were wrongly adding the assertion that this must not be an enum but
this is a pointless assertion we only care that there are variant in the
ADT and if the field exists in the first variant.
Fixes Rust-GCC#3581
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit): fix bad assertion
gcc/testsuite/ChangeLog:
* rust/compile/nonexistent-field.rs: fix bad error message
* rust/compile/issue-3581-1.rs: New test.
* rust/compile/issue-3581-2.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
Fixes Rust-GCC#3652
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude: nr2 does not error on the T it should require Self::T
* rust/compile/issue-3652.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
gcc/rust/ChangeLog:
* resolve/rust-forever-stack.hxx
(ForeverStack::resolve_path): Pass instance of Node to lambda by
reference instead of by value.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
The error handling here was done long ago when we didnt know how to do
any error handling very well. This removed bad fatal_errors and adds in
some nice rich_location error diagnostics instead.
Fixes Rust-GCC#3628
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-struct-field.h: keep reference to parent expression
* typecheck/rust-hir-type-check-struct.cc (TypeCheckStructExpr::TypeCheckStructExpr):
update ctor
(TypeCheckStructExpr::resolve): remove bad rust_fatal_errors
(TypeCheckStructExpr::visit): cleanup errors
gcc/testsuite/ChangeLog:
* rust/compile/macros/mbe/macro-issue2983_2984.rs: cleanup error diagnotics
* rust/compile/struct_init1.rs: likewise
* rust/compile/issue-3628.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
This was already fixed in: bb01719f0e but we require fn_once lang item
to be defined as we are working on libcore support still.
Fixes Rust-GCC#3711
gcc/testsuite/ChangeLog:
* rust/compile/issue-3711.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
Add a new HIR LlvmInlineAsm HIR node as well as some structures to
represent it's options and operands. Lower AST::LlvmInlineAsm node to it
and then create a tree from that node.
gcc/rust/ChangeLog:
* ast/rust-ast-collector.cc (TokenCollector::visit): Remove unreachable
code.
* ast/rust-expr.h (struct LlvmOperand): Add LlvmOperand struct to
represent input and outputs.
(class LlvmInlineAsm): Add input, output and clobber operands.
(struct TupleTemplateStr): Add locus getter.
* backend/rust-compile-block.h: Add visit for LlvmInlineAsm.
* backend/rust-compile-expr.cc (CompileExpr::visit): Add llvm inline
asm stmt compilation.
* backend/rust-compile-expr.h: Add function prototype.
* backend/rust-compile-asm.h (class CompileLlvmAsm): Add llvm asm hir
not to gimple.
* backend/rust-compile-asm.cc (CompileLlvmAsm::CompileLlvmAsm): Add
constructor.
(CompileLlvmAsm::construct_operands): Add function to construct operand
tree.
(CompileLlvmAsm::construct_clobbers): Add function to construct clobber
tree.
(CompileLlvmAsm::tree_codegen_asm): Generate the whole tree for a given
llvm inline assembly node.
* checks/errors/borrowck/rust-bir-builder-expr-stmt.cc (ExprStmtBuilder::visit):
Add visit function.
* checks/errors/borrowck/rust-bir-builder-expr-stmt.h: Add function
prototype.
* checks/errors/borrowck/rust-bir-builder-lazyboolexpr.h: Add visit
function.
* checks/errors/borrowck/rust-bir-builder-struct.h: Likewise.
* checks/errors/borrowck/rust-function-collector.h: Likewise.
* checks/errors/privacy/rust-privacy-reporter.cc (PrivacyReporter::visit):
Likewise.
* checks/errors/privacy/rust-privacy-reporter.h: Add visit function
prototype.
* checks/errors/rust-const-checker.cc (ConstChecker::visit): Add visit
function.
* checks/errors/rust-const-checker.h: Add visit function prototype.
* checks/errors/rust-hir-pattern-analysis.cc (PatternChecker::visit):
Add visit function.
* checks/errors/rust-hir-pattern-analysis.h: Add visit function
prototype.
* checks/errors/rust-unsafe-checker.cc (UnsafeChecker::visit): Add
visit function.
* checks/errors/rust-unsafe-checker.h: Add function prototype.
* expand/rust-macro-builtins-asm.cc (parse_llvm_templates): Parse
templates.
(parse_llvm_arguments): Add function to parse non template tokens.
(parse_llvm_operands): Add function to parse operands, either input or
output.
(parse_llvm_outputs): Add function to parse and collect llvm asm
outputs.
(parse_llvm_inputs): Likewise with inputs.
(parse_llvm_clobbers): Add function to parse llvm asm clobbers.
(parse_llvm_options): Add function to parse llvm asm options.
(parse_llvm_asm): Add function to parse llvm asm.
* expand/rust-macro-builtins-asm.h (class LlvmAsmContext): Add context
for llvm asm parser.
(parse_llvm_outputs): Add function prototype.
(parse_llvm_inputs): Likewise.
(parse_llvm_clobbers): Likewise.
(parse_llvm_options): Likewise.
* hir/rust-ast-lower-expr.cc (ASTLoweringExpr::visit): Lower AST llvm
asm node to HIR.
* hir/rust-ast-lower-expr.h: Add function prototype.
* hir/rust-hir-dump.cc (Dump::visit): Add visit function.
* hir/rust-hir-dump.h: Add function prototype.
* hir/tree/rust-hir-expr-abstract.h: Add HIR llvm asm node kind.
* hir/tree/rust-hir-expr.h (struct LlvmOperand): Add LlvmOperand type
to represent input and outputs.
(class LlvmInlineAsm): Add LlvmInlineAsm hir node.
* hir/tree/rust-hir-full-decls.h (class LlvmInlineAsm): Add
LlvmInlineAsm hir node forward declaration.
* hir/tree/rust-hir-visitor.h: Add visit functions for LlvmInlineAsm
hir node.
* hir/tree/rust-hir.cc (LlvmInlineAsm::accept_vis): Add hir node
visitor related functions.
* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit):
Type check input and output operands.
* typecheck/rust-hir-type-check-expr.h: Add function prototype.
* ast/rust-ast-visitor.cc (DefaultASTVisitor::visit): Visit input and
output operand expressions.
* resolve/rust-ast-resolve-expr.cc (ResolveExpr::visit): Resolve input
and output expressions.
* resolve/rust-ast-resolve-expr.h: Add function prototypes.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
It is not allowed to have a declared inference variable in the return
position of a function as this may never get infered you need good points
of truth.
Ideally if we get a student for GSoC 25 we will get the Default Hir Visitor
so that we can grab the HIR::InferredType locus instead of using the ref
location lookups.
Fixes Rust-GCC#402
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-item.cc (TypeCheckItem::visit): add diagnostic
* typecheck/rust-tyty.cc (BaseType::contains_infer): new helper to grab first infer var
* typecheck/rust-tyty.h: prototype
gcc/testsuite/ChangeLog:
* rust/compile/issue-402.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
I copied a bad form of this check from the c front-end this updates it
to ensure the rhs is an INTEGER_CST and the lhs needs checked in the first
place.
Fixes Rust-GCC#3664
gcc/rust/ChangeLog:
* rust-gcc.cc (arithmetic_or_logical_expression): Ensure this is an integer
gcc/testsuite/ChangeLog:
* rust/compile/issue-3664.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-base.cc: Set enum representing
type properly if repr is an integer type.
* typecheck/rust-hir-type-check-item.cc: Update comments.
Signed-off-by: Yap Zhi Heng <yapzhhg@gmail.com>
Trait constants were missing type resolution step, this adds that
as if it was a normal constant. The unsafe checker was missing a
null check.
Fixes Rust-GCC#3612
gcc/rust/ChangeLog:
* checks/errors/rust-unsafe-checker.cc (UnsafeChecker::visit): add null check
* hir/tree/rust-hir-item.h: add has_type helper
* typecheck/rust-hir-trait-resolve.cc (TraitItemReference::resolve_item):
add missing type checking
gcc/testsuite/ChangeLog:
* rust/compile/issue-3612.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
This causes an assertion failure when compiling core with nr2.0, but should
probably be improved. I'm not sure how this code enables built-in derive
macros to be resolved so this is a temporary fix.
gcc/rust/ChangeLog:
* resolve/rust-early-name-resolver-2.0.cc (Early::visit_attributes): Remove assertion.
ChangeLog:
* .github/glibcxx_ubuntu64b_log_expected_warnings: Change line number
for warning from 2230 to 2236.
* .github/log_expected_warnings: Likewise.
gcc/rust/ChangeLog:
* expand/rust-macro-builtins-format-args.cc (format_args_parse_arguments): Improve safety,
allow extra commas after end of argument list.
gcc/testsuite/ChangeLog:
* rust/compile/format_args_extra_comma.rs: New test.
gcc/rust/ChangeLog:
* expand/rust-macro-expand.cc (MacroExpander::match_n_matches): Do not
insert fragments and substack fragments if the matcher failed.
gcc/testsuite/ChangeLog:
* rust/compile/macros/mbe/macro-issue3708.rs: New test.
Instead, mark the visitor as dirty and wait for the next round of the fixed point to take care of
them. This avoids issues with module items being loaded while not being stripped yet.
gcc/rust/ChangeLog:
* resolve/rust-toplevel-name-resolver-2.0.cc (TopLevel::visit): Return if module
is unloaded.
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-expr.cc (is_default_fn): New.
(emit_ambiguous_resolution_error): New.
(handle_multiple_candidates): Properly handle multiple candidates in
the case of specialization.
(TypeCheckExpr::visit): Call `handle_multiple_candidates`.
gcc/testsuite/ChangeLog:
* rust/execute/torture/min_specialization2.rs: New test.
* rust/execute/torture/min_specialization3.rs: New test.
Inside a BLOCK node, all of the variables of the scope/block
are chained together and that connects them to the block.
This just adds a comment to that effect as reading the code
it is not so obvious why they need to be chained together.
gcc/rust/ChangeLog:
PR rust/119342
* rust-gcc.cc (block): Add comment on why chaining
the variables of the scope toether.
Signed-off-by: Andrew Pinski <quic_apinski@quicinc.com>
There are some places inside rust-gcc.cc which are candidates
to use range for instead of iterators directly. This changes
the locations I saw and makes the code slightly more readable.
gcc/rust/ChangeLog:
PR rust/119341
* rust-gcc.cc (function_type): Use range fors.
(function_type_variadic): Likewise.
(fill_in_fields): Likewise.
(statement_list): Likewise.
(block): Likewise.
(block_add_statements): Likewise.
(function_set_parameters): Likewise.
(write_global_definitions): Likewise.
Signed-off-by: Andrew Pinski <quic_apinski@quicinc.com>
Just a simple cleanupof the code to use error_operand_p
instead of directly comparing against error_mark_node.
This also moves some cdoe around when dealing with error_operand_p
just to be faster and/or slightly tighten up the code slightly.
gcc/rust/ChangeLog:
* rust-gcc.cc (Bvariable::get_tree): Use error_operand_p.
(pointer_type): Likewise.
(reference_type): Likewise.
(immutable_type): Likewise.
(function_type): Likewise.
(function_type_variadic): Likewise.
Cleanup the check for receiver.type first.
(function_ptr_type): Use error_operand_p.
(fill_in_fields): Likewise.
(fill_in_array): Likewise.
(named_type): Likewise.
(type_size): Likewise.
(type_alignment): Likewise.
(type_field_alignment): Likewise.
(type_field_offset): Likewise.
(zero_expression): Likewise.
(float_constant_expression): Likewise.
(convert_expression): Likewise.
(struct_field_expression): Likewise.
(compound_expression): Likewise.
(conditional_expression): Likewise.
(negation_expression): Likewise.
(arithmetic_or_logical_expression): Likewise.
(arithmetic_or_logical_expression_checked): Likewise.
(comparison_expression): Likewise.
(lazy_boolean_expression): Likewise.
(constructor_expression): Likewise.
(array_constructor_expression): Likewise.
(array_index_expression): Likewise.
(call_expression): Likewise.
(init_statement): Likewise.
(assignment_statement): Likewise.
(return_statement): Likewise.
(exception_handler_statement): Likewise.
(if_statement): Likewise.
(compound_statement): Likewise.
Tighten up the code, removing t variable.
(statement_list): Use error_operand_p.
(block): Likewise.
(block_add_statements): Likewise.
(convert_tree): Likewise.
(global_variable): Likewise.
(global_variable_set_init): Likewise.
(local_variable): Likewise.
(parameter_variable): Likewise.
(static_chain_variable): Likewise.
(temporary_variable): Likewise.
(function): Likewise. Tighten up the code.
(function_defer_statement): Use error_operand_p.
(function_set_parameters): Use error_operand_p.
(write_global_definitions): Use error_operand_p.
Tighten up the code around the loop.
Signed-off-by: Andrew Pinski <quic_apinski@quicinc.com>
This moves is_floating_point over to using FLOAT_TYPE_P instead
of manually checking. Note before it would return true for all
COMPLEX_TYPE but complex types' inner type could be integral.
Also fixes up the comment to be in more of the GNU style.
Bootstrapped and tested on x86_64-linux-gnu.
gcc/rust/ChangeLog:
* rust-gcc.cc (is_floating_point): Use FLOAT_TYPE_P
instead of manually checking the type.
Signed-off-by: Andrew Pinski <quic_apinski@quicinc.com>
This patch fixes an issue where an empty feature gate would segfault,
instead of reporting a syntax error to the user.
gcc/rust/ChangeLog:
* ast/rust-ast.h: (AST::Attribute): add empty_input function
* checks/errors/rust-feature-gate.cc: (FeatureGate::visit): check for empty feature gate
gcc/testsuite/ChangeLog:
* rust/compile/feature.rs: add an invalid empty feature to produce an error
Signed-off-by: Matty Kuhn <matty.kuhn.1@gmail.com>
gcc/rust/ChangeLog:
* parse/rust-parse-impl.h (Parser::parse_loop_label): Change function
return type to expected.
(Parser::parse_labelled_loop_expr): Adapt call location to new return
type.
* parse/rust-parse.h (enum class): Update function prototype.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Name resolution 2.0 behavior matches more closely rustc's behavior
and trying to prevent undeclared label error emission would break some
other test.
gcc/testsuite/ChangeLog:
* rust/compile/invalid_label_name.rs: Adapt test to nr2.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
gcc/rust/ChangeLog:
* resolve/rust-late-name-resolver-2.0.cc (Late::visit): Add call
to label resolution if there is one label.
(Late::resolve_label): Look for labels and emit an error message on
failure.
* resolve/rust-late-name-resolver-2.0.h: Add function prototypes.
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude: Remove test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
The visitor was visiting loop label even when they did not exist.
gcc/rust/ChangeLog:
* ast/rust-ast-visitor.cc (DefaultASTVisitor::visit): Add
check for loop label before visiting it.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
These constructor for eroneous state are not in use anymore since we
replaced this error state with an optional in the parent nodes.
gcc/rust/ChangeLog:
* ast/rust-expr.h: Remove error getter and constructor.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
A loop label error state was in use to represent missing loop label but
this may be easily forgotten and the optional nature of the label was
misrepresented.
gcc/rust/ChangeLog:
* ast/rust-ast-builder.cc (Builder::block): Call with a nullopt instead
of an error loop label.
(WhileLetLoopExpr::as_string): Use getter function and adapt to
newtype.
* ast/rust-ast.cc (WhileLoopExpr::as_string): Likewise.
(LoopExpr::as_string): Likewise.
(BreakExpr::as_string): Likewise.
(ForLoopExpr::as_string): Likewise.
* ast/rust-expr.h (class BlockExpr): Make loop label optional.
(class BreakExpr): Likewise.
* expand/rust-derive-clone.cc (DeriveClone::clone_fn): Use nullopt.
* expand/rust-derive-debug.cc (DeriveDebug::stub_debug_fn): Likewise.
* expand/rust-derive-default.cc (DeriveDefault::default_fn): Likewise.
* expand/rust-derive-eq.cc: Likewise.
* parse/rust-parse-impl.h (Parser::parse_block_expr): Use optional
for arguments.
(Parser::parse_loop_expr): Likewise.
(Parser::parse_while_loop_expr): Likewise.
(Parser::parse_while_let_loop_expr): Likewise.
(Parser::parse_for_loop_expr): Likewise.
(Parser::parse_labelled_loop_expr): Likewise.
(Parser::parse_loop_label): Return an optional.
* parse/rust-parse.h: Update function prototype and use nullopt for
default values.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
If the label is referenced within the while predicate expression it has
to be resolved before the latter.
gcc/rust/ChangeLog:
* ast/rust-ast-visitor.cc (DefaultASTVisitor::visit): Change default
visit order.
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude: Remove test from exclusion list.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
This commit got rid of msvc specific code and remove the else clause,
this triggered warning with tl::expected::value function.
gcc/rust/ChangeLog:
* util/expected.h: Use gcc_unreachable within gcc context.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
gcc/rust/ChangeLog:
* resolve/rust-ast-resolve-base.h (redefined_error): created a function for
rust_error_at for redefined at multiple times.
* resolve/rust-ast-resolve-implitem.h: changed rust_error_at to redefined_error.
* resolve/rust-ast-resolve-stmt.cc (ResolveStmt::visit): changed rust_error_at to
redefined_error.
* resolve/rust-ast-resolve-stmt.h: changed rust_error_at to redefined_error.
* resolve/rust-ast-resolve-toplevel.h: changed rust_error_at to redefined_error.
Signed-off-by: Sri Ganesh Thota <sriganeshthota12345@gmail.com>
gcc/testsuite/ChangeLog:
* rust/compile/nr2/compile.exp: Avoid absolute paths in output,
adjust phrasing of output, and avoid false XPASS output when
tests are run in parallel.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
gcc/rust/ChangeLog:
* ast/rust-ast-visitor.cc
(DefaultASTVisitor::visit): Remove explicit visitation of a
function's self parameter, as if it exists it'll be visited as
one of the function parameters.
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude: Remove entry.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
This is a reserved name so this changes the assertion to a diagnostic.
Fixes Rust-GCC#3647
gcc/rust/ChangeLog:
* typecheck/rust-typecheck-context.cc (TypeCheckContext::lookup_lifetime): emit error
gcc/testsuite/ChangeLog:
* rust/compile/issue-3647.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
We need to check upfront if the type is valid or not. Then
error with a decent message.
Fixes Rust-GCC#3643
Fixes Rust-GCC#3646
Fixes Rust-GCC#3654
Fixes Rust-GCC#3663
Fixes Rust-GCC#3671
gcc/rust/ChangeLog:
* resolve/rust-ast-resolve-type.cc (ResolveRelativeTypePath::go): fix error msg
* typecheck/rust-substitution-mapper.cc (SubstMapper::Resolve): add validation
(SubstMapper::valid_type): new check
(SubstMapper::visit): check if can resolve
* typecheck/rust-substitution-mapper.h: new prototype
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude: nr2 is missing type path error
* rust/compile/issue-3643.rs: New test.
* rust/compile/issue-3646.rs: New test.
* rust/compile/issue-3654.rs: New test.
* rust/compile/issue-3663.rs: New test.
* rust/compile/issue-3671.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
This patch adds support for raw references which enforce the pointer
type away from a reference type.
Fixes Rust-GCC#3667
gcc/rust/ChangeLog:
* backend/rust-compile-base.cc (HIRCompileBase::address_expression): allow optional type
* backend/rust-compile-base.h: update prototype
* backend/rust-compile-expr.cc (CompileExpr::visit): update borrow expr
* backend/rust-compile-extern.h: remove unused debug
* backend/rust-compile-resolve-path.cc (HIRCompileBase::query_compile): update usage
* hir/rust-ast-lower-expr.cc (ASTLoweringExpr::visit): lower raw ref
* hir/tree/rust-hir-expr.cc (BorrowExpr::BorrowExpr): add flag for raw ref
* hir/tree/rust-hir-expr.h (class BorrowExpr): add new raw ref field
* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit): add handle for raw ref
gcc/testsuite/ChangeLog:
* rust/compile/issue-3667.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
We hit assertions on empty enum or unknown variant, this catches the error
and emits a new diagnostic.
Fixes Rust-GCC#3656
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-pattern.cc (TypeCheckPattern::visit): emit error
gcc/testsuite/ChangeLog:
* rust/compile/issue-3656.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
This was a small fix to sort out the segfault to check for nullptr on the
TypePath cases for query type. But when this happened opened up a few bugs
that were hidden under the carpet namely: compile/issue-2905-{1,2}.rs which
has a recursive type query which needs to ne handled but now and error
message is being output for the type path. This happens because we start
resolving a generic struct:
struct Wierd<T>(A<(T,)>);
So the child field A is also generic and the generic argument of the tuple
of T needs to be applied to this generic field. This causes a chunk of
code to do bounds checking to ensure the bounds are ok, this is also
something that probably might change as generic types will have the bounds
secified anyway but thats besides the case right now. So once this bounds
checking occurs we endup looking at the impl block for Wierd<i32> which is
also grand but we still havent finished resolving the parent type of Wierd
which is recusive. But the query type system needs to check for that.
The other issue was: compile/issue-3022.rs which is a resolution issue:
impl<T: Foo<U>, U> Foo<U> for Bar<T, U>
The bound of Foo<T> is added to T before U is resolved but this was hidden
before the new error message was added. So now we have a generic
arguements handler being used correctly all over the code base apart from
1 last case for Traits but we will deal with that later. This handles the
case by setting up the type parameters upfront then sorting out their
bounds.
Fixes Rust-GCC#3625
gcc/rust/ChangeLog:
* typecheck/rust-hir-trait-resolve.cc (TraitResolver::resolve_trait): new argument
* typecheck/rust-hir-type-check-base.cc (TypeCheckBase::TypeCheckBase): new helper
* typecheck/rust-hir-type-check-base.h: new helper prototype
* typecheck/rust-hir-type-check-implitem.cc (TypeCheckTopLevelExternItem::visit):
remove comment out code
* typecheck/rust-hir-type-check-path.cc (TypeCheckExpr::resolve_root_path): check for null
* typecheck/rust-hir-type-check-type.cc (TypeCheckType::resolve_root_path): likewise
(TypeResolveGenericParam::Resolve): new args
(TypeResolveGenericParam::ApplyAnyTraitBounds): new helper
(TypeResolveGenericParam::apply_trait_bounds): new field
(TypeResolveGenericParam::visit): update
* typecheck/rust-hir-type-check-type.h: new args
* typecheck/rust-hir-type-check.cc (TraitItemReference::get_type_from_fn): reuse helper
* typecheck/rust-type-util.cc (query_type): check for recursive query
* typecheck/rust-tyty-subst.cc (SubstitutionParamMapping::SubstitutionParamMapping):
remove const
(SubstitutionParamMapping::get_generic_param): likewise
* typecheck/rust-tyty-subst.h: likewise
* typecheck/rust-tyty-variance-analysis.cc (GenericTyVisitorCtx::process_type): likewise
gcc/testsuite/ChangeLog:
* rust/compile/issue-3625.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
We need to setup the main_identifier_node for MAIN_DECL_P checks in the
middle-end. But it is valid to have a main function/method on impl blocks.
So we need to flag if this is a "root" item or not, which is one that is
jsut an HIR::Function on part of the Crate::items as oppposed to a
HIR::Function which is part of an HIR::ImplBlock as part of the HIR::Crate.
Some small cleanups have been added here too.
Fixes Rust-GCC#3648
gcc/rust/ChangeLog:
* backend/rust-compile-base.cc: new flag is_root_item
* backend/rust-compile-base.h: update prototype
* backend/rust-compile-implitem.cc (CompileTraitItem::visit): update call
* backend/rust-compile-implitem.h: remove old debug internal error
* backend/rust-compile-item.cc (CompileItem::visit): update call
* backend/rust-compile-item.h: remove old debug
* backend/rust-compile-resolve-path.cc (HIRCompileBase::query_compile): update calls
* backend/rust-compile.cc: likewise
* typecheck/rust-hir-trait-resolve.cc (TraitResolver::resolve_path_to_trait):
remove assertion and error
gcc/testsuite/ChangeLog:
* rust/compile/issue-3648.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
We dont need to assert here the lifetime code already supports this case.
Fixes Rust-GCC#3657
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-base.cc: remove assertion
gcc/testsuite/ChangeLog:
* rust/compile/issue-3657.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
Const decls are just delcarations wrapping the value into the DECL_INITIAL
and the shift checks we have assume no decls are involved and its just flat
values. This patch simply unwraps the constant values if they exist.
Fixes Rust-GCC#3665
gcc/rust/ChangeLog:
* rust-gcc.cc (arithmetic_or_logical_expression): unwrap const decls
gcc/testsuite/ChangeLog:
* rust/compile/issue-3665.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
gcc/rust/ChangeLog:
* backend/rust-compile-resolve-path.cc: Evaluate the enum's discriminant in a const context
gcc/testsuite/ChangeLog:
* rust/compile/enum_discriminant1.rs: New test.
Signed-off-by: Ryutaro Okada <1015ryu88@gmail.com>
When we resolve paths we resolve to Types first we walk each segment to
the last module which has no type but then in the event that the child
of a module is not found we have a null root_tyty which needs to be caught
and turned into an ErrorType node.
Fixes Rust-GCC#3613
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-type.cc (TypeCheckType::resolve_root_path):
catch nullptr root_tyty
gcc/testsuite/ChangeLog:
* rust/compile/issue-3613.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
Fixes Rust-GCC#3606
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-base.cc (TypeCheckBase::parse_repr_options):
check for null and empty and add missing delete call
gcc/testsuite/ChangeLog:
* rust/compile/issue-3606.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
num regions is based on the used arguments of regions which can be
less than the substutions requirements. So lets check for that and allow
anon regions to be created for them.
Fixes Rust-GCC#3605
gcc/rust/ChangeLog:
* typecheck/rust-tyty-subst.h: check for min range
gcc/testsuite/ChangeLog:
* rust/compile/issue-3605.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
Since 898d55ad7e was fixed to remove the VIEW_CONVERT_EXPR from
array expressions we can now turn on the array element access
const expr.
Fixes Rust-GCC#3563
gcc/rust/ChangeLog:
* backend/rust-constexpr.cc (eval_store_expression): turn this back on
gcc/testsuite/ChangeLog:
* rust/compile/issue-3563.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
gcc/testsuite/ChangeLog:
* rust/compile/macros/mbe/macro43.rs: Adjust test to pass with
name resolution 2.0.
* rust/compile/nr2/exclude: Remove macros/mbe/macro43.rs.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
Array expressions are still getting turned into VIEW_CONVERT_EXPR's becuase
TYPE_MAIN_VARIANT is not set so then we might as well reuse the type-hasher
to sort this out.
Fixes Rust-GCC#3588
gcc/rust/ChangeLog:
* backend/rust-compile-context.h: only push named types
* backend/rust-compile-type.cc (TyTyResolveCompile::visit): run the type hasher
gcc/testsuite/ChangeLog:
* rust/compile/issue-3588.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
Lowercase self suffix with path was not resolved properly, this should
point to the module right before.
gcc/rust/ChangeLog:
* resolve/rust-forever-stack.hxx: Add a new specialized function
to retrieve the last "real" segment depending on the namespace.
* resolve/rust-forever-stack.h: Add new function prototype.
* resolve/rust-early-name-resolver-2.0.cc (Early::finalize_rebind_import):
Set declared name according to the selected segment, if there is a self
suffix in the use declaration then select the previous segment.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
This has been a pet peeve of mine for a while because the gimple never
emitted the struct () name properly it was always empty which for record
types they always require a real locus or they dont get a proper name.
gcc/rust/ChangeLog:
* backend/rust-compile-base.cc (HIRCompileBase::unit_expression): pass ctx
* backend/rust-compile-base.h: cant be static
* backend/rust-compile-intrinsic.cc (try_handler_inner): pass ctx
* backend/rust-compile-type.cc
(TyTyResolveCompile::get_unit_type): update to grab the first locus
(TyTyResolveCompile::visit): pass ctx
* backend/rust-compile-type.h: likewise
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
We need to ensure we are adding methods to the possible candidates.
Fixes Rust-GCC#3554
gcc/rust/ChangeLog:
* typecheck/rust-hir-dot-operator.cc:
gcc/testsuite/ChangeLog:
* rust/compile/issue-3554-1.rs: New test.
* rust/compile/issue-3554-2.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
Fixes Rust-GCC#3568
gcc/rust/ChangeLog:
* resolve/rust-ast-resolve-path.cc (ResolvePath::resolve_path): check for super mid path
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude: nr2 puts out a different error multiple times
* rust/compile/issue-3568.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
We need to reuse the existing compile_constant_item helper which handles
the case if this is a simple expression, fn-call or a block expression.
The patch extracts out this helper as a static method so this can be used
in more places.
Fixes Rust-GCC#3566
gcc/rust/ChangeLog:
* backend/rust-compile-base.cc (HIRCompileBase::address_expression): new helper constexpr
* backend/rust-compile-base.h: prototype
* backend/rust-compile-type.cc (TyTyResolveCompile::visit): call constexpr helper
gcc/testsuite/ChangeLog:
* rust/compile/issue-3566-1.rs: New test.
* rust/compile/issue-3566-2.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
We need to recursively check the super traits of the predicate the Self
type is trying to implement. Otherwise its cannot implement it.
Fixes Rust-GCC#3553
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-item.cc (TypeCheckItem::resolve_impl_block_substitutions):
Track the polarity
* typecheck/rust-tyty-bounds.cc (TypeBoundPredicate::validate_type_implements_this):
new validator
* typecheck/rust-tyty.h: new prototypes
gcc/testsuite/ChangeLog:
* rust/compile/issue-3553.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
We need to check for error_mark_node when doing adjustments from coercion
sites otherwise we hit assetions as part of the coercion. That fixes the
ICE but the reason for the error_mark_node is because the array element
value.
Fixes Rust-GCC#3567
gcc/rust/ChangeLog:
* backend/rust-compile-expr.cc (CompileExpr::array_value_expr): add value chk for array expr
gcc/testsuite/ChangeLog:
* rust/compile/issue-3567.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
Import from core library was wrong, it misses several crate directives
since we're no longer dealing with multiple files.
gcc/testsuite/ChangeLog:
* rust/compile/issue-2905-2.rs: Import from core library into a single
file misses the crate directives.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
The trick here is that when Bar::test is resolved it resolves to the
trait method:
fn <Bar<i32>, T> (placeholder) -> placeholder
Which is fine so we need to setup the associated types for Bar<i32> which
means looking up the associated impl block then setting up the projection
of A = T so it becomes:
fn <Bar<i32>, T> (placeholder: projection<T>:T)
-> placeholder: projection<T>:T
But previously it was auto injecting inference variables so it became:
fn <Bar<i32>, T> (placeholder: projection<T>:?T)
-> placeholder: projection<T>:?T
The issue is that the binding of the generics was still T so this caused
inference variables to be injected again but unlinked. A possible tweak
would be that we are substituting again with new infer vars to actually
just unify them enplace so they are all part of the chain. This still
might be needed but lets hold off for now.
So basically when we are Path probing we dont allow GAT's to generate new
inference vars because they wont be bound to this current segment which
just causes confusion.
Fixes Rust-GCC#3242
gcc/rust/ChangeLog:
* typecheck/rust-hir-trait-reference.h: add default infer arg
* typecheck/rust-hir-trait-resolve.cc: dont add new infer vars
* typecheck/rust-hir-type-check-path.cc (TypeCheckExpr::resolve_segments): dont infer
gcc/testsuite/ChangeLog:
* rust/compile/issue-3242.rs: no longer skip the test
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
gcc/rust/ChangeLog:
* checks/errors/rust-ast-validation.cc
(ASTValidation::visit): Allow constant items lacking expressions
if and only if they're associated with a trait definition, not a
trait implementation.
gcc/testsuite/ChangeLog:
* rust/compile/issue-3541-1.rs: New test.
* rust/compile/issue-3541-2.rs: Likewise.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
gcc/rust/ChangeLog:
* checks/errors/borrowck/ffi-polonius/Cargo.lock: Regenerate.
* checks/errors/borrowck/ffi-polonius/Cargo.toml: Update to use source patching instead of
vendoring, lower edition to 2018.
* checks/errors/borrowck/ffi-polonius/vendor/log/Cargo.toml: Change edition to 2018.
* checks/errors/borrowck/ffi-polonius/vendor/log/src/lib.rs: Remove uses of unstable
feature.
* checks/errors/borrowck/ffi-polonius/.cargo/config.toml: Removed.
libgrust/ChangeLog:
* libformat_parser/Makefile.am: Avoid using --config as it is unsupported by cargo 1.49.
* libformat_parser/Makefile.in: Regenerate.
* libformat_parser/generic_format_parser/src/lib.rs: Use extension trait for missing
features.
* libformat_parser/src/lib.rs: Likewise.
* libformat_parser/.cargo/config: Moved to...
* libformat_parser/.cargo/config.toml: ...here.
gcc/testsuite/ChangeLog:
* rust/compile/const_generics_3.rs: Modify test to run with name
resolution 2.0 only and to handle the absence of a bogus
resolution error.
* rust/compile/nr2/exclude: Remove const_generics_3.rs.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
Those tests were malformed and failed with the new name resolution
because of it.
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude: Remove test from exclusion list.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Those tests are coming from libcore and module inlining was wrong, in
libcore there was a use declaration to import those modules which was
missing here.
gcc/testsuite/ChangeLog:
* rust/compile/issue-2330.rs: Use complete path from crate root.
* rust/compile/issue-1901.rs: Likewise.
* rust/compile/issue-1981.rs: Likewise.
* rust/compile/iterators1.rs: Likewise.
* rust/compile/sizeof-stray-infer-var-bug.rs: Likewise.
* rust/compile/for-loop1.rs: Likewise.
* rust/compile/for-loop2.rs: Likewise.
* rust/compile/torture/builtin_abort.rs: Likewise.
* rust/compile/torture/uninit-intrinsic-1.rs: Likewise.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Function could not be found and triggered an error message.
gcc/testsuite/ChangeLog:
* rust/compile/feature_rust_attri0.rs: Add extern
function declaration and change name to printf.
* rust/compile/nr2/exclude: Remove now passing test from exclusion
list.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Disable network access via 'unshare' in two CI workflows to catch issues
like PR119333 where importing polonius meant bootstrap tried to pull crates
from the internet.
ChangeLog:
PR rust/119333
* .github/workflows/bootstrap.yml: Disable network via 'unshare'.
* .github/workflows/ccpp.yml: Ditto.
In order to handle generic super traits on any trait bound we need to ensure
we track the TypeBoundPredicate as part of the TraitReference instead of just
the raw TraitReferences because these will have any applied generics enplace.
Then for any TypeBoundPredicate it takes a copy of the super traits because
this is the usage of a TraitBound and we can apply generics which then need
to be recursively applied up the chain of super predicates.
The main tweak is around TypeBoundPredicate::lookup_associated_item because
we need to associate the predicate with the item we are looking up so the caller
can respect the generics correctly as well.
Fixes Rust-GCC#3502
gcc/rust/ChangeLog:
* typecheck/rust-hir-path-probe.cc: update call
* typecheck/rust-hir-trait-reference.cc (TraitReference::lookup_trait_item): track predicate
(TraitReference::is_equal): likewise
(TraitReference::is_object_safe): likewise
(TraitReference::satisfies_bound): likewise
* typecheck/rust-hir-trait-reference.h: likewise
* typecheck/rust-hir-trait-resolve.cc (TraitResolver::resolve_trait): likewise
* typecheck/rust-tyty-bounds.cc (TypeBoundPredicate::TypeBoundPredicate): track super traits
(TypeBoundPredicate::operator=): likewise
(TypeBoundPredicate::apply_generic_arguments): ensure we apply to super predicates
(TypeBoundPredicateItem::operator=): take copy of parent predicate
(TypeBoundPredicateItem::error): pass error instead of nullptr
(TypeBoundPredicateItem::is_error): update to no longer check for nullptr
(TypeBoundPredicateItem::get_parent): updated
(TypeBoundPredicateItem::get_tyty_for_receiver): likewise
(TypeBoundPredicate::get_associated_type_items): likewise
* typecheck/rust-tyty-bounds.h (class TypeBoundPredicateItem): move
* typecheck/rust-tyty-subst.cc: flag to handle placeholder Self on traits
* typecheck/rust-tyty-subst.h (class TypeBoundPredicateItem): likewise
* typecheck/rust-tyty.h (class TypeBoundPredicateItem): refactored
gcc/testsuite/ChangeLog:
* rust/execute/torture/issue-3502.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
This fixes PR #119333 by allowing our borrow-checker interface to be built
offline. This was already done for our components in libgrust/, but had never been
done for the borrow-checker.
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=119333
gcc/rust/ChangeLog:
* checks/errors/borrowck/ffi-polonius/.cargo/config.toml: New file, force vendored deps.
* checks/errors/borrowck/ffi-polonius/vendor/datafrog/.cargo-checksum.json: New file.
* checks/errors/borrowck/ffi-polonius/vendor/datafrog/CODE_OF_CONDUCT.md: New file.
* checks/errors/borrowck/ffi-polonius/vendor/datafrog/Cargo.toml: New file.
* checks/errors/borrowck/ffi-polonius/vendor/datafrog/LICENSE-APACHE: New file.
* checks/errors/borrowck/ffi-polonius/vendor/datafrog/LICENSE-MIT: New file.
* checks/errors/borrowck/ffi-polonius/vendor/datafrog/README.md: New file.
* checks/errors/borrowck/ffi-polonius/vendor/datafrog/RELEASES.md: New file.
* checks/errors/borrowck/ffi-polonius/vendor/datafrog/examples/borrow_check.rs: New file.
* checks/errors/borrowck/ffi-polonius/vendor/datafrog/examples/graspan1.rs: New file.
* checks/errors/borrowck/ffi-polonius/vendor/datafrog/src/join.rs: New file.
* checks/errors/borrowck/ffi-polonius/vendor/datafrog/src/lib.rs: New file.
* checks/errors/borrowck/ffi-polonius/vendor/datafrog/src/map.rs: New file.
* checks/errors/borrowck/ffi-polonius/vendor/datafrog/src/test.rs: New file.
* checks/errors/borrowck/ffi-polonius/vendor/datafrog/src/treefrog.rs: New file.
* checks/errors/borrowck/ffi-polonius/vendor/log/.cargo-checksum.json: New file.
* checks/errors/borrowck/ffi-polonius/vendor/log/CHANGELOG.md: New file.
* checks/errors/borrowck/ffi-polonius/vendor/log/Cargo.toml: New file.
* checks/errors/borrowck/ffi-polonius/vendor/log/LICENSE-APACHE: New file.
* checks/errors/borrowck/ffi-polonius/vendor/log/LICENSE-MIT: New file.
* checks/errors/borrowck/ffi-polonius/vendor/log/README.md: New file.
* checks/errors/borrowck/ffi-polonius/vendor/log/benches/value.rs: New file.
* checks/errors/borrowck/ffi-polonius/vendor/log/src/__private_api.rs: New file.
* checks/errors/borrowck/ffi-polonius/vendor/log/src/kv/error.rs: New file.
* checks/errors/borrowck/ffi-polonius/vendor/log/src/kv/key.rs: New file.
* checks/errors/borrowck/ffi-polonius/vendor/log/src/kv/mod.rs: New file.
* checks/errors/borrowck/ffi-polonius/vendor/log/src/kv/source.rs: New file.
* checks/errors/borrowck/ffi-polonius/vendor/log/src/kv/value.rs: New file.
* checks/errors/borrowck/ffi-polonius/vendor/log/src/lib.rs: New file.
* checks/errors/borrowck/ffi-polonius/vendor/log/src/macros.rs: New file.
* checks/errors/borrowck/ffi-polonius/vendor/log/src/serde.rs: New file.
* checks/errors/borrowck/ffi-polonius/vendor/log/triagebot.toml: New file.
* checks/errors/borrowck/ffi-polonius/vendor/polonius-engine/.cargo-checksum.json: New file.
* checks/errors/borrowck/ffi-polonius/vendor/polonius-engine/Cargo.toml: New file.
* checks/errors/borrowck/ffi-polonius/vendor/polonius-engine/README.md: New file.
* checks/errors/borrowck/ffi-polonius/vendor/polonius-engine/src/facts.rs: New file.
* checks/errors/borrowck/ffi-polonius/vendor/polonius-engine/src/lib.rs: New file.
* checks/errors/borrowck/ffi-polonius/vendor/polonius-engine/src/output/datafrog_opt.rs:
New file.
* checks/errors/borrowck/ffi-polonius/vendor/polonius-engine/src/output/initialization.rs:
New file.
* checks/errors/borrowck/ffi-polonius/vendor/polonius-engine/src/output/liveness.rs:
New file.
* checks/errors/borrowck/ffi-polonius/vendor/polonius-engine/src/output/location_insensitive.rs:
New file.
* checks/errors/borrowck/ffi-polonius/vendor/polonius-engine/src/output/mod.rs: New file.
* checks/errors/borrowck/ffi-polonius/vendor/polonius-engine/src/output/naive.rs: New file.
* checks/errors/borrowck/ffi-polonius/vendor/rustc-hash/.cargo-checksum.json: New file.
* checks/errors/borrowck/ffi-polonius/vendor/rustc-hash/CODE_OF_CONDUCT.md: New file.
* checks/errors/borrowck/ffi-polonius/vendor/rustc-hash/Cargo.toml: New file.
* checks/errors/borrowck/ffi-polonius/vendor/rustc-hash/LICENSE-APACHE: New file.
* checks/errors/borrowck/ffi-polonius/vendor/rustc-hash/LICENSE-MIT: New file.
* checks/errors/borrowck/ffi-polonius/vendor/rustc-hash/README.md: New file.
* checks/errors/borrowck/ffi-polonius/vendor/rustc-hash/src/lib.rs: New file.
gcc/rust/ChangeLog:
* resolve/rust-late-name-resolver-2.0.cc
(Late::visit): Make sure to return early after a resolution
error, improve the resolution error message, fix a typo, handle
ambiguous resolutions, and remove an old comment.
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude: Remove entries.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-implitem.cc (TypeCheckTopLevelExternItem::visit):
emit an error for type or const parameters on foreign items
gcc/testsuite/ChangeLog:
* rust/compile/extern_generics.rs: New test.
Signed-off-by: Ryutaro Okada <1015ryu88@gmail.com>
gcc/rust/ChangeLog:
* resolve/rust-forever-stack.h (ForeverStack): Add a dedicated prelude node for
the Language prelude
* resolve/rust-forever-stack.hxx (ForeverStack): Add support code for the
prelude node
* resolve/rust-late-name-resolver-2.0.cc (Late::visit): Move
language prelude builtins to the prelude context
* resolve/rust-name-resolution-context.cc
(NameResolutionContext::scoped): Add code for handling
the prelude corner case
* resolve/rust-rib.h (Rib::Kind): Add a special Prelude rib type
gcc/testsuite/ChangeLog:
* rust/compile/issue-3315-1.rs: Add test for module with same name
as builtin
* rust/compile/issue-3315-2.rs: Test with utilization of i32
type
* rust/compile/nr2/exclude: issue-3315-2.rs Does not work with
NR2.0
Signed-off-by: Liam Naddell <liamnprg@gmail.com>
Those tests are now passing.
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude: Remove two mangling tests from exclusion
file.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
The algorithm was comparing using the wrong id, this lead to some
mangling errors as an erroneous parent was selected.
gcc/rust/ChangeLog:
* resolve/rust-forever-stack.hxx: Fix the id comparison.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
gcc/rust/ChangeLog:
* resolve/rust-forever-stack.hxx: Insert a new segment with the crate's
name as canonical's path prefix.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
gcc/rust/ChangeLog:
* util/rust-hir-map.cc (Mappings::lookup_crate_num): Add function to
retrieve crate number from it's node id.
(Mappings::node_is_crate): change function with call to
lookup_crate_num to avoid looping through all crates.
(Mappings::insert_ast_crate): Populate node id to crate number map.
* util/rust-hir-map.h: Change function prototype.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Import mapping was relying on resolve_path which in turn relies on
the cursor function. This means the mapping resolver should be called
from the correct scope instead of being called from the crate scope.
gcc/rust/ChangeLog:
* resolve/rust-early-name-resolver-2.0.cc (Early::Early): Move the
top level visitor from the function scope to attributes.
(Early::go): Remove top level visitor creation and adapt calling code.
Remove call to mapping resolution and import finalization.
(Early::finalize_simple_import): Move the finalization from it's
visitor.
(Early::finalize_glob_import): Likewise.
(Early::finalize_rebind_import): Likewise.
(Early::visit): Add mapping resolution and finalization in
UseDeclaration visitor function.
* resolve/rust-finalize-imports-2.0.cc (finalize_simple_import): Move
function.
(finalize_glob_import): Likewise.
(finalize_rebind_import): Likewise.
(FinalizeImports::visit): Remove call to finalizers.
* resolve/rust-early-name-resolver-2.0.h (class Early): Add top level
attribute.
* resolve/rust-finalize-imports-2.0.h: Add function prototypes.
* resolve/rust-toplevel-name-resolver-2.0.h: Change getter return type
to reference.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
We need to be careful when doing bounds check as to not create a recusive
trait resolution. This patch checks for that case and fixes a bad type
is equal check on ADT Types which was caught with a regression here.
Fixes Rust-GCC#3126
gcc/rust/ChangeLog:
* typecheck/rust-hir-trait-resolve.cc (TraitResolver::ResolveHirItem): new helper
* typecheck/rust-hir-trait-resolve.h: add helper prototype
* typecheck/rust-type-util.cc (query_type): add debug
* typecheck/rust-tyty-bounds.cc (TypeBoundsProbe::scan): check for recursion
* typecheck/rust-tyty.cc (VariantDef::is_equal): fix is equal check
gcc/testsuite/ChangeLog:
* rust/execute/torture/issue-3126.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
Just a small refactor to remove a visitor which is not needed.
gcc/rust/ChangeLog:
* backend/rust-compile-resolve-path.cc (ResolvePathRef::Compile): remove visitor
(ResolvePathRef::ResolvePathRef): likewise
(ResolvePathRef::visit): likewise
* backend/rust-compile-resolve-path.h (class ResolvePathRef): likewise
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
Highlight the fact that a value inside an enum definition refers to
a struct outside of the enum and not to the enum variant's name
directly.
gcc/testsuite/ChangeLog:
* rust/compile/enum_variant_name.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
New enum variant status now appears in the string representation of
the resolver's definition.
gcc/rust/ChangeLog:
* resolve/rust-rib.cc (Rib::Definition::to_string): Add enum variant
status.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Enum variants shouldn't be accessed directly even from within an enum.
This commit keeps the provenance for enum variants definition so we
can skip them when resolving a value within an enum definition.
gcc/rust/ChangeLog:
* resolve/rust-forever-stack.h: Add new function to insert enum
variants and add argument to resolver's get function to explicitely
skip enum variants.
* resolve/rust-forever-stack.hxx: Update function
definitions.
* resolve/rust-name-resolution-context.cc (NameResolutionContext::insert_variant):
Add function to insert enum variants.
* resolve/rust-name-resolution-context.h: Add function's prototype.
* resolve/rust-rib.cc (Rib::Definition::Definition): Add new boolean to
hint at enum variant provenance.
(Rib::Definition::is_variant): New getter for variant status.
(Rib::Definition::Shadowable): Update constructor to opt out of enum
variants.
(Rib::Definition::Globbed): Likewise.
(Rib::Definition::NonShadowable): Change constructor to forward enum
variant provenance status.
* resolve/rust-rib.h: Update function prototypes.
* resolve/rust-toplevel-name-resolver-2.0.cc (TopLevel::insert_enum_variant_or_error_out):
Add function to insert enum variants in the name resolver.
(TopLevel::visit): Update several enum variant's visitor function
with the new enum variant name resolving code.
* resolve/rust-toplevel-name-resolver-2.0.h: Update function
prototypes.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Rib kind had no string representation, and thus were not used in the
debug string representation.
gcc/rust/ChangeLog:
* resolve/rust-forever-stack.hxx: Output rib kind.
* resolve/rust-rib.h: Add function to get string representation from
a rib kind.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
gcc/rust/ChangeLog:
* resolve/rust-forever-stack.h
(ForeverStack::ForeverStack): Set the node id of the root node
to that of the current crate.
* resolve/rust-forever-stack.hxx
(ForeverStack::find_starting_point): Use the node id of the root
node during resolution of crate segments.
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude: Remove entries.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
gcc/rust/ChangeLog:
* expand/rust-macro-expand.cc: Use new SubstituteCtx API.
* expand/rust-macro-expand.h: Likewise.
* expand/rust-macro-substitute-ctx.cc: Implement proper expansion of $crate.
* expand/rust-macro-substitute-ctx.h: Adapt APIs to take macro definition when
substituting.
* util/rust-hir-map.cc (Mappings::insert_macro_def): Store crate information when
inserting macro definition in mappings.
(Mappings::lookup_macro_def_crate): New.
* util/rust-hir-map.h: Adapt mappings to store crate in which macros were defined.
gcc/testsuite/ChangeLog:
* rust/execute/crate-metavar1.rs: New test.
* rust/compile/crate-metavar1.rs: New test.
gcc/rust/ChangeLog:
* resolve/rust-late-name-resolver-2.0.cc
(Late::visit): Call DefaultResolver::visit earlier, in order to
ensure it is called even if Late::visit returns early.
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude: Remove entries.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
gcc/rust/ChangeLog:
* util/rust-edition.cc: New file.
* util/rust-edition.h: New file.
* Make-lang.in: Add rust-edition.o to the object list.
* ast/rust-pattern.cc: Remove inclusion of
rust-session-manager.h.
* expand/rust-macro-expand.cc: Likewise.
* expand/rust-macro-builtins-helpers.h: Likewise.
* expand/rust-macro-builtins-include.cc: Include
rust-session-manager.h.
* expand/rust-macro-builtins-utility.cc: Likewise.
* lex/rust-lex.cc: Include rust-edition.h instead of
rust-session-manager.h.
(Lexer::classify_keyword): Use get_rust_edition instead of
Session and CompileOptions.
* parse/rust-parse-impl.h: Include rust-edition.h instead of
rust-session-manager.h.
(Parser::parse_async_item): Use get_rust_edition instead of
Session and CompileOptions.
* checks/errors/rust-feature.h: Include rust-edition.h instead
of rust-session-manager.h.
(class Feature): Use Rust::Edition instead of
Rust::CompileOptions::Edition.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
Adapt functions for lowering nodes that should never reach the lowering phase to cause an
unreachable, and mark them as final so as it not possible to override them in other visitors.
gcc/rust/ChangeLog:
* hir/rust-ast-lower-base.cc: Adapt functions for ErrorPropagationExpr and MacroInvocation.
* hir/rust-ast-lower-base.h: Mark them as final.
* hir/rust-ast-lower-expr.cc: Remove previous definition for those overrides.
* hir/rust-ast-lower-expr.h: Likewise.
gcc/rust/ChangeLog:
* Make-lang.in: Compile it.
* ast/rust-desugar-question-mark.cc: New file.
* ast/rust-desugar-question-mark.h: New file.
gcc/testsuite/ChangeLog:
* rust/compile/try-expr1.rs: New test.
gcc/rust/ChangeLog:
* expand/rust-expand-visitor.cc (ExpandVisitor::visit): Correctly visit the generic args
of a generic type path segment.
gcc/testsuite/ChangeLog:
* rust/compile/issue-2015.rs: New test.
Some empty overrides were incorrectly being set-up instead of using the correct behavior
from DefaultASTVisitor.
gcc/rust/ChangeLog:
* resolve/rust-early-name-resolver.cc: Remove definitions.
* resolve/rust-early-name-resolver.h: Remove declarations.
gcc/rust/ChangeLog:
* resolve/rust-early-name-resolver-2.0.cc:
Include rust-attribute-values.h.
(Early::visit): If a module has a macro_use attribute, avoid
pushing a new textual macro scope.
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude: Remove entries.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
gcc/rust/ChangeLog:
* hir/rust-hir-dump.cc: Check unique_ptr members are present before
visiting them.
* hir/tree/rust-hir-path.h: Add `has_{type, trait}` methods to
QualifiedPathInType.
gcc/rust/ChangeLog:
* Make-lang.in: Compile it.
* expand/rust-derive.cc (DeriveVisitor::derive): Call it.
* expand/rust-derive-hash.cc: New file.
* expand/rust-derive-hash.h: New file.
gcc/testsuite/ChangeLog:
* rust/compile/derive-hash1.rs: New test.
* rust/compile/nr2/exclude: Add testcase to exclusion list.
gcc/rust/ChangeLog:
* expand/rust-expand-visitor.cc
(ExpandVisitor::visit): Override DefaultASTVisitor in order to
expand a module's items, rather than directly visit them.
* expand/rust-expand-visitor.h
(ExpandVisitor::visit): Add override.
gcc/testsuite/ChangeLog:
* rust/compile/macros/mbe/macro-expand-module.rs: New test.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
gcc/rust/ChangeLog:
* expand/rust-derive.cc (DeriveVisitor::derive): Return a vector of items.
* expand/rust-derive.h: Change return type.
* expand/rust-expand-visitor.cc: Insert all generated items into the AST.
We are still missing some deriving for enums, as part of our codegen and nameres for rebinding struct
field patterns is missing.
gcc/rust/ChangeLog:
* expand/rust-derive-partial-eq.cc: New file.
* expand/rust-derive-partial-eq.h: New file.
* expand/rust-derive.cc (DeriveVisitor::derive): Call them.
* Make-lang.in: Compile them.
gcc/testsuite/ChangeLog:
* rust/compile/derive-eq-invalid.rs: Mark PartialEq def as a lang item.
* rust/compile/derive-partialeq1.rs: New test.
* rust/execute/torture/derive-partialeq1.rs: New test.
* rust/compile/nr2/exclude: Exclude all of them.
gcc/rust/ChangeLog:
* ast/rust-ast-builder.cc (Builder::block): Change return type.
(Builder::loop): Use new APIs.
* ast/rust-ast-builder.h: Change return type of block functions.
gcc/rust/ChangeLog:
* resolve/rust-toplevel-name-resolver-2.0.cc
(TopLevel::visit): When visiting an external crate declaration,
handle failed crate name lookups. This can happen when
Session::load_extern_crate fails to load a crate during the
CfgStrip phase.
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude: Remove entries.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
gcc/rust/ChangeLog:
* resolve/rust-forever-stack.hxx
(ForeverStack::resolve_segments): Add comments explaining
the behaviour of a while loop.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
Check if an if-expr returns void type or a coercible type like an early return.
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit):
Add check on if-expr.
gcc/testsuite/ChangeLog:
* rust/compile/implicit_returns_err3.rs: Change test to be valid.
* rust/compile/torture/if.rs: Likewise.
* rust/compile/if-without-else.rs: New test.
Signed-off-by: Benjamin Thos <benjamin.thos@epita.fr>
gcc/rust/ChangeLog:
* resolve/rust-forever-stack.hxx
(ForeverStack::find_starting_point): Be more careful about
applying ForeverStack::find_closest_module.
(ForeverStack::resolve_segments): Allow traversal into parent
nodes when not in a module node or root node, which
ForeverStack::find_starting_point previously made moot through
use of ForeverStack::find_closest_module. Also, when a child
node lookup fails when resolving in the type namespace, attempt
a rib lookup as a fallback.
* resolve/rust-late-name-resolver-2.0.cc
(Late::visit): Avoid throwing a resolution error for type paths
when the typechecker may be able to finish the resolution. Also,
throw an error when a resolution is ambiguous.
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude: Remove entries.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
We have the type information for the resolved call lets tell the user about
it in the diagnostic and apply the correct error code.
Fixes Rust-GCC#2035
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit): improve error diag
gcc/testsuite/ChangeLog:
* rust/compile/generics4.rs: cleanup
* rust/compile/generics6.rs: likewise
* rust/compile/type-bindings1.rs: likewise
* rust/compile/unconstrained_type_param.rs: likewise
* rust/compile/issue-2035.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
With simple patterns we dont introduce any more inference varaibles as
they are already declared in a specific way. This would only lead to
more unconstrained inference varaibles than is required.
Fixes Rust-GCC#3022
gcc/rust/ChangeLog:
* hir/rust-ast-lower-base.cc (ASTLoweringBase::lower_self): add location mappings
* typecheck/rust-hir-type-check-path.cc (TypeCheckExpr::resolve_root_path): check for self
gcc/testsuite/ChangeLog:
* rust/compile/issue-3022.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
Rust allows you to use generics within type bounds when they are declared
later on. This changes the name resolution to walk the genric params
in two passes to ensure the type parameters are setup before drilling down
into the type parameters
This issue has exposed another type checking issue which needs fixed in
a subseqent patch.
Addresses Rust-GCC#3022
gcc/rust/ChangeLog:
* resolve/rust-ast-resolve-item.cc (ResolveTraitItems::visit): use new api
(ResolveItem::visit): likewise
(ResolveExternItem::visit): likewise
* resolve/rust-ast-resolve-stmt.h: likewise
* resolve/rust-ast-resolve-type.h (class ResolveGenericParam): remove
(class ResolveGenericParams): added new api
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
Generics can be constrained within other generic types so this check needs
to be recursive.
Fixes Rust-GCC#3031
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-base.cc (walk_types_to_constrain): recursive walker
* typecheck/rust-tyty.cc (BaseType::get_subst_argument_mappings): new helper
* typecheck/rust-tyty.h: prototype
gcc/testsuite/ChangeLog:
* rust/compile/issue-3031.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
It seems bounds in qualified paths are not allowed to specify associated
type bindings because its going to be associated with the impl block
anyway.
Fixes Rust-GCC#2369
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-base.h: add flag
* typecheck/rust-hir-type-check-type.cc (TypeCheckType::visit): likewise
* typecheck/rust-tyty-bounds.cc: new diagnostic
gcc/testsuite/ChangeLog:
* rust/compile/issue-2369.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
We resolve path segments and inserted their resolution into the name
resolution space which was an old hack to use this as information in
code-gen/check-passes in order to help things move forward but this is
not nessecary
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-type.cc (TypeCheckType::visit): remove name resolution info
(TypeCheckType::resolve_root_path): likewise
* typecheck/rust-hir-type-check-type.h: likewise
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
This is pretty nasty piece of rust in my opinion the return type of this
intrinsic results into a lang item associated type:
<T as DiscriminantKind>::Discriminant
This is a special case which needs to support mapping onto the repr type
of the associated ADT that is passed in, but defaults to iszie otherwise.
This patch assumes we only come accross this case in a HIR::CALL_EXPR, so
and makes assumutions that its always of this function signiture. I will
do some checking in libcore to verify that assumption. More work is needed
to parse the repr type on enums but the code is there to support this when
its in to change the types etc.
Addresses Rust-GCC#3348
gcc/rust/ChangeLog:
* backend/rust-compile-intrinsic.cc (discriminant_value_handler): new handler
* typecheck/rust-hir-trait-resolve.cc (TraitItemReference::resolve_item): track the defid
* typecheck/rust-hir-type-check-base.cc (TypeCheckBase::parse_repr_options): default isize
* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit): special case CallExpr
* typecheck/rust-hir-type-check-item.cc (TypeCheckItem::visit): parse repr options enum
* typecheck/rust-hir-type-check-type.cc (TypeCheckType::visit): remove bad diagnostic
* typecheck/rust-tyty.cc (PlaceholderType::PlaceholderType): track defid
(PlaceholderType::clone): likewise
(PlaceholderType::get_def_id): likeiwse
* typecheck/rust-tyty.h: placeholder track defid
* util/rust-lang-item.cc: add new lang items
* util/rust-lang-item.h: likewise
gcc/testsuite/ChangeLog:
* rust/execute/torture/enum_intrinsics1.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
This was a bad diagnostic added when I was working on slices and iterators
also the name of the function is also bad. This is all about setting up
associated types based on the current context of the bounds assocated with
the associated trait bounds on this function.
The tell tale is that this didnt have an associated rust error code so
this is most definetly not the correct error diagnostic.
Fixes Rust-GCC#3403
gcc/rust/ChangeLog:
* typecheck/rust-tyty-subst.cc (SubstitutionRef::monomorphize): remove diagnostic
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude: nr2 cant handle this
* rust/compile/issue-3403.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
gcc/rust/ChangeLog:
* ast/rust-desugar-for-loops.cc: New file.
* ast/rust-desugar-for-loops.h: New file.
* hir/rust-ast-lower-expr.cc (ASTLoweringExpr::visit): Make lowering of for-loops an
unreachable.
* Make-lang.in: Compile it.
gcc/testsuite/ChangeLog:
* rust/compile/for-loop1.rs: New test.
* rust/compile/for-loop2.rs: New test.
* rust/execute/torture/for-loop1.rs: New test.
* rust/execute/torture/for-loop2.rs: New test.
* rust/compile/nr2/exclude: Exclude for-loop1.rs
gcc/rust/ChangeLog:
* expand/rust-macro-builtins-asm.cc (strip_double_quotes): Special case empty
strings ("\"\"").
(parse_reg_operand): Remove use of the `struct` keyword.
(parse_reg_operand_in): Likewise.
(parse_reg_operand_out): Likewise.
* expand/rust-macro-builtins.cc: Add llvm_asm! built-in macro as an alias to asm!.
We already lost some time on this unusual pattern, a comment will
hopefully prevent this from happening again.
gcc/rust/ChangeLog:
* resolve/rust-toplevel-name-resolver-2.0.cc (TopLevel::visit): Add
warning about current code.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
This was fixed as part of: c63ecb2f032
Fixes Rust-GCC#3402
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude: nr2 cant handle this
* rust/compile/issue-3402-1.rs: New test.
* rust/compile/issue-3402-2.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
When we have paths such as Try::from_error the Try references the Trait
and then from_error references the from_error trait item. So this resolves
directly to a trait implementation which has the type:
fn <Self> (v: placeholder) -> Self
Remember that a path such as: Try::from_error gets handled by doing a
clever substitution: <T? as Try>::from_error
The main piece here is that we resolve this function type and for
monomoprhization we know this is a trait call but we know that all trait's
have an implicit Self type param which in this case is Result<i32, i32>
so when it comes to knowing which impl block this is we got rid of the old
bad insert/lookup receiver hack and use the specified type to know which
impl block we are talking about to generate the function.
The hard part here is inside rust-compil-item.cc, where we have the
'concete' type which is the trait item fntype of:
fn <Result<i32, i32>> (v : i32) -> Result<i32,i32>
This does not really match the signiture of the impl item for Result
which is:
fn <T, E> (v: i32) -> Result<T, E>
So what we need to do is actually infer this by inputing inference
variables on the impl fntype then unify'ing the trait object to this to
compute the types of this to monomorphize this.
Fixes Rust-GCC#3381
gcc/rust/ChangeLog:
* backend/rust-compile-expr.cc (CompileExpr::visit): remove receiver interface
* backend/rust-compile-item.cc (CompileItem::visit): monomorphize trait to impl item
* backend/rust-compile-resolve-path.cc (HIRCompileBase::query_compile): use trait item Self
* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit): remove receiver interface
(TypeCheckExpr::resolve_fn_trait_call): likewise
* typecheck/rust-hir-type-check-path.cc (TypeCheckExpr::visit): likewise
(TypeCheckExpr::resolve_segments): likewise
* typecheck/rust-hir-type-check-type.cc (TypeCheckType::visit): likewise
* typecheck/rust-hir-type-check.h: likewise
* typecheck/rust-typecheck-context.cc (TypeCheckContext::insert_receiver): remove
(TypeCheckContext::lookup_receiver): remove
gcc/testsuite/ChangeLog:
* rust/execute/torture/issue-3381.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
When passing generics around we try to adjust them because there are cases
where the names are adjusted from other generics this can fail for traits
because of the implicit Self and we just need to continue on without
adjustment.
Fxies Rust-GCC#3382
gcc/rust/ChangeLog:
* typecheck/rust-substitution-mapper.cc (SubstMapperInternal::visit):
continue on for trait item mode.
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude: nr2 cant handle this.
* rust/compile/issue-3382.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
This guards against a crash but i think this should actually be treated
as if its a generic type like below. But for now this addresses a crash which can occur.
gcc/rust/ChangeLog:
* checks/errors/privacy/rust-privacy-reporter.cc (PrivacyReporter::check_base_type_privacy):
Add guard for placeholder
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
It is valid for the query to fail here so its valid to not assert here.
gcc/rust/ChangeLog:
* typecheck/rust-hir-path-probe.cc (PathProbeType::visit): remove assertion
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
We needed to check for the optional has a value here or not it leads to an
ICE.
gcc/rust/ChangeLog:
* typecheck/rust-tyty.cc (ClosureType::setup_fn_once_output): add checks for lang items
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
gcc/rust/ChangeLog:
* resolve/rust-early-name-resolver-2.0.cc
(Early::resolve_glob_import): Use
NameResolutionContext::resolve_path instead of
ForeverStack::resolve_path.
(Early::visit): Likewise.
(Early::visit_attributes): Likewise.
* resolve/rust-early-name-resolver-2.0.h
(Early::resolve_path_in_all_ns): Likewise.
* resolve/rust-late-name-resolver-2.0.cc
(Late::visit): Likewise, insert segment resolutions not
handled by NameResolutionContext::resolve_path, and avoid throwing
an error when path resolution could be finished by the typechecker.
* resolve/rust-name-resolution-context.h
(NameResolutionContext::resolve_path): Add.
* typecheck/rust-hir-type-check-path.cc
(TypeCheckExpr::resolve_root_path): Use segment node ids instead
of the path node id to look up segment resolutions when using
the 2.0 resolver, as is done with the 1.0 resolver.
* typecheck/rust-hir-type-check-type.cc
(TypeCheckType::resolve_root_path): Likewise.
* resolve/rust-forever-stack.h
(ForeverStack::resolve_path): Add callback parameter for
inserting segment resolutions.
(ForeverStack::find_starting_point): Likewise.
(ForeverStack::resolve_segments): Likewise.
* resolve/rust-forever-stack.hxx
(ForeverStack::find_starting_point): Likewise.
(ForeverStack::resolve_segments): Likewise.
(ForeverStack::resolve_path): Likewise and avoid resolving
inside TraitOrImpl ribs.
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude: Remove entries.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
These lang items are used when deriving Eq and PartialEq, and will be checked when compiling pattern matching.
gcc/rust/ChangeLog:
* util/rust-lang-item.cc: New items.
* util/rust-lang-item.h: Likewise.
gcc/testsuite/ChangeLog:
* rust/compile/structural-eq-peq.rs: New test.
gcc/rust/ChangeLog:
* expand/rust-macro-builtins-utility.cc: Add macro expansion for
option_env with eager expansion
* expand/rust-macro-builtins.cc: Add option_env to builtin list
* expand/rust-macro-builtins.h: Add option_env handler to header
file
* resolve/rust-late-name-resolver-2.0.cc: Prevent NR2.0 from
recursing into lang-item segments
gcc/testsuite/ChangeLog:
* rust/compile/macros/builtin/option_env1.rs: Add success case for option_env
* rust/compile/macros/builtin/option_env2.rs: Add failure case for option_env
* rust/execute/torture/builtin_macro_option_env.rs: Add
execution case for option_env
Collapses all of the OperatorExprs into Expr instead of first having to check for OperatorExpr and
then check for each OperatorExpr::Kind.
gcc/rust/ChangeLog:
* ast/rust-ast.h: Add new Expr::Kinds.
* ast/rust-expr.h: Implement missing get_expr_kind(), Add get_function_expr_ptr()
This will be crucial for more complex gimple debugging to make it easier
to follow the code vs the original rust code.
gcc/rust/ChangeLog:
* backend/rust-compile-expr.cc (CompileExpr::visit): disable overflow checks
* lang.opt: new flag
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
Those tests are now passing.
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude: Remove some tests.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
gcc/rust/ChangeLog:
* backend/rust-compile-resolve-path.cc (ResolvePathRef::resolve): Do
not use query system for unit struct but compile it's constructor
instead.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
We need to query all namespaces and error out at a later stage if the
retrieved item is wrong.
gcc/rust/ChangeLog:
* typecheck/rust-hir-trait-resolve.cc (TraitResolver::resolve_path_to_trait):
Query all namespaces.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Those function should not change anything within the foreverstack, it
can therefore be made const.
gcc/rust/ChangeLog:
* resolve/rust-forever-stack.h: Make debug functions const.
* resolve/rust-forever-stack.hxx: Likewise.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
We're reusing the value, it could therefore not be taken be should be
cloned.
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-enumitem.cc (TypeCheckEnumItem::visit):
Clone expr instead of taking it.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Those test are now passing.
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude: Remove passing tests.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Query mode was a hack to catch up some compile errors early, it was
deemed to be removed at some time. Recent changes to NR1 highlighted
an incompatibility with it hence it's removal.
gcc/rust/ChangeLog:
* backend/rust-compile-item.h: Remove query mode.
* backend/rust-compile-resolve-path.cc (HIRCompileBase::query_compile):
Likewise.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
We missed the name namespace for unit struct in the old resolver.
gcc/rust/ChangeLog:
* resolve/rust-ast-resolve-toplevel.h: Add struct to name namespace.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
It might be necessary to compare both name resolution' internal states
during the transition. This new debug representation could help with
that.
gcc/rust/ChangeLog:
* resolve/rust-name-resolver.h: Add new degug dump for old name
resolver.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
When we lookup here it returns an optional which can lead to a crash
because it needs a guard if it has a value.
gcc/rust/ChangeLog:
* backend/rust-compile-resolve-path.cc (HIRCompileBase::query_compile): add guard
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude: these tests now work it seems
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
Fixes#3129.
gcc/rust/ChangeLog:
* rust-session-manager.cc (Session::handle_crate_name): Remove
crate name inference
(Session::compile_crate): Add crate name inference and error if
inferred name is empty. Remove CompileOptions::get_instance ()
that returned a local copy of the options. Rename
crate_name_changed to crate_name_found to match semantics.
(rust_crate_name_validation_test): Test inferring ".rs" name
* rust-session-manager.h: Modify handle_crate_name definition to
include filename.
Captures were only processed for regular ClosureExprInner.
gcc/rust/ChangeLog:
* resolve/rust-late-name-resolver-2.0.cc (Late::visit): Add
ClosureExprInnerTyped visit implementation.
(add_captures): Add a function to avoid code duplication.
* resolve/rust-late-name-resolver-2.0.h: Add function prototype.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
The compiler was still relying on NR1 for closure captures when using nr2
even though the resolver was not used and thus it's state empty.
gcc/rust/ChangeLog:
* resolve/rust-late-name-resolver-2.0.cc (Late::visit): Add environment
collection.
* resolve/rust-late-name-resolver-2.0.h: Add function prototype.
* resolve/rust-name-resolver.cc (Resolver::get_captures): Add assertion
to prevent NR2 usage with nr1 capture functions.
* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit): Use
nr2 captures.
* util/rust-hir-map.cc (Mappings::add_capture): Add function to
register capture for a given closure.
(Mappings::lookup_captures): Add a function to lookup all captures
available for a given closure.
* util/rust-hir-map.h: Add function prototypes.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Some of our tests only work with name resolution 2.0 because the latter
misinterprets type paths. This change should cause the compiler to error out
if it would otherwise misinterpret a type path. A fix for type path
resolution isn't included in this comment, since doing so would make it
harder to track the meaningfulness of test regressions.
gcc/rust/ChangeLog:
* resolve/rust-late-name-resolver-2.0.cc
(Late::visit): Error out if a type path has multiple segments,
as we currently ignore every segment except the last.
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude: Add entries.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
Nr2 did not emit the correct error message for break identifier "rust".
gcc/rust/ChangeLog:
* resolve/rust-late-name-resolver-2.0.cc (Late::visit): Add "rust"
identifier detection akin to nr1.
(funny_ice_finalizer): Copy ICE finalizer from nr1.
* resolve/rust-late-name-resolver-2.0.h: Add funny_error member
context state.
* Make-lang.in: Add new translation unit for new ice finalizer.
* resolve/rust-ast-resolve-expr.cc: Move ice
finalizer to it's own file.
* resolve/rust-ice-finalizer.cc: New file.
* resolve/rust-ice-finalizer.h: New file.
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude: Remove break-rust3.rs from exclude list.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
gcc/rust/ChangeLog:
* expand/rust-derive-clone.cc (DeriveClone::visit_union): Use lang items for Copy and
Sized bounds.
gcc/testsuite/ChangeLog:
* rust/compile/derive_macro6.rs: Add lang item attribute to Copy trait.
Add and implement a lang item (receiver) in source code.
gcc/rust/ChangeLog:
* util/rust-lang-item.cc: Add receiver to map.
* util/rust-lang-item.h: Define LangItem::Kind::RECEIVER.
gcc/testsuite/ChangeLog:
* rust/compile/issue-2954.rs: New test.
Signed-off-by: lishin <lishin1008@gmail.com>
This paves the way for adding trait bounds that aren't necessarily Sized.
gcc/rust/ChangeLog:
* typecheck/rust-tyty-bounds.cc (TypeBoundsProbe::add_trait_bound): New function.
* typecheck/rust-hir-type-bounds.h: Declare it.
(TypeBoundsProbe::assemble_builtin_candidate): Call into add_trait_bound.
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude: Add failing lang item typepaths tests.
* rust/execute/torture/derive_macro4.rs: Mark Clone as lang item.
gcc/rust/ChangeLog:
* expand/rust-derive-clone.cc (DeriveClone::clone_enum_struct): New function for deriving
enum struct variants.
(DeriveClone::visit_enum): Call into the new function.
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude:
* rust/compile/derive_clone_enum1.rs: New test.
* rust/compile/derive_clone_enum2.rs: New test.
* rust/compile/derive_clone_enum3.rs: New test.
* rust/execute/torture/derive_clone_enum1.rs: New test.
gcc/rust/ChangeLog:
* ast/rust-ast-builder.cc: Add new methods for constructing struct exprs.
* ast/rust-ast-builder.h: Mention how to build tuple expressions.
This method errors out if the lang item has not been declared yet.
gcc/rust/ChangeLog:
* util/rust-hir-map.cc (Mappings::get_lang_item_node): New.
* util/rust-hir-map.h: New function.
Which formats a lang item as it appears in source code.
gcc/rust/ChangeLog:
* util/rust-lang-item.cc (LangItem::PrettyString): New.
* util/rust-lang-item.h: New.
Lang item typepaths were not handled properly, and required a complete overhaul.
All old classes that concerned lang item paths are now modified to use a simpler
version of `AST::LangItemPath`, which has been removed. TypePath segments can now
be lang items, as this is requied for having generic lang item paths such as
PhantomData<T>.
gcc/rust/ChangeLog:
* ast/rust-path.h: Rework how lang item paths are represented.
* ast/rust-path.cc: Likewise.
* ast/rust-item.h: Likewise.
* ast/rust-ast.cc: Likewise.
* ast/rust-ast-collector.cc: Adapt to new lang item path system.
* ast/rust-ast-collector.h: Likewise.
* ast/rust-ast-visitor.cc (DefaultASTVisitor::visit): Likewise.
* ast/rust-ast-visitor.h: Likewise.
* expand/rust-derive-copy.cc: Likewise.
* expand/rust-derive.h: Likewise.
* hir/rust-ast-lower-base.cc (ASTLoweringBase::visit): Likewise.
* hir/rust-ast-lower-base.h: Likewise.
* hir/rust-ast-lower-type.cc (ASTLowerTypePath::translate): Likewise.
(ASTLowerTypePath::visit): Likewise.
* hir/rust-ast-lower-type.h: Likewise.
* resolve/rust-ast-resolve-base.cc (ResolverBase::visit): Likewise.
* resolve/rust-ast-resolve-base.h: Likewise.
* resolve/rust-ast-resolve-item.cc (ResolveItem::visit): Likewise.
* resolve/rust-ast-resolve-type.h: Likewise.
* resolve/rust-ast-resolve-type.cc (ResolveRelativeTypePath::go): Likewise.
* resolve/rust-late-name-resolver-2.0.cc (Late::visit): Likewise.
* resolve/rust-late-name-resolver-2.0.h: Likewise.
* hir/tree/rust-hir-path.cc (TypePathSegment::TypePathSegment): Likewise.
(TypePathSegmentGeneric::TypePathSegmentGeneric): Likewise.
* hir/tree/rust-hir-path.h: Likewise.
* typecheck/rust-hir-type-check-type.cc (TypeCheckType::resolve_root_path): Likewise.
* ast/rust-ast-builder.cc: Likewise.
* ast/rust-ast-builder.h: Likewise.
We need to add name resolution and hir lowering for items as part of blocks
in order to typecheck and compile them correctly.
Fixes Rust-GCC#3350
gcc/rust/ChangeLog:
* hir/rust-ast-lower-stmt.cc (ASTLoweringStmt::visit): hir lowering
* hir/rust-ast-lower-stmt.h: likewise
* resolve/rust-ast-resolve-stmt.cc (ResolveStmt::visit): name resolution
* resolve/rust-ast-resolve-stmt.h: likewise
gcc/testsuite/ChangeLog:
* rust/compile/issue-3350.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
gcc/testsuite/ChangeLog:
* rust/compile/macros/builtin/eager1.rs: Switch to scan-assembler directive as the
GIMPLE dump does not contain strings on LE.
* rust/compile/macros/builtin/recurse2.rs: Likewise.
Some failures occur in the testsuite because we
did not account for the little-endian case.
gcc/testsuite/ChangeLog:
* rust/compile/issue-1446.rs: Add swap_bytes function.
* rust/compile/iterators1.rs: Remove unused {to, from}_le functions.
ForeverStackStore is meant to partially unify the internal states of
per-namespace ForeverStack instances. This commit does not contain
modifications to ForeverStack which would allow it to rely on a
ForeverStackStore to store nodes, but a future commit should address
this.
gcc/rust/ChangeLog:
* Make-lang.in: Handle rust-forever-stack.cc.
* resolve/rust-forever-stack.h
(class ForeverStackStore): Add.
* resolve/rust-forever-stack.cc: New file, based on
rust-forever-stack.hxx.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
gcc/testsuite/ChangeLog:
* rust/compile/try-catch-unwind-old.rs: add a test to test the older
try intrinsics from plain old Rust to v1.78.0
* rust/compile/try-catch-unwind-new.rs: add a test to test the newer
catch_unwind instrinsics since Rust v1.78.0
gcc/rust/ChangeLog:
* backend/rust-compile-intrinsic.cc: add the new `catch_unwind` variant
of the `try` intrinsic: this variant can be seen on Rust 1.78+
and returns `()` instead of `i32`.
Unify rules are not the same as coercion rules. The coercion of ! is
allowed to any type but not for a unify site which is different.
Match arms are another least upper bound coercion.
gcc/rust/ChangeLog:
* backend/rust-compile-expr.cc (CompileExpr::visit): implement coercion
* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit): this is an LUB
* typecheck/rust-unify.cc (UnifyRules::go): remove unify ! coercion
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
gccrs now should be able to cast float types as numeric.
gcc/rust/ChangeLog:
* typecheck/rust-casts.cc (TypeCastRules::cast_rules): Add rule.
gcc/testsuite/ChangeLog:
* rust/compile/cast_float_as_integer.rs: New test.
Signed-off-by: Nobel Singh <nobel2073@gmail.com>
This changes our enum type layout so for example:
enum Foo {
A,
B,
C(char),
D { x: i32, y: i32 },
}
Used to get layed out like this in gccrs:
union {
struct A { int RUST$ENUM$DISR; };
struct B { int RUST$ENUM$DISR; };
struct C { int RUST$ENUM$DISR; char __0; };
struct D { int RUST$ENUM$DISR; i64 x; i64 y; };
}
This has some issues notably with the constexpr because this is just a
giant union it means its not simple to constify what enum variant we are
looking at because the discriminant is a mess.
This now gets layed out as:
struct {
int RUST$ENUM$DISR;
union {
struct A { };
struct B { };
struct C { char __0; };
struct D { i64 x; i64 y; };
} payload;
}
This layout is much cleaner and allows for our constexpr to work properly.
gcc/rust/ChangeLog:
* backend/rust-compile-expr.cc (CompileExpr::visit): new layout
* backend/rust-compile-pattern.cc (CompilePatternCheckExpr::visit): likewise
(CompilePatternBindings::visit): likewise
* backend/rust-compile-resolve-path.cc: likewise
* backend/rust-compile-type.cc (TyTyResolveCompile::visit): implement new layout
* rust-gcc.cc (constructor_expression): get rid of useless assert
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
Return type and parameter types are optional on closures.
gcc/rust/ChangeLog:
* hir/rust-hir-dump.cc (Dump::visit): add null guard
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
The Eq and Partial Ord are very similar to the operator overloads
we support for add/sub/etc... but they differ in that usually the
function call name matches the name of the lang item. This time
we need to have support to send in a new path for the method call
on the lang item we want instead of just the name of the lang item.
NOTE: this test case doesnt work correctly yet we need to support
the derive of partial eq on enums to generate the correct comparison
code for that.
Fixes Rust-GCC#3302
gcc/rust/ChangeLog:
* backend/rust-compile-expr.cc (CompileExpr::visit): handle partial_eq possible call
* backend/rust-compile-expr.h: handle case where lang item calls differ from name
* hir/tree/rust-hir-expr.cc (OperatorExprMeta::OperatorExprMeta): new helper
* hir/tree/rust-hir-expr.h: likewise
* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit): handle partial_eq
(TypeCheckExpr::resolve_operator_overload): likewise
* typecheck/rust-hir-type-check-expr.h: likewise
* util/rust-lang-item.cc (LangItem::ComparisonToLangItem): map comparison to lang item
(LangItem::ComparisonToSegment): likewise
* util/rust-lang-item.h: new lang items PartialOrd and Eq
* util/rust-operators.h (enum class): likewise
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude: nr2 cant handle this
* rust/compile/cmp1.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
We need to check if the borrowed value is valid before creating the
reference type. Otherwise this will lead to an ICE.
Fixes Rust-GCC#3140
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit): check for error
* typecheck/rust-tyty-call.cc (TypeCheckCallExpr::visit): likewise and remove debug error
gcc/testsuite/ChangeLog:
* rust/compile/issue-3046.rs: remove old error message
* rust/compile/nr2/exclude: nr2 cant handle this
* rust/compile/issue-3140.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
gcc/rust/ChangeLog:
* resolve/rust-default-resolver.cc
(DefaultResolver::visit): Make sure to scope visitation of the
children of type definition items.
* resolve/rust-default-resolver.h
(DefaultResolver::visit): Add overrides for TupleStruct, Union,
and TypeAlias.
* resolve/rust-late-name-resolver-2.0.cc
(Late::visit): Remove override for Enum.
* resolve/rust-late-name-resolver-2.0.h
(Late::visit): Likewise.
* resolve/rust-toplevel-name-resolver-2.0.cc
(TopLevel::visit): Rely more on DefaultResolver::visit.
* resolve/rust-toplevel-name-resolver-2.0.h
(TopLevel::visit): Remove override for BlockExpr.
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude: Remove entries.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
These hir nodes have optional expressions which need guarded
gcc/rust/ChangeLog:
* hir/rust-hir-dump.cc (Dump::do_qualifiedpathtype): add guard
(Dump::do_traitfunctiondecl): likewise
(Dump::visit): likewise
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
Replaces the DIY vector stack with a StackedContexts object for block
scopes in the type checker context.
Fixes#3284.
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check.h (class TypeCheckContext): add
header file and use StackedContexts for blocks
* typecheck/rust-typecheck-context.cc: update methods
* typecheck/rust-hir-trait-resolve.cc: refactor function calls
* typecheck/rust-hir-type-check-implitem.cc: refactor function calls
* typecheck/rust-hir-type-check-type.cc: refactor function calls
Signed-off-by: Prajwal S N <prajwalnadig21@gmail.com>
This commit adds things like Item::Kind, Expr::Kind, etc, and implements the associated `get_*_kind` functions.
It also removes the more generic AST::Kind enum we were using, which was incomplete and painful to use.
gcc/rust/ChangeLog:
* ast/rust-ast.h: Add new Kind enums, remove Node class.
* ast/rust-builtin-ast-nodes.h: Use new Kind enums.
* ast/rust-expr.h (class LoopLabel): Likewise.
* ast/rust-item.h: Likewise.
* ast/rust-macro.h: Likewise.
* ast/rust-path.h: Likewise.
* expand/rust-macro-builtins-helpers.cc: Likewise.
* expand/rust-macro-builtins-utility.cc (MacroBuiltin::concat_handler): Likewise.
(MacroBuiltin::stringify_handler): Likewise.
* resolve/rust-ast-resolve-expr.cc (ResolveExpr::visit): Likewise.
* resolve/rust-early-name-resolver.cc: Likewise.
* hir/rust-ast-lower.cc (ASTLoweringBlock::visit): Likewise.
This commit correctly lowers and typechecks parenthesized types, which are used for trait objects with additional bounds.
gcc/rust/ChangeLog:
* resolve/rust-ast-resolve-type.cc (ResolveType::visit): New visitor to handle
ParenthesizedType.
* resolve/rust-ast-resolve-type.h: Likewise.
* typecheck/rust-hir-type-check-type.cc (TypeCheckType::visit): Likewise.
* typecheck/rust-hir-type-check-type.h: Likewise.
gcc/testsuite/ChangeLog:
* rust/compile/auto_traits2.rs: New test.
* rust/compile/auto_traits3.rs: New test.
* rust/compile/nr2/exclude: Add auto_traits2 test.
This is useful for handling multiple trait bounds, and required for better handling of auto traits.
gcc/rust/ChangeLog:
* hir/rust-ast-lower-type.cc (ASTLoweringType::visit): Add implementation for
ParenthesizedType.
* hir/rust-ast-lower-type.h: Declare that new visitor.
gcc/testsuite/ChangeLog:
* rust/compile/auto_traits1.rs: New test.
gcc/rust/ChangeLog:
* resolve/rust-late-name-resolver-2.0.cc:
Change the late name resolver to enter proper lexical scope during typechecking
* resolve/rust-late-name-resolver-2.0.h:
Add needed prototype to header
* resolve/rust-toplevel-name-resolver-2.0.cc:
Add generic parameters to enum's scoped RIB to allow for proper name resolution on types.
gcc/testsuite/ChangeLog:
* rust/compile/issue-3304.rs:
Add small test for generics+enums combination for NR2.0
Signed-off-by: Liam Naddell <liam.naddell@mail.utoronto.ca>
This commit adds new methods for building pattern nodes, match expressions and more precise call expressions.
gcc/rust/ChangeLog:
* ast/rust-ast-builder.cc: Add new functions.
* ast/rust-ast-builder.h: Declare them.
This commit adds two new constructors for AST::PathInExpression: One using a provided lang-item, and one with an already built std::unique_ptr<Path>
gcc/rust/ChangeLog:
* ast/rust-path.h: Add two new constructors.
gcc/rust/ChangeLog:
* ast/rust-collect-lang-items.cc (CollectLangItems::visit): Add visitor for collecting
functions that might be lang items.
* ast/rust-collect-lang-items.h: Likewise.
If additional trait bounds aren't auto traits, then the typechecker
must error out (Rust-GCC#3008)
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-type.cc: Add TODO note.
Regression checks for Rust-GCC#1399
gcc/testsuite/ChangeLog:
* rust/compile/multiline-string.rs: New test.
* rust/execute/torture/multiline-string.rs: New test.
Added rules to allow type casting pointer as integer types (u*,i*)
and integer types to be casted as pointer.
gcc/rust/ChangeLog:
* typecheck/rust-casts.cc (TypeCastRules::cast_rules): Add rule.
gcc/testsuite/ChangeLog:
* rust/compile/ptr_int_cast.rs: New test.
Signed-off-by: Nobel Singh <nobel2073@gmail.com>
gcc/rust/ChangeLog:
* ast/rust-item.h: I have changed helper constructor for typepath
to be a delegating constructor.
Signed-off-by: Sri Ganesh Thota <sriganeshthota12345@gmail.com>
In order to handle the tuple pattern of: fn test ((x _) : (i32, i32)) -> i32 { x }
we need to recognize that ABI wise this function still takes a tuple as the parameter
to this function its just how we can address the "pattern" of the tuple changes.
So reall if this was C it would look like:
void test (struct tuple_type __prameter)
{
return __parameter.0
}
The code here reuses our existing pattern code so that we generate these implicit
bindings of the paramter with a field access so any time x is referenced it's really
just emplacing __parameter.0 for the field access into the struct which is a tuple.
Fixes Rust-GCC#2847
gcc/rust/ChangeLog:
* backend/rust-compile-fnparam.cc (CompileFnParam::visit): compile tuple patterns
(CompileSelfParam::compile): update return type
(CompileFnParam::create_tmp_param_var): return Bvariable not tree to stop ICE
* backend/rust-compile-fnparam.h: update prototype
* backend/rust-compile-pattern.cc (CompilePatternBindings::visit): implement TuplePattern
* backend/rust-compile-pattern.h: update prototype
gcc/testsuite/ChangeLog:
* rust/compile/issue-2847.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
We moved to a bootstrap requirement of C++11 in GCC 11, 8 years after
support was stable in GCC 4.8.
It is now 8 years since C++14 was the default mode in GCC 6 (and 9 years
since support was complete in GCC 5), and we have a few bits of optional
C++14 code in the compiler, so it seems a good time to update the bootstrap
requirement again.
The big benefit of the change is the greater constexpr power, but C++14 also
added variable templates, generic lambdas, lambda init-capture, binary
literals, and numeric literal digit separators.
C++14 was feature-complete in GCC 5, and became the default in GCC 6. 5.4.0
bootstraps trunk correctly; trunk stage1 built with 5.3.0 breaks in
eh_data_format_name due to PR69995.
gcc/ChangeLog:
* doc/install.texi (Prerequisites): Update to C++14.
ChangeLog:
* configure.ac: Update requirement to C++14.
* configure: Regenerate.
gcc/rust/ChangeLog:
* ast/rust-item.h: Add new method to specifically get a type-path.
* ast/rust-path.cc (LangItemPath::as_string): Implement properly.
* hir/rust-ast-lower-type.cc (ASTLowerTypePath::translate): Adapt
visitor to use the new LangItemPath.
* hir/rust-ast-lower-type.h: Likewise.
* resolve/rust-ast-resolve-item.cc (ResolveItem::visit): Likewise.
* resolve/rust-ast-resolve-type.h: Likewise.
This commit adds a new kind of Path, changes the base Path class and turns TypePath
into a child of the base Path class.
gcc/rust/ChangeLog:
* ast/rust-path.h (class LangItemPath): New.
(class TypePath): Adapt to accomodate LangItemPath.
* ast/rust-ast.cc (TraitImpl::as_string): Use new checks for lang items.
(QualifiedPathType::as_string): Likewise.
(FormatArgs::set_outer_attrs): Likewise.
* ast/rust-item.h (class TraitImpl): Likewise.
gcc/rust/ChangeLog:
* util/rust-hir-map.h: Keep a NodeId mappings for lang items.
* util/rust-hir-map.cc (Mappings::insert_lang_item_node): New function.
(Mappings::lookup_lang_item_node): Likewise.
gcc/rust/ChangeLog:
* hir/rust-hir-dump.cc (Dump::visit): add missing check for no return value
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
These are ported from the c-family code c-warn.cc and c/c-typchk.cc
Fixes Rust-GCC#2394
gcc/rust/ChangeLog:
* backend/rust-constexpr.cc (eval_store_expression): check for null
(eval_call_expression): remove bad warning
* rust-gcc.cc (arithmetic_or_logical_expression): add warnings
gcc/testsuite/ChangeLog:
* rust/compile/issue-2394.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
The code here was wrongly assuming the decl type from the folding of the
expression would be the type of the constant decl. This is not the case for
unsized coercions for slices, where the expression here is a reference to
an array then we require the coercion to fix the result up to the expected
type.
Fixes Rust-GCC#1525
gcc/rust/ChangeLog:
* backend/rust-compile-base.cc: apply coercion site to result
* backend/rust-compile-base.h: update prototype
* backend/rust-compile-implitem.cc (CompileTraitItem::visit): send in coercion info
* backend/rust-compile-item.cc (CompileItem::visit): likewise
gcc/testsuite/ChangeLog:
* rust/compile/issue-1525.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
This was a handy debug assertion but only works for valid rust code. This
needs to handle the case where the type is not resolved which is a valid
case.
Fixes Rust-GCC#2423
gcc/rust/ChangeLog:
* resolve/rust-ast-resolve-item.cc (ResolveItem::visit): remove assertions
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude: nr2 can't handle this
* rust/compile/issue-2423.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
We cannot apply aligned or packed after layout_type is called you need
to set this up first then call it.
Fixes Rust-GCC#3260
gcc/rust/ChangeLog:
* backend/rust-compile-type.cc (TyTyResolveCompile::visit): call lauout type directly
* rust-backend.h (struct_type): add optional layout parameter
(union_type): likewise
(fill_in_fields): likewise
* rust-gcc.cc (struct_type): likewise
(union_type): likewise
(fill_in_fields): only layout if we required
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
TypePaths have special handling for Self where we can look at the current ctx
for more acurate TypeAlias information if required. We cant do this for Impl
contexts but not for Traits as we might as well fall back to the TypePathProbe.
The other issue was the dyn type comming in because Foo::foo and Foo is a trait
reference we represent this as a dyn type as the root resolved path but then find
the associated impl block for this but we cannot do this when we have resolved to
a Dyn because this is just a representation that we know we are talking about a
trait not because we are actually working with a real Dyn type.
Fixes Rust-GCC#2907
gcc/rust/ChangeLog:
* typecheck/rust-hir-trait-resolve.cc (TraitResolver::resolve_trait): track trait
* typecheck/rust-hir-type-check-implitem.cc: trait block
* typecheck/rust-hir-type-check-path.cc (TypeCheckExpr::resolve_segments): dont when dyn
* typecheck/rust-hir-type-check-type.cc (TypeCheckType::visit): look at Self contenxt
(TypeCheckType::resolve_root_path): track if Self
(TypeCheckType::resolve_associated_type): look at current context for associated types
* typecheck/rust-hir-type-check-type.h: change prototype
* typecheck/rust-hir-type-check.h (class TypeCheckBlockContextItem):
new context system to track current state
* typecheck/rust-typecheck-context.cc (TypeCheckContext::have_block_context): likewise
(TypeCheckContext::peek_block_context): likewise
(TypeCheckContext::push_block_context): likewise
(TypeCheckContext::pop_block_context): likewise
(TypeCheckBlockContextItem::Item::Item): likewise
(TypeCheckBlockContextItem::TypeCheckBlockContextItem): likewise
(TypeCheckBlockContextItem::is_impl_block): likewise
(TypeCheckBlockContextItem::is_trait_block): likewise
(TypeCheckBlockContextItem::get_impl_block): likewise
(TypeCheckBlockContextItem::get_trait): likewise
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude: nr2 cant handle this
* rust/compile/issue-2907.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
Use a GCC 5.4.0 built from Compiler Explorer and execute everything on
ubuntu 22.04.
Use the caching framework provided by github to avoid downloading every
time from Compiler Explorer's servers.
ChangeLog:
* .github/workflows/ccpp.yml: Adjust to use gcc-5 on ubuntu 22.04.
Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
GCC's baseline was changed from C++11 -> C++14 and GCC 4.8 -> GCC 5.4
in r15-4719-ga9ec1bc06bd3cc, so adjust the baseline CI job accordingly.
One quirk here is that the Ubuntu image we're using in CI has 5.5.0
rather than 5.4.0. But I think we can eat that difference.
ChangeLog:
* .github/workflows/ccpp.yml: Use GCC 5.5 instead of GCC 4.8.
We are using github merge queues for some time now, instead of bors.
Remove unmaintained files, and remove bors mentions.
ChangeLog:
* .github/bors_log_expected_warnings: Move to...
* .github/log_expected_warnings: ...here.
* .github/workflows/ccpp.yml:
* .github/workflows/ccpp32alpine.yml:
* CONTRIBUTING.md:
* README.md:
* .github/bors.toml: Removed.
Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
This is a special case in Rust and the ! type can unify with pretty much
anything its almost a inference variable and a unit-type for special cases.
FixesRust-GCC/gccrs#3231FixesRust-GCC/gccrs#2567
gcc/rust/ChangeLog:
* backend/rust-compile-expr.cc (check_match_scrutinee): check for empty match
(CompileExpr::visit): fix assertion
* checks/errors/rust-hir-pattern-analysis.cc (check_match_usefulness): check for empty
* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit): resolve to !
gcc/testsuite/ChangeLog:
* rust/compile/exhaustiveness1.rs: remove bad check
* rust/compile/issue-2567-1.rs: New test.
* rust/compile/issue-2567-2.rs: New test.
* rust/compile/issue-2567-3.rs: New test.
* rust/compile/issue-3231.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
Issue references shall now be used with the Rust GCC prefix in order to
avoid mixing gccrs issues and GCC bugzilla PRs.
ChangeLog:
* .github/workflows/commit-format.yml: Add a new step to detect issue
references in commit messages.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
I probably missed a few spots, but this should cover most of the type
checker.
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-expr.cc: Add includes.
(TypeCheckExpr::visit): Use name resolver 2.0.
(TypeCheckExpr::resolve_operator_overload): Likewise.
(TypeCheckExpr::resolve_fn_trait_call): Likewise.
* typecheck/rust-hir-type-check-path.cc
(TypeCheckExpr::visit): Likewise.
(TypeCheckExpr::resolve_segments): Likewise.
* typecheck/rust-hir-type-check-type.cc
(TypeCheckType::resolve_segments): Likewise.
(ResolveWhereClauseItem::visit): Likewise.
(TypeCheckType::visit): Avoid usage of
Resolver::get_unit_type_node_id when handling TupleType, use
name resolver 2.0 when handling QualifiedPathInType.
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude: Remove entries.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
gcc/rust/ChangeLog:
* backend/rust-compile-expr.cc (CompileExpr::visit): Change call.
(CompileExpr::resolve_operator_overload): Update function arguments.
* backend/rust-compile-expr.h: Change the function's prototype to use
a reference wrapper instead of a reference within the optional.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Clang on macos as well as GCC 4.8 complains when those templates are
missing.
gcc/rust/ChangeLog:
* hir/rust-ast-lower-expr.cc (ASTLoweringExpr::visit): Add template
to tl::optional.
* hir/rust-ast-lower-type.cc (ASTLowerGenericParam::visit): Likewise.
* typecheck/rust-hir-type-check-type.cc (TypeResolveGenericParam::visit):
Likewise.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Condition was inverted, we should retrieve the locus only if we have a
pattern.
gcc/rust/ChangeLog:
* typecheck/rust-tyty-call.cc (TypeCheckCallExpr::visit): Do not
get a reference if the pattern does not exist.
(TypeCheckMethodCallExpr::check): Likewise.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Refactor some optional initializer in the lowering stage to make them
more readable.
gcc/rust/ChangeLog:
* hir/rust-ast-lower-stmt.cc (ASTLoweringStmt::visit): Change the
ternary expression with a more readable if.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
FnParam type where monomorphized during cloning.
gcc/rust/ChangeLog:
* typecheck/rust-tyty.h: Reverse monomorphization during cloning and
make a new function to explicitly monomorphize.
* typecheck/rust-tyty.cc: Use monomorphization when required.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
gcc/rust/ChangeLog:
* hir/rust-ast-lower-type.cc (ASTLowerGenericParam::visit): Forward
an optional to the constructor.
* hir/tree/rust-hir-item.cc (TypeParam::TypeParam): Use an optional
in the constructor.
(TypeParam::operator=): Ensure the TypeParam has a type properly.
(TypeParam::get_type_mappings): Likewise.
* hir/tree/rust-hir-item.h: Wrap the type smart pointer into an
optional.
* hir/tree/rust-hir.cc (TypeParam::as_string): Unwrap optional type
correctly.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
A variant being moved lead to a null being created and a segfault later
down the line.
gcc/rust/ChangeLog:
* backend/rust-compile-expr.cc (CompileExpr::visit): Call getter
instead of size function.
* checks/errors/privacy/rust-privacy-reporter.cc (PrivacyReporter::visit):
Only check privacy if the type is present.
* hir/rust-ast-lower-stmt.cc (ASTLoweringStmt::visit): Use an optional.
* hir/tree/rust-hir-generic-param.h: Assert type before getting it.
* hir/tree/rust-hir-item.h: Assert pointers before dereference, fix
has_type condition.
* hir/tree/rust-hir-path.h: Add more assertions.
* hir/tree/rust-hir-stmt.cc: Change constructor with optionals.
* hir/tree/rust-hir-stmt.h: Use optionals over smart pointers to
emphasize these fields might be missing.
* hir/tree/rust-hir.cc (LetStmt::as_string): Use getters.
* typecheck/rust-hir-type-check-expr.cc: Clone structures to prevent
parent's fields from being nulled by the move operation.
* typecheck/rust-hir-type-check-item.cc (TypeCheckItem::visit): Use
optionals.
* typecheck/rust-tyty.cc: Likewise.
* typecheck/rust-tyty.h: Likewise.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Refactor the hir tree files to remove raw pointer usage and most forward
declarations. Move implementation out of headers and split headers into
smaller and more manageable units.
gcc/rust/ChangeLog:
* Make-lang.in: Add new files.
* hir/tree/rust-hir-item.h: Move Item definition and remove
implementations to their corresponding cc file.
* hir/tree/rust-hir-expr.h: Move implementation to the corresponding
cc file.
* hir/tree/rust-hir-path.h: Likewise.
* hir/tree/rust-hir-pattern.h: Likewise.
* hir/tree/rust-hir-stmt.h: Likewise.
* hir/tree/rust-hir-type.h: Likewise.
* hir/tree/rust-hir-visitor.h: Likewise.
* hir/tree/rust-hir.h: Likewise.
* hir/tree/rust-hir.cc (Crate::Crate): Add implementations from Crate
and remove ConstGenericParam implementations to move them to their
own file.
* hir/tree/rust-hir-attrs.h: New file.
* hir/tree/rust-hir-bound-abstract.h: New file.
* hir/tree/rust-hir-bound.h: New file.
* hir/tree/rust-hir-expr-abstract.h: New file.
* hir/tree/rust-hir-expr.cc: New file.
* hir/tree/rust-hir-generic-param.cc: New file.
* hir/tree/rust-hir-generic-param.h: New file.
* hir/tree/rust-hir-item.cc: New file.
* hir/tree/rust-hir-literal.h: New file.
* hir/tree/rust-hir-node.h: New file.
* hir/tree/rust-hir-path.cc: New file.
* hir/tree/rust-hir-pattern-abstract.h: New file.
* hir/tree/rust-hir-simple-path.h: New file.
* hir/tree/rust-hir-stmt.cc: New file.
* hir/tree/rust-hir-trait-bound.h: New file.
* hir/tree/rust-hir-type-abstract.cc: New file.
* hir/tree/rust-hir-type-abstract.h: New file.
* hir/tree/rust-hir-type-no-bounds.h: New file.
* hir/tree/rust-hir-type.cc: New file.
* hir/tree/rust-hir-visibility.h: New file.
* hir/tree/rust-hir-visitable.h: New file.
* checks/lints/rust-lint-marklive.h: Use References.
* hir/rust-ast-lower-expr.cc (ASTLoweringExpr::visit): Reformat
vectors.
* hir/rust-hir-dump.cc (Dump::visit): Use reference.
* typecheck/rust-hir-type-check-struct.cc (TypeCheckStructExpr::resolve):
Use references.
* typecheck/rust-tyty-bounds.cc: Likewise.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
The HIR made heavy use of pair and other unamed types which can be
difficult to read.
gcc/rust/ChangeLog:
* backend/rust-compile-base.cc: Use FnParam getter.
* backend/rust-compile-expr.cc (CompileExpr::visit): Likewise.
* backend/rust-compile-intrinsic.cc: Likewise.
* backend/rust-compile-type.cc: Likewise.
* checks/errors/privacy/rust-privacy-reporter.cc (PrivacyReporter::visit):
Only visit childrens if not missing.
* checks/errors/rust-unsafe-checker.cc (UnsafeChecker::visit): Use
a reference instead of a raw pointer.
* hir/tree/rust-hir-expr.h: Add presence function for return
expression.
* hir/tree/rust-hir-item.h: Remove take_param_name.
* hir/tree/rust-hir.h: Make mapping getter const.
* typecheck/rust-hir-dot-operator.cc (MethodResolver::Select): Use
getter.
* typecheck/rust-hir-type-check-expr.cc: Likewise.
* typecheck/rust-hir-type-check-implitem.cc: Use FnParam vector instead
of std::pair of Pattern and BaseType.
* typecheck/rust-hir-type-check-item.cc: Likewise.
* typecheck/rust-hir-type-check.cc: Likewise.
* typecheck/rust-tyty-call.cc (TypeCheckCallExpr::visit): Use getters.
(TypeCheckMethodCallExpr::check): Likewise.
* typecheck/rust-tyty-cmp.h: Likewise.
* typecheck/rust-tyty.cc: Use FnParam.
* typecheck/rust-tyty.h (class FnParam): Add FnParam to handle function
parameters instead of handling std::pairs.
* typecheck/rust-unify.cc (UnifyRules::expect_fndef): Use getters.
(UnifyRules::expect_fnptr): Likewise.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
gcc/rust/ChangeLog:
* resolve/rust-toplevel-name-resolver-2.0.cc
(TopLevel::visit): Use DefaultResolver::visit and avoid a call
to Identifier::as_string while handling instances of StaticItem.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
When resolving a type like this which is generic it causes the argument
substitution to go through bounds checking which is expected. But this
can call a type bounds probe which again calls a type query which will be
on the Impl Type on an impl block which can result in a recursive type
query which does eventually get caught and errors correctly. But this then
triggers some old error diagnositcs which are not valid error codes but old
error messages we used to catch simple errors very early on which do not
apply for this senario.
Fixes Rust-GCC#2905
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-item.cc (TypeCheckItem::resolve_impl_block_substitutions):
dont check for unconstrained when the self is not resolved
* typecheck/rust-hir-type-check-type.cc (TypeCheckType::resolve_root_path):
remove bad debug error diagnostic
* typecheck/rust-tyty-subst.cc: likewise
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude: nr2 cant handle this
* rust/compile/issue-2905-1.rs: New test.
* rust/compile/issue-2905-2.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
The original test case 1773 has been moved to a new issue 3242 which
is still open and test-case is skipped. The original issue in 1773 is
fixed so this will close out that issue
Fixes Rust-Gcc#1773
gcc/testsuite/ChangeLog:
* rust/compile/issue-1773.rs: new test case
* rust/compile/nr2/exclude: nr2 cant handle this
* rust/compile/issue-3242.rs: old test ranamed to match issue.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
We can have a case where the placeholder is not configred and the
can_resolve check is not detecting this case which can lead to ICE.
gcc/rust/ChangeLog:
* typecheck/rust-tyty.cc (PlaceholderType::can_resolve): check for empty mappings
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
Move the code from i386-rust.cc to i386-rust-and-jit.inc so that it can
be reused by libgccjit.
gcc/ChangeLog:
* config/i386/i386-rust-and-jit.inc: New file.
* config/i386/i386-rust.cc: Move code to i386-rust-and-jit.inc.
We do not need to inject inference variables on generic patterns
with generic blocks. This will just cause unconstrained inference
variables as they may not unify against something.
Fixes Rust-GCC#2323
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-path.cc (TypeCheckExpr::resolve_root_path): dont infer here
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude: nr2 cant handle this
* rust/compile/issue-2323.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
This catch to inject inference variables into generic paths was a
catch all 'hack' that we needed before we handled generics correctly
as we do now.
Fixes#3009
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-path.cc (TypeCheckExpr::resolve_segments): remove hack
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude: nr2 cant handle this
* rust/compile/issue-3009.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
The issue here was that the impl block for Cell<T> defines that T must have
the bound of Copy implemented. But simultaneously if you do an deref
you get direct access to the unsafe cell which also defines a get method
so these are two valid ways of accessing the method in question but
when Copy is implementet the simplest case is prefered so it does resolve
to Cell<T>::get.
Fixes#3033
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude: nr can't handle this
* rust/compile/issue-3033.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
gcc/rust/ChangeLog:
* checks/errors/rust-unsafe-checker.cc: Add includes.
(UnsafeChecker::visit): Use 2.0 version of resolver when name
resolution 2.0 is enabled.
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude: Remove entries.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
gcc/rust/ChangeLog:
* backend/rust-compile-implitem.cc
(CompileTraitItem::visit): Use name resolver 2.0 (when enabled)
to obtain canonical paths for instances of TraitItemConst and
TraitItemFunc.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check.cc: Add includes.
(TraitItemReference::get_type_from_fn): Use
ForeverStack::to_canonical_path when name resolution 2.0 is
enabled.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
gcc/rust/ChangeLog:
* resolve/rust-late-name-resolver-2.0.cc
(Late::visit): Visit the initialization expressions of let
statements before visiting their patterns.
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude: Remove entries.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
gcc/rust/ChangeLog:
* resolve/rust-toplevel-name-resolver-2.0.cc
(TopLevel::visit): Insert trait names into the type namespace.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
When we are typechecking the impl block for DerefMut for &mut T
the implementation follows the usual operator overload check
but this ended up just resolving directly to the Trait definition
which ends up being recursive which we usually handle. The issue
we had is that a dereference call can be for either the DEREF
or DEREF_MUT lang item here it was looking for a recurisve call
to the DEREF lang item but we were in the DEREF_MUT lang item
so this case was not accounted for.
Fixes#3032
gcc/rust/ChangeLog:
* typecheck/rust-hir-trait-reference.h: new get locus helper
* typecheck/rust-hir-trait-resolve.cc (AssociatedImplTrait::get_locus): implemention
* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::resolve_operator_overload):
fix overload
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude: nr2 cant handle this
* rust/compile/issue-3032-1.rs: New test.
* rust/compile/issue-3032-2.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
gcc/rust/ChangeLog:
* backend/rust-compile-expr.cc
(CompileExpr::visit): Use name resolver 2.0 to lookup label
definitions for break and continue statements when name
resolution 2.0 is enabled.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
gcc/rust/ChangeLog:
* checks/errors/rust-const-checker.cc: Add includes.
(ConstChecker::visit): Use name resolver 2.0 to lookup
function definitions when name resolution 2.0 is enabled.
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude: Remove entries.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
This may load conditionally compiled modules too eagerly.
gcc/rust/ChangeLog:
* resolve/rust-toplevel-name-resolver-2.0.cc
(TopLevel::visit): Load unloaded modules before attempting to
visit their items.
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude: Remove issue-1089.rs.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
gcc/rust/ChangeLog:
* resolve/rust-late-name-resolver-2.0.cc
(Late::visit): Visit GenericArgs and GenericArg, the former
because the latter involves a non-virtual member function call.
* resolve/rust-late-name-resolver-2.0.h
(Late::visit): Likewise.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
gcc/rust/ChangeLog:
* resolve/rust-late-name-resolver-2.0.cc
(Late::visit): Allow IdentifierExpr and PathInExpression to
reference types as well as values, remove ability for
IdentifierExpr to reference labels.
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude: Remove entries.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
gcc/rust/ChangeLog:
* backend/rust-compile-item.cc
(CompileItem::visit): Check canonical path of StaticItem
properly when name resolution 2.0 is enabled.
* resolve/rust-toplevel-name-resolver-2.0.cc
(TopLevel::visit): Insert static items into the value namespace.
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude: Remove entries.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
Not thrilled with some of this boilerplate, but it does seem like an
improvement.
gcc/rust/ChangeLog:
* ast/rust-expr.h
(InlineAsmOperand): Replace multiple mutually-exclusive tl::optional
fields with a std::unique_ptr and modify nested classes to allow
this. Also, make getters return references where possible.
* expand/rust-macro-builtins-asm.cc
(parse_reg_operand_out): Pass location when constructing
InlineAsmOperand.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
We just had an assertion here for this case where we expect a trait.
This changes the assertion into error handling producing the correct
error code with fixit suggestion like rustc.
Fixes#2499
gcc/rust/ChangeLog:
* typecheck/rust-hir-trait-resolve.cc (TraitResolver::resolve_path_to_trait):
use error handling instead of assertion
* typecheck/rust-hir-type-check-item.cc (TypeCheckItem::visit): reuse trait reference
* typecheck/rust-hir-type-check-item.h: update prototype
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude: nr2 cant handle this
* rust/compile/issue-2499.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
This was resolved in: 18422c9c38 which was missing the name
resolution step for unit-types.
Fixes#2203
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude:
* rust/compile/issue-2203.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
The resolution with ! was fixed in: 09cfe530f9 this adds a
test case to show the other issue is also fixed.
Fixes#2951
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude: nr2 is crashing here
* rust/compile/issue-2951.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
The canonical paths need to support unit-types which are technically a
TupleType with no fields. This handles this case and adds an unreachable.
Fixes#3036
gcc/rust/ChangeLog:
* resolve/rust-ast-resolve-type.cc (ResolveTypeToCanonicalPath::visit): add unit-type catch
* resolve/rust-ast-resolve-type.h: likewise
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude: nr2 cant handle this
* rust/compile/issue-3036.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
When we generate derivations for Copy and Clone we need to make sure
the associated impl block sets up the generic parameters and arguments
correctly. This patch introduces the framework to copy chunks of the AST
because we need to make sure these new AST nodes have their own associated
id, calling clone on the nodes will just confuse name-resolution and
subsequent mappings.
Fixes#3139
gcc/rust/ChangeLog:
* Make-lang.in: new objects
* ast/rust-ast-builder.cc (Builder::generic_type_path_segment): new helper
(Builder::single_generic_type_path): likewise
(Builder::new_type): likewise
(Builder::new_lifetime_param): likewise
(Builder::new_type_param): likewise
(Builder::new_lifetime): likewise
(Builder::new_generic_args): likewise
* ast/rust-ast-builder.h: new helper decls
* ast/rust-ast.h: new const getters
* ast/rust-path.h: likewise
* ast/rust-type.h: likewise
* expand/rust-derive-clone.cc (DeriveClone::clone_impl): take the types generics
(DeriveClone::visit_tuple): likewise
(DeriveClone::visit_struct): likewise
(DeriveClone::visit_union): likewise
* expand/rust-derive-clone.h: update header
* expand/rust-derive-copy.cc (DeriveCopy::copy_impl): similarly take type generics
(DeriveCopy::visit_struct): likewise
(DeriveCopy::visit_tuple): likewise
(DeriveCopy::visit_enum): likewise
(DeriveCopy::visit_union): likewise
* expand/rust-derive-copy.h: likewse
* ast/rust-ast-builder-type.cc: New file.
* ast/rust-ast-builder-type.h: New file.
gcc/testsuite/ChangeLog:
* rust/compile/issue-3139-1.rs: New test.
* rust/compile/issue-3139-2.rs: New test.
* rust/compile/issue-3139-3.rs: New test.
* rust/compile/nr2/exclude: these all break nr2
We need the top level to run at least once before breaking because it
will be required by the other name resolution steps.
gcc/rust/ChangeLog:
* rust-session-manager.cc (Session::expansion): Break on error after
top level name resolution.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Box definition is part of the standard library and cannot be found during
name resolution. This simple definition prevent any error from being
emitted.
gcc/testsuite/ChangeLog:
* rust/compile/box_syntax_feature_gate.rs: Add box land item
definition.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
It requires the standard library and Copy to work correctly which we
cannot provide. Stopping the compiler before the name resolution allow us
to prevent an error whilst resolving Copy and keep the test's goal.
gcc/testsuite/ChangeLog:
* rust/compile/functions_without_body.rs: Add compile step argument.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
We might have some duplicated name in some pattern and we should
therefore not assert the non duplication of identifiers.
gcc/rust/ChangeLog:
* resolve/rust-late-name-resolver-2.0.cc (Late::visit): Remove
assertion and explicitely tells why we ignore the insertion result.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Move function implementation to their own file.
gcc/rust/ChangeLog:
* Make-lang.in: Add new rust-bir-builder-pattern file.
* checks/errors/borrowck/rust-bir-builder-pattern.h: Remove
implementation.
* checks/errors/borrowck/rust-bir-builder-pattern.cc: New file.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
We want to begin experimenting with this new name resolution 2.0
algorithm as soon as possible. This test highlight a problem where the
compiler should emit an error and should be fixed soon.
gcc/testsuite/ChangeLog:
* rust/compile/name_resolution21.rs: Move to...
* rust/compile/xfail/name_resolution21.rs: ...here.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Make those functions public so they can be used within a lambda on GCC
4.8.
gcc/rust/ChangeLog:
* ast/rust-ast-visitor.h: Make visit functions public.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
We can reduce code duplication by using the default visitor functions
from within the scoped lambda function.
gcc/rust/ChangeLog:
* resolve/rust-default-resolver.cc (DefaultResolver::visit): Use
default visitor instead.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
We can let the default visitor visit those nodes anyway so we're sure
all nodes can be reached.
gcc/rust/ChangeLog:
* resolve/rust-default-resolver.cc (DefaultResolver::visit): Remove
empty visit function implementations.
* resolve/rust-default-resolver.h: Remove corresponding prototypes.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Those function prototype were not marked as override and throwing
warning.
gcc/rust/ChangeLog:
* resolve/rust-default-resolver.h: Make most visit function override.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
When a use statement requires a reexported item it cannot find it in
the same pass, an additional pass shall be performed. This means we need
to detect whether a new item has been reexported and resolve until the
end.
gcc/rust/ChangeLog:
* resolve/rust-early-name-resolver-2.0.cc (Early::Early): Add dirty
flag initialization.
(Early::go): Set dirty flag using top level resolver.
* resolve/rust-early-name-resolver-2.0.h: Add dirty flag.
* resolve/rust-toplevel-name-resolver-2.0.cc (TopLevel::TopLevel):
Initialize dirty flag.
(TopLevel::insert_or_error_out): Set dirty flag on successful
namespace modification.
* resolve/rust-toplevel-name-resolver-2.0.h: Add dirty flag.
* rust-session-manager.cc (Session::expansion): Modify fixed point
condition to include name resolution modifications.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
When we tried to insert a shadowable node and another shadowable node has
been inserted before, we didn't emit any error if the node has already
been inserted previously and failed silently.
gcc/rust/ChangeLog:
* resolve/rust-rib.cc (Rib::insert): Emit an error when trying to
insert an already inserted node.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
gcc/rust/ChangeLog:
* resolve/rust-early-name-resolver-2.0.cc (Early::resolve_simple_import):
Insert import in all namespaces where they were resolved.
(Early::resolve_rebind_import): Likewise.
* resolve/rust-early-name-resolver-2.0.h: Improve APIs, make them
accept multiple resolutions.
* resolve/rust-finalize-imports-2.0.cc: Handle multiple resolutions.
* resolve/rust-name-resolution-context.h (resolve_path): Remove function.
gcc/rust/ChangeLog:
* resolve/rust-late-name-resolver-2.0.cc (Late::visit): Add debug call.
* resolve/rust-toplevel-name-resolver-2.0.cc (TopLevel::visit): Store
imports using the new classes.
* resolve/rust-toplevel-name-resolver-2.0.h: Use new classes.
gcc/rust/ChangeLog:
* resolve/rust-early-name-resolver-2.0.cc (Early::resolve_glob_import): New function.
(Early::resolve_simple_import): Likewise.
(Early::resolve_rebind_import): Likewise.
(Early::build_import_mapping): Likewise.
* resolve/rust-early-name-resolver-2.0.h: Add declarations and list of imports to
resolve.
* resolve/rust-toplevel-name-resolver-2.0.cc (TopLevel::handle_use_glob): Remove function,
which is now being handled by the Early name resolver.
(TopLevel::handle_use_dec): Likewise.
(TopLevel::handle_rebind): Likewise.
* resolve/rust-toplevel-name-resolver-2.0.h: Likewise, and add functions for creating
import list and fetching it.
This could trigger an assertions as `get_type` on `SelfParam` asserts that
the self param does have a given type, which is not always the case.
gcc/rust/ChangeLog:
* resolve/rust-default-resolver.cc (DefaultResolver::visit): Do not
visit self's type if it does not have one.
Qualified path expressions usually are <X as Y>::... but the as is optional
this adds the extra checking in hir lowering to not hit that nullptr.
Fixes#3082
gcc/rust/ChangeLog:
* hir/rust-ast-lower-type.cc (ASTLowerQualifiedPathInType::visit):
check for valid as segment
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude: nr2 cant handle this
* rust/compile/issue-3082.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
We need to resolve the never type which is its own special AST node so it
doesnt magically get handled like the regular builtin type paths such as
i32.
Fixes#3035
gcc/rust/ChangeLog:
* resolve/rust-ast-resolve-type.cc (ResolveType::visit):
handle never type
(ResolveTypeToCanonicalPath::visit): likewise
* resolve/rust-ast-resolve-type.h: missing never type
* resolve/rust-name-resolver.cc (Resolver::generate_builtins):
track never type node_id
(Resolver::setup_builtin): likewise
* resolve/rust-name-resolver.h: new never type getter
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude: nr2 cant handle this
* rust/compile/issue-3035.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
gcc/rust/ChangeLog:
* resolve/rust-default-resolver.cc
(DefaultResolver::visit): Remove some empty overloads which
DefaultASTVisitor::visit should be able to handle.
* resolve/rust-default-resolver.h
(DefaultResolver::visit): Likewise.
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude: Remove entries.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
This commit adds Liu Hao's patch from
5859d27b2b/mingw-w64-gcc/0100-rust-fix.patch
gcc/rust/ChangeLog:
* checks/errors/borrowck/rust-borrow-checker.cc (mkdir_wrapped): Remove.
(BorrowChecker::go): Use `mkdir` instead.
* expand/rust-proc-macro.cc (register_callback): Use Windows APIs to
open dynamic proc macro library.
(load_macros_array): Likewise.
* parse/rust-parse.cc (defined): Replace separators in paths using
std::replace.
Add tail_reachable and label fields to the dump.
gcc/rust/ChangeLog:
* hir/rust-hir-dump.cc (Dump::visit): Add missing fields.
Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
Negative polarity means we can just ignore if any trait items are not
implemented.
Fxies #3030
gcc/rust/ChangeLog:
* hir/rust-ast-lower-item.cc (ASTLoweringItem::visit): the polarity was reversed
* typecheck/rust-hir-type-check-item.cc: check the polarity
gcc/testsuite/ChangeLog:
* rust/compile/nr2/exclude: nr2 cant handle this
* rust/compile/issue-3030.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
add a resolve expr visitor on error propagation to avoid internal
compiler error when used with generics
gcc/rust/ChangeLog:
* resolve/rust-ast-resolve-expr.cc (ResolveExpr::visit): Add
implementation of error propagation visitor
* resolve/rust-ast-resolve-expr.h: Add prototype of error
propagation
Signed-off-by: benjamin.thos <benjamin.thos@epita.fr>
We did not check the optional was valid, this lead to rogue dereference
and undefined behaviors.
gcc/rust/ChangeLog:
* resolve/rust-late-name-resolver-2.0.cc (Late::visit): Add optional
check.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Version 2 of this github action has been deprecated, we shall bump the
version used in the CI.
ChangeLog:
* .github/workflows/bootstrap.yml: Bump version from 2 to 4.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add the "Tested-by" prefix to the list of already matched footer
prefixes.
Adjust the error message.
This avoid warnings on commits using it.
Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
This runs the standard compile/**.rs tests
with name resolution 2.0 enabled. The exclude file
can be used to exclude tests which are not yet working
with name resolution 2.0.
gcc/testsuite/ChangeLog:
* rust/compile/nr2/compile.exp: New test.
* rust/compile/nr2/exclude: New.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
Fixes#3141.
gcc/rust/ChangeLog:
* backend/rust-compile-expr.cc: Fix range checking for both integers and floats.
* hir/tree/rust-hir-expr.h: Add "negative_number" boolean to LiteralExpr class.
gcc/testsuite/ChangeLog:
* rust/compile/issue-3141.rs: New test.
Signed-off-by: Joan Vilardaga <github-91yu@joanvc.cat>
Throw an error when auto-traits used without feature attribute.
gcc/rust/ChangeLog:
* checks/errors/rust-feature-gate.cc (FeatureGate::visit): Emit error
on trait when auto field member true.
* checks/errors/rust-feature-gate.h: add prototype of trait visitor.
* checks/errors/rust-feature.cc (Feature::create): add
optin_builtin_traits in match of feature.
gcc/testsuite/ChangeLog:
* rust/compile/auto_trait_super_trait.rs: Add feature attribute.
* rust/compile/generic_auto_trait.rs: likewise.
* rust/compile/auto_trait.rs: add test for error without
feature attribute
Signed-off-by: benjamin.thos <benjamin.thos@epita.fr>
gcc/rust/ChangeLog:
* backend/rust-compile.cc:
Modify compute_address_for_trait_item to support supertraits
* typecheck/rust-tyty.cc:
Remove auto
gcc/testsuite/ChangeLog:
* rust/compile/trait13.rs:
Add test for supertraits of supertraits
* rust/compile/trait14.rs:
Diamond problem with supertraits test
* rust/execute/torture/trait14.rs:
Add test for dynamic dispatch with supertraits
* rust/execute/torture/trait15.rs:
Add test for dynamic dispatch with generics
* rust/execute/torture/trait16.rs:
Add test for dynamic dispatch with lifetime params 1
* rust/execute/torture/trait17.rs:
Add test for dynamic dispatch with lifetime params 2
* rust/execute/torture/trait18.rs:
Add test for default implementations with dynamic dispatch and
supertraits
Signed-off-by: Liam Naddell <liam.naddell@mail.utoronto.ca>
gcc/rust/ChangeLog:
* checks/errors/borrowck/rust-bir-dump.cc (Dump::go): Use strong
type instead of size_t.
(Dump::visit_place): Likewise.
(Dump::visit_scope): Likewise.
* checks/errors/borrowck/rust-bir-dump.h (class Dump): Use
IndeVec for place_map.
Signed-off-by: Kushal Pal <kushalpal109@gmail.com>
gcc/rust/ChangeLog:
* checks/errors/borrowck/rust-bir-dump.cc (simplify_cfg):
Used `IndexVec` for bb_fold_map.
(Dump::go): Use strong type as index instead of value as now we
are using `IndexVec`.
(Dump::visit): Likewise.
* checks/errors/borrowck/rust-bir-dump.h (class Dump): Use
`IndexVec` for bb_fold_map.
* checks/errors/borrowck/rust-bir-place.h: Add constructor for
`IndexVec` that can reserve size.
Signed-off-by: Kushal Pal <kushalpal109@gmail.com>
gcc/rust/ChangeLog:
* checks/errors/borrowck/rust-bir-builder-expr-stmt.cc
(ExprStmtBuilder::visit): Use strong type as index and
remove access to numeric value.
* checks/errors/borrowck/rust-bir-builder-internal.h
(struct BuilderContext): Likewise.
* checks/errors/borrowck/rust-bir-dump.cc (simplify_cfg):
Likewise.
(Dump::go): Likewise.
(Dump::visit): Likewise.
* checks/errors/borrowck/rust-bir-fact-collector.h
(class FactCollector): Likewise.
(points): Likewise.
* checks/errors/borrowck/rust-bir.h (struct BasicBlockId): Used
IndexVec for BasicBlocks.
(struct Function): Likewise.
* checks/errors/borrowck/rust-borrow-checker-diagnostics.cc
(BorrowCheckerDiagnostics::get_statement): Change the extracted
index to strong type.
Signed-off-by: Kushal Pal <kushalpal109@gmail.com>
gcc/rust/ChangeLog:
* checks/errors/borrowck/rust-bir-place.h: Used `IndexVec` with
ScopeId as index.
* checks/errors/borrowck/rust-borrow-checker-diagnostics.cc
(BorrowCheckerDiagnostics::get_loan): Convert Polonius::Loan to
BIR::Loan, so we can use it as index.
Signed-off-by: Kushal Pal <kushalpal109@gmail.com>
gcc/rust/ChangeLog:
* checks/errors/borrowck/rust-bir-place.h:
Used `IndexVec` with ScopeId as index.
Signed-off-by: Kushal Pal <kushalpal109@gmail.com>
gcc/rust/ChangeLog:
* checks/errors/borrowck/rust-bir-place.h (struct Loan):
Introduce new class `IndexVec` inspired from IndexVec of rust.
It acts as a wrapper around `std::vector` and lets user specify
a strong type to use as index.
Signed-off-by: Kushal Pal <kushalpal109@gmail.com>
gcc/rust/ChangeLog:
* checks/errors/borrowck/rust-bir-builder-expr-stmt.cc (ExprStmtBuilder::visit):
Use value of BasicBlockId as index.
* checks/errors/borrowck/rust-bir-builder-internal.h (struct BuilderContext):
Likewise.
* checks/errors/borrowck/rust-bir-builder-lazyboolexpr.h:
Initialize with ENTRY_BASIC_BLOCK.
* checks/errors/borrowck/rust-bir-dump.cc (simplify_cfg):
Use value of BasicBlockId as index.
(Dump::go): Likewise.
(Dump::visit): Likewise.
* checks/errors/borrowck/rust-bir-fact-collector.h (class FactCollector):
Initialize with ENTRY_BASIC_BLOCK.
(points): Use value of BasicBlockId as index.
* checks/errors/borrowck/rust-bir.h (struct BasicBlockId):
BasicBlockId is a struct now.
Signed-off-by: Kushal Pal <kushalpal109@gmail.com>
gcc/rust/ChangeLog:
* checks/errors/borrowck/rust-bir-builder-expr-stmt.cc
(ExprStmtBuilder::setup_loop): Use value of ScopeId.
(ExprStmtBuilder::visit): Use continue scope id instead of
continue basic block id.
* checks/errors/borrowck/rust-bir-builder-internal.h: Use value
of ScopeId.
* checks/errors/borrowck/rust-bir-dump.cc (Dump::go): Use
ROOT_VALUE instead of hardcoded 0.
(Dump::visit_scope): Use value of ScopeId.
* checks/errors/borrowck/rust-bir-place.h (struct ScopeId):
ScopeId is now a struct.
(std::numeric_limits::max): Set invalid ScopeId.
Signed-off-by: Kushal Pal <kushalpal109@gmail.com>
gcc/rust/ChangeLog:
* checks/errors/borrowck/rust-bir-dump.cc (Dump::visit): Use new
API, i.e get_loan_id() instead of get_loan().
* checks/errors/borrowck/rust-bir-fact-collector.h (points): Use
value of LoanId in Polonius facts.
* checks/errors/borrowck/rust-bir-place.h (struct LoanId):
LoanId is a struct now.
* checks/errors/borrowck/rust-bir.h (class AbstractExpr): Use
new API, as we are getting a LoanId and not a loan itself.
Signed-off-by: Kushal Pal <kushalpal109@gmail.com>
gcc/rust/ChangeLog:
* checks/errors/borrowck/rust-bir-builder-internal.h: Use
FreeRegions instead of making a temporary vector of FreeRegion.
* checks/errors/borrowck/rust-bir-builder.h: Likewise.
* checks/errors/borrowck/rust-bir-fact-collector.h (class FactCollector):
Likewise.
(points): Likewise.
* checks/errors/borrowck/rust-bir-free-region.h: Remove obsolete
set_from() helpers, add push_back().
* checks/errors/borrowck/rust-bir-place.h: Use FreeRegions
instead of making a temporary vector of Origin.
* typecheck/rust-tyty-variance-analysis-private.h: Change type
of `regions`.
* typecheck/rust-tyty-variance-analysis.cc (CrateCtx::query_type_regions):
Use new type.
(GenericTyPerCrateCtx::query_generic_variance): Likewise.
(TyVisitorCtx::add_constraints_from_generic_args): Likewise.
(FieldVisitorCtx::add_constraints_from_region): Likewise.
(FieldVisitorCtx::add_constrints_from_param): Likewise.
* typecheck/rust-tyty-variance-analysis.h: Likewise.
Signed-off-by: Kushal Pal <kushalpal109@gmail.com>
gcc/rust/ChangeLog:
* checks/errors/borrowck/rust-bir-builder-internal.h: Use
STATIC_FREE_REGION, use value of FreeRegion for origin.
* checks/errors/borrowck/rust-bir-builder.h: Use free region
value.
* checks/errors/borrowck/rust-bir-dump.cc (Dump::visit_scope):
Likewise.
* checks/errors/borrowck/rust-bir-fact-collector.h (points):
Likewise.
* checks/errors/borrowck/rust-bir-free-region.h (struct FreeRegion):
Make FreeRegion a struct.
* checks/errors/borrowck/rust-bir-place.h: Use FreeRegion
instead of Origin in PlaceDB.
* typecheck/rust-tyty-variance-analysis.cc (FieldVisitorCtx::add_constraints_from_region):
Use value of FreeRegion for origin.
(FieldVisitorCtx::add_constrints_from_param): Likewise.
(Term::make_transform): Likewise.
Signed-off-by: Kushal Pal <kushalpal109@gmail.com>
gcc/rust/ChangeLog:
* checks/errors/borrowck/rust-bir-dump.cc (renumber_places):
Use value of PlaceId as index.
(Dump::visit_place): Likewise.
(Dump::visit_scope): Likewise.
(Dump::go): Refill `place_map` with for loop instead of
using std::iota().
* checks/errors/borrowck/rust-bir-fact-collector.h (points): Use
value as index.
* checks/errors/borrowck/rust-bir-place.h (struct PlaceId):
PlaceId is now a class holding a uint32_t value. Overloaded
comparision operators for easier comparision.
Signed-off-by: Kushal Pal <kushalpal109@gmail.com>
gcc/rust/ChangeLog:
* backend/rust-compile-asm.cc (CompileAsm::asm_build_expr):
Use's array type when constring string tree
(CompileAsm::asm_construct_string_tree):
Use's array type when constring string tree
gcc/rust/ChangeLog:
* backend/rust-compile-asm.cc (CompileAsm::asm_build_expr):
Add debug comment
(CompileAsm::asm_construct_outputs):
Perform lowering hir output operand to tree
gcc/rust/ChangeLog:
* backend/rust-compile-asm.cc (CompileAsm::asm_construct_outputs):
Lower the HIR to tree with CompileExpr
* backend/rust-compile-asm.h: Remove static from method
gcc/rust/ChangeLog:
* expand/rust-macro-builtins-asm.cc (parse_reg_operand):
Remove warnings
(parse_reg_operand_out): Remove warnings
(expand_inline_asm): New function for eventual expansion
(parse_asm): Use expand_inline_asm
gcc/testsuite/ChangeLog:
* rust/execute/torture/inline_asm_mov_x_5.rs: New test.
ChangeLog:
* .github/alpine_32bit_log_warnings: New file.
* .github/workflows/ccpp32alpine.yml: New file.
gcc/rust/ChangeLog:
* resolve/rust-ast-resolve.cc (NameResolution::go):
Fix warnings from const auto& to const auto
gcc/rust/ChangeLog:
* hir/tree/rust-hir.cc (Item::item_kind_string): New function.
* hir/tree/rust-hir.h: New function.
* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit):
Modify to check all arms in match expressions even if some of them
has errors.
* typecheck/rust-hir-type-check-pattern.cc (TypeCheckPattern::visit):
Add and fix check for path patterns.
gcc/testsuite/ChangeLog:
* rust/compile/issue-2324-2.rs: Fix error message.
* rust/compile/match9.rs: New test.
Signed-off-by: Raiki Tamura <tamaron1203@gmail.com>
This commit turns a few of the fields into `tl::optional<T>` and cleanups
the constructor with a couple default parameters. We can also reuse the
variable that we are `switch`ing on, instead of repeating the enum variants
each time.
Most importantly, the `FeatureGate` visitor now uses the `DefaultAstVisitor`
correctly, and will now visit nested items. This means that we have to
fix a bunch of the testsuite as some feature attributes were missing.
gcc/rust/ChangeLog:
* checks/errors/rust-feature.cc (Feature::create): Reuse variable,
remove now optional parameters from constructor.
* checks/errors/rust-feature.h: Cleanup class definition.
* checks/errors/rust-feature-gate.cc (FeatureGate::gate): Use optional.
* checks/errors/rust-feature-gate.h: Cleanup visitor implementation.
gcc/testsuite/ChangeLog:
* rust/compile/assume.rs: Add missing feature attribute.
* rust/compile/issue-1901.rs: Likewise.
* rust/compile/issue-1981.rs: Likewise.
* rust/compile/sizeof-stray-infer-var-bug.rs: Likewise.
* rust/compile/torture/intrinsics-8.rs: Likewise.
* rust/compile/torture/transmute-size-check-1.rs: Likewise.
* rust/compile/torture/transmute1.rs: Likewise.
* rust/compile/torture/uninit-intrinsic-1.rs: Likewise.
* rust/execute/torture/issue-1436.rs: Likewise.
* rust/execute/torture/issue-2583.rs: Likewise.
gcc/rust/ChangeLog:
* ast/rust-ast-full-decls.h (struct InlineAsmOperand):
Change to class
(class InlineAsmOperand): Change from struct
* hir/tree/rust-hir-full-decls.h (struct InlineAsmRegOrRegClass):
Removed from decl, used from AST
(struct AnonConst): new decl from rust-hir-expr.h
(class InlineAsmOperand): new decl from rust-hir-expr.h
Create a base Path class which is derived into two children classes for
regular paths and lang item paths. This allows it to hold either the
segments of a fully formed path, or the node ID of a lang-item path.
This is required in order to create these special paths
which do not have segments, and do not necessarily have a canonical
form - they only depend on where the item was defined.
gcc/rust/ChangeLog:
* ast/rust-ast-full-decls.h (class PathPattern): Rename PathPattern to...
(class Path): ...Path
* ast/rust-ast-collector.cc (TokenCollector::visit): Add required methods
for LangItemPath and RegularPath.
* ast/rust-ast-collector.h: Likewise.
* ast/rust-ast-visitor.cc (DefaultASTVisitor::visit): Likewise.
* ast/rust-ast-visitor.h: Likewise.
* ast/rust-path.cc (PathPattern::as_string): Likewise.
(RegularPath::as_string): Likewise.
(LangItemPath::as_string): Likewise.
(PathPattern::convert_to_simple_path): Likewise.
(RegularPath::convert_to_simple_path): Likewise.
(RegularPath::accept_vis): Likewise.
(LangItemPath::accept_vis): Likewise.
(PathInExpression::as_string): Likewise.
(QualifiedPathInExpression::as_string): Likewise.
* ast/rust-path.h (class PathPattern): Likewise.
(class Path): Likewise.
(class RegularPath): Likewise.
(class LangItemPath): Likewise.
(class PathInExpression): Likewise.
(class QualifiedPathInExpression): Likewise.
* ast/rust-pattern.h (class PathPattern): Likewise.
(class Path): Likewise.
* expand/rust-derive.h: Likewise.
* hir/rust-ast-lower-base.cc (ASTLoweringBase::visit): Likewise.
* hir/rust-ast-lower-base.h: Likewise.
* resolve/rust-ast-resolve-base.cc (ResolverBase::visit): Likewise.
* resolve/rust-ast-resolve-base.h: Likewise.
This method was used only for stripping PathPattern AST nodes during
`cfg-strip`, which seems like a misnomer and makes it a good candidate
for simplification.
gcc/rust/ChangeLog:
* ast/rust-path.h (class PathInExpression): Remove `remove_all_segments`
method, add a `marked_for_strip` flag instead.
gcc/rust/ChangeLog:
* checks/errors/borrowck/rust-borrow-checker-diagnostics.cc
(BorrowCheckerDiagnostics::report_move_errors): Specify
locations for code causing errors and related moves.
gcc/testsuite/ChangeLog:
* rust/borrowck/test_move.rs: Test rich-errors related to moves.
* rust/borrowck/test_move_conditional.rs: Likewise.
Signed-off-by: Kushal Pal <kushalpal109@gmail.com>
Mapped placeholder regions to their respective HIR nodes so we can fetch
locations during error reporting.
gcc/rust/ChangeLog:
* checks/errors/borrowck/rust-bir-builder.h: Map regions to
their respective HIR nodes.
* checks/errors/borrowck/rust-bir.h (struct Function):
Add unordered_map to maintain the mapping.
Signed-off-by: Kushal Pal <kushalpal109@gmail.com>
gcc/testsuite/ChangeLog:
* rust/borrowck/test_move.rs: Assigning `a` to `c` is the
correct way to test the behaviour.
Signed-off-by: Kushal Pal <kushalpal109@gmail.com>
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-pattern.cc:
Emit E0532 when trying to reference a Tuple or Struct variant
using a non Tuple or Struct pattern.
gcc/testsuite/ChangeLog:
* rust/compile/issue-2324-1.rs:
add test for E0532 with tuple enum variant
* rust/compile/issue-2324-2.rs:
add test for E0532 with struct enum variant
Signed-off-by: Liam Naddell <liam.naddell@mail.utoronto.ca>
On architectures where `size_t` is `unsigned int`, such as 32bit x86,
we encounter an issue with `PlaceId` and `FreeRegion` being aliases to
the same types. This poses an issue for overloading functions for these
two types, such as `push_subset` in that case. This commit renames one
of these `push_subset` functions to avoid the issue, but this should be
fixed with a newtype pattern for these two types.
gcc/rust/ChangeLog:
* checks/errors/borrowck/rust-bir-fact-collector.h (points): Rename
`push_subset(PlaceId, PlaceId)` to `push_subset_place(PlaceId, PlaceId)`
gcc/rust/ChangeLog:
* checks/errors/borrowck/rust-bir-builder.h: Cast size_t values to unsigned
long before printing.
* checks/errors/borrowck/rust-bir-fact-collector.h: Likewise.
gcc/rust/ChangeLog:
* expand/rust-expand-visitor.h:
remove auto keyword
* expand/rust-macro-builtins-helpers.cc:
allow for changing macro invoc types on eager expansions to
semicoloned macros
* expand/rust-macro-builtins-helpers.h:
add default semicoloned argument
* expand/rust-macro-builtins-include.cc:
allow for eager expansion for include and include_bytes
allow for parsing include invocations as items instead of
expressions, which allows invocations at global scope
* expand/rust-macro-expand.cc:
push Expr type for eager invocations
gcc/testsuite/ChangeLog:
* rust/compile/macros/builtin/include1.rs:
add basic include test at global scope
* rust/compile/macros/builtin/include2.rs:
add basic include test at local scope with expression
* rust/compile/macros/builtin/include3.rs:
add eager expansion test at global scope
* rust/compile/macros/builtin/include4.rs:
add eager expansion test at local scope with expression
* rust/compile/macros/builtin/include_bytes.rs:
add eager expansion test at global scope
* rust/compile/macros/builtin/include_rs:
supporting test file with dummy function
* rust/compile/macros/builtin/include_rs2:
supporting test file with dummy string
* rust/compile/macros/builtin/include_str.rs:
add eager expansion test at global scope
* rust/execute/torture/builtin_macro_include_bytes.rs:
clean up old test logic, add permutations for eager expansion
* rust/execute/torture/builtin_macro_include_str.rs:
add eager expansion permutations
Save LIBS around calls to AC_SEARCH_LIBS to avoid clobbering $LIBS.
ChangeLog:
* configure: Regenerate.
* configure.ac: Save LIBS around calls to AC_SEARCH_LIBS.
Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
Reviewed-by: Thomas Schwinge <tschwinge@baylibre.com>
Tested-by: Thomas Schwinge <tschwinge@baylibre.com>
gcc/rust/ChangeLog:
* checks/errors/borrowck/rust-bir-builder-internal.h:
Use `make_*` functions to create BIR::Statements.
* checks/errors/borrowck/rust-bir.h: Make a complete constructor
and introduce `make_*` functions to create various
BIR::Statements.
Signed-off-by: Kushal Pal <kushalpal109@gmail.com>
gcc/rust/ChangeLog:
* checks/errors/borrowck/rust-borrow-checker-diagnostics.cc
(BorrowCheckerDiagnostics::report_loan_errors): Add label to
where the borrow occurs and where the invalid access occurs.
(BorrowCheckerDiagnostics::get_statement):
Fetch BIR::Statement from Polonius::Point
(BorrowCheckerDiagnostics::get_loan):
Fetch BIR::Loan from Polonius::Loan
* checks/errors/borrowck/rust-borrow-checker-diagnostics.h:
Function definition of helpers.
gcc/testsuite/ChangeLog:
* rust/borrowck/reference.rs: Test rich errors for
borrow-checker.
* rust/borrowck/return_ref_to_local.rs: Likewise.
* rust/borrowck/tmp.rs: Likewise.
* rust/borrowck/use_while_mut.rs: Likewise.
* rust/borrowck/use_while_mut_fr.rs: Likewise.
* rust/borrowck/well_formed_function_inputs.rs: Likewise.
Signed-off-by: Kushal Pal <kushalpal109@gmail.com>
This commit adds location_t to BIR::Statement where type is RETURN.
gcc/rust/ChangeLog:
* checks/errors/borrowck/rust-bir-builder-expr-stmt.cc (ExprStmtBuilder::visit):
Add location parameter.
* checks/errors/borrowck/rust-bir-builder.h: Likewise.
* checks/errors/borrowck/rust-bir-builder-internal.h: Add helper
function for pushing return statements.
* checks/errors/borrowck/rust-bir.h: Remove `expr` parameter as
it is only needed for ASSIGNMENT statements, for which we
already have a constructor.
Signed-off-by: Kushal Pal <kushalpal109@gmail.com>
This commit adds location_t to BIR::Loan, this location will point to
location is source code where the borrow occured, this information will
be useful for reporting borrow-checking errors.
gcc/rust/ChangeLog:
* checks/errors/borrowck/rust-bir-builder-internal.h:
Fill location for loan.
* checks/errors/borrowck/rust-bir-place.h (struct Loan):
Add location field.
Signed-off-by: Kushal Pal <kushalpal109@gmail.com>
This commit adds location_t to BIR::Statement where type is ASSIGNMENT
this information will be later used for reporting borrow-checking
errors.
gcc/rust/ChangeLog:
* checks/errors/borrowck/rust-bir-builder-expr-stmt.cc
(ExprStmtBuilder::visit): Added location parameter.
* checks/errors/borrowck/rust-bir-builder-internal.h: Likewise.
* checks/errors/borrowck/rust-bir-builder-lazyboolexpr.h:
Likewise.
* checks/errors/borrowck/rust-bir-builder-pattern.h: Likewise.
* checks/errors/borrowck/rust-bir-builder.h: Likewise.
* checks/errors/borrowck/rust-bir.h: Likewise.
Signed-off-by: Kushal Pal <kushalpal109@gmail.com>
gcc/rust/ChangeLog:
* hir/rust-ast-lower-expr.cc (from_operand):
Set up the lowering for operand
(ASTLoweringExpr::visit): Likewise
* hir/tree/rust-hir-expr.h (struct InlineAsmRegOrRegClass):
Not necessary, kept from ast
(struct AnonConst): Set up lowering for operand
(class InlineAsmOperand): Likewise, add getters
gcc/rust/ChangeLog:
* checks/errors/borrowck/polonius/rust-polonius.h (struct FullPoint):
Added comments and made extraction of statement more verbose for
better understanding.
* checks/errors/borrowck/ffi-polonius/src/lib.rs: Likewise.
Signed-off-by: Kushal Pal <kushalpal109@gmail.com>
gcc/rust/ChangeLog:
* ast/rust-expr.h (struct InlineAsmOperand): changed to class
(class InlineAsmOperand): Have appropriate constructor,
and getter
* expand/rust-macro-builtins-asm.cc (parse_reg_operand):
Use the new implement constructors and new control flow.
(parse_reg_operand_in): Likewise
(parse_reg_operand_out): Likewise
(parse_reg_operand_inout): Likewise
(parse_reg_operand_const): Likewise
gcc/rust/ChangeLog:
* checks/errors/borrowck/polonius/rust-polonius.h (struct FullPoint):
This is the correct way of extracting the required bits.
Signed-off-by: Kushal Pal <kushalpal109@gmail.com>
This will allow us to revert our dependency on extern types, which would
help our godbolt build as well as our various builders.
gcc/rust/ChangeLog:
* checks/errors/borrowck/ffi-polonius/src/gccrs_ffi.rs: Remove extern
type feature.
* checks/errors/borrowck/ffi-polonius/src/lib.rs: Define FFIVector
per the nomicon's recommendation
https://doc.rust-lang.org/nomicon/ffi.html#representing-opaque-structs
gcc/rust/ChangeLog:
* ast/rust-ast.cc:
Fix Attribute constructors to copy inner_attribute
* checks/errors/rust-unsafe-checker.cc:
Add pass for #[may_dangle] in safe impl's
* hir/rust-ast-lower-item.cc:
Add support for unsafe impl's
* hir/rust-ast-lower-type.cc:
Lower attributes in impl's from AST to HIR
* hir/rust-hir-dump.cc:
Change single attribute to AttrVec
* hir/tree/rust-hir-item.h:
Add unsafe support to Impl blocks in HIR
* hir/tree/rust-hir.cc:
Change single attribute to AttrVec
* hir/tree/rust-hir.h:
Add has/get_outer_attribute to GenericParam
gcc/testsuite/ChangeLog:
* rust/compile/issue-3045-1.rs:
Add test for #[may_dangle] Generic Type triggering error
* rust/compile/issue-3045-2.rs:
Add test for #[may_dangle] Lifetime triggering error
Signed-off-by: Liam Naddell <liam.naddell@mail.utoronto.ca>
gcc/testsuite/ChangeLog:
* rust/rustc/README.md: information about
rustc external directory.
* rust/rustc/rustc.exp: New test.
Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
gcc/rust/ChangeLog:
* expand/rust-cfg-strip.cc:
Strip struct expr fields and strip fields in struct definition
* expand/rust-cfg-strip.h:
Signatures for new function maybe_strip_struct_expr_fields
gcc/testsuite/ChangeLog:
* rust/compile/macro-issue2983_2984.rs:
Add test to check for correct stripped fields
Signed-off-by: Antonio Gomes <antoniospg100@gmail.com>
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-type.cc (TypeCheckType::visit):
Add rich error message and error code similiar to rustc with
associaed type and trait name
gcc/testsuite/ChangeLog:
* rust/compile/unknown-associated-item.rs: New test.
Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
gcc/rust/ChangeLog:
* expand/rust-expand-visitor.cc:
Fix ICE caused by unique_ptr UB and buggy iterator use
gcc/testsuite/ChangeLog:
* rust/compile/issue-2987.rs:
Add test for deriving Clone and Copy at the same time
Signed-off-by: Liam Naddell <liam.naddell@mail.utoronto.ca>
Change the assert of (expr != nullptr) to
(this->expr != nullptr) because we assigned (std::move(expr)) to
this->expr, no need to assert expr
gcc/rust/ChangeLog:
* ast/rust-expr.h (struct AnonConst):
Change assertion of constructor
(struct InlineAsmOperand):
Change assertion of constructor
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-expr.cc:
Fix ICE caused by not finding enum variant by adding new error
message
gcc/testsuite/ChangeLog:
* rust/compile/issue-3046.rs:
Add test for new error message
Signed-off-by: Liam Naddell <liam.naddell@mail.utoronto.ca>
The CI failed to compile some recent code that requires a nightly
feature. This change allows the CI to use a nightly compiler instead.
ChangeLog:
* .github/workflows/bootstrap.yml: Install nightly rustc.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
gcc/rust/ChangeLog:
* hir/tree/rust-hir-expr.h: Add new get_operator_str method in
ArithmeticOrLogicalExpr and CompoundAssignmentExpr
* hir/tree/rust-hir.cc: Likewise
* typecheck/rust-hir-type-check-expr.cc: Improve error message for
operator expressions to display the correct operator symbol
gcc/testsuite/ChangeLog:
* rust/compile/shadow1.rs: Fix test for new error message
Signed-off-by: Antonio Gomes <antoniospg100@gmail.com>
gcc/rust/ChangeLog:
* Make-lang.in: Compile new file.
* checks/errors/borrowck/rust-borrow-checker.cc (BorrowChecker::go):
Use new class to report errors.
* checks/errors/borrowck/rust-borrow-checker-diagnostics.cc: New file.
* checks/errors/borrowck/rust-borrow-checker-diagnostics.h:
New file, adds new class.
Signed-off-by: Kushal Pal <kushalpal109@gmail.com>
ChangeLog:
* .github/workflows/ccpp.yml: Switch to nightly version of rustc
to use unstable features, namely extern types for FFI.
gcc/rust/ChangeLog:
* Make-lang.in: Compile new file, rust-polonius.cc
* checks/errors/borrowck/ffi-polonius/src/gccrs_ffi.rs: Opaque
type to represent FFIVector from C++.
* checks/errors/borrowck/ffi-polonius/src/gccrs_ffi_generated.rs:
Change types of fields in Output.
* checks/errors/borrowck/ffi-polonius/src/lib.rs: Added helper
functions to contruct Polonius output on C++ side,
used helpers to contruct Polonius output on C++ side.
* checks/errors/borrowck/polonius/rust-polonius-ffi.h (make_vector):
FFIVector is a wrapper around std::vector for transfering data
from Rust to C++.
(struct Output): Use pointers to FFIVector instead of bool to
store Polonius output data.
* checks/errors/borrowck/polonius/rust-polonius.h (FFIVector__new):
Helper function.
(FFIVector__new_vec_pair): Likewise.
(FFIVector__new_vec_triple): Likewise.
(FFIVector__push): Likewise.
(FFIVector__push_vec_pair): Likewise.
(FFIVector__push_vec_triple): Likewise.
* checks/errors/borrowck/rust-borrow-checker.cc (BorrowChecker::go):
Convert FFIVector to std::vector representation for easier
navigation.
* checks/errors/borrowck/polonius/rust-polonius.cc: New file,
implementation of helper functions.
Signed-off-by: Kushal Pal <kushalpal109@gmail.com>
The visitor was still using the as_string() method.
gcc/rust/ChangeLog:
* hir/rust-hir-dump.cc (Dump::do_matcharm): New.
(Dump::do_matchcase): New.
(Dump::visit(MatchExpr)): Adjust, don't use as_string.
* hir/rust-hir-dump.h (Dump::do_matcharm, Dump::do_matchcase): New.
Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
gcc/rust/ChangeLog:
* expand/rust-macro-builtins-asm.cc (parse_clobber_abi):
added comments
(parse_options): Likewise
(parse_asm_arg): Likewise
(parse_asm): Likewise
* expand/rust-macro-builtins-asm.h: Likewise
gcc/testsuite/ChangeLog:
* rust/compile/inline_asm_illegal_options.rs: new test
* rust/compile/inline_asm_illegal_operands.rs: New test.
This is expected to fail but we couldn't resolve parse_expr()'s
general functionality yet
Signed-off-by: badumbatish <tanghocle456@gmail.com>
This is quite a rough fix (like a lot of the macro expansion code...) but
it allows built-in macros to be treated as statements. I *think* asm!()
might be the only one where it really matters, but also doing something
like
{
line!();
}
will now work, whereas before the macro invocation would not get expanded
properly and would be ignored.
gcc/rust/ChangeLog:
* ast/rust-ast-fragment.h: Pass `is_semicolon` information to builtin
macro transcribers.
* ast/rust-macro.h: Pass semicolon information to transcriber..
* expand/rust-macro-builtins-asm.cc (MacroBuiltin::asm_handler): Likewise.
(parse_asm): Likewise.
* expand/rust-macro-builtins-asm.h (parse_asm): Likewise.
* expand/rust-macro-builtins-format-args.cc (MacroBuiltin::format_args_handler): Likewise.
* expand/rust-macro-builtins-include.cc (MacroBuiltin::include_bytes_handler): Likewise.
(MacroBuiltin::include_str_handler): Likewise.
(MacroBuiltin::include_handler): Likewise.
* expand/rust-macro-builtins-location.cc (MacroBuiltin::file_handler): Likewise.
(MacroBuiltin::column_handler): Likewise.
(MacroBuiltin::line_handler): Likewise.
* expand/rust-macro-builtins-log-debug.cc (MacroBuiltin::assert_handler): Likewise.
* expand/rust-macro-builtins-utility.cc (MacroBuiltin::compile_error_handler): Likewise.
(MacroBuiltin::concat_handler): Likewise.
(MacroBuiltin::env_handler): Likewise.
(MacroBuiltin::cfg_handler): Likewise.
(MacroBuiltin::stringify_handler): Likewise.
* expand/rust-macro-builtins.cc (format_args_maker): Likewise.
(inline_asm_maker): Likewise.
(MacroBuiltin::sorry): Likewise.
(MacroBuiltin::proc_macro_builtin): Likewise.
* expand/rust-macro-builtins.h: Likewise.
* expand/rust-macro-expand.cc (MacroExpander::expand_decl_macro): Likewise.
(MacroExpander::expand_invoc): Likewise.
* ast/rust-ast-visitor.cc (DefaultASTVisitor::visit): Remove rust_unreachable.
* ast/rust-ast.cc (InlineAsm::accept_vis): Likewise.
* hir/tree/rust-hir.cc (InlineAsm::accept_vis): Likewise.
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-item.cc (TypeCheckItem::visit): Check for ?Trait in visitor
gcc/testsuite/ChangeLog:
* rust/compile/issue-2725.rs: New test.
Signed-off-by: Dave Evans <dave@dmetwo.org>
gcc/rust/ChangeLog:
* expand/rust-macro-builtins-asm.cc (parse_reg_operand):
Update parser to parse strings in the first stage
(parse_label): not needed right now
gcc/testsuite/ChangeLog:
* rust/compile/inline_asm_faulty_clobber.rs: compress
the test
* rust/compile/inline_asm_nop.rs: compress
the test
* rust/compile/inline_asm_faulty_clobber_1.rs: Removed.
* rust/compile/inline_asm_faulty_clobber_2.rs: Removed.
* rust/compile/inline_asm_nop_2.rs: Removed.
gcc/rust/ChangeLog:
* expand/rust-macro-builtins-asm.cc (parse_reg):
Working towards parse_reg and parse_reg_operand
(parse_reg_operand):
Working towards parse_reg and parse_reg_operand
(parse_asm_arg):
Add todo about errors
* expand/rust-macro-builtins-asm.h (parse_global_asm):
remove dead code.
(parse_nonglobal_asm):
remove dead code.
gcc/rust/ChangeLog:
* expand/rust-macro-builtins-asm.cc (parseAsmArg):
Renamed parseAsmArg to conform to other function names
(parse_asm_arg): Likewise.
(parse_asm): Likewise.
* expand/rust-macro-builtins-asm.h (parseAsmArg): Likewise.
(parse_asm_arg): Likewise.
Safegaurd InlineAsm's clone_expr_... with unreachable since
we would never use them.
gcc/rust/ChangeLog:
* ast/rust-expr.h:
Safegaurd InlineAsm's clone_expr_... with unreachable.
This is without any mutually exclusive options checked, or
any relationship with reg_operands. Very primitive.
gcc/rust/ChangeLog:
* ast/rust-expr.h: parsing of options(...)
* expand/rust-macro-builtins-asm.cc (check_and_set):
likewise.
(parse_options): likewise.
(parseAsmArg): likewise.
* expand/rust-macro-builtins-asm.h (check_and_set):
likewise.
gcc/testsuite/ChangeLog:
* rust/compile/inline_asm_legal_options.rs: New test.
gcc/testsuite/ChangeLog:
* rust/compile/inline_asm_faulty_clobber.rs: New test.
* rust/compile/inline_asm_faulty_clobber_1.rs: New test.
* rust/compile/inline_asm_faulty_clobber_2.rs: New test.
Finish up on parse_option, formatted parse_clobber_abi
gcc/rust/ChangeLog:
* expand/rust-macro-builtins-asm.cc (parse_clobber_abi): format
(check_and_set): helper function, is try_set_option equivalent
(parse_options): new function
* expand/rust-macro-builtins-asm.h (enum InlineAsmOptions):
removed
(check_and_set): decl of helper function
Add a few test to check the exclusive range pattern feature. This feature
is experimental and shall not be enabled in stable rust.
gcc/testsuite/ChangeLog:
* rust/compile/exclusive_range_pattern.rs: New test.
* rust/compile/exclusive_range_pattern_feature_gate.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
This syntax is experimental and shall be explicitely enabled in the crate
attributes as it cannot be used in stable rust.
gcc/rust/ChangeLog:
* checks/errors/rust-feature-gate.cc (FeatureGate::visit): Gate the
excluded pattern.
* checks/errors/rust-feature-gate.h: Update the function prototype
and delete two empty implementations in order to use default visitor
behavior.
* checks/errors/rust-feature.cc (Feature::create): Add the new
exclusive range pattern feature gate.
* checks/errors/rust-feature.h: Add new feature enum variant for
exclusive range patterns.
* parse/rust-parse-impl.h (Parser::parse_pattern_no_alt): Forward the
token location to the AST.
(Parser::parse_ident_leading_pattern): Likewise.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Exclusive range pattern were not handled by the parser as this an
experimental feature.
gcc/rust/ChangeLog:
* ast/rust-pattern.cc (tokenid_to_rangekind): Add a new function to
get a range kind from the current token type.
(RangePattern::as_string): Change the string representation for range
pattern in order to handle excluded ranges.
* ast/rust-pattern.h (enum class): Add new enum class to differentiate
range kinds.
(tokenid_to_rangekind): New prototype for a function that converts a
token id to it's corresponding range kind.
(class RangePattern): Change the class to accept a range kind instead
of an ellipsis boolean.
* hir/rust-ast-lower-pattern.cc (ASTLoweringPattern::visit): Abort
when an excluded pattern has been found as we do not handle their
lowering yet.
* parse/rust-parse-impl.h (Parser::parse_literal_or_range_pattern):
Parse excluded range patterns.
(Parser::parse_pattern_no_alt): Likewise.
(Parser::parse_ident_leading_pattern): Likewise.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add a test for the feature gate, as well as some test to ensure the raw
keyword stays weak. Also add some tests to check whether the raw_ref_op
syntax is parsed correctly.
gcc/testsuite/ChangeLog:
* rust/compile/not_raw_ref_op.rs: New test.
* rust/compile/raw_ref_op.rs: New test.
* rust/compile/raw_ref_op_feature_gate.rs: New test.
* rust/compile/raw_ref_op_invalid.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Raw ref operators are still experimental and shall not slip within
stable rust, they should therefore be feature gated.
gcc/rust/ChangeLog:
* checks/errors/rust-feature-gate.cc (FeatureGate::visit): Gate raw
borrow.
* checks/errors/rust-feature-gate.h: Update function prototype.
* checks/errors/rust-feature.cc: Add raw_ref_op gate.
* checks/errors/rust-feature.h: Likewise.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
We do not handle those kind of references yet, we shall not let them
pass as a regular reference.
gcc/rust/ChangeLog:
* ast/rust-expr.h: Add a getter for mutability.
* hir/rust-ast-lower-expr.cc (ASTLoweringExpr::visit): Panic when a
raw reference is met.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
The raw ref operator is an unstable feature required to obtain a pointer
to unaligned adresses (mainly unaligned struct fields) without UB.
gcc/rust/ChangeLog:
* ast/rust-ast-builder.cc (Builder::ref): Adapt constructor to the new
API.
* ast/rust-ast-collector.cc (TokenCollector::visit): Emit a raw weak
keyword when required.
* ast/rust-ast.cc (BorrowExpr::as_string): Change as_string
representation to handle raw ref operator.
* ast/rust-expr.h (class BorrowExpr): Add raw discriminant.
* expand/rust-macro-builtins-include.cc: Adapt constructor to the new
API.
* parse/rust-parse-impl.h: Handle the raw weak keyword.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
We want to prevent regressions on struct expr field attribute parsing.
gcc/testsuite/ChangeLog:
* rust/compile/struct_expr_field_attributes.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Struct fields can have outer attributes on their field for various
purpose, this behavior should be reflected upon struct expr fields.
gcc/rust/ChangeLog:
* ast/rust-ast-collector.cc (TokenCollector::visit): Output field
attributes.
* ast/rust-expr.h (class StructExprField): Add outer attributes member.
* parse/rust-parse-impl.h (Parser::parse_struct_expr_field): Parse
outer attributes and store them in the appropriate AST node.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
ChangeLog:
* Makefile.tpl: Add CRAB1_LIBS variable.
* Makefile.in: Regenerate.
* configure: Regenerate.
* configure.ac: Check if -ldl and -lpthread are needed, and if so, add
them to CRAB1_LIBS.
gcc/rust/ChangeLog:
* Make-lang.in: Remove overazealous LIBS = -ldl -lpthread line, link
crab1 against CRAB1_LIBS.
First test checks the may_dangle outer atttribute on generic params can
be parsed. The second one tests whether may_dangle attributes are
correctly feature gated.
gcc/testsuite/ChangeLog:
* rust/compile/dropck_eyepatch_feature_gate.rs: New test.
* rust/compile/may_dangle.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add a new feature gate for may_dangle generic param outer attributes.
gcc/rust/ChangeLog:
* checks/errors/rust-feature-gate.cc: Visit and gate may_dangle
attributes.
* checks/errors/rust-feature-gate.h: Update visit function prototype
and add a new member function to check on a set of attributes whether
one is may_dangle.
* checks/errors/rust-feature.cc (Feature::create): Add new
dropck_eyepatch feature.
* checks/errors/rust-feature.h: Likewise.
* util/rust-attribute-values.h: Add new may_dangle attribute value.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Generic parameter parsing failed when an outer attribute was used on it.
gcc/rust/ChangeLog:
* parse/rust-parse-impl.h (Parser::parse_generic_param): Change token
reference to be the last token after all outer attributes have been
parsed.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add a new test to prevent regressions on the box syntax as well as its
feature gate.
gcc/testsuite/ChangeLog:
* rust/compile/box_syntax.rs: New test.
* rust/compile/box_syntax_feature_gate.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
The box syntax is experimental even though it is used in the standard
library. It should be feature gated to prevent anyone from using it in
stable rust.
gcc/rust/ChangeLog:
* checks/errors/rust-feature-gate.cc (FeatureGate::visit): Allow
visitor recursion in functions. Also add the gate for the box syntax.
* checks/errors/rust-feature-gate.h: Remove several recursion fences
in the feature gate visitor.
* checks/errors/rust-feature.cc (Feature::create): Add a new feature.
(Feature::as_name): Likewise.
* checks/errors/rust-feature.h: Add box_syntax gate.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Wrap the function's return type within an optional.
gcc/rust/ChangeLog:
* metadata/rust-export-metadata.cc (ExportContext::emit_trait):
Adapt call site to the new return type.
(ExportContext::emit_function): Likewise.
(ExportContext::emit_macro): Likewise.
* util/rust-hir-map.cc (Mappings::lookup_ast_item): Change the
function's return type.
* util/rust-hir-map.h: Update the function's prototype.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Wrap the return type within an optional.
gcc/rust/ChangeLog:
* checks/errors/privacy/rust-privacy-reporter.cc: Change call site
to accomodate new return type.
* checks/errors/privacy/rust-pub-restricted-visitor.cc: Likewise.
* util/rust-hir-map.cc (Mappings::lookup_visibility): Change the
function's return type.
* util/rust-hir-map.h: Update the function's prototype.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Wrap the function's return type within an optional and remove the out
reference argument.
gcc/rust/ChangeLog:
* expand/rust-macro-expand.cc (MacroExpander::expand_invoc): Adapt
the function call to match its new prototype.
* resolve/rust-early-name-resolver-2.0.cc (Early::insert_once):
Likewise.
(Early::visit): Likewise.
* resolve/rust-early-name-resolver.cc (EarlyNameResolver::visit):
Likewise.
* util/rust-hir-map.cc (Mappings::lookup_macro_invocation): Change the
function's return type.
* util/rust-hir-map.h: Update the function's prototype.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Wrap the function's return type within an optional.
gcc/rust/ChangeLog:
* resolve/rust-early-name-resolver-2.0.cc (Early::insert_once): Change
call site to accomodate the new return type.
(Early::visit): Likewise.
* resolve/rust-early-name-resolver.cc (EarlyNameResolver::visit):
Likewise.
* resolve/rust-toplevel-name-resolver-2.0.cc (TopLevel::visit):
Likewise.
* util/rust-hir-map.cc (Mappings::lookup_macro_def): Change the
function's return type.
* util/rust-hir-map.h: Update the function's prototype.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Change the function's return type to wrap it within an optional.
gcc/rust/ChangeLog:
* backend/rust-compile-base.cc: Change call site to accomodate new
return type.
* backend/rust-compile-base.h: Change parameter to use a reference.
* backend/rust-compile-extern.h: Likewise.
* backend/rust-compile-implitem.cc (CompileTraitItem::visit):
Change call site for new return type.
* backend/rust-compile-item.cc (CompileItem::visit): Likewise.
* resolve/rust-ast-resolve-type.cc (ResolveTypeToCanonicalPath::visit):
Likewise.
* typecheck/rust-hir-type-check-enumitem.cc (TypeCheckEnumItem::visit):
Likewise.
* typecheck/rust-hir-type-check-implitem.cc (TypeCheckImplItem::visit):
Likewise.
* typecheck/rust-hir-type-check-item.cc (TypeCheckItem::visit):
Likewise.
* typecheck/rust-hir-type-check.cc (TraitItemReference::get_type_from_fn):
Likewise.
* util/rust-hir-map.h: Update the function's prototype and change the
function's return type.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Wrap the function's return type within an optional in order to
differentiate between a null pointer and a missing value.
gcc/rust/ChangeLog:
* util/rust-hir-map.cc (Mappings::insert_hir_pattern): Change call site
in order to accomodate new return type.
(Mappings::lookup_hir_pattern): Change the function's return type.
* util/rust-hir-map.h: Update the function's prototype.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Wrap the function's return type within an optional to differentiate
between a null pointer and a missing value.
gcc/rust/ChangeLog:
* util/rust-hir-map.cc (Mappings::insert_hir_struct_field): Change
call site to accomodate new return type.
(Mappings::lookup_hir_struct_field): Change the function's return
type.
* util/rust-hir-map.h: Update the function's prototype.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Wrap the function's return type within an optional in order to
differentiate null pointers from missing value.
gcc/rust/ChangeLog:
* util/rust-hir-map.cc (Mappings::insert_hir_self_param): Adapt call
site to new return type.
(Mappings::lookup_hir_self_param): Change the function's return type.
* util/rust-hir-map.h: Update the function's prototype.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Wrap the function's return type within an optional to differentiate
between a null ppointer and a missing value.
gcc/rust/ChangeLog:
* util/rust-hir-map.cc (Mappings::insert_hir_param): Change call site
to accomodate new return type.
(Mappings::lookup_hir_param): Change the function's return type.
* util/rust-hir-map.h: Updat ethe function's prototype.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Wrap the function's return type within an optional in order to
differentiate missing values from null pointers.
gcc/rust/ChangeLog:
* util/rust-hir-map.cc (Mappings::insert_hir_stmt): Change call site
to accomodate new return type.
(Mappings::lookup_hir_stmt): Change the function's return type.
(Mappings::resolve_nodeid_to_stmt): Adapt call site to new return type.
* util/rust-hir-map.h: Update the function's prototype.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Wrap the function's return type with an optional in order to tell
appart a null pointer from a missing value.
gcc/rust/ChangeLog:
* util/rust-hir-map.cc (Mappings::insert_hir_type): Change call site
to accomodate the new return type.
(Mappings::lookup_hir_type): Change the function's return type.
* util/rust-hir-map.h: Update the function's prototype.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Wrap the function's return type with an optional.
gcc/rust/ChangeLog:
* util/rust-hir-map.cc (Mappings::insert_hir_generic_param): Change
call site to accomodate the new return type.
(Mappings::lookup_hir_generic_param): Wrap the function's return type
with an optional.
* util/rust-hir-map.h: Update the function's prototype.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Make the function's return type optional in order to differentiate
between null pointers and missing value.
gcc/rust/ChangeLog:
* util/rust-hir-map.cc (Mappings::insert_hir_path_expr_seg): Change
call site to accomodate the new return type.
(Mappings::lookup_hir_path_expr_seg): Wrap the function's return type
with an optional.
* util/rust-hir-map.h: Update the function's prototype.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Wrap the function's return type with an optional in order to
differentiate missing values from null pointers.
gcc/rust/ChangeLog:
* backend/rust-mangle-v0.cc (v0_path): Adapt call site to new returned
type.
* util/rust-hir-map.cc (Mappings::lookup_hir_expr): Change the
function's return type.
* util/rust-hir-map.h: Update the function's prototype.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Wrap the return type within an optional. Now return the parent id within
a pair instead of taking an out reference.
gcc/rust/ChangeLog:
* backend/rust-compile-item.cc (CompileItem::visit): Change call site
to accept new return type.
* backend/rust-compile-resolve-path.cc (HIRCompileBase::query_compile):
Likewise.
* backend/rust-mangle-v0.cc (v0_path): Likewise.
* checks/errors/rust-unsafe-checker.cc (UnsafeChecker::visit):
Likewise.
* checks/lints/rust-lint-marklive.cc (MarkLive::go): Likewise.
(MarkLive::visit): Likewise.
* typecheck/rust-type-util.cc (query_type): Likewise.
* util/rust-hir-map.cc (Mappings::insert_hir_implitem): Likewise.
(Mappings::lookup_hir_implitem): Change return type.
* util/rust-hir-map.h: Update the function's prototype.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Wrap the return type into an optional.
gcc/rust/ChangeLog:
* checks/errors/privacy/rust-visibility-resolver.cc: Update function
call to match the new return type.
* typecheck/rust-hir-type-check-path.cc (TypeCheckExpr::resolve_root_path):
Likewise.
* typecheck/rust-hir-type-check-type.cc (TypeCheckType::resolve_root_path):
Likewise.
* util/rust-hir-map.cc (Mappings::insert_module): Likewise.
(Mappings::lookup_module): Change the function's return type.
* util/rust-hir-map.h: Update the function's prototype.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Wrap the return type with an optional and make the return type a pair
with the parent hid.
gcc/rust/ChangeLog:
* backend/rust-compile-resolve-path.cc (HIRCompileBase::query_compile):
Adapt code around new return type.
* checks/errors/rust-const-checker.cc (ConstChecker::check_function_call):
Likewise.
* checks/errors/rust-unsafe-checker.cc (UnsafeChecker::check_use_of_static):
Likewise.
(UnsafeChecker::check_function_call): Likewise.
* typecheck/rust-type-util.cc (query_type): Likewise.
* util/rust-hir-map.cc (Mappings::insert_hir_extern_item): Likewise.
(Mappings::lookup_hir_extern_item): Change return type.
* util/rust-hir-map.h: Update the function's prototype.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Make the API more convenient by changing the function's return type. We
can now differentiate between a stored null pointer and a missing value.
gcc/rust/ChangeLog:
* util/rust-hir-map.cc (Mappings::insert_defid_mapping): Adapt call
to new return type.
(Mappings::insert_local_defid_mapping): Likewise.
(Mappings::lookup_local_defid): Change return type to wrap it with an
optional.
* util/rust-hir-map.h: Update the function's prototype.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Change their return type to a const reference in order to avoid copies
when possible. Also wrap this new return type into an optional.
gcc/rust/ChangeLog:
* checks/errors/borrowck/rust-borrow-checker.cc (BorrowChecker::go):
Adapt the code to the new return types.
* resolve/rust-ast-resolve.cc (NameResolution::go): Likewise.
* util/rust-hir-map.cc (Mappings::get_crate_name): Change return type
to const string reference optional.
(Mappings::get_current_crate_name): Likewise.
* util/rust-hir-map.h: Update function prototypes.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Change the function's return type to an optional.
gcc/rust/ChangeLog:
* resolve/rust-ast-resolve-toplevel.h: Adapt the code to the new
return type.
* rust-session-manager.cc (Session::load_extern_crate): Likewise.
* util/rust-hir-map.cc (Mappings::crate_num_to_nodeid): Change the
return type.
* util/rust-hir-map.h: Update the function's prototype.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Change the function's return type to use an optional.
gcc/rust/ChangeLog:
* resolve/rust-ast-resolve-toplevel.h: Adapt the code to the new
return type.
* resolve/rust-toplevel-name-resolver-2.0.cc (TopLevel::visit):
Likewise.
* rust-session-manager.cc (Session::load_extern_crate): Likewise.
* util/rust-hir-map.cc (Mappings::lookup_crate_name): Change the return
type to an optional.
* util/rust-hir-map.h: Update the function's prototype.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Change the return type to an optional.
gcc/rust/ChangeLog:
* typecheck/rust-type-util.cc (query_type): Adapt code to accomodate
the new return type.
* util/rust-hir-map.cc (Mappings::lookup_impl_block_type): Change
the function's return type and remove the out pointer argument.
* util/rust-hir-map.h: Update the function's prototype.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Change the return type to an optiona. This allows to differentiate
between missing hir impl block and null pointers.
gcc/rust/ChangeLog:
* typecheck/rust-type-util.cc (query_type): Change call to the function
in order to accomodate the new return type.
* util/rust-hir-map.cc (Mappings::lookup_hir_impl_block): Change the
function's return type to an optional.
* util/rust-hir-map.h: Update the function's prototype.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Change the return type to an optional in order to easily differentiate
between a null pointer and an missing value.
gcc/rust/ChangeLog:
* checks/errors/rust-unsafe-checker.cc (UnsafeChecker::check_function_call):
Adapt function call to new return type.
* typecheck/rust-type-util.cc (query_type): Likewise.
* util/rust-hir-map.cc (Mappings::insert_hir_extern_block): Likewise.
(Mappings::lookup_hir_extern_block): Change return type to an optional.
* util/rust-hir-map.h: Update the function's prototype.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Change the return type to an optional instead of returning a null
pointer. This allows easier tracking of rogue null pointers in the
map. This commit also fixes a bug in trait associated function mangling,
the function was using an already invalidated pointer.
gcc/rust/ChangeLog:
* backend/rust-compile-resolve-path.cc (HIRCompileBase::query_compile):
Adapt return type to new optional.
* backend/rust-mangle-v0.cc (v0_function_path): Change prototype to use
the generic arguments vector instead of the whole HIR function.
(v0_path): Fix a bug with a null pointer being used to create the
trait function mangling.
* util/rust-hir-map.cc (Mappings::insert_hir_trait_item): Adapt code
to new return type.
(Mappings::lookup_hir_trait_item): Change the return type of the
function to an optional.
* util/rust-hir-map.h: Update the function's prototype.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Change the return type to an optional.
gcc/rust/ChangeLog:
* util/rust-hir-map.cc (Mappings::resolve_nodeid_to_stmt): Change the
return type and remove pointer out argument.
* util/rust-hir-map.h: Update function prototype.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Optional are more convenient to use and avoid uninitialized data.
gcc/rust/ChangeLog:
* backend/rust-compile-expr.cc (CompileExpr::generate_closure_function):
Adapt code for new optional return type.
* checks/errors/privacy/rust-privacy-reporter.cc (PrivacyReporter::check_base_type_privacy):
Likewise.
* util/rust-hir-map.cc (Mappings::lookup_hir_to_node): Change return
type to an optional.
* util/rust-hir-map.h: Adapt function prototype with the new return
type.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Previous API was using a boolean and a pointer, this was not practical
and could be replaced with an optional.
gcc/rust/ChangeLog:
* backend/rust-compile-expr.cc (CompileExpr::visit): Change call to use
the returned optional.
(CompileExpr::generate_closure_function): Likewise.
* backend/rust-compile-resolve-path.cc (ResolvePathRef::resolve):
Likewise.
* backend/rust-compile-type.cc (TyTyResolveCompile::visit): Likewise.
* backend/rust-mangle-v0.cc (v0_path): Likewise.
* checks/errors/privacy/rust-visibility-resolver.cc:
Likewise.
* checks/errors/rust-const-checker.cc (ConstChecker::visit): Likewise.
* checks/errors/rust-unsafe-checker.cc (UnsafeChecker::visit):
Likewise.
* checks/lints/rust-lint-marklive.cc (MarkLive::visit): Likewise.
(MarkLive::visit_path_segment): Likewise.
* typecheck/rust-hir-trait-resolve.cc (TraitResolver::resolve_path_to_trait):
Likewise.
* typecheck/rust-hir-type-check-path.cc (TypeCheckExpr::resolve_root_path):
Likewise.
* typecheck/rust-hir-type-check-type.cc (TypeCheckType::resolve_root_path):
Likewise.
(ResolveWhereClauseItem::visit): Likewise.
* util/rust-hir-map.cc (Mappings::lookup_node_to_hir): Return an
optional instead of a boolean.
* util/rust-hir-map.h: Change function prototype to match the new
return type.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
gcc/rust/ChangeLog:
* resolve/rust-default-resolver.cc
(DefaultResolver::visit):
Verify constant item has expression before attempting to visit
the later.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
gcc/testsuite/ChangeLog:
* rust/compile/issue-2906.rs: New test.
* rust/execute/torture/issue-2906.rs: New test.
Signed-off-by: Nobel Singh <nobel2073@gmail.com>
libgrust/ChangeLog:
* libformat_parser/Cargo.toml: Change Rust edition from 2021 to 2018.
* libformat_parser/generic_format_parser/Cargo.toml: Likewise.
* libformat_parser/generic_format_parser/src/lib.rs: Remove usage of
then-unstable std features and language constructs.
* libformat_parser/src/lib.rs: Likewise, plus provide extension trait
for String::leak.
gcc/testsuite/ChangeLog:
* rust/borrowck/borrowck.exp: New test.
* rust/borrowck/position_dependant_outlives.rs: New test.
* rust/borrowck/reference.rs: New test.
* rust/borrowck/return_ref_to_local.rs: New test.
* rust/borrowck/subset.rs: New test.
* rust/borrowck/test_move.rs: New test.
* rust/borrowck/test_move_behind_reference.rs: New test.
* rust/borrowck/test_move_conditional.rs: New test.
* rust/borrowck/tmp.rs: New test.
* rust/borrowck/use_while_mut.rs: New test.
* rust/borrowck/use_while_mut_fr.rs: New test.
* rust/borrowck/well_formed_function_inputs.rs: New test.
gcc/rust/ChangeLog:
* Make-lang.in: Link Polonius.
* checks/errors/borrowck/rust-borrow-checker.cc: Run Polonius.
Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
This is minimalistic version to build Polonius with Cargo.
gcc/rust/ChangeLog:
* Make-lang.in: Build Polonius.
Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
gcc/rust/ChangeLog:
* backend/rust-compile-expr.cc (CompileExpr::visit): Lines
removed as the objects are unused.
Signed-off-by: Kushal Pal <kushalpal109@gmail.com>
Latest macos environment runs on arm and is thus
incompatible with gcc.
ChangeLog:
* .github/workflows/ccpp.yml: Pin macos runner
version.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
gcc/rust/ChangeLog:
* backend/rust-tree.h: removing the CLASSTYPE_VBASECLASSES macro
which is duplicated three times.
Signed-off-by: Zhang He <zhanghe9702@163.com>
A previous bug with name resolution 2.0 was caused by an incorrectly
resolved inherent impl name. This test shall highlight the behavior
and prevent regression.
gcc/testsuite/ChangeLog:
* rust/compile/name_resolution25.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Inherent impl has a type it applies to. This type
was not visited and thus not resolved.
gcc/rust/ChangeLog:
* resolve/rust-default-resolver.cc (DefaultResolver::visit): Visit
inherent impl type.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Fixes#2883.
* .gitignore: Remove 'libgrust/*/target/'.
gcc/rust/
* Make-lang.in (LIBFORMAT_PARSER): Point to the GCC build
directory.
* ($(LIBFORMAT_PARSER)): Build in the GCC build directory.
... to avoid verbatim repetition.
gcc/rust/
* Make-lang.in (LIBPROC_MACRO_INTERNAL): New.
(RUST_LIBDEPS, crab1$(exeext), rust/libformat_parser.a): Use it.
This isn't necessary, as the full path to 'libproc_macro_internal.a' is
specified.
gcc/rust/
* Make-lang.in (RUST_LDFLAGS): Remove
'libgrust/libproc_macro_internal'.
This commits vendors and locks our dependencies so that our Rust components
do not need internet access to be built anymore. Tested in a docker container
with no network access.
We can think about merging the vendor directory once we have more than one
Rust component, e.g. when we add polonius to the mix.
libgrust/ChangeLog:
* libformat_parser/.cargo/config: New file.
* libformat_parser/vendor.NOTES: New file.
* libformat_parser/vendor/libc/.cargo-checksum.json: New file.
* libformat_parser/vendor/libc/CONTRIBUTING.md: New file.
* libformat_parser/vendor/libc/Cargo.toml: New file.
* libformat_parser/vendor/libc/LICENSE-APACHE: New file.
* libformat_parser/vendor/libc/LICENSE-MIT: New file.
* libformat_parser/vendor/libc/README.md: New file.
* libformat_parser/vendor/libc/build.rs: New file.
* libformat_parser/vendor/libc/rustfmt.toml: New file.
* libformat_parser/vendor/libc/src/fixed_width_ints.rs: New file.
* libformat_parser/vendor/libc/src/fuchsia/aarch64.rs: New file.
* libformat_parser/vendor/libc/src/fuchsia/align.rs: New file.
* libformat_parser/vendor/libc/src/fuchsia/mod.rs: New file.
* libformat_parser/vendor/libc/src/fuchsia/no_align.rs: New file.
* libformat_parser/vendor/libc/src/fuchsia/riscv64.rs: New file.
* libformat_parser/vendor/libc/src/fuchsia/x86_64.rs: New file.
* libformat_parser/vendor/libc/src/hermit/aarch64.rs: New file.
* libformat_parser/vendor/libc/src/hermit/mod.rs: New file.
* libformat_parser/vendor/libc/src/hermit/x86_64.rs: New file.
* libformat_parser/vendor/libc/src/lib.rs: New file.
* libformat_parser/vendor/libc/src/macros.rs: New file.
* libformat_parser/vendor/libc/src/psp.rs: New file.
* libformat_parser/vendor/libc/src/sgx.rs: New file.
* libformat_parser/vendor/libc/src/solid/aarch64.rs: New file.
* libformat_parser/vendor/libc/src/solid/arm.rs: New file.
* libformat_parser/vendor/libc/src/solid/mod.rs: New file.
* libformat_parser/vendor/libc/src/switch.rs: New file.
* libformat_parser/vendor/libc/src/teeos/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/aix/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/aix/powerpc64.rs: New file.
* libformat_parser/vendor/libc/src/unix/align.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/apple/b32/align.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/apple/b32/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/apple/b64/aarch64/align.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/apple/b64/aarch64/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/apple/b64/align.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/apple/b64/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/apple/b64/x86_64/align.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/apple/b64/x86_64/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/apple/long_array.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/apple/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/freebsdlike/dragonfly/errno.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/freebsdlike/dragonfly/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/freebsdlike/freebsd/aarch64.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/freebsdlike/freebsd/arm.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/freebsdlike/freebsd/freebsd11/b64.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/freebsdlike/freebsd/freebsd11/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/freebsdlike/freebsd/freebsd12/b64.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/freebsdlike/freebsd/freebsd12/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/freebsdlike/freebsd/freebsd12/x86_64.rs:
New file.
* libformat_parser/vendor/libc/src/unix/bsd/freebsdlike/freebsd/freebsd13/b64.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/freebsdlike/freebsd/freebsd13/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/freebsdlike/freebsd/freebsd13/x86_64.rs:
New file.
* libformat_parser/vendor/libc/src/unix/bsd/freebsdlike/freebsd/freebsd14/b64.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/freebsdlike/freebsd/freebsd14/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/freebsdlike/freebsd/freebsd14/x86_64.rs:
New file.
* libformat_parser/vendor/libc/src/unix/bsd/freebsdlike/freebsd/freebsd15/b64.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/freebsdlike/freebsd/freebsd15/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/freebsdlike/freebsd/freebsd15/x86_64.rs:
New file.
* libformat_parser/vendor/libc/src/unix/bsd/freebsdlike/freebsd/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/freebsdlike/freebsd/powerpc.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/freebsdlike/freebsd/powerpc64.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/freebsdlike/freebsd/riscv64.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/freebsdlike/freebsd/x86.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/freebsdlike/freebsd/x86_64/align.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/freebsdlike/freebsd/x86_64/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/freebsdlike/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/netbsdlike/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/netbsdlike/netbsd/aarch64.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/netbsdlike/netbsd/arm.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/netbsdlike/netbsd/mips.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/netbsdlike/netbsd/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/netbsdlike/netbsd/powerpc.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/netbsdlike/netbsd/riscv64.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/netbsdlike/netbsd/sparc64.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/netbsdlike/netbsd/x86.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/netbsdlike/netbsd/x86_64.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/netbsdlike/openbsd/aarch64.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/netbsdlike/openbsd/arm.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/netbsdlike/openbsd/mips64.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/netbsdlike/openbsd/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/netbsdlike/openbsd/powerpc.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/netbsdlike/openbsd/powerpc64.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/netbsdlike/openbsd/riscv64.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/netbsdlike/openbsd/sparc64.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/netbsdlike/openbsd/x86.rs: New file.
* libformat_parser/vendor/libc/src/unix/bsd/netbsdlike/openbsd/x86_64.rs: New file.
* libformat_parser/vendor/libc/src/unix/haiku/b32.rs: New file.
* libformat_parser/vendor/libc/src/unix/haiku/b64.rs: New file.
* libformat_parser/vendor/libc/src/unix/haiku/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/haiku/native.rs: New file.
* libformat_parser/vendor/libc/src/unix/haiku/x86_64.rs: New file.
* libformat_parser/vendor/libc/src/unix/hurd/align.rs: New file.
* libformat_parser/vendor/libc/src/unix/hurd/b32.rs: New file.
* libformat_parser/vendor/libc/src/unix/hurd/b64.rs: New file.
* libformat_parser/vendor/libc/src/unix/hurd/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/hurd/no_align.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/android/b32/arm.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/android/b32/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/android/b32/x86/align.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/android/b32/x86/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/android/b64/aarch64/align.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/android/b64/aarch64/int128.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/android/b64/aarch64/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/android/b64/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/android/b64/riscv64/align.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/android/b64/riscv64/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/android/b64/x86_64/align.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/android/b64/x86_64/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/android/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/emscripten/align.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/emscripten/lfs64.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/emscripten/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/emscripten/no_align.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/align.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/arch/generic/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/arch/mips/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/arch/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/arch/powerpc/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/arch/sparc/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/gnu/align.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/gnu/b32/arm/align.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/gnu/b32/arm/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/gnu/b32/csky/align.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/gnu/b32/csky/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/gnu/b32/m68k/align.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/gnu/b32/m68k/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/gnu/b32/mips/align.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/gnu/b32/mips/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/gnu/b32/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/gnu/b32/powerpc.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/gnu/b32/riscv32/align.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/gnu/b32/riscv32/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/gnu/b32/sparc/align.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/gnu/b32/sparc/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/gnu/b32/x86/align.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/gnu/b32/x86/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/gnu/b64/aarch64/align.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/gnu/b64/aarch64/fallback.rs:
New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/gnu/b64/aarch64/ilp32.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/gnu/b64/aarch64/int128.rs:
New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/gnu/b64/aarch64/lp64.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/gnu/b64/aarch64/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/gnu/b64/loongarch64/align.rs:
New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/gnu/b64/loongarch64/mod.rs:
New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/gnu/b64/mips64/align.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/gnu/b64/mips64/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/gnu/b64/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/gnu/b64/powerpc64/align.rs:
New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/gnu/b64/powerpc64/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/gnu/b64/riscv64/align.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/gnu/b64/riscv64/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/gnu/b64/s390x.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/gnu/b64/sparc64/align.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/gnu/b64/sparc64/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/gnu/b64/x86_64/align.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/gnu/b64/x86_64/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/gnu/b64/x86_64/not_x32.rs:
New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/gnu/b64/x86_64/x32.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/gnu/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/gnu/no_align.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/musl/b32/arm/align.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/musl/b32/arm/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/musl/b32/hexagon.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/musl/b32/mips/align.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/musl/b32/mips/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/musl/b32/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/musl/b32/powerpc.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/musl/b32/riscv32/align.rs:
New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/musl/b32/riscv32/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/musl/b32/x86/align.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/musl/b32/x86/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/musl/b64/aarch64/align.rs:
New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/musl/b64/aarch64/int128.rs:
New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/musl/b64/aarch64/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/musl/b64/mips64.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/musl/b64/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/musl/b64/powerpc64.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/musl/b64/riscv64/align.rs:
New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/musl/b64/riscv64/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/musl/b64/s390x.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/musl/b64/x86_64/align.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/musl/b64/x86_64/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/musl/lfs64.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/musl/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/no_align.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/non_exhaustive.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/uclibc/align.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/uclibc/arm/align.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/uclibc/arm/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/uclibc/arm/no_align.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/uclibc/mips/mips32/align.rs:
New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/uclibc/mips/mips32/mod.rs:
New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/uclibc/mips/mips32/no_align.rs:
New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/uclibc/mips/mips64/align.rs:
New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/uclibc/mips/mips64/mod.rs:
New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/uclibc/mips/mips64/no_align.rs:
New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/uclibc/mips/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/uclibc/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/uclibc/no_align.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/uclibc/x86_64/l4re.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/uclibc/x86_64/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/linux/uclibc/x86_64/other.rs: New file.
* libformat_parser/vendor/libc/src/unix/linux_like/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/newlib/aarch64/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/newlib/align.rs: New file.
* libformat_parser/vendor/libc/src/unix/newlib/arm/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/newlib/espidf/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/newlib/generic.rs: New file.
* libformat_parser/vendor/libc/src/unix/newlib/horizon/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/newlib/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/newlib/no_align.rs: New file.
* libformat_parser/vendor/libc/src/unix/newlib/powerpc/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/newlib/vita/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/no_align.rs: New file.
* libformat_parser/vendor/libc/src/unix/nto/aarch64.rs: New file.
* libformat_parser/vendor/libc/src/unix/nto/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/nto/neutrino.rs: New file.
* libformat_parser/vendor/libc/src/unix/nto/x86_64.rs: New file.
* libformat_parser/vendor/libc/src/unix/redox/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/solarish/compat.rs: New file.
* libformat_parser/vendor/libc/src/unix/solarish/illumos.rs: New file.
* libformat_parser/vendor/libc/src/unix/solarish/mod.rs: New file.
* libformat_parser/vendor/libc/src/unix/solarish/solaris.rs: New file.
* libformat_parser/vendor/libc/src/unix/solarish/x86.rs: New file.
* libformat_parser/vendor/libc/src/unix/solarish/x86_64.rs: New file.
* libformat_parser/vendor/libc/src/unix/solarish/x86_common.rs: New file.
* libformat_parser/vendor/libc/src/vxworks/aarch64.rs: New file.
* libformat_parser/vendor/libc/src/vxworks/arm.rs: New file.
* libformat_parser/vendor/libc/src/vxworks/mod.rs: New file.
* libformat_parser/vendor/libc/src/vxworks/powerpc.rs: New file.
* libformat_parser/vendor/libc/src/vxworks/powerpc64.rs: New file.
* libformat_parser/vendor/libc/src/vxworks/x86.rs: New file.
* libformat_parser/vendor/libc/src/vxworks/x86_64.rs: New file.
* libformat_parser/vendor/libc/src/wasi.rs: New file.
* libformat_parser/vendor/libc/src/windows/gnu/align.rs: New file.
* libformat_parser/vendor/libc/src/windows/gnu/mod.rs: New file.
* libformat_parser/vendor/libc/src/windows/mod.rs: New file.
* libformat_parser/vendor/libc/src/windows/msvc/mod.rs: New file.
* libformat_parser/vendor/libc/src/xous.rs: New file.
* libformat_parser/vendor/libc/tests/const_fn.rs: New file.
* libformat_parser/vendor/unicode-xid/.cargo-checksum.json: New file.
* libformat_parser/vendor/unicode-xid/COPYRIGHT: New file.
* libformat_parser/vendor/unicode-xid/Cargo.toml: New file.
* libformat_parser/vendor/unicode-xid/LICENSE-APACHE: New file.
* libformat_parser/vendor/unicode-xid/LICENSE-MIT: New file.
* libformat_parser/vendor/unicode-xid/README.md: New file.
* libformat_parser/vendor/unicode-xid/benches/xid.rs: New file.
* libformat_parser/vendor/unicode-xid/src/lib.rs: New file.
* libformat_parser/vendor/unicode-xid/src/tables.rs: New file.
* libformat_parser/vendor/unicode-xid/src/tests.rs: New file.
* libformat_parser/vendor/unicode-xid/tests/exhaustive_tests.rs: New file.
This is the main Polonius based logic which creates the information
Polonius needs from BIR. It is largly guessed and rever engineered, so
some aspects are probably wrong.
gcc/rust/ChangeLog:
* checks/errors/borrowck/rust-bir-fact-collector.h: New file.
* checks/errors/borrowck/rust-borrow-checker.cc (BorrowChecker::go):
Enable fact collection.
Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
gcc/rust/ChangeLog:
* checks/errors/borrowck/rust-bir-place.h (struct Lifetime):
Extended regions and loans.
(struct Loan): Representation of loan (result of borrowing)
* checks/errors/borrowck/rust-bir-builder-expr-stmt.cc (ExprStmtBuilder::visit):
Fix let stmt handling.
* checks/errors/borrowck/rust-bir-builder-pattern.h: improved
pattern translation
* checks/errors/borrowck/rust-bir-builder-internal.h: region binding
* checks/errors/borrowck/rust-bir-builder-expr-stmt.h (class ExprStmtBuilder):
Region support.
(class RenumberCtx): Region support.
* checks/errors/borrowck/rust-bir-builder.h (class Builder): Region support.
* checks/errors/borrowck/rust-bir-dump.cc (get_lifetime_name): Region support.
(renumber_places): Region support.
(Dump::go): Region support.
(Dump::visit): Region support.
(Dump::visit_lifetime): Region support.
(Dump::visit_scope): Region support.
* checks/errors/borrowck/rust-bir.h (class AbstractExpr): Region support.
(struct Function): Region support.
(class BorrowExpr): Region support.
(class CallExpr): Region support.
Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
Biggybag on variance analysis to extract regions of fields from ADT
regions.
gcc/rust/ChangeLog:
* typecheck/rust-tyty-variance-analysis-private.h (class FieldVisitorCtx):
Region extraction.
* typecheck/rust-tyty-variance-analysis.cc (query_field_regions): Region extraction.
(FieldVisitorCtx::collect_regions): Region extraction.
(FieldVisitorCtx::add_constraints_from_ty): Region extraction.
(FieldVisitorCtx::add_constraints_from_region): Region
extraction.
(FieldVisitorCtx::add_constrints_from_param): Region extraction.
* typecheck/rust-tyty-variance-analysis.h (query_field_regions):
Region extraction.
Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
Rust part is not build and not invoked at this point.
gcc/rust/ChangeLog:
* checks/errors/borrowck/ffi-polonius/Cargo.toml: New file.
* checks/errors/borrowck/ffi-polonius/src/gccrs_ffi.rs: New file.
* checks/errors/borrowck/ffi-polonius/src/gccrs_ffi_generated.rs: New file.
* checks/errors/borrowck/ffi-polonius/src/lib.rs: New file.
* checks/errors/borrowck/polonius/rust-polonius-ffi.h: New file.
* checks/errors/borrowck/polonius/rust-polonius.h: New file.
Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
gcc/rust/ChangeLog:
* checks/errors/borrowck/rust-bir-builder-expr-stmt.cc (ExprStmtBuilder::visit):
Use callable API
Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
Replace direct usage of system headers.
gcc/rust/ChangeLog:
* checks/errors/borrowck/rust-bir-dump.cc: Use rust-system.h
* checks/errors/borrowck/rust-bir-dump.h (RUST_BIR_DUMP_H): Use rust-system.h
* checks/errors/borrowck/rust-bir-place.h (RUST_BIR_PLACE_H): Use rust-system.h
* checks/errors/borrowck/rust-function-collector.h: Use rust-system.h
* rust-system.h: Use rust-system.h
* typecheck/rust-hir-type-check.h: Use rust-system.h
* typecheck/rust-tyty-subst.cc: Use rust-system.h
* typecheck/rust-tyty-subst.h: Use rust-system.h
* typecheck/rust-tyty.h: Use rust-system.h
Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
Never can... never... exist, so it should always be coerced to the type
it is being matched against. This is useful for breaking off of a loop
from inside a match, or an if condition, for example.
gcc/rust/ChangeLog:
* typecheck/rust-unify.cc (UnifyRules::go): Always unify to `ltype` if
we are matching against a `Never` in `rtype`.
(UnifyRules::expect_never): Always unify to the expected type.
gcc/testsuite/ChangeLog:
* rust/compile/match-never-ltype.rs: New test.
* rust/compile/match-never-rtype.rs: New test.
The error is actually expected and uses the correct location.
gcc/testsuite/ChangeLog:
* rust/compile/raw-byte-string-loc.rs: Use dg-error instead of
dg-excess-error.
* rust/compile/raw-string-loc.rs: Likewise.
gcc/rust/ChangeLog:
* lex/rust-lex.cc
(Lexer::parse_raw_string):
Bring handling of edge cases to par with parse_raw_byte_string.
gcc/testsuite/ChangeLog:
* rust/compile/raw-string-loc.rs: New test.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
gcc/rust/ChangeLog:
* parse/rust-parse-impl.h
(Parser::parse_vis_item):
Call parse_function instead of parse_async_item when finding
UNSAFE or EXTERN_KW during lookahead.
gcc/testsuite/ChangeLog:
* rust/compile/func-const-unsafe.rs: New test.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
gcc/rust/ChangeLog:
* lex/rust-lex.cc
(Lexer::parse_raw_byte_string):
Bring handling of edge cases to par with parse_byte_string.
gcc/testsuite/ChangeLog:
* rust/compile/raw-byte-string-loc.rs: New test.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
GCC 4.8 does not handle pair with references correctly. We need to use a
properly typed struct instead.
gcc/rust/ChangeLog:
* resolve/rust-forever-stack.h: Change dfs function prototype and
declare dfs return type structure.
* resolve/rust-forever-stack.hxx: Adapt dfs function to the new return
type.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add a few test for globbing to highlight function call ambiguities.
gcc/testsuite/ChangeLog:
* rust/compile/name_resolution23.rs: New test.
* rust/compile/name_resolution24.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
gcc/testsuite/ChangeLog:
* rust/compile/name_resolution13.rs: Add new module and remove compile
step.
* rust/compile/name_resolution14.rs: New test.
* rust/compile/name_resolution15.rs: New test.
* rust/compile/name_resolution16.rs: New test.
* rust/compile/name_resolution17.rs: New test.
* rust/compile/name_resolution18.rs: New test.
* rust/compile/name_resolution19.rs: New test.
* rust/compile/name_resolution20.rs: New test.
* rust/compile/name_resolution21.rs: New test.
gcc/rust/ChangeLog:
* backend/rust-compile-resolve-path.cc: Attempt to resolve names
also using new name resolution context.
* backend/rust-compile-resolve-path.h: Add new declaration.
Name resolution for rebind were missing.
gcc/rust/ChangeLog:
* resolve/rust-toplevel-name-resolver-2.0.cc (TopLevel::handle_use_glob):
Change function prototype to use a reference instead.
(TopLevel::handle_use_dec): Likewise.
(TopLevel::handle_rebind): Add name resolution on rebind use
declarations.
(flatten_rebind): Change prototype to accept a pair of path/alias.
(flatten_list): Adapt call to flatten_rebind.
(flatten): Adapt call to flatten_rebind.
(flatten_glob): Remove unused part.
(TopLevel::visit): Add rebind resolution.
* resolve/rust-toplevel-name-resolver-2.0.h: Adapt function prototypes.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
This format dialog triggered a warning.
gcc/rust/ChangeLog:
* resolve/rust-toplevel-name-resolver-2.0.cc (TopLevel::handle_use_dec):
Replace the string format %<%s%> with the proper %qs format.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Immutable name resolution context is not initialized when the classic
name resolution is in use. It can therefore not be used, the getter would
error out.
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-path.cc (TypeCheckExpr::resolve_root_path):
Only get immutable name resolution context when name resolution 2.0 is
used.
* typecheck/rust-hir-type-check-type.cc (TypeCheckType::resolve_root_path):
Likewise.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Crate number was not assigned with the other fields in the assignment
operator overload of a CannonicalPath.
gcc/rust/ChangeLog:
* util/rust-canonical-path.h: Also assign crate number.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
The old resolver injected a Self generic parameter in order to help the
trait solver. This is clearly sketchy at best and should be fixed in
the future.
gcc/rust/ChangeLog:
* resolve/rust-toplevel-name-resolver-2.0.cc (TopLevel::visit): Add
Self generic parameter injection and a warning.
* resolve/rust-toplevel-name-resolver-2.0.h: Add function prototype.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Constant items were handled only by the old resolver, this lead to an
ICE when using the new resolver on some rust code containing a constant
item as the new and the old resolver cannot be used at the same time.
gcc/rust/ChangeLog:
* backend/rust-compile-item.cc (CompileItem::visit): Check the resolver
flag and use the new one when required.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
We need to visit subcomponents in unsafe elements, this means we can
leverage the default ast visitor's code instead of duplicating it.
gcc/rust/ChangeLog:
* resolve/rust-default-resolver.cc (DefaultResolver::visit): Remove
empty visit function.
* resolve/rust-default-resolver.h: Remove function prototype.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Remove extern block scoping visit function, use the default visitor visit
function instead. We do not need scoping for extern block as their
element shall be visible from the extern block scope.
gcc/rust/ChangeLog:
* resolve/rust-default-resolver.cc (DefaultResolver::visit): Remove
visitor implementation and scoping.
* resolve/rust-default-resolver.h: Remove function prototype.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Constants could not be resolved without their identifier in the right
scope.
gcc/rust/ChangeLog:
* resolve/rust-toplevel-name-resolver-2.0.cc (TopLevel::visit): Add
constant identifiers to the resolver.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
We shall search in the right namespace. The correct namespace for struct
is type namespace.
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-item.cc (TypeCheckItem::visit): Change
search location for struct types.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
The enum type shall be in type namespace, not value namespace.
gcc/rust/ChangeLog:
* resolve/rust-toplevel-name-resolver-2.0.cc (GlobbingVisitor::visit):
Change enum type namespace.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Only tuple struct constructor was added to the resolver.
gcc/rust/ChangeLog:
* resolve/rust-toplevel-name-resolver-2.0.cc (GlobbingVisitor::visit):
Add tuple struct type to the resolver's context.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Unit struct have a special constructor that should be added to the struct
namespace in order to be resolved later when called. As it is a function
it should be added in the value namespace.
gcc/rust/ChangeLog:
* resolve/rust-toplevel-name-resolver-2.0.cc (GlobbingVisitor::visit):
Add the struct constructor when the struct is a unit.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Values were inserted in the label namespace instead of the value
namespace this lead to several bugs.
gcc/rust/ChangeLog:
* resolve/rust-late-name-resolver-2.0.cc (Late::visit): Change the
namespace for values from "label" to "values".
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
This overload did not dispatch the visitor to sub members of a raw
pointer like the default one. It is therefore useless as pointed type
shall be visited to be resolved correctly.
gcc/rust/ChangeLog:
* resolve/rust-default-resolver.cc (DefaultResolver::visit): Remove
function implementation.
* resolve/rust-default-resolver.h: Remove function prototype.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
The type of constant item expression was not properly visited in the
default resolver.
gcc/rust/ChangeLog:
* resolve/rust-default-resolver.cc (DefaultResolver::visit): Visit
constant item's types.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Function return type was not properly visited in the default resolver
visitor pattern.
gcc/rust/ChangeLog:
* resolve/rust-default-resolver.cc (DefaultResolver::visit): Visit
function return type.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Error message did not match the test from the previous name resolver when
a given path cannot be resolved.
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-path.cc (TypeCheckExpr::resolve_root_path):
Change error message to match old resolver and test case.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
A tuple struct constructor should be inserted in the value namespace
during name resolution in order to reject multiple definitions of the
function.
gcc/rust/ChangeLog:
* resolve/rust-toplevel-name-resolver-2.0.cc (TopLevel::visit): Add
the struct constructor to the value namespace.
gcc/testsuite/ChangeLog:
* rust/compile/name_resolution22.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Glob use declarations may lead to ambiguous situation where two
definitions with the same name are imported in a given scope. The
compiler now handles shadowable items inserted after non shadowable
items. An error is now thrown when multiple shadowable items are imported
and used in the same rib.
gcc/rust/ChangeLog:
* resolve/rust-early-name-resolver-2.0.cc (Early::visit): Adapt
resolved type to the new API.
(Early::visit_attributes): Retrieve the node id from the definition.
* resolve/rust-forever-stack.h: Change the return type of getter
functions. Those functions now return a definition type instead of a
node id.
* resolve/rust-forever-stack.hxx: Change member function implementation
in the forever stack to accomodate it's API changes.
* resolve/rust-late-name-resolver-2.0.cc (Late::visit): Use internal
node id. Emit an error when resolving multiple ambiguous values.
* resolve/rust-rib.cc (Rib::Definition::Definition): Add a default
constructor.
(Rib::Definition::is_ambiguous): Add a new function to determine
whether a function definition is ambiguous or not.
(Rib::Definition::to_string): Add a member function to convert a given
definition to a string.
(Rib::insert): Add new rules for value insertion in a rib. Insertion
order does not impact the result anymore: inserting a shadowable value
after a non shadowable one does not trigger an error anymore. All
shadowable values inserted in a rib are kepts until being replaced by a
non shadowable one.
(Rib::get): Return a definition instead of a node id.
* resolve/rust-rib.h: Update function prototypes.
* resolve/rust-toplevel-name-resolver-2.0.cc (TopLevel::handle_use_glob):
Update return value container to match the new function's prototype.
(TopLevel::handle_use_dec): Likewise.
(flatten_glob): Likewise.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Elements from glob use declaration shall be shadowable by default.
gcc/rust/ChangeLog:
* resolve/rust-forever-stack.h: Add a new function prototype to insert
a shadowable definition.
* resolve/rust-forever-stack.hxx: Add the new insert_shadowable
function to insert shadowable definition into the forever stack.
* resolve/rust-name-resolution-context.cc (NameResolutionContext::insert_shadowable):
Likewise with the name resolution context.
* resolve/rust-name-resolution-context.h: Add name resolution context
insert_shadowable member function prototype.
* resolve/rust-toplevel-name-resolver-2.0.cc (GlobbingVisitor::visit):
Insert shadowable definition into the forever stack for glob use
declaration.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Globbing visitor did not visit subitems.
gcc/rust/ChangeLog:
* resolve/rust-late-name-resolver-2.0.cc (Late::visit): Add a check
for missing item.
* resolve/rust-toplevel-name-resolver-2.0.cc (GlobbingVisitor::go):
Add a new function in the visitor to dispatch the visitor to items in
the given module.
(TopLevel::handle_use_glob): Change call to visitor to use the pointer.
* resolve/rust-toplevel-name-resolver-2.0.h: Add prototype for new
member function.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Direct function calls did not work anymore due to the transition to the
new resolver.
gcc/rust/ChangeLog:
* checks/lints/rust-lint-marklive.cc (MarkLive::find_ref_node_id):
Add code path for the resolver 2.0
* resolve/rust-late-name-resolver-2.0.cc (Late::visit): Remove failing
label context resolve call.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
This is the first part of the code required to enable globbing on use
declarations.
gcc/rust/ChangeLog:
* resolve/rust-toplevel-name-resolver-2.0.cc (GlobbingVisitor::visit):
Insert names into their namespace.
(TopLevel::visit): Insert ast module.
(TopLevel::handle_use_dec): Resolve use declaration.
(TopLevel::handle_use_glob): Use globbing visitor.
(flatten_list): Use globbing path vector.
(flatten_glob): Likewise.
(flatten): Likewise.
(prefix_subpaths): Add a function to prefix subpath.
* resolve/rust-toplevel-name-resolver-2.0.h (class GlobbingVisitor):
Add globbing visitor.
* util/rust-hir-map.cc (Mappings::insert_ast_module): Add function to
insert module in module hashmap.
(Mappings::lookup_ast_module): Add function to retrieve ast module.
* util/rust-hir-map.h: Add module map and getter/setter prototypes.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
gcc/rust/ChangeLog:
* resolve/rust-toplevel-name-resolver-2.0.cc (TopLevel::visit): Module
should be added to the type namespace in order to be retrieved later.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
The resolver was emitting an error when meeting the same symbol twice.
What is important here is the origin of the resolved symbol, we should
emit an error when the name is similar but the symbol isn't be not when
the resolver is simply meeting the exact same symbol.
gcc/rust/ChangeLog:
* resolve/rust-toplevel-name-resolver-2.0.cc (insert_macros): Add
constraint over the ast node id.
(TopLevel::visit): Likewise.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
The error message did not match rustc's.
gcc/rust/ChangeLog:
* resolve/rust-toplevel-name-resolver-2.0.cc (TopLevel::visit): Change
error message.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
The compiler did not emit any warning when a same target was declared
from different sources.
gcc/rust/ChangeLog:
* resolve/rust-toplevel-name-resolver-2.0.cc (TopLevel::handle_use_dec):
Use the new dict to track down already resolved use declarations.
* resolve/rust-toplevel-name-resolver-2.0.h: Add new dict to store
previous use declarations.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
The resolver did report duplicate symbols when being run multiple times
even if the node id was the same. This commit adds an additional
condition, the error will only be reported if the existing node id is
different from the current node id.
gcc/rust/ChangeLog:
* resolve/rust-toplevel-name-resolver-2.0.cc (TopLevel::insert_or_error_out):
Add new constraint to duplicate errors.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Fetch the ImmutableNrCtx in order to access name resolver during
typechecking.
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-item.cc (TypeCheckItem::visit): Start
fetching name resolution information in the typechecker.
* typecheck/rust-hir-type-check-type.cc (TypeCheckType::resolve_root_path):
Likewise.
* typecheck/rust-hir-type-check-path.cc: Use nr 2.0.
gcc/rust/ChangeLog:
* rust-session-manager.cc: Add files for dumping name resolution, call
name resolution dump function.
(Session::dump_name_resolution): New.
* rust-session-manager.h: New declaration.
gcc/rust/ChangeLog:
* rust-session-manager.cc (Session::compile_crate): Create name resolution
context for Session::expansion and subsequent name resolution passes.
(Session::expansion): Take name resolution context as a parameter
instead.
* rust-session-manager.h (Session::expansion): Fix declaration.
gcc/rust/ChangeLog:
* Make-lang.in: Compile it.
* resolve/rust-immutable-name-resolution-context.cc: New file.
* resolve/rust-immutable-name-resolution-context.h: New file.
Fixes issue #2855
gcc/rust/ChangeLog:
* Make-lang.in: add new .o builds for new .cc files
* expand/rust-cfg-strip.h (RUST_CFG_STRIP_H): Add include guards
for rust-cfg-strip
* expand/rust-macro-builtins.cc (make_macro_path_str): moved to new respective files
(make_token): moved to new respective files
(make_string): moved to new respective files
(macro_end_token): moved to new respective files
(try_extract_string_literal_from_fragment): moved to new respective files
(try_expand_many_expr): moved to new respective files
(parse_single_string_literal): moved to new respective files
(source_relative_path): moved to new respective files
(load_file_bytes): moved to new respective files
(MacroBuiltin::assert_handler): moved to new respective files
(MacroBuiltin::file_handler): moved to new respective files
(MacroBuiltin::column_handler): moved to new respective files
(MacroBuiltin::include_bytes_handler): moved to new respective files
(MacroBuiltin::include_str_handler): moved to new respective files
(MacroBuiltin::compile_error_handler): moved to new respective files
(MacroBuiltin::concat_handler): moved to new respective files
(MacroBuiltin::env_handler): moved to new respective files
(MacroBuiltin::cfg_handler): moved to new respective files
(MacroBuiltin::include_handler): moved to new respective files
(MacroBuiltin::line_handler): moved to new respective files
(MacroBuiltin::stringify_handler): moved to new respective files
(struct FormatArgsInput): moved to new respective files
(struct FormatArgsParseError): moved to new respective files
(format_args_parse_arguments): moved to new respective files
(MacroBuiltin::format_args_handler): moved to new respective files
* expand/rust-macro-builtins.h (builtin_macro_from_string):
merge tl::optional from master
* expand/rust-macro-builtins-asm.cc: New file.
* expand/rust-macro-builtins-format-args.cc: New file.
* expand/rust-macro-builtins-helpers.cc: New file.
* expand/rust-macro-builtins-helpers.h: New file.
* expand/rust-macro-builtins-include.cc: New file.
* expand/rust-macro-builtins-location.cc: New file.
* expand/rust-macro-builtins-log-debug.cc: New file.
* expand/rust-macro-builtins-test-bench.cc: New file.
* expand/rust-macro-builtins-trait.cc: New file.
* expand/rust-macro-builtins-utility.cc: New file.
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-item.cc (TypeCheckItem::visit):
Collect variance info from types.
Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
This fixes an issue we had where the generated code ended with more static
pieces than its rustc counterpart.
gcc/rust/ChangeLog:
* expand/rust-macro-builtins.cc (struct FormatArgsInput): Store the format_str
as a string instead of an AST::Expr.
(format_args_parse_arguments): Transform format_expr into a format string
properly - add note for handling eager macro invocations later on.
(MacroBuiltin::format_args_handler): Parse the correct input, append
newline to format_str if necessary.
gcc/rust/ChangeLog:
* ast/rust-fmt.cc (ffi::RustHamster::to_string): New.
(Pieces::collect): Adapt to use new handle API.
(Pieces::~Pieces): Likewise.
(Pieces::Pieces): Likewise.
(Pieces::operator=): Likewise.
* ast/rust-fmt.h (struct RustString): Add members.
(struct FormatArgsHandle): New.
(clone_pieces): Adapt for new FFI API.
(destroy_pieces): Likewise.
(struct Pieces): Store new FormatArgsHandle type.
* expand/rust-expand-format-args.cc (expand_format_args): Use proper
namespace.
* resolve/rust-ast-resolve-base.cc (ResolverBase::visit): FormatArgs
nodes are already resolved, so do nothing.
libgrust/ChangeLog:
* libformat_parser/src/lib.rs: Use new Handle struct and expose it.
Merge "macro: Use MacroInvocation's node_id in ExternalItem constructor", to
avoid bootstrap failure:
[...]
In file included from [...]/source-gcc/gcc/rust/ast/rust-expr.h:6,
from [...]/source-gcc/gcc/rust/ast/rust-ast-full.h:24,
from [...]/source-gcc/gcc/rust/ast/rust-ast.cc:24:
In copy constructor ‘Rust::AST::MacroInvocation::MacroInvocation(const Rust::AST::MacroInvocation&)’,
inlined from ‘Rust::AST::MacroInvocation* Rust::AST::MacroInvocation::clone_macro_invocation_impl() const’ at [...]/source-gcc/gcc/rust/ast/rust-\
macro.h:798:38:
[...]/source-gcc/gcc/rust/ast/rust-macro.h:734:39: error: ‘*(Rust::AST::MacroInvocation*)<unknown>.Rust::AST::MacroInvocation::Rust::AST::ExprWithout\
Block.Rust::AST::ExprWithoutBlock::Rust::AST::Expr.Rust::AST::Expr::node_id’ is used uninitialized [-Werror=uninitialized]
734 | builtin_kind (other.builtin_kind)
| ^
cc1plus: all warnings being treated as errors
make[3]: *** [[...]/source-gcc/gcc/rust/Make-lang.in:423: rust/rust-ast.o] Error 1
[...]
In file included from [...]/source-gcc/gcc/rust/ast/rust-expr.h:6,
from [...]/source-gcc/gcc/rust/ast/rust-item.h:27,
from [...]/source-gcc/gcc/rust/parse/rust-parse.h:20,
from [...]/source-gcc/gcc/rust/expand/rust-macro-expand.h:24,
from [...]/source-gcc/gcc/rust/expand/rust-macro-expand.cc:19:
In copy constructor ‘Rust::AST::MacroInvocation::MacroInvocation(const Rust::AST::MacroInvocation&)’,
inlined from ‘Rust::AST::MacroInvocation* Rust::AST::MacroInvocation::clone_macro_invocation_impl() const’ at [...]/source-gcc/gcc/rust/ast/rust-\
macro.h:798:38:
[...]/source-gcc/gcc/rust/ast/rust-macro.h:734:39: error: ‘*(Rust::AST::MacroInvocation*)<unknown>.Rust::AST::MacroInvocation::Rust::AST::ExprWithout\
Block.Rust::AST::ExprWithoutBlock::Rust::AST::Expr.Rust::AST::Expr::node_id’ is used uninitialized [-Werror=uninitialized]
734 | builtin_kind (other.builtin_kind)
| ^
cc1plus: all warnings being treated as errors
make[3]: *** [[...]/source-gcc/gcc/rust/Make-lang.in:433: rust/rust-macro-expand.o] Error 1
[...]
The following separates the escape solution for return stmts not
only during points-to solving but also for later querying. This
requires adjusting the points-to-global tests to include escapes
through returns. Technically the patch replaces the existing
post-processing which computes the transitive closure of the
returned value solution by a proper artificial variable with
transitive closure constraints. Instead of adding the solution
to escaped we track it separately.
PR tree-optimization/112653
* gimple-ssa.h (gimple_df): Add escaped_return solution.
* tree-ssa.cc (init_tree_ssa): Reset it.
(delete_tree_ssa): Likewise.
* tree-ssa-structalias.cc (escaped_return_id): New.
(find_func_aliases): Handle non-IPA return stmts by
adding to ESCAPED_RETURN.
(set_uids_in_ptset): Adjust HEAP escaping to also cover
escapes through return.
(init_base_vars): Initialize ESCAPED_RETURN.
(compute_points_to_sets): Replace ESCAPED post-processing
with recording the ESCAPED_RETURN solution.
* tree-ssa-alias.cc (ref_may_alias_global_p_1): Check
the ESCAPED_RETUNR solution.
(dump_alias_info): Dump it.
* cfgexpand.cc (update_alias_info_with_stack_vars): Update it.
* ipa-icf.cc (sem_item_optimizer::fixup_points_to_sets):
Likewise.
* tree-inline.cc (expand_call_inline): Reset it.
* tree-parloops.cc (parallelize_loops): Likewise.
* tree-sra.cc (maybe_add_sra_candidate): Check it.
* gcc.dg/tree-ssa/pta-return-1.c: New testcase.
(cherry picked from commit f7884f7673)
PR109849 shows that a loop that heavily pushes and pops from a stack
implemented by a C++ std::vec results in slow code, mainly because the
vector structure is not split by SRA and so we end up in many loads
and stores into it. This is because it is passed by reference
to (re)allocation methods and so needs to live in memory, even though
it does not escape from them and so we could SRA it if we
re-constructed it before the call and then separated it to distinct
replacements afterwards.
This patch does exactly that, first relaxing the selection of
candidates to also include those which are addressable but do not
escape and then adding code to deal with the calls. The
micro-benchmark that is also the (scan-dump) testcase in this patch
runs twice as fast with it than with current trunk. Honza measured
its effect on the libjxl benchmark and it almost closes the
performance gap between Clang and GCC while not requiring excessive
inlining and thus code growth.
The patch disallows creation of replacements for such aggregates which
are also accessed with a precision smaller than their size because I
have observed that this led to excessive zero-extending of data
leading to slow-downs of perlbench (on some CPUs). Apart from this
case I have not noticed any regressions, at least not so far.
Gimple call argument flags can tell if an argument is unused (and then
we do not need to generate any statements for it) or if it is not
written to and then we do not need to generate statements loading
replacements from the original aggregate after the call statement.
Unfortunately, we cannot symmetrically use flags that an aggregate is
not read because to avoid re-constructing the aggregate before the
call because flags don't tell which what parts of aggregates were not
written to, so we load all replacements, and so all need to have the
correct value before the call.
This version of the patch also takes care to avoid attempts to modify
abnormal edges, something which was missing in the previosu version.
gcc/ChangeLog:
2023-11-23 Martin Jambor <mjambor@suse.cz>
PR middle-end/109849
* tree-sra.cc (passed_by_ref_in_call): New.
(sra_initialize): Allocate passed_by_ref_in_call.
(sra_deinitialize): Free passed_by_ref_in_call.
(create_access): Add decl pool candidates only if they are not
already candidates.
(build_access_from_expr_1): Bail out on ADDR_EXPRs.
(build_access_from_call_arg): New function.
(asm_visit_addr): Rename to scan_visit_addr, change the
disqualification dump message.
(scan_function): Check taken addresses for all non-call statements,
including phi nodes. Process all call arguments, including the static
chain, build_access_from_call_arg.
(maybe_add_sra_candidate): Relax need_to_live_in_memory check to allow
non-escaped local variables.
(sort_and_splice_var_accesses): Disallow smaller-than-precision
replacements for aggregates passed by reference to functions.
(sra_modify_expr): Use a separate stmt iterator for adding satements
before the processed statement and after it.
(enum out_edge_check): New type.
(abnormal_edge_after_stmt_p): New function.
(sra_modify_call_arg): New function.
(sra_modify_assign): Adjust calls to sra_modify_expr.
(sra_modify_function_body): Likewise, use sra_modify_call_arg to
process call arguments, including the static chain.
gcc/testsuite/ChangeLog:
2023-11-23 Martin Jambor <mjambor@suse.cz>
PR middle-end/109849
* g++.dg/tree-ssa/pr109849.C: New test.
* g++.dg/tree-ssa/sra-eh-1.C: Likewise.
* gcc.dg/tree-ssa/pr109849.c: Likewise.
* gcc.dg/tree-ssa/sra-longjmp-1.c: Likewise.
* gfortran.dg/pr43984.f90: Added -fno-tree-sra to dg-options.
(cherry picked from commit aae723d360)
Reference to unique pointers are a known anti pattern, only the element
shall be taken by reference instead of the whole wrapper.
gcc/rust/ChangeLog:
* ast/rust-item.h: Change getter function prototype to return a
reference directly instead of a reference to the wrapper type.
* checks/errors/rust-ast-validation.cc (ASTValidation::visit): Fix
the code to accept references instead.
* hir/rust-ast-lower-base.cc (ASTLoweringBase::lower_self): Change
function implementation to return a reference.
* hir/rust-ast-lower-base.h: Accept a reference instead of a unique
pointer reference.
* resolve/rust-ast-resolve-item.cc (ResolveItem::visit): Adapt the code
to a reference instead of a unique pointer.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Reformat the upstream GCC commit f4a2ae2338
"Change MODE_BITSIZE to MODE_PRECISION for MODE_VECTOR_BOOL" change to
'gcc/rust/backend/rust-tree.cc' to clang-format's liking.
gcc/rust/
* backend/rust-tree.cc (c_common_type_for_mode): Placate clang-format.
Before the r5-3834 commit for PR63362, GCC 4.8-4.9 refuses to compile
cse.cc which contains a variable with rtx_def type, because rtx_def
contains a union with poly_uint16 element. poly_int template has
defaulted default constructor and a variadic template constructor which
could have empty parameter pack. GCC < 5 treated it as non-trivially
constructible class and deleted rtunion and rtx_def default constructors.
For the cse_insn purposes, all we need is a variable with size and alignment
of rtx_def, not necessarily rtx_def itself, which we then memset to 0 and
fill in like rtx is normally allocated from heap, so this patch for
GCC_VERSION < 5000 uses an unsigned char array of the right size/alignment.
2023-10-18 Jakub Jelinek <jakub@redhat.com>
PR bootstrap/111852
* cse.cc (cse_insn): Add workaround for GCC 4.8-4.9, instead of
using rtx_def type for memory_extend_buf, use unsigned char
arrayy with size of rtx_def and its alignment.
(cherry picked from commit bc4bd69faf)
Note that instances of both classes which have been
moved from will have (items == nullptr).
gcc/rust/ChangeLog:
* ast/rust-pattern.h
(class TupleStructPattern): Assert that items != nullptr.
(class TuplePattern): Likewise.
(TupleStructPattern::has_items): Remove.
(TuplePattern::has_tuple_pattern_items): Likewise.
* parse/rust-parse-impl.h
(Parser::parse_ident_leading_pattern):
Prevent construction of TupleStructPattern with
(items == nullptr).
(Parser::parse_pattern_no_alt): Likewise.
* ast/rust-ast-collector.cc
(TokenCollector::visit): Remove usage of
TupleStructPattern::has_items.
* ast/rust-ast-visitor.cc
(DefaultASTVisitor::visit): Likewise.
* resolve/rust-early-name-resolver.cc
(EarlyNameResolver::visit): Likewise.
gcc/testsuite/ChangeLog:
* rust/compile/pattern-struct.rs: Fix test.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
gcc/rust/ChangeLog:
* Make-lang.in: Do not build Rust library in release mode.
* ast/rust-ast.cc: Make FormatArgs inherit from AST::Expr
* ast/rust-builtin-ast-nodes.h: Improve FormatArg* nodes and helpers.
* ast/rust-fmt.cc (Pieces::collect): Fix interface to match FFI function.
* ast/rust-fmt.h (collect_pieces): Likewise.
(struct Pieces): Add append_newline parameter.
* expand/rust-macro-builtins.cc: Add proper parsing of format_args
input.
* hir/rust-ast-lower-base.cc: Include diagnostics header.
libgrust/ChangeLog:
* libformat_parser/src/lib.rs: Switch interface to use more parser
parameters.
* libformat_parser/src/bin.rs: Use new interface.
gcc/rust/ChangeLog:
* hir/rust-ast-lower-extern.h: Lower to HIR::ExternalTypeItem nodes.
* hir/tree/rust-hir-item.h (class ExternalTypeItem): Create private
visibility by default as extern types have no visibility - add a comment
about the correctness of this.
gcc/rust/ChangeLog:
* Make-lang.in: Compile new rust-lang-item.o.
* util/rust-lang-item.h: Split into header and source.
* util/rust-lang-item.cc: Cleanup parsing of lang items by using a hashmap
and returning optional values, cleanup handling of exhaustive lang item
lookups.
* hir/rust-ast-lower-base.cc (ASTLoweringBase::handle_lang_item_attribute): Use
new optional API.
Workaround for Ubuntu 18.04, since we still use it for the GCC 4.8 CI.
The default Rust package is 1.65 (and unlikely to change I assume?),
but the generic format parser library uses `is_some_and` which was
introduced in 1.70. So this is a simple reimplementation, directly taken
from the standard library sources.
libgrust/ChangeLog:
* libformat_parser/generic_format_parser/src/lib.rs: Add IsSomeAnd<T>
trait, impl it for Option<T>.
gcc/rust/ChangeLog:
* ast/rust-fmt.cc (Pieces::collect): Fix signature to take ownership
of the given string.
* ast/rust-fmt.h (struct Pieces): Store parsed string in the struct.
libgrust/ChangeLog:
* libformat_parser/src/lib.rs: Add debug prompt.
gcc/rust/ChangeLog:
* expand/rust-macro-builtins.cc (MacroBuiltin::format_args_handler):
Transform entire invocation token stream into string for the parser.
Compile libformat_parser and link to it.
gcc/rust/ChangeLog:
* Make-lang.in: Compile libformat_parser.
* ast/rust-fmt.cc: New FFI definitions.
* ast/rust-fmt.h: Likewise.
* expand/rust-macro-builtins.cc (MacroBuiltin::format_args_handler): Call
into libformat_parser.
* expand/rust-macro-builtins.h: Define format_args!() handler proper.
libgrust/ChangeLog:
* libformat_parser/Cargo.lock: New file.
* libformat_parser/Cargo.toml: New file.
* libformat_parser/generic_format_parser/Cargo.toml: New file.
* libformat_parser/generic_format_parser/src/lib.rs: New file.
* libformat_parser/src/bin.rs: New file.
* libformat_parser/src/lib.rs: New file.
This commit adds a base class for parsing the various constructs of a
Rust format string, according to the grammar in the reference:
https://doc.rust-lang.org/std/fmt/index.html#syntax
gcc/rust/ChangeLog:
* Make-lang.in: Compile rust-fmt object
* ast/rust-fmt.cc: New file.
* ast/rust-fmt.h: New file.
The signature was incorrectly using an i64 for the integer power,
instead of an i32.
gcc/testsuite/ChangeLog:
* rust/compile/torture/intrinsics-math.rs: Adjust powif64
intrinsic signature.
Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
On Fri, Feb 09, 2024 at 11:03:38AM +0100, Jakub Jelinek wrote:
> On Wed, Feb 07, 2024 at 12:43:59PM +0100, arthur.cohen@embecosm.com wrote:
> > This patch introduces one regression because generics are getting better
> > understood over time. The code here used to apply generics with the same
> > symbol from previous segments which was a bit of a hack with out limited
> > inference variable support. The regression looks like it will be related
> > to another issue which needs to default integer inference variables much
> > more aggresivly to default integer.
> >
> > Fixes#2723
> > * rust/compile/issue-1773.rs: Moved to...
> > * rust/compile/issue-1773.rs.bak: ...here.
>
> Please don't use such suffixes in the testsuite.
> Either delete the testcase, or xfail it somehow until the bug is fixed.
To be precise, I have scripts to look for backup files in the tree (*~,
*.bak, *.orig, *.rej etc.) and this stands in the way several times a day.
Here is a fix for that in patch form, tested on x86_64-linux with
make check-rust RUNTESTFLAGS='compile.exp=issue-1773.rs'
2024-02-15 Jakub Jelinek <jakub@redhat.com>
* rust/compile/issue-1773.rs.bak: Rename to ...
* rust/compile/issue-1773.rs: ... this. Add dg-skip-if directive.
gcc/rust/ChangeLog:
* parse/rust-parse-impl.h (Parser::parse_trait_item):
Handle macros in trait items similar to how its handled for trait
implementation items.
Signed-off-by: Kushal Pal <kushalpal109@gmail.com>
To use AST::Function for trait functions, we can parse trait functions
using available parse_function().
gcc/rust/ChangeLog:
* parse/rust-parse-impl.h (Parser::parse_trait_item):
Use parse_function() to parse trait functions.
Signed-off-by: Kushal Pal <kushalpal109@gmail.com>
To use AST::Function instead of AST::TraitItemFunc and
AST::TraitItemMethod, we need to provide similar visitors during
lowering and resolving phase.
gcc/rust/ChangeLog:
* hir/rust-ast-lower-implitem.cc (ASTLowerTraitItem::visit):
Provide visitor for AST::Function.
* hir/rust-ast-lower-implitem.h:
Likewise.
* resolve/rust-ast-resolve-implitem.h:
Likewise.
* resolve/rust-ast-resolve-item.cc (ResolveTraitItems::visit):
Likewise.
* resolve/rust-ast-resolve-item.h:
Likewise.
Signed-off-by: Kushal Pal <kushalpal109@gmail.com>
Since we want to use AST::Function class for trait functions as well, we
need to check against specific conditions in ASTValidation phase.
gcc/rust/ChangeLog:
* checks/errors/rust-ast-validation.cc (ASTValidation::visit):
Add checks for Trait functions.
Signed-off-by: Kushal Pal <kushalpal109@gmail.com>
We can point to generic parent types which means we need to do the shallow
resolve thing that rustc does. We have destructure which is similar to get
what the parameter type points to.
Fixes#2775
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-pattern.cc (TypeCheckPattern::visit): use destructure
gcc/testsuite/ChangeLog:
* rust/compile/issue-2775.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
This patch moves the implementation of the implitem lowering
from rust-ast-lower-implitem.h into the rust-ast-lower-implitem.cc
file.
gcc/rust/ChangeLog:
* Make-lang.in: Add rust-ast-lower-implitem.cc to list of objects.
* hir/rust-ast-lower-implitem.h (RUST_AST_LOWER_IMPLITEM_H): Remove
implementation.
* hir/rust-ast-lower-implitem.cc: Copy implementation from header.
Signed-off-by: Nobel Singh <Nobel2073@gmail.com>
This patch introduces one regression because generics are getting better
understood over time. The code here used to apply generics with the same
symbol from previous segments which was a bit of a hack with out limited
inference variable support. The regression looks like it will be related
to another issue which needs to default integer inference variables much
more aggresivly to default integer.
Fixes#2723
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-path.cc (TypeCheckExpr::resolve_segments): remove hack
gcc/testsuite/ChangeLog:
* rust/compile/issue-1773.rs: Moved to...
* rust/compile/issue-1773.rs.bak: ...here.
* rust/compile/issue-2723-1.rs: New test.
* rust/compile/issue-2723-2.rs: New test.
Previously, the default ABI was set to Rust, which is not correct for
extern blocks and extern functions. This patch changes the default
ABI to C for these cases.
gcc/rust/ChangeLog:
* hir/rust-ast-lower-base.cc (ASTLoweringBase::lower_qualifiers):
Change default ABI to C for extern functions
(ASTLoweringBase::lower_extern_block): Likewise
Signed-off-by: Nobel Singh <nobel2073@gmail.com>
Fixes#2812
gcc/rust/ChangeLog:
* parse/rust-parse-impl.h (Parser::parse_function):
Skip token if its a COMMA.
gcc/testsuite/ChangeLog:
* rust/compile/issue-2812.rs: New test.
Signed-off-by: Kushal Pal <kushalpal109@gmail.com>
If a struct type with a variant that has fields is initialized with some fields the expression HIR StructExprStructFields is checked that all the fields are assigned. However, if no fields are initialized the HIR StructExprStruct is generated. This doesn't check if the struct is a unit during typechekc and only fails at the compile stage with a ICE.
Add a check at the typecheck stage that makes sure the struct does not have a variant with fields and give an error message based on the rustc one.
We have also updated the message given in the case where one field was present to list the missing fields and match more closely the new message.
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit) Add additional check
* typecheck/rust-hir-type-check-struct-field.h: A helper method to make error added
* typecheck/rust-hir-type-check-struct.cc (TypeCheckStructExpr::resolve) Update message
gcc/testsuite/ChangeLog:
* rust/compile/missing_constructor_fields.rs: Added case with no initializers
Signed-off-by: Robert Goss <goss.robert@gmail.com>
gcc/rust/ChangeLog:
* hir/rust-ast-lower-type.cc (ASTLoweringTypeBounds::visit): fix for lifetimes
(ASTLowerWhereClauseItem::visit): fix for lifetimes
Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
This test did not compile with rustc.
gcc/testsuite/ChangeLog:
* rust/compile/torture/utf8_identifiers.rs: add mising lifetime
Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
Fixes#2381
If a struct type is initialized with one of it's fields repeated it will currently issue an error at the use site. However we would like to give the rust error code and (like rustc) show both the specifications for the field to help the user diagnose the issue.
We move the check after the index for the field has been established so we can look up if the field has already been defined and get it's location.
We update the visit method to return if it has handled an error otherwise we then output a second fatal error as not all the field in the specification have been processed.
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-struct-field.h: Allow visit to return a bool
* typecheck/rust-hir-type-check-struct.cc: Improve check of repeat fields
gcc/testsuite/ChangeLog:
* rust/compile/repeated_constructor_fields.rs: Added case with constructor field repeated
Signed-off-by: Robert Goss <goss.robert@gmail.com>
Using %lu to format size_t values breaks 32 bit targets, and %zu is not
supported by one of the hosts GCC aims to support - HPUX
gcc/rust/ChangeLog:
* backend/rust-compile-base.cc (HIRCompileBase::resolve_method_address):
Cast size_t value to unsigned long.
* expand/rust-proc-macro.cc (load_macros): Likewise.
* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit): Likewise.
gcc/rust/ChangeLog:
* checks/errors/rust-ast-validation.cc (ASTValidation::visit):
Enclose const in single quotes.
gcc/testsuite/ChangeLog:
* rust/compile/const_trait_fn.rs:
Enclose const in single quotes.
Signed-off-by: Kushal Pal <kushalpal109@gmail.com>
This uses a stringstream instead of the older, better and more readable
`sprintf` version as the format overflow warning in current GCC is
overzealous and triggered on that code, despite the non-zero allocation.
Even using an unsigned value instead of a signed one for the `size`
variable caused issues, so switching to this is simpler.
gcc/rust/ChangeLog:
* expand/rust-proc-macro.cc: Use stringstream instead of sprintf.
* rust-system.h: Include <iomanip>.
If newline strings are encountered while lexing, the lexer now handles
newline characters by incrementing current line number. This provides
correct line number when displaying errors. If the lexer encounters end
of file before string end, then it will use the start of the string as
the location to an report error.
gcc/rust/ChangeLog:
* lex/rust-lex.cc (Lexer::parse_byte_string): Handle newline
while parsing byte strings
(Lexer::parse_string): Handle newline while parsing strings
Signed-off-by: Nirmal Patel <nirmal@nirmal.dev>
gcc/rust/ChangeLog:
* backend/rust-compile-expr.cc (CompileExpr::visit): Use new API.
* typecheck/rust-tyty-call.cc (TypeCheckCallExpr::visit): Use new API.
* typecheck/rust-tyty-cmp.h: Remove old API.
* typecheck/rust-tyty.cc (FnPtr::is_equal): Use new API.
* typecheck/rust-tyty.h: Remove old API.
* typecheck/rust-unify.cc (UnifyRules::expect_fnptr): Use new API.
Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
There was a mismatch whether lifetime 'static is parsed as "static"
or "'static".
gcc/rust/ChangeLog:
* parse/rust-parse-impl.h (Parser::lifetime_from_token): Fix matched pattern.
Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
gcc/rust/ChangeLog:
* hir/tree/rust-hir-item.h: Ad lifetime getter.
* hir/tree/rust-hir-path.h: Make getter const ref.
* hir/tree/rust-hir.h: Const ref and new getter.
Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
Many visit functions in the expand visitor simply visit their components
like the default visitor. Making the expand visitor inherit from the
default visitor allows us to keep all visitor in sync without having to
change every visitor.
gcc/rust/ChangeLog:
* expand/rust-expand-visitor.cc (ExpandVisitor::go): Add call to visit
on the crate.
(ExpandVisitor::visit): Remove some visit functions in favor of their
default visitor counterpart.
* expand/rust-expand-visitor.h (class ExpandVisitor): Inherit from
default visitor and remove now useless function prototypes.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
The default resolver put some scope in place but mostly has traversal
functions similar to the default ast visitor, making it inherit from the
default visitor allows us to avoid code duplication.
gcc/rust/ChangeLog:
* resolve/rust-default-resolver.cc (DefaultResolver::visit): Remove
duplicated functions.
* resolve/rust-default-resolver.h (class DefaultResolver): Make the
default resolver inherit from the default visitor.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Fixes issue #2040
Add check to assure that a function cant be declared const inside trait impl
blocks.
gcc/rust/ChangeLog:
* checks/errors/rust-ast-validation.cc (ASTValidation::visit): Add
check for const funtion.
gcc/testsuite/ChangeLog:
* rust/compile/issue-2040.rs: New test.
Signed-off-by: Nobel Singh <nobel2073@gmail.com>
Function body check emit an error message when a required function body
is missing.
gcc/testsuite/ChangeLog:
* rust/compile/functions_without_body.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add checks in the ast validation pass to error out with functions
(either free or associated) without a definition.
gcc/rust/ChangeLog:
* checks/errors/rust-ast-validation.cc (ASTValidation::visit): Add
a validation check and emit an error depending on the context.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Missing body on a function should be rejected at a later stage in the
compiler, not during parsing.
gcc/rust/ChangeLog:
* ast/rust-ast-collector.cc (TokenCollector::visit): Adapt defintion
getter.
* ast/rust-ast-visitor.cc (DefaultASTVisitor::visit): Likewise.
* expand/rust-cfg-strip.cc (CfgStrip::visit): Likewise.
* expand/rust-expand-visitor.cc (ExpandVisitor::visit): Likewise.
* hir/rust-ast-lower-implitem.h: Likewise.
* hir/rust-ast-lower-item.cc (ASTLoweringItem::visit): Likewise.
* resolve/rust-ast-resolve-item.cc (ResolveItem::visit): Likewise.
* resolve/rust-ast-resolve-stmt.h: Likewise.
* resolve/rust-default-resolver.cc (DefaultResolver::visit): Likewise.
* util/rust-attributes.cc (AttributeChecker::visit): Likewise.
* parse/rust-parse-impl.h: Allow empty function body during parsing.
* ast/rust-ast.cc (Function::Function): Constructor now take an
optional for the body.
(Function::operator=): Adapt to new optional member.
(Function::as_string): Likewise.
* ast/rust-item.h (class Function): Make body optional and do not
rely on nullptr anymore.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
We already have some compile tests but it lacked an execution test to
ensure everything compiles correctly to the correct value.
gcc/testsuite/ChangeLog:
* rust/execute/torture/name_resolution.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Local variables and functions or global variables have different
resolution when binded to a variable. This was not covered before, even
though it was handled by the new name resolution. This commit highlight
this behavior from the new name resolution mechanism.
gcc/testsuite/ChangeLog:
* rust/compile/name_resolution11.rs: New test.
* rust/compile/name_resolution12.rs: New test.
* rust/compile/name_resolution13.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Many visit functions in the early name resolver are just plain old
traversal visit functions like the ones from the default visitor.
gcc/rust/ChangeLog:
* resolve/rust-early-name-resolver.cc (EarlyNameResolver::resolve_generic_args):
Move function.
(EarlyNameResolver::resolve_qualified_path_type): Likewise.
(EarlyNameResolver::visit): Add a top level visit function for crate
and remove duplicated code.
* resolve/rust-early-name-resolver.h (class EarlyNameResolver): Update
overriden function list.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Make the attribute checker visitor inherit from the default visitor
in order to keep visit behavior shared.
gcc/rust/ChangeLog:
* util/rust-attributes.cc (AttributeChecker::visit): Add visit function
for crates.
* util/rust-attributes.h (class AttributeChecker): Update function
prototypes.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
The feature gating behavior may be shortened and kept cleaner using the
default visitor. This means less maintenance on visit functions as the
traversal is shared by multiple visitors.
gcc/rust/ChangeLog:
* checks/errors/rust-feature-gate.cc (FeatureGate::visit): Add a visit
function for the crate level.
(FeatureGate::check): Add call to crate visit.
* checks/errors/rust-feature-gate.h (class FeatureGate): Remove now
useless visit functions (traversal only).
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Const fn declaration in trait declarations shall emit an error. This new
test highlight this behavior.
gcc/testsuite/ChangeLog:
* rust/compile/const_trait_fn.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add a new check in AST validation pass that checks that no function
declaration in traits are declared const.
gcc/rust/ChangeLog:
* checks/errors/rust-ast-validation.cc (ASTValidation::visit): Add
const check.
* checks/errors/rust-ast-validation.h: Add visit function prototype.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Functions that are both async and const shall be rejected during the
AST validation pass. This new test highlight this behavior.
gcc/testsuite/ChangeLog:
* rust/compile/const_async_function.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add a check during AST validation pass to ensure functions are either
const or async but not both.
gcc/rust/ChangeLog:
* checks/errors/rust-ast-validation.cc (ASTValidation::visit): Add
async const check.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
We need to account for const specifiers in async parsing as const
can be used in the syntax before the async keyword.
gcc/rust/ChangeLog:
* parse/rust-parse-impl.h (Parser::parse_vis_item): Allow parsing async
items in const.
(Parser::parse_async_item): Account for const offset during async
lookahead.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
A function cannot be both async and const, however this should not be
handled in the parser but rather at a later stage in the compiler. This
commit change the AsyncConstStatus in the AST and the HIR to allows a
function to be both async and const.
gcc/rust/ChangeLog:
* ast/rust-ast-builder.cc (AstBuilder::fn_qualifiers): Change
constructor to match the new arguments.
* ast/rust-ast-collector.cc (TokenCollector::visit): Change behavior
to handle both const and async specifiers at the same time.
* ast/rust-ast.cc (FunctionQualifiers::as_string): Likewise.
* ast/rust-item.h (class FunctionQualifiers): Remove AsyncConstStatus
and replace it with both Async and Const status. Also change the safety
arguments to use an enum instead of a boolean.
* hir/rust-ast-lower-base.cc (ASTLoweringBase::lower_qualifiers):
Update constructor call.
* hir/tree/rust-hir-item.h: Add Const and Async status, remove
AsyncConstStatus, update the constructor.
* hir/tree/rust-hir.cc (FunctionQualifiers::as_string): Update with
the new status.
* parse/rust-parse-impl.h (Parser::parse_function_qualifiers): Update
constructor call.
* util/rust-common.h (enum Mutability): Make an enum class.
(enum class): Add Async and Const enum class to avoid booleans.
(enum Unsafety): Change to an enum class.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
When making more desugaring for the HIR we can need to add new Let bindings
which will require namesolution information but also rib information for
which block the let binding is associated which was very unnessecary. This
patch simply updates the BLOCK_CONTEXT of the current scope as we are
compiling and encounter HIR::LetStmts instead of trying to do it all
upfront which lots of wierd checks
gcc/rust/ChangeLog:
* backend/rust-compile-base.cc (HIRCompileBase::compile_locals_for_block): removed
* backend/rust-compile-base.h: update header
* backend/rust-compile-block.cc (CompileBlock::visit): remove old logic
* backend/rust-compile-expr.cc (CompileExpr::generate_closure_function): likewise
* backend/rust-compile-stmt.cc (CompileStmt::visit): likewise
* backend/rust-compile-var-decl.h: ensure we setup tuple bindings correctly
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
Add a new test to check for unsafe modules during AST validation pass.
gcc/testsuite/ChangeLog:
* rust/compile/unsafe_module.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
An error should be emitted on unsafe modules during the AST validation
pass as the syntax allows those even though they're not alowed later down
the line.
gcc/rust/ChangeLog:
* ast/rust-item.h: Add safety getter to modules.
* checks/errors/rust-ast-validation.cc (ASTValidation::visit): Check
a module's safety and emit an error when meeting an unsafe module.
* checks/errors/rust-ast-validation.h: Add function prototype.
* parse/rust-parse-impl.h (Parser::parse_module): Move the module locus
to the first token instead of the mod keyword.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Unsafe module are rejected at a later stage but could not be parsed
properly. This commit changes the parser in order to allow unsafe module
in the AST.
gcc/rust/ChangeLog:
* parse/rust-parse-impl.h (Parser::parse_vis_item): Dispatch to parse
module when meeting an unsafe module.
(Parser::parse_module): Set unsafe status when the parser encounter an
unsafe keyword.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
The rust syntax allows unsafe module even if those are rejected at a
later stage.
gcc/rust/ChangeLog:
* ast/rust-item.h: Add safety status to Modules in the AST.
* parse/rust-parse-impl.h (Parser::parse_module): Adapt constructors.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
gcc/rust/ChangeLog:
* resolve/rust-late-name-resolver-2.0.cc (Late::visit): Store mappings
after having resolved them.
* resolve/rust-late-name-resolver-2.0.h: Add `TypePath` visitor.
gcc/rust/ChangeLog:
* resolve/rust-name-resolution-context.h: Store a reference to the
mappings.
* resolve/rust-name-resolution-context.cc
(NameResolutionContext::NameResolutionContext): Likewise.
gcc/rust/ChangeLog:
* Make-lang.in: Compile late name resolver.
* resolve/rust-late-name-resolver-2.0.cc: New file.
* resolve/rust-late-name-resolver-2.0.h: New file.
Not sure if dealing with "labels" is the proper way of doing so, so we
might eventually change this to use `resolver.values` later on.
gcc/rust/ChangeLog:
* resolve/rust-name-resolution-context.h: Add a Labels stack.
Fixes issue #2650
The parser now parses ASYNC functions. Added ASYNC case to parse_item
Added a new function parse_async_item which is called in
parse_vis_item to handle the ASYNC case. Parse_async_item
also checks the current Rust edition and generates an error if the
edition is 2015
gcc/rust/ChangeLog:
* parse/rust-parse-impl.h (Parser::parse_item): Likewise.
(Parser::parse_vis_item): Likewise.
(Parser::parse_async_item): Likewise.
* parse/rust-parse.h: Made declaration for parse_async_item.
gcc/testsuite/ChangeLog:
* rust/compile/issue-2650-1.rs: New test.(edition=2018)
* rust/compile/issue-2650-2.rs: New test.(edition=2015)
Signed-off-by: M V V S Manoj Kumar <mvvsmanojkumar@gmail.com>
The old "keyword" list was used for the lexer, and could therefore not
be used with keyword spanning over multiple tokens as those tokens should
remain lexed as is. Hence the introduction of a new list macro for
keyword exclusive tasks. This also means we can no longer match a token
id for each keyword. The token id map has been renamed to keep it's
properties.
gcc/rust/ChangeLog:
* lex/rust-lex.cc (Lexer::classify_keyword): Update keyword map name.
* lex/rust-token.h (enum PrimitiveCoreType): Remove some deprecated
comments.
* util/rust-keyword-values.cc (get_keywords): Update the keyword map
name.
(RS_TOKEN): Define as empty
(RS_TOKEN_KEYWORD_2015): Add the emission value.
(RS_TOKEN_KEYWORD_2018): Likewise.
* util/rust-keyword-values.h (RS_KEYWORD_LIST): Introduce the keyword
list.
(RS_TOKEN_KEYWORD_2018): Define multiple new keywords.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Retrieving a weak keyword value is done using raw values. Introducing a
list of weak keywords means this could change.
gcc/rust/ChangeLog:
* util/rust-keyword-values.h (class WeakKeywords): Add new class with
weak keyword constexpr.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Raw values cannot be understood easily by most tools. This commit replace
some raw values with their variable counterpart.
gcc/rust/ChangeLog:
* ast/rust-ast-collector.cc (TokenCollector::visit): Replace raw value
with keyword call.
* ast/rust-ast.h: Likewise.
* parse/rust-parse-impl.h (Parser::parse_path_ident_segment): Likewise.
(Parser::parse_macro_match_fragment): Likewise.
(Parser::parse_extern_crate): Likewise.
(Parser::parse_use_tree): Likewise.
(Parser::parse_const_item): Likewise.
(Parser::parse_literal_expr): Likewise.
(Parser::parse_maybe_named_param): Likewise.
(Parser::parse_pattern_no_alt): Likewise.
(Parser::left_denotation): Likewise.
(Parser::parse_path_in_expression_pratt): Likewise.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Make the underscore token a 2015 keyword.
gcc/rust/ChangeLog:
* lex/rust-token.h (enum PrimitiveCoreType): Change macro for
underscore in token list.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
It might be required in the future to get only the keywords from a
specific edition. To do so we need a mean to differentiate keywords based
on their edition. This commit changes the existing keyword macro to
allow such behavior.
gcc/rust/ChangeLog:
* lex/rust-token.h (enum PrimitiveCoreType): Change enum macro calls.
(RS_TOKEN_KEYWORD): Remove generic token keyword macro.
(RS_TOKEN_KEYWORD_2015): Introduce keywords for edition 2015.
(RS_TOKEN_KEYWORD_2018): Likewise with edition 2018.
* lex/rust-token.cc (RS_TOKEN_KEYWORD): Remove old macro definition.
(RS_TOKEN_KEYWORD_2015): Replace with 2015 definition...
(RS_TOKEN_KEYWORD_2018): ... and 2018 definition.
* util/rust-keyword-values.cc (RS_TOKEN_KEYWORD): Likewise.
(RS_TOKEN_KEYWORD_2015): Likewise.
(RS_TOKEN_KEYWORD_2018): Likewise.
* util/rust-keyword-values.h (RS_TOKEN_KEYWORD): Likewise.
(RS_TOKEN_KEYWORD_2015): Likewise.
(RS_TOKEN_KEYWORD_2018): Likewise.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
TOK suffix was chosen to disambiguate some identifiers with c++ reserved
keyword. Even though this list lies within the rust-token header, this
macro is used in many context sometimes unrelated with the lexer and
tokens. This TOK suffix may appear surprising in such context.
gcc/rust/ChangeLog:
* lex/rust-token.h (enum PrimitiveCoreType): Change keyword suffix from
tok to kw.
* ast/rust-ast-collector.cc (TokenCollector::visit): Update suffix to
match the new declaration.
* lex/rust-lex.cc (Lexer::parse_raw_identifier): Likewise.
* parse/rust-parse-impl.h (can_tok_start_type): Likewise.
(Parser::parse_item): Likewise.
(Parser::parse_vis_item): Likewise.
(Parser::parse_extern_crate): Likewise.
(Parser::parse_function): Likewise.
(Parser::parse_function_qualifiers): Likewise.
(Parser::parse_struct): Likewise.
(Parser::parse_enum): Likewise.
(Parser::parse_static_item): Likewise.
(Parser::parse_trait_item): Likewise.
(Parser::parse_inherent_impl_item): Likewise.
(Parser::parse_trait_impl_item): Likewise.
(Parser::parse_extern_block): Likewise.
(Parser::parse_external_item): Likewise.
(Parser::parse_stmt): Likewise.
(Parser::parse_return_expr): Likewise.
(Parser::parse_match_expr): Likewise.
(Parser::parse_type): Likewise.
(Parser::parse_for_prefixed_type): Likewise.
(Parser::parse_type_no_bounds): Likewise.
(Parser::parse_stmt_or_expr): Likewise.
* parse/rust-parse.cc (peculiar_fragment_match_compatible): Likewie.
* util/rust-token-converter.cc (convert): Likewise.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Unions with zero fields are forbidden. Add regression test for empty
unions.
gcc/rust/ChangeLog:
* checks/errors/rust-ast-validation.cc (ASTValidation::visit): Add
zero field check during ast validation pass.
* checks/errors/rust-ast-validation.h: Add union visit function
prototype.
gcc/testsuite/ChangeLog:
* rust/compile/const_generics_8.rs: Fill the union with dummy values.
* rust/compile/empty_union.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add a new regression test for the error message in regular function
variadic errors during ast validation pass.
gcc/testsuite/ChangeLog:
* rust/compile/non_foreign_variadic_function.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Variadic regular functions were recently added in the parser as they
should be rejected in the ast validation pass. This commit add the ast
validation pass rejecting this kind of variadic arguments.
gcc/rust/ChangeLog:
* checks/errors/rust-ast-validation.cc (ASTValidation::visit): Add
ast validation pass to reject variadic arguments on regular functions.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Reject rust code with associated items on auto traits.
gcc/rust/ChangeLog:
* checks/errors/rust-ast-validation.cc (ASTValidation::visit): Add auto
trait associated item check in AST validation pass.
* parse/rust-parse-impl.h: Remove old error emission done during
parsing pass.
gcc/testsuite/ChangeLog:
* rust/compile/auto_trait_invalid.rs: Update old test with updated
error message.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add a new regression test to highlight the error behavior with a super
trait on an auto trait.
gcc/testsuite/ChangeLog:
* rust/compile/auto_trait_super_trait.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Reject auto traits containing a super trait bound during AST validation
pass.
gcc/rust/ChangeLog:
* checks/errors/rust-ast-validation.cc (ASTValidation::visit): Reject
auto traits with super traits.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Generics are forbidden on auto traits and an error should be emitted.
This commit highlight this behavior.
gcc/testsuite/ChangeLog:
* rust/compile/generic_auto_trait.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Generic parameters are not allowed on auto traits, the compiler should
emit an error.
gcc/rust/ChangeLog:
* checks/errors/rust-ast-validation.cc (ASTValidation::visit): Add
check for generics on auto traits.
* checks/errors/rust-ast-validation.h: Add visit function prototype.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Bootstrap was failing because the vector did not allocate the internal
buffer and was holding a null pointer.
Commit to fixup is b71fd2afa8
gcc/rust/ChangeLog:
* expand/rust-proc-macro.cc (generate_proc_macro_decls_symbol): Resize
the vector and initialize it with dummy data before changing it.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
gcc/rust/ChangeLog:
* ast/rust-ast.h: Change Path API to be more consistent.
* ast/rust-path.h: Likewise.
* ast/rust-ast-collector.cc (TokenCollector::visit): Use new API.
* resolve/rust-ast-resolve-item.cc (ResolveItem::visit): Likewise.
* resolve/rust-ast-resolve-path.cc (ResolvePath::resolve_path): Likewise.
* resolve/rust-forever-stack.hxx: Likewise.
Add new tests to highlight the behavior of errors thrown when meeting a
self pointer.
gcc/testsuite/ChangeLog:
* rust/compile/self_const_ptr.rs: New test.
* rust/compile/self_mut_ptr.rs: New test.
* rust/compile/self_ptr.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Self parameter parsing errors may come from different situations, which
should not be handled in the same way. It is now possible to
differentiate a missing self parameter from a self pointer or a parsing
error.
gcc/rust/ChangeLog:
* parse/rust-parse-impl.h (Parser::parse_function): Early return on
unrecoverable errors.
(Parser::parse_trait_item): Likewise.
(Parser::parse_self_param): Update return type.
* parse/rust-parse.h (enum ParseSelfError): Add enumeration to describe
different self parameter parsing errors.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
This new test highlight the parser's behavior around public trait types.
gcc/testsuite/ChangeLog:
* rust/compile/trait_pub_type.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
The compiler shall parse visibility modifiers on trait items and reject
those at a later stage (ast validation).
gcc/rust/ChangeLog:
* ast/rust-item.h (struct Visibility): Move Visibility from here...
* ast/rust-ast.h (struct Visibility): ...to here.
* parse/rust-parse-impl.h (Parser::parse_trait_item): Parse visibility
before giving it back to the item parsing function.
(Parser::parse_trait_type): Add visibility modifier.
* parse/rust-parse.h (RUST_PARSE_H): Change function prototype.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
This new regression test highlight the behavior fixed for float
disambiguation with empty floating point.
gcc/testsuite/ChangeLog:
* rust/compile/tuple_float_index.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
When a float has a floating point but no value after it, a zero was added
this lead to errors when trying to disambiguate a float into a tuple
index.
gcc/rust/ChangeLog:
* lex/rust-lex.cc (Lexer::parse_decimal_int_or_float): Remove
additional zero after empty floating point.
* parse/rust-parse-impl.h (Parser::left_denotation): Handle float with
empty floating point.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Move default ast visitor template implementation to headers in order to
match the codebase and avoid link errors.
gcc/rust/ChangeLog:
* ast/rust-ast-visitor.cc (DefaultASTVisitor::visit): Move from here...
* ast/rust-ast-visitor.h: ... to here.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Templated functions shall remain in header files to stay in line with the
rest of the codebase.
gcc/rust/ChangeLog:
* ast/rust-ast-collector.cc (TokenCollector::visit): Move to header
file.
(TokenCollector::visit_items_joined_by_separator): Likewise.
(TokenCollector::visit_as_line): Likewise.
(TokenCollector::visit_items_as_lines): Likewise.
(TokenCollector::visit_items_as_block): Likewise.
* ast/rust-ast-collector.h: Add implementation.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Make self param and variadic param Param, introduce Param class and make
function parameters param too.
Self can now be represented as a standard parameter and is thus no longer
required as a separate function attribute.
Prevent self pointers and allow self in standard functions during parsing
so they could be rejected at a later stage.
gcc/rust/ChangeLog:
* ast/rust-ast-collector.cc (TokenCollector::visit): Add visitor for
VariadicParam and remove Self parameter visitor from Function visit.
* expand/rust-cfg-strip.cc (CfgStrip::maybe_strip_self_param): Remove
function.
(CfgStrip::maybe_strip_trait_method_decl): Remove self parameter visit.
(CfgStrip::maybe_strip_function_params): Handle new function
parameters.
(CfgStrip::visit): Handle VariadicParam, SelfParam and FunctionParam.
* expand/rust-expand-visitor.cc (ExpandVisitor::expand_self_param):
Remove function.
(ExpandVisitor::expand_trait_method_decl): Do not visit self parameter.
(ExpandVisitor::visit): Add visit for VariadicParam, FunctionParam and
SelfParam.
(ExpandVisitor::expand_function_params): Visit parameters instead.
* expand/rust-expand-visitor.h: Update function prototypes.
* resolve/rust-ast-resolve-item.cc (ResolveItem::visit): Update visit
with new parameters.
(ResolveTraitItems::visit): Likewise.
* resolve/rust-early-name-resolver.cc (EarlyNameResolver::visit):
Update visit functions with the new visitor functions for VariadicParam
SelfParam and FunctionParam.
* resolve/rust-early-name-resolver.h: Update function prototypes.
* ast/rust-ast-visitor.cc (DefaultASTVisitor::visit): Update visitor
according to the new function parameter structures.
* ast/rust-ast-visitor.h: Update prototypes and add visitor virtual
functions for SelfParam, FunctionParam and VariadicParam.
* ast/rust-ast.cc (Function::Function): Move constructor in
implementation instead of header.
(Function::operator=): Likewise.
(Function::as_string): Update function with pointer dereference.
(VariadicParam::as_string): Likewise.
(TraitFunctionDecl::as_string): Likewise.
(TraitMethodDecl::as_string): Likewise.
(FunctionParam::accept_vis): Add function for visitor.
(SelfParam::accept_vis): Likewise.
(VariadicParam::accept_vis): Likewise.
(TraitItemFunc::TraitItemFunc): Move constructor to implementation
file.
(TraitItemFunc::operator=): Likewise.
(TraitItemMethod::TraitItemMethod): Likewise.
(TraitItemMethod::operator=): Likewise.
* ast/rust-item.h (class Function): Remove self optional member.
(class TraitMethodDecl): Likewise.
(class TraitFunctionDecl): Likewise.
(class Param): Add abstract parameter class.
(class SelfParam): Inherit from Param and remove parameter common
members.
(class FunctionParam): Likewise.
(class VariadicParam): Likewise.
(struct Visibility): Move structure declaration.
(class VisItem): Likewise.
* checks/errors/rust-ast-validation.cc (ASTValidation::visit): Add
a self parameter check during AST validation.
* checks/errors/rust-ast-validation.h: Add function prototype.
* expand/rust-derive-clone.cc (DeriveClone::clone_fn): Update function
constructor.
* hir/rust-ast-lower-base.cc (ASTLoweringBase::lower_self): Rework
function for the new parameters.
(ASTLoweringBase::visit): Add visit functions for VariadicParam,
FunctionParam and SelfParam.
* hir/rust-ast-lower-base.h: Update function prototypes.
* parse/rust-parse-impl.h (Parser::parse_function): Update function
according to new function representation.
(Parser::parse_function_param): Return vector of abstract param instead
of FunctionParam.
(Parser::parse_method): Update according to new representation.
(Parser::parse_trait_item): Likewise.
(Parser::parse_self_param): Error out with
self pointers and prevent the lexer from eating regular function
parameters. Update return type.
* parse/rust-parse.h: Update function return types.
* ast/rust-ast-collector.h: Add VariadicParam visit prototype.
* ast/rust-ast.h (struct Visibility): Move struct declaration.
(class VisItem): Likewise.
* ast/rust-expr.h: Update included files.
* checks/errors/rust-feature-gate.h: Add visitor functions for
SelfParam, FunctionParam and VariadicParam.
* expand/rust-cfg-strip.h: Update function prototypes.
* expand/rust-derive.h: Likewise.
* hir/rust-ast-lower-implitem.h: Handle special arguments.
* hir/rust-ast-lower-item.cc (ASTLoweringItem::visit): Likewise.
* metadata/rust-export-metadata.cc (ExportContext::emit_function):
Likewise.
* resolve/rust-ast-resolve-base.cc (ResolverBase::visit): Add visitor
functions.
* resolve/rust-ast-resolve-base.h: Update prototypes.
* resolve/rust-ast-resolve-stmt.h: Handle new parameter kind.
* resolve/rust-default-resolver.cc (DefaultResolver::visit): Likewise.
* resolve/rust-default-resolver.h: Update prototype.
* util/rust-attributes.cc (AttributeChecker::visit): Add visitor
functions for SelfParam and VariadicParam.
* util/rust-attributes.h: Add visit prototypes.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Variadics are forbidden alone as well as non final position, this should
be checked during ast validation.
gcc/rust/ChangeLog:
* checks/errors/rust-ast-validation.cc (ASTValidation::visit): Add
check for additional named argument as well as variadic argument's
position.
* checks/errors/rust-ast-validation.h: Add visit function prototype for
external functions.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Some construct are forbidden in trait context (eg. pub, async...) and
we'll need to reject those. To do so we need to identify a trait context.
gcc/rust/ChangeLog:
* ast/rust-ast-visitor.cc (ContextualASTVisitor::visit): Push the new
trait context when visiting a trait.
* ast/rust-ast-visitor.h: Add visit function prototype and TRAIT
context.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
An error message should be emitted when the rust code contains invalid
label name. Add a new test for this behavior.
gcc/testsuite/ChangeLog:
* rust/compile/invalid_label_name.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Loop label error reporting during ast validation was done at loop label
level. It lead to some innacurate error reporting in break loop labels
due to the way the label is built.
gcc/rust/ChangeLog:
* checks/errors/rust-ast-validation.cc (ASTValidation::visit): Change
reported error location to the lifetime location.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Prevent from using reserved keyword in label name.
gcc/rust/ChangeLog:
* ast/rust-ast-visitor.cc (DefaultASTVisitor::visit): Check if there is
a label before visit.
* checks/errors/rust-ast-validation.cc (ASTValidation::visit): Emit an
error when a label has a forbidden name.
* checks/errors/rust-ast-validation.h: Add function prototype.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Break expression were using a raw lifetime value instead of a loop label
this behavior would have lead to some errors in ast validation.
gcc/rust/ChangeLog:
* ast/rust-expr.h (class BreakExpr): Change Lifetime to LoopLabel.
* hir/rust-ast-lower-expr.cc (ASTLoweringExpr::visit): Lower lifetime
inside the label instead.
* resolve/rust-ast-resolve-expr.cc (ResolveExpr::visit): Resolve the
inner lifetime.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Change the keyword values from a raw string value to their matching const
value in utils.
gcc/rust/ChangeLog:
* lex/rust-lex.cc (Lexer::parse_raw_identifier): Use const value.
* parse/rust-parse-impl.h (Parser::parse_simple_path_segment):
Likewise.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Some part of the code requires the token id behind a given keyword, a map
keep the "set" aspect whilst providing this additional feature.
gcc/rust/ChangeLog:
* lex/rust-lex.cc (RS_TOKEN): Remove local map.
(RS_TOKEN_KEYWORD): Likewise.
(Lexer::classify_keyword): Change call to utils.
* util/rust-keyword-values.cc (get_keywords): Add init function.
(RS_TOKEN_KEYWORD): Call to X macro.
* util/rust-keyword-values.h: Change from set to a map.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
We don't require that local set anymore.
gcc/rust/ChangeLog:
* checks/errors/rust-ast-validation.cc (RS_TOKEN): Remove locale set.
(RS_TOKEN_KEYWORD): Likewise.
(ASTValidation::visit): Change keyword set call to the one from utils.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Much like attributes values, keywords are known beforehand and never
change. Instead of relying on handcrafted string we could centralize
everything in one place. We may require to check whether a word is a
keyword, which can now be done easily thanks to the keyword set.
gcc/rust/ChangeLog:
* Make-lang.in: Add rust-keyword-values.cc to the list.
* util/rust-keyword-values.cc: New file.
* util/rust-keyword-values.h: New file.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
This file was missing a licence text and it's header guard was not
matching the file name.
gcc/rust/ChangeLog:
* util/rust-attribute-values.h (RUST_ATTRIBUTES_VALUE_H): Remove old
header guard.
(RUST_ATTRIBUTE_VALUES_H): Add new one.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Lifetime name are restricted and cannot be keyword, this commit add a
test failing the ast validation pass due to some keyword name.
gcc/testsuite/ChangeLog:
* rust/compile/lifetime_name_validation.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Variadic arguments may have a name or a pattern. This commit provides two
new tests in order to ensure their correct behavior.
gcc/testsuite/ChangeLog:
* rust/compile/pattern_variadic.rs: New test.
* rust/execute/torture/named_variadic.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
This test ensure that extern C named variadics are parsed correctly.
gcc/testsuite/ChangeLog:
* rust/compile/extern_c_named_variadic.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add ability to parse named variadic parameters in extern c functions.
gcc/rust/ChangeLog:
* parse/rust-parse-impl.h (Parser::parse_named_function_param): Add
new parsing ability.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
This new test highlight the behavior of the new parser and it's ability
to parse variadic rust functions.
gcc/testsuite/ChangeLog:
* rust/compile/parse_variadic_function.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
The new variadic representation has introduced multiple issues and ICE
into the codebase. Some early passes in the compiler depend on the
parameters all having a type and being an actual parameter.
gcc/rust/ChangeLog:
* ast/rust-ast.cc (ExternalFunctionItem::as_string): Adapt as_string
function to the new ast representation.
(NamedFunctionParam::as_string): Likewise.
* ast/rust-item.h: Add a function to test whether a FunctionParam has
a name pattern.
* expand/rust-cfg-strip.cc (CfgStrip::visit): Adapt cfg strip visitor
for the new variadic arguments.
* hir/rust-ast-lower-extern.h: Adapt lowering to the new variadic
function representation.
* metadata/rust-export-metadata.cc (ExportContext::emit_function):
Change call to constructor.
* parse/rust-parse-impl.h (Parser::parse_named_function_param): Change
NamedFunctionParam parsing to accomodate new variadic representation.
(Parser::parse_external_item): Change external item parsing to use the
new NamedFunctionParam variadics.
* parse/rust-parse.h: Add new parsing function prototypes.
* ast/rust-ast-collector.cc (TokenCollector::visit): Rework token
collection to take into account variadic parameters.
* ast/rust-ast-visitor.cc: Likewise.
* expand/rust-expand-visitor.cc (ExpandVisitor::visit): Change function
bound to avoid getting the type of a variadic parameter.
* resolve/rust-ast-resolve-item.cc (ResolveExternItem::visit):
Likewise.
* resolve/rust-early-name-resolver.cc (EarlyNameResolver::visit):
Likewise.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
This was made to align NamedFunctionParam with FunctionParam.
gcc/rust/ChangeLog:
* ast/rust-item.h (class NamedFunctionParam): Add variadic boolean and
another constructor.
* hir/rust-ast-lower-extern.h: Avoid last parameter when variadic.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
This function provides an easy way to check for a function's varidicity.
gcc/rust/ChangeLog:
* ast/rust-item.h: Add a getter to check if a given function is
variadic.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Variadic functions were not parsed because it is an unstable feature.
While it is still unstable, it is required in order to parse libcore.
gcc/rust/ChangeLog:
* parse/rust-parse-impl.h (Parser::parse_function_param): Parse
variadic functions.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Variadic were represented at the function level while retaining most
informations of a given parameter.
gcc/rust/ChangeLog:
* ast/rust-item.h (class FunctionParam): Add some informations to
function parameters in order to be able to store variadic argument as
a function parameter.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
This new regression test highlight the fixed behavior for 2709.
gcc/testsuite/ChangeLog:
* rust/compile/issue-2709.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Use the new contextual ast visitor to reduce the amount of code in the
ast validation visitor.
gcc/rust/ChangeLog:
* checks/errors/rust-ast-validation.cc (ASTValidation::visit): Adapt
the call to the new visit functions.
(ASTValidation::check): Launch the parent class visitor root function.
* checks/errors/rust-ast-validation.h (class ASTValidation): Inherit
from the contextual visitor.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
This visitor is intended to be used by other visitors that require
context at some point for a given item.
gcc/rust/ChangeLog:
* ast/rust-ast-visitor.cc (ContextualASTVisitor::visit): Add multiple
context saving calls.
* ast/rust-ast-visitor.h (class DefaultASTVisitor): Make visit
functions virtual.
(class ContextualASTVisitor): Add a stack like container for the
current context chain.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
This will allow us to derive other visitors from it and overload only a
few selected visit methods.
gcc/rust/ChangeLog:
* Make-lang.in: Add the new visitor object file.
* ast/rust-ast-visitor.h (class DefaultASTVisitor): Create the default
visitor class.
* ast/rust-ast.h: Add a new reference getter for visitor pattern.
* ast/rust-ast-visitor.cc: New file.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Visitor pattern requires a getter to children using a mutable reference.
gcc/rust/ChangeLog:
* ast/rust-ast.h: Add some missing mutable reference getters.
* ast/rust-expr.h: Likewise.
* ast/rust-item.h: Likewise.
* ast/rust-path.h: Likewise.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
The parameter type was used instead of the default value.
gcc/rust/ChangeLog:
* ast/rust-ast-collector.cc (TokenCollector::visit): Check for presence
of a type and use the default value instead of the type.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Associated const with no value that are not in trait impl are prohibited.
gcc/rust/ChangeLog:
* checks/errors/rust-ast-validation.cc (ASTValidation::check): Launch
check over the whole given crate.
(ASTValidation::visit): Implement visitor for some members of the ast.
* checks/errors/rust-ast-validation.h: Update some prototype according
to implemented visitor functions. Also add a context tracker.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add call to ast validation check, also add appropriate step to this pass
and the feature gating.
gcc/rust/ChangeLog:
* rust-session-manager.cc (Session::compile_crate): Add call to ast
validation.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add the ast validation and feature gating steps to the compile pipeline.
gcc/rust/ChangeLog:
* lang.opt: Add the new compile options and update the enum values.
* rust-session-manager.h (struct CompileOptions): Add the new steps to
the enumeration.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add a new visitor to validate a given ast after the expansion pass.
gcc/rust/ChangeLog:
* Make-lang.in: Add the new object file the list.
* checks/errors/rust-ast-validation.cc: New file.
* checks/errors/rust-ast-validation.h: New file.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Early passes visitors may encounter constant item without a value, this
is expected as the pass rejecting a constant without an expression is
done later during the ast validation.
gcc/rust/ChangeLog:
* expand/rust-cfg-strip.cc (CfgStrip::visit): Add expr value check.
* expand/rust-expand-visitor.cc (ExpandVisitor::visit): Likewise.
* resolve/rust-early-name-resolver.cc (EarlyNameResolver::visit):
Likewise.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Those functions implementation put additional constraints on the headers
which makes the codebase harder to work with.
gcc/rust/ChangeLog:
* ast/rust-ast.h: Move implementation from here...
* ast/rust-ast.cc (SingleASTNode::SingleASTNode): ...to here.
(SingleASTNode::operator=): ...and here...
(SingleASTNode::accept_vis): ...and here...
(SingleASTNode::is_error): ...and here...
(SingleASTNode::as_string): ...also here.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Some function lacked the override specifier, this made the compiler emit
several warning.
gcc/rust/ChangeLog:
* ast/rust-ast.h: Add override specifier.
* ast/rust-item.h: Likewise.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add a new regression test in order to highlight the fix for #2659.
gcc/testsuite/ChangeLog:
* rust/compile/not_a_float_literal_tuple_index.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
The lexer cannot distinguish the difference between a float literal and a
tuple index in some cases. This means we should fix this while parsing
depending on the context.
gcc/rust/ChangeLog:
* expand/rust-macro-invoc-lexer.cc (MacroInvocLexer::split_current_token):
Add implementation for multiple token split.
* expand/rust-macro-invoc-lexer.h: Add function prototype.
* expand/rust-proc-macro-invoc-lexer.cc (ProcMacroInvocLexer::split_current_token):
Add implementation for 2+ token split for procedural macros.
* expand/rust-proc-macro-invoc-lexer.h: Add function prototype.
* lex/rust-lex.cc (Lexer::split_current_token): Add function to split a
token in multiple other tokens.
* lex/rust-lex.h: Add function prototype for split_current_token.
* parse/rust-parse-impl.h (Parser::left_denotation): Handle float tuple
index identified as a float literal.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Multiple references to procedural macro token trees were left as magic
number in the code. This commit introduces some constexpr for those along
some explanation for the selected value.
gcc/rust/ChangeLog:
* backend/rust-compile-base.cc (get_attributes): Add documentation for
indices 3 and 4.
(get_trait_name): Add documentation for index 1.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
The code to build the required procedural macro symbols is rather long
and could be placed in it's own file.
gcc/rust/ChangeLog:
* Make-lang.in: Add gcc/rust/backend/rust-compile-proc-macro.cc to the
list of file to compile.
* backend/rust-compile.cc (attribute_array): Move to
rust-compile-proc-macro.cc
(derive_proc_macro): Likewise.
(bang_proc_macro): Likewise.
(attribute_proc_macro): Likewise.
(proc_macro_payload): Likewise.
(proc_macro): Likewise.
(proc_macro_buffer): Likewise.
(entrypoint): Likewise.
(proc_macro_array): Likewise.
(CompileCrate::add_proc_macro_symbols): Likewise.
* backend/rust-compile-proc-macro.cc: New file.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
The compiler cannot infer the array length from the type, we should
therefore hand it the information. The proc macro buffer missed that
information.
gcc/rust/ChangeLog:
* backend/rust-compile.cc (proc_macro_buffer): Update type builder with
array length information.
(proc_macro_array): Update type initializer with array length
information.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Half of the functions introduced recently had a similar goal while the
other half had a similar goal too. Introducing some namespace to separate
those will keep the code cleaner and avoid confusion.
gcc/rust/ChangeLog:
* backend/rust-compile.cc (build_attribute_array): Renamed from...
(attribute_array): ...to attribute array.
(build_derive_proc_macro): Likewise from...
(derive_proc_macro): ... to derive_proc_macro.
(build_bang_proc_macro): Likewise from...
(bang_proc_macro): ...to bang_proc_macro.
(build_attribute_proc_macro): Likewise from...
(attribute_proc_macro): ... to attribute_proc_macro.
(build_proc_macro_payload): Likewise from...
(proc_macro_payload): to proc_macro_payload.
(build_proc_macro): Likewise from...
(proc_macro): ...to proc_macro.
(build_proc_macro_buffer): Likewise from...
(proc_macro_buffer): ... to proc_macro_buffer.
(build_entrypoint): Likewise from...
(entrypoint): ...to entrypoint.
(init_derive_proc_macro): Renamed to it's shorter counterpart.
(init_attribute_proc_macro): Likewise.
(init_bang_proc_macro): Likewise.
(init_proc_macro): Likewise.
(initialize_proc_macro_array): Likewise.
(proc_macro_array): Likewise.
(CompileCrate::add_proc_macro_symbols): Update function calls.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Export a new symbol containing the proc macros.
gcc/rust/ChangeLog:
* backend/rust-compile-base.h: Make static function address_expression
public.
* backend/rust-compile.cc (CompileCrate::add_proc_macro_symbols): Add
new global variable in export function.
(build_bang_proc_macro): Add a function to build the bang proc macro
structure type.
(build_proc_macro): Add a function to build the proc macro structure
type.
(build_proc_macro_payload): Add a function to build the proc macro
union used in proc macro structures.
(init_derive_proc_macro): Add a function to initialize custom derive
proc macros.
(init_attribute_proc_macro): Add a function to initialize attribute
proc macros.
(init_bang_proc_macro): Add a function to initialize bang proc macros.
(init_proc_macro): Add a function to initialize proc macro structures.
(initialize_proc_macro_array): Add a function to initialize the proc
macro buffer array.
(CompileCrate::add_proc_macro_symbols): Add call to the new functions
to correctly initialize proc macros as well as their entrypoint.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
We'll need this value in the final binary, it should therefore be kept
explicit.
ChangeLog:
* libgrust/libproc_macro_internal/proc_macro.h (enum ProcmacroTag): Add
explicit value for proc macro tag enum.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Change proc macro entrypoint from a fixed constant declaration to a
proper generation from the stable crate id. Although the stable crate id
is not in use yet, the mechanism to handle it is.
gcc/rust/ChangeLog:
* expand/rust-proc-macro.cc (CustomDeriveProcMacro::CustomDeriveProcMacro):
Remove constant string declaration.
(load_macros_array): Add call to the new generation function.
(generate_proc_macro_decls_symbol): Add a new function to generate the
entrypoint symbol name from the stable crate id.
(PROC_MACRO_DECLS_FMT_ARGS):
New macro to keep formats arguments in sync between each call.
* expand/rust-proc-macro.h (generate_proc_macro_decls_symbol): Add
function prototype.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add some utility function to build proc macro entrypoint related types.
Those functions will help generate all required metadata in order for
proc macros to be expanded properly.
gcc/rust/ChangeLog:
* backend/rust-compile.cc (build_attribute_array): Add a function to
build the attribute array type.
(build_derive_proc_macro): Add a function to build the derive proc
macro type.
(build_bang_proc_macro): Add a function to build the bang proc macro
type.
(build_attribute_proc_macro): Add a function to build the attribute
proc macro type.
(build_proc_macro): Add a function to build the proc macro tagged union
type.
(build_proc_macro_buffer): Add a function to build the proc macro
buffer type.
(build_entrypoint): Add a function to build the proc macro entrypoint
type.
* backend/rust-compile.h: Add function prototype.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add three different getters, one for each proc macro type.
gcc/rust/ChangeLog:
* backend/rust-compile-context.h: Add getters.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Collect informations on procedural macros in the compiled crate. For
attribute and bang procedural macros we only require the final address
as well as the name of the function. Derive procedural macros are a bit
different, we collect the fonction's address through it's fndecl tree as
well as the trait's name and the multiple attributes.
gcc/rust/ChangeLog:
* backend/rust-compile-base.cc (HIRCompileBase::setup_fndecl):
Make the function non static in order to be able to access the
compile context. Also add the whole proc macro infomrmation
collection.
(get_attributes): Add a function to retrieve the different
attributes from a derive procedural macro definition attribute.
(get_trait_name): Add a function to retrieve the trait name from
a derive procedural macro definition attribute.
* backend/rust-compile-base.h: Add function prototypes.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add one container for each kind of procedural macro mapping. Also add a
new structure to gather informations required for derive procedural
macros. Add different functions to fill those new containers.
gcc/rust/ChangeLog:
* backend/rust-compile-context.h (struct CustomDeriveInfo): Add
new derive procedural macro metadata information holder for
mappings.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
We often need to retrieve the underlying tokentree without modifying it,
this getter will help achieve this.
gcc/rust/ChangeLog:
* ast/rust-ast.h: Add const getter.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Change the way the ABI is setup on a function to avoid duplicates. ABI
is setup by the setup function only now. Add a new attribute to the
function "gccrs_proc_macro" in order to differentiate it from another
type of function.
gcc/rust/ChangeLog:
* backend/rust-compile-base.cc (handle_proc_macro_common): Add
new attribute "gccrs_proc_macro" to all procedural macro
functions.
(get_abi): Add a function to retrieve the correct ABI depending
on wether the function is a proc macro or not.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
We need to make sure proc macros have the C abi in order to be called by
the compiler with dlopen.
gcc/rust/ChangeLog:
* backend/rust-compile-base.cc (HIRCompileBase::setup_fndecl):
Add proc macro handlers dispatch.
(handle_proc_macro_common): Add a function for common behavior
between all kinds of proc macros.
* backend/rust-compile-base.h: Add function prototypes.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add option to simplify cfg for better readability. Off by default.
gcc/rust/ChangeLog:
* checks/errors/borrowck/rust-bir-dump.cc (simplify_cfg): Simplify cfg logic.
(Dump::go): Run simplify cfg.
* checks/errors/borrowck/rust-bir-dump.h: Option to simplify cfg.
Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
gcc/rust/ChangeLog:
* checks/errors/borrowck/rust-bir-dump.cc (Dump::go): Use new print.
(print_comma_separated): Comma separation print.
(Dump::visit): Use new print.
Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
gcc/rust/ChangeLog:
* Make-lang.in: Build BIR dump.
* checks/errors/borrowck/rust-borrow-checker.cc (mkdir_wrapped): Cross-platform mkdir.
(dump_function_bir): Save dump to file.
(BorrowChecker::go): Run dump during borrowck.
* checks/errors/borrowck/rust-bir-dump.cc: New file.
* checks/errors/borrowck/rust-bir-dump.h: New file.
Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
gcc/rust/ChangeLog:
* Make-lang.in: Compile BIR expr visitor.
* checks/errors/borrowck/rust-borrow-checker.cc (BorrowChecker::go): Use BIR builder.
* rust-session-manager.cc (Session::compile_crate): Run borrow checker.
* checks/errors/borrowck/rust-bir-builder-expr-stmt.cc: New file.
* checks/errors/borrowck/rust-bir-builder-expr-stmt.h: New file.
* checks/errors/borrowck/rust-bir-builder-internal.h: New file.
* checks/errors/borrowck/rust-bir-builder-lazyboolexpr.h: New file.
* checks/errors/borrowck/rust-bir-builder-pattern.h: New file.
* checks/errors/borrowck/rust-bir-builder-struct.h: New file.
* checks/errors/borrowck/rust-bir-builder.h: New file.
Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
gcc/rust/ChangeLog:
* checks/errors/borrowck/rust-borrow-checker.cc: Include to compile new code.
* checks/errors/borrowck/rust-bir-place.h: New file.
* checks/errors/borrowck/rust-bir-visitor.h: New file.
* checks/errors/borrowck/rust-bir.h: New file.
Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
Highlight issue 2665's fix for const with no value expression.
gcc/testsuite/ChangeLog:
* rust/compile/issue-2665.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Const with no value expression may exist either in trait or in disabled
blocks. This means we should be able to parse those correctly.
gcc/rust/ChangeLog:
* ast/rust-item.h: Add a new constructor for const with no value
expression.
* parse/rust-parse-impl.h (Parser::parse_const_item): Allow const with
no expression value.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
gcc/rust/ChangeLog:
* hir/rust-ast-lower.cc (ASTLoweringBlock::visit): Call loop lowering and add it to constr.
* hir/tree/rust-hir-expr.h (class LoopLabel): Move before BlockExpr and add to BlockExpr.
This new test highlight the fix of #2656.
gcc/testsuite/ChangeLog:
* rust/compile/closure_in_closure.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
The parser was unable to process as closure inside a closure because the
lexer could not differentiate an OR from two PIPE tokens.
gcc/rust/ChangeLog:
* parse/rust-parse-impl.h (Parser::parse_closure_expr_pratt): Fix
closure parsing function to handle consecutive parameter lists.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add a new test to highlight the fix introduced for #2653.
gcc/testsuite/ChangeLog:
* rust/compile/macro-issue2653.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
The previous follow set rules did not allow PATH fragment, changing this
allow gccrs to accept more valid rust macros.
gcc/rust/ChangeLog:
* ast/rust-macro.h: Add PATH fragment to follow set restrictions.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Macro rules named macro_rules may cause some problems if not handled
correctly. This new test ensure we always compile those macros named
macro_rules correctly as well as other macro definitions.
gcc/testsuite/ChangeLog:
* rust/compile/macro57.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
This new test highlight the fix for #2651.
gcc/testsuite/ChangeLog:
* rust/compile/macro_rules_macro_rules.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Change the constraints around macro rules declaration in order to allow
macro_rules named macro as well as tighter constraint around macro rules
definitions.
gcc/rust/ChangeLog:
* parse/rust-parse-impl.h (Parser::is_macro_rules_def): Add a function
that checks tokens given by the lexer represents an accurate macro
definition. This will reduce code duplication.
(Parser::parse_item): Replace condition with call to new checking
function.
(Parser::parse_stmt): Likewise.
* parse/rust-parse.h: Add function prototype for is_macro_rules_def.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add a new test to highlight fix of #2658.
gcc/testsuite/ChangeLog:
* rust/compile/while_break_expr.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add a new test to highlight the fix made for #2660.
gcc/testsuite/ChangeLog:
* rust/compile/range_from_expr_for_loop.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Those ranges were looking for a curly brace after the brace, leading
to an error when using range from expr in for loops.
gcc/rust/ChangeLog:
* parse/rust-parse-impl.h (Parser::parse_expr): Fix range from expr.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
This test highlight the fix required for #2655.
gcc/testsuite/ChangeLog:
* rust/compile/parse_item_default_macro.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
The parser was too agressive and did reject any line beginning with
default even if this was a macro call.
gcc/rust/ChangeLog:
* parse/rust-parse-impl.h (Parser::parse_item): Relax constraints
around default identifier at item scope to accept "default" macros.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
New regression test to highlight behavior of #2652.
gcc/testsuite/ChangeLog:
* rust/compile/parse_generic_path_expr.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
When a token was identified as bit left shift it slipped through the
parser and resulted in an error.
gcc/rust/ChangeLog:
* parse/rust-parse-impl.h (Parser::parse_path_expr_segment): Accept
left shift tokens in order to let generic parsing function split the
token.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
This new test highlight the fix for issue #2657.
gcc/testsuite/ChangeLog:
* rust/compile/match_break.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add a comma as an expr delimiter, this will allow correct parsing of
match arm expressions.
gcc/rust/ChangeLog:
* parse/rust-parse-impl.h (Parser::parse_expr): Add comma delimiter.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add a new test to highlight fix for #2648.
gcc/testsuite/ChangeLog:
* rust/compile/parse_pub_unit_type.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Public unit types where not parsed correctly due to visibility specifiers
within parenthesis. Fixes#2648.
gcc/rust/ChangeLog:
* parse/rust-parse-impl.h (Parser::parse_visibility): Relax constraints
over public visibility return condition in order to accept pub unit
types.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Associate each subclass with its kind and create cast/match+cast
methods.
gcc/rust/ChangeLog:
* typecheck/rust-tyty.cc (InferType::InferType): Use static constant for kind information.
(ErrorType::ErrorType): Use static constant for kind information.
(TupleType::TupleType): Use static constant for kind information.
(BoolType::BoolType): Use static constant for kind information.
(IntType::IntType): Use static constant for kind information.
(UintType::UintType): Use static constant for kind information.
(FloatType::FloatType): Use static constant for kind information.
(USizeType::USizeType): Use static constant for kind information.
(ISizeType::ISizeType): Use static constant for kind information.
(CharType::CharType): Use static constant for kind information.
(ReferenceType::ReferenceType): Use static constant for kind information.
(PointerType::PointerType): Use static constant for kind information.
(ParamType::ParamType): Use static constant for kind information.
(StrType::StrType): Use static constant for kind information.
(NeverType::NeverType): Use static constant for kind information.
(PlaceholderType::PlaceholderType): Use static constant for kind information.
* typecheck/rust-tyty.h: Add static kind information to all TyTy classes.
Create safe cast and check methods.
Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
The function parsing type param bounds had a problem with scope
resolution opening token.
gcc/rust/ChangeLog:
* parse/rust-parse-impl.h (Parser::parse_type_param_bound): Add missing
case for lifetime switch.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
This will ensure an accurate representation of the token. Also update the
as_string function to represent accurately scope resolution tokens.
gcc/rust/ChangeLog:
* lex/rust-token.cc (Token::as_string): Update function to output scope
resolution tokens correctly.
* parse/rust-parse-impl.h (Parser::parse_generic_param): Change call to
as_string.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
gcc/rust/ChangeLog:
* backend/rust-compile-context.h: Modify declaration.
* backend/rust-mangle.cc (struct V0Path): New struct.
(v0_path): New function.
(legacy_mangle_name): Take Context as argument.
(v0_numeric_prefix): Fix type strings.
(v0_complex_type_prefix): New function.
(v0_add_integer_62): Deleted
(v0_integer_62): New function.
(v0_add_opt_integer_62): Deleted.
(v0_opt_integer_62): New function.
(v0_add_disambiguator): Deleted.
(v0_disambiguator): New function.
(v0_type_prefix): Support more types.
(v0_generic_args): New function.
(v0_add_identifier): Deleted.
(v0_identifier): New function.
(v0_type_path): New function.
(v0_function_path): New function.
(v0_scope_path): New function.
(v0_crate_path): New function.
(v0_inherent_or_trait_impl_path): New function.
(v0_mangle_item): Use v0_path.
(Mangler::mangle_item): Take Context as argument.
* backend/rust-mangle.h (class Context): Add forward declaration.
* hir/tree/rust-hir-item.h: Fix include.
Signed-off-by: Raiki Tamura <tamaron1203@gmail.com>
Fix a typo and merge 2 if clauses using the same condition.
gcc/rust/ChangeLog:
* backend/rust-compile-expr.cc (CompileExpr::visit): Merge 2 if clauses.
* backend/rust-compile-extern.h: Fix typo in comment.
Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
There was a mismatch between a manual discriminant test and the static cast.
gcc/rust/ChangeLog:
* backend/rust-compile.cc (HIRCompileBase::coercion_site1): Fix wrong cast
Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
When an error was emitted during the cfg strip pass by the crate loader,
it was ignored and the error state propagated until another pass
(name resolver).
gcc/rust/ChangeLog:
* rust-session-manager.cc (Session::expansion): Add early break on
error.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
gcc/rust/ChangeLog:
* util/rust-canonical-path.h: Add new segment kind for inherent impl.
* resolve/rust-ast-resolve-item.cc (ResolveItem::visit): Use it.
* resolve/rust-ast-resolve-toplevel.h: Use it.
Signed-off-by: Raiki Tamura <tamaron1203@gmail.com>
Add simple debug wrapper to dump HIR nodes on stderr.
Similar to what we already have for AST.
gcc/rust/ChangeLog:
* hir/rust-hir-dump.cc (Dump::debug): New.
(debug): New.
* hir/rust-hir-dump.h (debug): New.
Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
There are some certain rust types must be cast before
passing them to a variadic function, because of arcane
ABI rules dictated by the C standard. To fix the error,
cast the value to the type specified by the error message.
gcc/rust/ChangeLog:
* typecheck/rust-tyty-call.cc (TypeCheckCallExpr::visit):
Added ErrorCode & more fixit hints.
gcc/testsuite/ChangeLog:
* rust/compile/variadic.rs: Added new checks.
Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
... also made `copy_nonoverlapping` handler more generic
gcc/rust/ChangeLog:
* backend/rust-compile-intrinsic.cc: add `copy`
intrinsics and make `copy_nonoverlapping` handler more generic
Signed-off-by: Zixing Liu <liushuyu011@gmail.com>
Add a libstd++-v3 dependency to libgrust in order to be able to compile
it properly when using a crosscompiler.
ChangeLog:
* Makefile.def: Add dependency.
* Makefile.in: Regenerate file.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
When some proc macro create tokens and later have some code referring to
those created tokens the code was missing a linemap since the pointer
was null, throwing an ICE.
gcc/rust/ChangeLog:
* expand/rust-proc-macro.cc (tokenstream_from_string): Change
linemap null pointer to the current linemap.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Since the node id already is contained into the proc macro we may omit
it from the function arguments.
gcc/rust/ChangeLog:
* util/rust-hir-map.cc (Mappings::insert_derive_proc_macro_def):
Change the function body to fetch the node id from the macro
parameter.
(Mappings::insert_bang_proc_macro_def): Likewise.
(Mappings::insert_attribute_proc_macro_def): Likewise.
* util/rust-hir-map.h: Update the function's prototype by
removing the node id from the list of arguments.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Continue changing the api to use optionals instead of bools and double
pointers.
gcc/rust/ChangeLog:
* util/rust-hir-map.cc (Mappings::lookup_derive_proc_macro_def):
Update function to accomodate new signature.
(Mappings::lookup_bang_proc_macro_def): Likewise.
(Mappings::lookup_attribute_proc_macro_def): Likewise.
* util/rust-hir-map.h: Update function signatures.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
The old interface for those mappings was clunky at best. Now we can use
the optional structure to return a reference to the instance.
gcc/rust/ChangeLog:
* expand/rust-macro-expand.h (struct MacroExpander): Update
lookup function prototypes.
* util/rust-hir-map.cc (Mappings::lookup_derive_proc_macro_invocation):
Update lookup function according to new signature.
(Mappings::lookup_bang_proc_macro_invocation): Likewise.
(Mappings::lookup_attribute_proc_macro_invocation): Likewise.
* util/rust-hir-map.h: Update function prototypes.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
This part of the code is a bit tricky as it calls multiple functions
with almost the same name and slightly different behaviors. It was even
more with a meaningless variable name.
gcc/rust/ChangeLog:
* rust-session-manager.cc (Session::load_extern_crate): Change
variable name, add temporaries and comments.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add a templated function to insert any of the three kind of proc macro
into the resolver context.
gcc/rust/ChangeLog:
* expand/rust-proc-macro.h: Change get_trait_name to get_name in
order to be coherent with the others proc macro type name
convention.
* resolve/rust-toplevel-name-resolver-2.0.cc (insert_macros):
Add a templated funtion that inserts a proc macro into the
context and emit an error on failure.
(TopLevel::visit): Change from manual insertion to a function
call.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Change the condition with rust_unreachable to an assertion. This will
keep the code clean and concise.
Some styling issues appeared during review, this commit make the code
more readable.
gcc/rust/ChangeLog:
* resolve/rust-toplevel-name-resolver-2.0.cc (TopLevel::visit):
Change to assertion.
* util/rust-hir-map.cc (Mappings::lookup_derive_proc_macros):
Add empty line.
(Mappings::lookup_bang_proc_macros): Likewise.
(Mappings::lookup_attribute_proc_macros): Likewise.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Move extern crate resolving under the extern crate declaration instead
of doing it under the crate's root as extern crates are not resolved by
the top level resolver.
gcc/rust/ChangeLog:
* metadata/rust-extern-crate.cc (ExternCrate::ExternCrate):
Update definition to allow Extern crate with no content (pure
proc macros).
(ExternCrate::ok): Panic on no content.
(ExternCrate::load): Likewise.
* metadata/rust-extern-crate.h: Update prototypes.
* resolve/rust-toplevel-name-resolver-2.0.cc (TopLevel::go):
Remove macro resolution.
(TopLevel::visit): Likewise.
* resolve/rust-toplevel-name-resolver-2.0.h: Add visit prototype
for extern crate.
* rust-session-manager.cc (Session::load_extern_crate): Adapt
content depending on the loaded crate's content.
* util/rust-hir-map.cc (Mappings::lookup_derive_proc_macros):
Change return type to optional because it is way more
convenient.
(Mappings::lookup_bang_proc_macros): Likewise.
(Mappings::lookup_attribute_proc_macros): Likewise.
* util/rust-hir-map.h: Update function prototypes.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
This error was emitted when a valid proc macro crate was loaded. Proc
macros do not contain any import data for now.
gcc/rust/ChangeLog:
* metadata/rust-imports.cc (Import::try_package_in_directory):
Remove error when some macro are found even if no import data is
available.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
This commit moves the procedural macros loaded definition from outside
the AST to the mappings. This means most getters/setters around the
mappings had to be changed. This commit also introduces the top level
visit of those mappings instead of visiting the Crate ast members.
gcc/rust/ChangeLog:
* ast/rust-ast.h (class BangProcMacro): Move class from here to
rust-proc-macro.h. Also remove related functions.
(class AttributeProcMacro): Likewise.
(class CustomDeriveProcMacro): Likewise.
(struct Crate): Remove proc macro vector members.
* expand/rust-macro-expand.h (struct MacroExpander): Change the
type to the newly created classes.
* expand/rust-proc-macro.cc (BangProcMacro::BangProcMacro): Add
constructor implementation.
(AttributeProcMacro::AttributeProcMacro): Likewise.
(CustomDeriveProcMacro::CustomDeriveProcMacro): Likewise.
* expand/rust-proc-macro.h (class BangProcMacro): Move class to
here.
(class AttributeProcMacro): Likewise.
(class CustomDeriveProcMacro): Likewise.
* resolve/rust-toplevel-name-resolver-2.0.cc (TopLevel::go):
Change top level visitor to check mappings instead
* rust-session-manager.cc (Session::load_extern_crate):
Add back macro collection to mappings.
* util/rust-hir-map.cc (Mappings::insert_derive_proc_macros):
Update getter signature with new types.
(Mappings::insert_bang_proc_macros): Likewise.
(Mappings::insert_attribute_proc_macros): Likewise.
(Mappings::lookup_derive_proc_macros): Likewise.
(Mappings::lookup_bang_proc_macros): Likewise.
(Mappings::lookup_attribute_proc_macros): Likewise.
(Mappings::insert_derive_proc_macro_def): Likewise.
(Mappings::insert_bang_proc_macro_def): Likewise.
(Mappings::insert_attribute_proc_macro_def): Likewise.
(Mappings::lookup_derive_proc_macro_def): Likewise.
(Mappings::lookup_bang_proc_macro_def): Likewise.
(Mappings::lookup_attribute_proc_macro_def): Likewise.
(Mappings::insert_derive_proc_macro_invocation): Likewise.
(Mappings::lookup_derive_proc_macro_invocation): Likewise.
(Mappings::insert_bang_proc_macro_invocation): Likewise.
(Mappings::lookup_bang_proc_macro_invocation): Likewise.
(Mappings::insert_attribute_proc_macro_invocation): Likewise.
(Mappings::lookup_attribute_proc_macro_invocation): Likewise.
* util/rust-hir-map.h: Update function prototypes as well as map
types.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add mechanism to discover proc macros in loaded extern crates. In the
top level resolver.
gcc/rust/ChangeLog:
* resolve/rust-toplevel-name-resolver-2.0.cc (TopLevel::go):
Visit crate's newly stored proc macros.
* rust-session-manager.cc (Session::load_extern_crate):
Store proc macros in the parsed crate instead of a local
variable to achieve mappings.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
We do not need to copy the whole vector we can simply take a reference
instead.
gcc/rust/ChangeLog:
* resolve/rust-early-name-resolver-2.0.cc (Early::visit_attributes):
Change argument to reference.
* resolve/rust-early-name-resolver-2.0.h: Update function
prototype.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add some getters on the ast crate in order to be able to retrieve a
reference to a crate's proc macros.
gcc/rust/ChangeLog:
* ast/rust-ast.h: Add getters.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
When resolving proc macros it is convenient to store every macro
directly in the extern crate. These class in the ast module provide a
better abstraction over the raw ProcMacro::{CustomDerive, Bang,
Attribute} structures provided by the proc_macro library.
gcc/rust/ChangeLog:
* ast/rust-ast.h (class BangProcMacro): Add new proc macro
abstraction.
(class AttributeProcMacro): Likewise.
(class CustomDeriveProcMacro): Likewise.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Derive attributes should be parsed before attempting to retrieve any
traits. This will convert the tokenstream to a list of path if this
hasn't been done previously.
gcc/rust/ChangeLog:
* ast/rust-ast.cc (Attribute::get_traits_to_derive): Convert
tokenstream to path list.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Member function is_derive was overly constrained, the attribute changes
when we parse it's meta items and it no longer contains a tokenstream
while staying a derive.
gcc/rust/ChangeLog:
* ast/rust-ast.cc (Attribute::is_derive): Remove tokenstream
condition.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Having copy and any other constructor stuff might lead to a breakage in
the future where the node id differs due to a newly constructed
SimplePath node. This change will allow us to assert the NodeId is from
the ast and not any copy made in between.
gcc/rust/ChangeLog:
* ast/rust-ast.cc (Attribute::get_traits_to_derive): Change
return type to a vector of references.
* ast/rust-ast.h: Update constructor.
* expand/rust-expand-visitor.cc (ExpandVisitor::expand_inner_stmts):
Update function call.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
This function will be used outside of the expand visitor, making it
easily accessible is therefore mandatory.
gcc/rust/ChangeLog:
* ast/rust-ast.cc (Attribute::get_traits_to_derive): Add
function as member function.
* ast/rust-ast.h: Add prototype.
* expand/rust-expand-visitor.cc (get_traits_to_derive): Remove
function.
(ExpandVisitor::expand_inner_stmts): Update function call.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
This function will be used in the multiple other places, therefore we
should make it easily usable from there.
gcc/rust/ChangeLog:
* ast/rust-ast.cc (Attribute::is_derive): Add member function.
* ast/rust-ast.h: Likewise.
* expand/rust-expand-visitor.cc (is_derive): Remove old
function.
(ExpandVisitor::expand_inner_stmts): Update function call.
(ExpandVisitor::visit_inner_using_attrs): Likewise.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
We were massing the match scruitinee expression as a way to access the
result of the expression. This is wrong and needs to be stored in a
temporary otherwise it will cause the code to be regnerated for each time
it is used. This is not an issue in the case where the expression is only
used once.
Fixes#1895
gcc/rust/ChangeLog:
* backend/rust-compile-expr.cc (CompileExpr::visit): use a temp for the value
gcc/testsuite/ChangeLog:
* rust/execute/torture/iter1.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-expr.cc
(TypeCheckExpr::visit): Expect if conditions to have type bool.
gcc/testsuite/ChangeLog:
* rust/compile/type-if.rs: New test.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
The intrinsic move_val_init was being optimized away even at -O0 because
the function looked "pure" but this adds in the attributes to enforce that
this function has side-effects to override that bad assumption by the
middle-end.
Addresses #1895
gcc/rust/ChangeLog:
* backend/rust-compile-intrinsic.cc (move_val_init_handler): mark as side-effects
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
Ensure the uninit intrinsic does not get optimized away
Addresses #1895
gcc/rust/ChangeLog:
* backend/rust-compile-intrinsic.cc (uninit_handler): Update fndecl attributes
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
The overflow intrinsic returns a tuple of (value, boolean) where it value
is the operator result and boolean if it overflowed or not. The intrinsic
here did not initilize the resulting tuple and therefore was creating a use
before init error resulting in garbage results
Addresses #1895
gcc/rust/ChangeLog:
* backend/rust-compile-intrinsic.cc (op_with_overflow_inner): fix use before init
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
We were using the DECL_RESULT but this just contains the TREE_TYPE of the
retval. It was also missing taking the address of the destination for the
memset call. This changes the code to create a temp variable for the return
value and asserts the destination size is the same as the size of the
template param.
Fixes#2583
gcc/rust/ChangeLog:
* backend/rust-compile-intrinsic.cc (enter_intrinsic_block): take the locals vector
(uninit_handler): make a temp variable and use the address of it
gcc/testsuite/ChangeLog:
* rust/execute/torture/issue-2583.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
Add a new test to avoid regression on newly added changes about macros
expanding to new macro definitions.
gcc/testsuite/ChangeLog:
* rust/compile/nested_macro_definition.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
We need to collect the early resolver's macros error to emit them at a
later stage after further expansion in order to retrieve macros defined
by other macro invocations.
Register some mappings for macro invocations and macro definitions.
gcc/rust/ChangeLog:
* resolve/rust-early-name-resolver-2.0.cc (Early::visit):
Collect error instead of emitting it. Also add invocation
registration.
* resolve/rust-early-name-resolver-2.0.h (std::function<void):
Add type definition for collection.
* resolve/rust-toplevel-name-resolver-2.0.cc (TopLevel::visit):
Register macro rule definition in mappings.
* rust-session-manager.cc (Session::expansion): Add macro
resolve error collection.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Currently, gccrs using the const `rich_location &`, and
then using the cast to convert it to the functions which
was used to emit the errors, having the overloaded is
good, similiar to other frontends.
gcc/rust/ChangeLog:
* rust-diagnostics.cc (rust_be_error_at): Added overload function.
(rust_error_at): non-const `rich_location *` function.
* rust-diagnostics.h (rust_error_at): Implementation of overloaded
function.
(rust_be_error_at): likewise.
* rust_error_codes.def: Added GNU license.
Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
There is a case where some generic types are holding onto inference
variable pointers directly. So this gives the backend a chance to do one
final lookup to resolve the type.
This now allows us to compile a full test case for iterators but there is
still one miscompilation in here which results in a segv on O2 and bad
result on -O0.
Addresses #1895
gcc/rust/ChangeLog:
* backend/rust-compile-type.cc (TyTyResolveCompile::visit): do a final lookup
gcc/testsuite/ChangeLog:
* rust/compile/iterators1.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
Added more userfriendly message.
gcc/rust/ChangeLog:
* parse/rust-parse-impl.h (Parser::parse_generic_params):
Added more user friendly message.
gcc/testsuite/ChangeLog:
* rust/compile/generics13.rs:
for dejagnu,
Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
This errorcode & message emits when cycle
detected when computing the super predicates
of `x` which requires computing the super
predicates of `y`, which again requires
computing the super predicates of `x`,
completing the cycle.
gcc/rust/ChangeLog:
* typecheck/rust-hir-trait-resolve.cc (TraitResolver::resolve_trait):
Updated errorcode & more userfriendly message.
gcc/testsuite/ChangeLog:
* rust/compile/issue-1589.rs: Updated comment for dejagnu.
* rust/compile/trait-cycle.rs: New relevant test.
Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
Issue #2514 fixed by the previous commit highlight a behavior we want to
avoid in the future, hence this regression test.
gcc/testsuite/ChangeLog:
* rust/compile/issue-2514.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
The lexer did output a literal for values such as 42.e wich are invalid
in rust.
gcc/rust/ChangeLog:
* lex/rust-lex.cc (Lexer::parse_decimal_int_or_float): Only
accept digits after a dot instead of accepting any float
member.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Checking if pattern has items, before returing solves ICE.
Added error code and rich location.
Also, fixes https://github.com/Rust-GCC/gccrs/issues/2430
gcc/rust/ChangeLog:
* ast/rust-pattern.h: No need of assertion, we are handling it.
* resolve/rust-early-name-resolver.cc (EarlyNameResolver::visit):
Added check which emits error instead of using assertion.
* typecheck/rust-hir-type-check-pattern.cc (TypeCheckPattern::visit):
Added rich location and error code.
gcc/testsuite/ChangeLog:
* rust/compile/match5.rs:
Updated comment for dejagnu.
* rust/compile/pattern-struct.rs: New test for ICE.
Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
The inline attribute only supports two arguments:
- always
- never
All other arguments given to the inline attribute will
return error.
gcc/rust/ChangeLog:
* backend/rust-compile-base.cc (HIRCompileBase::handle_inline_attribute_on_fndecl):
Added rich_location & error code.
gcc/testsuite/ChangeLog:
* rust/compile/inline_2.rs: Added new message.
Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
Added method of binding ErrorCode & rich location to
parser and expansion errors.
Fixes https://github.com/Rust-GCC/gccrs/issues/2385
gcc/rust/ChangeLog:
* rust-diagnostics.cc (va_constructor):
Added constructor for all possible cases.
(Error::Error): Updated error struct
for all possible cases.
* rust-diagnostics.h (struct Error):
Updated error struct to support error
code & rich location support.
Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
Inline attribute takes one argument, but
more than one argument was found.
gcc/rust/ChangeLog:
* backend/rust-compile-base.cc (HIRCompileBase::handle_inline_attribute_on_fndecl):
Added rich_location & error code.
gcc/testsuite/ChangeLog:
* rust/compile/inline_2.rs: Added new case.
Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
We cannot use `free` on a pointer allocated through `new[]`, and this
causes an ASAN failure. This fixes it by using `xcalloc` instead of
`new[]` when creating description buffers for our error codes.
gcc/rust/ChangeLog:
* rust-diagnostics.cc: Switch from new[] to xcalloc
We can endup with duplicate symbol names for different intrinsics with our
current hash setup. This adds in the mappings and extra info to improve
hash uniqueness.
Addresses #1895
gcc/rust/ChangeLog:
* backend/rust-compile-intrinsic.cc (check_for_cached_intrinsic):
simplify this cached intrinsic check
* backend/rust-mangle.cc (legacy_mangle_item): use new interface
* typecheck/rust-tyty.h: new managle helper
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
We do extra checking after the fact here to ensure its a valid candidate
and in the case there is only one candidate lets just go for it.
Addresses #1895
gcc/rust/ChangeLog:
* backend/rust-compile-base.cc (HIRCompileBase::resolve_method_address):
use the single candidate
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
We hit an assertion with range based iterators here. This code was used
to solve complex generics such as:
struct Foo<X,Y>(X,Y);
impl<T> Foo<T, i32> {
fn test<Y>(self, a: Y) { }
}
The impl item will have the signiture of:
fn test<T,Y> (Foo<T, i32> self, a:Y)
So in the case where we have:
let a = Foo(123f32, 456);
a.test<bool>(true);
We need to solve the generic argument T from the impl block by infering the
arguments there and applying them so that when we apply the generic
argument bool we dont end up in the case of missing number of generics.
Addresses #1895
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit): remove hack
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
This avoids a use-after-free when reaching the recursion limit.
gcc/rust/ChangeLog:
* expand/rust-macro-expand.h: Keep optional references for last_def
and last_invoc.
* expand/rust-macro-expand.cc (MacroExpander::expand_invoc): Store
optional references.
* rust-session-manager.cc (Session::expansion): Use tl::optional's APIs
for better checking.
Adjust the HIR dump for IfExpr and IfExprConseqElse
to use visit_field() and factor common part.
gcc/rust/ChangeLog:
* hir/rust-hir-dump.h (do_ifexpr): New.
* hir/rust-hir-dump.cc (Dump::do_ifexpr): New.
(Dump::visit): Use do_ifexpr and visit_field
Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
Added errorcodes according to different conditions
and updated error message according to type casting
type.
gcc/rust/ChangeLog:
* typecheck/rust-casts.cc (TypeCastRules::emit_cast_error):
Refactored ErrorCodes & error messages.
gcc/testsuite/ChangeLog:
* rust/compile/bad_as_bool_char.rs:
Updated comment to pass test case.
* rust/compile/cast1.rs: likewise.
* rust/compile/cast4.rs: likewise.
* rust/compile/cast5.rs: likewise.
* rust/compile/all-cast.rs: New test for all error codes.
Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
Added error code support for invalid ABI.
gcc/rust/ChangeLog:
* hir/rust-ast-lower-base.cc (ASTLoweringBase::lower_qualifiers):
called error function.
(ASTLoweringBase::lower_extern_block): likewise.
gcc/testsuite/ChangeLog:
* rust/compile/abi-options1.rs: updated comment for testcase.
Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
type must be known at compile time.
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check.cc (TypeResolution::Resolve):
added errorcode.
Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
This semicolon produces several warning in each TU the header file is
included in.
gcc/rust/ChangeLog:
* util/rust-common.h (enum_to_str): Remove extra semicolon after
the function.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
gcc/rust/ChangeLog:
* checks/errors/rust-const-checker.cc (ConstChecker::visit):
Use of mutable reference in constant functions.
* checks/errors/rust-feature-gate.cc (FeatureGate::gate):
ErrorCode for intrinsics are subject to change.
Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
gcc/testsuite/ChangeLog:
* rust/compile/name_resolution6.rs: New test.
* rust/compile/name_resolution7.rs: New test.
* rust/compile/name_resolution8.rs: New test.
* rust/compile/name_resolution9.rs: New test.
This visitor takes care of resolving macro invocations, procedural macros
and imports - it is used in conjunction with the `TopLevel` pass and
the macro expander.
gcc/rust/ChangeLog:
* Make-lang.in: Add new object file.
* resolve/rust-early-name-resolver-2.0.cc: New file.
* resolve/rust-early-name-resolver-2.0.h: New file.
Refactored error message to print more
userfriendly message and added error
code.
gcc/rust/ChangeLog:
* resolve/rust-ast-resolve-expr.cc (ResolveExpr::visit):
refactored message and called error function.
gcc/testsuite/ChangeLog:
* rust/compile/undeclared_label.rs: New test for E0426.
Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
Added ErrorCode support for use of unknown
feature.
gcc/rust/ChangeLog:
* checks/errors/rust-feature-gate.cc (FeatureGate::check):
errorcode support for unknown feature.
gcc/testsuite/ChangeLog:
* rust/compile/feature.rs: Added new unknown feature.
Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
When the load_file_bytes() fails to open the file, it emits an error but
returns an empty vector (as if the file is empty).
Instead, return a tl::optional nullopt in case of error and an empty
vector in case of an empty file.
fixes#2421
gcc/rust/ChangeLog:
* expand/rust-macro-builtins.cc
(load_file_bytes): Return a tl::optional.
(MacroBuiltin::include_byte_handler): Adjust and check file was
correctly opened.
(MacroBuiltin::include_str_handler): Likewise.
gcc/testsuite/ChangeLog:
* rust/compile/empty_file: New file.
* rust/compile/issue-2421_str.rs: New test.
Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
The DefaultResolver class provides a visitor framework for all three resolvers
in the new name resolution algorithm, with things such as scoping or visiting
sub items.
gcc/rust/ChangeLog:
* Make-lang.in: Add new object file.
* resolve/rust-default-resolver.cc: New file.
* resolve/rust-default-resolver.h: New file.
The `TopLevel` pass takes care of collecting definitions, placing them
in the proper namespaces, and making them accessible for later resolution
passes like `Early` and `Late`. It is meant to be run in a fixed point
fashion, as import resolution, macro resolution and macro expansion
may generate multiple new definitions.
gcc/rust/ChangeLog:
* Make-lang.in: Add new object file.
* resolve/rust-toplevel-name-resolver-2.0.cc: New file.
* resolve/rust-toplevel-name-resolver-2.0.h: New file.
This commit adds a first simple `NameResolutionContext` data structure, which will
be used by all passes of the name resolution to store definitions and access
them. Namely, it contains a few instances of `ForeverStack`, for each
namespace we will be using.
gcc/rust/ChangeLog:
* Make-lang.in: Add new object file.
* resolve/rust-name-resolution-context.cc: New file.
* resolve/rust-name-resolution-context.h: New file.
Fixes#2479
gcc/rust/ChangeLog:
* typecheck/rust-hir-trait-resolve.cc (TraitItemReference::resolve_item):
always resolve the type even when its an a mandatory trait item
* typecheck/rust-hir-type-check-type.cc (TypeCheckType::resolve_root_path):
Add check for enum candidates otherwise you get undefined behaviour
gcc/testsuite/ChangeLog:
* rust/compile/issue-2479.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
Fixes#2477
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit):
We need to check if a function context exists
gcc/testsuite/ChangeLog:
* rust/compile/issue-2477.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
Trait bounds can have three forms in Rust the regular trait bound, '!' the
negative trait bound to enforice that this trait must not be implmented and
'?' the anti trait bound to remove this bound. This patch extends our
Polarity enum to include the Anti trait bound and updates the HIR lowering
code to track this properly.
Addresses #2443
gcc/rust/ChangeLog:
* hir/rust-ast-lower-item.cc (ASTLoweringItem::visit): use new BoundPolarity enum
* hir/rust-ast-lower-type.cc (ASTLoweringTypeBounds::visit): likewise
* hir/rust-hir-dump.cc (BoundPolarityString): new helper
(Dump::visit): update hir dump
* hir/tree/rust-hir-item.h (class ImplBlock): likewise
* hir/tree/rust-hir-type.h (class TraitBound): likewise
* hir/tree/rust-hir.cc (TraitBound::as_string): fix as string
* util/rust-common.h (enum Polarity): add new anti bound
(enum BoundPolarity): likewise
* util/rust-hir-map.cc (Mappings::Mappings): update naming
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
When the resulting trait item is in an error state this means the
underlying fields will be null.
Fixes#2478
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-item.cc: add is_error check
gcc/testsuite/ChangeLog:
* rust/compile/non_member_const.rs: add missing error message
* rust/compile/issue-2478.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
The function to get a literal from a string missed an implementation.
It did require a conversion function to achieve it, now that callback
system has been merged this function can be easily implemented.
gcc/rust/ChangeLog:
* expand/rust-proc-macro.cc (literal_from_string): Add callback
function.
(load_macros_array): Likewise.
ChangeLog:
* libgrust/libproc_macro/literal.cc (Literal__from_string): Add
implementation with call to constructor.
(Literal::make_literal): Add new constructor which calls the
callback.
* libgrust/libproc_macro/literal.h: Add new constructor's
prototype.
* libgrust/libproc_macro/proc_macro.cc (bridge_is_available):
Change symbol name to match convention.
* libgrust/libproc_macro/registration.h: Add lit_from_str
symbol.
* libgrust/libproc_macro/tokenstream.cc (TokenStream::make_tokenstream):
Change symbol name to disambiguate with literal from string.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
The literal conversion code could be used for the literal_from_string
callback, this means we should move it out of the function in it's own
function. This involves a new switch, which is quite sad but we're not
yet at a performance profiling phase, there may be lower hanging fruits.
gcc/rust/ChangeLog:
* util/rust-token-converter.cc (handle_suffix): Rework function
to make it work with the new literal conversion function.
(convert_literal): Add a new function to convert to a proc macro
literal from a literal tokenptr. The function will abort if the
pointer does not point to a literal.
(convert): Add call to convert literal for every literal case.
* util/rust-token-converter.h (convert_literal): Add public
prototype.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Move the function registered as a callback in a new anonymous namespace
in order to group every callback in the future under the same namespace.
gcc/rust/ChangeLog:
* expand/rust-proc-macro.cc: Remove static modifier and move to
an anonymous namespace.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Updated ErrorCode struct to enum class to enforce proper
error codes, similiar to rustc. For converting the enum
to the respective error code, I used a map and updated
make_description & make_url function accordingly and
also removes the memory leak from the previous frame-
work. Also, added macro to safely convert the enum
number to string.
gcc/rust/ChangeLog:
* backend/rust-compile-intrinsic.cc (Intrinsics::compile):
Formatted according to enum class.
* checks/errors/rust-feature-gate.cc (FeatureGate::gate): likewise.
* checks/errors/rust-unsafe-checker.cc (check_unsafe_call): likewise.
* hir/rust-ast-lower-base.cc (struct_field_name_exists): likewise.
* resolve/rust-ast-resolve-expr.cc (ResolveExpr::visit): likewise.
* resolve/rust-ast-resolve-path.cc (ResolvePath::resolve_path):
likewise.
* resolve/rust-ast-resolve-pattern.cc (PatternDeclaration::go): likewise.
(PatternDeclaration::add_new_binding): likewise.
* resolve/rust-ast-resolve-type.cc (ResolveRelativeTypePath::go): likewise.
* resolve/rust-ast-verify-assignee.h: likewise.
* rust-diagnostics.cc: updated make_desc & url function for enum class.
* rust-diagnostics.h (struct ErrorCode): removed struct to switch to enum.
(enum class): Switched from errorcode struct to enum class.
(XSTR): Macro for converting enum to string.
(STR): macro Used by XSTR for converting to string.
(ERROR_CODE): macro used by map for check.
(TABLE_TO_MAP): macro used by map for check
* typecheck/rust-casts.cc (TypeCastRules::emit_cast_error):
Formatted according to enum class.
* typecheck/rust-hir-path-probe.h: likewise.
* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit): likewise.
* typecheck/rust-hir-type-check-implitem.cc (TypeCheckTopLevelExternItem::visit):
likewise.
(TypeCheckImplItemWithTrait::visit): likewise.
* typecheck/rust-hir-type-check-item.cc: likewise.
* typecheck/rust-hir-type-check-pattern.cc (TypeCheckPattern::visit): likewise.
(emit_invalid_field_error): likewise.
* typecheck/rust-hir-type-check-struct.cc (TypeCheckStructExpr::resolve): likewise.
* typecheck/rust-tyty-call.cc (emit_unexpected_argument_error): likewise.
(TypeCheckCallExpr::visit): likewise.
* typecheck/rust-tyty-subst.cc (SubstitutionRef::get_mappings_from_generic_args):
likewise.
* typecheck/rust-tyty.cc (BaseType::bounds_compatible): likewise.
Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
Add multiple tests to prevent regressions on procedural macros errors
when one is declared outside of the crate's top level.
gcc/testsuite/ChangeLog:
* rust/compile/proc_macro_attribute_non_root_function.rs: New test.
* rust/compile/proc_macro_attribute_non_root_method.rs: New test.
* rust/compile/proc_macro_attribute_non_root_module.rs: New test.
* rust/compile/proc_macro_derive_non_root_function.rs: New test.
* rust/compile/proc_macro_derive_non_root_method.rs: New test.
* rust/compile/proc_macro_derive_non_root_module.rs: New test.
* rust/compile/proc_macro_non_root_function.rs: New test.
* rust/compile/proc_macro_non_root_method.rs: New test.
* rust/compile/proc_macro_non_root_module.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Check proc_macro, proc_macro_attribute and proc_macro_derive attributes
on non root functions, emit an error when one is found.
gcc/rust/ChangeLog:
* util/rust-attributes.cc (check_proc_macro_non_root): Add
function to emit this specific error.
(AttributeChecker::visit): Modify visitor to propagate to some
containers that were not handled correctly.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Initially a typedef was used to easily get the callback function pointer
type. Since this type has changed to a simpler well defined type, this
using declaration has no more purpose.
ChangeLog:
* libgrust/libproc_macro/proc_macro.cc: Remove type alias.
* libgrust/libproc_macro/registration.h: Likewise.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
This function prototype was forgotten when the function was deleted.
ChangeLog:
* libgrust/libproc_macro/proc_macro.h (proc_macro_register_from_str):
Remove rogue function prototype.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
There was no need to register a function when the value could be
registered directly.
gcc/rust/ChangeLog:
* expand/rust-proc-macro.cc (available): Remove function.
(load_macros_array): There was no need for an indirection here.
ChangeLog:
* libgrust/libproc_macro/proc_macro.cc (not_available): Remove
function.
* libgrust/libproc_macro/proc_macro.h (not_available): Remove
function prototype.
* libgrust/libproc_macro/registration.h: Change symbol type.
* libgrust/libproc_macro/bridge.h: New file.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add a callback from gcc to determine wether the bridge is available or
not.
gcc/rust/ChangeLog:
* expand/rust-proc-macro.cc (available): Add symbol
registration.
(load_macros_array): Likewise.
ChangeLog:
* libgrust/libproc_macro/proc_macro.cc (not_available): Add a
function to express bridge unavailability.
* libgrust/libproc_macro/proc_macro.h (not_available): Likewise.
* libgrust/libproc_macro/registration.h: Add symbol type.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
The symbol had a different convention from rust standard naming
convention (?) hence the change before adding new callback.
gcc/rust/ChangeLog:
* expand/rust-proc-macro.cc (load_macros_array): Symbol rename.
ChangeLog:
* libgrust/libproc_macro/proc_macro.cc (Procmacro::make_bang):
Change symbol name.
* libgrust/libproc_macro/registration.h: Likewise.
* libgrust/libproc_macro/tokenstream.cc (TokenStream::make_tokenstream): Likewise.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Refactor attribute search with early return. Also fix the optional
building an object with it's default empty constructor by explicitely
using tl::null_opt.
gcc/rust/ChangeLog:
* checks/errors/privacy/rust-privacy-reporter.cc (find_proc_macro_attribute):
Refactor the function to be safer and more efficient.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Refactor proc macro specific privacy check in multiple shorter
functions.
gcc/rust/ChangeLog:
* checks/errors/privacy/rust-privacy-reporter.cc (find_proc_macro_attribute):
Add a new function to find a potential proc macro type
attribute on a given item.
(proc_macro_privacy_check): Move all proc macro privacy check in
their own function to avoid cluttering the usual privacy check.
(PrivacyReporter::go): Add call to newly created proc macro
privacy check function.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Crates of type 'proc-macro' should not have any other pub member than
procedural macros. These new test will avoid regression on error
messages in such sitation.
gcc/testsuite/ChangeLog:
* rust/compile/proc_macro_pub_function.rs: New test.
* rust/compile/proc_macro_pub_module.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Some test were using dg-excess-errors instead of dg-error, this is now
fixed.
gcc/testsuite/ChangeLog:
* rust/compile/proc_macro_attribute_crate_type.rs: Replace
dg-excess-errors with dg-error and fix the line so the test
can pass.
* rust/compile/proc_macro_crate_type.rs: Likewise.
* rust/compile/proc_macro_derive_crate_type.rs: Likewise.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add some tests to prevent regression on private procedural macros error
messages.
gcc/testsuite/ChangeLog:
* rust/compile/proc_macro_attribute_private.rs: New test.
* rust/compile/proc_macro_derive_private.rs: New test.
* rust/compile/proc_macro_private.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Proc macro crates cannot have any public function but proc macros. Proc
macros should be public.
gcc/rust/ChangeLog:
* checks/errors/privacy/rust-privacy-reporter.cc (PrivacyReporter::go):
Add visibility verification.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add a bunch of test cases to avoid regressions on proc_macro_derive
attribute errors when placed on any non function item.
gcc/testsuite/ChangeLog:
* rust/compile/proc_macro_derive_non_function.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add a bunch of test case to avoid regressions on proc_macro_attribute
attribute error messages.
gcc/testsuite/ChangeLog:
* rust/compile/proc_macro_attribute_non_function.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add a bunch of test cases to avoid regressions on attribute error
message.
gcc/testsuite/ChangeLog:
* rust/compile/proc_macro_non_function.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
An error should be emitted when a proc_macro, proc_macro_attribute or
proc_macro_derive attribute is met on any non function item. Those
attribute shall be placed only on bare functions.
gcc/rust/ChangeLog:
* util/rust-attributes.cc (is_proc_macro_type): Add function to
identify matching proc macro attribute type.
(check_proc_macro_non_function): Add function to check and emit
error.
(AttributeChecker::visit): Add cal to new check function.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Remove the NodeId member from identifiers. This member did not make
sense and was solely used for procedural macros.
gcc/rust/ChangeLog:
* ast/rust-ast.h: Remove NodeId from identifiers.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Added error code support for using variadic parameters used
on Non-C ABI function. Fixes#2382
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-implitem.cc (TypeCheckTopLevelExternItem::visit):
Added check for error code support.
gcc/testsuite/ChangeLog:
* rust/compile/abi-vardaic.rs: New test.
Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
Recent changes in the rust interface on some extern C function shall be
synced up in the C++ library.
ChangeLog:
* libgrust/libproc_macro/literal.cc (Literal__from_string):
Update to match rust interface.
* libgrust/libproc_macro/literal.h (Literal__from_string):
Likewise.
* libgrust/libproc_macro/tokenstream.cc (TokenStream__from_string):
Likewise.
* libgrust/libproc_macro/tokenstream.h (TokenStream__from_string):
Likewise.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Two remaining structures in the rust interface were still using raw
string pointer and length couples to communicate with the C++ library
throught extern C functions. Using FFIString instead allow us to reduce
the scope of potential errors using those raw pointers. As FFIString
encapsulate raw pointer operations there will be only one locaiton to
look after.
ChangeLog:
* libgrust/libproc_macro/rust/bridge/literal.rs: Change extern C
function argument from raw string pointer and length to
FFIString.
* libgrust/libproc_macro/rust/bridge/token_stream.rs: Likewise.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
We wish to remove node ids from identifiers, because they do not make
that much sense and are only used for procedural macros anyway. This
means we either have to wrap those into a structure or converting them
to an existing structure that already have a node id. This commit
convert those meta word identifiers to a meta path SimplePath.
gcc/rust/ChangeLog:
* ast/rust-ast.h: Add new constructor for SimplePath from an
identifier.
* expand/rust-expand-visitor.cc (get_traits_to_derive): Add
conversion.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add multiple mappings for procedural macro name resolution.
Procedural macros were not resolved using name resolution and mapping
but rather with some hacky path comparison.
gcc/rust/ChangeLog:
* expand/rust-macro-expand.cc (MacroExpander::import_proc_macros):
Remove function.
* expand/rust-macro-expand.h (struct MacroExpander): Remove
import_proc_macro function.
* util/rust-hir-map.cc (Mappings::insert_derive_proc_macro_def):
Add a function to insert a derive proc macro definition.
(Mappings::insert_bang_proc_macro): Remove function.
(Mappings::insert_bang_proc_macro_def): Add function to insert a
bang proc macro definition.
(Mappings::insert_attribute_proc_macro_def): Likewise with
attribute proc macros.
(Mappings::lookup_derive_proc_macro_def): Add a function to
lookup a defined derive proc macro definition.
(Mappings::lookup_bang_proc_macro): Remove function.
(Mappings::lookup_bang_proc_macro_def): Add a function to lookup
a bang proc macro definition.
(Mappings::lookup_attribute_proc_macro_def): Add a function to
lookup an attribute prod macro definition.
(Mappings::insert_derive_proc_macro_invocation): Add a function
to insert a derive proc macro invocation.
(Mappings::lookup_derive_proc_macro_invocation): Add a function
to lookup a derive proc macro invocation.
(Mappings::insert_bang_proc_macro_invocation): Add a function to
insert a bang proc macro invocation.
(Mappings::lookup_bang_proc_macro_invocation): Add a function to
lookup a bang proc macro invocation.
(Mappings::insert_attribute_proc_macro_invocation): Add a
function to insert an attribute proc macro invocation.
(Mappings::lookup_attribute_proc_macro_invocation): Add a
function to lookup an attribute proc macro invocation.
* util/rust-hir-map.h: Add different proc macro mappings
and change function prototypes.
* expand/rust-expand-visitor.cc (get_traits_to_derive): Return a
vector of SimplePath instead.
(derive_item): Accept SimplePath instead of a string.
* ast/rust-ast.h: Add common ProcMacroInvocable interface to
Identifiers and SimplePath nodes.
* ast/rust-ast.cc: Add const modifier.
* ast/rust-macro.h: Change path and identifier getters.
* ast/rust-path.h: Change return type to reference.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Several meta items shall be downcasted in various places, this commit
introduces values to dispatch on.
gcc/rust/ChangeLog:
* ast/rust-ast.h (class MetaItem): Add MetaItem dispatch values.
* ast/rust-expr.h: Add LitExpr and PathLit dispatch.
* ast/rust-macro.h: Add remaining dispatch getters.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Create a mapping for procedural macros with their crate num.
gcc/rust/ChangeLog:
* metadata/rust-extern-crate.h: Add proc macro getter.
* rust-session-manager.cc (Session::load_extern_crate): Collect
mappings and create mappings.
* util/rust-hir-map.cc: Add insertion and lookup functions for
every mapping.
* util/rust-hir-map.h: Add function prototypes.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Also return a vector of proc macros when trying to open an external
crate.
gcc/rust/ChangeLog:
* metadata/rust-imports.cc (add_search_path): Change prototype,
now return a pair of Stream and procedural macro vector.
(Import::open_package): Likewise.
(Import::try_package_in_directory): Likewise.
* metadata/rust-imports.h: Likewise.
* rust-session-manager.cc (Session::load_extern_crate):
Likewise.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
This commit add the ability to specify the path to an extern crate
through the -frust-extern cli option. Path given as cli argument
shall resolve to the exact extern crate location.
gcc/rust/ChangeLog:
* metadata/rust-imports.h: Make the function to load a given
file public.
* rust-session-manager.cc (Session::load_extern_crate): Change
path resolution depending on extern crate declaration in cli
arguments.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add a new test to highlight possible future regressions on malformed
proc_macro_derive input.
gcc/testsuite/ChangeLog:
* rust/compile/proc_macro_derive_malformed.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add several tests to prevent regression with proc_macro,
proc_macro_derive and proc_macro_attribute attributes error messages.
gcc/testsuite/ChangeLog:
* rust/compile/proc_macro_attribute_crate_type.rs: New test.
* rust/compile/proc_macro_crate_type.rs: New test.
* rust/compile/proc_macro_derive_crate_type.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add an help message in case of malformed proc_macro_derive declaration.
gcc/rust/ChangeLog:
* util/rust-attributes.cc (AttributeChecker::visit): Add help
message.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
A derive procedural macro declaration shall always have at least a trait
to refer to. We should error out when it doesn't.
gcc/rust/ChangeLog:
* util/rust-attributes.cc (AttributeChecker::visit): Add
attribute input check.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
A procedural macroa attribute can only be used on proc macro crates.
gcc/rust/ChangeLog:
* util/rust-attributes.cc (AttributeChecker::visit): Add
attribute check on functions.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Change rust interface Ident definition to match C++ struct definition.
This structure now uses an FFIString instead of raw pointers.
ChangeLog:
* libgrust/libproc_macro/rust/bridge/ident.rs: Change raw
pointer string with an FFIString.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Use FFIString in Ident structure rather that a raw pointer and a
length, this will reduce the size of the code dealing with raw
pointers. Which should prevent some error.
gcc/rust/ChangeLog:
* util/rust-token-converter.cc (from_ident): Adapt code to new
constructor.
ChangeLog:
* libgrust/libproc_macro/ident.cc (Ident__new): Constructor
accepts an FFIString now.
(Ident__new_raw): Likewise.
(Ident::clone): Internal members change means clone also change.
(Ident::make_ident): Change constructor call.
(Ident::drop): Add call to FFIString::clone.
* libgrust/libproc_macro/ident.h (struct Ident): Remove raw
pointer and length, add an FFIString inside instead.
(Ident__new): Change constructor.
(Ident__new_raw): Change constructor.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add a callback registration function into the proc macro library so the
compiler can register it's own lexing/parsing functions on load.
gcc/rust/ChangeLog:
* expand/rust-proc-macro.cc (tokenstream_from_string): Add a
function that creates a tokenstream from a given string.
(load_macros_array): Add call to registration function.
ChangeLog:
* libgrust/libproc_macro/proc_macro.cc (proc_macro_register_from_str):
Add registration function.
* libgrust/libproc_macro/proc_macro.h (proc_macro_register_from_str):
Add registration function prototype.
* libgrust/libproc_macro/tokenstream.cc (TokenStream::make_tokenstream):
Add a new constructor from a string that uses the registered
callback.
(TokenStream__from_string): Add call to new constructor.
* libgrust/libproc_macro/tokenstream.h: Add registration
declaration.
* libgrust/libproc_macro/registration.h: New file.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add a new option to crab1 cli to accept crate type. This version of the
argument only accept a single crate type. Rustc accepts a comma
separated list of crate types but this might require a litle more work
for gcc.
gcc/rust/ChangeLog:
* lang.opt: Add option
* rust-session-manager.cc: Add option registration in session
target options.
* rust-session-manager.h (struct CompileOptions): Add new getter
for proc macros instead of a boolean.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
This data structure replaces our existing scopes and allows for multiple
name resolution passes to insert definitions or look up names at different
stages of the pipeline. The documentation goes into detail about how the
data structure works, and how the source's hierarchy is preserved
throughout the pipeline.
The class is templated to enforce specific behavior based on the namespace
the scope map targets.
gcc/rust/ChangeLog:
* resolve/rust-forever-stack.h: New file.
* resolve/rust-forever-stack.hxx: New file.
This class adds a basic Rib class for the new name resolution algorithm.
It uses `optional` and `expected` return types in order to try and
improve error handling in these new passes.
gcc/rust/ChangeLog:
* Make-lang.in: Add `rust-rib.cc` object.
* resolve/rust-rib.cc: New file.
* resolve/rust-rib.h: New file.
Co-authored-by: Matthew Jasper <mjjasper1@gmail.com>
Give error when an identifier was used like a function
name or a value was expected and the identifier exists
but it belongs to a different namespace.
gcc/rust/ChangeLog:
* typecheck/rust-tyty-call.cc (TypeCheckCallExpr::visit):
called error function.
gcc/testsuite/ChangeLog:
* rust/compile/found_struct.rs: New test.
Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
Refactored error message similiar to rustc.
gcc/rust/ChangeLog:
* backend/rust-compile-intrinsic.cc (Intrinsics::compile):
called error function.
gcc/testsuite/ChangeLog:
* rust/compile/torture/intrinsics-3.rs: Updated comment to pass the test case.
Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
Consider Signed-Off-By lines as part of the ending of the initial
commit to avoid having these in the middle of the log when the
changelog part is injected after.
This is particularly usefull with:
$ git gcc-commit-mklog --amend -s
that can be used to create the changelog and add the Signed-Off-By line.
Also applies most of the shellcheck suggestions on the
prepare-commit-msg hook.
contrib/ChangeLog:
* mklog.py: Leave SOB lines after changelog.
* prepare-commit-msg: Apply most shellcheck suggestions.
Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
Output escaped character values instead of their raw values in string.
gcc/rust/ChangeLog:
* lex/rust-token.cc (escape_special_chars): Add a function that
escape a given string.
(Token::as_string): Add call to escape function for string/char
representations.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Those interfaces missed a virtual destructor. This lead to several
warning.
gcc/rust/ChangeLog:
* ast/rust-ast.h: Add virtual destructor.
* expand/rust-macro-expand.h: Likewise.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Refactored error message for more
than one duplicate fields.
gcc/rust/ChangeLog:
* hir/rust-ast-lower-base.cc (struct_field_name_exists):
called error function.
gcc/testsuite/ChangeLog:
* rust/compile/bad_pub_enumitems.rs: changed comment to pass test cases.
* rust/compile/dup_fields.rs: likewise.
* rust/execute/same_field_name.rs: New test.
Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
gcc/rust/ChangeLog:
* resolve/rust-ast-verify-assignee.h: called error function.
gcc/testsuite/ChangeLog:
* rust/compile/wrong_lhs_assignment.rs: New test.
Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
Added Invalid number of arguments (argument mismatch)
was passed when calling a function - unexpected
number of arguments `x` expected `y` And Refactored
error into one function.
gcc/rust/ChangeLog:
* typecheck/rust-tyty-call.cc (emit_unexpected_argument_error):
Refactored invalid number of argument into one function.
(TypeCheckCallExpr::visit): called refactored function.
(TypeCheckMethodCallExpr::check): likewise.
gcc/testsuite/ChangeLog:
* rust/compile/func2.rs: updated comment to pass new test cases.
* rust/compile/tuple_struct2.rs: likewise.
* rust/compile/wrong_no_of_parameters.rs: New test.
Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
gcc/testsuite/ChangeLog:
* rust/compile/name_resolution1.rs: New test.
* rust/compile/name_resolution2.rs: New test.
* rust/compile/name_resolution3.rs: New test.
* rust/compile/name_resolution4.rs: New test.
* rust/compile/name_resolution5.rs: New test.
Co-authored-by: GuillaumeGomez <guillaume1.gomez@gmail.com>
This commit removes the poisoned includes as well as the exception throwing
mechanism of the original class.
gcc/rust/ChangeLog:
* util/optional.h: Adapt for GCC.
This is directly adapted from https://github.com/TartanLlama/optional.
This class is tested for C++11 and on GCC 4.8, which is our target mimimum
GCC version.
This optional class provides multiple advantages over our existing
implementation of Optional<T>:
- Easier API (no static constructors)
- Better method chaining (and_then, map...)
- Harsher semantics (no assign-through on Optional<T&>)
Over the std::optional type present in C++'s standard library, this type offers:
- Optional references without going through std::reference_wrapper
- Better method chaining
For these reasons, I am in favor of importing it directly rather than
adapt C++14's std::optional type to work with C++11 and GCC 4.8.
gcc/rust/ChangeLog:
* util/optional.h: New file.
Abi did output as several tokens instead of a fixed string.
gcc/rust/ChangeLog:
* ast/rust-ast-collector.cc (TokenCollector::visit): Fix abit
output format.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Fix remaining failing tests with trait and extern. Outer attributes were
missing and the semicolon did output on macro invocations.
gcc/rust/ChangeLog:
* ast/rust-ast-collector.cc (TokenCollector::visit): Fix
external item trailing semicolon and outer attributes.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Method qualifiers did not output correctly (no unsafe in the output).
gcc/rust/ChangeLog:
* ast/rust-ast-collector.cc (TokenCollector::visit): Fix method
qualifier output.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Trait impl block were missing a where clause for their output.
gcc/rust/ChangeLog:
* ast/rust-ast-collector.cc (TokenCollector::visit): Add where
clause.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Generics on the target structure did not correctly output.
gcc/rust/ChangeLog:
* ast/rust-ast-collector.cc (TokenCollector::visit): Fix generic
output.
gcc/testsuite/ChangeLog:
* rust/link/trait_import_0.rs: Mark test as xfail.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Generic in inherent impl block were did not output at all.
gcc/rust/ChangeLog:
* ast/rust-ast-collector.cc (TokenCollector::visit): Output
generic in inherent impl.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Space should be removed after the dollar sign, not before.
gcc/rust/ChangeLog:
* ast/rust-ast-dump.cc (Dump::require_spacing): Change dollar
spacing rule.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Match arm were not readable with previous format options.
gcc/rust/ChangeLog:
* ast/rust-ast-collector.cc (TokenCollector::visit): Change
formatting.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Generics were output two times and binding args were missing in
TypePathSegmentGeneric collection.
gcc/rust/ChangeLog:
* ast/rust-ast-collector.cc (TokenCollector::visit): Fix binding
args.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Function qualifiers did not output properly.
gcc/rust/ChangeLog:
* ast/rust-ast-collector.cc (TokenCollector::visit): Output
function qualifiers after visibility.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
A space was output around dots as well as after references, this made
things kinda horrible to look at and clearly not usual.
gcc/rust/ChangeLog:
* ast/rust-ast-dump.cc (Dump::require_spacing): Add a rule to
remove spaces around dots and after references.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Some ast subtrees where not correctly collected. Among those where macro
match repetition introducing empty tokens.
gcc/rust/ChangeLog:
* ast/rust-ast-collector.cc (TokenCollector::visit): Fix several
token collection rules.
* ast/rust-ast-dump.cc (Dump::require_spacing): Add spacing rule
for comma.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
This should help work towards the removal of Linemap/Gcc_linemap.
gcc/rust/ChangeLog:
* rust-linemap.cc
(Gcc_linemap::get_unknown_location): Remove.
(Gcc_linemap::get_predeclared_location): Remove.
(Gcc_linemap::is_predeclared): Remove.
(Gcc_linemap::is_unknown): Remove.
* rust-linemap.h
(Linemap::get_predeclared_location): Remove.
(Linemap::get_unknown_location): Remove.
(Linemap::is_predeclared): Remove.
(Linemap::is_unknown): Remove.
(Linemap::predeclared_location): Use BUILTINS_LOCATION.
(Linemap::unknown_location): Use UNKNOWN_LOCATION.
(Linemap::is_predeclared_location): Remove.
(Linemap::is_unknown_location): Remove.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
The parameters of any trait method must match between
a trait implementation and the trait definition
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-implitem.cc (TypeCheckImplItemWithTrait::visit):
called error function
Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
Added error code for Missing Field in
struct or struct-like enum variant.
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-struct.cc (TypeCheckStructExpr::resolve):
called error function.
gcc/testsuite/ChangeLog:
* rust/compile/missing_constructor_fields.rs: New test.
Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
missing foo in implementation of trait 'Foo'
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-item.cc: called error function.
Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
Ambiguous Method Call Error - more than one method
has the same prototype
gcc/rust/ChangeLog:
* typecheck/rust-hir-path-probe.h: called error function
Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
Associated type binding outside of type
parameter Declaration and where Clause
gcc/rust/ChangeLog:
* typecheck/rust-tyty-subst.cc (SubstitutionRef::get_mappings_from_generic_args):
called error function
Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
In order to setup the Output assoicated type we can rely on using generic
argument bindings. So for example when we have the FnOnce trait:
#[lang = "fn_once"]
pub trait FnOnce<Args> {
#[lang = "fn_once_output"]
type Output;
extern "rust-call" fn call_once(self, args: Args) -> Self::Output;
}
Thn we might have a function such as:
pub fn map<R, F: FnOnce(T) -> R>(self, f: F) -> Option<R> { ... }
This trait bound predicate of FnOnce(T) -> R we setup generics for the
bound as:
FnOnce<(T), Output=R>
This means we can reuse our generic arguments handling to get this support.
Fixes#2105
gcc/rust/ChangeLog:
* typecheck/rust-tyty-bounds.cc (TypeCheckBase::get_predicate_from_bound): track output
* util/rust-hir-map.cc (Mappings::lookup_trait_item_lang_item): new helper
* util/rust-hir-map.h: add prototype for helper
gcc/testsuite/ChangeLog:
* rust/compile/issue-2105.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
We were using the call-expr id for the autoderef mappings but this doesn't
work when the call expression itself is part of a coercion-site so this
changes the code to use the call-expression function path expression for
the id instead which will not be duplicated again.
Addresses #2105
gcc/rust/ChangeLog:
* backend/rust-compile-expr.cc (CompileExpr::generate_possible_fn_trait_call): use fnexpr
* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::resolve_fn_trait_call): likewise
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
A pattern for a struct fails to specify a sub-pattern
for every one of the struct's fields. - pattern does
not mention fields `x`, `y`
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-pattern.cc (TypeCheckPattern::visit): called rust_error_at
Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
Some class members were not accessible from outside, which will be needed
for the new HIR dump.
gcc/rust/ChangeLog:
* hir/tree/rust-hir-expr.h (AwaitExpr::get_awaited_expr): New.
(AsyncBlockExpr::get_has_move, AsyncBlockExpr::get_block_expr): New.
* hir/tree/rust-hir-item.h (Enum::get_where_clause): New.
(Trait::get_where_clause, Trait::is_unsafe): New.
(ExternalItem::get_visibility): New.
Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
Type hint value was not propagated correctly to LiteralPattern in ast.
This was defaulted to CORETYPE_STR instead, which introduced several
bugs with systems that did require any ast collection.
gcc/rust/ChangeLog:
* ast/rust-pattern.h: Change constructor to accept new parameter
instead of defaulting on string type.
* parse/rust-parse-impl.h (Parser::parse_literal_or_range_pattern):
Propagate type hint.
(Parser::parse_pattern_no_alt): Likewise.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
gcc/rust/ChangeLog:
* lex/rust-lex.cc (Lexer::parse_byte_char):add check for range of codepoint
gcc/testsuite/ChangeLog:
* rust/compile/bytecharstring.rs:add test for it
Signed-off-by: Raiki Tamura <tamaron1203@gmail.com>
Refactored field error function into one funciton
Fixes#2336
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-pattern.cc (emit_invalid_field_error): Refactored Field
Error Function
(TypeCheckPattern::visit): called emit_invalid_field_error function
Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
I copied swap_nonoverlapping badly from libcore which uses an unsafe
pointer case of x as *mut u8, I thought this was x as *mut T when i was
copying code form libcore this caused new infererence variables to be
introduced which actually automatically turned this swap_nonoverlapping
function to turn into a swap_nonoverlapping<u8> and lost the general
generic one in the type system context.
Rust allows for you to cast any pointer to another pointer of different
base type. The rules here are really subtle though because we need to
handle the case where we do really need to unify the types here there
are a few cases to consider but the main three are:
*u32 vs *u32 -> valid pointers match = simple coercion
*<?> vs *u8 -> inference variable unified with u8 which is valid
*T vs *u8 -> invalid coercion as the element types don't match
-> But this is a valid cast site
The code for casts try a coercion first then if that was sucsessful goes
on to perform a real coercion. Otherwise it follows the cast rules. The
bug here was that we saw the case of *T vs *u8 the try coercion used
inference variables to match T vs u8 but this will cause a cascase of
bad inference variables which we don't want when we perform the simple
coercion.
Fixes#2330
gcc/rust/ChangeLog:
* typecheck/rust-casts.cc (TypeCastRules::check): apply new argument
* typecheck/rust-coercion.cc (TypeCoercionRules::Coerce): track if this is a cast site
(TypeCoercionRules::TryCoerce): update ctor
(TypeCoercionRules::TypeCoercionRules): cleanup error handling
(TypeCoercionRules::do_coercion): likewise
(TypeCoercionRules::coerce_unsafe_ptr): only infer in try mode
(TypeCoercionRules::coerce_borrowed_pointer): cleanup
* typecheck/rust-coercion.h: update header
gcc/testsuite/ChangeLog:
* rust/compile/issue-1981.rs: Fix badly copied libcore code test
* rust/compile/issue-2330.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
This fixes an issue with our qualified type-paths if we point to a generic
associated type this needs to either use the placeholder type on the trait
reference or use the impl-type but apply the generics.
gcc/rust/ChangeLog:
* typecheck/rust-hir-trait-reference.h: update prototype
* typecheck/rust-hir-trait-resolve.cc: add generic args as an out param
* typecheck/rust-hir-type-check-type.cc (TypeCheckType::visit): use the generics
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
Store a custom type to differentiate formatting and metadata from data.
gcc/rust/ChangeLog:
* ast/rust-ast-collector.cc (TokenCollector::collect_tokens):
Filter tokens.
(TokenCollector::visit_items_joined_by_separator): Change store
call.
(TokenCollector::visit_as_line): Likewise.
(TokenCollector::visit_items_as_block): Likewise.
(TokenCollector::trailing_comma): Likewise.
(TokenCollector::visit): Likewise.
(TokenCollector::visit_closure_common): Likewise.
(TokenCollector::visit_function_common): Likewise.
* ast/rust-ast-collector.h (class CollectItem): Add class to
differentiate between formatting and raw data (tokens).
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
The token collector was using an external container but it was later
revealed that this whole reuse thing was not necessary.
gcc/rust/ChangeLog:
* ast/rust-ast-collector.cc (TokenCollector::TokenCollector):
Remove constructor, changing it to an implicit default
constructor.
* ast/rust-ast-collector.h: Change from container reference to
direct container.
* ast/rust-ast-dump.h: Change call to constructor.
* expand/rust-macro-expand.h (struct MacroExpander): Likewise.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Separating space shall not be output between every tokens to make the
dump clear and easy to read.
gcc/rust/ChangeLog:
* ast/rust-ast-dump.cc (Dump::require_spacing): Add a function
to determine wether a space shall output.
* ast/rust-ast-dump.h: Add function prototype as well as
condition.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Replace ast dump visitor with call to token collector.
gcc/rust/ChangeLog:
* ast/rust-ast-collector.cc (TokenCollector::visit): Add a visit
function for visitable abstract class so we can call a dump on
any visitable item.
* ast/rust-ast-collector.h: Add new visit function prototype.
* ast/rust-ast-dump.cc (Dump::go): Add call to process function.
(Dump::visit): Remove functions.
(Dump::visit_items_joined_by_separator): Likewise.
(Dump::visit_as_line): Likewise.
(Dump::visit_items_as_lines): Likewise.
(Dump::visit_items_as_block): Likewise.
(Dump::visit_function_common): Likewise.
(get_delimiters): Likewise.
(Dump::debug): Update with call to tokencollector.
* ast/rust-ast-dump.h (RUST_AST_DUMP_H): Move include
directives.
(class Dump): Remove multiple prototypes and add generic process
function.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
A final semicolon was missing after every items in an extern block.
gcc/rust/ChangeLog:
* ast/rust-ast-collector.cc (TokenCollector::visit): Add
semicolon in extern blocks.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
gcc/rust/ChangeLog:
* lex/rust-lex.cc (Lexer::build_token):add check for all kinds of whitespaces
gcc/testsuite/ChangeLog:
* rust/compile/torture/utf8_whitespaces.rs: New test.
Signed-off-by: Raiki Tamura <tamaron1203@gmail.com>
gcc/rust/ChangeLog:
* lex/rust-lex.cc (is_float_digit):Change types of param to `uint32_t`
(is_x_digit):Likewise
(is_octal_digit):Likewise
(is_bin_digit):Likewise
(check_valid_float_dot_end):Likewise
(is_whitespace):Likewise
(is_non_decimal_int_literal_separator):Likewise
(is_identifier_start):Likewise
(is_identifier_continue):Likewise
(Lexer::skip_broken_string_input):Likewise
(Lexer::build_token):Remove handling BOM
(Lexer::parse_in_type_suffix):Modify use of `current_char`
(Lexer::parse_in_decimal):Likewise
(Lexer::parse_escape):Likewise
(Lexer::parse_utf8_escape):Likewise
(Lexer::parse_partial_string_continue):Likewise
(Lexer::parse_partial_hex_escape):Likewise
(Lexer::parse_partial_unicode_escape):Likewise
(Lexer::parse_byte_char):Likewise
(Lexer::parse_byte_string):Likewise
(Lexer::parse_raw_byte_string):Likewise
(Lexer::parse_raw_identifier):Likewise
(Lexer::parse_non_decimal_int_literal):Likewise
(Lexer::parse_decimal_int_or_float):Likewise
(Lexer::peek_input):Change return type to `Codepoint`
(Lexer::get_input_codepoint_length):Change to return 1
(Lexer::peek_codepoint_input):Change to be wrapper of `peek_input`
(Lexer::skip_codepoint_input):Change to be wrapper of `skip_input`
(Lexer::test_get_input_codepoint_n_length):Deleted
(Lexer::split_current_token):Deleted
(Lexer::test_peek_codepoint_input):Deleted
(Lexer::start_line):Move backwards
(assert_source_content):New helper function for selftest
(test_buffer_input_source):New helper function for selftest
(test_file_input_source):Likewise
(rust_input_source_test):New test
* lex/rust-lex.h (rust_input_source_test):New test
* rust-lang.cc (run_rust_tests):Add selftest
Signed-off-by: Raiki Tamura <tamaron1203@gmail.com>
ErrorCode[E0023]: Incorrect Number of Fields in Pattern Extraction.
The pattern has x fields, but the corresponding tuple variant
has y field
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-pattern.cc (TypeCheckPattern::visit): called rust_error_at
Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
Non-Existent Field Extraction in Struct Pattern
variant `Foo::D` does not have a field named `b`
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-pattern.cc (TypeCheckPattern::visit): called rust_error_at
Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
This option enables an experimental name resolution algorithm. Disabled
by default.
gcc/rust/ChangeLog:
* lang.opt: Add -frust-name-resolution-2.0 option
It is unsafe to deref raw pointers during autoderef this adds a check to
stop autoderef early when we are about to try and deref pointers.
Fixes#2015
gcc/rust/ChangeLog:
* typecheck/rust-autoderef.cc (AutoderefCycle::cycle): add check for pointers
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
When we do operator overloading we can get multiple candidates and we need
to use the optional arguments to filter the candidates event further. In
the bug we had:
<integer> + <usize>
Without the Add impl blocks for the primitive interger types we unify
against the rhs to figure out that the lhs should be a usize but when we
are using the impl blocks we need to use the rhs to ensure that its
possible to coerce the rhs to the expected fntype parameter to filter the
candidates.
Fixes#2304
gcc/rust/ChangeLog:
* typecheck/rust-autoderef.cc: use new selection filter
* typecheck/rust-hir-dot-operator.cc (MethodResolver::Select): new slection Filter
* typecheck/rust-hir-dot-operator.h: New select prototype
* typecheck/rust-hir-type-check-expr.cc: call select
* typecheck/rust-type-util.cc (try_coercion): new helper
* typecheck/rust-type-util.h (try_coercion): helper prototype
gcc/testsuite/ChangeLog:
* rust/compile/issue-2304.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
Type Does Not Implement Expected Trait - the type [{integer}] cannot be indexed by u32
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit): passed "E0277"
* typecheck/rust-tyty.cc (BaseType::bounds_compatible): passed "E0277"
Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
Expressions are expanded in constant/static items, match expressions
and in parentheses now. Types are expanded in enum variants.
gcc/rust/ChangeLog:
* expand/rust-expand-visitor.cc (ExpandVisitor::visit):
Expand expressions in more contexts.
* resolve/rust-early-name-resolver.cc (EarlyNameResolver::visit):
Visit enum variants.
gcc/testsuite/ChangeLog:
* rust/compile/macro54.rs: New test.
* rust/compile/macro55.rs: New test.
Signed-off-by: Matthew Jasper <mjjasper1@gmail.com>
Change some argument name, as well as some documentation.
gcc/rust/ChangeLog:
* ast/rust-ast.cc (BlockExpr::normalize_tail_expr): Refactor
code and warn about dangling reference.
* expand/rust-expand-visitor.cc (expand_stmt_attribute):
Document function and change argument names to make those
clearer.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
The second argument could be derived from the first one, the second
argument is hence useless as the first argument alone could be kept to
access it's data.
gcc/rust/ChangeLog:
* expand/rust-expand-visitor.cc (ExpandVisitor::expand_inner_stmts):
Remove second argument.
(ExpandVisitor::visit): Remove argument from function call.
* expand/rust-expand-visitor.h: Update function prototype.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Some inner statements may be expanded to statements as well as a tail
expression, which should then be propagated to the parent tail
expression field.
gcc/rust/ChangeLog:
* expand/rust-expand-visitor.cc (ExpandVisitor::visit): Change
call to expand_inner_stmts.
(expand_tail_expr): Change argument name and try to expand the
last statement as a tail expression once all statements have
been expanded.
* expand/rust-expand-visitor.h: Change prototype to accept
parent class.
* ast/rust-expr.h: Add try_convert_last_stmt function prototype.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Tail expression may contain attribute and thus should be expanded.
gcc/rust/ChangeLog:
* ast/rust-expr.h: Add a function to take tail expr as well
as a function to set a tail expression.
* expand/rust-expand-visitor.cc (expand_tail_expr): Add tail
expression expansion function.
(ExpandVisitor::visit): Add call to tail expr expansion in for
BlockExpr.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
gcc/rust/ChangeLog:
* resolve/rust-ast-resolve-path.cc (ResolvePath::resolve_path): called rust_error_at
* resolve/rust-ast-resolve-type.cc (ResolveRelativeTypePath::go): called rust_error_at
Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
When we have an impl block for a generic type such as T which is a generic
type which does not 'bind' generic arguments, which means its not a type
such as an ADT or Fn which holds generic parameter mappings we need to
ensure inference variables are applied to the segment type apropriately so
that inference variables unified correctly and the higher ranked trait
bounds are as well.
Fixes: #1893
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-item.cc (TypeCheckItem::ResolveImplBlockSelfWithInference):
arguments mappings as an out parameter and apply them to the bounds
* typecheck/rust-hir-type-check-item.h: update the prototype
* typecheck/rust-hir-type-check-path.cc (TypeCheckExpr::resolve_segments):
apply the arguments to the segment type
gcc/testsuite/ChangeLog:
* rust/compile/issue-1893.rs: fully compile the test case
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
When we do generic argument substitution we creating mappings of the
HIR::GenericArgs argument to the TyTy::SubstitutionParam as a pointer. So
for example when we have Generic Parameters <Self, T> and arguments <T, U>
T0: Arguments: <Self=T, T=U>
T1: Self -> replaced-with T
T2: Arguments: <T=T, T=U>
T3: T maps back to the replace Self->T
T4: Arguments <T=T, T=T>
Which is wrong but because we do a string comparison to find the argument
mapping we cant reply on the pointer to the origin parameter mapping as
the parameter will be updated resulting in bad mappings.
This patch changes the Argument mappings to track the _original_ parameter
type so that lookup's for the mappings use this symbol instead not the
updated ones during substitution.
Addresses #1893
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-path.cc (TypeCheckExpr::resolve_segments):
simplify lookup of the respective predicate
* typecheck/rust-tyty-subst.cc (SubstitutionArg::SubstitutionArg): track original parameter
(SubstitutionArg::operator=): update copy ctor
(SubstitutionArg::get_param_ty): use original param
(SubstitutionArg::as_string): update as_string
* typecheck/rust-tyty-subst.h: add new private field
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
When we resolve a path segment the associated impl Self may not be a type
which 'binds' generic types. Which would be any type which does not inherit
SubstitionRef base class. There is a case where an impl block for generic
type T has bound generics on the trait bound of the trait impl block this
allows us to infer the T for this case.
Addresses #1893
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-item.cc (TypeCheckItem::ResolveImplBlockSelfWithInference):
New helper utility to infer non concrete types and handle the case where its not a
binding generic type (which inherits SubstitutionRef)
* typecheck/rust-hir-type-check-item.h: new helper prototype
* typecheck/rust-hir-type-check-path.cc (TypeCheckExpr::resolve_segments): use this helper
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
Using lookup_predciate by DefId is the safe way to get the relevant
predicate.
Addresses #1893
gcc/rust/ChangeLog:
* typecheck/rust-hir-trait-resolve.cc: use lookup_predicate (DefID)
* typecheck/rust-hir-type-check-path.cc (TypeCheckExpr::resolve_segments): fix formatting
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
gcc/rust/ChangeLog:
* ast/rust-ast.h (Expr::to_stmt): Remove method.
* ast/rust-macro.h (MacroInvocation::to_stmt): Remove override.
* ast/rust-stmt.h: Remove use of Expr::to_stmt.
* expand/rust-macro-expand.h (struct MacroExpander):
Add EXPR/STMT and remove BLOCK from ContextType.
* expand/rust-expand-visitor.cc (ExpandVisitor::maybe_expand_expr): Use EXPR context.
(ExpandVisitor::expand_inner_stmts): Use STMT context.
(ExpandVisitor::visitor): Remove use of BLOCK context.
* expand/rust-macro-expand.cc (transcribe_on_delimiter): Remove function.
(transcribe_context): Use EXPR/STMT contexts.
(MacroExpander::parse_proc_macro_output): Use EXPR/STMT contexts.
* parse/rust-parse-impl.h (Parser::parse_stmt):
Delegate macro parsing to parse_expr_stmt, check for ! after macro_rules.
(Parser::parse_expr_stmt):
Parse macro statements/expression statements starting with a macro.
(Parser::parse_match_expr): Don't modify flag unnecessarily.
(Parser::parse_stmt_or_expr):
Parse macro statements/expression statements starting with a macro.
(Parser::parse_path_based_stmt_or_expr): Remove method.
(Parser::parse_macro_invocation_maybe_semi): Remove method.
(Parser::parse_expr): Move code into left_denotations.
(Parser::left_denotations): New method.
(Parser::null_denotation): Split out methods for cases with and without paths.
(Parser::null_denotation_path): New method.
(Parser::null_denotation_not_path): New method.
(Parser::parse_macro_invocation_partial): Don't check for semicolon here.
* parse/rust-parse.h: Update declarations.
gcc/testsuite/ChangeLog:
* rust/compile/braced_macro_arm.rs: New test.
* rust/compile/braced_macro_statements1.rs: New test.
* rust/compile/braced_macro_statements2.rs: New test.
* rust/compile/braced_macro_statements3.rs: New test.
* rust/compile/issue-2225.rs: Update test.
Signed-off-by: Matthew Jasper <mjjasper1@gmail.com>
gcc/rust/ChangeLog:
* ast/rust-ast.h (MacroInvocation::add_semicolon): New method.
* ast/rust-macro.h (MacroInvocation::add_semicolon): Add override.
* ast/rust-stmt.h (ExprStmt::add_semicolon): Add override.
* expand/rust-macro-expand.cc (parse_many): Pass enum by value.
(transcribe_many_stmts): Parse statements with semicolons.
* parse/rust-parse-impl.h (Parser::parse_let_stmt):
Work around lack of NT tokens.
(Parser::parse_expr_stmt): Handle statements at end of macro expansions.
* parse/rust-parse.h (struct ParseRestrictions): Additional flag.
gcc/testsuite/ChangeLog:
* rust/compile/macro53.rs: New test.
Signed-off-by: Matthew Jasper <mjjasper1@gmail.com>
This allows braced macros at the end of blocks to correctly expand to
zero or more statements followed by a tail expression. Parsing still
creates a tail expression for now.
gcc/rust/ChangeLog:
* ast/rust-ast.cc (BlockExpr::strip_tail_expr):
Don't normalize tail expression in this method.
(BlockExpr::normalize_tail_expr): New method that only does the normalization.
* ast/rust-expr.h: Declare new method.
* hir/rust-ast-lower-block.h: Normalize tail expressions on blocks before lowering.
Signed-off-by: Matthew Jasper <mjjasper1@gmail.com>
gcc/rust/ChangeLog:
* lex/rust-lex.cc (is_whitespace):add all lacked codepoints valid as whitespaces
(is_identifier_start):new function to check XID_Start and underscore
(is_identifier_continue):new function to check XID_Continue
(Lexer::build_token):tokenize Unicode identifiers
(Lexer::parse_partial_string_continue):add comments
(Lexer::parse_partial_unicode_escape):add comments
(Lexer::parse_raw_identifier):change to use `is_identifier_scontinue`
(Lexer::parse_identifier_or_keyword):change to use `is_identifier_continue`
(Lexer::parse_char_or_lifetime):change to use `is_identifier_start/continue`
(Lexer::skip_codepoint_input):do not attempt to skip input when bumping EOF
* lex/rust-lex.h:add `current_char32` field
Signed-off-by: Raiki Tamura <tamaron1203@gmail.com>
gcc/rust/ChangeLog:
* lex/rust-lex.cc
(Lexer::classify_keyword): Check if iterator is valid before dereferencing.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
We use placeholders for assoicated types on traits but if we are unifying
types against a placeholder its not possible to check the bounds as the
placeholder does not have enough information yet at this point to determine
if bounds will or won't be satisfied. That check will occur when associated
types and generics are setup.
Fixes#2036
gcc/rust/ChangeLog:
* typecheck/rust-unify.cc (UnifyRules::go): dont check bounds on placeholders
gcc/testsuite/ChangeLog:
* rust/compile/issue-2036.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
Previously we were building libgrust even when not building the rust
compiler. Since libgrust is useless for any other frontend this commit
prevent it's build when it is not required.
ChangeLog:
* configure: Regenerate.
* configure.ac: Add condition to configure and build libgrust.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Fix the missing dependency between the gcc and libgrust.
ChangeLog:
* Makefile.def: Add a dependency to libgrust for all-gcc.
* Makefile.in: Regenerate the file.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Fixes#2019
gcc/rust/ChangeLog:
* backend/rust-compile-base.cc (HIRCompileBase::resolve_method_address):
match the fntype to the candidate
gcc/testsuite/ChangeLog:
* rust/compile/issue-2019-2.rs: New test.
* rust/compile/issue-2019-3.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
We have been concentrating on generic impl blocks for so long that we have
not handled the simple concrete impl block case where associated types need
to be setup when compling a function/method on a trait impl block which
uses associated types.
Addresses #2019
gcc/rust/ChangeLog:
* backend/rust-compile-item.cc (CompileItem::visit): ensure assoicated types are setup
* typecheck/rust-hir-trait-reference.h: new interface for concrete impl block
* typecheck/rust-hir-trait-resolve.cc (AssociatedImplTrait::setup_raw_associated_types):
ensure we setup assoicated types for this impl block
gcc/testsuite/ChangeLog:
* rust/compile/issue-2019-1.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
gcc/rust/ChangeLog:
* backend/rust-compile-expr.cc (check_match_scrutinee): Add REF type to rust_assert.
(CompileExpr::visit): Add REF type for scrutinee_kind in MatchExpr visitor.
gcc/testsuite/ChangeLog:
* rust/compile/issue-1813.rs: New test.
Signed-off-by: Dave Evans <dave@dmetwo.org>
This is an initiative to begin getting rid of the can_eq interface.
Addresses #2019
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-implitem.cc (TypeCheckImplItemWithTrait::visit):
use new interface
* typecheck/rust-type-util.cc (types_compatable): implementation of new interface
* typecheck/rust-type-util.h (types_compatable): prototype
* typecheck/rust-unify.cc (UnifyRules::expect_placeholder):
It is allow for unification against placeholders
gcc/testsuite/ChangeLog:
* rust/compile/traits2.rs: update error message
* rust/compile/traits3.rs: update error message
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
This string will never change and can be constified.
gcc/rust/ChangeLog:
* expand/rust-expand-visitor.cc (derive_item): Add const
attribute to the trait name argument.
* expand/rust-macro-expand.h (struct MacroExpander): Likewise.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Changes derive macro expansion to accept empty derive attributes. This
commit also add a test to prevent future regressions.
gcc/rust/ChangeLog:
* expand/rust-expand-visitor.cc (get_traits_to_derive): Change
assertion to allow empty derive directives.
gcc/testsuite/ChangeLog:
* rust/compile/derive_empty.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Expand custom attributes from procedural macros at item level.
gcc/rust/ChangeLog:
* expand/rust-expand-visitor.cc (expand_attribute): Add function
to expand a given attribute on a given item.
* expand/rust-macro-expand.h (struct MacroExpander): Change
return type to ast fragment.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add in order trait expansion using derive macros. Remove expansion of
outer attributes.
gcc/rust/ChangeLog:
* expand/rust-expand-visitor.cc (get_traits_to_derive): Change
the function to get traits in a given attribute instead of an
attribute vector.
(ExpandVisitor::expand_struct_fields): Remove call in visitor.
(ExpandVisitor::expand_function_params): Likewise.
(ExpandVisitor::expand_closure_params): Likewise.
(ExpandVisitor::visit): Likewise.
(ExpandVisitor::expand_outer_attribute): Remove function.
(ExpandVisitor::visit_outer_attrs): Remove function.
* expand/rust-expand-visitor.h: Remove function prototypes.
(ExpandVisitor::visit_outer_attrs): Remove function.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Procedural macros are no longer expanded on post order but rather
expanded from their parent. Hence they are no longer stored in the
expander which means this attribute can be removed. This commit also
remove the old expansion mechanism.
gcc/rust/ChangeLog:
* expand/rust-expand-visitor.h: Remove fragment collection fro
procedural macros.
* expand/rust-macro-expand.h (struct MacroExpander): Remove
procedural macro fragment from expander.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Builtin derive already had their own code scheme, incompatible with the
proc macro pattern. This commit unifies derive macros with it.
gcc/rust/ChangeLog:
* ast/rust-ast-fragment.cc (Fragment::Fragment): Remove
overwrite member in constructor.
(Fragment::operator=): Removal of overwrite member in copy.
(Fragment::should_overwrite): Remove overwrite getter.
* ast/rust-ast-fragment.h: Remove overwrite boolean member.
* expand/rust-expand-visitor.cc (derive_item): Add a function to
derive items using the expander for now.
(builtin_derive_item): Rename from derive_item to
builtin_derive_item.
(ExpandVisitor::visit): Remove visit to derive attributes.
(ExpandVisitor::expand_derive): Remove derive attribute visitor.
(ExpandVisitor::visit_attrs_with_derive): Likewise.
* expand/rust-expand-visitor.h: Update insertion of other kind
of proc macros. We no longer have an overwrite attribute in the
fragment.
* expand/rust-macro-expand.cc (MacroExpander::parse_procmacro_output):
Return the fragment instead of inserting it.
* expand/rust-macro-expand.h (struct MacroExpander): Return
fragment.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add a first draft for derive proc macros based on the attribute expander
code. Convert the result back to a parsable entity and parse it.
The procedural macro expander was beginning to require almost all
functionalities already provided by the macro expander, hence the merge.
gcc/rust/ChangeLog:
* ast/rust-ast-collector.h: Update enum name to match
definition.
* expand/rust-expand-visitor.cc (ExpandVisitor::expand_derive):
Add call to expander.
(ExpandVisitor::expand_outer_attribute):
Change call to macro expander.
(ExpandVisitor::expand_inner_attribute): Likewise.
* expand/rust-expand-visitor.h: Remove const attribute to match
visitor declaration. Attach result to the AST. Add condition for
item erasure.
* expand/rust-proc-macro.h: Add token collector and expansion
call. Add lexers and parsers for each proc macro type and uses
them to parse macro output.
* expand/rust-macro-expand.h (struct MacroExpander): Add
functions.
* expand/rust-proc-macro.cc (ProcMacroExpander::import_proc_macros):
Moved from here...
* expand/rust-macro-expand.cc (MacroExpander::import_proc_macros):
... to here. Unify procedural macro parsing under one function.
Add a flag to determine whether it originate from a derive
macro.
(MacroExpander::parse_procmacro_output):
Parse macro output to statements. Store an error on parsing
failure.
* Make-lang.in: Add const_TokenPtr specific lexer.
* expand/rust-proc-macro-invoc-lexer.cc: New file.
* expand/rust-proc-macro-invoc-lexer.h: New file.
* rust-session-manager.cc (Session::expansion): Remove
ProcMacroExpander declaration.
* ast/rust-ast-fragment.cc (Fragment::Fragment): Add overwrite
flag.
(Fragment::should_overwrite): Add a getter to determine whether
the fragment shall overwrite it's parent or be appended after.
* ast/rust-ast-fragment.h: Add flag to declaration.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add containers and functions to the hir-map in order to register and
lookup all three kind of procedural macros.
Add a first draft for attribute procedural macro expansion. This
expander still lack proper error handling as well as polishing.
gcc/rust/ChangeLog:
* util/rust-hir-map.cc (Mappings::insert_bang_proc_macro):
Add a function to insert a new bang proc macro.
(Mappings::lookup_bang_proc_macro): Add a function to lookup a
bang procedural macro.
(Mappings::insert_derive_proc_macro): Add a function to insert a
derive procedural macro.
(Mappings::lookup_derive_proc_macro): Add a function to lookup a
derive procedural macro.
(Mappings::insert_attribute_proc_macro): Add a function to
insert an attribute procedural macro.
(Mappings::lookup_attribute_proc_macro): Add a function to
lookup an attribute procedural macro.
* util/rust-hir-map.h: Add function prototypes.
* expand/rust-expand-visitor.cc (ExpandVisitor::expand_outer_attribute):
Implement expansion of outer attributes.
(ExpandVisitor::expand_inner_attribute):
Add call for inner attribute expansion.
* expand/rust-expand-visitor.h:
Add new procedural macro expander attribute.
* expand/rust-proc-macro.cc (load_macros_array): Add a function
to load the proc macro array from a given shared object.
(load_macros): Add a function to retrieve procedural macro
vector from a given shared object.
(ProcMacroExpander::import_proc_macros): Add a function to load
procedural macros from a given extern crate name.
* expand/rust-proc-macro.h (RUST_PROC_MACRO_H): Add new
proc-macro file.
(class ProcMacroExpander): Add new ProcMacroExpander class.
* rust-session-manager.cc (Session::expansion): Create new macro
expander and feed it to the expand visitor.
* util/rust-attributes.cc: Add macro_export builtin attribute.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Items attribute were not correctly collected and thus could not be
expanded from a previous macro invocation.
gcc/rust/ChangeLog:
* ast/rust-ast-collector.cc (TokenCollector::visit): Fix
attribute collection.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
TokenStream did not copy back enough old data to the new location. This
commit also add more explicit memcpy usages in order to facilitate
change to utf-8 later.
ChangeLog:
* libgrust/libproc_macro/ffistring.cc (FFIString::make_ffistring):
Add explicit sizeof and utf-8 warning.
(FFIString::clone): Add explicit sizeof and utf-8 warning.
* libgrust/libproc_macro/ident.cc (Ident::clone): Likewise.
(Ident::make_ident): Likewise.
* libgrust/libproc_macro/tokenstream.cc (TokenStream::grow):
Fix vector growth.
(TokenStream__clone): Add explicit sizeof.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
The capacity was not updated on tokenstream grow. This commit also add a
new mechanism to prevent a tokenstream to grow with a zero delta capacity.
ChangeLog:
* libgrust/libproc_macro/tokenstream.cc (TokenStream::grow): Add
minimum growing capacity.
(TokenStream::push): Change condition.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Make all trivial visitor functions public so we could easily call the
collection of an ast's subtree from any node.
gcc/rust/ChangeLog:
* ast/rust-ast-collector.h: Make trivial visitors public.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Rename procedural macro specializations without the "payload" suffix.
Those types will be reused in several places where the old suffix might
be counterintuitive.
ChangeLog:
* libgrust/libproc_macro/proc_macro.h (struct CustomDerivePayload):
Rename from CustomDerivePayload to...
(struct CustomDerive): ... CustomDerive
(struct AttrPayload): Rename from AttrPayload to ...
(struct Attribute): ... Attribute
(struct BangPayload): Rename from BangPayload to ...
(struct Bang): ... Bang
(union ProcmacroPayload): Update union with new names.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add a function to load a shared object procmacro and retrieve the list
of available procedural macros.
gcc/rust/ChangeLog:
* Make-lang.in: Add rust-proc-macro object to list.
* expand/rust-proc-macro.cc: New file.
* expand/rust-proc-macro.h: New file.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Standard types do not guarantee anything about their ABI and are
therefore unconvenient to use as a primarily exposed container.
With such asumption this commit introduces a container.
ChangeLog:
* libgrust/libproc_macro/proc_macro.h (struct ProcmacroArray):
Add ProcmacroArray definition.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add allow_internal_unstable to the attribute table in order for it to be
flagged as builtin.
gcc/rust/ChangeLog:
* util/rust-attributes.cc: Add attribute to the table.
Move implementation from cc file to header, in order to allow call from
other headers and prevent linker errors.
gcc/rust/ChangeLog:
* ast/rust-ast-collector.cc (TokenCollector::visit): Move
implementation from here...
* ast/rust-ast-collector.h: ... to here.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Concrete types can resolve to assoicated impl blocks which will allow us to
resolve the path to the projection type instead of the placeholder trait
associated type which can change. The projection will be fixed and is
safer to use.
Fixes#2165#2166
gcc/rust/ChangeLog:
* typecheck/rust-hir-trait-resolve.cc: when the bound is concrete keep the mapping
* typecheck/rust-hir-type-check-path.cc (TypeCheckExpr::visit): add missing call
* typecheck/rust-hir-type-check-type.cc (TypeCheckType::visit): make this the same as paths
gcc/testsuite/ChangeLog:
* rust/compile/issue-2165.rs: New test.
* rust/compile/issue-2166.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
This commit fixes printing of literals based on their
type.
Previous implementation printed literals the same, regardless
their type. Now we are printing:
* int, float, bool don't require special printing
* char -> '<char>'
* string -> "<string>"
* byte -> b'<byte>'
* byte_string -> b"<byte_string>"
gcc/rust/ChangeLog:
* ast/rust-ast-dump.cc (Dump::visit):
print literals based on their type.
Signed-off-by: Charalampos Mitrodimas <charmitro@gmail.com>
Fixes#2257.
Derive builtins do not need a real transcriber, but still need one. It
will however never be called since builtin derive macros get expanded
differently, and benefit from knowing on what kind of items they are
applied (struct, enums, unions) rather than receiving a list of tokens
like regular builtin macros.
gcc/rust/ChangeLog:
* expand/rust-macro-builtins.cc (MacroBuiltin::dummy): New function.
* expand/rust-macro-builtins.h: Declare it.
gcc/testsuite/ChangeLog:
* rust/compile/derive_macro7.rs: New test.
The bootstrap was failing due to a missing target which was not
available during the bootstrap.
ChangeLog:
* Makefile.def: Add libgrust target to bootstrap.
* Makefile.in: Regenerate.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
gcc/rust/ChangeLog:
* Make-lang.in: Add new files.
* expand/rust-derive.cc (DeriveVisitor::derive): Call into DeriveCopy.
* expand/rust-derive-copy.cc: New file.
* expand/rust-derive-copy.h: New file.
Refactor location to make code smaller and cleaner.
gcc/rust/ChangeLog:
* util/rust-token-converter.cc (convert): Use a variable instead
of multiple nested calls.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Use spans to get locations of expanded tokens instead of using unknown
locations.
gcc/rust/ChangeLog:
* lex/rust-lex.h: Make build_token method public.
* lex/rust-token.h: Add a setter for a token location.
* util/rust-token-converter.cc (convert): Add the function to
convert from a Span to a Location.
(from_ident): Convert Ident span to a Location.
(from_literal): Convert Literal span to a Location.
(from_punct): Convert Punct span to a Location.
(from_group): Convert Group span to a Location.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add function implementation to convert either a Location or a
RicheLocation to a libproc_macro span.
gcc/rust/ChangeLog:
* util/rust-token-converter.cc (convert): Add implementation.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add Span type definition in the rust interface.
ChangeLog:
* libgrust/libproc_macro/rust/bridge/group.rs: Add span member
to the Group structure.
* libgrust/libproc_macro/rust/bridge/ident.rs: Likewise with the
Ident structure.
* libgrust/libproc_macro/rust/bridge/literal.rs: Likewise with
the Literal structure.
* libgrust/libproc_macro/rust/bridge/punct.rs: Likewise with the
Punct structure.
* libgrust/libproc_macro/rust/bridge/span.rs: Add span
internals.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
gcc/rust/ChangeLog:
* rust-session-manager.h:
Include "rust-optional.h".
(struct TargetOptions):
Store values in config key/value pairs as Optional<std::string> rather than std::string.
* rust-session-manager.cc
(TargetOptions::dump_target_options):
Handle Optional<std::string> values.
gcc/testsuite/ChangeLog:
* rust/compile/cfg6.rs: New test.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
When attempting casts we can try a type coercion first, this is a
TryCoercion which will return a result. In the event this is ok we need to
perform a true coercion so that we don't leave missing infeence variable's
ununified.
Fixes#2195
gcc/rust/ChangeLog:
* typecheck/rust-casts.cc (TypeCastRules::check): do coercion
(TypeCastRules::emit_cast_error): clang-format
gcc/testsuite/ChangeLog:
* rust/compile/issue-2195.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
This fixes the issue but there are two cleanups to do at some point.
1. misc namesapce this is a scope AST namespace where we dump resolution
info when its not defined here. This occurs in the case such as nested
scopes where the nested scope is popped and we hit an assertion.
Outside of name resolution this requirement shouldnt really apply
it should be permissive to allow for this
2. We reuse our existing name resolution pieces here for Traits and impl
blocks we should start doing this for the other statements.
Fixes#2238
gcc/rust/ChangeLog:
* resolve/rust-ast-resolve-stmt.cc (ResolveStmt::visit): add name resolution
* resolve/rust-ast-resolve-stmt.h: likewise
* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit): insert resolved node
gcc/testsuite/ChangeLog:
* rust/compile/issue-2238.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
This adds the missing label scope and fixes the missing pop of the name
scope at the end of the resolution for a TraitImpl.
gcc/rust/ChangeLog:
* resolve/rust-ast-resolve-item.cc (ResolveItem::visit): fix missing pop
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
gcc/rust/ChangeLog:
* expand/rust-macro-substitute-ctx.cc
(SubstituteCtx::substitute_metavar): Allow substitution failure.
(SubstituteCtx::substitute_token):
Handle substitution failure, include dollar sign in count of tokens to substitute.
(SubstituteCtx::substitute_tokens):
Include dollar sign in count of tokens to substitute.
* expand/rust-macro-substitute-ctx.h
(SubstituteCtx::substitute_metavar):
Adjust signature and document new substitution failure handling.
gcc/testsuite/ChangeLog:
* rust/compile/issue-2225.rs: New test.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
We were missing bounds checking for both lhs and rhs directions this is
important as we might fail checking for all specified bounds properly.
This is why for #2236 we need the Type parameter T to realise that it
_cannot_ coerce to the i32 max function directly without any adjustments
because T has the specified bound of Deref but i32 does not implement
Deref. This indrectly forces the autoderef cycle to try a deref in order
to get an i32 which _will_ match the i32 max function in the case we
pass an &32 as the type parameter T.
Fixes#2236
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-path.cc (TypeCheckExpr::resolve_segments): stop if error
* typecheck/rust-tyty-bounds.cc (TypeBoundsProbe::assemble_sized_builtin): fix sized options
* typecheck/rust-tyty.cc (BaseType::satisfies_bound): its ok if its an ?T
(BaseType::bounds_compatible): likewise
* typecheck/rust-tyty.h: update prototype
* typecheck/rust-unify.cc (UnifyRules::go): check both sides bounds
gcc/testsuite/ChangeLog:
* rust/execute/torture/issue-2236.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
We can reuse the DefId to lookup the mappings to Items or Trait Items
instead of the HirId this is more generic and can then be reused for the
deref operator overload during autoderef cycles.
Addresses #2190
gcc/rust/ChangeLog:
* backend/rust-compile-base.cc (HIRCompileBase::resolve_method_address): refactor
* backend/rust-compile-base.h: likewise
* backend/rust-compile-expr.cc (CompileExpr::visit): likewise
* backend/rust-compile-resolve-path.cc (HIRCompileBase::query_compile): likewise
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
gcc/rust/ChangeLog:
* resolve/rust-early-name-resolver.cc (EarlyNameResolver::go): Cleanup
order of calls when accumulating #[macro_use] macros.
(EarlyNameResolver::visit): Likewise.
In #[cfg_attr(A, B, C(D))], only A is a predicate.
gcc/rust/ChangeLog:
* ast/rust-ast.cc (Attribute::check_cfg_predicate):
Only check first item as a predicate.
gcc/testsuite/ChangeLog:
* rust/compile/cfg-attr.rs: New test.
Signed-off-by: Matthew Jasper <mjjasper1@gmail.com>
Propagate back type suffix to created tokens.
gcc/rust/ChangeLog:
* ast/rust-ast-collector.cc (TokenCollector::visit): Propagate
coretype hint.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
gcc/rust/ChangeLog:
* ast/rust-ast.h: Add `outer_attrs` to Item.
* ast/rust-expr.h: Make use of new inheritance methods.
* ast/rust-item.h: Likewise.
* ast/rust-macro.h: Likewise.
Data from source pointer were not copied correctly in the ffistring
constructor.
ChangeLog:
* libgrust/libproc_macro/ffistring.cc (FFIString::make_ffistring):
Add copy from source pointer.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
This variable was redundant with the empty string representation and
may have lead to desync between both.
ChangeLog:
* libgrust/libproc_macro/literal.h: Remove has_suffix member
attribute from Literal.
* libgrust/libproc_macro/literal.cc: Update constructors.
* libgrust/libproc_macro/rust/bridge/literal.rs: Remove
has_suffix attribute from Literal.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Floating point and integer dispatch now have almost the same behavior,
their code could therefore be merged.
gcc/rust/ChangeLog:
* util/rust-token-converter.cc (dispatch_float_literals): Remove
function.
(handle_suffix): Rename old dispatch and add one LitKind
argument.
(dispatch_integer_literals): Remove function.
(convert): Change call from dispatch to suffix handler.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Change the literal representation on cpp side to match the new one in
rust. This means FFIString had to be implemented on cpp side. A few
helper functions has also been introduced.
ChangeLog:
* libgrust/libproc_macro/Makefile.am: Add ffistring unit to
compiled objects list.
* libgrust/libproc_macro/Makefile.in: Regenerate.
* libgrust/libproc_macro/literal.cc (Literal::drop): Change with
a call to ffistring drop function.
(Literal::make_literal): Add new helper constructor
(Literal__drop): Remove this function.
(Literal__string): Likewise.
(Literal__byte_string): Likewise.
(Literal__from_string): Moved this function.
(Literal::make_unsigned): Changed the constructor to match the
new layout.
(Literal::make_signed): Likewise.
(Literal::clone): Reimplement th eclone function.
(Literal::make_u8): Changed the constructor, make suffixed by
default.
(Literal::make_u16): Likewise.
(Literal::make_u32): Likewise.
(Literal::make_u64): Likewise.
(Literal::make_i8): Likewise.
(Literal::make_i16): Likewise.
(Literal::make_i32): Likewise.
(Literal::make_i64): Likewise.
(Literal::make_string): Likewise.
(Literal::make_byte_string): Likewise.
(Literal::make_f32): Likewise.
(Literal::make_f64): Likewise.
(Literal::make_char): Likewise.
(Literal::make_usize): Likewise.
(Literal::make_isize): Likewise.
(LitKind::make_byte): Add new helper constructor to avoid having
to set the payload value.
(LitKind::make_char): Likewise.
(LitKind::make_integer): Likewise.
(LitKind::make_float): Likewise.
(LitKind::make_str): Likewise.
(LitKind::make_str_raw): Add a new helper constructor which
takes the payload value as an argument.
(LitKind::make_byte_str): Add new helper constructor to avoid
mistakes with payload value.
(LitKind::make_byte_str_raw): Add a new helper constructor which
takes the payload value as an argument.
* libgrust/libproc_macro/literal.h: Add new functions prototype.
(enum UnsignedTag): Removed because it is now unused.
(struct Payload128): Likewise.
(union UnsignedPayload): Likewise.
(struct Unsigned): Likewise.
(enum SignedTag): Likewise.
(union SignedPayload): Likewise.
(struct Signed): Likewise.
(enum LiteralTag): Likewise.
(enum LitKindTag): Likewise.
(struct StringPayload): Likewise.
(struct ByteStringPayload): Likewise.
(union LitKindPayload): Likewise.
(struct UnsignedSuffixPayload): Likewise.
(struct LitKind): Add new literal kind struct representation to
match the enum on rust side.
(struct SignedSuffixPayload): Removed because now unused.
(struct UsizePayload): Likewise.
(struct IsizePayload): Likewise.
(struct Float32Payload): Likewise.
(struct Float64Payload): Likewise.
(union LiteralPayload): Likewise.
(struct Literal): Changed the internals of the structure.
(Literal__drop): Removed the drop function fom the c interface.
(Literal__string): Removed unused function.
(Literal__byte_string): Removed unused function.
* libgrust/libproc_macro/ffistring.cc: New file.
* libgrust/libproc_macro/ffistring.h: New file.
gcc/rust/ChangeLog:
* lex/rust-token.h: Implement hash for token id enumeration.
* util/rust-token-converter.cc (dispatch_float_literals): Update
to new internals.
(dispatch_integer_literals): Likewise.
(convert): Likewise.
(string_literal): Remove function.
(byte_string_literal): Likewise.
(unsigned_literal): Likewise.
(signed_literal): Likewise.
(from_literal): Update with new internals.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Rust interface literal internals were taking a type and storing that
type. This lead to multiple problems such as various conversion from
string to int/float/other type as well as dead end on undetermined types
(type checker runs at a later stage).
ChangeLog:
* libgrust/libproc_macro/rust/bridge.rs: Add ffistring module.
* libgrust/libproc_macro/rust/bridge/literal.rs: Rework type
internals.
* libgrust/libproc_macro/rust/bridge/ffistring.rs: New file.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
`{ ... }.f;` is parsed as a single statement in rust. This means that we can't
determine whether an expression statement will need a semicolon terminator
until we finish parsing it. To handle this we change expression parsing to
check for this case by inspecting the expression returned from null_denotation
and looking ahead for a `.` or `?` token.
gcc/rust/ChangeLog:
* ast/rust-ast.h (Expr::as_expr_without_block): Remove.
(Expr::set_outer_attrs): Make public in base class.
* expand/rust-macro-expand.cc:
Add fixme comment for pre-existing bug.
* hir/tree/rust-hir.h: Remove Expr::as_expr_without_block.
* parse/rust-parse-impl.h (Parser::parse_lifetime): Use lifetime_from_token.
(Parser::lifetime_from_token): New method.
(Parser::null_denotation): Handle labelled loop expressions and for loop expressions.
(Parser::parse_loop_label): Make initial token a parameter.
(Parser::parse_labelled_loop_expr): Likewise.
(Parser::parse_for_loop_expr): Allow FOR token to already be skipped.
(Parser::parse_expr): Handle expr_can_be_stmt.
(Parser::parse_expr_with_block): Remove.
(Parser::parse_expr_stmt_with_block): Remove.
(Parser::parse_expr_stmt_without_block): Remove.
(Parser::parse_expr_without_block): Remove.
(Parser::parse_stmt_or_expr_with_block): Remove.
(Parser::parse_expr_stmt): Use parse_expr directly.
(Parser::parse_match_expr): Likewise.
(Parser::parse_stmt): Use parse_expr_stmt in more cases.
(Parser::parse_stmt_or_expr):
Rename from parse_stmt_or_expr_without_block, use parse_expr directly.
(Parser::parse_block_expr): Update error message.
* parse/rust-parse.h: Update declarations.
gcc/testsuite/ChangeLog:
* rust/compile/for_expr.rs: New test.
* rust/compile/issue-407-2.rs: Update compiler output.
* rust/compile/issue-407.rs: Update compiler output.
* rust/compile/issue-867.rs: Update compiler output.
* rust/compile/issue-2189.rs: New test.
* rust/compile/macro_call_statement.rs: New test.
* rust/compile/stmt_with_block_dot.rs: New test.
* rust/compile/torture/loop8.rs: New test.
Signed-off-by: Matthew Jasper <mjjasper1@gmail.com>
The suffix condition was wrong, the code was assigning a suffix to
unsuffixed literals. The literals length equals the end of digit
parsing position means there is no suffix.
gcc/rust/ChangeLog:
* util/rust-token-converter.cc (dispatch_float_literals): Invert
suffix condition.
(dispatch_integer_literals): Likewise.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Fix multiple issues regarding style around loops and conditions with one
single element.
gcc/rust/ChangeLog:
* util/rust-token-converter.cc (convert): Fix style.
(from_ident): Likewise.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Inputs of the converter are never changed and may thus be qualified as
const.
gcc/rust/ChangeLog:
* util/rust-token-converter.cc (dispatch_float_literals): Make
input immutable.
(dispatch_integer_literals): Likewise.
(convert): Likewise.
* util/rust-token-converter.h (convert): Likewise.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add the implementation to convert an Ident structure back to a token.
gcc/rust/ChangeLog:
* util/rust-token-converter.cc (from_tokenstream): Add
conversion of Ident structures.
(from_ident): Likewise.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add the implementation of the function to convert Literal back to
tokens. Also change the function signature to accept const.
gcc/rust/ChangeLog:
* util/rust-token-converter.cc (from_literal): Add function
implementation.
(string_literal): String literal specific handler.
(byte_string_literal): Byte string specific handler.
(unsigned_literal): Unsigned literal specific handler.
(signed_literal): Signed literal specific handler.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add the implementation of the Punct conversion function to tokens.
gcc/rust/ChangeLog:
* util/rust-token-converter.cc (from_punct): Add conversion
implementation.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Make the conversion to tokenstream accept a const pointer vector instead
of a simple pointer vector because no changes are made to the original
tokens.
gcc/rust/ChangeLog:
* util/rust-token-converter.cc (dispatch_float_literals): Accept
const_TokenPtr instead of TokenPtr.
(dispatch_integer_literals): Likewise.
(convert): Accept vector of const_TokenPtr instead of a vector
of TokenPtr.
* util/rust-token-converter.h (convert): Likewise.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
We do not need mutability on the output vector. Also add an accumulator
for punct tokens.
gcc/rust/ChangeLog:
* util/rust-token-converter.cc (from_tokenstream): Add vector
for joined punct accumulation.
(from_ident): Accept const pointer vector.
(from_literal): Likewise.
(from_punct): Likewise.
(from_group): Likewise.
(from_tokentree): Likewise.
(convert): Likewise.
* util/rust-token-converter.h (convert): Likewise.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add the from_tokentree function which converts a tokentree to it's
token representation. This function was previously inlined in the
from_tokenstream function but I wanted to keep things clear and
coherent.
gcc/rust/ChangeLog:
* util/rust-token-converter.cc (from_tokenstream): Add call to
from_tokentree.
(from_tokentree): Add implementation, from the from_tokenstream
function.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add conversion of a given Group reference.
gcc/rust/ChangeLog:
* util/rust-token-converter.cc (from_punct): Add group
conversion.
(from_group): Likewise.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add a tokenstream conversion function dispatching to inner elements
gcc/rust/ChangeLog:
* util/rust-token-converter.cc (to_tokenstream): Change function
name from to_tokenstream to convert.
(convert): Likewise.
(from_tokenstream): Add tokenstream handler.
(from_ident): Add empty function.
(from_literal): Likewise.
(from_punct): Likewise.
(from_group): Likewise.
* util/rust-token-converter.h (to_tokenstream): Change function
name from to_tokenstream to convert.
(convert): Likewise.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Since the introduction of this variable the code has changed and no
value order preservation is required anymore, the comparison can be done
inline.
gcc/rust/ChangeLog:
* util/rust-token-converter.cc (dispatch_float_literals): Remove
suffixed temporary variable.
(dispatch_integer_literals): Likewise.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Move the token vector to tokenstream converter out of the TokenCollector
class. This code is not exactly related to the token collection and the
code would be clearer with this rather lengthy conversion split on it's
own.
gcc/rust/ChangeLog:
* Make-lang.in: Add new rust-token-converter file.
* ast/rust-ast-collector.cc (pop_group): Function moved from
TokenCollector.
(dispatch_float_literals): Likewise.
(dispatch_integer_literals): Likewise.
(TokenCollector::collect): Removed function.
* ast/rust-ast-collector.h: Removed function prototype.
* util/rust-token-converter.cc: New file.
* util/rust-token-converter.h: New file.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
The header guard did not match the file name anymore.
gcc/rust/ChangeLog:
* ast/rust-ast-collector.h (RUST_AST_TOKENSTREAM_H): Rename
headerguard from RUST_AST_TOKENSTREAM_H ...
(RUST_AST_COLLECTOR_H): ... to RUST_AST_COLLECTOR_H.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
The file does not contain any TokenStream declaration anymore and thus
should be named more appropriately.
gcc/rust/ChangeLog:
* Make-lang.in: Change file name.
* ast/rust-ast-tokenstream.cc: Moved to...
* ast/rust-ast-collector.cc: ...here.
* ast/rust-ast-tokenstream.h: Moved to...
* ast/rust-ast-collector.h: ...here.
* rust-session-manager.cc: Change header name.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Rename the TokenStream class to TokenCollector as it may induce errors
in the future as it is not a tokenstream as defined by the rust
interface. Furthermore this change match more closely the actual behavior
of the class.
gcc/rust/ChangeLog:
* ast/rust-ast-tokenstream.cc (TokenStream::TokenStream): Rename
TokenStream to TokenCollector.
(TokenCollector::TokenCollector): Likewise.
(TokenStream::collect_tokens): Likewise.
(TokenCollector::collect_tokens): Likewise.
(TokenStream::collect): Likewise.
(TokenCollector::collect): Likewise.
(TokenStream::visit): Likewise.
(TokenCollector::visit): Likewise.
(TokenStream::visit_items_joined_by_separator): Likewise.
(TokenCollector::visit_items_joined_by_separator): Likewise.
(TokenStream::visit_as_line): Likewise.
(TokenCollector::visit_as_line): Likewise.
(TokenStream::visit_items_as_lines): Likewise.
(TokenCollector::visit_items_as_lines): Likewise.
(TokenStream::visit_items_as_block): Likewise.
(TokenCollector::visit_items_as_block): Likewise.
(TokenStream::trailing_comma): Likewise.
(TokenCollector::trailing_comma): Likewise.
(TokenStream::newline): Likewise.
(TokenCollector::newline): Likewise.
(TokenStream::indentation): Likewise.
(TokenCollector::indentation): Likewise.
(TokenStream::increment_indentation): Likewise.
(TokenCollector::increment_indentation): Likewise.
(TokenStream::decrement_indentation): Likewise.
(TokenCollector::decrement_indentation): Likewise.
(TokenStream::visit_closure_common): Likewise.
(TokenCollector::visit_closure_common): Likewise.
(TokenStream::visit_loop_common): Likewise.
(TokenCollector::visit_loop_common): Likewise.
(TokenStream::visit_function_common): Likewise.
(TokenCollector::visit_function_common): Likewise.
* ast/rust-ast-tokenstream.h (class TokenStream): Likewise.
(class TokenCollector): Likewise.
* rust-session-manager.cc (Session::dump_tokenstream): Rename
token vector for clearer intent.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add the conversion handler for float/double literal tokens to
tokenstream Literals.
gcc/rust/ChangeLog:
* ast/rust-ast-tokenstream.cc (dispatch_float_literals): Add
dispatch function for floating point literals.
(TokenStream::collect): Add call to dispatcher.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add a first draft for the literal integer conversion to tokenstream
Literal types.
gcc/rust/ChangeLog:
* ast/rust-ast-tokenstream.cc (dispatch_integer_literals):
Add a static function to dispatch depending on the core type.
(TokenStream::collect): Add call to dispatch function.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add conversion to tokenstream Literals for string and byte strings.
gcc/rust/ChangeLog:
* ast/rust-ast-tokenstream.cc (TokenStream::collect): Add
conversion for byte string and string.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add the conversion from tokens to punct structures in tokenstream
conversion function.
gcc/rust/ChangeLog:
* ast/rust-ast-tokenstream.cc (TokenStream::collect): Add joint
punct token conversion.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add the code to convert single punctuation tokens to a tokenstream
element.
gcc/rust/ChangeLog:
* ast/rust-ast-tokenstream.cc (TokenStream::collect): Add
conversion for single punctuation tokens.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add conversion for group delimiters.
gcc/rust/ChangeLog:
* ast/rust-ast-tokenstream.cc (pop_group): Add a function to
easily collect a group from a given stack at the end of it.
(TokenStream::collect): Collect tokens as a rust compatible
Tokenstream type.
* ast/rust-ast-tokenstream.h (RUST_AST_TOKENSTREAM_H): Move
includes to stay constrained by guards.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Fixes Issue #1568
Added HIR node HIR::InlineAsm similar to the one found in rustc. In this
I also changed the defination of the AST::InlineAsm node, so that we can
reuse many of it's data members in the HIR::InlineAsm node.
gcc/rust/ChangeLog:
* ast/rust-ast-full-decls.h (enum class): Added declaration.
(struct AnonConst): Added declaration.
(struct InlineAsmRegOrRegClass): Added declaration.
(struct InlineAsmOperand): Added declaration.
(struct InlineAsmPlaceHolder): Added declaration.
(struct InlineAsmTemplatePiece): Added declaration.
(struct TupleClobber): Added declaration.
(struct TupleTemplateStr): Added declaration.
* ast/rust-expr.h (class InlineAsm): Defined all it's data members outside.
(enum class InlineAsmOptions): Converted this to a enum class so we could use it in the HIR.
(struct AnonConst): Defined it independent of the AST::InlineAsm node.
(struct InlineAsmRegOrRegClass): Defined it independent of the AST::InlineAsm node.
(struct InlineAsmOperand): Defined it independent of the AST::InlineAsm node.
(struct InlineAsmPlaceHolder): Defined it independent of the AST::InlineAsm node.
(struct InlineAsmTemplatePiece): Defined it independent of the AST::InlineAsm node.
(struct TupleClobber): Defined it independent of the AST::InlineAsm node.
(struct TupleTemplateStr): Defined it independent of the AST::InlineAsm node.
* hir/tree/rust-hir-expr.h (class InlineAsmReg): Added defination.
(class InlineAsmRegClass): Added defination.
(struct InlineAsmRegOrRegClass): Added defination.
(class InlineAsm): Added defination.
* hir/tree/rust-hir-full-decls.h (class InlineAsmReg): Added declaration.
(class InlineAsmRegClass): Added declaration.
(struct InlineAsmRegOrRegClass): Added declaration.
(class InlineAsm): Added declaration.
Signed-off-by: M V V S Manoj Kumar <mvvsmanojkumar@gmail.com>
DST's are not truely reference types they are "unsized types" so
the exact size of them is not known at compile time. We actually
achieve this by pretending they are a reference but really its
struct we pass around.
Fixes#2180
gcc/rust/ChangeLog:
* backend/rust-compile-expr.cc (CompileExpr::visit): refactr
(CompileExpr::get_fn_addr_from_dyn): likewise
(CompileExpr::get_receiver_from_dyn): likewise
(CompileExpr::type_cast_expression): likewise
* backend/rust-compile-type.cc (TyTyResolveCompile::visit): likewise
(TyTyResolveCompile::create_dyn_obj_record): likewise
(TyTyResolveCompile::create_slice_type_record): likewise
(TyTyResolveCompile::create_str_type_record): likewise
* backend/rust-compile-type.h: likewise
* backend/rust-compile.cc (HIRCompileBase::coercion_site1): likewise
(HIRCompileBase::coerce_to_dyn_object): refactor
* backend/rust-tree.h (SLICE_FLAG): removed
(SLICE_TYPE_P): removed
(RS_DST_FLAG): new flag
(RS_DST_FLAG_P): new predicate
* typecheck/rust-tyty.cc (ReferenceType::is_dyn_object): new helper
(ReferenceType::is_dyn_obj_type): likewise
(PointerType::is_dyn_object): likewise
(PointerType::is_dyn_obj_type): likewise
* typecheck/rust-tyty.h (class DynamicObjectType): moved up
gcc/testsuite/ChangeLog:
* rust/execute/torture/issue-2180.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
We had a very inconsistant way for dealing with unit-types in gccrs we
tried to optimize the case for a function returning unit type to be clever
and not emit any return value for unit types. Then for other cases we would
use an empty constructor for an empty tuple and in others use a zero
percsion integer. This was all just confusing and made the IR less
conformant to Rust. In this patch I change all of this to use an empty
tuple type for all cases so we pass around {} which maps over to Rust and
gets optimized away in the middle end anyway.
In the patch we also remove old gccgo code which optimizes away zero
size types to void_type_node which is why my original attempt at doing this
two years ago failed.
Fixes#2188
gcc/rust/ChangeLog:
* backend/rust-compile-base.cc (HIRCompileBase::compile_function_body): use unit_expression
(HIRCompileBase::unit_expression): new helper
* backend/rust-compile-base.h: update prototype
* backend/rust-compile-block.cc (CompileBlock::visit): use unit_expression
* backend/rust-compile-expr.cc (CompileExpr::visit): likewise
(CompileExpr::generate_closure_function): likewise
* backend/rust-compile-implitem.cc (CompileTraitItem::visit): cleanup
* backend/rust-compile-item.cc (CompileItem::visit): likewise
* backend/rust-compile-pattern.cc (CompilePatternLet::visit): likewise
* backend/rust-compile-resolve-path.cc (ResolvePathRef::resolve): likewise
* backend/rust-compile-type.cc (TyTyResolveCompile::get_unit_type): new helper
(TyTyResolveCompile::visit): use new unit_type helper
* backend/rust-compile-type.h: likewise
* rust-backend.h: simplify the return_expression
* rust-gcc.cc (Gcc_backend::function_type): likewise
(Gcc_backend::return_statement): likewise
* backend/rust-constexpr.cc (eval_constant_expression): remove bad assertion
gcc/testsuite/ChangeLog:
* rust/compile/issue-2188.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
Calling get variable expression will return an expression but we are
checking for unused decls so lets actually pass the decl.
Addresses #2188
gcc/rust/ChangeLog:
* checks/lints/rust-lint-unused-var.cc (UnusedVariables::Lint): use the decl not the expr
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
When we have a block expression for cosntants or statics we need to ensure
we compile the locals for the implicit function we generate in GIMPLE
before feeding it directly into the constant folder to evaluate the data.
Fixes#2178
gcc/rust/ChangeLog:
* backend/rust-compile-base.cc: add missing compile_locals call
gcc/testsuite/ChangeLog:
* rust/compile/issue-2178.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
gcc/rust/ChangeLog:
* resolve/rust-early-name-resolver.cc (is_macro_use_module): New function.
(EarlyNameResolver::accumulate_escaped_macros): New function.
(EarlyNameResolver::go): Use `accumulate_escaped_macros`.
(EarlyNameResolver::visit): Likewise.
* resolve/rust-early-name-resolver.h: Declare `accumulate_escaped_macros`.
gcc/testsuite/ChangeLog:
* rust/compile/macro_use1.rs: New test.
* rust/execute/torture/macro_use1.rs: New test.
* rust/compile/nested_macro_use1.rs: New test.
* rust/compile/nested_macro_use2.rs: New test.
Both the AST::Crate and AST::Module class are std::unique_ptr<AST::Item>
containers, and may require spurious insertions in these containers,
for example when expanding a procedural macro, or in our case, escaping
macros through the #[macro_use] attribute. These functions allow you
to replace *all* of the items contained in such a container.
gcc/rust/ChangeLog:
* ast/rust-ast.h: Add take_items() and set_items() method to Crate.
* ast/rust-item.h: Add take_items() and set_items() method to Module.
This commit regroups information related to builtin macros in one place instead
of spreading it over multiple files. It also adds a simple bi-directional
hashmap in order to perform lookups from a key as well as a value.
gcc/rust/ChangeLog:
* ast/rust-macro.cc (builtin_macro_from_string): Move function.
* ast/rust-macro.h (enum class): Move enum.
(builtin_macro_from_string): Move function.
* expand/rust-macro-builtins.cc (builtin_macro_from_string): New function.
(make_macro_path_str): Use new bi-map.
(parse_single_string_literal): Use new `BuiltinMacro` enum.
(MacroBuiltin::include_bytes_handler): Likewise.
(MacroBuiltin::include_str_handler): Likewise.
(MacroBuiltin::compile_error_handler): Likewise.
(MacroBuiltin::concat_handler): Likewise.
(MacroBuiltin::env_handler): Likewise.
(MacroBuiltin::include_handler): Likewise.
(MacroBuiltin::sorry): New function.
* expand/rust-macro-builtins.h (enum class): Move enum here.
(builtin_macro_from_string): New function declaration.
* resolve/rust-early-name-resolver.cc (EarlyNameResolver::visit): Use
new function.
* util/rust-hir-map.cc (Mappings::insert_macro_def): Remove old
builtin macro map.
Add the structures that should be used by a compiler opening a
procedural macro to either identify or execute it.
ChangeLog:
* libgrust/libproc_macro/proc_macro.h (struct CustomDerivePayload):
Add C compatible payload structure.
(struct AttrPayload): Likewise.
(struct BangPayload): Likewise.
(enum ProcmacroTag): Add tag for tagged union.
(union ProcmacroPayload): Proc macro payload union.
(struct Procmacro): Tagged union.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
gcc/rust/ChangeLog:
* ast/rust-ast.cc
(BlockExpr::strip_tail_expr):
Try to take new tail expression from statements list.
* ast/rust-expr.h
(BlockExpr::strip_tail_expr):
Replace definition with only declaration.
gcc/testsuite/ChangeLog:
* rust/execute/torture/cfg-tail.rs: New test.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
Add different include directives to the proc_macro header in order to
create an handy header much alike rust-system.
ChangeLog:
* libgrust/libproc_macro/proc_macro.h: Add Literal, Punct,
Group, TokenTree and Tokenstream headers.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
We do not need dynamic linking, all use case of this library cover can
be done statically hence the change.
gcc/rust/ChangeLog:
* Make-lang.in: Link against the static libproc_macro.
ChangeLog:
* libgrust/Makefile.am: Remove libtool forwarding.
* libgrust/Makefile.in: Regenerate.
* libgrust/libproc_macro/Makefile.am: Creates an archive instead
of using libtool.
* libgrust/libproc_macro/Makefile.in: Regenerate.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
This variable was not used in libproc_macro and made the build system
harder to read than it already is.
ChangeLog:
* libgrust/libproc_macro/Makefile.am: Remove gm2 variable
propagation.
* libgrust/libproc_macro/Makefile.in: Regenerate.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add a new option to gather extern crates location.
gcc/rust/ChangeLog:
* lang.opt: Add frust-extern option.
* rust-session-manager.cc (Session::handle_extern_option): Add
frust-extern option handler.
* rust-session-manager.h (struct Session): Add an unordered map
to store library name and locations.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
This is a case in #2019 where you have the default Add impl for i32 for
example which has:
impl Add for i32 {
fn add(self, other:i32) { self + other }
}
This function will do a check for operator overload which then is able to
find multiple candidates such as:
impl<'a> Add<i32> for &'a i32 {
type Output = <i32 as Add<i32>>::Output;
fn add(self, other: i32) -> <i32 as Add<i32>>::Output {
Add::add(*self, other)
}
}
This initial operator overload will resolve to this as it looks like a
valid candidate. This patch adds another level of checks to ensure the
candidate does not equal the current context DefId.
Addresses #2019
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-expr.cc: update for op overload
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
When resolving a qualified path we need to use the predicate to lookup the
relevant assoicated impl block where possible. The issue here is that
it might not have one due to a valid error in the impl block or it might
be used within a trait this is a valid case. Generally we will be able to
resolve to an impl block then it can grab that type and move on.
Fixes#2135
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-path.cc (TypeCheckExpr::visit): use the predicate
(TypeCheckExpr::resolve_segments): cleanup
gcc/testsuite/ChangeLog:
* rust/compile/issue-2135.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
This will look for a specified predicate that is associated with it so we
might have the predicate Foo<u16, i32> which would refer to:
impl Foo<i32> for u16 {}
This is a general helper which can be used in several places.
gcc/rust/ChangeLog:
* typecheck/rust-hir-trait-reference.cc (AssociatedImplTrait::AssociatedImplTrait):
bind the predicate
(AssociatedImplTrait::get_trait): remove
(AssociatedImplTrait::get_predicate): new getter
* typecheck/rust-hir-trait-reference.h: bind predicate
* typecheck/rust-hir-type-check-item.cc: update ctor
* typecheck/rust-type-util.cc (lookup_associated_impl_block): new function
* typecheck/rust-type-util.h (class BaseType): remove unused forward decl
(lookup_associated_impl_block): new helper
* typecheck/rust-tyty-bounds.cc (TypeBoundPredicate::is_equal): new
* typecheck/rust-tyty-subst.cc (SubstitutionRef::lookup_associated_impl): use new helper
(SubstitutionRef::monomorphize): update usage/error handling
* typecheck/rust-tyty-subst.h: remove old prototype
* typecheck/rust-tyty.h: add is_equal decl
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
This is required to solve #2105
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::resolve_fn_trait_call):
return the assoicated predicate
* typecheck/rust-hir-type-check-expr.h: update prototype
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
Use parentheses to remove any ambiguities when dumping expressions with
unary ! and -.
gcc/rust/ChangeLog:
* ast/rust-ast-dump.cc (Dump::visit): print parentheses around
unique expression operand.
Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
Addresses #2304
gcc/rust/ChangeLog:
* typecheck/rust-unify.cc (UnifyRules::emit_abi_mismatch): new error method
(UnifyRules::expect_fndef): add ABI check
* typecheck/rust-unify.h: prototype for new error method
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
When we have an untyped closure we assumed all parameters were inference
variables but we can use the pattern type to try and improve the type info
so if we have a reference pattern it must be a reference to an inference
variables '&_'. This patch adds a new visitor to figure this out for
untyped closure parameters.
Note this test case does fully type resolve into the gimple:
bool test::main::{{closure}}
(struct test::main::{{closure}} $closure, struct (& u8) args)
{ ... }
Though the Rustc version does fail type-resolution but we make some
assumptions during comparison expressions here that they resolve to a bool
this will change when we implement the comparison lang items.
Fixes#2142
gcc/rust/ChangeLog:
* hir/tree/rust-hir-pattern.h: add missing get_mutability
* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit):
use new ClosureParamInfer on untyped parameters
* typecheck/rust-hir-type-check-pattern.cc (ClosureParamInfer::Resolve): interface
(ClosureParamInfer::ClosureParamInfer): constructor
(ClosureParamInfer::visit): visitors for each pattern
* typecheck/rust-hir-type-check-pattern.h (class ClosureParamInfer): new visitor
gcc/testsuite/ChangeLog:
* rust/compile/issue-2142.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-pattern.cc (TypeCheckPattern::visit):
return so we dont hit undefined behaviour
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
gcc/rust/ChangeLog:
* lang.opt: add lang option flag
* rust-lang.cc (grs_langhook_init_options_struct): enable by default
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
gcc/rust/ChangeLog:
* typecheck/rust-tyty-bounds.cc (TypeBoundPredicate::operator=):
we are done if other is in an error state
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
We were missing a check for trait item selection to ensure they are
actually methods and remove assertion to check if the trait item is a
function this is a valid error check not an assertion.
Fixes#2139
gcc/rust/ChangeLog:
* typecheck/rust-hir-dot-operator.cc (MethodResolver::select): verify it is a method
gcc/testsuite/ChangeLog:
* rust/compile/issue-2139.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
When we handle generic trait bounds we never tracked its associated Self
type. Its important to remember a Trait Predicate is associated with a type
this means we end up missing a lot of helpful type information down the
line relating to higher ranked trait bounds and associated types
compuations. Remember traits have an implict Generic Type Parameter of Self
we use this in computing trait defintions so in that case no associated
type is specified which is to be expected but in all other cases we do
even if it is generic its still useful type information to keep track of.
There is one regression here with compile/issue-1893.rs this testcase
mostly worked out as a fluke rather than a proper fix so its no suprise
here it has regressed the other two test cases one where the number
generic arguments has changed, Rustc gets around this and has a seperate
error message for this case.
We need to solve this patch in order to solve #2019
gcc/rust/ChangeLog:
* typecheck/rust-hir-trait-resolve.cc (TraitResolver::resolve_trait): use new interface
* typecheck/rust-hir-type-check-base.h: update prototype to include Self
* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit): lifewise
* typecheck/rust-hir-type-check-item.cc (TypeCheckItem::resolve_impl_block_substitutions):
likewise
* typecheck/rust-hir-type-check-path.cc (TypeCheckExpr::visit): likewise
(TypeCheckExpr::resolve_segments): likewise
* typecheck/rust-hir-type-check-type.cc (TypeCheckType::visit): likewise
(TypeResolveGenericParam::visit): likewise
(ResolveWhereClauseItem::visit): likewise
* typecheck/rust-tyty-bounds.cc (TypeCheckBase::get_predicate_from_bound): likewise
(TypeBoundPredicate::apply_generic_arguments): likewise
(TypeBoundsMappings::lookup_predicate): likewise
* typecheck/rust-tyty-bounds.h: likewise
* typecheck/rust-tyty.h:likewise
gcc/testsuite/ChangeLog:
* rust/compile/issue-1893.rs: regression
* rust/compile/traits12.rs: rustc uses a custom error message here
* rust/compile/unconstrained_type_param.rs: extra error message
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
When checking current context we might be in the const or static context
which does not have a current function or impl or trait context associated
with it. So this allows us to represent the an error state for that case.
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check.h: New error state and missing copy implementations
* typecheck/rust-typecheck-context.cc (TypeCheckContextItem::TypeCheckContextItem):
missing copy ctor
(TypeCheckContextItem::operator=): missing copy implementation
(TypeCheckContextItem::get_error): new static function
(TypeCheckContextItem::is_error): new method
(TypeCheckContextItem::get_context_type): handle error state
(TypeCheckContextItem::get_defid): handle error state
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
When working in the resolve_operator_overload it was found that we got
memory corruption as method resolution will use the query system and
therefore resolve new methods and the current function context info will
change and due to the fact the peek_context interface returns a reference
to the element which was now safe from a vector which can change and all
you need is the current function context at that moment in time.
gcc/rust/ChangeLog:
* typecheck/rust-autoderef.cc: don't take a reference
* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit): likewise
* typecheck/rust-hir-type-check.h: remove reference
* typecheck/rust-typecheck-context.cc (TypeCheckContext::pop_return_type): likewise
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
These testcases are similar to the ones added in #2072 but regarding
execution. One more issue was opened from them - #2144
gcc/testsuite/ChangeLog:
* rust/execute/torture/issue-1852-1.rs: New test.
* rust/execute/torture/issue-1852.rs: New test.
Fix drop function by changing the delete operator to delete[] in order
to avoid undefined behaviors.
ChangeLog:
* libgrust/libproc_macro/literal.cc (Literal::drop): Change
delete operator to delete[].
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
TokenStream did not have any drop implementation, the memory could not
have been freed correctly.
ChangeLog:
* libgrust/libproc_macro/rust/bridge/token_stream.rs: Implement
drop.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Remaining structures from the rust bridge that missed a drop function
now have one.
ChangeLog:
* libgrust/libproc_macro/group.cc (Group::drop): Add drop
implementation.
* libgrust/libproc_macro/group.h: Add drop prototype.
* libgrust/libproc_macro/tokenstream.cc (TokenStream::drop): Add
drop implementation.
(TokenStream__drop): Change to a call to TokenStream::drop.
* libgrust/libproc_macro/tokenstream.h: Add drop prototype.
* libgrust/libproc_macro/tokentree.cc (TokenTree::drop): Add
drop implementation.
* libgrust/libproc_macro/tokentree.h: Add drop prototype.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add a drop function to clean internal fields of a Literal struct.
ChangeLog:
* libgrust/libproc_macro/literal.cc (Literal__drop): Replace
implementation by a call to Literal::drop.
(Literal::drop): Add drop implementation.
* libgrust/libproc_macro/literal.h: Add function prototype.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add a drop function that cleans internal fields of a given Ident struct.
ChangeLog:
* libgrust/libproc_macro/ident.cc (Ident__drop): Replace by call
to Ident::drop.
(Ident::drop): Add drop function.
* libgrust/libproc_macro/ident.h: Add drop prototype.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add remaining missing tokenstream structures. Most are interdependent.
ChangeLog:
* libgrust/libproc_macro/Makefile.am: Add tokenstream,
group and tokentree source files.
* libgrust/libproc_macro/Makefile.in: Regenerate.
* libgrust/libproc_macro/group.cc: New file.
* libgrust/libproc_macro/group.h: New file.
* libgrust/libproc_macro/tokenstream.cc: New file.
* libgrust/libproc_macro/tokenstream.h: New file.
* libgrust/libproc_macro/tokentree.cc: New file.
* libgrust/libproc_macro/tokentree.h: New file.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
In https://gcc.gnu.org/PR108890 "Translation mistakes 2023"
@rillig lists several issues with GCC/Rust diagnostics and
option help texts (but also a few non-GCC/Rust).
This commit fix mistakes only related to GCC/Rust,
specifically to the file `gcc/rust/lang.opt`.
closes https://github.com/Rust-GCC/gccrs/issues/1916
PR translation/108890
gcc/rust/
* lang.opt: Fix translation mistakes 2023 in
GCC/Rust [PR108890]
(line 67): change the inconsistent tab to spaces
(line 75): wrap bare placeholder `integer`
(line 79): remove redundant text of `Choose which`
(line 96): remove redundant text of `Choose which`
(line 112): remove redundant `Flag to`
(line 124): correct the exclusive term `When to stop`
(line 124): correct typo of `copimlation`
Signed-off-by: Tieway59 <tieway59@foxmail.com>
Add Punct struct for rust interface as well as a basic named
constructor.
ChangeLog:
* libgrust/libproc_macro/Makefile.am: Add punct.cc.
* libgrust/libproc_macro/Makefile.in: Regenerate.
* libgrust/libproc_macro/punct.cc: New file.
* libgrust/libproc_macro/punct.h: New file.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add a new Ident namespace to group Ident related enumeration and
structures.
ChangeLog:
* libgrust/libproc_macro/ident.cc (Ident::make_ident): Add Ident
namespace.
* libgrust/libproc_macro/ident.h (Ident__clone): Likewise.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add named constructor directly in Ident struct.
ChangeLog:
* libgrust/libproc_macro/ident.cc (Ident__new): Use named
constructor.
(Ident__new_raw): Use named constructor.
(Ident__clone): Use clone member function.
(Ident::clone): Make clone const.
(Ident::make_ident): Add named construcot.
* libgrust/libproc_macro/ident.h (struct Ident): Add named
constructor prototypes.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Change rust interface on drop function to take a mut pointer instead.
This will match the drop trait interface more closely.
ChangeLog:
* libgrust/libproc_macro/rust/bridge/ident.rs: Change drop
function interface.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add implementation and representation for ident cpp structure as well as
a high level wrapper interface.
ChangeLog:
* libgrust/libproc_macro/Makefile.am: Add ident to source list.
* libgrust/libproc_macro/Makefile.in: Regenerate.
* libgrust/libproc_macro/ident.cc: New file.
* libgrust/libproc_macro/ident.h: New file.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Fixes#2021, #2022
Deleted Parser::debug_dump_ast_output, removed any functions that called
it i.e Session::dump_ast and Session::dump_ast_expanded, and any
associated items.
Made it so that when you use the dump option "expanded" it dumps the
pretty ast only.
gcc/rust/ChangeLog:
* parse/rust-parse-impl.h (Parser::debug_dump_ast_output): Removed this funtion.
* rust-session-manager.cc (Session::enable_dump): Removed else if (arg == "parse").
(Session::compile_crate): Removed calls of dump_ast and dump_ast_expanded.
(Session::dump_ast): Removed this function.
(Session::dump_ast_expanded): Removed this function.
* rust-session-manager.h (struct CompileOptions): Removed the PARSER_AST_DUMP option.
Signed-off-by: M V V S Manoj Kumar <mvvsmanojkumar@gmail.com>
Reference patterns cannot contain AltPatterns per the Rust reference,
so we should not call into `parse_pattern` to parse the referenced pattern,
but rather the more restrictive `parse_pattern_no_alt`.
gcc/rust/ChangeLog:
* parse/rust-parse-impl.h (Parser::parse_reference_pattern): Do not
call into `parse_pattern` anymore.
gcc/testsuite/ChangeLog:
* rust/compile/issue-1807.rs: New test.
Add a Literal namespace to gather all every literal related code.
ChangeLog:
* libgrust/libproc_macro/literal.cc (Literal__from_string):
Add abort because unimplemented.
* libgrust/libproc_macro/literal.h (Literal__from_string): Add
namespace.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
The rust API requires a mut reference, hence having a mutable pointer
seems to match better. Furthermore the implementation is now modifying
the struct in order to set the size to 0 instead of simply freeing the
data, this will allow us to easily identify mistaken manual call to this
function.
ChangeLog:
* libgrust/libproc_macro/rust/bridge/literal.rs: Make the
pointer mutable.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add literal type related ffi functions implementation.
ChangeLog:
* libgrust/libproc_macro/Makefile.am: Add literal.cc.
* libgrust/libproc_macro/Makefile.in: Regenerate.
* libgrust/libproc_macro/literal.h (Literal__drop): Implement
drop.
(Literal__string): Constructor from a string function prototype.
(Literal__byte_string): Constructor from a byte string function
prototype.
(Literal__from_string): Add function body, no implementation
yet.
* libgrust/libproc_macro/literal.cc: New file.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
The associated type was not kept in the tokenstream.
gcc/rust/ChangeLog:
* ast/rust-ast-tokenstream.cc (TokenStream::visit): Keep
associated type.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Function body were skipped in tokenstream when no return type was
provided.
gcc/rust/ChangeLog:
* ast/rust-ast-tokenstream.cc (TokenStream::visit_function_common):
Fix function body output.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
In some cases, while parsing an outer attribute, the parser would return
an inner attribute.
gcc/rust/ChangeLog:
* parse/rust-parse-impl.h (Parser::parse_outer_attribute): Fix
attribute status.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
When we encounter a "break rust" statement, emit a funny error message
and intentionally cause an ICE. This matches the corresponding Easter
egg in rustc. As a GNU extension, "break gcc" is also supported.
The conditions for this to happen are:
* The break expression must be literally "rust" or "gcc". For instance,
"break (rust)" will not trigger the Easter egg.
* The name ("rust" or "gcc") must not be in scope; if it is, no error
is emitted, and the compilation proceeds as usual. In other words,
this only affects how GCC diagnoses programs that would fail to
compile anyway.
Note that this is different from the conditions under which rustc emits
its ICE. For rustc, it matters whether or not the "break" is inside a
loop, and for us it matters whether or not the name resolves. The end
result should be the same anyway: valid programs continue to compile,
and typing in
fn main() {
break rust;
}
triggers a funny ICE.
Closes https://github.com/Rust-GCC/gccrs/issues/1996
gcc/rust/ChangeLog:
* resolve/rust-ast-resolve-expr.cc: Add "break rust" Easter egg
gcc/testsuite/ChangeLog:
* lib/prune.exp (prune_ices):
Also prune "You have broken GCC Rust. This is a feature."
* rust/compile/break-rust1.rs: New test
* rust/compile/break-rust2.rs: New test
* rust/compile/break-rust3.rs: New test
Signed-off-by: Sergey Bugaev <bugaevc@gmail.com>
...and thread it through the constructors and the ResolveExpr::go ()
method.
This will be used for implementing the "break rust" Easter egg.
gcc/rust/ChangeLog:
* resolve/rust-ast-resolve-expr.h,
resolve/rust-ast-resolve-expr.cc: Add ResolveExpr::funny_error
Signed-off-by: Sergey Bugaev <bugaevc@gmail.com>
...and return it from IdentifierExpr::get_ast_kind (). This enables
other code to dynamically test whether an expression is in fact an
IdentifierExpr.
gcc/rust/ChangeLog:
* ast/rust-ast.h: Add AST::Kind::IDENTIFIER
Signed-off-by: Sergey Bugaev <bugaevc@gmail.com>
We're going to introduce AST::Kind::IDENTIFIER next, and with the
default C-style enum member scoping, this would cause name clashes.
Instead, convert AST::Kind into an enum class, so that its members
are properly namespaced.
gcc/rust/ChangeLog:
* ast/rust-ast.h (Kind): Convert into a C++ enum class
* expand/rust-macro-builtins.cc: Adapt to the change
Signed-off-by: Sergey Bugaev <bugaevc@gmail.com>
A matcher like $(a),? is no longer accepted.
Fixes#2092.
gcc/rust/ChangeLog:
* parse/rust-parse-impl.h
(Parser<ManagedTokenSource>::parse_macro_match_repetition):
reject separator in `?` repetition
gcc/testsuite/ChangeLog:
* rust/compile/macro-issue2092.rs: New test.
Signed-off-by: Sebastian Kirmayer <gnu@kirmayer.eu>
StructExprStructFields inherit from StructExprStruct and shall output
the struct name and curly braces.
gcc/rust/ChangeLog:
* ast/rust-ast-tokenstream.cc (TokenStream::visit): Add struct
name and curly braces to output tokenstream.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
'gcc/tree.h':
#define main_identifier_node global_trees[TI_MAIN_IDENTIFIER]
#define MAIN_NAME_P(NODE) \
(IDENTIFIER_NODE_CHECK (NODE) == main_identifier_node)
..., which is not initialized by default, but has to be set up by every front
end individually. 'MAIN_NAME_P' enables certain code optimizations, but is
especially also relevant for back ends that emit additional program entry setup
code for 'main'.
gcc/rust/
* backend/rust-compile-base.cc (HIRCompileBase::compile_function):
For 'main', initialize 'main_identifier_node'.
'gcc/tree.h':
#define main_identifier_node global_trees[TI_MAIN_IDENTIFIER]
#define MAIN_NAME_P(NODE) \
(IDENTIFIER_NODE_CHECK (NODE) == main_identifier_node)
..., which is not initialized by default, but has to be set up by every front
end individually. 'MAIN_NAME_P' enables certain code optimizations, but is
especially also relevant for back ends that emit additional program entry setup
code for 'main'.
gcc/rust/
* backend/rust-compile-base.cc (HIRCompileBase::compile_function):
Handle 'main' specially.
* rust-lang.cc (grs_langhook_init): Initialize
'main_identifier_node'.
Inner attribute did not output exclamation tokens as there was no way to
differentiate inner from outer attributes previously.
gcc/rust/ChangeLog:
* ast/rust-ast-tokenstream.cc (TokenStream::visit): Fix inner
attribute tokenstream output.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
AST::Visitable is an abstract class with a unique accept_vis() method.
Make all abstract AST node class inherit from this class.
Allows for easy definition of operations on nodes that must accept a
visitor.
The static Dump::dump() is an example of such use: the static method
accepts any AST node, creates a Dump visitor and have it visit the AST
starting at the node.
This change also inserts a debug(Visitable&) function in the global
namespace to make it easy to call from the debugger (similar to
debug_tree or debug(rtx*) functions).
gcc/rust/ChangeLog:
* ast/rust-ast-dump.cc (Dump::debug): New.
* ast/rust-ast-dump.h (Dump::debug): Untemplate it.
(debug): New.
* ast/rust-ast.h (class Visitable): New.
(class TokenTree): Inherit from Visitable.
(class MacroMatch): Likewise.
(class AttrInput): Likewise.
(class MetaItemInner): Likewise.
(class Pattern): Likewise.
(classTypeParamBound): Likewise.
(class GenericParam): Likewise.
(class TraitItem): Likewise.
(classInherentImplItem): Likewise.
(class TraitImplItem): Likewise.
(class ExternalItem): Likewise.
(class SingleASTNode): Likewise.
Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
Yesterday's commit 3757e8d717
"Merge commit '6baa95c9c5b3fea96fd22d03d961db4e4cf48d88' into HEAD [#2112]"
brought in the #1713 change from GCC upstream master branch that broke the
rules (via code copied verbatim from elsehwhere in GCC).
gcc/rust/
* rust-lang.cc (grs_langhook_type_for_mode): Placate clang-format.
In #2112 'Merge upstream, last commit before "Rust front-end update 2023-04-05"'
we merged commit 939fb3fffe from upstream GCC
master branch.
This one now merges the "Rust front-end update 2023-04-05", commits
939fb3fffebf7be2638ddef25dbe1c15f2aaa9d6..d2a499a9881c7c079d2a722b57c7fcf022a864dd:
- f66b135d0b gccrs: fatal_error_flag: Fix typo in error message
- 776ff05380 gccrs: unsafe: check use of `target_feature` attribute
- d9e05700ac gccrs: Check for mutable references in const functions
- ef792b9658 gccrs: rust: add bound parsing in parse_generic_arg.
- e1394230b3 gccrs: Implement declarative macro 2.0 parser
- 3f1dbb2cf8 gccrs: Add name resolution to generic argument associated item bindings
- 7eab9d18d9 gccrs: Support associated type bound arguments
- 364f4cd307 gccrs: Reuse TypeCheckPattern on LetStmt's
- 8e2abbef4c gccrs: Add get_locus function for abstract class MetaItemInner.
- 86f8e47f9d gccrs: diagnostics: Add underline for tokens in diagnostics.
- 881ed7fb27 gccrs: Change how CompileVarDecl outputs Bvariable's
- 60affc3a1c gccrs: testsuite: Handle Windows carriage returns properly
- 910e7e0a95 gccrs: Support GroupedPattern during name resolution
- cb42610bfb gccrs: Do not crash on empty macros expand. Fixes#1712
- 93fcadd208 gccrs: Add HIR lowering for GroupedPattern
- d5a303cc66 gccrs: Add get_item method for HIR::GroupedPattern
- 83e5f634d7 gccrs: Add type resolution for grouped patterns
- 221650c280 gccrs: Added missing GroupedPattern visitors for code generation
- 9b19e93873 gccrs: Rename file rust-ast-full-test.cc to rust-ast.cc
- d6cb04bf5c gccrs: moved operator.h to util/rust-operators.h
- 760f529d81 gccrs: fixed compiler error message on wildcard pattern within expression
- 8e7e682a9f gccrs: fixed indentations in AST pretty expanded dump of trait
- 51b607c222 gccrs: macro: Allow builtin `MacroInvocation`s within the AST
- ad9d75f508 gccrs: Create and use CompilePatternLet visitor for compiling let statments
- 9cbd270632 gccrs: parser: Allow parsing multiple reference types
- 2dab57c3f2 gccrs: Move rust-buffered-queue.h to util folder #1766
- fd7358af3c gccrs: Improve GroupedPattern lowering
- 95efd84db1 gccrs: Remove HIR::GroupedPattern
- 0e4bf6e7fc gccrs: Optimize HIR::ReferencePattern
- 86f53e5853 gccrs: Implement lowering ReferencePattern from AST to HIR
- 2af66ebd1d gccrs: parser: Improve parsing of complex generic arguments
- 7f5144d1c9 gccrs: parser: Fix parsing of closure param list
- 476faea356 gccrs: Add support for feature check.
- 4141941ae7 gccrs: Removed comment copy-pasted from gcc/tree.def
- 8d1d08cdbc gccrs: Add another test case for passing associated type-bounds
- c1b1bbbc64 gccrs: Move TypePredicateItem impl out of the header
- 688fccb522 gccrs: Refactor TyVar and TypeBoundPredicates
- e42118c327 gccrs: Refactor SubstitutionRef base class into its own CC file
- 6abbfb5280 gccrs: Refactor all substitution mapper code implementation into its own CC file
- d73082efec gccrs: Refactor BaseType, InferType and ErrorType impl into cc file
- 26af4b0604 gccrs: Refactor PathProbe into cc file
- 547e511fbd gccrs: Refactor PathProbeType code into CC file
- 615ee14c08 gccrs: Refactor all code out of the rust-tyty.h header
- 6c4fa22d38 gccrs: Rename rust-tyctx.cc to rust-typecheck-context.cc
- 1019fd6337 gccrs: Rename header rust-hir-trait-ref.h to rust-hir-trait-reference.h
- dcb2e571ac gccrs: Refactor handle_substitutions to take a reference
- 2f228578d5 gccrs: Clear the substitution callbacks when copying ArgumentMappings
- 31f1e59962 gccrs: Add missing param subst callback
- e42c28bcfd gccrs: Remove monomorphization hack to setup possible associated types
- 68d671ac72 gccrs: Refactor the type unification code
- 2a2e6712ba gccrs: Fix nullptr dereference
- f62dcf2c65 gccrs: Add missing Sized, Copy and Clone lang item mappings
- 9754a60623 gccrs: Fix higher ranked trait bounds computation of self
- 11150b7c05 gccrs: Remove bad error message on checking function arguments
- eb4a61ac1b gccrs: Add general TypeBounds checks
- fa7b3a2f07 gccrs: Add support for TuplePattern in let statements
- 1c57244dbc gccrs: rust-item: include rust-expr.h
- f548ddee96 gccrs: parser: Expose parse_macro_invocation as public API
- 2d30e0b882 gccrs: expansion: Add `get_token_slice` to `MacroInvocLexer` class
- 3821669164 gccrs: macros: Perform macro expansion in a fixed-point fashion.
- fbd5244df6 gccrs: expander: Add documentation for `expand_eager_invocations`
- 5fd04425c0 gccrs: typecheck: Refactor rust-hir-trait-reference.h
- f64799a567 gccrs: cli: Update safety warning message
- b4229fb086 gccrs: Update copyright years.
- fd5eb9f2b0 gccrs: Add feature gate for "rust-intrinsic".
- a9d72ef2d0 gccrs: Add variadic argument type checking
- 8a9886a85e gccrs: Add test
- e81f5be60d gccrs: Simplify WildcardPattern let statement handling
- b56d093e95 gccrs: lex: Prevent directories in RAIIFile
- 7b00a80c9d gccrs: testsuite: Add empty string macro test
- 20529dff93 gccrs: Add support for parsing empty tuple patterns.
- fd406fc704 gccrs: Implemented UTF-8 checking for include_str!()
- c627781b8f gccrs: Extract query_type from TypeCheckBase to be a simple extern
- e90d06c544 gccrs: Add new virtual function HIR::ImplItem::get_impl_item_name
- 4b25fc15b9 gccrs: Support for Sized builtin marker trait
- a11b44b6a5 gccrs: Fix regression in testcase
- ecdce2bf17 gccrs: Add trailing newline
- 8b0ed2387a gccrs: builtins: Return empty list of tokens instead of nullptr
- 6774d569c6 gccrs: Fix formatting
- 8628486f48 gccrs: Add AST::AltPattern class
- 0ec543c7c6 gccrs: Fix up DejaGnu directives in 'rust/compile/issue-1830_{bytes,str}.rs' test cases [#1838]
- 1a58da7c2d gccrs: rename rust-hir-full-tests.cc
- 3b342e1162 gccrs: add test case to show our query-type system is working
- fa7675df86 gccrs: ast: Refactor TraitItem to keep Location info
- 2785d59111 gccrs: diagnostic: Refactor Error class
- f2d6ab839c gccrs: Added AST Node AST::InlineAsm
- 990ae497b8 gccrs: Address unsafe with/without block handling ambiguity
- d2a499a988 gccrs: Fix issue with parsing unsafe block expression statements
This merge is done with 'git merge --strategy=ours', so effectively doesn't
merge any changes. Rationale: those commits are taken from GCC/Rust master
branch, and any remaining changes we'd either like to persist, or assess
individually, later.
Add a boolean to tell inner and outer attributes ast nodes appart. This
meant refactoring a bit their parsing function.
gcc/rust/ChangeLog:
* ast/rust-ast.h: Add boolean for differenciation.
* parse/rust-parse-impl.h (Parser::parse_doc_comment): Change
function interface to make code cleaner. It should return a body
instead of the whole attribute.
(Parser::parse_inner_attribute): Specify the inner status of the
node.
(Parser::parse_attribute_body): Change function interface to
make the code cleaner much like parse_doc_comment.
(Parser::parse_outer_attribute): Specify outer status of the
node.
* parse/rust-parse.h: Update functions prototypes.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
It results in a recursive generic Param cycle.
gcc/rust/ChangeLog:
* typecheck/rust-hir-path-probe.cc: dont subst with a dynamic object
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
Calling PathProbeImplTrait resolves directly to the trait bound in question
to stop resolving to potentially multiple implementations of that bound
gcc/rust/ChangeLog:
* backend/rust-compile-expr.cc (CompileExpr::resolve_method_address):
call path probe impl trait
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
Add a stub function and utility functions that should be called on some
nodes to expand attribute procedural macros.
gcc/rust/ChangeLog:
* expand/rust-expand-visitor.cc (ExpandVisitor::expand_outer_attribute):
Stub for a single attribute expansion.
(ExpandVisitor::visit_outer_attrs): Visit the attributes to
expand on a given item.
* expand/rust-expand-visitor.h: Add function prototypes.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
We need to retrieve outer attributes from some Expressions depending on
their context. This means this should be retrieved from their parent
node. But expr did not have a getter for outer attributes since some
expr can't have any outer attribute.
gcc/rust/ChangeLog:
* ast/rust-ast.h: Add getter to Expr class.
* ast/rust-expr.h: Add override attribute to existing getters.
Also implement it for RangeExpr, attempting to retrieve outer
attributes on those types will crash the compiler.
* ast/rust-macro.h: Add override attribute to existing getters.
* ast/rust-path.h: Likewise.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add function stubs for inner attribute proc macros expansion.
gcc/rust/ChangeLog:
* expand/rust-expand-visitor.cc (ExpandVisitor::visit): Add call
to inner attribute stub.
(ExpandVisitor::expand_inner_attribute): Expand one single
attribute.
(ExpandVisitor::visit_inner_using_attrs): Expand a given item
using a vector of attributes.
(ExpandVisitor::visit_inner_attrs): Visit inner attributes of a
given item.
* expand/rust-expand-visitor.h: Add function prototypes.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
The path should be retrieved only when a generic arg has either type.
gcc/rust/ChangeLog:
* ast/rust-ast-tokenstream.cc (TokenStream::visit): Fix ICE.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
A default token was used as a separator, wich resulted in a wrong token
stream.
gcc/rust/ChangeLog:
* ast/rust-ast-tokenstream.cc (TokenStream::visit): Remove
default separator.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Change the token type from a custom identifier to the reserved token
keyword "in".
gcc/rust/ChangeLog:
* ast/rust-ast-tokenstream.cc (TokenStream::visit): Change token
type.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Attributes were not converted to a correct tokenstream, furthermore meta
items containers and token trees attribute arguments were not even
implemented. This commit fix the literal attribute type and implement
both unimplemented types.
gcc/rust/ChangeLog:
* ast/rust-ast-tokenstream.cc (TokenStream::visit): Fix existing
and implement remaining attribute visitors.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Output a union's outer attributes in a tokenstream.
gcc/rust/ChangeLog:
* ast/rust-ast-tokenstream.cc (TokenStream::visit): Add visitor
to the union's outer attributes.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
The code was attempting to convert a char to an integer by parsing it
instead of taking it's raw value.
gcc/rust/ChangeLog:
* ast/rust-ast-tokenstream.cc (TokenStream::visit): Fix ICE.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Even though the comma may be optional with blocks of expressions, it is
mandatory for a single expression alone. By changing this behavior we
ensure a working behavior with any kind of expressions.
gcc/rust/ChangeLog:
* ast/rust-ast-tokenstream.cc (TokenStream::visit): Make comma
mandatory.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
The visitor created some additional semicolon between statements in
extern blocks, this lead to empty statement.
gcc/rust/ChangeLog:
* ast/rust-ast-tokenstream.cc (TokenStream::visit): Remove
additional semicolon output.
* ast/rust-ast-tokenstream.h: Change block visitor prototype
with a default value for trailing tokens.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
We are getting constant expressions for the initilizers for static items
this hits an assertion in the GCC middle-end which is looking for a
constructor so we need to unwrap the constant expression using DECL_INITIAL
as the initilizer to the global static.
Fixes#2080
gcc/rust/ChangeLog:
* backend/rust-compile-item.cc (CompileItem::visit): unwrap the constant expression
gcc/testsuite/ChangeLog:
* rust/execute/torture/issue-2080.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
In rust cast to char is allowed only from u8 type.
This patch handles fix the case when the type is infered from an integer value,
allowing only the u8 case'
Fixes#2027
gcc/rust/ChangeLog:
* typecheck/rust-casts.cc (TypeCastRules::cast_rules):
case INTEGRAL handles TypeKind::CHAR
gcc/testsuite/ChangeLog:
* rust/compile/cast5.rs: New test.
Signed-off-by: Emanuele Micheletti <micheletti.emanuele@hotmail.com>
We might have generics that are only for lifetimes this is a bad error
check. We can simply rely on the function to marshall the HIR generics
arguements for the type system to do the error handling for us which will
be more acurate anyway.
Fixes#2043#2039
gcc/rust/ChangeLog:
* resolve/rust-ast-resolve-item.cc (ResolveTraitItems::visit):
add check for reference marker and type's in self params
(ResolveItem::visit): likewise
* typecheck/rust-hir-type-check-path.cc (TypeCheckExpr::resolve_root_path):
remove bad generics check
(TypeCheckExpr::resolve_segments): likewise
* typecheck/rust-hir-type-check-type.cc (TypeCheckType::resolve_root_path): likewise
gcc/testsuite/ChangeLog:
* rust/compile/const_generics_5.rs: update test case
* rust/compile/issue-2043.rs: New test.
* rust/compile/issue-2039.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
In rust it is possible to write method where you explicitly specify the
type of a self param. It does not however allow for you to use reference
destructuring in this senario.
gcc/rust/ChangeLog:
* resolve/rust-ast-resolve-item.cc
(ResolveTraitItems::visit): add name resolution self param
(ResolveItem::visit): likewise
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
When handling generics of only lifetimes we have an empty
SubstitutionArgumentMappings which was being detected as an error but this
is not the case as we don't currently handle const generics or generic
lifetimes so this makes the distinction between an error occurred or its
simply empty because it was all only lifetime arguments and we don't care
about it.
Addresses #2043#2039
gcc/rust/ChangeLog:
* typecheck/rust-tyty-bounds.cc (TypeBoundPredicate::TypeBoundPredicate): this is an empty
(TypeBoundPredicate::operator=): likewise
* typecheck/rust-tyty-subst.cc (SubstitutionArgumentMappings::empty): new interface
(SubstitutionArgumentMappings::is_error): this marks it as an error
* typecheck/rust-tyty-subst.h: update prototypes
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
gcc/rust/ChangeLog:
* checks/errors/privacy/rust-privacy-reporter.cc
(PrivacyReporter::check_base_type_privacy): allow error types to be permissive
Signed-off-by: Philip Herron <herron.philip@googlemail.com>a
TokenStream visitors still have many issues, this commit fixes some of
them.
gcc/rust/ChangeLog:
* ast/rust-ast-tokenstream.cc (TokenStream::visit_items_as_lines):
Handle trailing chars.
(TokenStream::visit_items_as_block): Likewise.
(TokenStream::visit): Fix visitor.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
The conversion to string of any known type literal was not giving back
any type hint, not even quotes for string. This commit fix this.
gcc/rust/ChangeLog:
* lex/rust-token.cc (Token::as_string): Add type hint output.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add an option to the command line interface to dump the ast back to a
tokenstream.
gcc/rust/ChangeLog:
* rust-session-manager.cc (Session::enable_dump): Enable new
dump.
(Session::compile_crate): CLI argument parsing.
(Session::dump_tokenstream): Dump the tokenstream as a string in
the specified file.
* rust-session-manager.h (struct CompileOptions): Add
tokenstream dump option.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add a new representation for tokens which should reflect the string
token as it could be found in the original source.
gcc/rust/ChangeLog:
* lex/rust-token.cc (Token::as_string): Add as_string
implementation.
* lex/rust-token.h: Add as_string prototype.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add a function to TokenStream to collect in a single vector all tokens.
gcc/rust/ChangeLog:
* ast/rust-ast-tokenstream.cc (TokenStream::collect_tokens): Add
getter.
(TokenStream::go): Rename function.
(TokenStream::visit): Likewise.
* ast/rust-ast-tokenstream.h: Add collect prototype.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
The getter name was overly complicated and long, this could be
refactored to a shorter name.
gcc/rust/ChangeLog:
* ast/rust-ast-tokenstream.cc (TokenStream::visit): Change
getter name.
* ast/rust-ast.cc (SimplePath::as_string): Change attribute
name.
* ast/rust-ast.h (class SimplePath): Refactor attribute name and
change getter name.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add an option to output trailing commas depending on the configuration
of the TokenStream.
gcc/rust/ChangeLog:
* ast/rust-ast-tokenstream.cc (TokenStream::trailing_comma):
Output a trailing comma to the token stream according to the
configuration.
* ast/rust-ast-tokenstream.h: Add function prototype.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add several functions to convert an ast back to a token stream. This may
be used later either to unify the ast dumping and modifications on ast
nodes in procedural macros.
gcc/rust/ChangeLog:
* Make-lang.in: Add rust-as-tokenstream to compile list.
* ast/rust-item.h: Add missing getter for location.
* ast/rust-ast-tokenstream.cc: Add ast visitor implementation.
* ast/rust-ast-tokenstream.h: New file.
* ast/rust-pattern.h: Add getter.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
When we have a function with no return type this defaults to (), but we
need to be sure we generate a new implicit HirId for it otherwise it will
end up in a recursive reference chain.
Fixes#2042
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-type.cc (TypeCheckType::visit):
Add implicit unit type as the return type when not specified
gcc/testsuite/ChangeLog:
* rust/compile/issue-2042.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
Fixes#2025
gcc/rust/ChangeLog:
* util/rust-attributes.cc: Add stable to the table of known attributes
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
This testcase was missed and not actually added to the testsuite. This
moves it to be part of the simple compile tests.
gcc/testsuite/ChangeLog:
* rust/bounds1.rs: Moved to...
* rust/compile/bounds1.rs: ...here.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
We expect to get some kind of ADT or Tuple type when computing this kind of
match arms this adds a new diagnostic to check for this case instead of
an assertion.
Fixes#2029
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit): return early on bad type
* typecheck/rust-hir-type-check-pattern.cc (TypeCheckPattern::TypeCheckPattern):
remove assertion in favor of check
(TypeCheckPattern::visit): likewise
gcc/testsuite/ChangeLog:
* rust/compile/issue-2029.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
Change string format to match older rust version. Inline variable name
were not available with rust 1.49.
ChangeLog:
* librust/proc_macro/rust/bridge/literal.rs: Change inline
variable name format to usual empty "{}" along with arguments.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Change some bits to make the code more idiomatic/clearer.
ChangeLog:
* librust/proc_macro/rust/bridge/literal.rs: Make byte range
clearer.
* librust/proc_macro/rust/bridge/token_stream.rs: Remove old
comment.
* librust/proc_macro/rust/token_stream.rs: Remove useless return
statement.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Change for a custom implementation of the Clone trait since the
TokenStream structure owns a foreign array which needs to be deeply
cloned to prevent use after free in case the original TokenStream is
dropped early.
ChangeLog:
* librust/proc_macro/rust/bridge/token_stream.rs: Implement
custom Clone.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
The Literal type may contain foreign byte array when representing a byte
array or a string. This means auto deriving the Clone trait would only
perform a shallow copy of the pointer rather than a deep copy. This
behavior would lead to use-after-free when a literal is cloned and then
dropped.
ChangeLog:
* librust/proc_macro/rust/bridge/literal.rs: Implement Clone
manually.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
The internal Ident structure contains a foreign allocated byte array,
it's Clone trait cannot be derived automatically as the array would not
be cloned correctly, only the pointer. This would lead to use
after-free.
ChangeLog:
* librust/proc_macro/rust/bridge/ident.rs: Implement Clone for
Ident.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Rust string are not null terminated and the C++ part will require a
bound to know where a string type end. This means the length should be
given as an argument in all ffi functions.
ChangeLog:
* librust/proc_macro/rust/bridge/ident.rs: Add length to extern
C functions.
* librust/proc_macro/rust/bridge/literal.rs: Add length to
extern C functions.
* librust/proc_macro/rust/bridge/token_stream.rs: Add length to
extern C functions.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Implement the Display trait for the rust Group external structure.
ChangeLog:
* librust/proc_macro/rust/group.rs: Implement Display.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Implement the Display trait for the rust internal Punct structure.
ChangeLog:
* librust/proc_macro/rust/bridge/punct.rs: Implement Display.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Implement the Display trait for LexError by writing an error string to
the the output formatter.
ChangeLog:
* librust/proc_macro/rust/lib.rs: Implement Display for
LexError.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Implement FromIterator for TokenStream, from either a TokenTree iterator
or a TokenStream iterator.
ChangeLog:
* librust/proc_macro/rust/bridge/token_stream.rs: Add internal
implementation.
* librust/proc_macro/rust/lib.rs: Add FromIterator
implementation.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add the TokenStream rust type implementation to libproc_macro. Also
implement IntoIter structure to iterator over a TokenStream.
ChangeLog:
* librust/proc_macro/rust/bridge.rs: Add group and token_stream
modules.
* librust/proc_macro/rust/group.rs: Add group internal
representation.
* librust/proc_macro/rust/lib.rs: Add TokenStream
implementation.
* librust/proc_macro/rust/literal.rs: Make internal
implementation visible in the whole crate.
* librust/proc_macro/rust/token_stream.rs: Implement IntoIter.
* librust/proc_macro/rust/bridge/group.rs: Add Group internals.
* librust/proc_macro/rust/bridge/token_stream.rs: Add
TokenStream internals.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add most parts of TokenTree type implementation.
ChangeLog:
* librust/proc_macro/rust/lib.rs: Add TokenTree implementation.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
The rust Punct type was using a 1 byte c_char, incompatible with rust
char.
ChangeLog:
* librust/proc_macro/rust/bridge/punct.rs: Change value getter.
* librust/proc_macro/rust/punct.rs: Change structure size.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
The internal Punct rust type was not entirely ffi safe, thus these
changes in order for it to be used by both parts of the libproc_macro.
ChangeLog:
* librust/proc_macro/rust/bridge/punct.rs: Change internal Punct
representation.
* librust/proc_macro/rust/punct.rs: Change Punct interface
interaction.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Make the Ident rust type ffi-safe. This involved a rework of the
structure construction/destroy which will be delagated to the cpp part.
ChangeLog:
* librust/proc_macro/rust/bridge/ident.rs: Make Ident ffi-safe.
* librust/proc_macro/rust/ident.rs: Refactor display trait.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add the implementation for the Punct rust type in libproc_macro.
ChangeLog:
* librust/proc_macro/rust/bridge.rs: Add punct module.
* librust/proc_macro/rust/punct.rs: Add Punct bridge.
* librust/proc_macro/rust/bridge/punct.rs: Add Punct internals.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add a rust implementation for the Span rust type. Since this type is a
compiler internal and unstable even in the reference compiler, the
bridge internal structure is left empty.
ChangeLog:
* librust/proc_macro/rust/lib.rs: Add bridge module.
* librust/proc_macro/rust/span.rs: Add reference to internal
Span module.
* librust/proc_macro/rust/bridge.rs: Add internal bridge module.
* librust/proc_macro/rust/bridge/span.rs: Add internal Span
module.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add the token_stream rust module interface to libproc_macro in order to
provide public implementation details for the TokenStream type such as
iterators.
ChangeLog:
* librust/proc_macro/rust/lib.rs: Add token_stream module.
* librust/proc_macro/rust/token_stream.rs: Add iterator.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add the rust interface for the is_available function in libproc_macro.
ChangeLog:
* librust/proc_macro/rust/lib.rs: Add is_available.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
The Delimiter rust type is inherently tied to the Group type in the
group module.
ChangeLog:
* librust/proc_macro/rust/group.rs: Add Delimiter type.
* librust/proc_macro/rust/lib.rs: Remove Delimiter type.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add the Group rust type interface to libproc_macro.
ChangeLog:
* librust/proc_macro/rust/lib.rs: Add group module.
* librust/proc_macro/rust/group.rs: Add rust Group type.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add the TokenStream rust type interface to libproc_macro. Note that the
token_stream module containing the iterator operations implemented on
the TokenStream type is missing.
ChangeLog:
* librust/proc_macro/rust/lib.rs: Add TokenStream type.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
The spacing type is inherently linked to the Punct type and can
therefore be moved to the punct module. This commit also add some
documentation to the spacing type.
ChangeLog:
* librust/proc_macro/rust/lib.rs: Remove Spacing type.
* librust/proc_macro/rust/punct.rs: Add Spacing type.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add the Punct rust type interface for the libproc_macro.
ChangeLog:
* librust/proc_macro/rust/lib.rs: Add punct module.
* librust/proc_macro/rust/punct.rs: Add Punct type.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
The file for the rust interfaces became quite long and we could
therefore split it in multiple module and reexport their symbol at the
root level. This way the code is shorter and well separated whilst
keeping the exact same interface as the libproc_macro from rustc.
ChangeLog:
* librust/proc_macro/rust/lib.rs: Remove somes types.
* librust/proc_macro/rust/ident.rs: Add Ident type to it's own
module.
* librust/proc_macro/rust/literal.rs: Add Literal type to it's
own module.
* librust/proc_macro/rust/span.rs: Add Span type to it's own
module.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add spacing type rust interface to the rust part of the libproc_macro.
ChangeLog:
* librust/proc_macro/rust/lib.rs: Add Spacing type.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add the rust interface for the Ident type in libproc_macro.
ChangeLog:
* librust/proc_macro/rust/lib.rs: Add ident type.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add the rust stable interface for Span type in libproc_macro.
ChangeLog:
* librust/proc_macro/rust/lib.rs: Add span type interface
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add the Delimiter type for the rust libproc_macro interface.
ChangeLog:
* librust/proc_macro/rust/lib.rs: Add Ident type.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Fixes: #2052
gcc/rust/ChangeLog:
* backend/rust-compile-expr.cc (CompileExpr::generate_closure_function):
when its not a block we dont have any ribs to generate locals from
gcc/testsuite/ChangeLog:
* rust/execute/torture/issue-2052.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
Array expressions were being eagerly handled
outside of Pratt parsing.
gcc/rust/ChangeLog:
* parse/rust-parse-impl.h
(Parser<ManagedTokenSource>::parse_expr_without_block):
Remove direct array expression handling.
gcc/testsuite/ChangeLog:
* rust/compile/array4.rs: New test.
* rust/execute/torture/arrays.rs: New test.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
We do not need to set the system's compiler to `gccrs`, as we are mostly
interested in *having* gccrs - not necessarily using it as a C and C++
compiler as well.
ChangeLog:
* Dockerfile: Remove update-alternatives invocation.
Co-authored-by: Marc Poulhiès <dkm@kataplop.net>
This causes the function to return true and the checks to pass, but it
requires more thinking - how do we deal with pub(crate) in the current system?
Should we simply treat it as a pub item in the current crate, but export it as
a private item in the metadata?
gcc/rust/ChangeLog:
* ast/rust-item.h: Fix `Visibility::has_path()` implementation.
* checks/errors/privacy/rust-visibility-resolver.cc
(VisibilityResolver::resolve_module_path): Check if we are dealing with pub(crate) properly.
gcc/testsuite/ChangeLog:
* rust/compile/privacy8.rs: New test.
SimplePath are allowed to resolve to their root segment even if it is `crate`
or `super` when checking visibilities. We now have to make sure that this
is allowed everywhere a SimplePath is kept.
gcc/rust/ChangeLog:
* resolve/rust-ast-resolve-path.cc (ResolvePath::resolve_path): Set
resolved_node_id when visiting root segment of SimplePath.
When creating a SimplePath from a string, we end up creating a path
which contains only one segment but no location. Take the location of
the one segment instead and use it as the simple path's location.
gcc/rust/ChangeLog:
* ast/rust-ast.h: Call SimplePath constructor differently in
SimplePath::from_str
In rust is not allowed to cast from int to bool. This patch handles the case when we cast a integer to bool with 'as bool'
Fixes#2026
gcc/rust/ChangeLog:
* typecheck/rust-casts.cc (TypeCastRules::cast_rules): BOOL removed from switch cases
gcc/testsuite/ChangeLog:
* rust/compile/cast4.rs: New test.
Signed-off-by: Emanuele Micheletti <micheletti.emanuele@hotmail.com>
Since the expansion and stripping phase are now separated, it does not
make sense to keep AttrVisitor named AttrVisitor. Furthermore, the visitor
is already very complex, with a heavy mental load (erasing iterators,
rearranging them, performing cfg-expansion, etc) so further attribute
handling should probably happen in rust-attribute-checker.h
gcc/rust/ChangeLog:
* Make-lang.in: Rename rust-asttribute-visitor.o -> rust-cfg-strip.o
* expand/rust-attribute-visitor.cc: Moved to...
* expand/rust-cfg-strip.cc: ...here.
* expand/rust-attribute-visitor.h: Moved to...
* expand/rust-cfg-strip.h: ...here.
* expand/rust-macro-expand.cc: Fix include of rust-attribute-visitor.h
* expand/rust-macro-builtins.cc: Likewise.
* rust-session-manager.cc (Session::expansion): Call CfgStrip instead of
AttrVisitor.
This class takes care of actually performing the macro expansion by calling
into the MacroExpander for each node of a given AST, leaving the job of
cfg-stripping nodes to the AttrVisitor.
gcc/rust/ChangeLog:
* Make-lang.in: Add new object file.
* expand/rust-attribute-visitor.cc (AttrVisitor::go): Visit all items of a
crate.
(AttrVisitor::expand_struct_fields): Do not perform macro expansion anymore.
(AttrVisitor::expand_function_params): Likewise.
(AttrVisitor::expand_generic_args): Likewise.
(AttrVisitor::expand_qualified_path_type): Likewise.
(AttrVisitor::expand_self_param): Likewise.
(AttrVisitor::expand_trait_function_decl): Likewise.
(AttrVisitor::expand_trait_method_decl): Likewise.
(AttrVisitor::visit): Likewise.
(AttrVisitor::maybe_expand_expr): Remove function.
(AttrVisitor::maybe_expand_type): Likewise.
* expand/rust-attribute-visitor.h: Do not keep MacroExpander inside AttrVisitor
anymore.
* expand/rust-macro-expand.h (struct MacroExpander): Turn ContextType into an
enum class for more type safety.
* expand/rust-macro-expand.cc (MacroExpander::expand_crate): Use new ContextType
API.
* rust-session-manager.cc (Session::expansion): Call into ExpandVisitor.
* expand/rust-expand-visitor.cc: New file.
* expand/rust-expand-visitor.h: New file.
gcc/testsuite/ChangeLog:
* rust/compile/macro49.rs: New test.
* rust/compile/macro50.rs: New test.
The current situation where the MacroExpander and AttrVisitor recursively
call into each other is not great, and causes pains for macro imports. We
need to split this pass in two, with one pass being responsible for cfg-attr
checking and stripping, and one being responsible for macro expansion.
gcc/rust/ChangeLog:
* expand/rust-macro-expand.cc (MacroExpander::expand_crate): Do not cfg-attr
strip in MacroExpander
(MacroExpander::fails_cfg): Function moved...
(MacroExpander::fails_cfg_with_expand): Function moved...
(MacroExpander::expand_cfg_attrs): Function moved...
* expand/rust-attribute-visitor.cc (fails_cfg): ...here.
(fails_cfg_with_expand): ...here.
(expand_cfg_attrs): ...here.
(AttrVisitor::expand_struct_fields): Use new functions.
(AttrVisitor::expand_tuple_fields): Likewise.
(AttrVisitor::expand_function_params): Likewise.
(AttrVisitor::visit): Likewise.
(AttrVisitor::go): New function.
* expand/rust-attribute-visitor.h: Declare AttrVisitor::go.
* expand/rust-macro-expand.h (struct MacroExpander): Remove cfg-attr related
functions.
Macros marked with #[macro_export] need to be lowered to HIR in order
to get exported to the relevant metadata files.
gcc/rust/ChangeLog:
* hir/rust-ast-lower-base.cc (ASTLoweringBase::lower_macro_definition):
New function.
* hir/rust-ast-lower-base.h: Declare `lower_macro_definition`.
* hir/rust-ast-lower-item.cc (ASTLoweringItem::visit): Lower public
macro definitions.
* hir/rust-ast-lower-stmt.cc (ASTLoweringStmt::visit): Likewise.
* hir/rust-ast-lower-stmt.h: Add visitor for `AST::MacroRulesDefinition`.
* hir/rust-ast-lower.cc (ASTLowering::go): Formatting.
(ASTLoweringBlock::visit): Visit `AST::MacroRulesDefinition`
(ASTLoweringIfLetBlock::visit): Formatting.
(ASTLoweringExprWithBlock::visit): Formatting.
gcc/rust/ChangeLog:
* hir/rust-ast-lower-item.cc (ASTLoweringItem::visit): Add new visitor
for AST::MacroRulesDefinition.
* hir/rust-ast-lower-item.h: Declare above mentioned visitor.
* metadata/rust-export-metadata.cc (ExportContext::emit_macro): New function.
* metadata/rust-export-metadata.h: Declare it.
(PublicInterface::gather_export_data): Go through each exported macro.
* util/rust-hir-map.cc (Mappings::insert_exported_macro): New function.
(Mappings::get_exported_macros): New function.
* util/rust-hir-map.h: Add new mappings for exported macros.
Trait objects are not required to use the 'dyn' keyword though it is
depreciated in later editions/version of Rustc. This patch handles the case
when we query the type for an HIR::Item which happens to be an HIR::Trait
and return a trait object or error.
Fixes#2037
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-item.cc (TypeCheckItem::visit): return a TraitObject
gcc/testsuite/ChangeLog:
* rust/compile/issue-2037.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
Check Signed-off-by/Reviewed-by/Co-authored-by lines are all grouped and
last in commit log.
ChangeLog:
* .github/workflows/commit-format.yml: Check SoB lines are last.
Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
Having the extra semicolon causes parsing errors when importing macros
exported using the AST dump, as no rule expects multiple tokens after a
single macro rule definition.
gcc/rust/ChangeLog:
* ast/rust-ast-dump.cc (Dump::visit): Remove extraneous semicolon when
dumping macro rules.
Some were still present from the original adaptation of the Go metadata
imports and exports.
gcc/rust/ChangeLog:
* metadata/rust-imports.cc (add_search_path): Change `Go` -> `Rust`.
(Import::try_package_in_directory): Likewise.
(Import::find_export_data): Likewise.
gcc/rust/ChangeLog:
* checks/errors/rust-feature-gate.cc: Adjust 'ld'->'u'.
* checks/errors/rust-feature.h: Adjust
the type of `m_issue`: 'uint64_t' -> 'unsigned'.
Signed-off-by: Xiao Ma <mxlol233@outlook.com>
Co-authored-by: Thomas Schwinge <thomas@codesourcery.com>
This builds upon the previous path resolution fixes so that it returns the
resolved_node_id or UNKNOWN_NODEID on failure to resolve the use-path.
It then exports the name to the current module namespace so it can be used.
Fixes#850#855
gcc/rust/ChangeLog:
* ast/rust-ast.h: add const get_final_segment helper
* hir/rust-ast-lower-enumitem.h: dont add an item mapping for enumitems
* hir/rust-ast-lower-item.cc (ASTLoweringItem::visit): add enum to enum-items mappings
* hir/rust-ast-lower-stmt.cc (ASTLoweringStmt::visit): likewise
* hir/tree/rust-hir-item.h: add non const helper to get variants
* resolve/rust-ast-resolve-item.cc (ResolveItem::visit): resolve the use declaration
* resolve/rust-ast-resolve-path.cc (ResolvePath::resolve_path): handle self
* resolve/rust-ast-resolve-toplevel.h: add enum item mappings to module mappings
* typecheck/rust-hir-type-check-path.cc (TypeCheckExpr::resolve_root_path): ensure variant
(TypeCheckExpr::resolve_segments): likewise
* typecheck/rust-type-util.cc (query_type): lookup enum's
* util/rust-hir-map.cc (Mappings::insert_hir_enumitem): enum item mappings
(Mappings::lookup_hir_enumitem): likewise
* util/rust-hir-map.h: likewise
gcc/testsuite/ChangeLog:
* rust/compile/issue-850.rs: New test.
* rust/compile/issue-855.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
To enable use statement to export a name to a path such as the prelude
example: use option::Option::{self, None, Some} we need to get the resolved
node id of the self, None and Some in order to export the name of None and
Some to their respective NodeId.
gcc/rust/ChangeLog:
* resolve/rust-ast-resolve-path.cc (ResolvePath::ResolvePath): return NodeId
(ResolvePath::go): update signiture
(ResolvePath::resolve_path): return resolved_node_id
* resolve/rust-ast-resolve-path.h: update prototypes
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
This implements it as a builtin memcpy using the generic param T for the
size hint.
Fixes#1902
gcc/rust/ChangeLog:
* backend/rust-compile-intrinsic.cc (move_val_init_handler): new intrinsice
(uninit_handler): use a builtin memcpy
gcc/testsuite/ChangeLog:
* rust/compile/issue-1981.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
We should use the result of our attempted unify inference as this will
allow the direct unification of generic pointer types to concrete ones.
Fixes#1981
gcc/rust/ChangeLog:
* typecheck/rust-coercion.cc (TypeCoercionRules::select): use the result
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
In the senario where you infer types via unify_site_and but choose to not
commit the result you can end up with coercion to infer the result later on
which does not get fully replaced resulting in a stray inference variable
that can be left alone as a general inference variable leading to missing
type context info. This patch gives support to add type hints to inference
variables so they can be defaulted correctly in more complex cases. The
old system relied on the unification result commiting and overriding the
inference variables so they dissapear out of the current typeing context.
This was needed to fix#1981 where it is valid to inject inference
variables here. This lead to a regression in a few of the complex generic
trait test cases such as execute/torture/traits9.rs which had the wrong
argument type and defaulted wrongly to i32 instead of isize.
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-base.cc (TypeCheckBase::resolve_literal): fix ctor
* typecheck/rust-hir-type-check-stmt.cc (TypeCheckStmt::visit): likewise
* typecheck/rust-hir-type-check-type.cc (TypeCheckType::visit): likewise
* typecheck/rust-typecheck-context.cc (TypeCheckContext::push_new_loop_context): likewise
* typecheck/rust-tyty-util.cc (TyVar::get_implicit_infer_var): likewise
* typecheck/rust-tyty.cc (InferType::InferType): new ctor with type hint
(InferType::clone): fix ctor
(InferType::apply_primitive_type_hint): new function to apply possible hint
* typecheck/rust-tyty.h: update prototypes
* typecheck/rust-unify.cc (UnifyRules::expect_inference_variable): apply type hints
(UnifyRules::expect_bool): likewise
(UnifyRules::expect_char): likewise
(UnifyRules::expect_int): likewise
(UnifyRules::expect_uint): likewise
(UnifyRules::expect_float): likewise
(UnifyRules::expect_isize): likewise
(UnifyRules::expect_usize): likewise
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
The main changes in this commit can be logically split into two parts:
1) Pushing new pattern binding contexts in alt patterns. At the start
of each AltPattern we push an 'Or' context which represents the relation
between the bindings of different alts.
Before we resolve each alt arm we need to push a 'Product' context to represent
the relation between the bindings of this specific alt arm and each other.
This 'Product' context is removed after the alt arm visit and the its bindings
are pushed into the 'Or' context.
Eventually, the 'Or' context is removed as well after it fulfills its duty.
Its bindings are then pushed into the previous context similarly and so on.
2) Checking for consistent bindings between the alt arms which is handled
by check_bindings_consistency. The info necessary for this check is held
by binding_info_map inside PatternDeclaration class. The binding_info_map
only holds bindings for one alt arm at a time. After every alt arm visit,
these bindings info are pushed into a vec (that contains all alt arms info
and will eventually be passed to check_bindings_consistency) and emptied out
for the next alt arm visit. At the end, all the info from all the alt arms
are pushed again into binding_info in addition to the initial bindings that
were there before the alt arms visits, this way the binding_info will contain
all the binding_info present in the AltPattern (as it should).
In addition to that, some refactors were made (e.g. add_new_binding function)
and some errors emitted, no biggie.
gcc/rust/ChangeLog:
* resolve/rust-ast-resolve-pattern.cc (PatternDeclaration::go):
Print out consistency errors.
(PatternDeclaration::visit): Implement visit for AltPattern.
(PatternDeclaration::add_new_binding): New helper function for
adding a binding to identifier.
* resolve/rust-ast-resolve-pattern.h (struct BindingInfo):
New struct to facilitate checking for inconsistencies between bindings.
gcc/testsuite/ChangeLog:
* rust/compile/torture/alt_patterns1.rs: New test.
Signed-off-by: Mahmoud Mohamed <mahadelr19@gmail.com>
gcc/rust/ChangeLog:
* resolve/rust-ast-resolve-expr.cc (ResolveExpr::visit):
Push a Product context instead of an Or context.
gcc/testsuite/ChangeLog:
* rust/compile/multiple_bindings2.rs: New test.
Signed-off-by: Mahmoud Mohamed <mahadelr19@gmail.com>
On Paths such as: mem::size_of<T>() we always specified to infer the
generics which is not always the case and can cause stay inference
variables.
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-path.cc (TypeCheckExpr::visit): remove infer call
(TypeCheckExpr::resolve_root_path): only infer when we need to
gcc/testsuite/ChangeLog:
* rust/compile/sizeof-stray-infer-var-bug.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
change how we monomorphize dyn-items when we need to compute the generics
We might have a trait item such as:
impl<'a, T> FnLike<&'a T, &'a T> for Identity {
fn call(&self, arg: &'a T) -> &'a T { ... }
}
Which ended up monomorphized badly to:
const isize & const &
<example::Identity as example::FnLike::<& T, & T>>::call<& isize>
(const struct example::Identity & const self,
const isize & const & const arg)
This is wrong because it turned into a double reference type becasuse this
bug was consistent bugs were not picked up but this is not correct. We now
reuse our type inference infrastructure to solve the parameters instead.
Fixes#1984
gcc/rust/ChangeLog:
* backend/rust-compile.cc: use unify_and instead
* typecheck/rust-tyty-subst.cc (SubstitutionRef::solve_missing_mappings_from_this): remove
* typecheck/rust-tyty-subst.h: update header
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
The can_eq interface is very inconsistent so this begins the journey to
remove this and also address part of #1981
gcc/rust/ChangeLog:
* typecheck/rust-coercion.cc (TypeCoercionRules::select): use new unify_and interface
* typecheck/rust-hir-dot-operator.cc (MethodResolver::try_hook): grab bounds behind refs
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
This removes can_substitute and contains_type_parameters which were
confusing interfaces to act as a proxy to the SubstitionRef types. This
replaces them with a single base implementation which is much easier to
debug and follow.
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-path.cc (TypeCheckExpr::visit): update to use new interface
(TypeCheckExpr::resolve_root_path): likewise
(TypeCheckExpr::resolve_segments): likewise
* typecheck/rust-hir-type-check-type.cc (TypeCheckType::visit): likewise
(TypeCheckType::resolve_root_path): likewise
* typecheck/rust-tyty-subst.cc (SubstitutionRef::get_mappings_from_generic_args): likewise
* typecheck/rust-tyty.cc (BaseType::supports_substitutions): likewise
(BaseType::can_substitute): remove
(BaseType::contains_type_parameters): remove
(handle_substitions): cleanup
(TupleType::handle_substitions): update
(FnType::handle_substitions): update
(ProjectionType::supports_substitutions): update
* typecheck/rust-tyty.h: update header
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
We can just return error_mark_node instead of our own custom
recursion limit checker code. This makes the backend more reuseable
in error states.
gcc/rust/ChangeLog:
* backend/rust-compile-type.cc (TyTyResolveCompile::TyTyResolveCompile): call destructure
(TyTyResolveCompile::compile): use error_mark_node
(TyTyResolveCompile::visit): use error_mark_node
* backend/rust-compile-type.h: remove recursive ops
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
Previously, the following macro rules were rejected by gccrs:
```Rust
macro_rules! {
($v:vis <KEY_WORD>) => { ... };
}
```
This PR fixes so the above code is accepted by the compiler for all key words like `async` or `unsafe`.
The only exception is the keyword `priv` which is not allowed.
See [this page](https://doc.rust-lang.org/reference/macro-ambiguity.html) for reference. Especially the following excerpt:
> FOLLOW(vis) = {,l any keyword or identifier except a non-raw priv; any token that can begin a type; ident, ty, and path nonterminals}.
Fixes#1060
gcc/rust/ChangeLog:
* parse/rust-parse.cc: fix follow-sets
gcc/testsuite/ChangeLog:
* rust/compile/macro47.rs: Test that :vis can be followed by some keywords
* rust/compile/macro48.rs: Test that :vis cannot be followed by the keyword priv
Signed-off-by: Tage Johansson <frans.tage@gmail.com>
Define the libgrust directory as a host compilation module as well as
for targets.
ChangeLog:
* Makefile.def: Add libgrust as host & target module.
* configure.ac: Add libgrust to host tools list.
gcc/rust/ChangeLog:
* config-lang.in: Add libgrust as a target module for the rust
language.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add some dummy files in libproc_macro along with it's build system.
ChangeLog:
* libgrust/Makefile.am: New file.
* libgrust/configure.ac: New file.
* libgrust/libproc_macro/Makefile.am: New file.
* libgrust/libproc_macro/proc_macro.cc: New file.
* libgrust/libproc_macro/proc_macro.h: New file.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
https://github.com/rust-lang/rust/blob/master/compiler/rustc_resolve/src/late.rs#L3168
This commit follows rustc's implementation of handling multiple bindings
to the same identifier in parameters.
gcc/rust/ChangeLog:
* resolve/rust-ast-resolve-expr.cc (ResolveExpr::visit) :declare and
pass bindings to PatternDeclaration::go.
(ResolveExpr::resolve_closure_param): Likewise.
* resolve/rust-ast-resolve-expr.h: Likewise.
* resolve/rust-ast-resolve-item.cc (ResolveTraitItems::visit): Likewise.
(ResolveItem::visit): Likewise.
* resolve/rust-ast-resolve-pattern.cc (PatternDeclaration::go): Likewise.
(PatternDeclaration::visit): check for previous identifier bindings
before inserting the new one.
* resolve/rust-ast-resolve-pattern.h (enum PatternBoundCtx): New enum.
* resolve/rust-ast-resolve-stmt.h: pass bindings to PatterDeclaration::go.
gcc/testsuite/ChangeLog:
* rust/compile/multiple_bindings1.rs: New test.
Signed-off-by: Mahmoud Mohamed <mahadelr19@gmail.com>
gcc/rust/ChangeLog:
* hir/tree/rust-hir-full-decls.h
(struct GenericArgsBinding): Convert to class.
(class GenericArgsBinding): Convert from struct.
(struct TypePathFunction): See above.
(class TypePathFunction): See above.
(struct QualifiedPathType): See above.
(class QualifiedPathType): See above.
* ast/rust-ast-full-decls.h
(struct WhereClause): See above.
(class WhereClause): See above.
(struct SelfParam): See above.
(class SelfParam): See above.
(struct FunctionQualifiers): See above.
(class FunctionQualifiers): See above.
(struct FunctionParam): See above.
(class FunctionParam): See above.
(struct StructField): See above.
(class StructField): See above.
(struct TupleField): See above.
(class TupleField): See above.
(struct TraitFunctionDecl): See above.
(class TraitFunctionDecl): See above.
(struct TraitMethodDecl): See above.
(class TraitMethodDecl): See above.
(struct NamedFunctionParam): See above.
(class NamedFunctionParam): See above.
* hir/tree/rust-hir-path.h
(struct GenericArgsBinding): See above.
(class GenericArgsBinding): See above.
(struct TypePathFunction): See above.
(class TypePathFunction): See above.
(struct QualifiedPathType): See above.
(class QualifiedPathType): See above.
* ast/rust-item.h
(struct WhereClause): See above.
(class WhereClause): See above.
(struct SelfParam): See above.
(class SelfParam): See above.
(struct FunctionQualifiers): See above.
(class FunctionQualifiers): See above.
(struct FunctionParam): See above.
(class FunctionParam): See above.
(struct StructField): See above.
(class StructField): See above.
(struct TupleField): See above.
(class TupleField): See above.
(struct TraitFunctionDecl): See above.
(class TraitFunctionDecl): See above.
(struct TraitMethodDecl): See above.
(class TraitMethodDecl): See above.
(struct NamedFunctionParam): See above.
(class NamedFunctionParam): See above.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
This HIR node represents macros which should be exported into the final
Rust metadata files. Because our metadata exporter operates on the HIR,
while macros are inherently tied to the AST, we need a way to propagate
exported macros up until the metadata export pass on the HIR. Hence the
existence of this class, whose sole purpose is to keep enough information
for the metadata exporter to retrieve the original AST::MacroRulesDefinition.
Handling for actually exporting these macros will come later.
gcc/rust/ChangeLog:
* hir/tree/rust-hir-item.h (class ExportedMacro): Add new ExportedMacro class.
* hir/tree/rust-hir.cc (ExportedMacro::accept_vis): New function.
(ExportedMacro::get_locus): Likewise.
(ExportedMacro::get_item_kind): Likewise.
(ExportedMacro::clone_item_impl): Likewise.
* hir/tree/rust-hir-full-decls.h (class ExportedMacro): Forward declare class.
* backend/rust-compile-item.h: Add visitor for ExportedMacro.
* backend/rust-compile-stmt.h: Likewise.
* checks/errors/privacy/rust-privacy-reporter.cc (PrivacyReporter::visit): Likewise.
* checks/errors/privacy/rust-privacy-reporter.h: Likewise.
* checks/errors/privacy/rust-pub-restricted-visitor.cc (PubRestrictedVisitor::visit):
Likewise.
* checks/errors/privacy/rust-pub-restricted-visitor.h: Likewise.
* checks/errors/privacy/rust-reachability.cc (ReachabilityVisitor::visit): Likewise.
* checks/errors/privacy/rust-reachability.h: Likewise.
* checks/errors/privacy/rust-visibility-resolver.cc (VisibilityResolver::visit): Likewise.
* checks/errors/privacy/rust-visibility-resolver.h: Likewise.
* checks/errors/rust-const-checker.cc (ConstChecker::visit): Likewise.
* checks/errors/rust-const-checker.h: Likewise.
* checks/errors/rust-unsafe-checker.cc (UnsafeChecker::visit): Likewise.
* checks/errors/rust-unsafe-checker.h: Likewise.
* hir/rust-ast-lower-item.cc (ASTLoweringItem::visit): Likewise.
* hir/rust-ast-lower-item.h: Likewise.
* hir/rust-hir-dump.cc (Dump::visit): Likewise.
* hir/rust-hir-dump.h: Likewise.
* hir/tree/rust-hir-visitor.h: Likewise.
* metadata/rust-export-metadata.cc: Likewise.
* typecheck/rust-hir-type-check-item.h: Likewise.
* typecheck/rust-hir-type-check-stmt.cc (TypeCheckStmt::visit): Likewise.
* typecheck/rust-hir-type-check-stmt.h: Likewise.
* typecheck/rust-tycheck-dump.h: Likewise.
* hir/tree/rust-hir.h: Add new ItemKind::MacroExport variant.
* util/rust-attributes.cc: Add #[macro_export] attribute.
Added an implementation for
`CompilePatternBindings::visit (HIR::ReferencePattern)` where we
dereference the initial expression and recurse.
Added an implementation for
`CompilePatternBindings::visit (HIR::IdentifierPattern)` as well since it's
the simplest base case.
In addition to this, a small refactor for the shared code in
`StructPattern` and `TupleStructPattern` visits was added as a helper
function called `create_tmp_param_var`.
gcc/rust/ChangeLog:
* backend/rust-compile-fnparam.cc (CompileFnParam::visit):
Added visit implementation for ReferencePattern.
(CompileFnParam::create_tmp_param_var):
Refactored duplicated code into a helper function.
* backend/rust-compile-fnparam.h: Added visit implementation for
ReferencePattern.
* backend/rust-compile-pattern.cc (CompilePatternBindings::visit):
Added visit implementation for ReferencePattern and
IdentifierPattern.
* backend/rust-compile-pattern.h: Added visit implementation for
ReferencePattern and IdentifierPattern.
gcc/testsuite/ChangeLog:
* rust/compile/ref_pattern_fn_param.rs: Moved to...
* rust/compile/ref_pattern_fn_param1.rs: ...here.
* rust/compile/ref_pattern_fn_param2.rs: New test.
* rust/execute/torture/ref-pattern1.rs: New test.
Signed-off-by: Mahmoud Mohamed <mahadelr19@gmail.com>
This is important as public macros can be present in other modules,
which would otherwise not be loaded until the expansion phase
happening right after the early name resolution.
gcc/rust/ChangeLog:
* resolve/rust-early-name-resolver.cc (EarlyNameResolver::visit): Move
unloaded module item loading to...
* expand/rust-attribute-visitor.cc (AttrVisitor::visit): ...here.
Improves readability by better corresponding to resulting output.
gcc/rust/ChangeLog:
* hir/rust-hir-dump.cc (Dump::visit): Simplify indentation dump to single line.
Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
gcc/rust/ChangeLog:
* ast/rust-ast-dump.cc (Indent::Indent): Move to separate file.
(operator<<): Move to separate file.
(Indent::increment): Move to separate file.
(Indent::decrement): Move to separate file.
* ast/rust-ast-dump.h (class Indent): Move to separate file.
* hir/rust-hir-dump.cc (Dump::Dump): Use new indentation object.
(Dump::go): Use new indentation object.
(Dump::visit): Use new indention object.
* hir/rust-hir-dump.h: Use new indentation object.
* util/rust-dump.h: New file. Moved Indentation from rust-ast-dump.cc
Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
The visit for TypeCheckPattern::visit (HIR::ReferencePattern) was missing
an assignment to infered
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-pattern.cc (TypeCheckPattern::visit):
Add the missing infered type assignment
Signed-off-by: Mahmoud Mohamed <mahadelr19@gmail.com>
This fixes some extra warnings reported by clang.
gcc/rust/ChangeLog:
PR rust/108111
* ast/rust-ast-full-decls.h (StructPatternElements): Declare as a
class.
* ast/rust-item.h (EnumItem): Mark several method as being
overrides.
* ast/rust-pattern.h (StructPattern::get_locus): Add override.
* lex/rust-lex.h (BufferInputSource): Use reference_wrapper
instead of bare reference.
(TokenSource::get): Add method to implement the reference_wrapper
interface.
* typecheck/rust-tyty.h (TypeBoundPredicate): Add empty dtor.
* util/rust-buffered-queue.h (peek): Source token stream is now
using a reference_wrapper, use .get()
Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
This commit adds a helper function for TypeCheckPattern::visit
(HIR::RangePattern &pattern) to remove redundancy
gcc/rust/ChangeLog:
* typecheck/rust-hir-type-check-pattern.cc
(TypeCheckPattern::visit): rewrite part code to helper function
(TypeCheckPattern::typecheck_range_pattern_bound): helper function
* typecheck/rust-hir-type-check-pattern.h
(TypeCheckPattern::typecheck_range_pattern_bound):
change the parameter of the function
Signed-off-by: Jiakun Fan <jfan30@u.rochester.edu>
gcc/rust/ChangeLog:
* util/rust-lang-item.h
(RustLangItem::ItemType): New enumerators.
(RustLangItem::Parse): Parse new enumerators.
(RustLangItem::ToString): Handle new enumerators.
gcc/testsuite/ChangeLog:
* rust/compile/lang-impl.rs: New test.
Add the stringify macro expansion as well as some tests.
gcc/rust/ChangeLog:
* ast/rust-macro.cc (builtin_macro_from_string): Add identifier
identification.
* ast/rust-macro.h (enum class): Add Stringify builtin macro
type.
* expand/rust-macro-builtins.cc (make_macro_path_str): Add path
for builtin stringify macro.
(MacroBuiltin::stringify_handler): Add handler for builtin
stringify macro.
* expand/rust-macro-builtins.h: Add stringify handler's
prototype.
* util/rust-hir-map.cc (Mappings::insert_macro_def): Add
stringify handler to builtin hir map.
gcc/testsuite/ChangeLog:
* rust/compile/stringify.rs: Add a basic test with some text.
* rust/execute/torture/builtin_macro_stringify.rs: Verify the
text is left as is without any other macro expansion.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
When compiling types especially when using queries it needs to be
permissive and allow them to be overwritten and a predicate might have one
set of details in one senario and a new one with the same id later on but
with different types.
Fixes#1524
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
gcc/rust/ChangeLog:
* typecheck/rust-typecheck-context.cc (TypeCheckContext::insert_resolved_predicate): remove
gcc/testsuite/ChangeLog:
* rust/compile/issue-1524.rs: New test.
There are a few edge cases when resolving TypePaths that we cannot fully
resolve to an explicit node_id and this is expected. So for example
<A as B>::foo
A and B are simple Type paths and thats 100% but the segment foo cannot be
100% resolved to an explicit node id as this requires type-resolution to
find the correct path. So when we have complex paths such as:
<<A as B>::foo as C>
The ::foo part will return UNKNOWN_NODEId and we return early and think its
a failure case but its not necessarily a failure but we need to make sure
to name resolve C so when we do type-resolution we can resolve C properly.
Addresses #1524
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
gcc/rust/ChangeLog:
* resolve/rust-ast-resolve-type.cc (ResolveRelativeQualTypePath::resolve_qual_seg): fix
gcc/testsuite/ChangeLog:
* rust/compile/parse_associated_type_as_generic_arg3.rs: remove -fsyntax-only
When we have complex generic code you can end up with situations where we
compile types:
Maybe<<S as Foo>::A>
Into
Maybe<<placeholder:<Projection=::()>>>
This calls destructure to cleanup the naming here and avoid making non
canonical TREE_TYPES hitting the verify_gimple code triggering non-trival
constructors.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
gcc/rust/ChangeLog:
* typecheck/rust-tyty.cc (ParamType::get_name): call destructure
Wen computing higher ranked trait bounds where there are multiple type
params and ones which are not bound entirely on the impl-type we need
to inject inference variables as required to compute the types. The
inference variables we inject are missing the callbacks that we can compute
the bounds properly so this is the first part of the fix.
Addresses #1893
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
gcc/rust/ChangeLog:
* typecheck/rust-hir-trait-resolve.cc: use unify_and infer
While let expr return unit but are valid construct in rust, they should
therefore be included in the parsing code. Also add a new test to check
parsing of while let expressions.
gcc/rust/ChangeLog:
* parse/rust-parse-impl.h (Parser::parse_while_let_loop_expr):
Prevent hard error on token skip.
(Parser::null_denotation): Fix parser for while let expressions.
gcc/testsuite/ChangeLog:
* rust/compile/while_let_expr.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Following an investigation from rustc and discussions on zulip the
recommendation was that for uninit we memset to 0x01 which is less likely
to be a null ptr but still an invalid reference.
Fixes#1899
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
gcc/rust/ChangeLog:
* backend/rust-builtins.cc (BuiltinsContext::setup): add memset builtin to the map
* backend/rust-compile-intrinsic.cc (uninit_handler): implement uninit intrinsic
gcc/testsuite/ChangeLog:
* rust/compile/torture/uninit-intrinsic-1.rs: New test.
Check for a closing square bracket before attempting to parse any
pattern within a slice. Also add a new test to verify zero sized
slice parsing.
gcc/rust/ChangeLog:
* parse/rust-parse-impl.h (Parser::parse_slice_pattern): Add
closing square bracket check.
gcc/testsuite/ChangeLog:
* rust/compile/zero_sized_slice.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
The recent changes in the parser bringing the parsing of extern type
items also brought a compilation error when boostrapping the compiler.
gcc/rust/ChangeLog:
* parse/rust-parse-impl.h (Parser::parse_external_type_item):
Fix compilation error due to unnecessary move.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
gcc/rust/ChangeLog:
* hir/rust-hir-dump.cc (Dump::go): support inner attrs, crate items and node mappings
(Dump::visit): support functions, arith/logical exprs, let stmts and literals
Signed-off-by: Abdul Rafey <abdulrafeyq@gmail.com>
Add a test to check wether the syntax of a RestPattern in a SlicePattern
parse correctly.
gcc/testsuite/ChangeLog:
* rust/compile/slice_rest_pattern.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
The RestPattern AST node did not have any NodeId to identify it and
could therefore not be instanciated.
gcc/rust/ChangeLog:
* ast/rust-pattern.h (class RestPattern): Add NodeId as well as
the clone_impl function.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add a new test to check the if let expression syntax parsing.
gcc/testsuite/ChangeLog:
* rust/compile/if_let_expr.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Fix if let parsing in null_notation function. This problem was due to
the current token already being passed in the function parameters and
already out of the buffered queue. Hence why the peeked token was let
and not if.
gcc/rust/ChangeLog:
* parse/rust-parse-impl.h (Parser::null_denotation): Fix if let
parsing.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Fixes#1898
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
gcc/rust/ChangeLog:
* backend/rust-compile-intrinsic.cc (op_with_overflow_inner): wraps op_with_overflow
(std::function<tree): likewise
(op_with_overflow): generate the intrinsic based on the tree_code op
gcc/testsuite/ChangeLog:
* rust/compile/torture/intrinsics-8.rs: New test.
Rust allows us to call generic pointer methods on pointers so in non
generic contexts the old code using the bad can_eq interface couldn't
handle this case. So taking advantage of our new unify_and interface to try
and infer when required we can start using our TryCoerce interface to reuse
existing code to assemble possible candidates more acurately using the
existing coercion rules.
Fixes#1901#878
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
gcc/rust/ChangeLog:
* typecheck/rust-coercion.cc (TypeCoercionRules::Coerce): Add new try_flag
(TypeCoercionRules::TypeCoercionRules): set new try flag
(TypeCoercionRules::do_coercion): default to a final unify_and in the else case
(TypeCoercionRules::coerce_unsafe_ptr): cannot coerce to a ptr from ref during autoderef
(TypeCoercionRules::coerce_borrowed_pointer): respect coerceable mutability
* typecheck/rust-coercion.h: update header
* typecheck/rust-hir-dot-operator.cc (MethodResolver::select): use new TryCoerce interface
(MethodResolver::append_adjustments): ensure we maintain adjustment mappings
* typecheck/rust-hir-dot-operator.h: add new method append_adjustments
* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit): extra logging
gcc/testsuite/ChangeLog:
* rust/compile/issue-1901.rs: New test.
When generating implicit inference variables we can miss cases where the
other side might be another inference variable too but it runs the risk of
generating unending inference cycles needing more info but if they other
side is a non general inference variables like <integer> or <float> this
is safe to do so and allows us to infer mroe cases.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
gcc/rust/ChangeLog:
* typecheck/rust-unify.cc (UnifyRules::go): fix inference check
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
gcc/rust/ChangeLog:
* typecheck/rust-unify.cc (UnifyRules::go): respect the emit_errors flag
We should allow implicit inference on the expected side too not just the
receiver.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
gcc/rust/ChangeLog:
* typecheck/rust-unify.cc (UnifyRules::go): allow lhs infer vars
This is a complex type-system change where it begins out journey to get
rid of our can_eq interface. Rust allows:
let x:*mut T
let y = x as *mut u8;
Which requires us to consider find a way to infer what T should be so as
to keep unify happy. This means we need to introduce a new unify_and
interface where we can optionally inject inference variables as well as
only commit the inference variable joins when they are sucsessful.
So for this case we can then inject an implicit inference variables for T
that can unify against u8 to make this a valid type-resolution.
Fixes#1930
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
gcc/rust/ChangeLog:
* backend/rust-compile-expr.cc (CompileExpr::resolve_method_address): update to new inteface
* typecheck/rust-coercion.cc (TypeCoercionRules::coerce_unsafe_ptr): likewise
(TypeCoercionRules::coerce_borrowed_pointer): likewise
* typecheck/rust-hir-type-check.h: likewise
* typecheck/rust-type-util.cc (unify_site_and): new interface to allow for infer and commit
* typecheck/rust-type-util.h (unify_site_and): likewise
* typecheck/rust-typecheck-context.cc (TypeCheckContext::clear_type): new interface
* typecheck/rust-unify.cc (UnifyRules::UnifyRules): update
(UnifyRules::Resolve): new optional flags for commit and infer
(UnifyRules::go): likewise
(UnifyRules::expect_adt): refactor to use new interface
(UnifyRules::expect_reference): likewise
(UnifyRules::expect_pointer): likewise
(UnifyRules::expect_array): likewise
(UnifyRules::expect_slice): likewise
(UnifyRules::expect_fndef): likewise
(UnifyRules::expect_fnptr): likewise
(UnifyRules::expect_tuple): likewise
(UnifyRules::expect_closure): likewise
* typecheck/rust-unify.h: refactor interface
gcc/testsuite/ChangeLog:
* rust/compile/issue-1930.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
gcc/rust/ChangeLog:
* typecheck/rust-tyty.cc (ADTType::is_concrete): need to consider if is a num_variant
* typecheck/rust-tyty.h: refactor to cc file
Add a test to the testsuite in order to verify the presence of a
semicolon at the end of an external type item declaration.
gcc/testsuite/ChangeLog:
* rust/compile/extern_type_item_missing_semi.rs: New failing
test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add a test for extern type item declaration.
gcc/testsuite/ChangeLog:
* rust/compile/extern_type_item.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Add the code to parse type item declaration within an extern block.
gcc/rust/ChangeLog:
* parse/rust-parse-impl.h (Parser::parse_external_type_item):
Add function to parser an external type item.
(Parser::parse_external_item):
Add identification and parsing for external type items.
* parse/rust-parse.h:
Add parser_external_type_item prototype.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
This adds enough handling to start parsing `auto` traits but not handle
them in the AST, lowering phase or HIR yet.
The feature is named `optin_builtin_traits` in Rust 1.49 but changes to
`auto_traits` later down the line. So we'll need to take care of this later
on.
Finally, this also changes the way the lexer detects if a string is a
keyword or not. We relied on a call to `std::lower_bound` to figure
out if a string was contained in an array or not, and this ended up
causing issues when adding new keywords. We can instead switch to a
simple hashmap and search for the key. The code *might* be less
optimized (unsure) but it is definitely simpler and easier to read.
Fixes#1814
gcc/rust/ChangeLog:
* ast/rust-item.h (class Trait): Add `has_auto` field.
* checks/errors/rust-feature.cc: Add handling for `feature(optin_builtin_traits)`
* checks/errors/rust-feature.h: Likewise.
* lex/rust-lex.cc: Fix keyword classification using hashmap.
* lex/rust-token.h: Add `auto` keyword token.
* parse/rust-parse-impl.h (Parser::parse_vis_item): Parse auto traits
on `auto` keyword.
gcc/testsuite/ChangeLog:
* rust/compile/auto_trait_invalid.rs: New test.
* rust/compile/auto_trait_valid.rs: New test.
We should probably think about building GCC 4.8 from source from time
to time and hosting the image on our Dockerhub, but I think this is okay
as well for now.
ChangeLog:
* .github/workflows/ccpp.yml: Run GCC 4.8 action in ubuntu 18.04 container
Similarly to the last commit, we need to allow `LEFT_SHIFT` tokens to
start a qualified path type and split them into two `LEFT_ANGLE` tokens.
gcc/rust/ChangeLog:
* parse/rust-parse-impl.h (Parser::parse_type): Allow LEFT_SHIFT to
start a type and then split it in `parse_qualified_path_type`
gcc/testsuite/ChangeLog:
* rust/compile/parse_associated_type_as_generic_arg3.rs: New test.
Let's take the example of lexing `Option<<T as Iterator>::Item>` and look
at the first few tokens. Originally, `Option<<T` was lexed as 3 tokens:
* IDENTIFIER(Option)
* LEFT_SHIFT
* IDENTIFIER(T)
The parser did not allow a list of generic arguments to start with a left
shift, and rejected the above type. We are now splitting the left shift
into two left angles, as this allows complex generic arguments and overall
makes sense parsing wise. Thus, the above list becomes:
* IDENTIFIER(Option)
* LEFT_ANGLE
* LEFT_ANGLE
* IDENTIFIER(T)
and `<T as Iterator>` is properly parsed as a qualified path.
Fixes#1815Fixed#1809
Addresses #1524
gcc/rust/ChangeLog:
* parse/rust-parse-impl.h (Parser::parse_path_generic_args): Split leading
`LEFT_SHIFT` token into two `LEFT_ANGLE` tokens when parsing generic arguments.
(Parser::parse_type_path_segment): Allow `LEFT_ANGLE` as starting token for
parsing generic arguments.
gcc/testsuite/ChangeLog:
* rust/compile/parse_associated_type_as_generic_arg.rs: New test.
* rust/compile/parse_associated_type_as_generic_arg2.rs: New test.
* rust/compile/path_as_generic_arg.rs: New test.
* rust/compile/nested_generic.rs: New test.
Addresses #1567
Created a AST node InlineAsm similar to the one found in rustc.
As there is no Symbol struct/class in gccrs I have made every instance
of Symbol a string.
Signed-off-by: M V V S Manoj Kumar <mvvsmanojkumar@gmail.com>
gcc/rust/ChangeLog:
* ast/rust-ast-full-decls.h (class InlineAsm):Added class declaration.
* ast/rust-expr.h (class InlineAsm):Added class definition.
The class now allows for more variants including a `Hint` one which
then gets emitted by calling `rust_inform`. This allows us to display
hints/tips/notes in backtracking contexts such as the parser.
gcc/rust/ChangeLog:
* rust-diagnostics.h (struct Error): Add new Kind enum and various new
static constructors to allow for hints as well.
* rust-diagnostics.cc (Error::Error): Use new `kind` field properly.
* checks/errors/privacy/rust-visibility-resolver.cc
(VisibilityResolver::resolve_module_path): Use new Error API.
* expand/rust-macro-builtins.cc (MacroBuiltin::include_handler): Likewise.
* expand/rust-macro-expand.cc (parse_many): Likewise.
(transcribe_type): Likewise.
* parse/rust-parse-impl.h (Parser::parse_crate): Likewise.
* rust-session-manager.cc (Session::handle_crate_name): Likewise.
* ast/rust-ast.cc (Module::load_items): Likewise.
gcc/rust/ChangeLog:
* ast/rust-ast.h: Keep location in TraitItem base class
* ast/rust-item.h (class TraitItemFunc): Use base class location instead.
(class TraitItemMethod): Likewise.
(class TraitItemConst): Likewise.
(class TraitItemType): Likewise.
* ast/rust-macro.h: Likewise.
'dg-excess-errors' "indicates that the test is expected to fail due to compiler
messages that are not handled by 'dg-error', [etc.]". It's argument doesn't
specify the message to match but just just a comment. Here, however, we'd like
to match specific compiler messages, so we should use 'dg-error', etc. Use the
magic line number zero as the compiler error diagnostic doesn't tell which line
the error occurred on (separate issue to resolve). This gives us:
-XFAIL: rust/compile/issue-1830_str.rs (test for excess errors)
+PASS: rust/compile/issue-1830_bytes.rs at line 8 (test for errors, line )
+PASS: rust/compile/issue-1830_bytes.rs (test for excess errors)
-XFAIL: rust/compile/issue-1830_bytes.rs (test for excess errors)
+PASS: rust/compile/issue-1830_str.rs at line 8 (test for errors, line )
+PASS: rust/compile/issue-1830_str.rs (test for excess errors)
Fix-up for recent GCC/Rust master branch #1838
commit cf9ed4001e
"testsuite: Add empty string macro test".
gcc/testsuite/
* rust/compile/issue-1830_bytes.rs: Fix up DejaGnu directives.
* rust/compile/issue-1830_str.rs: Likewise.
gcc/rust/ChangeLog:
* expand/rust-macro-builtins.cc (MacroBuiltin::include_handler): Do not
return nullptr token in expansion of `include!()`
gcc/testsuite/ChangeLog:
* rust/compile/empty.in: New test.
* rust/compile/include_empty.rs: New test.
When implementing general bounds checking as part of unify calls, we did
not check associated types on bounds which lead to alot of missed error
checking. This now recursively checks the bounds and the associated types
with a decent error message. This also required us to implement the Sized
marker trait to keep existing test-cases happy.
Fixes#1725
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
gcc/rust/ChangeLog:
* typecheck/rust-hir-trait-reference.cc (TraitReference::clear_associated_types): make const
(TraitReference::clear_associated_type_projections): new interface
* typecheck/rust-hir-trait-reference.h:
* typecheck/rust-hir-trait-resolve.cc (TraitResolver::resolve_trait): refactor
(TraitItemReference::associated_type_reset): reset projections
* typecheck/rust-hir-type-bounds.h:
* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit): fix bounds
* typecheck/rust-tyty-bounds.cc (TypeBoundsProbe::TypeBoundsProbe): refactor into cc file
(TypeBoundsProbe::Probe): refactor
(TypeBoundsProbe::is_bound_satisfied_for_type): likewise
(TypeBoundsProbe::assemble_sized_builtin): add builtin for Sized
(TypeCheckBase::get_predicate_from_bound): refactor
(TypeBoundPredicate::lookup_associated_type): refactor
* typecheck/rust-tyty-subst.cc (SubstitutionRef::lookup_associated_impl)
(SubstitutionRef::prepare_higher_ranked_bounds): new interface to clear hanging bounds
(SubstitutionRef::monomorphize): refactor
* typecheck/rust-tyty-subst.h:
* typecheck/rust-tyty.cc (BaseType::get_locus): helper
(BaseType::satisfies_bound): ensure bounds are satisfied and assoicated types
(ParamType::ParamType): new field in constructor
(ParamType::clone): update clone
(ParamType::set_implicit_self_trait): new interface
(ParamType::is_implicit_self_trait): likewise
* typecheck/rust-tyty.h: cleanup
* util/rust-hir-map.cc (Mappings::Mappings): builtin marker
(Mappings::~Mappings): delete marker
(Mappings::lookup_builtin_marker): lookup
* util/rust-hir-map.h: update header
gcc/testsuite/ChangeLog:
* rust/compile/issue-1725-1.rs: New test.
* rust/compile/issue-1725-2.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
gcc/rust/ChangeLog:
* hir/tree/rust-hir-item.h: implement virtual function
* hir/tree/rust-hir.h: add virtual function
Add two new tests with empty string for include_str and include_bytes
macros.
gcc/testsuite/ChangeLog:
* rust/compile/issue-1830_bytes.rs: New test.
* rust/compile/issue-1830_str.rs: New test.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
RAIIFile constructor was accepting directory filename. This lead to
unattended directory opening in some part of the code (load_file_bytes)
wich resulted in ice. Since RAIIFile are used for the lexer, removing
the ability to open directories with RAIIFile fixes those issues and
prevent future mistakes.
gcc/rust/ChangeLog:
* lex/rust-lex.h: Add file type check.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Now that we're using the Github merge queue, this is required to not
let the queue hanging.
ChangeLog:
* .github/workflows/bootstrap.yml: Add missing `merge_group` trigger.
* .github/workflows/ccpp.yml: Likewise.
* .github/workflows/clang-format.yml: Likewise.
* .github/workflows/commit-format.yml: Likewise.
1850: Update GCC/Rust files per 'contrib/update-copyright.py --this-year' [#1831] r=tschwinge a=tschwinge
Fixes: #1831
1851: Merge upstream (dummy), 2023-01-31 GCC/Rust upstreaming r=tschwinge a=tschwinge
In #1847 "Merge upstream, last commit before 2023-01-31 GCC/Rust upstreaming"
we merged commit 9e56306f4d from upstream GCC
master branch.
This one now merges the 2023-01-31 GCC/Rust upstreaming, commits
9e56306f4d7c15e7667d8ac0b62ae6efb93ba756..50335ddd301404e9053786b26a23a924471b4d09:
- 5be4c2687a gccrs: session-manager: Add ast-pretty-expanded dump
- e66fec8e6b gccrs: const folding port
- ff8a569507 gccrs: Desugar double borrows into two HIR:BorrowExpr's
- 86743891a6 gccrs: backend: Expose Bvariable class through rust-gcc header
- 41547275c5 gccrs: builtins: Add add_overflow builtin and refactor class
- 9c87dc0afe gccrs: backend: Add overflow checks to every arithmetic operation
- 3a3a352091 gccrs: rustc_attrs: Allow `rustc_inherit_overflow_checks` as a builtin..
- 938facc5e9 gccrs: lint: Do not emit unused warnings for public items
- f7014b28b8 gccrs: parser: Parse RangeFullExpr without erroring out
- 1fed030c16 gccrs: macros: Handle matchers properly in repetitions
- 252216dd0c gccrs: transcriber: Do not infinite loop if the current parsed node is an error
- 7dc4190121 gccrs: dump: Add AST debugging using the AST::Dump class
- 55fb35c51b gccrs: ast: Only expand expressions and types if the kind is right
- 3663d7ef66 gccrs: ast: Add better assertion on AST fragments
- 245ce6f26a gccrs: Add guards against getting data from an empty vector
- af22b54af5 gccrs: Add missing location info to coercions
- 7ad24d802e gccrs: Refactor unify to hit a unify_site
- 1eabeb5aec gccrs: Remove param_use_canonical_types checks ported from c++ front-end
- ffa16a4590 gccrs: Create canonical process of compiling constant items
- 43cb42a3d8 gccrs: Add extra debugging for method call expressions
- e641158a5f gccrs: Add new check for contains_associated_types
- 0fffc0e772 gccrs: Unit structs are not concrete when they need substitutions
- 689a5c6711 gccrs: bugfix: initialize slice from array in const context
- b0ff1647cb gccrs: add testcase to test component_ref and constructor codes in eval_constant_expression()
- e6a3886a83 gccrs: backend: correctly formulate the exit condition ...
- dd9d6656e9 gccrs: add testcase with struct to test component_ref and constructor codes..
- 0d5adf0935 gccrs: testsuite: add loop condition execution test
- 288b6298a6 gccrs: const generics: Make sure const generic types are visited properly
- ff9d7741d4 gccrs: const generics: Forbid default values in Functions, Traits and Impls
- 739d0509ed gccrs: attributes: Add #[macro_use] as builtin
- 3736647947 gccrs: module lowering: Do not append null pointers as items
- 70fc174b78 gccrs: Static Items must be const evaluated
- 408ab8a6e4 gccrs: Statics are a coercion site
- a0c2ea3ee6 gccrs: remove bad assertion
- f92f8ee75b gccrs: Add testcase for const-eval issue from rust-blog
- 9d6b434e1f gccrs: rust: Add -frust-compile-until option
- e88ce5cc68 gccrs: expand: eager evaluate macros inside builtin macros
- c6c4342273 gccrs: testsuite/rust: add a testcase for testing ...
- e1beb624ff gccrs: Cleanup formatting of backend expression visitor
- 9c60f0e1e5 gccrs: Make constexpr constructors type-checking more permissive
- 11a37f8950 gccrs: Fix duplicated function generation on higher ranked trait bounds
- 104cc28553 gccrs: Refactor TypeResolution to be a simple query based system
- d9d7b6ccd4 gccrs: Add testcase to show forward declared items work
- 50335ddd30 gccrs: Add testcase to show forward declared items work via TypeAlias
This merge is done with 'git merge --strategy=ours', so effectively doesn't
merge any changes. Rationale: those commits are taken from GCC/Rust master
branch, and any remaining changes we'd either like to persist, or assess
individually, later.
Co-authored-by: Thomas Schwinge <thomas@codesourcery.com>
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
Co-authored-by: Faisal Abbas <90.abbasfaisal@gmail.com>
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
Co-authored-by: liushuyu <liushuyu011@gmail.com>
In #1847 "Merge upstream, last commit before 2023-01-31 GCC/Rust upstreaming"
we merged commit 9e56306f4d from upstream GCC
master branch.
This one now merges the 2023-01-31 GCC/Rust upstreaming, commits
9e56306f4d7c15e7667d8ac0b62ae6efb93ba756..50335ddd301404e9053786b26a23a924471b4d09:
- 5be4c2687a gccrs: session-manager: Add ast-pretty-expanded dump
- e66fec8e6b gccrs: const folding port
- ff8a569507 gccrs: Desugar double borrows into two HIR:BorrowExpr's
- 86743891a6 gccrs: backend: Expose Bvariable class through rust-gcc header
- 41547275c5 gccrs: builtins: Add add_overflow builtin and refactor class
- 9c87dc0afe gccrs: backend: Add overflow checks to every arithmetic operation
- 3a3a352091 gccrs: rustc_attrs: Allow `rustc_inherit_overflow_checks` as a builtin..
- 938facc5e9 gccrs: lint: Do not emit unused warnings for public items
- f7014b28b8 gccrs: parser: Parse RangeFullExpr without erroring out
- 1fed030c16 gccrs: macros: Handle matchers properly in repetitions
- 252216dd0c gccrs: transcriber: Do not infinite loop if the current parsed node is an error
- 7dc4190121 gccrs: dump: Add AST debugging using the AST::Dump class
- 55fb35c51b gccrs: ast: Only expand expressions and types if the kind is right
- 3663d7ef66 gccrs: ast: Add better assertion on AST fragments
- 245ce6f26a gccrs: Add guards against getting data from an empty vector
- af22b54af5 gccrs: Add missing location info to coercions
- 7ad24d802e gccrs: Refactor unify to hit a unify_site
- 1eabeb5aec gccrs: Remove param_use_canonical_types checks ported from c++ front-end
- ffa16a4590 gccrs: Create canonical process of compiling constant items
- 43cb42a3d8 gccrs: Add extra debugging for method call expressions
- e641158a5f gccrs: Add new check for contains_associated_types
- 0fffc0e772 gccrs: Unit structs are not concrete when they need substitutions
- 689a5c6711 gccrs: bugfix: initialize slice from array in const context
- b0ff1647cb gccrs: add testcase to test component_ref and constructor codes in eval_constant_expression()
- e6a3886a83 gccrs: backend: correctly formulate the exit condition ...
- dd9d6656e9 gccrs: add testcase with struct to test component_ref and constructor codes..
- 0d5adf0935 gccrs: testsuite: add loop condition execution test
- 288b6298a6 gccrs: const generics: Make sure const generic types are visited properly
- ff9d7741d4 gccrs: const generics: Forbid default values in Functions, Traits and Impls
- 739d0509ed gccrs: attributes: Add #[macro_use] as builtin
- 3736647947 gccrs: module lowering: Do not append null pointers as items
- 70fc174b78 gccrs: Static Items must be const evaluated
- 408ab8a6e4 gccrs: Statics are a coercion site
- a0c2ea3ee6 gccrs: remove bad assertion
- f92f8ee75b gccrs: Add testcase for const-eval issue from rust-blog
- 9d6b434e1f gccrs: rust: Add -frust-compile-until option
- e88ce5cc68 gccrs: expand: eager evaluate macros inside builtin macros
- c6c4342273 gccrs: testsuite/rust: add a testcase for testing ...
- e1beb624ff gccrs: Cleanup formatting of backend expression visitor
- 9c60f0e1e5 gccrs: Make constexpr constructors type-checking more permissive
- 11a37f8950 gccrs: Fix duplicated function generation on higher ranked trait bounds
- 104cc28553 gccrs: Refactor TypeResolution to be a simple query based system
- d9d7b6ccd4 gccrs: Add testcase to show forward declared items work
- 50335ddd30 gccrs: Add testcase to show forward declared items work via TypeAlias
This merge is done with 'git merge --strategy=ours', so effectively doesn't
merge any changes. Rationale: those commits are taken from GCC/Rust master
branch, and any remaining changes we'd either like to persist, or assess
individually, later.
1750: Implement fixed point macro expansion r=CohenArthur a=CohenArthur
This is a cleanup of #1606's branch, which also contains the code necessary for performing eager macro expansion in builtin macros.
This commit changes our macro expansion system from an eager and recursive
macro expansion to a fixed-point like system. Instead of, when seeing
a macro invocation, expanding it and all of the macros within it, we
now perform multiple passes of expansion on the entire crate.
This, however, leads to a problem. Rust macros are expanded lazily, but
Rust builtin macros should be expanded eagerly. Due to this, we must
work around the lazy expansion in builtin macros and perform eager
expansion for each pass of the fixed-point, before finally expanding
the builtin when there are no longer any inner macro invocations.
To perform proper macro scoping, the ENR now keeps track of the current
scope (`current_scope` member) and resolves macros accordingly.
This is done through the use of the `scoped` method, which creates a new
scope, runs a specified lambda and then exits the scope. This prevents
pushing/popping errors that we've seen happen already in similar
contexts.
We might think about generalizing it to other classes, providing a
`Scoped<EntryFn, ExitFn>` class or similar
Fixes#1795
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
Conflicts:
gcc/config/rs6000/rs6000-logue.cc
This overrides GCC/Rust #1512 commit 8e9dcd47d3
"Add missing language selection for rs6000"
with upstream GCC commit r13-4762-gf80f540e394e87ac70349bad109bfc4b465c7c98
"rs6000: Add Rust support to traceback table".
1820: Support for TuplePattern in let statements r=CohenArthur a=powerboat9
Added support for TuplePattern in let statements, along with a test.
Co-authored-by: Owen Avery <powerboat9.gamer@gmail.com>
1810: fixed indentation in AST pretty printed expanded dump of trait. r=CohenArthur a=00AR
fixes#1785
Signed-off-by: Abdul Rafey <abdulrafeyq@gmail.com>
---
In Dump::visit (TraitImpl), the for loop adds indentation before calling visit () on every iteration. I think when Dump::visit (Method) is executed it adds extra indentation on top of it.
1823: parser: Improve parsing of complex generic arguments r=CohenArthur a=CohenArthur
The parser was missing code for handling complex type arguments such as type paths or nested generics.
gcc/rust/ChangeLog:
* parse/rust-parse-impl.h (Parser::parse_generic_arg): Handle type paths and nested generics properly.
gcc/testsuite/ChangeLog:
* rust/compile/parse_complex_generic_application.rs: New test.
* rust/compile/parse_complex_generic_application2.rs: New test.
1824: parser: Fix parsing of closure param list r=CohenArthur a=CohenArthur
gcc/rust/ChangeLog:
* parse/rust-parse-impl.h (Parser::parse_closure_expr): Advance tokens properly when parsing closure param list.
gcc/testsuite/ChangeLog:
* rust/compile/closure_move_expr.rs: New test.
1837: typecheck: Refactor rust-hir-trait-reference.h r=CohenArthur a=P-E-P
Move function body to their own cc file instead of keeping them in the header file.
gcc/rust/ChangeLog:
* Make-lang.in: Add `rust-hir-trait-reference.o`.
* typecheck/rust-hir-trait-reference.h: Remove multiple function body.
* typecheck/rust-hir-trait-reference.cc: Add multiple function body.
Fixes#1835
1839: cli: Update safety warning message r=CohenArthur a=P-E-P
The compiler's warning message about the safety flag did not match cargo-gccrs environment variable name anymore.
gcc/rust/ChangeLog:
* rust-session-manager.cc (Session::compile_crate): Update the environment variable name.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Fixes#1829
Co-authored-by: Abdul Rafey <abdulrafeyq@gmail.com>
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
Co-authored-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
1832: ci: Run commit format checker on push to `trying` branch r=CohenArthur a=CohenArthur
ChangeLog:
* .github/workflows/commit-format.yml: Run job on pushes to `trying`.
This should hopefully stop bors from timing out.
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
The compiler's warning message about the safety flag did not match
cargo-gccrs environment variable name anymore.
gcc/rust/ChangeLog:
* rust-session-manager.cc (Session::compile_crate): Update the
environment variable name.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Move function body to their own cc file instead of keeping them in the
header file.
gcc/rust/ChangeLog:
* Make-lang.in: Add `rust-hir-trait-reference.o`.
* typecheck/rust-hir-trait-reference.h: Remove multiple function body.
* typecheck/rust-hir-trait-reference.cc: Add multiple function body.
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
This commit changes our macro expansion system from an eager and recursive
macro expansion to a fixed-point like system. Instead of, when seeing
a macro invocation, expanding it and all of the macros within it, we
now perform multiple passes of expansion on the entire crate.
This, however, leads to a problem. Rust macros are expanded lazily, but
Rust builtin macros should be expanded eagerly. Due to this, we must
work around the lazy expansion in builtin macros and perform eager
expansion for each pass of the fixed-point, before finally expanding
the builtin when there are no longer any inner macro invocations.
To perform proper macro scoping, the ENR now keeps track of the current
scope (`current_scope` member) and resolves macros accordingly.
This is done through the use of the `scoped` method, which creates a new
scope, runs a specified lambda and then exits the scope. This prevents
pushing/popping errors that we've seen happen already in similar
contexts.
We might think about generalizing it to other classes, providing a
`Scoped<EntryFn, ExitFn>` class or similar
gcc/rust/ChangeLog:
* ast/rust-macro.cc: New file.
* Make-lang.in: Add `rust-macro.o` object
* ast/rust-ast-fragment.cc (Fragment::Fragment): Change API around
the construction of AST fragments.
(Fragment::operator=): Correct `Fragment::operator=` to take into
account the fragment tokens.
(Fragment::create_error): Use new constructor.
(Fragment::complete): Remove in favor of new constructor.
(Fragment::unexpanded): Remove as that Fragment type is no longer used
or possible.
(Fragment::get_tokens): Add helper to access a fragment's tokens.
* ast/rust-ast-fragment.h (enum class): Remove `FragmentKind::Unused`
* ast/rust-ast.cc (MacroInvocation::as_string): Display
builtin macro invocations properly.
* ast/rust-ast.h: Fix `DelimTokenTree` class copy constructors and
handling of its token vector.
* ast/rust-macro.h (class MacroMatcher): Format.
(class MetaItemSeq): Likewise.
(builtin_macro_from_string): Get a `BuiltinMacroKind` from a given
string, i.e the name of the macro (`assert!`, `cfg!` and so on).
* expand/rust-attribute-visitor.cc (AttrVisitor::visit): Do not expand
macros recursively anymore.
(AttrVisitor::maybe_expand_expr): Likewise.
(AttrVisitor::maybe_expand_type): Likewise.
* expand/rust-attribute-visitor.h: Likewise, and remove
`expand_macro_fragment_recursively` function.
* expand/rust-macro-builtins.cc (make_token): Add shorthand for
returning `std::unique_ptr<AST::Token>`s.
(make_macro_invocation): Add shorthand for returning fragments
containing builtin macro invocations.
(try_expand_macro_expression): Do not expand macros recursively.
(try_expand_single_string_literal): Likewise.
(try_expand_many_expr): Likewise.
(parse_single_string_literal): Error out more appropriately.
(MacroBuiltin::file_handler): Return the proper tokens associated with
macro invocation, and builtin macros in the case of necessary eager
expansion.
(MacroBuiltin::column_handler): Likewise.
(MacroBuiltin::include_bytes_handler): Likewise.
(MacroBuiltin::include_str_handler): Likewise.
(MacroBuiltin::concat_handler): Likewise.
(MacroBuiltin::env_handler): Likewise.
(MacroBuiltin::cfg_handler): Likewise.
(MacroBuiltin::include_handler): Likewise.
(MacroBuiltin::line_handler): Likewise.
* expand/rust-macro-expand.cc (MacroExpander::expand_eager_invocations):
Add function to expand eager invocations *once* in the fixed point
pipeline.
(MacroExpander::expand_invoc): Call into `expand_eager_invocations` for
builtin macro invocations.
(MacroExpander::expand_crate): Use new `AttrVisitor` API.
(parse_many): Return tokens in `AST::Fragment`.
(transcribe_expression): Likewise.
(transcribe_type): Likewise.
* expand/rust-macro-expand.h (struct MacroExpander): Add `has_changed`
flag for fixed point checking.
* resolve/rust-early-name-resolver.cc (EarlyNameResolver::EarlyNameResolver):
Keep track of the current macro scope.
(EarlyNameResolver::go): Use `scoped` API.
(EarlyNameResolver::visit): Likewise.
* resolve/rust-early-name-resolver.h: Add `scoped` API.
* rust-session-manager.cc (Session::expansion): Perform macro expansion
in a fixed-point fashion.
gcc/testsuite/ChangeLog:
* rust/compile/macro17.rs: Fix testsuite for new recursion errors.
* rust/compile/macro44.rs: Fix invalid testcase assertions.
* rust/compile/builtin_macro_recurse.rs: Fix invalid test.
* rust/compile/builtin_macro_recurse2.rs: New test.
* rust/compile/macro46.rs: New test.
This commit turns AST::MacroInvocation into a sum type.
The class can now represent a regular macro invocation (lazily expanded)
or a builtin one (eagerly expanded)
gcc/rust/ChangeLog:
* expand/rust-macro-builtins.cc (make_macro_invocation): Add short hand
function for returning fragments containing macro invocations.
(MacroBuiltin::compile_error_handler): Add explanation for eager
invocation
1739: Initial type bounds checking for all type checks r=philberty a=philberty
This patchset is my branch for general improvements to the type-system and
for improved type bounds checking in preparation for opaque types.
Fixes#1773#1786
Co-authored-by: Philip Herron <herron.philip@googlemail.com>
This updates the higher ranked trait bounds computation to handle ambigious
cases. When we have a slice for example:
let slice = &a[1..3];
This works by reusing the Index operator overload from libcore, so when the
index range of 1..3 is computed, the type system needs to compute what the
types of index are; this works by integer inference variables
Range<<integer>> that need to be unified with the impl Index for
Range<Usize> which computes the real type of usize for the index. This is
fine but what happens when we have the Copy and Clone traits bounds which
have implementations for all the primitive types i8, i16, i32, i64...
which is valid for any integer inference variable so the code prior to this
patch would have grabbed the first impl it would have found and used it
which is incorrect. When we have integer or float inference variables we
need to look for their respective defaults or emit an ambigious type bound
error.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
gcc/rust/ChangeLog:
* typecheck/rust-hir-trait-reference.h: add const infterface
* typecheck/rust-tyty-subst.cc (SubstitutionParamMapping::get_generic_param): make const
(SubstitutionRef::monomorphize): fix issue
* typecheck/rust-tyty-subst.h: constify interface
We need these lang items to be defined and later down the line the mappings
will be used to implement proper copy and clone logic.
Fixes#1786
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
gcc/rust/ChangeLog:
* util/rust-lang-item.h:
gcc/testsuite/ChangeLog:
* rust/compile/issue-1786.rs: New test.
When we check if this is concrete the guard checks to ensure the argument
is non null but the check here is wrongly returning early when the check
is non null meaning when it is null and therefore not concrete it will
end up doing a null dereference.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
gcc/rust/ChangeLog:
* typecheck/rust-tyty-subst.cc (SubstitutionArg::is_conrete): fix check
This refactors the unification systems to be a consistent interface using
switch statements and simple functions instead of the old clunky visitor
system. This is more maintainable as it is harder to miss cases when we
can take advantages of switch statements.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
gcc/rust/ChangeLog:
* Make-lang.in: update names
* backend/rust-compile-expr.cc (CompileExpr::resolve_method_address):
update to use new interface
* typecheck/rust-coercion.cc (TypeCoercionRules::coerce_borrowed_pointer): likewise
* typecheck/rust-hir-type-check-base.cc (TypeCheckBase::unify_site): likewise
* typecheck/rust-tyty.cc (BaseType::destructure): likewise
(InferType::unify): removed old unify interface
(ErrorType::unify): likewise
(ADTType::unify): likewise
(TupleType::unify): likewise
(FnType::unify): likewise
(FnPtr::unify): likewise
(ClosureType::unify): likewise
(ArrayType::unify): likewise
(SliceType::unify): likewise
(BoolType::unify): likewise
(IntType::unify): likewise
(UintType::unify): likewise
(FloatType::unify): likewise
(USizeType::unify): likewise
(ISizeType::unify): likewise
(CharType::unify): likewise
(ReferenceType::unify): likewise
(PointerType::unify): likewise
(ParamType::unify): likewise
(StrType::unify): likewise
(NeverType::unify): likewise
(PlaceholderType::unify): likewise
(ProjectionType::unify): likewise
(DynamicObjectType::unify): likewise
* typecheck/rust-tyty.h: update destructure interface
* typecheck/rust-tyty-rules.h: Removed.
* typecheck/rust-unify.cc: New file.
* typecheck/rust-unify.h: New file.
gcc/testsuite/ChangeLog:
* rust/compile/never_type_err1.rs: Moved to...
* rust/compile/never_type1.rs: ...here. It now works
During CallExpr argument type checking we may be calling a default
implementation of a trait function this will require any possible
associated types to be resolved and setup. This monomoprhization call does
this but it will premtivly do extra unification of types which will throw
off type checking later on. This fix is required for my work into type
bounds checking.
Fixes#1773
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
gcc/rust/ChangeLog:
* typecheck/rust-hir-trait-reference.h: change interface to return self
* typecheck/rust-hir-trait-resolve.cc: likewise
* typecheck/rust-hir-type-check-path.cc (TypeCheckExpr::resolve_segments): likewise
* typecheck/rust-tyty-call.cc (TypeCheckCallExpr::visit): remove monomorphization hack
gcc/testsuite/ChangeLog:
* rust/compile/issue-1773.rs: New test.
When we set the callback on substitutions this is not safe to be copied
around since we store the used argument mappings and can reuse them in
different contexts. This clears the callback on copy's to make it safer.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
gcc/rust/ChangeLog:
* typecheck/rust-tyty-subst.cc: update copy constructors
This patch changes the recusive substitution code to take a reference
instead of a copy. This is important as the callback field is going to be
made non-copyable in a future patch and this pipeline is for recursive
substitutions so its ok to reuse the same mappings here.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
gcc/rust/ChangeLog:
* typecheck/rust-tyty-bounds.cc: refactor to take a reference
* typecheck/rust-tyty-subst.cc: likewise
(SubstitutionRef::get_substitution_arguments): likewise
(SubstitutionRef::infer_substitions): likewise
* typecheck/rust-tyty-subst.h: likewise
* typecheck/rust-tyty.cc (ADTType::handle_substitions): likewise
(TupleType::handle_substitions): likewise
(FnType::handle_substitions): likewise
(ClosureType::handle_substitions): likewise
(ArrayType::handle_substitions): likewise
(SliceType::handle_substitions): likewise
(ReferenceType::handle_substitions): likewise
(PointerType::handle_substitions): likewise
(ParamType::handle_substitions): likewise
(ProjectionType::handle_substitions): likewise
* typecheck/rust-tyty.h: likewise
This moves the implementation code out of the header and into its
respective cc file.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
gcc/rust/ChangeLog:
* typecheck/rust-tyty-bounds.cc (TypeBoundPredicateItem::error): refactor
(TypeBoundPredicateItem::is_error): likewise
(TypeBoundPredicateItem::get_parent): likewise
* typecheck/rust-tyty.h: Move the implementation for the above
This demonstrates that this also works for custom algebraic data types too.
gcc/testsuite/ChangeLog:
* rust/execute/torture/issue-1720-2.rs: New test.
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
1737: Add support for feature check. r=CohenArthur a=TuringKi
This commit implements a very basic feature checking module.
The results like this:
```
../gcc/testsuite/rust/compile/feature.rs:1:12: error: unknown feature 'AA'
1 | #![feature(AA)] //{ dg-error "unknown feature 'AA'" }
| ^
```
This commit is split from pr https://github.com/Rust-GCC/gccrs/pull/1718.
Signed-off-by: Xiao Ma <mxlol233@outlook.com>
Co-authored-by: mxlol233 <mxlol233@outlook.com>
1698: update the ubuntu version r=CohenArthur a=ArshErgon
Fixes: #1689
updated the ubuntu-version from 20.04 to 22.04
Thank you for making Rust GCC better!
If your PR fixes an issue, you can add "Fixes #issue_number" into this
PR description and the git commit message. This way the issue will be
automatically closed when your PR is merged. If your change addresses
an issue but does not fully fix it please mark it as "Addresses #issue_number"
in the git commit message.
Here is a checklist to help you with your PR.
- \[ ] GCC development requires copyright assignment or the Developer's Certificate of Origin sign-off, see https://gcc.gnu.org/contribute.html or https://gcc.gnu.org/dco.html
- \[ ] Read contributing guidlines
- \[ ] `make check-rust` passes locally
- \[ ] Run `clang-format`
- \[ ] Added any relevant test cases to `gcc/testsuite/rust/`
Note that you can skip the above if you are just opening a WIP PR in
order to get feedback.
---
*Please write a comment explaining your change. This is the message
that will be part of the merge commit.
Co-authored-by: ArshErgon <arshergon@gmail.com>
This commit implements a very basic feature checking module.
gcc/rust/ChangeLog:
* Make-lang.in: Add object files: `rust-feature.o` and `rust-feature-gate.o`
* checks/errors/rust-feature-gate.cc: New file.
* checks/errors/rust-feature-gate.h: New file.
* checks/errors/rust-feature.cc: New file.
* checks/errors/rust-feature.h: New file.
* rust-session-manager.cc: Add FeatureGate check.
gcc/testsuite/ChangeLog:
* rust/compile/feature.rs: New test.
Signed-off-by: Xiao Ma <mxlol233@outlook.com>
1812: parser: Allow parsing multiple reference types r=CohenArthur a=CohenArthur
The parser now recursively tries to parse a reference type after seeing a `&` or `&&` token.
gcc/rust/ChangeLog:
* parse/rust-parse-impl.h (Parser::parse_type): Handle double ampersan properly (Parser::parse_reference_type): Call into `parse_reference_type_inner` and wrap double reference types in another `AST::ReferenceType` node (Parser::parse_reference_type_inner): Add parsing implementation which does not care about the leading token (& or &&) (Parser::parse_type_no_bounds): Handle double ampersand properly
* parse/rust-parse.h: Declare `parse_reference_type_inner`
gcc/testsuite/ChangeLog:
* rust/compile/multi_reference_type.rs: New test.
Addresses #1807 partly
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
The parser was missing code for handling complex type arguments such
as type paths or nested generics.
gcc/rust/ChangeLog:
* parse/rust-parse-impl.h (Parser::parse_generic_arg): Handle type
paths and nested generics properly.
gcc/testsuite/ChangeLog:
* rust/compile/parse_complex_generic_application.rs: New test.
* rust/compile/parse_complex_generic_application2.rs: New test.
This updates the CI to use ubuntu's latest LTS release, 22.04
ChangeLog:
* .github/bors_log_expected_warnings: Update warnings.
* .github/workflows/bootstrap.yml: Update Ubuntu version to 22.04.
* .github/workflows/ccpp.yml: Likewise.
1811: Merge upstream (dummy), "Rust front-end patches v4" r=tschwinge a=tschwinge
Last we did #1700 "Merge upstream, last commit before GCC/Rust upstreaming",
which merged commit b4fddbe959 from GCC upstream
master branch.
This one now merges the "Rust front-end patches v4", commits
b4fddbe9592e9feb37ce567d90af822b75995531..edc676cfe8988c62c81b0df224c7fe82583012b1:
- dd950cbbb9 Use DW_ATE_UTF for the Rust 'char' type
- b772a504ef gccrs: Add necessary hooks for a Rust front-end testsuite
- 4b8f3005af gccrs: Add Debug info testsuite
- f60df7e620 gccrs: Add link cases testsuite
- 97705b4459 gccrs: Add general compilation test cases
- 5a56869d6e gccrs: Add execution test cases
- dc4171edb3 gccrs: Add gcc-check-target check-rust
- 6b35ae12ce gccrs: Add Rust front-end base AST data structures
- 438ae944fa gccrs: Add definitions of Rust Items in AST data structures
- d588754c82 gccrs: Add full definitions of Rust AST data structures
- 5b981e9c74 gccrs: Add Rust AST visitors
- 18f6990f84 gccrs: Add Lexer for Rust front-end
- 35e4f3b4af gccrs: Add Parser for Rust front-end pt.1
- 32c8fb0eea gccrs: Add Parser for Rust front-end pt.2
- 1841081a8a gccrs: Add expansion pass for the Rust front-end
- 85a8fe00f8 gccrs: Add name resolution pass to the Rust front-end
- 8ad1d56d68 gccrs: Add declarations for Rust HIR
- 7641eaead4 gccrs: Add HIR definitions and visitor framework
- 7999cf327d gccrs: Add AST to HIR lowering pass
- b32b1b1576 gccrs: Add wrapper for make_unique
- c7f8347e83 gccrs: Add port of FNV hash used during legacy symbol mangling
- 15b0278905 gccrs: Add Rust ABI enum helpers
- eb10bc5225 gccrs: Add Base62 implementation
- 9a4fee5f57 gccrs: Add implementation of Optional
- 2e7fc8780e gccrs: Add attributes checker
- 9ce37e7206 gccrs: Add helpers mappings canonical path and lang items
- c6c3db2176 gccrs: Add type resolution and trait solving pass
- 24393cb68f gccrs: Add Rust type information
- 06688fe40a gccrs: Add remaining type system transformations
- b1b35204d8 gccrs: Add unsafe checks for Rust
- 5215235f01 gccrs: Add const checker
- ca246e573f gccrs: Add privacy checks
- 520b52b24e gccrs: Add dead code scan on HIR
- 4d67468d1d gccrs: Add unused variable scan
- 509e4c32c6 gccrs: Add metadata output pass
- 15f04af347 gccrs: Add base for HIR to GCC GENERIC lowering
- 019b2f1558 gccrs: Add HIR to GCC GENERIC lowering for all nodes
- cfbda2f78b gccrs: Add HIR to GCC GENERIC lowering entry point
- fe6264fa28 gccrs: These are wrappers ported from reusing gccgo
- bba14a0790 gccrs: Add compiler driver
- ea34614225 gccrs: Compiler proper interface kicks off the pipeline
- ab1e0db43c gccrs: Add lang-spec.h
- 5e7d199739 gccrs: Add lang.opt
- 88415d33bb gccrs: Add GCC Rust front-end Make-lang.in
- b07ef39ffb gccrs: Add fatal_error when experimental flag is not present
- a75f038c06 gccrs: Add config-lang.in
- edc676cfe8 gccrs: Add README, CONTRIBUTING and compiler logo
This merge is done with `git merge --strategy=ours`, so that we effectively
don't bring any changes. Rationale: any changes due to upstream review etc.,
have already been applied individually to GCC/Rust master branch, and any
remaining changes we'd either like to persist, or assess individually, later.
Co-authored-by: Tom Tromey <tom@tromey.com>
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
Co-authored-by: Joel Phillips <simplytheother@gmail.com>
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
The parser now recursively tries to parse a reference type after seeing
a `&` or `&&` token.
gcc/rust/ChangeLog:
* parse/rust-parse-impl.h (Parser::parse_type): Handle double ampersan
properly
(Parser::parse_reference_type): Call into `parse_reference_type_inner`
and wrap double reference types in another `AST::ReferenceType` node
(Parser::parse_reference_type_inner): Add parsing implementation
which does not care about the leading token (& or &&)
(Parser::parse_type_no_bounds): Handle double ampersand properly
* parse/rust-parse.h: Declare `parse_reference_type_inner`
gcc/testsuite/ChangeLog:
* rust/compile/multi_reference_type.rs: New test.
Last we did #1700 "Merge upstream, last commit before GCC/Rust upstreaming",
which merged commit b4fddbe959 from GCC upstream
master branch.
This one now merges the "Rust front-end patches v4", commits
b4fddbe9592e9feb37ce567d90af822b75995531..edc676cfe8988c62c81b0df224c7fe82583012b1:
- dd950cbbb9 Use DW_ATE_UTF for the Rust 'char' type
- b772a504ef gccrs: Add necessary hooks for a Rust front-end testsuite
- 4b8f3005af gccrs: Add Debug info testsuite
- f60df7e620 gccrs: Add link cases testsuite
- 97705b4459 gccrs: Add general compilation test cases
- 5a56869d6e gccrs: Add execution test cases
- dc4171edb3 gccrs: Add gcc-check-target check-rust
- 6b35ae12ce gccrs: Add Rust front-end base AST data structures
- 438ae944fa gccrs: Add definitions of Rust Items in AST data structures
- d588754c82 gccrs: Add full definitions of Rust AST data structures
- 5b981e9c74 gccrs: Add Rust AST visitors
- 18f6990f84 gccrs: Add Lexer for Rust front-end
- 35e4f3b4af gccrs: Add Parser for Rust front-end pt.1
- 32c8fb0eea gccrs: Add Parser for Rust front-end pt.2
- 1841081a8a gccrs: Add expansion pass for the Rust front-end
- 85a8fe00f8 gccrs: Add name resolution pass to the Rust front-end
- 8ad1d56d68 gccrs: Add declarations for Rust HIR
- 7641eaead4 gccrs: Add HIR definitions and visitor framework
- 7999cf327d gccrs: Add AST to HIR lowering pass
- b32b1b1576 gccrs: Add wrapper for make_unique
- c7f8347e83 gccrs: Add port of FNV hash used during legacy symbol mangling
- 15b0278905 gccrs: Add Rust ABI enum helpers
- eb10bc5225 gccrs: Add Base62 implementation
- 9a4fee5f57 gccrs: Add implementation of Optional
- 2e7fc8780e gccrs: Add attributes checker
- 9ce37e7206 gccrs: Add helpers mappings canonical path and lang items
- c6c3db2176 gccrs: Add type resolution and trait solving pass
- 24393cb68f gccrs: Add Rust type information
- 06688fe40a gccrs: Add remaining type system transformations
- b1b35204d8 gccrs: Add unsafe checks for Rust
- 5215235f01 gccrs: Add const checker
- ca246e573f gccrs: Add privacy checks
- 520b52b24e gccrs: Add dead code scan on HIR
- 4d67468d1d gccrs: Add unused variable scan
- 509e4c32c6 gccrs: Add metadata output pass
- 15f04af347 gccrs: Add base for HIR to GCC GENERIC lowering
- 019b2f1558 gccrs: Add HIR to GCC GENERIC lowering for all nodes
- cfbda2f78b gccrs: Add HIR to GCC GENERIC lowering entry point
- fe6264fa28 gccrs: These are wrappers ported from reusing gccgo
- bba14a0790 gccrs: Add compiler driver
- ea34614225 gccrs: Compiler proper interface kicks off the pipeline
- ab1e0db43c gccrs: Add lang-spec.h
- 5e7d199739 gccrs: Add lang.opt
- 88415d33bb gccrs: Add GCC Rust front-end Make-lang.in
- b07ef39ffb gccrs: Add fatal_error when experimental flag is not present
- a75f038c06 gccrs: Add config-lang.in
- edc676cfe8 gccrs: Add README, CONTRIBUTING and compiler logo
This merge is done with `git merge --strategy=ours`, so that we effectively
don't bring any changes. Rationale: any changes due to upstream review etc.,
have already been applied individually to GCC/Rust master branch, and any
remaining changes we'd either like to persist, or assess individually, later.
1788: ci: Add commit format checker r=CohenArthur a=CohenArthur
Bring over the commit checker from `gcc-patch-dev` with the `gccrs` prefix checker enabled only for `gcc-patch-dev` PRs. I'll open up an issue to make sure that in the future it's easier to keep that folder in sync between the two branches
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
1775: Create and use CompilePatternLet visitor for compiling let statments r=philberty a=powerboat9
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
Implements and utilizes CompilePatternLet to compile let statements
Co-authored-by: Owen Avery <powerboat9.gamer@gmail.com>
1776: fixed compiler error message on wildcard pattern within expression r=CohenArthur a=00AR
Signed-off-by: Abdul Rafey <abdulrafeyq@gmail.com>
fixed compiler error message on wildcard pattern '_' within expression.
Added a new testcase for the same.
#867
Co-authored-by: Abdul Rafey <abdulrafeyq@gmail.com>
1735: macro: Allow builtin `MacroInvocation`s within the AST r=CohenArthur a=CohenArthur
gcc/rust/ChangeLog:
* ast/rust-macro.h (enum class): Add `BuiltinMacro` enum class
* expand/rust-attribute-visitor.cc (AttrVisitor::visit): Mention switching on `macro.kind` once builtin macro invocations are properly handled
* parse/rust-parse-impl.h (Parser::parse_macro_invocation): Switch to new MacroInvocation API
(Parser::parse_type): Switch to new MacroInvocation API
(Parser::parse_type_no_bounds): Switch to new MacroInvocation API
This will be necessary for proper handling of builtin macros with the new `EarlyNameResolver` class and associated fixed-point algorithm
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
1778: Moved operator.h to util/rust-operators.h. r=CohenArthur a=00AR
Signed-off-by: Abdul Rafey <abdulrafeyq@gmail.com>
Refactored operator.h. #1768
Changes shown in rust-operators.h are done by clang-formater.
Co-authored-by: Abdul Rafey <abdulrafeyq@gmail.com>
1777: Rename file rust-ast-full-test.cc to rust-ast.cc r=CohenArthur a=Parthib314
* Fixes issue #1765
**Rename the `rust-ast-full-test.cc` to `rust-ast.cc` and also update it on `Make-lang.in`**
Co-authored-by: Parthib <parthibdutta02@gmail.com>
1759: Revert 10-second timeout for each test r=philberty a=Parthib314
* Fixes issue #1747
**Remove the 10-second timeout for each compile case**
Co-authored-by: vagrant <vagrant@vagrant.vm>
1763: Do not crash on empty macros expand. Fixes#1712 r=philberty a=teromene
This PR fixes a compiler crash when expanding an empty macro into an existing AST.
(I ran clang-format but it marked a few other files as dirty, and I therefore did not touch them)
Signed-off-by: Lyra Karenai <teromene@teromene.fr>
Co-authored-by: Lyra <teromene@teromene.fr>
1760: Support GroupedPattern during name resolution r=philberty a=powerboat9
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
Adds support for GroupedPattern during name resolution.
Addresses #1136
Co-authored-by: Owen Avery <powerboat9.gamer@gmail.com>
1751: README.md: Added experimental flag & updated gccrs path r=CohenArthur a=DrMahad
(1) There is a need of the flag "-frust-incomplete-and-experimental-compiler-do-not-use" because the rust1 compiler didn't work without this.
(2) The gccrs was not present in the $HOME/gccrs-install/, so updated the path to $HOME/gccrs-install/bin
Signed-off-by: MAHAD <mahadtxt@gmail.com>
Co-authored-by: MAHAD <mahadtxt@gmail.com>
(1) There is a need of the flag "-frust-incomplete-and-experimental-compiler-do-not-use" because the rust1 compiler didn't work without this.
(2) The gccrs was not present in the $HOME/gccrs-install/, so updated the path to $HOME/gccrs-install/bin
Signed-off-by: MAHAD <mahadtxt@gmail.com>
1733: diagnostics: Add underline for tokens in diagnostics. r=CohenArthur a=TuringKi
Currently, the diagnostics only point to the corresponding token's start position by carets, and lack of underlines for full token. This commit add support for such underlines in diagnostics by encoding range information in location_t.
the results like this:
```
../gcc/testsuite/rust/compile/bad_as_bool_char.rs:5:14: error: invalid cast 'bool' to 'f32' [E0054]
5 | let fone = t as f32; // { dg-error "invalid cast" }
| ^ ~~~
../gcc/testsuite/rust/compile/bad_as_bool_char.rs:6:15: error: invalid cast 'bool' to 'f64' [E0054]
6 | let fzero = f as f64; // { dg-error "invalid cast" }
| ^ ~~~
../gcc/testsuite/rust/compile/bad_as_bool_char.rs:8:12: error: invalid cast 'u8' to 'bool' [E0054]
8 | let nb = 0u8 as bool; // { dg-error "invalid cast .u8. to .bool. \\\[E0054\\\]" }
| ^~~ ~~~~
../gcc/testsuite/rust/compile/bad_as_bool_char.rs:9:12: error: invalid cast 'bool' to 'char' [E0054]
9 | let nc = true as char; // { dg-error "invalid cast" }
| ^~~~ ~~~~
../gcc/testsuite/rust/compile/bad_as_bool_char.rs:13:12: error: invalid cast 'char' to 'f32' [E0054]
13 | let fa = a as f32; // { dg-error "invalid cast" }
| ^ ~~~
../gcc/testsuite/rust/compile/bad_as_bool_char.rs:14:12: error: invalid cast 'char' to 'bool' [E0054]
14 | let bb = b as bool; // { dg-error "invalid cast .char. to .bool. \\\[E0054\\\]" }
| ^ ~~~~
../gcc/testsuite/rust/compile/bad_as_bool_char.rs:17:12: error: invalid cast 'u32' to 'char' [E0054]
17 | let ab = t32 as char; // { dg-error "invalid cast" }
| ^~~ ~~~~
```
This commit is split from pr #1718.
Signed-off-by: Xiao Ma <mxlol233@outlook.com>
Co-authored-by: mxlol233 <mxlol233@outlook.com>
Currently, the diagnostics only point to the corresponding token's start position by carets, and lack of underlines for full token. This commit add support for such underlines in diagnostics by encoding range information in location_t.
Signed-off-by: Xiao Ma <mxlol233@outlook.com>
1734: Add get_locus function for abstract class MetaItemInner. r=CohenArthur a=TuringKi
This commit adds virtual function get_locus to base class MetaItemInner, which is helpful when we need to print diagnostics on some sub-classes of MetaItemInner.
This commit is split from pr https://github.com/Rust-GCC/gccrs/pull/1718.
Signed-off-by: Xiao Ma <mxlol233@outlook.com>
Co-authored-by: mxlol233 <mxlol233@outlook.com>
This commit adds virtual function get_locus to base class MetaItemInner, which is helpful when we need to print diagnostics on some sub-classes of MetaItemInner.
Signed-off-by: Xiao Ma <mxlol233@outlook.com>
1730: Improve type checking on let statements r=philberty a=powerboat9
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
---
Improves the typechecking of patterns in let statements.
Co-authored-by: Owen Avery <powerboat9.gamer@gmail.com>
Update Rust type-checking to reuse TypeCheckPattern on HIR::LetStmt's.
This will unify the paths and improve error handling.
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
1724: Add support for generics associated type binding r=philberty a=philberty
This patch set adds support to specify the associated type via the argument
binding syntax. We are still missing general bounds checking so in order to
properly add more test cases for bad types we need to implement that first.
I have also changed a test case to -fsyntax-only as at the time I always get
confused between Generic arguments of foo=i32 and bar: baz only specifies
the associated type and the latter adds a bound. Currently we are lacking a
way to represent adding a bound in the AST and HIR within generic arguments
so I have raised: #1725 and #1726Fixes#1720
Co-authored-by: Philip Herron <herron.philip@googlemail.com>
This patch adds support for the GenercArgsBinding type, where you can
specify the associated types of a trait bound using `<Foo=i32>` style
syntax. Note that the type-resolution relys on the i32 impl for Add
as type resolution will resolve the `a+a` to the core::ops::Add method
so code generation will require this to exist.
I have ameded testsuite/rust/compile/bounds.rs as this code is wrongly
creating an HIR::GenericArgs with a trait-object type and causing issues.
the parsing is still correct but we dont have the mechanism to represent
this in AST and HIR properly. I think we will need a new HIR::GenericArgs
AssociatedTypeBindingBound or something similar. We are still lacking
bounds checking during are type coercions and unifications so running this
example using an f32 will wrongly pass type checking, this will need
addressed next.
Fixes#1720
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
gcc/rust/ChangeLog:
* hir/tree/rust-hir-path.h:
* typecheck/rust-hir-path-probe.h:
* typecheck/rust-hir-trait-resolve.cc:
* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit):
* typecheck/rust-tyty-bounds.cc (TypeCheckBase::get_predicate_from_bound):
(TypeBoundPredicate::TypeBoundPredicate):
(TypeBoundPredicate::operator=):
(TypeBoundPredicate::apply_generic_arguments):
(TypeBoundPredicateItem::get_tyty_for_receiver):
(TypeBoundPredicate::get_num_associated_bindings):
(TypeBoundPredicate::lookup_associated_type):
(TypeBoundPredicate::get_associated_type_items):
* typecheck/rust-tyty.cc (SubstitutionRef::get_mappings_from_generic_args):
(SubstitutionRef::infer_substitions):
(SubstitutionRef::solve_missing_mappings_from_this):
* typecheck/rust-tyty.h:
gcc/testsuite/ChangeLog:
* rust/compile/bounds.rs: change to use -fsyntax-only
* rust/execute/torture/issue-1720.rs: New test.
When specifying generic arguments to Traits we can also specify the
associated types using `<BindingName=i32>` syntax we need to add
name resolution to the type argument here and rely on the type
resolution pass to ensure the associated type exists and to setup the
associated types accordingly.
Addresses #1720
Signed-off-by: Philip Herron <herron.philip@googlemail.com>
gcc/rust/ChangeLog:
* resolve/rust-ast-resolve-type.cc (ResolveGenericArgs::go):
1707: Fix frust very long typo r=CohenArthur a=CohenArthur
Missing space character
1717: format: Fix git whitespace errors r=CohenArthur a=CohenArthur
Addresses #1680Fixes#1680
Probably does not need a changelog since I assume this commit will just be dropped when we merge
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
1711: unsafe: check use of `target_feature` attribute r=CohenArthur a=snprajwal
The `target_feature` attribute is for conditional compilation and may or may not compile on all platforms. Using it requires an unsafe function or block.
Addresses #1411
Co-authored-by: Prajwal S N <prajwalnadig21@gmail.com>
1716: rust: add bound parsing in parse_generic_arg. r=philberty a=TuringKi
This patch adds parsing for generic parameters like: <F: Foo<Bar: Foo>>. In current version, this pattern leads to endless loop.
Co-authored-by: mxlol233 <mxlol233@outlook.com>
Use StackedContext instead. Fix error string
Signed-off-by: Dave Evans <dave@dmetwo.org>
(Squashed commits) Check for mutable references in const functions using StackedContext
Signed-off-by: Dave Evans <dave@dmetwo.org>
The `target_feature` attribute is for conditional compilation and may or
may not compile on all platforms. Using it requires an unsafe function
or block.
Signed-off-by: Prajwal S N <prajwalnadig21@gmail.com>
1704: rust: fix link serialization [PR108113] r=CohenArthur a=dkm
The Make-lang.in was missing the link serialization support.
PR rust/108113
gcc/rust
* Make-lang.in (rust.serial): New variable.
(rust1$(exeext)): Depend on $(rust.prev). Call LINK_PROGRESS.
Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
Co-authored-by: Marc Poulhiès <dkm@kataplop.net>
The Make-lang.in was missing the link serialization support.
PR rust/108113
gcc/rust
* Make-lang.in (rust.serial): New variable.
(rust1$(exeext)): Depend on $(rust.prev). Call LINK_PROGRESS.
Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
1703: Backport "c++: Quash -Wdangling-reference for member operator* [PR107488]" r=tschwinge a=tschwinge
As had also been reported in <https://gcc.gnu.org/PR107633> "Bootstrap failure due to -Werror=unused-parameter and -Werror=dangling-reference", GCC `--enable-bootstrap` build is currently broken:
[...]/gcc/rust/backend/rust-compile-expr.cc: In member function ‘tree_node* Rust::Compile::CompileExpr::resolve_method_address(Rust::TyTy::FnType*, Rust::HirId, Rust::TyTy::BaseType*, Rust::HIR::PathIdentSegment&, Rust::Analysis::NodeMapping, Location)’:
[...]/gcc/rust/backend/rust-compile-expr.cc:2019:13: error: possibly dangling reference to a temporary [-Werror=dangling-reference]
2019 | auto &candidate = *candidates.begin ();
| ^~~~~~~~~
[...]/gcc/rust/backend/rust-compile-expr.cc:2019:44: note: the temporary was destroyed at the end of the full expression ‘candidates.std::set<Rust::Resolver::PathProbeCandidate>::begin().std::_Rb_tree_const_iterator<Rust::Resolver::PathProbeCandidate>::operator*()’
2019 | auto &candidate = *candidates.begin ();
| ^
[...]/gcc/rust/backend/rust-compile-expr.cc: In member function ‘tree_node* Rust::Compile::CompileExpr::generate_closure_fntype(Rust::HIR::ClosureExpr&, const Rust::TyTy::ClosureType&, tree, Rust::TyTy::FnType**)’:
[...]/gcc/rust/backend/rust-compile-expr.cc:3034:35: error: possibly dangling reference to a temporary [-Werror=dangling-reference]
3034 | const TyTy::TypeBoundPredicate &predicate
| ^~~~~~~~~
[...]/gcc/rust/backend/rust-compile-expr.cc:3035:52: note: the temporary was destroyed at the end of the full expression ‘(&(& closure_tyty)->Rust::TyTy::ClosureType::<anonymous>.Rust::TyTy::BaseType::<anonymous>.Rust::TyTy::TypeBoundsMappings::get_specified_bounds())->std::vector<Rust::TyTy::TypeBoundPredicate>::begin().__gnu_cxx::__normal_iterator<const Rust::TyTy::TypeBoundPredicate*, std::vector<Rust::TyTy::TypeBoundPredicate> >::operator*()’
3035 | = *closure_tyty.get_specified_bounds ().begin ();
| ^
[...]/gcc/rust/typecheck/rust-hir-type-check-path.cc: In member function ‘void Rust::Resolver::TypeCheckExpr::resolve_segments(Rust::NodeId, std::vector<Rust::HIR::PathExprSegment>&, size_t, Rust::TyTy::BaseType*, const Rust::Analysis::NodeMapping&, Location)’:
[...]/gcc/rust/typecheck/rust-hir-type-check-path.cc:340:13: error: possibly dangling reference to a temporary [-Werror=dangling-reference]
340 | auto &candidate = *candidates.begin ();
| ^~~~~~~~~
[...]/gcc/rust/typecheck/rust-hir-type-check-path.cc:340:44: note: the temporary was destroyed at the end of the full expression ‘candidates.std::set<Rust::Resolver::PathProbeCandidate>::begin().std::_Rb_tree_const_iterator<Rust::Resolver::PathProbeCandidate>::operator*()’
340 | auto &candidate = *candidates.begin ();
| ^
[...]/gcc/rust/typecheck/rust-hir-type-check-type.cc: In member function ‘Rust::TyTy::BaseType* Rust::Resolver::TypeCheckType::resolve_segments(Rust::NodeId, Rust::HirId, std::vector<std::unique_ptr<Rust::HIR::TypePathSegment> >&, size_t, Rust::TyTy::BaseType*, const Rust::Analysis::NodeMapping&, Location)’:
[...]/gcc/rust/typecheck/rust-hir-type-check-type.cc:465:13: error: possibly dangling reference to a temporary [-Werror=dangling-reference]
465 | auto &candidate = *candidates.begin ();
| ^~~~~~~~~
[...]/gcc/rust/typecheck/rust-hir-type-check-type.cc:465:44: note: the temporary was destroyed at the end of the full expression ‘candidates.std::set<Rust::Resolver::PathProbeCandidate>::begin().std::_Rb_tree_const_iterator<Rust::Resolver::PathProbeCandidate>::operator*()’
465 | auto &candidate = *candidates.begin ();
| ^
I understand this code has been changed in the GCC/Rust upstream submission; but in order to make progress with #1700, I'd like to first individually backport "c++: Quash -Wdangling-reference for member operator* [PR107488]", to resolve this issue here.
Co-authored-by: Marek Polacek <polacek@redhat.com>
-Wdangling-reference complains here:
std::vector<int> v = ...;
std::vector<int>::const_iterator it = v.begin();
while (it != v.end()) {
const int &r = *it++; // warning
}
because it sees a call to
__gnu_cxx::__normal_iterator<const int*, std::vector<int> >::operator*
which returns a reference and its argument is a TARGET_EXPR representing
the result of
__gnu_cxx::__normal_iterator<const int*, std::vector<int> >::operator++
But 'r' above refers to one of the int elements of the vector 'v', not
to a temporary object. Therefore the warning is a false positive.
I suppose code like the above is relatively common (the warning broke
cppunit-1.15.1 and a few other projects), so presumably it makes sense
to suppress the warning when it comes to member operator*. In this case
it's defined as
reference
operator*() const _GLIBCXX_NOEXCEPT
{ return *_M_current; }
and I'm guessing a lot of member operator* are like that, at least when
it comes to iterators. I've looked at _Fwd_list_iterator,
_Fwd_list_const_iterator, __shared_ptr_access, _Deque_iterator,
istream_iterator, etc, and they're all like that, so adding #pragmas
would be quite tedious. :/
PR c++/107488
gcc/cp/ChangeLog:
* call.cc (do_warn_dangling_reference): Quash -Wdangling-reference
for member operator*.
gcc/testsuite/ChangeLog:
* g++.dg/warn/Wdangling-reference5.C: New test.
(cherry picked from commit 32a06ce38a)
1701: Standardize warning flags r=tschwinge a=tschwinge
Bring in #1670, revert #1623 and parts of #1585.
Co-authored-by: Thomas Schwinge <thomas@codesourcery.com>
As discussed in
<https://inbox.sourceware.org/gcc-patches/871qpjtmd8.fsf@euler.schwinge.homeip.net>:
> '-Werror=overloaded-virtual' is implied as by default, we have
> '-Woverloaded-virtual' and '-Werror' [for '--enable-bootstrap' builds].
> ([...])
> (Maybe that isn't active for '--disable-bootstrap' builds, but that's
> "OK".)
For '--disable-bootstrap' builds, we still have '-Woverloaded-virtual', and any
new such diagnostics will be caught by the #1026 "check for new warnings"
machinery, so effectively that does implement '-Werror', too.
> '-Wno-unused-parameter' [did] move into
> 'rust-warn'
This reverts #1585 commit a32ef7aa18.
1678: Cleanup unused parameters r=CohenArthur a=philberty
This starts removing some of the unused parameters within the codebase
1682: const evaluator: Simplify get_nth_callarg r=CohenArthur a=CohenArthur
1687: Repair 'gcc/rust/lang.opt' comment r=CohenArthur a=tschwinge
... lost in #1527 commit 138a626012
"rust: Add -frust-compile-until option".
Co-authored-by: Philip Herron <herron.philip@googlemail.com>
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
Co-authored-by: Thomas Schwinge <thomas@codesourcery.com>
We only used one path of the C++ folder's get_nth_callarg function:
CALL_EXPR_ARG. Replace all calls to get_nth_callarg by macro calls to
CALL_EXPR_ARG
1540: Implement `-frust-incomplete-and-experimental-compiler-do-not-use` flag r=dkm a=CohenArthur
Remember to change your `./configure` line :)
This is obviously up for discussion and I would be happy to get some more input.
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
Co-authored-by: Thomas Schwinge <thomas@codesourcery.com>
1688: ci: Lock Ubuntu version to 20.04 r=CohenArthur a=CohenArthur
This locks all of our CI images to Ubuntu-20.04.
This should be upgraded eventually to 22.04, in time. I'll open up an issue to accompany it.
All of yesterday's PRs will need to be rebased on master once this is merged
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
1632: Fix mac-os regression in apply generic arguments to method calls r=philberty a=philberty
When applying generic arguments to method calls such as:
```receiver.method_name<i32, bool>()```
This ended up wrongly using the default constructor with an empty generic arguments which seems
like a possible bug in the new version of clang. This explicitly sets up all relevant copy constructors
for HIR::PathExprSegment and removes the defaults.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
This adds missing copy constructors to HIR::PathExprSegment which were
wrongly defaulting to empty vectors when apply specified generic arguments
to method calls.
1611: Initial state capture for closures r=philberty a=philberty
This patch set adds the initial support closure captures, move semantics are not
handled here. We track what variables are being captured by a closure during
name resolution so that when a VAR_DECL is resolved, we check if we are inside
a closure context node_id which is the same id as its associated rib id. So when
we resolve a name that resides in an outermost rib we can add this to set of
node-id's that are captured by this closure.
There is a gap here for the case where we need to check if it is inside a nested
function and that function contains closures which could wrongly capture variables
in the enclosing function. This will also be a problem for nested functions in general.
Fixes#195
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
When we have a closure expression that captures a parent function's
variable we must setup the closure data to contain this. Ignoring
moveability and mutability requires for now, this patch creates the closure
structure with fields for each of the captured variables. When it comes to
compilation of the closure expression in order to support nested closures
we must setup a context of implicit mappings so that for all path
resolution we hit this implicit closure mappings lookups code before any
lookup_var_decl as this decl will not exist so the order here is important
during path resolution which is a similar problem to match expression
destructuring.
Fixes#195
When we have a closure block referencing variables in a parent function,
we must track what these are. We do this by having a context of closures
so if we have a variable reference and its declared in a rib whose node id
is less than the node id of the closure's node id we know it must be a
captured variable. We also need to iterate all possible closure contexts
as we might be in the case of a nested closure.
Addresses #195
1676: Fix regressions in 32 bit mode and gcc4.8 builds r=CohenArthur a=philberty
This reverts commit 9657c328d0.
This reverts commit fc59d13749.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
1630: Cleanup builtin handling r=CohenArthur a=CohenArthur
This PR adds proper GCC-like handling of builtins, which allows us to not re-define all the builtins we use and fight with declaring the types each time.
This is also safer and works better. Sadly, this has unearthed some problems in our handling of builtins, specifically the ones I've added recently (atomic ones and data prefetching). These are the two issues that remain for this PR to be in a nice state which does not cause regressions:
1. `atomic_{store, load}` (and maybe cmp_xchg) do not work on signed integers. I'm currenty working around this by simply using `u32`s instead of `i32`s for the tests, but that's not a valid solution. These intrinsics need to work on all integer types and I will thus need to add some conversions from `i*` to `u*` before calling the intrinsics. The upside is that with these cleanups we should now be able to handle `*size` types easily and cleanly for those intrinsics
2. `__builtin_prefetch()` requires the `locality` argument (third argument) to be a const value. While LLVM will let you build the function and maybe error out later down the line, GCC does not let you pass non compile time known values as locality arguments. Because we are trying to build the following intrinsic:
```rust
fn prefetch_read_data<T>(src: *const T, locality: i32) {
__builtin_prefetch(src, 1, locality);
}
```
we cannot know that the `locality` arg is a compile-time constant. There are two ways to go around this problem:
a. Try to constant fold the `locality` argument. If this works, it's a compile time constant and we can keep going
b. Somehow map a generic intrinsic directly to a GCC one and inserting a new argument. So instead of generating something like
```rust
fn prefetch_read_data<i32>(src: *const i32, locality: i32) {
__builtin_prefetch(src, 0, locality)
}
```
we'd swap the call to `prefetch_read_data::<i32>(src, locality)` with `__builtin_prefetch(src, 0, locality)` and enforce `locality` being a compile time constant.
Edited because dynamically dispatching a *compiler hint* does not make any sense at all.
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
This commit performs builtin initialization in a more "GCC-y" way, similarly to what the D frontend is doing. This way, we no longer have to worry about invalid attributes or types when initializing them by hand.
1636: Add location to AST::Visibility r=CohenArthur a=dme2
Hi. I've added location to AST::Visibility, but it's possible I may have missed some steps here.
Fixes#1183.
Co-authored-by: Dave <dme2223@gmail.com>
1649: dwarf2out.c: Don't emit DW_LANG_Rust_old r=dkm a=dkm
DW_LANG_Rust_old is a non-standard DWARF language code used by old rustc compilers before DWARF5 (released in 2017). Just always emit DW_LANG_Rust unless producing strict DWARF for versions before 5. And in that old strict DWARF case just emit DW_LANG_C instead of a non-standard language code.
Co-authored-by: Mark Wielaard <mark@klomp.org>
1635: rust: Remove unused variables and fix dangling references r=CohenArthur a=CohenArthur
This should make the bootstrap build green again.
This commit contains some aggressive refactoring which either removes unused arguments altogether or removes the argument name in some cases where it might get used later on or cannot change due to implementing a virtual method or something like that.
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
1631: Ast dump where clause r=CohenArthur a=jdupak
Adds dump of the where clause and recursively needed nodes.
Adds visitor compatibility layer for general references except for unique pointers - needed for lifetimes. The enable is necessary to coexist with the unique_ptr overload.
Depends on #1624 and will be rebased when it is merged.
Co-authored-by: Jakub Dupak <dev@jakubdupak.com>
1628: typecheck: Fix overzealous `delete` call r=CohenArthur a=CohenArthur
I'm hoping this fixes the MacOS problem
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
1624: Ast dump refactor r=CohenArthur a=jdupak
Unifies all methods to overloads of the visit method and adds new helpers for common patterns (join by separator, visit as lines...)
Co-authored-by: Jakub Dupak <dev@jakubdupak.com>
1623: ci: Use same CXXFLAGS in bootstrap workflow r=CohenArthur a=CohenArthur
This should fix the CI job for bootstrapping
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
DW_LANG_Rust_old is a non-standard DWARF language code used by old
rustc compilers before DWARF5 (released in 2017). Just always emit
DW_LANG_Rust unless producing strict DWARF for versions before 5.
And in that old strict DWARF case just emit DW_LANG_C instead of a
non-standard language code.
This commit also comments out the definition of the generic atomic_store
builtins, with an explanation as to why
Co-authored-by: Marc Poulhies <dkm@kataplop.net>
1616: Apply 1559 master (remove system includes) r=CohenArthur a=CohenArthur
Fixes#1571
1617: Apply #1605 on master (fix lang spec) r=CohenArthur a=CohenArthur
Co-authored-by: ibuclaw <ibuclaw@gdcproject.org>
Let's still do this while we haven't resolved#1540 :)
Closes#1609
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
1619: parser: Fix ICE in closure parsing r=CohenArthur a=CohenArthur
`pattern` is a `unique_ptr`, which should be set to NULL once `std::move`d, hence causing the ICE as we were dereferencing a NULL pointer to get its location.
Addresses #1612
This should also help bring the MacOS build back to green
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
`pattern` is a `unique_ptr`, which should be set to NULL once
`std::move`d, hence causing the ICE as we were dereferencing a NULL
pointer to get its location.
1615: intrinsics: Add early implementation for atomic_store_{seqcst, relaxed, release} r=CohenArthur a=CohenArthur
Needs #1614 so ignore the first commit
This commit adds support for three `atomic_store_*` intrinsics declared
in the core library. The mapping is as follows:
- atomic_store_seqcst(dst, val) -> __atomic_store_n(dst, val,
__ATOMIC_SEQ_CST)
- atomic_store_relaxed(dst, val) -> __atomic_store_n(dst, val,
__ATOMIC_RELAXED)
- atomic_store_release(dst, val) -> __atomic_store_n(dst, val,
__ATOMIC_RELEASE)
The one remaining question is whether `atomic_store_unordered` can be
abstracted as an atomic store with the __ATOMIC_RELAXED ordering.
This commit also performs the overloading "by hand": Replacing
`atomic_store_release<i32>` with `__atomic_store_4` as I cannot get the
generic version to work. This will be done in future improvements.
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
1585: Apply #1556 on master r=CohenArthur a=CohenArthur
We should probably wonder about our usage of `-Wno-unused-parameter` :)
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
This commit adds support for three `atomic_store_*` intrinsics declared
in the core library. The mapping is as follows:
- atomic_store_seqcst(dst, val) -> __atomic_store_n(dst, val,
__ATOMIC_SEQ_CST)
- atomic_store_release(dst, val) -> __atomic_store_n(dst, val,
__ATOMIC_RELEASE)
- atomic_store_relaxed(dst, val) -> __atomic_store_n(dst, val,
__ATOMIC_RELAXED)
- atomic_store_unordered(dst, val) -> __atomic_store_n(dst, val,
__ATOMIC_RELAXED)
This commit also performs the overloading "by hand": Replacing
`atomic_store_release<i32>` with `__atomic_store_4` as I cannot get the
generic version to work. This will be done in future improvements.
Because of this, size type atomics are not handled and result in a call
to `rust_sorry_at`.
Co-authored-by: bjorn3 <bjorn3@github.com>
Co-authored-by: dafaust <dafaust@github.com>
1614: intrinsics: Add rust_sorry wrapper for unimplemented intrinsics r=CohenArthur a=CohenArthur
This allows us to define intrinsics without implementing their body. This will be useful for atomic intrinsics for example, as there are a lot of them and we should work on implementing them one by one properly and slowly
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
1613: builtins: Rename all bang macro handlers r=CohenArthur a=CohenArthur
This renames all builtin macro functions to `<macro>_handler`. This helps avoiding the `ifdef/undef` dance we performed for MacOS in order to compile the `assert` method
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
This allows us to define intrinsics without implementing their body.
This will be useful for atomic intrinsics for example, as there are a
lot of them and we should work on implementing them one by one properly
and slowly
This renames all builtin macro functions to `<macro>_handler`. This
helps avoiding the `ifdef/undef` dance we performed for MacOS in order
to compile the `assert` method
1608: Initial support for closures r=philberty a=philberty
This patch series introduces initial support for closures. Rust's implementation
of closures is actually pretty clever, the function signatures for closures is driven
by the specific FnTrait that the closure implements, this means a CallExpr to a closure
becomes a method-call expr with the receiver type being the closure itself using the
normal autoderef mechanism to do method selection for an implicit impl block.
See 7807a694c2/library/core/src/ops/function.rs (L54-L71)
The other implicit part of this is that arguments being passed to a closure _must_
be passed as a tuple. The down side of allowing libcore to specify the signatures
of the closure functions is that we are limited in how we pass arguments, but
using a tuple and then using similar machinery from the match-expr to restructure
the parameter access to become the tuple accessors makes it look seamless. For
example:
```rust
let closure_annotated = |i: i32| -> i32 { i + 123 };
let i = 1;
closure_annotated(i);
```
Wil generate a function and call-expr such as:
```c
i32 test::main::{{closure}} (struct {{closure}} $closure, struct (i32) args)
{
_1 = args.__0; // this is 'i'
return _1 + 123;
}
__attribute__((cdecl))
i32 test::main ()
{
struct
{
i32 __0;
} D.137;
i32 D.140;
const i32 a;
const struct{{closure}} closure_annotated;
const i32 i;
try
{
a = 1;
i = 1;
D.137.__0 = i;
_1 = test::main::{{closure}} (closure_annotated, D.137);
<...>
}
finally
{
closure_annotated = {CLOBBER(eol)};
}
}
```
Note this patch series does not implement the argument capture yet but this patch set is
good start to the implementation so far.
Addresses #195
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
1607: Improve AST Fragment class r=CohenArthur a=CohenArthur
This changes the APIs around creating AST fragments and refactors the class into its own header and source file, hopefully making it easier to use. This will also help creating "unexpanded" AST fragments for proper builtin macro expansion with the new fixed-point algorithm introduced by #1606
`@liushuyu` pinging you since you've worked extensively with the macro system. Would love your review!
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
Closures's need to generate their specific function and setup their
argument passing based on the signiture specified in libcore. We can get
this information based on the specified bound on the closure.
Addresses #195
This adds the type checking for a HIR::ClosureExpr which specifies a
TyTy::ClosureType whih inherits the FnOnce trait by default. The
specialisation of the trait bound needs to be determined by the the
mutability and argument capture and moveablity rules.
The CallExpr is amended here so that we support CallExpr's for all
receivers that implement any of the FnTraits. This means closures and
generics that have the relevant type bound of FnTraits we get the same path
of type checking.
Addresses #195
We used a visitor interface to handle type checking argument passing on
method call expressions. This was completely unnessecary as all method
calls should _always_ be to TyTy::FnType's. The benifit here is that we
need to reuse this interface to handle method resolution type checking
for FnTrait calls as closure calls dont have an HIR::MethodExpr so we
need a more abstract interface so that we can specify the types directly
with relevant location info.
This is the first pass at name resolution, it simply creates a new rib for
the closure. We eventually need more checks here to enforce what things
can be included within the closure.
In the AST we have ClosureExprInner and ClosureExprInnerTyped the first
is the closure expression of the form:
let closure_inferred = |i| i + 1;
The second is of the form:
let closure_annotated = |i: i32| -> i32 { i + 1 };
Both of these can be seguared into a single HIR::ClosureExpr with an
optional return type and parameter types.
Addresses #195
1602: Add check for recursive trait cycles r=philberty a=philberty
This adds a new RAII style TraitQueryGuard so that we can manage the query lifetime when resolving a trait. This adds in a DefId into a set when we begin to resolve and then finally removes it when completed. This allows us to add in a check at the start if this DefId is already within the set which means this is a trait cycle.
Fixes#1589
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
This adds a new RAII style TraitQueryGuard so that we can manage the query
lifetime when resolving a trait. This adds in a DefId into a set when we
begin to resolve and then finally removes it when completed. This allows
us to add in a check at the start if this DefId is already within the set
which means this is a trait cycle.
Fixes#1589
1597: ast: Module: unloaded module and inner attributes r=CohenArthur a=jdupak
Adds support for unloaded modules and dumps also inner attributes.
Resolves issue found in #1548.
Co-authored-by: Jakub Dupak <dev@jakubdupak.com>
1594: Refactor TraitResolver to not require a visitor r=philberty a=philberty
We used a visitor to dispatch the HIR::Item so that we could cast it directly to an HIR::Trait and then check for nullptr if it failed. This patch changes this to simply use our new enum item_type_kind to switch so we can directly static_cast.
1595: Support outer attribute handling on trait items just like normal items r=philberty a=philberty
This patch adds a proxy class ItemWrapper to be a proxy allowing us to use the same code paths for attribute handling as we have with normal items. We need this so we can grab the fn trait associated type lang item's. Which are being missed currently.
Addresses #195
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
1590: AST: more dump improvements r=dafaust a=dafaust
This PR adds new AST dump visitors for several nodes, and cleans up some minor formatting issues in blocks without tail expressions and if expressions.
Co-authored-by: David Faust <david.faust@oracle.com>
This patch adds a proxy class ItemWrapper to be a proxy allowing us to use
the same code paths for attribute handling as we have with normal items. We
need this so we can grab the fn trait associated type lang item's. Which
are being missed currently.
Addresses #195
1580: Add early name resolver r=CohenArthur a=CohenArthur
This addresses our issue with name resolution (#1576) not acting on macros early enough but does not fix it yet.
This name resolver performs the same macro name resolution as what was previously done by the AttrVisitor visitor and macro expander.
It also resolves macro expressions in builtin-macros properly, as well as expanded AST nodes when necessary.
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
We used a visitor to dispatch the HIR::Item so that we could cast it directly to an HIR::Trait and then check for nullptr if it failed. This
patch changes this to simply use our new enum item_type_kind to switch so
we can directly static_cast.
1587: Method resolution must support multiple candidates r=philberty a=philberty
This patch fixes bad method resolution in our operator_overload_9 case.
When we have a &mut reference to something and we deref we must resolve to
the mutable reference impl block. The interface we are using to resolve
methods is the can_eq interface which allows for permissive mutability
which means allowing for mutable reference being unified with an immutable
one. This meant we actual match against both the immutable and mutable
version leading to multiple candidate error.
Fixes#1588
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
1583: Support type resolution on super traits on dyn objects r=philberty a=philberty
When checking if specified bounds satisfy other bounds we must lookup the super traits. To finish the support for super traits we need to redo the computation of method addresses to support super traits.
Addresses #914
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
1584: Add missing lang item mappings r=philberty a=philberty
Adds the missing fn_once lang item and the missing rust-call abi option.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
This patch fixes bad method resolution in our operator_overload_9 case.
When we have a &mut reference to something and we deref we must resolve to
the mutable reference impl block. The interface we are using to resolve
methods is the can_eq interface which allows for permissive mutability
which means allowing for mutable reference being unified with an immutable
one. This meant we actual match against both the immutable and mutable
version leading to multiple candidate error.
The fix here adds a method resolution flag to the can_eq interface so that
we enforce mutability equality. The other hack is that we do not allow
can_eq of ParamTypes to generic Slices. I think there is some subtle thing
going on for that case. The Rustc method resolver actually filters the
impl blocks for reference types based looking up the relevant lang items
we need to do this as well but is a much larger refactor to our method
resolver which should be done seperately.
Fixes#1588
gcc/ChangeLog:
* config.gcc (*linux*): Set rust target_objs, and
target_has_targetrustm,
* config/t-linux (linux-rust.o): New rule.
* config/linux-rust.cc: New file.
gcc/ChangeLog:
* config.gcc (i[34567]86-*-mingw* | x86_64-*-mingw*): Set
rust_target_objs and target_has_targetrustm.
* config/t-winnt (winnt-rust.o): New rule.
* config/winnt-rust.cc: New file.
gcc/ChangeLog:
* config.gcc (*-*-fuchsia): Set tmake_rule, rust_target_objs,
and target_has_targetrustm.
* config/fuchsia-rust.cc: New file.
* config/t-fuchsia: New file.
gcc/ChangeLog:
* config.gcc (*-*-vxworks*): Set rust_target_objs and
target_has_targetrustm.
* config/t-vxworks (vxworks-rust.o): New rule.
* config/vxworks-rust.cc: New file.
gcc/ChangeLog:
* config.gcc (*-*-dragonfly*): Set rust_target_objs and
target_has_targetrustm.
* config/t-dragonfly (dragonfly-rust.o): New rule.
* config/dragonfly-rust.cc: New file.
gcc/ChangeLog:
* config.gcc (*-*-solaris2*): Set rust_target_objs and
target_has_targetrustm.
* config/t-sol2 (sol2-rust.o): New rule.
* config/sol2-rust.cc: New file.
gcc/ChangeLog:
* config.gcc (*-*-openbsd*): Set rust_target_objs and
target_has_targetrustm.
* config/t-openbsd (openbsd-rust.o): New rule.
* config/openbsd-rust.cc: New file.
gcc/ChangeLog:
* config.gcc (*-*-netbsd*): Set rust_target_objs and
target_has_targetrustm.
* config/t-netbsd (netbsd-rust.o): New rule.
* config/netbsd-rust.cc: New file.
gcc/ChangeLog:
* config.gcc (*-*-freebsd*): Set rust_target_objs and
target_has_targetrustm.
* config/t-freebsd (freebsd-rust.o): New rule.
* config/freebsd-rust.cc: New file.
1570: Apply #1560 master r=CohenArthur a=CohenArthur
Same as #1560, but in a single more descriptive commit. I'll hold on doing the other fixes until you're okay with the process `@philberty`
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
When checking if specified bounds satisfy other bounds we must lookup the
super traits. To finish the support for super traits we need to redo the
computation of method addresses to support super traits.
Addresses #914
This name resolver performs the same macro name resolution as what was
previously done by the AttrVisitor visitor and macro expander.
It also resolves macro expressions in builtin-macros properly, as well
as expanded AST nodes when necessary.
1574: fix ICE on missing closing paren r=dkm a=dkm
Fix crash (segfault) on a missing closing parenthesis when parsing the expressions in a block. The returned `expr` was missing a check before being used.
Add corresponding test.
Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
Co-authored-by: Marc Poulhiès <dkm@kataplop.net>
Fix crash (segfault) on a missing closing parenthesis when parsing the
expressions in a block. The returned `expr` was missing a check before being
used.
Add corresponding test.
Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
1543: Reintroduce targetrustm hooks without the maze of macro definitions in target headers r=CohenArthur a=ibuclaw
- Adds skeleton support and documentation for targetrustm hooks.
- Re-adds previously reverted `TARGET_RUST_CPU_INFO` target hook.
- Re-adds the previously reverted `TARGET_RUST_OS_INFO` target hook.
- Implements `TARGET_RUST_CPU_INFO` hook for x86 (only a subset of the original i386-rust.cc was re-added)
- Implements `TARGET_RUST_OS_INFO` hook for darwin (covers both x86 and powerpc).
There's quite a bit to unpick from what was removed, but I hope this shows how firstly `rust-target.h` and `tm_rust.h` should be kept as empty as possible for the `default-rust.cc` source file that pulls in these headers; secondly all rust macros and declarations be put in rust-specific headers, then pulled into tm_rust.h as-needed. From every other `${target}-rust.cc` file, you can include as much as you like in order to pry out the information you need to get at.
I've verified this does work as expected with the `-frust-dump-target_options` switch, e.g with `-mavx2`
```
target_endian: "little"
target_pointer_width: "64"
target_feature: "fxsr"
target_feature: "popcnt"
target_feature: "avx2"
target_feature: "ssse3"
target_feature: "sse4.1"
target_feature: "sse3"
target_feature: "avx"
target_feature: "sse"
target_feature: "xsave"
target_feature: "sse4.2"
target_feature: "sse2"
target_feature: "mmx"
target_arch: "x86_64"
```
I've also built a few darwin cross compilers with the following results on i686-darwin
```
target_pointer_width: "32"
target_env: ""
target_vendor: "apple"
target_endian: "little"
target_os: "macos"
target_family: "unix"
target_feature: "sse3"
target_feature: "sse"
target_feature: "sse2"
target_feature: "mmx"
target_arch: "x86"
```
and on powerpc64-darwin
```
target_pointer_width: "64"
target_env: ""
target_vendor: "apple"
target_endian: "big"
target_os: "macos"
target_family: "unix"
```
Co-authored-by: Iain Buclaw <ibuclaw@gdcproject.org>
1565: Implement data prefetch intrinsics r=CohenArthur a=CohenArthur
Addresses #658
Needs #1564 so only review the last commit
This PR implements the two intrinsics related to data prefetching. I have to say, since these are hints for the backend, I am unsure if the current implementation is right. I believe it should be.
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
pipeline: Add default warning initialisation
Option initialisations in lang.opt files are applied globally, so the
test suites of other frontend would fail when the rust language was
enabled.
This should be reversed once @tschwinge `LangInit` option is merged
1562: Support looking up super trait items during path resolution r=philberty a=philberty
When we lookup names in paths such as Foo::bar, foo is a type we resolve
and then we lookup 'bar' based on what type Foo is which includes probing
relevant bounds of this type. We currently return a vector of possible
candidates and this patch changes it so that we return a vector of unique
items based on DefId. Ideally we should use move to a std::set for this.
The final patch actually updates the trait reference lookup functions to revert
to looking up relevant super traits when required.
Fixes#1555
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
When we lookup names in paths such as Foo::bar, foo is a type we resolve
and then we lookup 'bar' based on what type Foo is which includes probing
relevant bounds of this type. We currently return a vector of possible
candidates and this patch changes it so that we return a set of unique
items based on DefId.
Addresses #1555
gcc/ChangeLog:
* config.gcc (*-*-darwin*): Set rust_target_objs and
target_has_targetrustm.
* config/t-darwin (darwin-rust.o): New rule.
* config/darwin-rust.cc: New file.
There are still quite a lot of the previously reverted i386-rust.cc
missing, so it's only a partial reimplementation.
gcc/ChangeLog:
* config/i386/t-i386 (i386-rust.o): New rule.
* config/i386/i386-rust.cc: New file.
* config/i386/i386-rust.h: New file.
gcc/ChangeLog:
* doc/tm.texi: Regenerate.
* doc/tm.texi.in: Add @node for Rust language and ABI, and document
TARGET_RUST_CPU_INFO.
gcc/rust/ChangeLog:
* rust/rust-lang.cc (rust_add_target_info): Remove sorry.
* rust/rust-session-manager.cc: Replace include of target.h with
include of tm.h and rust-target.h.
(Session::init): Call targetrustm.rust_cpu_info.
* rust/rust-target.def (rust_cpu_info): New hook.
* rust/rust-target.h (rust_add_target_info): Declare.
1551: Add catch for recusive type queries r=philberty a=philberty
When we have a type query where by generic substitution occurs we can hit the case where we need to Probe the bounds of the substited item to determine whether the the bounds are compatible this can cause us to end up querying the same type recursively.
Fixes#1550
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
When we have a type query where by generic substitution occurs we can hit
the case where we need to Probe the bounds of the substited item to
determine whether the the bounds are compatible this can cause us to
end up querying the same type recursively.
Fixes#1550
1545: Refactor TypeResolution to be a simple query based system r=philberty a=philberty
This patch refactors the type resolution system to introduce a new
interface
bool query_type (HirId, TyTy::BaseType** result)
This is needed in order to properly support forward declared items. Our
name resolution system has two parts:
1. Toplevel scan
2. Item resolution
The toplevel scan gathers all the nesseacry 'names' into their respective
namespace by doing a full toplevel scan and generate canonical paths for
each item. The second pass is responsible for drilling down into each
structure or function to resolve each field or variable etc. This means
our name resolution system supports forward decalred items but our type
resolution system did not.
This patch removes the toplevel scan from our type resolution pass which
is not able to handle all cases such as a function with return type and
the type is decalred after the fact or a type alias to a type declared
after the fact. The name resolution mappings are resolved so when errors
occured here we got errors such as unable to lookup HirId 1234, which meant
yes we have 'resolved' this reference to this HirId but we are unable to
find any type information for it. This means we needed a new way to figure
out the type in a query based way.
This is where the new query_type inferface comes in so when we have an
HirId we want to resolve the mappings class allows us to figure out what
item this is such as:
1. HIR::Item (normal HIR::Function, Struct, TypeAlias, ...)
2. HIR::ImplItem (function, constant, ... within an impl-block)
3. HIR::ImplBlock (Self type on an impl-block)
4. HIR::ExternalItem (extern-block item)
The mappings class allows us to simply lookup these HIR nodes and then
call the relevant resolver class to compute the type. This patch does not
add support for self-referencial types but is the starting point to be able to support such types.
Fixes#1455Fixes#1006Fixes#1073Fixes#1272
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
When resolving local enum's within a Block the name resolution info is
not at the top of the stack so this patch introduces a new mappings class
for miscellaneous name resolutions which can be used during path analaysis.
Fixes#1272
This patch refactors the type resolution system to introduce a new
interface
bool query_type (HirId, TyTy::BaseType** result)
This is needed in order to properly support forward declared items. Our
name resolution system has two parts:
1. Toplevel scan
2. Item resolution
The toplevel scan gathers all the nesseacry 'names' into their respective
namespace by doing a full toplevel scan and generate canonical paths for
each item. The second pass is responsible for drilling down into each
structure or function to resolve each field or variable etc. This means
our name resolution system supports forward decalred items but our type
resolution system did not.
This patch removes the toplevel scan from our type resolution pass which
is not able to handle all cases such as a function with return type and
the type is decalred after the fact or a type alias to a type declared
after the fact. The name resolution mappings are resolved so when errors
occured here we got errors such as unable to lookup HirId 1234, which meant
yes we have 'resolved' this reference to this HirId but we are unable to
find any type information for it. This means we needed a new way to figure
out the type in a query based way.
This is where the new query_type inferface comes in so when we have an
HirId we want to resolve the mappings class allows us to figure out what
item this is such as:
1. HIR::Item (normal HIR::Function, Struct, TypeAlias, ...)
2. HIR::ImplItem (function, constant, ... within an impl-block)
3. HIR::ImplBlock (Self type on an impl-block)
4. HIR::ExternalItem (extern-block item)
The mappings class allows us to simply lookup these HIR nodes and then
call the relevant resolver class to compute the type. This patch does not
add support for self-referencial types but is the starting point to be able to support such types.
Fixes#1455
Deuplicate function elimination can fail when we compile helpers during
higher ranked trait bound monomorphization. This because the
TyTy::BaseType info can be lost/reset during the compilation process. This
adds a second mechanism to match based on the manged names which is a bit
more reliable. This patch is required since the query based refactor of
the type system so this issue was likely hidden to to using duplicated type
info for higher ranked trait bounds.
1527: rust: Add -frust-compile-until option r=CohenArthur a=CohenArthur
This option helps ensure that we do not introduce regressions on various
parts of the compilation pipeline. For example, a testcase (or testsuite
from the `testing` project) might pass attribute checking, expansion and
lowering, but fail during typechecking. Should a change suddenly make
that testcase fail expansion, we would not be able to notice it. By
generating tests that run up until expansion, typechecking, compilation
and so forth we ensure that no regressions are added accidentally to
already failing tests/testsuites.
1529: const generics: Make sure const generic types are visited properly in all contexts r=CohenArthur a=CohenArthur
Closes#1360
1530: const generics: Forbid default values in Functions, Traits and Impls r=CohenArthur a=CohenArthur
Fixes#1310
1534: module lowering: Do not append null pointers as items r=CohenArthur a=CohenArthur
Some module items do not need to get lowered to HIR such as `macro_rules!` definitions. Hence, module lowering should act the same as crate lowering: Only emplace back the lowered item if it is a valid pointer
Fixes#1533
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
This option helps ensure that we do not introduce regressions on various
parts of the compilation pipeline. For example, a testcase (or testsuite
from the `testing` project) might pass attribute checking, expansion and
lowering, but fail during typechecking. Should a change suddenly make
that testcase fail expansion, we would not be able to notice it. By
generating tests that run up until expansion, typechecking, compilation
and so forth we ensure that no regressions are added accidentally to
already failing tests/testsuites.
1532: attributes: Add #[macro_use] as builtin r=CohenArthur a=CohenArthur
Fixes#1531
I think the checking for builtin attributes should definitely be moved to the `AttributeChecker` visitor. It's also a bit messy at the moment considering it isn't in effect on *everything*, simply some nodes such as `Module`s. Thoughts?
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
Statics like constants need to have a singular value they are not functions
to be lazy evaluated. So to evaluate a block expr we can just reuse our
const code to resolve this to a singular value.
Some module items do not need to get lowered to HIR such as `macro_rules!` definitions. Hence, module lowering should act the same as crate lowering: Only emplace back the lowered item if it is a valid pointer
1528: add testcase with struct to test component_ref and constructor codes in eval_constant_expression() r=philberty a=abbasfaisal
Co-authored-by: Faisal Abbas <90.abbasfaisal@gmail.com>
1526: backend: correctly formulate the exit condition r=philberty a=liushuyu
- backend: correctly formulate the exit condition. Previously the exit condition was treated the same as the loop condition (which is the inverse condition of the exit condition). Now, this is corrected.
Should fix#1523
Co-authored-by: liushuyu <liushuyu011@gmail.com>
... previously the exit condition was treated the same as the loop
condition (which is the inverse condition of the exit condition). Now
this is corrected.
1522: Add testcases to test folding r=philberty a=abbasfaisal
The fix is a bit of guess so do have a careful look :)
Co-authored-by: Faisal Abbas <90.abbasfaisal@gmail.com>
1505: Create canonical process of compiling constant items r=philberty a=philberty
In order to compile a block expression constant, the simplest way for us
was to reuse what code we have and to generate an artifical function which
does not get added to the translation unit. The constant then becomes
a CALL_EXPR to this artifical function which we can pass to the constexpr
evaluator to resolve the result of this artifical 'CALL_EXPR'.
Before this patch we seperated the difference between block expressions
and non block expressions in constants. So for non block expressions we
simply compiled them as if it was a simple constant but this is not
guaranteed to be the case in rust, for example coercion sites can generate
temporaries during autoderef which we let the constant evaluator resolve
for us. This makes all constants handled in the same way to simplify the
logic here.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
In order to compile a block expression constant, the simplest way for us
was to reuse what code we have and to generate an artifical function which
does not get added to the translation unit. The constant then becomes
a CALL_EXPR to this artifical function which we can pass to the constexpr
evaluator to resolve the result of this artifical 'CALL_EXPR'.
Before this patch we seperated the difference between block expressions
and non block expressions in constants. So for non block expressions we
simply compiled them as if it was a simple constant but this is not
guaranteed to be the case in rust, for example coercion sites can generate
temporaries during autoderef which we let the constant evaluator resolve
for us. This makes all constants handled in the same way to simplify the
logic here.
We are not fully setting TYPE_CANONICAL yet but we don't need to be as
strict as the C++ front-end yet. param_use_canonical_types is a command
line option we are not using either.
1517: Refactor error handling on unify r=philberty a=philberty
This is the first pass on a refactor for error handling on unify sites. Eventually we
will be able to get rid of our can_eq interface but this is the first pass to abstract
unify's to use this interface.
Eventually, we will have unify and unify_and_commit. Unify will become our can_eq
interface but will require more helpers around inference variables.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
1408: Experiment: add optional error codes to diagnostics r=CohenArthur a=davidmalcolm
rustc has error codes to identify specific errors, with URLs documenting each error.
In GCC 13 I've extended GCC's diagnostic subsystem so that a diagnostic can be associated with zero or more `diagnostic_metadata::rule` instances, which have a textual description and a URL. I meant this for rules in coding standards and specifications, but it struck me that potentially gccrs could reuse the same error codes as rustc.
The following pull request implements an experimental form of this; I picked a single error at random: [E0054](https://doc.rust-lang.org/error-index.html#E0054).
With this patch, gccrs emits e.g.:
```
bad_as_bool_char.rs:8:19: error: invalid cast [u8] to [bool] [E0054]
8 | let nb = 0u8 as bool;
| ~ ^
```
where the trailing [E0054] is colorized, and, in a suitably capable terminal is a clickable URL to https://doc.rust-lang.org/error-index.html#E0054.
The error code is after the diagnostic message, whereas rustc puts it after the word "error". I could change that in gcc's diagnostic.cc, perhaps.
I'm not sure if this is a good idea (e.g. is it OK and maintainable to share error codes with rustc?), but thought it was worth sharing.
1503: Add overflow traps r=CohenArthur a=CohenArthur
Opening as a draft since the code is really ugly and some tests still fail. I am looking for feedback on the implementation and my approximative use of functions like `temporary_variable` which I feel I might be using the wrong way.
I'll open up an issue of what still needs to be done, namely:
- [x] Properly handle sub and mul operations
- [ ] Disable the check in `release` mode (`-frust-disable-overflow-checks`)
- [ ] Handle specific rust overflow attribute (needs checkup on the name)
I'll open up some PRs to clean up some parts of the backend as well.
1511: lint: Do not emit unused warnings for public items r=CohenArthur a=CohenArthur
This fixes the overzealous warnings on public items from the unused pass
Co-authored-by: David Malcolm <dmalcolm@redhat.com>
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
1514: Fix SEGV in transcribe_type when compiling libcore 1.29 r=CohenArthur a=CohenArthur
Needs #1513, Skip reviewing the first commit
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
1515: transcriber: Do not infinite loop if the current parsed node is an error r=CohenArthur a=CohenArthur
1516: parser: Parse RangeFullExpr without erroring out r=CohenArthur a=CohenArthur
Previously the parser would emit the errors despite later allowing the parsed expression to be null.
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
1513: macros: Handle matchers properly in repetitions r=CohenArthur a=CohenArthur
This fixes an issue encountered when trying to compile libcore 1.29
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
1510: rustc_attrs: Allow `rustc_inherit_overflow_checks` as a builtin attribute r=CohenArthur a=CohenArthur
We cannot yet handle this attribute, but we should not reject it either.
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
1512: Add missing language selection for rs6000 r=philberty a=philberty
This is an attempt to fix the ppc64le build issues.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
1507: Desugar double borrows into two HIR:BorrowExpr's r=philberty a=philberty
We simply hit a gcc_unreachable() on double borrows but it seems reasonable
to just desugar the AST into a borrow of a borrow to foo. Instead of a
borrow expression with a flag to be respected.
Fixes#1506
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
1499: Constant folding in gccrs: port over rest of the code from CP frontend r=philberty a=abbasfaisal
Co-authored-by: Faisal Abbas <90.abbasfaisal@gmail.com>
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
We simply hit a gcc_unreachable() on double borrows but it seems reasonable
to just desugar the AST into a borrow of a borrow to foo. Instead of a
borrow expression with a flag to be respected.
Fixes#1506
1473: Improve AST dump r=CohenArthur a=CohenArthur
Let's abuse C++ a little bit to make dumping and the chaining of dumping operations easier. If anyone has input feel free, this is definitely a roundabout way to go about it.
This also adds pretty printing of the expanded AST, which can be useful to debug macros or `cfg` invocations
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
- error in handling of NOP_EXPR which results in failure in make check-rust
- DECL not being marked constant inside finalize_intrinsic_block
Signed-off-by: Faisal Abbas <90.abbasfaisal@gmail.com>
Following cases have been added in this changeset:
- LOOP_EXPR
- WHILE_STMT
- FOR_STMT
These need following supporting functions which are also ported:
- eval_loop_expr
- returns
- breaks
- continues
- switches
- more cases into constexpr_expression.
- cxx_eval_condtional_expression.
Note that COND_EXPR and IF_STMT are defined in cp-tree.def
Also renames constexpr_expression to eval_constant_expression.
Signed-off-by: Faisal Abbas <90.abbasfaisal@gmail.com>
These intrinsics and builtin's need to be marked as const in order for the
const eval code to generate copy's to cache their results and folded
function bodies.
This signifys in the GCC generic that this is a constant function and
should be foldable in the constexpr evaluation. This also ports over the
correct eval_store_expression which updates the context tables.
CPP consteval seems pretty powerful but overall the algorithm is fairly
simple at least for simple types. When we encounter a CALL_EXPR we must
"bind" the arguments. So when we encourter a PARAM_DECL the associated
argument for this parameter is bound to this parameter in a map of
map<tree, tree> using their pointer as the key to value. So when folding
a function body every usage of the parameter decl is then updated in the
context with the apropriate value fomr the context. When we hit
assignment operations a similar context store occurs for VAR_DECLS.
While walking the tree We finally hit the RESULT_DECL with the folded
result. The complex pieces remaining are aggregate, record and union types
so that we have zero allocation required to find the result. We also need
to support walking conditionals and loop expressions which require porting
a few more functions and using the jump_target tree.
- cxx_bind_parameters_in_call
- addr_of_non_const_var
- adjust_temp_type
There is alot of cleanup we can do when we get more of this working but
for now its best to keep porting like this.
Following functions are ported in this changeset:
- decl_constant_var_p
- undeduced_auto_decl
- require_deduced_type
Signed-off-by: Faisal Abbas <90.abbasfaisal@gmail.com>
Following functions are ported in this changeset:
- find_heap_var_refs
- find_immediate_fndecl
- instantiation_dependent_expression_p
- cp_get_callee
- build_nop
- scalarish_type_p
- type_has_nontrivial_copy_init
- build_local_temp
- is_normal_capture_proxy
- reject_gcc_builtin
- is_bitfield_expr_with_lowered_type
- maybe_undo_parenthesized_ref
- fold_offsetof
- char_type_p
- resolve_nondeduced_context
- null_node_p
Following structs, classes and enums are ported in this changeset:
- c_tree_index
- warning_sentinel
- uid_sensitive_constexpr_evaluation_checker
- iloc_sentinel
- ptrmem_cst
This changeset puts c_global_trees and cp_global_trees outside Rust and Compile
namespaces because keeping them inside is causing build issues.
This is possibly because rust-tree.cc contains only Rust namespace while
rust-constexpr.cc is Rust+Compile namespace. This causes issues when trying to use
them inside both files.
Signed-off-by: Faisal Abbas <90.abbasfaisal@gmail.com>
Following functions are ported in this changeset:
- get_fileinfo
- cxx_make_type
- build_min_array_type
- identifier_p
Following structs are ported in this changeset:
- c_fileinfo
Signed-off-by: Faisal Abbas <90.abbasfaisal@gmail.com>
Following functions are ported in this changeset:
- var_in_constexpr_fn
- member_vec_linear_search
- member_vec_binary_search
- is_overloaded_fn
- ovl_make
- lookup_add
- ovl_first
- type_unknown_p
Following structs, classes and enums are ported in this changeset:
- tree_overload
- ovl_iterator
- tsubst_flags
- cp_identifier_kind
- tag_types
This changeset ports cp_global_trees structure which is used throughout the
cp constexpr.cc code. I am not sure what it's purpose is but it seems it is used
to add and manipulate tree information during the c++ compilation process.
It is possible this is not needed in the Rust code and may be taken out later.
Also, the initialization function isn't being called from anywhere yet, so
we will need to find a suitable point for it.
Signed-off-by: Faisal Abbas <90.abbasfaisal@gmail.com>
1497: Refactor our casts to follow the Rustc implemention r=philberty a=philberty
This gets rid of our old visitor system for cast type checking. Casts
depend on type coercions as they are meant to attempt a type coercion
before trying a simple cast. This explicitly defines the rules which should
be allowed for simple casts. In rustc they use match expressions to write
a list of casts which should not be allowed. We have likely missed some
rules of what should be allowed but this is at least the start of how
to implement this.
Fixes#1496
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
1500: Remove missed target hooks code r=philberty a=philberty
This was missed since the last PR #1471
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
This gets rid of our old visitor system for cast type checking. Casts
depend on type coercions as they are meant to attempt a type coercion
before trying a simple cast. This explicitly defines the rules which should
be allowed for simple casts. In rustc they use match expressions to write
a list of casts which should not be allowed. We have likely missed some
rules of what should be allowed but this is at least the start of how
to implement this.
Fixes#1496
1493: Fix ICE in dyn impl block r=philberty a=philberty
The issue here was that our name resolution assumed qualified path always
has an as clause. We also had missing visitors to generate the canonical path
for impl blocks using dynamic trait objects.
We should investigate implementing the fine-grained visitors for the AST
similar to the ones we have for HIR. This will solve the issue where we
have missing visitors.
Fixes#1249
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
Qualified paths can look like <dyn T>::bla with an associated impl block
for dynamic trait objects. If we implement similar fine grained visitors
that we use in the HIR this will help solve issues like this where we have
missing visitors.
Fixes#1249
1492: Redo coercion site code r=philberty a=philberty
This gets rid of the old visitor method and brings us much closer to the
Rustc rules which from the algo mentioned in the comment's do the checks
in a very specific order which we need to match.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
This gets rid of the old visitor method and brings us much closer to the
Rustc rules which from the algo mentioned in the comment's do the checks
in a very specific order which we need to match.
1491: typecheck: resolve tuple pattern elt against parent elt r=philberty a=dafaust
When doing type resolution for an element of a tuple pattern, check it
against the corresponding element of the parent, if the parent is also a
tuple.
Fixes: #1476
Co-authored-by: David Faust <david.faust@oracle.com>
1477: Refactor backend to use finegrained visitors r=philberty a=philberty
This also moves more code out of the headers to their associated impl files
to improve compilation times and code navigation.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
1471: Remove target hooks changes r=philberty a=philberty
This reverts the unnecessary changes we have made to GCC
so that merging from upstream should be simplified. This is
also making writing the patches for GCC simpler.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
Co-authored-by: Thomas Schwinge <thomas@codesourcery.com>
1459: intrinsics: Add copy_nonoverlapping<T> r=CohenArthur a=CohenArthur
intrinsics: Add copy_nonoverlapping<T>
This intrinsic is similar to C's memcpy (or in our case, GCC's
__builtin_memcpy) with the order of arguments swapped and knowledge
about the type of the operands. So we can desugar the following calls:
`copy_nonoverlapping::<T>(src, dst, count)`
can be converted to
`__builtin_memcpy(dst, src, count * size_of::<T>())`
~~Sadly, calling this intrinsic results in calls being optimized out for some reason. I'll open a separate issue to deal with that as I don't have the skills to resolve it.~~ fixed by not marking the function's declaration as `TREE_READONLY`
Fixes#1450
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
This intrinsic is similar to C's memcpy (or in our case, GCC's
__builtin_memcpy) with the order of arguments swapped and knowledge
about the type of the operands. So we can desugar the following calls:
`copy_nonoverlapping::<T>(src, dst, count)`
can be converted to
`__builtin_memcpy(dst, src, count * size_of::<T>())`
Finally, unlike most intrinsics, copy_nonoverlapping must be marked as impure
Co-authored-by: philbert <philip.herron@embecosm.com>
1465: intrinsics: Add wrapping_{add, sub, mul} r=CohenArthur a=CohenArthur
Since wrapping arithmetics are guaranteed in Rust, we turn on the -fwrapv and simply desugar wrapping_{add, sub, mul} to their non-checked inner operations. This is the only difference between a wrapping add and a regular addition: The regular addition will gain some checks for overflows, which are simply not used for the wrapping version.
Fixes#1449
`@bjorn3` if you want to have a look :)
1467: Desugar HIR::IdentifierExpr into HIR::PathInExpression r=philberty a=philberty
This completly removes the HIR::IdentifierExpr and unifies how we handle
generics in general. There was a hack from last year that did not infer
generic arguments on IdentifierExpr's which leads to a type inferencing
behvaiour mismatch which was becoming difficult to debug. This simplifies
everything.
The changes to the test case reflect making our code more compliant to
real rustc apart from compile/traits3.rs which will be fixed as part of the
refactoring effort going on in the type system.
Fixes#1456
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
1466: Dont return error_mark_node on bad CallExpr arguments r=philberty a=philberty
If we return error_mark_node on a bad expression argument we loss alot of
useful debug info from the error node within the -fdump-tree-original which
saves alot of debug printf.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
1468: Revert "Ensure we set TREE_SIDE_EFFECTS on call expressions" r=CohenArthur a=philberty
This reverts commit f891a13aa2. This fix
ensures the code is added to the block but still as the artifical function
is marked READONLY it ends up being optimized out anyway.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
This reverts commit f891a13aa2. This fix
ensures the code is added to the block but still as the artifical function
is marked READONLY it ends up being optimized out anyway.
This completly removes the HIR::IdentifierExpr and unifies how we handle
generics in general. There was a hack from last year that did not infer
generic arguments on IdentifierExpr's which leads to a type inferencing
behvaiour mismatch which was becoming difficult to debug. This simplifies
everything.
The changes to the test case reflect making our code more compliant to
real rustc apart from compile/traits3.rs which will be fixed as part of the
refactoring effort going on in the type system.
Fixes#1456
If we return error_mark_node on a bad expression argument we loss alot of
useful debug info from the error node within the -fdump-tree-original which
saves alot of debug printf.
1464: Remove unused include in HIR r=philberty a=philberty
This is a hang over from the AST bootstrap of the HIR tree's
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
1458: Refactor type resolution pass to use fine grained visitors r=philberty a=philberty
Thanks for `@dkm` work on fine-grained HIR visitors this patch takes advantage of this
and moves most implementation into CC files and takes advantage of fine-grained visitors
this will help with the maintainability of the code and it also makes it clear what classes do
and don't do.
It's part of an incremental refactor to get rid of the awkward top-level scan pass in the
type resolution pass. This will allow us to move towards a more query-based model
like the code generation pass so that we can support the forward declared items.
The problem is that we our name resolution pass supports forward declared items but our
type resolution pass does not. We know the HIR nodes when type paths or path expressions
resolve to but when it comes to actually resolve this we just fail when we reuse our mappings
class to look up the item.
1463: Remove unused backend wrapper r=philberty a=philberty
This removes the unused switch statement wrapper
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
Since wrapping arithmetics are guaranteed in Rust, we turn on the -fwrapv and simply desugar wrapping_{add, sub, mul} to their non-checked inner operations. This is the only difference between a wrapping add and a regular addition: The regular addition will gain some checks for overflows, which are simply not used for the wrapping version.
1462: Ensure we set TREE_SIDE_EFFECTS on call expressions r=philberty a=philberty
When we compiling call expressions the GCC helper has quite a simple
implementation to determine if there are SIDE_EFFECTS we have more
information in the front-end to determine this. This adds a check that
the call expression is deemed to have no side effects ensure we check this
against the fndecl used.
Fixes#1460
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
When we compiling call expressions the GCC helper has quite a simple
implementation to determine if there are SIDE_EFFECTS we have more
information in the front-end to determine this. This adds a check that
the call expression is deemed to have no side effects ensure we check this
against the fndecl used.
Fixes#1460
This is a huge refactor but no logic has been changed. Most implementation
has now been moved from the headers and into cc files now. This should
help alot with compilation times when working within the type system.
This is another incremental step to improve our coercion site logic as also
support forward declared items.
Addresses #1455
The reason we cannot type-resolve forward declared items is due to the
fact our type-resolver runs in a toplevel pass trying to type resolve as
best it can but when we hit structs for example which contain types that
are forward declared they need to be resolved in a query based manar. We
have all the missing pieces to do this now and this means we need to get
rid of this toplevel pass as the starting point.
Addresses #1455
1453: Add in -m32,-m64 configuration to make check-rust r=philberty a=philberty
This is to gate PR's which might break builds on 32bit systems.
Fixes#1439#871
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
1452: transmute: Fix behavior by always performing the raw copy r=CohenArthur a=CohenArthur
This desugars calls to transmute the following way:
`transmute::<T1, T2>(value)`
->
`*((T2 *) &value)`
This always ends up being optimized into a simple copy for small types
and a memcpy for larger types.
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
This desugars calls to transmute the following way:
`transmute::<T1, T2>(value)`
->
`*((T2 *) &value)`
This always ends up being optimized into a simple copy for small types
and a memcpy for larger types.
Co-authored-by: philberty <philip.herron@embecosm.com>
1454: intrinsics: Refactor compilation of intrinsics r=CohenArthur a=CohenArthur
This commit adds helpers around caching, compiling and using intrinsic
functions before extending them with instructions specific to the
intrinsic. We can refactor them further, but this is already a bit
easier to deal with when writing new intrinsics
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
Change the CI requirements to have seperate jobs for 64 and 32 bit testing.
It also runs both combinations on the gcc4.8 build job. Bors only requires
the normal build check 64bit job to pass to minimize impact.
This commit adds helpers around caching, compiling and using intrinsic
functions before extending them with instructions specific to the
intrinsic. We can refactor them further, but this is already a bit
easier to deal with when writing new intrinsics
1445: compile: Move and rename `SimpleIntrinsics` -> BuiltinsContext r=CohenArthur a=CohenArthur
This will allow us to use the class for more than just math builtins
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
128 bit integer support is not always available for every GCC arch and we
will need to rely on runtime libraries for these operations in the future.
Addresses #1439
1425: Cleanup frontend entrypoint r=CohenArthur a=CohenArthur
This removes a lot of code that was simply ported from the Go frontend, and forbids the usage of multiple input files.
Addresses #1115
1451: Fix failiure to type inference on unit-structs r=philberty a=philberty
This patch set adds fixes to ensure we can type inference generic unit-structs.
Fixes#1447
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
1444: Handle `rustc_const_{un}stable` properly for intrinsics r=CohenArthur a=CohenArthur
Since extern functions cannot be marked as const (they take no
qualifiers) but some intrinsics are const, while still being `extern
"rust-intrinsic", we need to be able to handle the
`#[rustc_const_stable]` and `#[rustc_const_unstable]` attribute.
Technically, this simply indicates that a certain intrinsic is constant
and can be used in const contexts, such as `size_of` or `offset`.
We also need to mark all const intrinsics with `rustc_const_stable` in
the testsuite.
Closes#1440
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
When we initilize a structure that contains an identifier for the value
which resolves to a generic unit-struct. The unit struct has no fields
but it also contains a reference to a generic parameter which needs to be
infered this updates the code for identifiers to act like a
PathInExpression to infer the generic parameters when its unit struct only.
Fixes#1447
When we have generic unit-structs there are no fields to unify the generic.
This adds a case to ensure we iterate and check these. We might end up
making it always do this for all structs always.
Addresses #1447
There is some dulication here which will eventually go away with the
coercion site refactor which is still a WIP. Here we update the type rules
so that we allow ADT's and tuples to unify and thus fulfill the type
inference rules.
Addresses #1447
1438: Enhance #1426 "Invalid recursive :stmt expansion in fragment specifiers" test case r=philberty a=tschwinge
... that was recently added in #1429 commit 9fc6a27b5c "expand: correctly handles non-macro nodes ...".
- Rename 'macro-issue1403.rs' -> 'macro-issue1426.rs'.
- Get rid of '-w'; expect diagnostic instead.
- Get rid of debugging options not relevant here.
- Get rid of explicit '-O1'; make it a "torture" test case.
- Replace always-matching 'scan-assembler "14"' ("14" appears in the crate name) with directed dump scanning.
- ..., just not for '-O0', where such optimization is not done.
Co-authored-by: Thomas Schwinge <thomas@codesourcery.com>
Since extern functions cannot be marked as const (they take no
qualifiers) but some intrinsics are const, while still being `extern
"rust-intrinsic", we need to be able to handle the
`#[rustc_const_stable]` and `#[rustc_const_unstable]` attribute.
Technically, this simply indicates that a certain intrinsic is constant
and can be used in const contexts, such as `size_of` or `offset`.
We also need to mark all const intrinsics with `rustc_const_stable` in
the testsuite.
1442: testsuite: test for diagnostics shown when a built-in macro does not exist r=CohenArthur a=liushuyu
- testsuite: test for diagnostics shown when a built-in macro does not exist
Co-authored-by: liushuyu <liushuyu011@gmail.com>
... that was recently added in #1429 commit 9fc6a27b5c "expand: correctly handles non-macro nodes ...".
- Rename 'macro-issue1403.rs' -> 'macro-issue1426.rs'.
- Get rid of '-w'; expect diagnostic instead.
- Get rid of debugging options not relevant here.
- Get rid of explicit '-O1'; make it a "torture" test case.
- Replace always-matching 'scan-assembler "14"' ("14" appears in the crate name) with directed dump scanning.
- ..., just not for '-O0', where such optimization is not done.
1437: Array index access does not need to unsize to a slice for access r=philberty a=philberty
When we define the core code for SliceIndex access its possible for an
array to be fully coerced into a slice DST and follow the normal slice
index access which removes support for GCC -Warray-index checks and
generates unnessecary code for array access.
Fixes#1436
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
When we define the core code for SliceIndex access its possible for an
array to be fully coerced into a slice DST and follow the normal slice
index access which removes support for GCC -Warray-index checks and
generates unnessecary code for array access.
Fixes#1436
1435: Update the type hasher to stop duplication of aggregate types r=philberty a=philberty
The hasher we ported was always calling TYPE_HASH which ends up with
DECL_UID which is geneated causing aggregate types keep having a unique
hash which ends up confusing the middle end as two copy's of the same
aggegate type ends up making GCC think there is some kind of type
conversion required here.
Fixes#1434
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
The hasher we ported was always calling TYPE_HASH which ends up with
DECL_UID which is geneated causing aggregate types keep having a unique
hash which ends up confusing the middle end as two copy's of the same
aggegate type ends up making GCC think there is some kind of type
conversion required here.
Fixes#1434
1431: Incremental refactor for better coercion site support r=philberty a=philberty
This is the major refactor to get our coercion site code closer to Rustc.
It introduced several new pieces most notably a refactor to the autoderef
cycle so this can be reused in method resolution and in coercion sites which
allows us to handle deref coercions. It will eventually allow us to get rid
of our bad implementation in rust-tyty-coercion.h which is just messy now.
Fixes#1198
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
1433: Fix bad transmute for aggregate types r=philberty a=philberty
This changes the CONVERT_EXPR to use the same ```*(foo*)&bar``` style cast from
the c front-end to handle the case of:
```
int a[1];
int b = (int)a;
```
Which is converted into:
```
int b = *(int*)&a;
```
which the constant folders can turn directly into int b = a[0];
Fixes#1432
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
This changes the CONVERT_EXPR to use the same *(foo*)&bar style cast from
the c front-end to handle the case of:
int a[1];
int b = (int)a;
Which is converted into:
int b = *(int*)&a;
which the constant folders can turn directly into int b = a[0];
Fixes#1432
This is an incremental approach to get our coercion sites more acurate to
rustc. This allows us to support coercions which require a deref by sharing
the code from the autoderef cycle. The eventual goal here will allow us to
remove the rust-tyty-coercion rules which is messy and cannot handle logic
such as DST's very well.
Fixes#1198
Similar to the fix in 405d9f1d13 when we have
arguments that our method calls. The id used for storing the autoderef
mappings being the method call itself rather than the receiver argument
it will cause an ICE when we are type checking all arguments for the case
of:
Foo(a, bar.baz(123))
This ensures we store the autoderef mappings directly on the reciever
instead.
Imagine the call expression:
Foo(a+b)
But the a+b is an operator overload of the assignment operation. We store
the autoderef coercions on the HIR id of the plus_expression here which is
going to conflict with the id used to store the autoderef coercions the
argument a+b. So this patch changes that all autoderef coercions store the
autoderef for the implicit method call on the hirid of the lvalue hirid
which in this case is 'a'. This means we won't conflict and cause an ICE
in this case.
This brings out the indirect expression out of our gcc wrapper, it also
just simplifies down to the normal build_indirect_expr_loc calls. Which
does not require specifiying the type since we can reuse TREE_TYPE. This
also simplifies the address_expression to just address_expr_with_loc and
grabs the type from TREE_TYPE as well.
In order to fully support coercion sites we need a single place in order to
implement the logic. This refactors all the coercion calls to have a single
TypeCheckBase::coercion_site(lhs, rhs, location). Eventually we will do
something similar for unifications and casts so we can improve our
diagnostics.
The autoderef cycle is used to coerce/select apropriate methods during
method resolution. This same cycle of autoderef is also used as coercion
sites. In order to avoid duplicating the logic this extracts out a useful
base class that can be implemented to support this elsewhere.
... a macro is now considered builtin macro only if it has
rustc_builtin_macro attribute. This also allows overriding macro
definition with the same name as the builtin ones.
Signed-off-by: Zixing Liu <liushuyu011@gmail.com>
When inserting external items, it's interesting to also be able to
lookup the extern block they were defined in, similarly to impl items.
This is useful to know the ABI or other specifiers of the block the item
has been declared in.
1421: expand: further improves the handling of recursive macros r=CohenArthur a=liushuyu
- expand: further improves the handling of recursive macros.
Now all the attribute visitor that expands the macro fragment will recursively expand the macro using the unified expanding function `expand_macro_fragment_recursive` instead of expanding the fragment only once.
Fixes#1403
Co-authored-by: liushuyu <liushuyu011@gmail.com>
... now all the attribute visitor that expands the
macro fragment will recursively expand the macro
using the unified expanding function
`expand_macro_fragment_recursive` instead of expanding
the fragment only once.
Signed-off-by: Zixing Liu <liushuyu011@gmail.com>
1419: Const checker r=CohenArthur a=CohenArthur
This commit serves as a base to ensure that only the allowed subset of
the language is called from const contexts. For example, this limits
function calls to calls to const functions only when in a const context
You can skip reviewing b4864c7e5a59a19fea6203c4b581889d4d6c20a1 as it's the exact same commit cherry-picked from #1415
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
This commit serves as a base to ensure that only the allowed subset of
the language is called from const contexts. For example, this limits
function calls to calls to const functions only when in a const context
1417: unsafe: check uses of static variables r=CohenArthur a=CohenArthur
Addresses #1411
Accessing an extern static or a mut static is unsafe and requires an unsafe function or block
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
1378: hir/dump: simple dumping of crate attrs and adding a few todos r=CohenArthur a=ndrwnaguib
This is draft PR to track the current implementation of the pretty dumping of HIR. `@CohenArthur` and I have agreed to keep it as simple as possible for now, and enhancements will be added along the way.
Co-authored-by: andrewnaguib <24280372+ndrwnaguib@users.noreply.github.com>
1410: unsafe: Add UnsafeCheck visitor r=CohenArthur a=CohenArthur
This visitor takes care of checking for unsafe expressions in safe
contexts. This first iteration reports the dereferencing of raw
pointers.
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
1406: Add Attribute checking visitor r=CohenArthur a=CohenArthur
This PR adds a new attribute checker visitor. Its role is to take care of validating builtin attributes and their inputs.
This is currently a draft as there are multiple issues:
1. The visitor is not complete
2. The lexer is broken, but was also broken before in that it didn't allow multiline string literals. There is a FIXME asking for how to check for an `EOF` character when parsing UTF-8 strings
3. The checking of attributes is very limited. Currently, only the `#[doc(alias = "...")]` is being checked. This is incomplete.
I'm looking for feedback on the implementation and advice for my issues. Thanks :)
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
1409: checks: Refactor project architecture for checking passes r=CohenArthur a=CohenArthur
This commit adds a new `checks/` folder in the root of the Rust
frontend, which then contains a folder for `lints` and one for `errors`
passes. Otherwise, some error reporting passes like the privacy checks
or upcoming unsafe visitor would have to live in their own folder in the
root, or be part of another folder like `typecheck` or `hir` which
doesn't necessarily makes sense. This should enable us to find them more
easily going forward
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
This commit adds a new `checks/` folder in the root of the Rust
frontend, which then contains a folder for `lints` and one for `errors`
passes. Otherwise, some error reporting passes like the privacy checks
or upcoming unsafe visitor would have to live in their own folder in the
root, or be part of another folder like `typecheck` or `hir` which
doesn't necessarily makes sense. This should enable us to find them more
easily going forward
This commit adds a new attribute checker visitor. Its role is to take care of validating builtin attributes and their inputs.
In order to validate doc(alias) strings properly, as well as handle
multiline (byte) strings, this also fixes the lexer to better handle EOF
in bytes and codepoints.
When expanding repeating metavars, we have to allow the repetition of non-repeating metavars as well:
```
macro_rules! foo {
( ( $( $Trait: ident ),+ ) for $Ty: ident ) => {
$(
impl $Trait for $Ty {
fn bar() -> i32 {
14
}
}
)+
}
}
trait Foo {
fn bar() -> i32;
}
trait Bar {
fn bar() -> i32;
}
trait Baz {
fn bar() -> i32;
}
trait Qux {
fn bar() -> i32;
}
struct S;
foo!{(Foo, Bar, Baz, Qux) for S}
```
This is valid, as the $Ty metavar is not a repetition. However, this should fail to compile:
```
macro_rules! foo {
// note the repetition here now
( ( $( $Trait: ident ),+ ) for $($Ty: ident)+ ) => {
$(
impl $Trait for $Ty {
fn bar() -> i32 {
14
}
}
)+
}
}
trait Foo {
fn bar() -> i32;
}
trait Bar {
fn bar() -> i32;
}
trait Baz {
fn bar() -> i32;
}
trait Qux {
fn bar() -> i32;
}
struct S;
foo!{(Foo, Bar, Baz, Qux) for S}
```
Obviously, if we were to specify as many $Ty as $Trait then there would be no issue, but that behavior is already handled.
1404: 'gcc/testsuite/rust/link/link.exp': Fix 'runtest_file_p' usage r=philberty a=tschwinge
The recent commit 418aef1b00
"Support extern crate" (merged in
commit fd2bd659e4 "Merge #1362"), added
'gcc/testsuite/rust/link/link.exp', which I understand to be a hacked up
variant of the LTO multi-file testing harness (not reviewed in detail).
Since that commit, there are issues in parallel testing, so that, for example
with:
$ make -j12 check-rust RUNTESTFLAGS='--target_board=unix\{,-m32,-mx32\}'
..., the first variant does test as expected:
`@@` -6490,9 +6490,31 `@@` PASS: rust/execute/torture/trait9.rs -Os at line 13 (test for warnings, line
PASS: rust/execute/torture/trait9.rs -Os (test for excess errors)
PASS: rust/execute/torture/trait9.rs -Os execution test
PASS: rust/execute/torture/trait9.rs -Os output pattern test
+Running /home/thomas/tmp/source/gcc/rust/build/trace-slim/source-gcc/gcc/testsuite/rust/link/link.exp ...
+PASS: rust/link/generic_function_0.rs -O0 (test for excess errors)
+[...]
+PASS: rust/link/trait_import_0.rs -Os (test for excess errors)
=== rust Summary for unix ===
-# of expected passes 6445
+# of expected passes 6466
# of expected failures 31
..., but we then get undesired changes for the second and following variants:
Running target unix/-m32
Running /home/thomas/tmp/source/gcc/rust/build/trace-slim/source-gcc/gcc/testsuite/rust/compile/compile.exp ...
PASS: rust/compile/abi-options1.rs at line 2 (test for errors, line 1)
PASS: rust/compile/abi-options1.rs at line 7 (test for errors, line 6)
PASS: rust/compile/abi-options1.rs (test for excess errors)
-PASS: rust/compile/array3.rs at line 2 (test for warnings, line 1)
-PASS: rust/compile/array3.rs (test for excess errors)
-PASS: rust/compile/array_empty_list.rs at line 3 (test for errors, line 2)
-PASS: rust/compile/array_empty_list.rs (test for excess errors)
-PASS: rust/compile/arrays1.rs (test for errors, line 3)
-PASS: rust/compile/arrays1.rs (test for excess errors)
PASS: rust/compile/arrays2.rs at line 4 (test for errors, line 3)
PASS: rust/compile/arrays2.rs (test for excess errors)
PASS: rust/compile/attr-mismatch-crate-name.rs (test for excess errors)
`@@` -8355,110 +8371,215 `@@` PASS: rust/compile/torture/generics17.rs -O3 -g (test for excess errors)
PASS: rust/compile/torture/generics17.rs -Os at line 18 (test for warnings, line 17)
PASS: rust/compile/torture/generics17.rs -Os (test for excess errors)
PASS: rust/compile/torture/generics18.rs -O0 at line 19 (test for warnings, line 18)
+PASS: rust/compile/torture/generics18.rs -O0 at line 19 (test for warnings, line 18)
+PASS: rust/compile/torture/generics18.rs -O0 at line 5 (test for warnings, line 4)
PASS: rust/compile/torture/generics18.rs -O0 at line 5 (test for warnings, line 4)
PASS: rust/compile/torture/generics18.rs -O0 (test for excess errors)
+PASS: rust/compile/torture/generics18.rs -O0 (test for excess errors)
..., and so on.
This has been determined to be due to repetitive 'runtest_file_p' calls (it's
a mess...), thusly fixed (some would call it a "hack", no doubt), and verified
that, for example:
$ make -j12 check-rust RUNTESTFLAGS='--target_board=unix\{,-m32,-mx32\} link.exp=simple_function_0.rs'
... only runs the one test as indicated.
Co-authored-by: Thomas Schwinge <thomas@codesourcery.com>
The recent commit 418aef1b00
"Support extern crate" (merged in
commit fd2bd659e4 "Merge #1362"), added
'gcc/testsuite/rust/link/link.exp', which I understand to be a hacked up
variant of the LTO multi-file testing harness (not reviewed in detail).
Since that commit, there are issues in parallel testing, so that, for example
with:
$ make -j12 check-rust RUNTESTFLAGS='--target_board=unix\{,-m32,-mx32\}'
..., the first variant does test as expected:
@@ -6490,9 +6490,31 @@ PASS: rust/execute/torture/trait9.rs -Os at line 13 (test for warnings, line
PASS: rust/execute/torture/trait9.rs -Os (test for excess errors)
PASS: rust/execute/torture/trait9.rs -Os execution test
PASS: rust/execute/torture/trait9.rs -Os output pattern test
+Running /home/thomas/tmp/source/gcc/rust/build/trace-slim/source-gcc/gcc/testsuite/rust/link/link.exp ...
+PASS: rust/link/generic_function_0.rs -O0 (test for excess errors)
+[...]
+PASS: rust/link/trait_import_0.rs -Os (test for excess errors)
=== rust Summary for unix ===
-# of expected passes 6445
+# of expected passes 6466
# of expected failures 31
..., but we then get undesired changes for the second and following variants:
Running target unix/-m32
Running /home/thomas/tmp/source/gcc/rust/build/trace-slim/source-gcc/gcc/testsuite/rust/compile/compile.exp ...
PASS: rust/compile/abi-options1.rs at line 2 (test for errors, line 1)
PASS: rust/compile/abi-options1.rs at line 7 (test for errors, line 6)
PASS: rust/compile/abi-options1.rs (test for excess errors)
-PASS: rust/compile/array3.rs at line 2 (test for warnings, line 1)
-PASS: rust/compile/array3.rs (test for excess errors)
-PASS: rust/compile/array_empty_list.rs at line 3 (test for errors, line 2)
-PASS: rust/compile/array_empty_list.rs (test for excess errors)
-PASS: rust/compile/arrays1.rs (test for errors, line 3)
-PASS: rust/compile/arrays1.rs (test for excess errors)
PASS: rust/compile/arrays2.rs at line 4 (test for errors, line 3)
PASS: rust/compile/arrays2.rs (test for excess errors)
PASS: rust/compile/attr-mismatch-crate-name.rs (test for excess errors)
@@ -8355,110 +8371,215 @@ PASS: rust/compile/torture/generics17.rs -O3 -g (test for excess errors)
PASS: rust/compile/torture/generics17.rs -Os at line 18 (test for warnings, line 17)
PASS: rust/compile/torture/generics17.rs -Os (test for excess errors)
PASS: rust/compile/torture/generics18.rs -O0 at line 19 (test for warnings, line 18)
+PASS: rust/compile/torture/generics18.rs -O0 at line 19 (test for warnings, line 18)
+PASS: rust/compile/torture/generics18.rs -O0 at line 5 (test for warnings, line 4)
PASS: rust/compile/torture/generics18.rs -O0 at line 5 (test for warnings, line 4)
PASS: rust/compile/torture/generics18.rs -O0 (test for excess errors)
+PASS: rust/compile/torture/generics18.rs -O0 (test for excess errors)
..., and so on.
This has been determined to be due to repetitive 'runtest_file_p' calls (it's
a mess...), thusly fixed (some would call it a "hack", no doubt), and verified
that, for example:
$ make -j12 check-rust RUNTESTFLAGS='--target_board=unix\{,-m32,-mx32\} link.exp=simple_function_0.rs'
... only runs the one test as indicated.
1397: lexer: Allow specifiying tokens as reserved in certain editions r=CohenArthur a=CohenArthur
Some tokens such as `try` only became reserved keywords in certain
editions. This behavior might happen again in the future and we should
be able to handle it.
Closes#1395
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
Some tokens such as `try` only became reserved keywords in certain
editions. This behavior might happen again in the future and we should
be able to handle it.
1394: Fix parsing grammer of grouped expressions as the block tail expression r=philberty a=philberty
When we want to compile a grouped expression we had a check for the
LEFT_PAREN during the parse_expr_without_block but this can't be handled
here since in this paticular example the grouped expressions is simply the
lhs of the bit shift expression. This is already handled as part of
parse_expr so we can simply remove the rule here and rely on parse_expr
handling this.
Fixes#1393
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
When we want to compile a grouped expression we had a check for the
LEFT_PAREN during the parse_expr_without_block but this can't be handled
here since in this paticular example the grouped expressions is simply the
lhs of the bit shift expression. This is already handled as part of
parse_expr so we can simply remove the rule here and rely on parse_expr
handling this.
Fixes#1393
1392: Ensure we parse any inner item attributes when expanding a module r=philberty a=philberty
When compiling code containing module expansions we must first ensure any
possible inner item attributes are parser first and applied to the module,
otherwise we end up in a bad state and ignore attributes.
Fixes#1089
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
1358: Disambiguate generic args r=CohenArthur a=CohenArthur
Needs #1355. Only review the last commit. The next steps are to typecheck const generics and then lower them to TREE
This removes all the hacks previously introduced to resolve ambiguous
generic args as types, and adds proper disambiguation.
The algorithm is as follows:
is that name referring to a type?
-> disambiguate to a type
is that name referring to a value?
-> disambiguate to a const value
else
-> disambiguate to type
Since types are the default expected behavior, this allows us to report
type errors properly during typechecking.
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
This removes all the hacks previously introduced to resolve ambiguous
generic args as types, and adds proper disambiguation.
The algorithm is as follows:
is that name referring to a type?
-> disambiguate to a type
is that name referring to a value?
-> disambiguate to a const value
else
-> disambiguate to type
Since types are the default expected behavior, this allows us to report
type errors properly during typechecking.
When compiling code containing module expansions we must first ensure any
possible inner item attributes are parser first and applied to the module,
otherwise we end up in a bad state and ignore attributes.
Fixes#1089
1373: Typecheck const generic params r=CohenArthur a=CohenArthur
```rust
struct Foo<const N: usize>;
struct Bar<const N: usize = { 15i32 }>; // { dg-error "expected .usize. got .i32." }
```
This PR allows us to typecheck the type of const generics as well as make sure that the optional default expression fits that type
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
1391: Fix ICE on duplicate compilation of ExternBlock items r=philberty a=philberty
When we declare an extern block after where it is used the query
compilation system in the backend code-gen pass will resolve this and
compile as required. But when the iteration of the crate as part of the
pipeline we end up compiling this function again. The check we used to stop
this was copy paste from the other function items but in this case the
check for function_completed is not valid as this is a prototype for an
extern item so we dont add this to the translation unit as an fndecl which
meant we hit the ICE where we compile and add it again.
Fixes#1323
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
When we declare an extern block after where it is used the query
compilation system in the backend code-gen pass will resolve this and
compile as required. But when the iteration of the crate as part of the
pipeline we end up compiling this function again. The check we used to stop
this was copy paste from the other function items but in this case the
check for function_completed is not valid as this is a prototype for an
extern item so we dont add this to the translation unit as an fndecl which
meant we hit the ICE where we compile and add it again.
Fixes#1323
1362: extern crate loading r=philberty a=philberty
WIP still trying to write dejagnu to enable automated tests
Extern crates statements to tell the front-end to look for another library.
The mechanism here is heavily inspired from gccgo, so when we compile a
library for example we invoke:
```
gccrs -g -O2 -frust-crate=mylib -c src/lib.rs -o src/mylib.o
```
All going well this object file will now contain extra data inside
.rust-export section inside the object file which will be preserved inside
archives and shared objects. When we have another application which uses
this library 'mylib'.
```rust
extern crate mylib;
use mylib::foo;
fn main() {
foo();
}
```
We compile using:
```
gcc -g -O2 -frust-crate=test -c src/main.rs -o src/main.o
```
When the extern crate line is hit the front-end will look for mylib.o,
libmylib.a, mylib.rox. If it finds a raw object file it will read the
.rust-export section directly from the object for the public metadata
such as public functions, types constants etc. If it fails to find an
object it might find .rox which is the objdump of the .rust-export to a
raw file, it might even find libmylib.a and read the export directly out
of the archive file reusing code from gccgo to do so.
The full compiler pipeline is reused here, so the metatadata is actually
just real rust code. The benifit here is that Rust supports exporting,
macros and generics so this requires the name-resolution and type info
all to be generated and inserted into the apropriate context classes. Since
the metadata is real rust code it means we can reuse the full pipeline to
generate the code as nessecary. So for the simple case of a public struct
we simply emit the AST dump of this struct directly into the metadata. If
its a non-generic public function we emit and extern rust abi block for
that function. If its a trait we can simply emit the trait with the public
memebers. Generics are more complicated since we need to emit the function
fully for it to be compiled correctly this still needs tests to be added.
The hardest part is non generic impl blocks which is still a WIP.
To finally link the two crates together you run:
```
gcc -g -O2 -o rust-program.exe src/main.o src/mylib.o
```
Fixes: 1169
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
This interface will allow us to write the metadata directly to a file.
MacOs does not support metadata embeded directly into a .section of
object files and archives. This allows us to seperate this mechanism so
that we can follow rustc and write this directly to a seperate file.
This patch adds two new options to control metadata outputs
-frust-embed-metadata this toggles to embed the metadata into .rust_export
section of the target asm output
-frust-metadata-output= specifies the path to directly write the metadata
to file
We need these options as embeding the metadata does not seem to be
supported for all platforms like MacOs so writing directly to file is a
platform agnostic solution.
There is an implicit naming convetion to metadata export files. They need
to be of crate_name.rox. This patch adds some simple validation by checking
the basename of the specified path.
Extern crates statements to tell the front-end to look for another library.
The mechanism here is heavily inspired from gccgo, so when we compile a
library for example we invoke:
gccrs -g -O2 -frust-crate=mylib -c src/lib.rs -o src/mylib.o
All going well this object file will now contain extra data inside
.rust-export section inside the object file which will be preserved inside
archives and shared objects. When we have another application which uses
this library 'mylib'.
extern crate mylib;
use mylib::foo;
fn main() {
foo();
}
We compile using:
gcc -g -O2 -frust-crate=test -c src/main.rs -o src/main.o
When the extern crate line is hit the front-end will look for mylib.o,
libmylib.a, mylib.rox. If it finds a raw object file it will read the
.rust-export section directly from the object for the public metadata
such as public functions, types constants etc. If it fails to find an
object it might find .rox which is the objdump of the .rust-export to a
raw file, it might even find libmylib.a and read the export directly out
of the archive file reusing code from gccgo to do so.
The full compiler pipeline is reused here, so the metatadata is actually
just real rust code. The benifit here is that Rust supports exporting,
macros and generics so this requires the name-resolution and type info
all to be generated and inserted into the apropriate context classes. Since
the metadata is real rust code it means we can reuse the full pipeline to
generate the code as nessecary. So for the simple case of a public struct
we simply emit the AST dump of this struct directly into the metadata. If
its a non-generic public function we emit and extern rust abi block for
that function. If its a trait we can simply emit the trait with the public
memebers. Generics are more complicated since we need to emit the function
fully for it to be compiled correctly this still needs tests to be added.
The hardest part is non generic impl blocks which is still a WIP.
To finally link the two crates together you run:
gcc -g -O2 -o rust-program.exe src/main.o src/mylib.o
Fixes: 1169
This allows AST dump of attributes on Traits this code needs to be applied
for all attribute dumps. Traits also have an implicit Self generic param
this ensure we ignore this during an AST dump.
1385: Add missing include for intellisense r=philberty a=philberty
1386: Fix undefined behaviour using .get on unique_ptr r=philberty a=philberty
As the move semantics for AST and HIR crates are unsafe on older compilers
we are working around this by storing the pointer into the mappings class
this was using the get method to store the pointer. The issue for loading
extern crates the unique_ptr goes out of scope and this the deletion code
resulting in undefined behaviour. This changes it to call release to take
full ownership of the pointer as we expect.
1387: External Items with Rust ABI need to mangle the full path r=philberty a=philberty
When compiling external rust abi item requires the fully qualified
canonical path to be mangled in order to link correctly.
1388: Add new interfaces to mappings class r=philberty a=philberty
In order to load and resolve extern crates we need to support detection
of node_id is a crate in order to support paths outside of the current
crate.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
As the move semantics for AST and HIR crates are unsafe on older compilers
we are working around this by storing the pointer into the mappings class
this was using the get method to store the pointer. The issue for loading
extern crates the unique_ptr goes out of scope and this the deletion code
resulting in undefined behaviour. This changes it to call release to take
full ownership of the pointer as we expect.
1380: Support aggregate types in transmute r=philberty a=philberty
In some testcases in libcore transmute is used on aggregate types like
array's. The convert expression code assumes simple integer's. This this
patch uses a gimple convert_expr to try and convert this type. This might
change to a generic memcpy at somepoint but lets try this first and see how
it works.
1381: Implement AST dump for ArithmeticOrLogicalExpr to fix unreachable r=philberty a=philberty
1382: Support ast dump of generic parameters on functions r=philberty a=philberty
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
1384: Support generics in check for valid types in arithmetic expressions r=philberty a=philberty
When we check for valid types we need to be sure to call destructure which
will extract out any generics so that we are checking the actual concrete
type that is being used here.
Fixes#1383
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
When we check for valid types we need to be sure to call destructure which
will extract out any generics so that we are checking the actual concrete
type that is being used here.
Fixes#1383
In some testcases in libcore transmute is used on aggregate types like
array's. The convert expression code assumes simple integer's. This this
patch uses a gimple convert_expr to try and convert this type. This might
change to a generic memcpy at somepoint but lets try this first and see how
it works.
1379: backend: explain why cdecl is treated differently when setting up the ABIs r=philberty a=liushuyu
- backend: explain why `cdecl` is treated differently when setting up the ABIs
Co-authored-by: liushuyu <liushuyu011@gmail.com>
1374: remove unused go code r=philberty a=philberty
This function is not used and we don't want to disable optimizations
randomly like this.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
1372: typecheck-resolve-type: Move all remaining definitions r=CohenArthur a=CohenArthur
This PR finishes the refactoring of `typecheck-resolve-type.h` that had been previously started.
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
1366: Refactor mappings class and HIR lowering to be consistent r=philberty a=philberty
In order to support loading extern crates and use statements we needed to
clarify the usage of NodeId and HirId within gccrs. Each of these id's were
nested behind the CrateNum but the type resolution, linting and code-gen
passes do not support that level of nesting.
In order to get metadata exports and imports working lets focus on gccrs
supporting compilation of a single crate at a time. This means the crate
prefix only matters for imports and limits the complexity here. Down the
line there might be a way to leverage DefId's for all Path resolution
which could solve this problem but significant refactoring would be
required here to do this properly and its not nessecary for a basic working
rust compiler.
The mappings changes here will help us resolve issues like #1361 much more
easily.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
In order to support loading extern crates and use statements we needed to
clarify the usage of NodeId and HirId within gccrs. Each of these id's were
nested behind the CrateNum but the type resolution, linting and code-gen
passes do not support that level of nesting.
In order to get metadata exports and imports working lets focus on gccrs
supporting compilation of a single crate at a time. This means the crate
prefix only matters for imports and limits the complexity here. Down the
line there might be a way to leverage DefId's for all Path resolution
which could solve this problem but significant refactoring would be
required here to do this properly and its not nessecary for a basic working
rust compiler.
The clone interface on HIR::Functions can have an optional nullptr return
type which was always being derefed for the clone interface. This seems
to trigger when compiling with gcc-4.8 but not on modern GCC versions.
1371: typecheck: Refactor TypeCheckTopLevel class r=CohenArthur a=CohenArthur
This commit moves the TypeCheckTopLevel implementation into its own
source file, and factors generic parameter resolving into a single
function
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
1367: Initial support for matches on tuples r=dafaust a=dafaust
Initial work on supporting more complex match expressions, starting with tuples. It's proven to be quite a bit more complicated than I originally expected. Still this implementation is very naive, probably very poor performance, and skips all the nuanced stuff like bindings in patterns and pattern guards.
Overview
The general idea is that we lower `MatchExpr`s to `SWITCH_EXPR` trees, but a switch can only operate on one value at a time. When scrutinizing a tuple, we can't build a switch that checks all the elements at once. So instead, just before lowering to trees, we construct a new set of nested match expressions which tests the tuple one element at a time, and is (hopefully) semantically identical to the original match. These new nested matches are simplified, so that each one tests only one thing and therefore *can* lower directly to a `SWITCH_EXPR`.
To see an example, this
```text
match (tupA, tupB, tupC) {
(a1, b1, c1) => { blk1 }
(a2, b2, c2) => { blk2 }
(a1, b3, c3) => { blk3 }
...
_ => { blk4 }
}
```
after one step becomes
```text
match tupA {
a1 => {
match (tupB, tupC) {
(b1, c1) => { blk1 }
(b3, c3) => { blk3 }
...
_ => { blk4 }
}
a2 => {
match (tupB, tupC) {
(b2, c2) => { blk2 }
...
_ => { blk4 }
}
}
_ => { blk4 }
}
```
Repeat until all matches are fully simplified, then compile it all into trees.
Now, we might end up with a lot of duplicated basic blocks here as a result, but the optimization in GENERIC and GIMPLE (further on in gcc) is very good and knows how to take care of that for us.
This approach seems somewhat similar to how rustc lowers HIR to MIR, which is hopefully a good sign :)
Addresses: #1081
Co-authored-by: David Faust <david.faust@oracle.com>
This is a first take on compiling matches on more complex expressions,
starting with tuples.
The general idea is to first rearrange the match into a simpler form, in
which only one element of the scrutinee tuple is examined at a time.
The remaining elements are then checked by a new match in each arm. By
repeating this process, we end up with a series of nested matches each
checking one element of the original scrutinee, which is equivalent to
the original match expression, and which lowers directly to SWITCH_EXPR
tree nodes (since these can only switch on one thing).
The resulting SWITCH_EXPRs may be messy, and unoptimal, but we can rely
on later optimizations in GENERIC and GIMPLE to clean them up for us.
This commit pulls some of the validation of the match expression
scrutinee out into a helper, since it will be needed to be reused when
compiling matches on tuples.
1363: Refactor Lexer to support an abstract InputSource class r=philberty a=philberty
This patch allows us to remove the fmemopen lex_string hack to support
parsing buffers. This will allow us to support mutliple sources such as
metadata imports etc. The patch here updates the parser to hold onto a
reference to the lexer rather than 'owning' the lexer which allows us to
decouple the move semantics here.
Fixes#1203Fixes#1000
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
This patch allows us to remove the fmemopen lex_string hack to support
parsing buffers. This will allow us to support mutliple sources such as
metadata imports etc. The patch here updates the parser to hold onto a
reference to the lexer rather than 'owning' the lexer which allows us to
decouple the move semantics here.
Fixes#1203#1000
1364: Allow linemap to be optional nullptr r=philberty a=philberty
The line map within the lexer is used to notify GCC of location data.
This lexer is used on raw string buffers where the linemap can be
null and thus can hit nullptr's. This patch wraps the linemap usage
behind a function. We might make the linemap mandatory as a reference
but lets figure out how the location info should look for imports first.
1365: Support extern-blocks in ast-dumps r=philberty a=philberty
This allows us to support really basic expressions and extern blocks. These
are used for the hello world version of importing metadata in crates.
1368: Fix bad ABI from string method r=philberty a=philberty
We use this method to turn the string ABI into the enum. The
rust abi was wrongly turned into the C ABI always which was
causing issues on the mangling logic for extern crate items.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
1355: Ambiguous generic arg r=CohenArthur a=CohenArthur
Needs #1354. Only review the last commit :)
ast: Rename ConstGenericArg -> GenericArg
This makes the class clearer and exposes the fact that it may contain a
type OR a const value clearer.
Because we now run in ambiguous cases later in the compiler pipeline,
this commit also adds horrible hacks to simply ignore ambiguous generic
arguments and treat them as type arguments.
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
This makes the class clearer and exposes the fact that it may contain a
type OR a const value clearer.
Because we now run in ambiguous cases later in the compiler pipeline,
this commit also adds horrible hacks to simply ignore ambiguous generic
arguments and treat them as type arguments.
1354: ast: Add ResolveGenericArgs resolver r=CohenArthur a=CohenArthur
This resolver replaces the helper function
`ResolveType::type_resolve_generic_args` and will later benefit from
more functionality such as generic disambiguation
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
This resolver replaces the helper function
`ResolveType::type_resolve_generic_args` and will later benefit from
more functionality such as generic disambiguation
1346: Support self paths r=philberty a=philberty
This adds support for the self path which is used in two different
contexts. One where it refers to the self parameter within methods
the other is where it can refer to the crate module scope.
Handling self has some limitations where it must be the first
the segment in the path or be a single segment path for example see:
```
struct foo;
fn test() {
crate::self::foo;
}
```
Errors with (rustc 1.61):
```
Error[E0433]: failed to resolve: `self` in paths can only be used in start position
```
crate and super keywords can be chained as expected but self seems to be a special case.
The patch here reorders the algorithm to look at the name/type scope first if its the first segment
and handle the lower case self as a special case. If this fails to result in a resolved node we
then try to look at the module_scope_id hierarchy to handle the case that the previous segments
were crate or super and finally error out at the end if we failed to resolve the segment. We can
only error for the first segment as associated paths such as Foo::Bar with Bar being an associated
impl block item requiring type-resolution.
Fixes#1231#1227
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
1352: HIR: fixup MatchArm assignment operator r=philberty a=dafaust
We overload the assignment operator to clone the vector of patterns for
the match arm. However the existing patterns were not cleared before
inserting the new ones, so the result was to append the new patterns
onto the assignee arm rather than replace them.
Co-authored-by: David Faust <david.faust@oracle.com>
We overload the assignment operator to clone the vector of patterns for
the match arm. However the existing patterns were not cleared before
inserting the new ones, so the result was to append the new patterns
onto the assignee arm rather than replace them.
1336: Resolve const generic parameters r=CohenArthur a=CohenArthur
Fixes#1319.
This can only resolve the simpler test cases: Anything that is ambiguous is ignored and does not get resolved. This will be fixed very soon :)
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
This commit adds a base for resolving the type and default expression of
const generic parameters.
For now, there is no disambiguation happening. So we are still
extremely limited.
For example, this structure gets its const generic parameter ignored and
unresolved because it looks like a type: Despite us knowing for sure
that the default expression here WILL be a constant expression.
```rust
const M: usize = 15;
struct Foo<const N: usize = M>;
```
When we resolve paths the code was looking at the crate hierarchy first
in the algorithm this leads to a bug where in rust you can have a function
named foo at the item level then declare a nested function with the same
name. So when we wanted to call the nested function the code was defaulting
to the toplevel first resulting in bad name resolution.
This patch updates the code to look at the scope first, then look at the
module scope hierarchy. It finally adds the error handling in a nice single
path at the end. We can only error out if its not the first segment since
paths such as associated types like Self::foo we cannot resolve foo as this
requires the type-resolution system to determine the projection.
Fixes#1231
This keyword is described in
https://doc.rust-lang.org/std/keyword.self.html
Which allows it to refer to the current module when used as the first
segment. If the keyword is used as any other segment it leads to a
confusion between self the local parameter keyword in methods. Rustc
emits a generic unresolved segment error in that senario which I have
adopted here.
Fixes#1227
1151: backend: handle deprecated attribute r=philberty a=liushuyu
- handle the `deprecated` attribute
1343: Ensure we support generic arguments on mangled type-paths r=philberty a=philberty
This allows us to have the generic arguments within type paths for mangled
symbols such as those in impl-blocks. This also updates our symbol
managling to mangle comma's to $C$.
Co-authored-by: liushuyu <liushuyu011@gmail.com>
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
This allows us to have the generic arguments within type paths for mangled
symbols such as those in impl-blocks. This also updates our symbol
managling to mangle comma's to $C$.
1342: Refactor name-resolution pass r=philberty a=philberty
This is a patch series which cleans up the code in the name resolution pass. Prior to
#1307 we used to build up canonical path segments to do name resolution of types
and paths, this lead to confusing code in how we handle impl blocks Self type and
in general. This fixes that confusion to make the code more maintainable.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
This patch also decouples handle the case where we need to resolve the full
canonical path of a TypeNoBounds such as:
struct Foo;
impl &Foo { .. }
And te canonical path for the impl block Self type is actually
&crate_name::Foo
This is used in name mangling right now.
1341: ci: Temporarily disable Remark CI r=CohenArthur a=CohenArthur
The Remark CI is breaking for seemingly unrelated reasons regarding
JavaScript syntax. Let's disable it in the meantime and investigate so
that our PRs can still get proper feedback
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
The Remark CI is breaking for seemingly unrelated reasons regarding
JavaScript syntax. Let's disable it in the meantime and investigate so
that our PRs can still get proper feedback
1337: Actually set TYPE_PACKED for type_record r=dafaust a=CohenArthur
When bootstrapping with --enable-checking=no you'll get:
gcc/rust/backend/rust-compile-type.cc: In member function
‘virtual void Rust::Compile::TyTyResolveCompile::visit(const Rust::TyTy::ADTType&)’:
gcc/tree.h:2312:59: error: statement has no effect [-Werror=unused-value]
2312 | #define TYPE_PACKED(NODE) (TYPE_CHECK (NODE)->base.u.bits.packed_flag)
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~
gcc/rust/backend/rust-compile-type.cc:315:7:
note: in expansion of macro ‘TYPE_PACKED’
315 | TYPE_PACKED (type_record);
| ^~~~~~~~~~~
We need to actually set a value for the packed_flag.
Co-authored-by: Mark Wielaard <mark@klomp.org>
At the AST level, we might encounter situations where const generic
arguments are ambiguous: They could be resolved to either a type or a
const expression, as shown in this example:
```rust
let a: Foo<N>; // what is N? A type? A const? The parser doesn't know
```
However, when parsing default expressions for const generic parameters,
we need to be able to disambiguate to const expressions early:
```rust
struct Foo<const N: usize = { M }> {
/* ... */
}
```
In that code, `M` could be considered ambiguous: Is it a type? a const?
A random non-const variable? What matters is that we disambiguate it to
a const generic argument, so that it errors out appropriately in later
phases of the compiler.
In that case, we need to go from a `ConstArg::Ambiguous("M")` to a
`ConstArg::Clear(IdentifierExpr("M"))`.
In later passes of the compiler, we will also need to disambiguate to
types. But that will be done at the HIR/Resolving level.
1335: cli: add "hir-pretty" as a "dump" option r=CohenArthur a=ndrwnaguib
Fixes#1333
Instead of mixing the ongoing project of pretty dumping the HIR with the current
implementation, this commit adds a new option "-frust-dump-hir-pretty" which
calls the hir pretty dump visitor class. Closes https://github.com/Rust-GCC/gccrs/issues/1333
Co-authored-by: andrewnaguib <24280372+ndrwnaguib@users.noreply.github.com>
Instead of mixing the ongoing project of pretty dumping the HIR with the current
implementation, this commit adds a new option "-frust-dump-hir-pretty" which
calls the hir pretty dump visitor class. Closes https://github.com/Rust-GCC/gccrs/issues/1333
Co-authored-by: CohenArthur <arthur.cohen@embecosm.com>
1332: hir/add: pretty printing visitor skeleton r=CohenArthur a=ndrwnaguib
This commit adds a visitor skeleton for pretty printing of the HIR. Also,
modifies the session manager to call the new entry point
`Rust::HIR::Dump::crate` which simply prints the crate the way it used to be.
Co-authored-by: andrewnaguib <24280372+ndrwnaguib@users.noreply.github.com>
1331: Fix remaining misuses of format specifiers on 32-bit targets r=CohenArthur a=CohenArthur
> Unfortunately, another instance of this issue sneaked in after my original patch.
Fixed by the attached patch, which makes this work again on i386-pc-solaris2.11
Co-authored-by: Rainer Orth <ro@gcc.gnu.org>
This commit adds a visitor skeleton for pretty printing of the HIR. Also,
modifies the session manager to call the new entry point
`Rust::HIR::Dump::crate` which simply prints the crate the way it used to be.
Co-authored-by: CohenArthur <arthur.cohen@embecosm.com>
1326: ast: Add location to ConstGenericArg r=CohenArthur a=CohenArthur
Closes#1320
Sorry for taking a good-first-pr but this is starting to be needed :)
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
Unfortunately, another instance of this issue sneaked in after my original patch.
Fixed by the attached patch, which makes this work again on i386-pc-solaris2.11
Since this is a huge function, we will start by porting chunks on which it depends.
This changeset ports over the below typedefs, structs and functions in addition to the macros:
Typedefs:
- tsubst_flags_t
Structs:
- lang_type
- tree_pair_s
Functions:
- cp_expr_loc_or_loc
- cp_expr_loc_or_input_loc
- cp_expr_location
- is_really_empty_class
- is_empty_class
- array_type_nelts_top
When bootstrapping with --enable-checking=no you'll get:
gcc/rust/backend/rust-compile-type.cc: In member function
‘virtual void Rust::Compile::TyTyResolveCompile::visit(const Rust::TyTy::ADTType&)’:
gcc/tree.h:2312:59: error: statement has no effect [-Werror=unused-value]
2312 | #define TYPE_PACKED(NODE) (TYPE_CHECK (NODE)->base.u.bits.packed_flag)
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~
gcc/rust/backend/rust-compile-type.cc:315:7:
note: in expansion of macro ‘TYPE_PACKED’
315 | TYPE_PACKED (type_record);
| ^~~~~~~~~~~
We need to actually set a value for the packed_flag.
1317: AST for const generic arguments/const application r=CohenArthur a=CohenArthur
This commit adds a new type to the AST which contains const generic
arguments. The `GenericArgs` structure now also keeps a vector of them,
and the parser was modified accordingly. We need to handle these extra
arguments in the various resolvers and type-checking phase.
As pointed out before, const generic arguments are ambiguous at the AST
level. Which is why this "sum type" contains a "Clear" variant when
there is no ambiguity at all (`<5>`, `<{ 5 }>`, `<{ 5 + 15 }>` or
`<{ N }>`) and an "Ambiguous" one if the value in question might be
referring to a type argument (`<N>`) instead of a const generic
argument.
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
This commit adds a new type to the AST which contains const generic
arguments. The `GenericArgs` structure now also keeps a vector of them,
and the parser was modified accordingly. We need to handle these extra
arguments in the various resolvers and type-checking phase.
As pointed out before, const generic arguments are ambiguous at the AST
level. Which is why this "sum type" contains a "Clear" variant when
there is no ambiguity at all (`<5>`, `<{ 5 }>`, `<{ 5 + 15 }>` or
`<{ N }>`) and an "Ambiguous" one if the value in question might be
referring to a type argument (`<N>`) instead of a const generic
argument.
However, when parsing a const generic declaration, we can also have a
default value. Thus, we need a mechanism to disambiguate
`ConstGenericArg`s early.
1322: Fixes#1263; diagnostics/feature/wrapper r=CohenArthur a=ndrwnaguib
* wrapping GCC's diagnostics `sorry_at` with a new rust macro named `rust_sorry_at` which accepts `Location` instead of the default `location_t`.
* refactoring previous usage of `sorry_at` to `rust_sorry_at`
Fixes#1263
Co-authored-by: andrewnaguib <24280372+ndrwnaguib@users.noreply.github.com>
1316: Add const generic declaration to AST r=CohenArthur a=CohenArthur
This uses a number of hacks and workarounds to avoid implementing the equivalent HIR node in the same PR. I'll raise issues for each of the `FIXME`s in the code. Needs one commit from #1315 to avoid unecessary conflicts.
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
This also implements all the necessary boilerplate to allow visitors to
work properly. For now, no operation is performed on const generic
params - similarly to lifetimes
1315: Add base for parsing const generic application r=CohenArthur a=CohenArthur
1. Refactor const generic declaration
The default value for const generics now benefits from using the same
function as parsing a regular const generic expression
2. `Parser::parse_type` should not always add errors
In the case that we are parsing a const generic and not a type, we
should not emit bogus errors from `parse_type` such as "unexpected token
in type: LITERAL". Thus, we add a flag to the function to not always
add errors to the error table
3. Figure out how to deal with ambiguities
In the following cases, parsing is ambiguous:
```rust
let a: Foo<N>;
```
What is N? Is it a type to be used as a generic argument? Is it a const
value to be used for a const generic argument? We need to keep both
possibilities and differentiate later during typechecking. We need to
figure out if it would be better to keep the ambiguity in our future
`ConstGenericArg` type (something like Kind::ConstVarOrType) or modify
our current `AST::Type` to maybe get differentiated later as a const
variable, which seems more annoying.
Finally, since the const evaluation is not implemented yet, we are
getting some bogus errors in the testcase. This commit simply serves as
a necessary base: parsing const generics before we can apply them.
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
1308: Fix formatting error on 32-bits targets r=CohenArthur a=dkm
Printing size_t as [unsigned] long (%ld or %lu) raises warnings on 32-bits
targets. As the GCC pretty printer doesn't have the equivalent of libc's %z/%zu,
fix all formats to use unsigned long and cast values.
refs #1229
Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
Co-authored-by: Rainer Orth <ro@gcc.gnu.org>
Co-authored-by: Marc Poulhiès <dkm@kataplop.net>
1. Refactor const generic declaration
The default value for const generics now benefits from using the same
function as parsing a regular const generic expression
2. `Parser::parse_type` should not always add errors
In the case that we are parsing a const generic and not a type, we
should not emit bogus errors from `parse_type` such as "unexpected token
in type: LITERAL". Thus, we add a flag to the function to not always
add errors to the error table
3. Figure out how to deal with ambiguities
In the following cases, parsing is ambiguous:
```rust
let a: Foo<N>;
```
What is N? Is it a type to be used as a generic argument? Is it a const
value to be used for a const generic argument? We need to keep both
possibilities and differentiate later during typechecking. We need to
figure out if it would be better to keep the ambiguity in our future
`ConstGenericArg` type (something like Kind::ConstVarOrType) or modify
our current `AST::Type` to maybe get differentiated later as a const
variable, which seems more annoying.
Finally, since the const evaluation is not implemented yet, we are
getting some bogus errors in the testcase. This commit simply serves as
a necessary base: parsing const generics before we can apply them.
1313: Parse const generics properly r=CohenArthur a=CohenArthur
Closes#1301
~~Needs #1312, so only review the last commit~~
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
Printing size_t as [unsigned] long (%ld or %lu) raises warnings on 32-bits
targets. As the GCC pretty printer doesn't have the equivalent of libc's %z/%zu,
fix all formats to use unsigned long and cast values.
refs #1229
Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
Co-authored-by: Rainer Orth <ro@gcc.gnu.org>
1312: Refactor generic parameter parsing and report order errors r=CohenArthur a=CohenArthur
Closes#1311
This allows us to parse lifetimes and types (and later const generics)
in any order without necessarily erroring out for the wrong reason. It also simplifies the
code greatly and makes it easier to modify.
This also removes an unused duplicate `parse_generic_params` function
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
1296: Ast dump trait impl r=CohenArthur a=CohenArthur
Needs #1295
This adds the dumping of trait implementations for types. However, it is incomplete as I don't believe we can yet handle associated types and associated constants properly? Am I looking in the wrong place?
Will dig deeper, but opening for any early review.
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
This allows us to parse lifetimes and types (and later const generics)
in any order without necessarily erroring out. It also simplifies the
code greatly and makes it easier to modify.
Finally, this commit removes an unused duplicate parse_generic_params function
1307: Handle super and crate in path resolution r=CohenArthur a=philberty
This patch completely reimplements our name resolution process for Paths in
general. This patch gets rid of the old Resolver::Definition structures
which were used so that we can map patterns back to LetStmts and establish
an hierarchy of nodes. This was not nessecary and complicated name/type
resolution.
TypePaths and PathInExpression are similar but have a slightl tweak in the
order they lookup the relevant scopes for types. But overall work the same.
There are several cases of paths you must consider in type resolution:
- i32 (simple type path)
- Self::A (associated type reference)
- mod::foo::impl_item() (reference to impl item)
- super::foo (reference to item)
- crate::foo
- T::bound()
In name resolution we cannot always fully resolve a path but have to rely
on the type-resolution to fully resolve a path as it may require careful
thought. For example a path like:
mod::foo::item()
might be for a generic foo<T>(), which might have two specialized impl
blocks so the best the name resolution can do is resolve mod::foo then
leave it up to the type resolution to figure out which item this is. We
might have i32 which is just a simple lookup.
Apart from that this patch introduces a module parent child hierachy so
that on paths such as super::foo we resolve super to be our parent module
scope then foo can be resolved with the lookup in the items for that
module.
More over this patch gets rid of some but not all of the awkward name
canonicalization to try and patch paths directly. More cleanup is still
needed here to make the name resolution step easier to read. This was
notable in the Qualified path handling where we can now rely on the type
resolver to setup the associated types properly rather than the name
resolver requiring us to resolve this directly.
Fixes#1251#1230
Addresses #1227#1153
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
1286: gccrs const folding: port over cp_walk_subtrees() r=CohenArthur a=abbasfaisal
Card: [Link](https://github.com/Rust-GCC/gccrs/projects/16#card-82441327)
Most of TREE_CODEs in the original function belonged to cp/cp-tree.def which have been removed so this ported function is a lot smaller.
Co-authored-by: Faisal Abbas <90.abbasfaisal@gmail.com>
1309: Fix lexing of empty comments continuing till next line r=CohenArthur a=nirmal-j-patel
Empty comments (comments without any characters including spaces after //) had a bug during lexing. The lexer did not recheck the current character after skipping / characters. When there was no character after //, the lexer skipped the next newline character. This caused lexer to count the next line as a part of the comment to. This commit fixes this bug by rechecking current character after skipping two / characters.
Fixes#1306
Signed-off-by: Nirmal Patel <nirmal@nirmal.dev>
Co-authored-by: Nirmal Patel <nirmal@nirmal.dev>
Empty comments (comments without any characters including spaces after
//) had a bug during lexing. The lexer did not recheck the current
character after skipping / characters. When there was no character after
//, the lexer skipped the next newline character. This caused lexer to
count the next line as a part of the comment to. This commit fixes this
bug by rechecking current character after skipping two / characters.
Signed-off-by: Nirmal Patel <nirmal@nirmal.dev>
This patch completely reimplements our name resolution process for Paths in
general. This patch gets rid of the old Resolver::Definition structures
which were used so that we can map patterns back to LetStmts and establish
an hierarchy of nodes. This was not nessecary and complicated name/type
resolution.
TypePaths and PathInExpression are similar but have a slightl tweak in the
order they lookup the relevant scopes for types. But overall work the same.
There are several cases of paths you must consider in type resolution:
- i32 (simple type path)
- Self::A (associated type reference)
- mod::foo::impl_item() (reference to impl item)
- super::foo (reference to impl item)
- crate::foo
- T::bound()
In name resolution we cannot always fully resolve a path but have to rely
on the type-resolution to fully resolve a path as it may require careful
thought. For example a path like:
mod::foo::item()
might be for a generic foo<T>(), which might have two specialized impl
blocks so the best the name resolution can do is resolve mod::foo then
leave it up to the type resolution to figure out which item this is. We
might have i32 which is just a simple lookup.
Apart from that this patch introduces a module parent child hierachy so
that on paths such as super::foo we resolve super to be our parent module
scope then foo can be resolved with the lookup in the items for that
module.
More over this patch gets rid of some but not all of the awkward name
canonicalization to try and patch paths directly. More cleanup is still
needed here to make the name resolution step easier to read. This was
notable in the Qualified path handling where we can now rely on the type
resolver to setup the associated types properly rather than the name
resolver requiring us to resolve this directly.
Fixes#1251#1230
Addresses #1227#1153
This adds a module scope stack to the resolver class such that we don't
have to continually update our constructors but are able to track it as
part of this context class instead.
Addresses #1227
1299: rust/lex: skip broken string expression r=philberty a=liushuyu
- rust/lex: skip broken string expression and unstuck the parser when it could not advance
should fix#1297
1300: docker: Fix GCCRS_BUILD info r=CohenArthur a=CohenArthur
Sometimes, the GCCRS_BUILD file would end up empty. I believe this is
due to how Dockerfiles work in that there was a "race condition" between
the two `RUN` commands. Hopefully this should fix it.
Co-authored-by: liushuyu <liushuyu011@gmail.com>
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
Sometimes, the GCCRS_BUILD file would end up empty. I believe this is
due to how Dockerfiles work in that there was a "race condition" between
the two `RUN` commands. Hopefully this should fix it.
1295: AST Dump impl traits r=CohenArthur a=CohenArthur
This adds proper AST formatting for inherent impl blocks and traits.
This does not handle trait impls yet (`impl Trait for Type`) but it should be really easy to refactor and add.
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
1290: Reformat copyright header in rust-parse-impl.h r=philberty a=philberty
1291: Fix bad impl item overlap check r=philberty a=philberty
This issue here was the equality checks for reference
and pointer types did not check the mutability.
Fixes#1289
1294: Add new mappings for items within a module r=philberty a=philberty
This patch adds two new interfaces to the mappings class.
- Lookup the child items within a module
- Lookup the parent module id from the child item id
Each of these API's are going to be required so that we can resolve two new
types of path segment:
super::foo::bar
Where we need to be able to lookup the super module node id from the
current scope node id. To then lookup the children within that scope. The
other path is simpler such as: crate::foo::bar. Where we lookup the items
within the current Crate NodeId and follow on as normal.
Addresses #1227
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
1292: Add name resolution to for loops r=philberty a=philberty
This just adds basic name resolution and hir lowering for
the loop. Eventually we will make all Loops into a single
HIR::LoopExpr but for now its really useful having a separate
visitor to implement this to avoid regressions in the short
term.
Addresses #869
1293: Fixup name canonicalization for impl blocks r=philberty a=philberty
When we generate the path for impl items we need to base this of the Self
type but this was ignoring cases like pointers, references or slices. This
meant generic slices had the same path has generic pointers etc. The only
reason we didn't end up with a linker symbol clash is due to the symbol
hash.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
This patch adds two new interfaces to the mappings class.
- Lookup the child items within a module
- Lookup the parent module id from the child item id
Each of these API's are going to be required so that we can resolve two new
types of path segment:
super::foo::bar
Where we need to be able to lookup the super module node id from the
current scope node id. To then lookup the children within that scope. The
other path is simpler such as: crate::foo::bar. Where we lookup the items
within the current Crate NodeId and follow on as normal.
Addresses #1227
When we generate the path for impl items we need to base this of the Self
type but this was ignoring cases like pointers, references or slices. This
meant generic slices had the same path has generic pointers etc. The only
reason we didn't end up with a linker symbol clash is due to the symbol
hash.
Thse types are not equal unless their mutabilities are equal so this patch
adds in the missing if statements to ensure that two pointers or two
references account for their mutability.
Fixes#1289
1284: Marklive: support arrayindex r=philberty a=thomasyonug
This makes `MarkLive` support `HIR::ArrayIndex` and adds a related test case.
Co-authored-by: Thomas Young <wenzhang5800@gmail.com>
1283: const folding in gccrs: remove ConstCtx class. r=philberty a=abbasfaisal
Card: [Link](https://github.com/Rust-GCC/gccrs/projects/16#card-82300522)
This class had potential to hinder porting further const folding code from C++. This edit makes it easy to copy code from constexpr.cc to rust-constexpr.cc and so on.
Structs `constexpr_ctx` and `constexpr_global_ctx` have been copied as well as to keep `constexpr_ops_count` after removing the class. These structs will be filled further as the port carries on. The prototypes inside ConstCtx have been copied over to rust-constexpr.cc as static prototypes.
Co-authored-by: Faisal Abbas <90.abbasfaisal@gmail.com>
1280: Str's have the same layout as [T] r=philberty a=philberty
Raw strings have a very specific type layout which maps over to Slices. It
also has very specific type checking rules so for example:
let a:&str = "TEST 1";
let b:&str = &"TEST 2";
Are both the same type this is likely to be for all DST's but lets do one
rule at a time.
Fixes#1023#1271
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
1281: Add testcase to prove bug is fixed r=philberty a=philberty
This bug was fixed in commit cb4d935508
with related PR #1223
The issue is that associated types get updated depending on the context
they are used so we need to monomorphize the types when we can so that we
don't then throw off the rest of type checking with bogus errors like this.
Fixes#1237
1282: Add build badges for marks build-farm r=philberty a=philberty
Fixes#1236
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
This class has potential to hinder porting further const folding code from C++.
So this edit makes it easy to copy code from constexpr.cc to rust-constexpr.cc
and so on.
Signed-off-by: Faisal Abbas <90.abbasfaisal@gmail.com>
This bug was fixed in commit cb4d935508
with related PR #1223
The issue is that associated tpyes get updated depending on the context
they are used so we need to monomorphize the types when we can so that we
don't then throw off the rest of typechecking with bogus errors like this.
Fixes#1237
1278: Remove inside_loop parameter r=philberty a=philberty
The parameter was a hack used to support error handling cases
in Break and Continue expression's but this is no longer required.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
Raw strings have a very specific type layout which maps over to Slices. It
also has very specific type checking rules so for example:
let a:&str = "TEST 1";
let b:&str = &"TEST 2";
Are both the same type this is likely to be for all DST's but lets do one
rule at a time.
Fixes#1023#1271
We already have a Context object containing info about loop contexts. This
removes the need for us to pass this variable around simplifying the type
resolution code. The parameter was a hack used to support error handling
cases in Break and Continue expression's but this is no longer required.
1275: Remove old hack to handle type inferencing in untyped decalred bindings r=philberty a=philberty
This reverts the code fix for 89631998d2
but keeps the test-case proving that we have not regressed. More info in
the commit message.
Fixes#1274#1273
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
1279: Implement type checking for the `IfLet` expression. r=philberty a=antego
Addresses #1177.
This change implements the type check for the `IfLet` expression. This is the adapted type checking code from the `MatchExpr`.
Tested on this code
```
enum E {
X(u8),
}
fn main() -> i32 {
let mut res = 0;
let v = E::X(4);
if let E::X(n) = v {
res = n;
}
0
}
```
Compilation finishes without errors.
Next is the implementation of the code generation but I'll need help to find where it's located.
Co-authored-by: antego <antego@users.noreply.github.com>
In the case where you define let a; with no type to then use this binding
and let type inferencing infer the type we used this code to implicitly
generate a new type binding to the resolved node id of the the lvalue.
This was very dangerous and was always meant to be a stop gap untill we
supported more of type inferencing. The issue here was that we were badly
overriting a function types within the type-context which hits an ICE
in the method resolution code which is expecting function TyTy's within
in order to match methods correctly.
Fixes#1274#1273
1277: Reuse index_expr_ty type r=philberty a=philberty
This is a small refactor to remove duplicating the work in type checking
the index expression.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
1276: Wrapup testing code within CHECKING_P guards r=philberty a=philberty
I seem to be having build issues locally with missing ASSERT macros but works when they are wrapped in CHECKING_P guards.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
1268: Fix Slice Type Layout r=philberty a=philberty
Slices in Rust are represented by TypePaths such as '[i32]'. Though if you
actually try to use this explicit type-path you will hit errors such as
this type has an unknown size at compile time. This is because this is
actually what Rust calls a dynamically sized type. This means when you use
types such as: '&[i32]' it is not actually a reference type to a slice. Its
a slice in its entirety this means for lack of a better word when you use
'*const [i32]' or '&mut [i32]' we end up actually passing around a struct
by value _not_ at pointer/reference to it.
This patch changes the type-layout so that we handle this layout change
properly. This patch will also need to be applied to str types which I
believe have a similar layout for safety.
The patch also sets up TYPE_MAIN_VARIANT so that we can avoid unnessecary
view_convert_expressions between *const [i32] and &mut [i32] which will
have the same layout.
Reference:
https://doc.rust-lang.org/reference/dynamically-sized-types.htmlhttps://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=672adac002939a2dab43b8d231adc1dcFixes#1232
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
1241: Implement name resolution for the IfLet expression. r=philberty a=antego
Addresses #1177.
Guidance from the ticket #1177:
> You should be able to copy how we do name resolution for the if blocks from that file. Though if let statements add a new binding and scope level so you need to declare the pattern so you should be able to see how that is done from rust-ast-resolve-stmt.
I don't understand how to modify the block expression resolution so that it can handle the `IfLet` expression. For now, I copied the code from the `MatchExpr` resolution. Not sure how to test it either and what is the desired expected result of the name resolution so I just hope that reviewers will spot the errors.
I created this PR in order to get some guidance about how to proceed with it. Thanks!
Co-authored-by: antego <antego@users.noreply.github.com>
Slices in Rust are represented by TypePaths such as '[i32]'. Though if you
actually try to use this explicit type-path you will hit errors such as
this type has an unknown size at compile time. This is because this is
actually what Rust calls a dynamically sized type. This means when you use
types such as: '&[i32]' it is not actually a reference type to a slice. Its
a slice in its entirety this means for lack of a better word when you use
'*const [i32]' or '&mut [i32]' we end up actually passing around a struct
by value _not_ at pointer/reference to it.
This patch changes the type-layout so that we handle this layout change
properly. This patch will also need to be applied to str types which I
believe have a similar layout for safety.
The patch also sets up TYPE_MAIN_VARIANT so that we can avoid unnessecary
view_convert_expressions between *const [i32] and &mut [i32] which will
have the same layout.
Reference:
https://doc.rust-lang.org/reference/dynamically-sized-types.htmlhttps://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=672adac002939a2dab43b8d231adc1dcFixes#1232
1266: Make TyTy::BaseType::destructure recursive r=philberty a=philberty
In the case of Generic Associated Types we end up
placeholders->projections->generic-param->i32
This means we need to keep destructuring the TyTy object until we finally
get the real type at the end. In order to do this safely we need to ensure
we add in recursion limits and apply this where it matters such as
compiling types in general too.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
In the case of Generic Associated Types we end up
placeholders->projections->generic-param->i32
This means we need to keep destructuring the TyTy object until we finally
get the real type at the end. In order to do this safely we need to ensure
we add in recursion limits and apply this where it matters such as
compiling types in general too.
1267: Marklive: support match expr r=philberty a=thomasyonug
This makes `MarkLive` support `HIR::MatchExpr` and adds a related test case.
Co-authored-by: Thomas Young <wenzhang5800@gmail.com>
1265: Canonicalize types based on hashing than HirIds and TyTy equality r=philberty a=philberty
This patch updates how we canonicalize the types. The old method was not
able to handle more complex cases involving generic associated types. So
this now uses a moe generic hashing system which now speeds up the lookups.
The commit message gives much more detail here.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
When we compile types for GCC we need to make sure we canonicalize them,
this means that for any user defined type such as Structs or Tuples we want
all expressions or declarations to use the same tree. Even if we have
duplicate tree's we can end up confusing the middle-end and lose out on
optimizations as we will be using view_convert_exprs to maintain the
consistancy which will marshall between the objects unnessecarily.
The old method for doing this kept mappings of HirIds which was fine for
simple cases but when generics are involved new Id's are generated so this
meant we ended up having a vector of pairs {TyTy::BaseType, tree} and we
did a liner search to find the relevant TyTy::BaseType that we equaled to.
This was not only slow but did not handle the cases for generic associated
types or nested generics. So we needed a more general faster implementation
therefore hashing. This patch takes the gcc/tree.h type_hash_canon code
and adds in hashing for RECORD and UNION types. This means we will generate
a duplicate type then hash it and look for an existing type.
This patch will also allow us to fix how we implement monomorphization of
functions by nesting the hashes behind DefId's.
1258: Report privacy errors on explicit types r=CohenArthur a=CohenArthur
~~Needs #1255, so skip reviewing the first commit or wait for it to be merged~~ Done and rebased :)
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
privacy: Circumvent weird behavior about inference types for now
The issue we're facing is detailed in #1260. It's not necessary to fix
now to have a good type privacy base
privacy: PrivacyReporter: Handle projections and placeholders
1255: Privacy report expressions r=CohenArthur a=CohenArthur
This adds privacy reporting to all expression types inside our HIR. It also restricts the `PrivacyReporter` visitor to `HIR::Expression`s and `HIR::Stmt`s as a lot of the previous types did not need to be visited.
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
1252: privacy: Handle calls to functions defined in previous ancestors r=CohenArthur a=CohenArthur
Previously, we would only check if `current_module` was a direct
descendant of the item's module. However, we also need to visit each of this
item's module's children recursively.
1254: issue #1233: Do not rely on the endianness for testing r=CohenArthur a=CohenArthur
This testcase uncovered a very interesting bug requiring a refactor of
our `AST::Block` class (#1253), but should still be fixed/adapted in the
meantime so that the BE builds on our buildbot do not fail.
I've tested this newtestcase with a compiler from 74e836599c, which was the commit pointed out in #1233. The same ICE would still trigger, so I can safely say that this is a different exemple showing the same underlying issue. I'll work on fixing #1253 but it is a refactor we need to think about a little.
This should make all the architectures on buildbot happy again!
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
1250: Support extern-blocks defined within blocks r=philberty a=philberty
This adds support for declaring extern blocks within blocks. So this adds
the missing name resolution visitor for the statement context. Then we
extract out a common extern block hir lowering function for both contexts.
The type resolution step needs to be updated to be like the code-generation
step so that we can solve these paths in a query rather than a top-down
approach but this is a known issue.
The final step was to support query-based compilation to extern functions.
Fixes#976
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
This testcase uncovered a very interesting bug requiring a refactor of
our `AST::Block` class (#1253), but should still be fixed/adapted in the
meantime so that the BE builds on our buildbot do not fail.
Previously, we would only check if `current_module` was a direct
descendant of the item's module. However, we also need to visit each of this
item's module's children recursively.
This adds support for declaring extern blocks within blocks. So this adds
the missing name resolution visitor for the statement context. Then we
extract out a common extern block hir lowering function for both contexts.
The type resolution step needs to be updated to be like the code-generation
step so that we can solve these paths in a query rather than a top down
approach but this is a known issue.
The final step was to support query based compilation to extern functions.
Fixes#976
1246: Report simple privacy violations r=CohenArthur a=CohenArthur
This adds a base visitor for reporting basic privacy violations. For now, only function calls are implemented.
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
1248: Support RangePatterns in matches r=dafaust a=dafaust
Add name resolution, lowering, type checking and compilation for `RangePattern`s in matches.
Co-authored-by: David Faust <david.faust@oracle.com>
1244: Allow match on integer and char types r=dafaust a=dafaust
Enable compiling match expressions on other primitive types like `i32`, `usize` and `char`.
Co-authored-by: David Faust <david.faust@oracle.com>
This patch enables compiling match expressions for other primitive
types, like int and char. However, we cannot currently compile matches
on floats; CASE_LABEL_EXPR doesn't support floating-point types.
1240: Change Artihmetic Operation to be a cast type operation r=philberty a=philberty
Arithmetic operations like this need a cast to support the range of integer
types which are allow here.
Fixes#1234
1243: Allow cast of integers to pointers r=philberty a=philberty
This adds the cast rules of integer types and integer inference variables
to pointers. The code-generation needed to remove the bad assertion that
all integer literals were always going to be of type integer. This also
needed a tweak to a bad port from the cp/constexpr.cc code which assumed
that all integer_cst of pointer types would be a zero pointer which was
used to detect cases of bad method pointers in CPP which we does not apply
here.
see gcc/cp/constexpr.cc:6564-6488
Fixes#1226
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
1242: Remove undefined behavior in context vector r=CohenArthur a=CohenArthur
This also fixes the undefined behavior. Once again we are hurt by
`std::vector<T>::back()` returning references and not
pointers/`std::optional<T>`s!
The cause of the bug was some overzealous popping from the context
vector in block expressions. The amount of calls to `pop_context` is now
the same as the amount of calls to `push_context`
Closes#1233
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
This adds the cast rules of integer types and integer inference variables
to pointers. The code-generation needed to remove the bad assertion that
all integer literals were always going to be of type integer. This also
needed a tweak to a bad port from the cp/constexpr.cc code which assumed
that all integer_cst of pointer types would be a zero pointer which was
used to detect cases of bad method pointers in CPP which we does not apply
here.
see gcc/cp/constexpr.cc:6564-6488
Fixes#1226
This also fixes the undefined behavior. Once again we are hurt by
`std::vector<T>::back()` returning references and not
pointers/`std::optional<T>`s!
The cause of the bug was some overzealous popping from the context
vector in block expressions. The amount of calls to `pop_context` is now
the same as the amount of calls to `push_context`
1238: Assigning members to structures is a coercion site r=philberty a=philberty
Fix missing coercion site call which allows the coecion of a reference to
a pointer type.
Fixes#1235
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
1228: Fix match tests on 32bit systems r=philberty a=philberty
Printing i64's on 32bit systems requires the proper format specifier
this amends these test cases to 32bit integers so %i works as expected.
I was able to use gdb to verify that these values are computed properly
from the structure on 32 bit systems.
Keeping the structures as i32 we can ignore platform-specific format
specifiers.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
Printing i64's on 32bit systems requires the proper format specifier
this amends these testcases to 32bit integers so %i works as expected.
I was able to use gdb to verify that these values are computed properly
from the structure.
1219: Add `Optional<T>` type r=CohenArthur a=CohenArthur
This adds a tagged union to try and simulate a sum type. This is safer and more ergonomic
than one of the two alternatives we're currently using in the compiler:
1. Storing a raw pointer, which can be `nullptr` or valid
This is wildly unsafe, and usable in conjunction with local references, stack
variables, or pointers managed elsewhere, which can cause crashes, hard to
debug issues or undefined behavior. Likewise, if you do not check for the
pointer's validity, this will cause a crash.
2. Storing an extra boolean alongside the object
This causes implementors to use a "dummy object": Either an empty version or
an error version. But what happens if what you really wanted to store was
the empty or error version? You can also easily incorporate logic bugs if you
forget to check for the associated boolean.
The `Optional<T>` type has the same "ergonomic" cost: You need to check
whether your option is valid or not. However, the main advantage is that it
is more restrictive: You can only acess the member it contains "safely".
It is similar to storing a value + an associated boolean, but has the
advantage of making up only one member in your class.
You also benefit from some helper methods such as `map()`.
You also get helper functions and operator overloading to "seamlessly"
replace raw pointer alternatives.
```c++
MyType *raw_pointer = something_that_can_fail();
if (raw_pointer)
raw_pointer->method();
// or
Optional<MyType> opt = something_that_can_fail2();
if (opt)
opt->method();
// equivalent to
if (opt.is_some())
opt.get().method();
```
This will be very useful for parent modules when resolving `super` paths :)
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
1222: Destructure our generics, placeholers or projections during coercion r=philberty a=philberty
When we coerce types we need to destructure from the generics in order to
apply these coercion rules correctly or we end up returning a bad
error_mark_node.
This was found while fixing https://github.com/Rust-GCC/gccrs/pull/1220
1223: Add new monomorphize_clone interface r=philberty a=philberty
This interface is required when we monomorphize since types might be
placeholder -> projection -> param -> actual-type
This gives us a clean clone interface to destructure this into its actual
type. This is important so for example if we have a generic trait function
and resolve the function for a specific set of generics we update the
associated types. This works, then when we go to substitute the same
generic trait again the placeholders are again updated throwing off the
typing for the first type.
There is more cleanup we can do once this PR is in to make this part of
the general monomorphization path so that we sort out these as part
of the fntype
Fixes#1133
1225: macros: Error out when repeating metavars which refer to repetitions r=CohenArthur a=CohenArthur
In the case were a repeting metavar was used as a regular metavar ($var
instead of $($var)* for example), the compiler would crash on an
assertion that $var was only repeating once. We should instead error out
and point to the user that this is probably not what they intended to
do.
Some spurious errors are emitted, but improving them requires a major refactor of the SubstitutionContext file to report error states before.
Closes#1224
Thanks to `@bjorn3` for pointing this out.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
Co-authored-by: CohenArthur <arthur.cohen@epita.fr>
In the case were a repeting metavar was used as a regular metavar ($var
instead of $($var)* for example), the compiler would crash on an
assertion that $var was only repeating once. We should instead error out
and point to the user that this is probably not what they intended to
do.
When we coerce types we need to destructure from the generics in order to
apply these coercion rules correctly or we end up returning a bad
error_mark_node.
1220: Ensure the coercion sites are applied correctly on unions r=philberty a=philberty
When we construct a union, we were wrongly compiling the constructor
without taking into account the associated union index. This meant we
if you were constructing a union using any other field than the first one
you had a bad coercion type check resulting in a silent failure of generating
an error_mark_node.
This was caught using an assertion to ensure there is no error on coercion site but it is valid
to have errors from coercion sites.
1221: Ensure we don't return error_mark_node for loop expressions r=philberty a=philberty
Loop expressions can return a value even if its a unit-type so we must
ensure we don't return an error_mark_node for the eventual coercion site
for the unit-type case.
The offending test-case was: rust/compile/torture/loop7.rs
This was found while fixing #1220
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
This interface is required when we monomorphize since types might be
placeholder -> projection -> param -> actual-type
This gives us a clean clone interface to destructure this into its actual
type. This is important so for example if we have a generic trait function
and resolve the function for a specific set of generics we update the
associated types. This works, then when we go to subsitute the same
generic trait again the placeholders are again updated throwing off the
typing for the first type.
Fixes#1133
Loop expressions can return a value even if its a unit-type so we must
ensure we don't return an error_mark_node for the eventual coercion site
for the unit-type case.
Offending test-case was: rust/compile/torture/loop7.rs
When we construct a union, we were wrongly compiling the constructor
without taking into account the associated union index. This means we ended
up trying to coerce the wrong field which was always zero here which
resulted in a silent failure by returning error mark node.
The offending test case was: gcc/testsuite/execute/torture/slice1.rs
1215: Report `pub restricted` violations r=CohenArthur a=CohenArthur
Needs #1202. The only commit worth reviewing in the meantime is [c229c7f](c229c7f891)
This visitor allows us to report invalid restrictions in `pub(restricted)` visibilities. I've added documentation and an example to the visitor to explain the expected behavior.
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
privacy: restricted: Add base for pub(restricted) violations reporting
This commit adds a new visitor whose purpose is to report `pub restricted`
violation: The path used in a `pub restricted` privacy can only be an
ancestor path, which needs to be checked.
1217: Fix size used in unsized adjustments r=philberty a=philberty
When we coerce from an array to a slice we take the full capacity of the
array as the size to the FatPtr slice object but this was off by one. This
The TYPE_MAX_VALUE is not the correct method of accessing this but instead
it needs to take into account other values to get the correct HOST_WIDE_INT
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
This also fixes the missing kind in HIR::Visibility.
Having both `pub` and `pub restricted` as a single variant in the
HIR::Visibility::Kind enum was a mistake, as it cause the path resolver to
be triggered for `pub` visibilities which do not refer to any paths.
Finally, erroneous calls to Visibility::create_error() are removed.
This caused a lot of ICEs now that the Visibility lowering logic is
fixed
When we coerce from an array to a slice we take the full capacity of the
array as the size to the FatPtr slice object but this was off by one. This
The TYPE_MAX_VALUE is not the correct method of accessing this but instead
it needs to take into account other values to get the correct HOST_WIDE_INT
1205: Take advantage of OBJ_TYPE_REF'S in dyn calls r=philberty a=philberty
OBJ_TYPE_REF's are the gcc nodes that signify that this is a virtual call
which gives a hint to the optimizers for devirtualization. This patch also enhaces
the dyn object to hold an array of pointers instead of multiple name fields of addresses.
Fixes#996
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
OBJ_TYPE_REF's are the gcc nodes that signify that this is a virtual call
which gives a hint to the optimizers for devirtualization.
Fixes#996Fixes#854
1206: Use correct format specifiers for unisnged HOST_WIDE_INT r=philberty a=philberty
The code here was wrongly assuming the unsigned long interface which is not
correctly for all targets.
1209: Allow match on boolean expressions r=philberty a=dafaust
Enables compiling `match` expressions where the scrutinee is a boolean expression. Also enable compiling match arms with Literal patterns, since `true` and `false` literals are commonly used with matches on boolean expressions.
Fixes: #1207
1211: Preserve inside_loop context when type checking match r=philberty a=dafaust
Previously, we would lose the context of being inside a loop when compiling a `match`.
This would lead to incorrect error messages like "cannot 'break' outside of a loop" when
trying to break out of a loop from within a `match` expression.
Fixes: #1196
1212: intrinsic: add breakpoint intrinsic r=philberty a=liushuyu
- intrinsic: add breakpoint intrinsic
Addresses #658
1213: intrinsic: add rotate_left and rotate_right intrinsic r=philberty a=liushuyu
- intrinsic: add rotate_left and rotate_right intrinsic
Address #658
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
Co-authored-by: David Faust <david.faust@oracle.com>
Co-authored-by: liushuyu <liushuyu011@gmail.com>
1214: Replace SSH cloning with HTTPS cloning in README.md r=philberty a=Zopolis4
HTTPS cloning is the standard across many projects as well as being simpler and more beginner-friendly.
Signed-off-by: Maximilian Downey Twiss <creatorsmithmdt@gmail.com>
Co-authored-by: Zopolis4 <creatorsmithmdt@gmail.com>
1197: Support recursive coercion sites r=philberty a=philberty
There are two changes are part of this PR one where we update the address_expression
helper to take a ptrtype tree. Since the default build_address_expr_loc was automatically
building a pointer type of the TREE_TYPE of the operand which is not correct since we
sometimes want REFERENCE_TYPES instead of POINTER_TYPES.
The 2nd commit enhances the coercion_site code to recursively walk the tree and their
types to handle coercions to dyn traits or do array bounds checking etc. This gets rid of
the get_root hack used and cleans up the code in general.
Fixes#1146
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
1199: Add new as_name interface for Dynamic types r=philberty a=philberty
The Gimple names of our dyn trait objects were looking like:
const struct dyn [HIR Trait: FnLike->[C: 0 Nid: 31 Hid: 38 Lid: 13] [(FN call ), ]<Self, &isize, &isize>] & const f
This is a horrible name but useful for debugging this patch fixes this so
we have a seperate naming for generating the type. So now it looks like:
const struct dyn [FnLike<Self, &isize, &isize>] & const f
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
1201: Generic functions should not be TREE_PUBLIC r=philberty a=philberty
Generic functions cannot be public since the symbols could overlap in
linking other crates reusing the same generic. The other benefit here is
that when optimizations are turned on we can eliminate more code since the
symbol does not _need_ to be public.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
1191: Resolve simple paths in use items r=CohenArthur a=CohenArthur
In order to resolve `SimplePath`s, we have to expand all paths present
in a `UseDeclaration` and resolve them. For example, we want to resolve
two paths with the following statement `use foo::bar::{baz, bul}`:
`foo::bar::baz` and `foo::bar::bul`
This also removes the prelude inclusion (`use std::prelude::v1::*`)
since we cannot resolve it (yet!)
Needs #1172 to compile
Adresses #1159
Adresses #1187
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
Generic functions cannot be public since the symbols could overlap in
linking other crates reusing the same generic. The other benifit here is
that when optimizations are turned on we can eliminate more code since the
symbol does not _need_ to be public.
The Gimple names of our dyn trait objects were looking like:
const struct dyn [HIR Trait: FnLike->[C: 0 Nid: 31 Hid: 38 Lid: 13] [(FN call ), ]<Self, &isize, &isize>] & const f
This is a horrible name but useful for debugging this patch fixes this so
we have a seperate naming for generating the type. So now it looks like:
const struct dyn [FnLike<Self, &isize, &isize>] & const f
Our code for coercion sites are handled in two places once where we do the
type-checking portion and one where we do the code-generation. This makes
the code-generation piece recursive so that we apply the behaviours
consistantly when types need checked or converted.
Fixes#1146
1188: Support align and packed repr layout on structs r=dafaust a=dafaust
This is a start at handling the various layout options supported by Rust, beginning with `#[repr(align(N))]` and `#[repr(packed(N))]`, on structs and tuple structs.
There are several other layout options which remain to be supported such as `#[repr(C)]`, `#[repr(transparent)]`, combinations e.g. `#[repr(C, packed(2))]`, as well as layouts on union and enum types.
Fixes: #915
Co-authored-by: David Faust <david.faust@oracle.com>
1194: Add support for transmute r=philberty a=philberty
This PR adds support for the transmute intrinsic by utilizing the convert
expression code. It also fixes a bug with our coercion rules which miss
two chances for inference variables to resolve slices and arrays.
Fixes#1130
Addresses #658
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
In order to resolve `SimplePath`s, we have to expand all paths present
in a `UseDeclaration` and resolve them. For example, we want to resolve
two paths with the following statement `use foo::bar::{baz, bul}`:
`foo::bar::baz` and `foo::bar::bul`.
This also removes the prelude inclusion (`use std::prelude::v1::*`)
since we cannot resolve it (yet!)
1190: Fix ICE in reachability class and refactor associated types code r=philberty a=philberty
There are several fixes going on to solve these issues which overlap with one
another so it seemed best to pack them within the same PR.
The main issue for #1128 was that we did not resolve a trait when it was unused
leading to us hitting the ICE in the privacy pass. Since the type check context was
empty for the trait since it was not resolved. To fix this we needed to refactor the
trait resolver to resolve the trait as part of iterating the crate. This resulted in some
regressions in the testsuite so this is why we need the the other commits. Which
required us to finally perform the refactor specified in #1105 to fix these.
Fixes#1105#1128#1132
1192: Add an assertion to avoid peeking when the stack is empty r=philberty a=philberty
This will ensure we get a proper ICE instead of memory corruption/segv.
Addresses #1130
1193: Remove unused parameter caller from generating Call expressions r=philberty a=philberty
Within const context the fncontext maybe empty which in turn results in a
segv for generating const calls which will be evaluated by the const-expr
code anyway.
Addresses #1130
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
1172: Resolve visibility paths r=CohenArthur a=CohenArthur
This tackles the remaining issues in #1158. ~~It also contains the commit from #1168 so you should wait for bors to merge that before reviewing it :D~~ done
The paths get resolved but their `NodeId`s are not used in the privacy visibility resolver yet.
Closes#1158
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
Within const context the fncontext maybe empty which in turn results in a
segv for generating const calls which will be evaluated by the const-expr
code anyway.
Addresses #1130
During type-resolution we resolve/type-check traits in a query based way.
So when we reference a trait we look it up as required but this left a case
for the privacy pass where the type-context information on the trait when
the trait was not used meant there was no type-checking performed on the
trait.
This patch adds an interface to directly resolve the trait when as we
iterate the crate so we do it as required. There is already code in the
trait resolver to check if we have already type-resolved this trait.
Fixes#1128
From PR #1086 I introduced a new setup_associated_types2 interface which
is used to ensure we handle the complex associated types in libcore slices
but this interface was inconsistant as well as the get_projected_type.
This path refactors the code base to get rid of the old
setup_associated_types interface in favour of this new one. It also removes
the get_projected_type interface which was not going to work either.
Fixes#1105
We missed a case to ensure the substitutions are equal in the is_equal
interface. This becomes important when dealing with generic associated
types since the projections could end up overlapping and we need to
differentiate them by the substitutions and monomorphization.
1189: Add missing `SimplePath`s location r=CohenArthur a=CohenArthur
Sorry to new contributors but I think I've taken all the good first issues we opened yesterday...
Closes#1179Closes#1180Closes#1181Closes#1182
Necessary for #1172
Addresses #1159
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
1184: Fix bad name resolution on path with generic segments r=philberty a=philberty
This fix breaks down into two commits the first commit fixes the issue directly
then the second one fixes the regression that was introduced in the first.
The TLDR for this patch set is that when we resolve the path here:
module::transmute
The name-resolver wronly added the specified generic arguments into the canonical
path meaning that the root segment could not be name-resolved such that during
type resolution we iterate and apply the generic arguments appropriately to the root
segment.
In fixing this it introduced a regression exposing a few more complex issues with
inference variables but for a more complete explanation about that please read the
commit message from ea38a59ee8Fixes#1173
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
A regression was introduced in e476433c45624ec713395c85bcbd410806e90639
this was a tricky bug to fix. There are several fixes here but they all
rely on one another so in order to have a commit which does not introduce
more regressions it seems best to keep these fixes together.
In this patch we remove the check at the end of type resolution to look
for any error type nodes within the type context since this will only ever
produce false postive/duplicate errors. Since any real error will have been
emitted at the time of occurance.
We also fixed a bug in infering the types on a generic type so for example:
struct Foo<A,B>(A,B);
impl<T> Foo<T,T> { ... }
In this example the Self type on the impl block will be Foo<T,T> so in the
code for infering the arguments for the type we simply iterated each of the
generic parameter mappings and if any of them need substitution we generate
implict inference variables for them but in this case the ParamType is T
so generating one for each of these T's will introduce a stay inference
variable which we cannot infer so it will not be used. This patch keeps
a mapping inside SubstitutionRef::infer_substitions to ensure we don't
introduce any extra inference variables than required.
The final fix was around how we clone inference variables, there is a
comment explaining this but we cannot safely clone a inference variables
simply by creating a new object, inference variables are closely tied to
the type-conext so that when we infer the type to be a concrete type we
need to be able to update the reference in memory but simply cloning an
inference variable does not guarentee this to occur. This change ensures
that we create a new implict inference variable and setup the reference
and chain apropirately.
When name-resolving paths we expect the name-resolver must resolve the
root of the path. Such that a path might be
module::type::associated_function
We expect that the name resolution step must be able to resolve the
module::type
Portion of the path, it is permissive to allow everything after that to
fail name resolution as this may require generic arguments of type
inferencing to figure out which associated items are required.
The issue in this referenced issue was that the generic arguments here were
wrongly canonicalized to be part of the root path which meant the segment
could not be name-resolved allowing the type resolution system to perform
the generic specialization.
Fixes#1173
1174: Remove default location for `SimplePath`s r=CohenArthur a=CohenArthur
This removes the default argument for the locus of `SimplePath`s. Addresses #1159
There are a lot of places in the code where it is not possible to insert a "correct" location for these `SimplePath`s: namely, when creating the use statement for the standard library's prelude, or when creating the `SimplePath`s of attributes. I've left a few FIXMEs in these cases because I'm unsure about the proper course of action.
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
1171: Dockerfile: change base image r=philberty a=liushuyu
- Dockerfile: change base image
This commit fixes a recent Docker building error where the GLibc version mismatches.
Co-authored-by: liushuyu <liushuyu011@gmail.com>
1162: CI: catch malformed test cases r=philberty a=liushuyu
- catch malformed test cases and use GitHub Actions' annotation feature to mark the failures
1167: Fix nullptr when resolving the root of a path expression r=philberty a=philberty
When we resolve paths we don't have a _type_, in this scenario there is a
bug in our resolution of this generic function so this means the root_tyty
is nullptr but the offset is non zero so we return nullptr.
Addresses #1132
This test case no longer ICE's but still fails. I have a fix in progress for this
```rust
mod mem {
extern "rust-intrinsic" {
fn transmute<U, V>(_: U) -> V;
}
}
pub trait Hasher {
fn write(&mut self, bytes: &[u8]);
fn write_u16(&mut self, i: u16) {
self.write(&mem::transmute::<_, [u8; 2]>(i))
}
}
pub struct SipHasher;
impl Hasher for SipHasher {
#[inline]
fn write(&mut self, msg: &[u8]) {}
}
```
1168: ast: resolve: Move ResolveItem into its own source file r=CohenArthur a=CohenArthur
Since we need to add new functions to resolve visibilities, we might as well refactor this file before hand :)
1170: Implement macro expansion in `IfExpr`, `IfExprConseqElse`, `IfExprConseqIf`, `IfExprConseqIfLet`. r=CohenArthur a=antego
Addresses #1141. Following up on #1161.
This change adds support for the macros inside the `if` condition expressions.
Things to note:
1. Judging by my research, the `IfExprConseqIfLet` isn't used. The parser treats the syntax `let var = if ...` as a `let` expression followed by `if` expression:

2. I didn't add the macro expansion to the `IfLetExpr...` family of expressions because I wasn't able to write a test case reproducing the missing macro expansion. I've tried the following code
```rust
fn main() -> i32 {
let mut res = 0;
enum E {
X(u8),
Y(u8),
Z(u8),
}
let v = E::Y(12);
if let E::Y(n) = v {
res = 1;
}
0
}
```
which caused the compiler error
```
FAIL: rust/compile/macro43.rs (internal compiler error: in append_reference_for_def, at rust/resolve/rust-name-resolver.h:227)
```
Co-authored-by: liushuyu <liushuyu011@gmail.com>
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
Co-authored-by: antego <antego@users.noreply.github.com>
1166: Support inference of generic parameters on paths behind reference's r=philberty a=philberty
We used a hack in the parser to turn simple cases such as &Foo(..) into:
BorrowExpr
CallExpr(
IdentifierExpr + <Argument-expressions>))
The IdentifierExpr here is parsed as a PathExpression but to simplify
things at the time it seemed logic to see these as identifier expressions
but this is actually a Path and we need to be careful about generic
arguments here. Identifiers are simply identifiers and must not be changed
or coherence of inference variables will become a jumble of inference
variables trying to infer one another inside purely generic code.
This patch leaves the PathInExpressions as Path's instead of trying to be
clever and turn them into identifiers.
Fixes#1165
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
1164: Add `NodeId`s to `SimplePath{Segment}`s r=CohenArthur a=CohenArthur
This is a necessary first step which addresses #1158
I am working on the visibility resolver and simple-path name resolver in parallel and will need those changes.
I'm not sure if the `has_path` method is necessary since we will have `HIR::Visibilities` in the visibility resolver, which will be desugared. Maybe I am doing this wrong and we should be working on `AST::Visibilities` instead?
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
When we resolve paths we don't have a _type_, in this senario there is a
bug in our resolution of this generic function so this means the root_tyty
is nullptr but the offset is non zero so we return nullptr.
Addresses #1132
We used a hack in the parser to turn simple cases such as &Foo(..) into:
BorrowExpr
CallExpr(
IdentifierExpr + <Argument-expressions>))
The IdentifierExpr here is parsed as a PathExpression but to simplify
things at the time it seemed logic to see these as identifier expressions
but this is actually a Path and we need to be careful about generic
arguments here. Identifiers are simply identifiers and must not be changed
or coherence of inference variables will become a jumble of inference
variables trying to infer one another inside purely generic code.
This patch leaves the PathInExpressions as Path's instead of trying to be
clever and turn them into identifiers.
Fixes#1165
1161: Implement macro expansion for ComparisonExpr, LazyBooleanExpr, AssignmentExpr r=CohenArthur a=antego
Following up on https://github.com/Rust-GCC/gccrs/issues/1141
Currently the macro expansion doesn't work for ComparisonExpr, LazyBooleanExpr, AssignmentExpr. To fix this, I just copied the code from the `ArithmeticOrLogicalExpr` and it seemed to work. I don't like the code duplication, happy to try refactoring it into a separate function.
Will work on the macro expansion in the `if` expressions next.
Co-authored-by: antego <antego@users.noreply.github.com>
1160: Refactor name resolver r=CohenArthur a=CohenArthur
This PR splits up the `rust-name-resolver.h` file into source and header. It also removes a bunch of `iterate_*` functions: Some were not used anymore, and some were refactored.
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
1156: tests/attr_cold: fix a typo r=philberty a=liushuyu
- fix a typo in the `rust/compile/attr_cold.rs` file
Co-authored-by: liushuyu <liushuyu011@gmail.com>
1157: Resolve remaining simple visibilites r=CohenArthur a=CohenArthur
Based on #1155, so you can review just the last commit.
This adds the remaining simple visitors for visibility resolving, as well as a helper method for doing so.
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
1155: Add base for visibility resolving r=CohenArthur a=CohenArthur
This adds a new visitor whose aim is to resolve the visibility of each VisItem in a crate. The crux of the implementation will be resolving `pub restricted` items, whose module needs to be resolved using name resolution/path resolution. On top of that, we will need to add a new visitor building a "tree" of modules, with a `accessible_from` or `is_child_of` method: All children of a module get to access its items whose visibility is inherited.
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
1154: Add support for isize and usize type-hints r=philberty a=philberty
This bug turned out to be that we expected a usize for the array capacity
but the specified capacity turned out to be an integer inference variable
which will default to a signed integer. The type resolution was missing
handling the type-hints of isize and usize
Fixes#1152
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
1147: Add missing coercion rule from array to slice r=philberty a=philberty
Arrays are coercible into slices, this adds the missing type-resolution
the rule which works for now. The other part of this fix is described in #1146
for coercion_site to be recursive and reuse the adjustment classes so that
we reuse as much code as possible and handle complex coercion sites.
Fixes#1129
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
1145: Fix generic param redefined bug r=philberty a=philberty
When we name-resolve generic parameters their declaration gets inserted in
to the upper-most rib on the stack. Then when this is referenced we lookup
the relevant binding starting from the uppermost rib this lead to the 2nd
extern item adding the same binding into the same rib which caused this
clash. To fix this we need to have a seperate rib for each declaration
so as reusing the same names don't clash with each other.
Fixes#1131
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
This bug turned out to be that we expected a usize for the array capacity
but the specified capacity turned out to be an integer inference variable
which will default to a signed integer. The type resolution was missing
handling the type-hints of isize and usize
Fixes#1152
Arrays are coercible into slices, this adds the missing type-resolution
the rule which works for now. The other part of this fix is described in
so that we reuse as much code as possible and handle complex coercion
sites.
Fixes#1129
When we name-resolve generic parameters their declaration gets inserted in
to the upper-most rib on the stack. Then when this is referenced we lookup
the relevant binding starting from the uppermost rib this lead to the 2nd
extern item adding the same binding into the same rib which caused this
clash. To fix this we need to have a seperate rib for each declaration
so as reusing the same names don't clash with each other.
Fixes#1131
1144: Add name and type resolution support TuplePatterns in MatchArms r=philberty a=philberty
This adds support for the name and type resolution of match expressions. The code generation
and checks for all cases possible cases needs more thought so this will be done as part of a
separate PR.
Addresses #1081
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
This adds the relevant pattern resolution steps to match up the
TuplePattern. This patch leaves out type resolution on TupleRange Patterns
for now. Some thought is needed to figure out how do have a canonical
algorithm for code-generation here so splitting this up makes sense for
now.
This patch extracts the type-resolution handling for HIR::LiteralExpr
to have a generic function to resolve the HIR::Literal which is used within
HIR::LiteralExpr and HIR::LiteralPattern.
Addresses #1081
When parsing a match expression such as:
```
match (f, g) {
(Foo::A, 1) => {}
(Foo::B, 2) => {}
_ => {}
}
```
The first match arm here has an empty block expression of {}. This was
being parsed into a CallExpr of {}(Foo::B, 2) which is wrong. The parsing
of match arms are expression statements so they can be a block but must not
consume the semi-colon as it is valid to have a comma to delimit the match
arm or it can be ignored if this is a ExprWithBlock.
Addresses #1081
1119: Add a test for the cfg!() macro r=CohenArthur a=antego
See #1116 and #1039
Adding a test for the cfg!() macro. The compilation of the test fails with the message:
```
fatal error: Failed to lower expr: [MacroInvocation:
outer attributes: none
cfg!((A))
has semicolon: false]
compilation terminated.
```
Co-authored-by: antego <antego@users.noreply.github.com>
1138: Support pattern bindings within function signitures r=philberty a=philberty
This reuses our code to handle match-arms within MatchExpressions, we
resolve the pattern's type's and implicitly create types for that binding.
For code-generation we create a tmp var name for the name of the parameter
which is the base type and for the destructuring we reuse the same match
arm code to generate the implicit bindings to the parts of the structure
```c
__attribute__((cdecl))
i32 test::pattern_as_arg (const struct test::Pattern RSTPRM.0)
{
i32 RUSTTMP.1;
return RSTPRM.0.0;
}
```
Fixes#995
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
1137: ast: lower: Split rust-lower-base in its own source file r=CohenArthur a=CohenArthur
The implementation of all functions declared in `rust-ast-lower-base.h` was a big offender of our "definitions in headers" problem, spanning over 900 lines of code. We can do the same for basically all headers in `gcc/rust/hir` which all contain some definitions that have accumulated over time
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
1134: Fix ICE during HIR lowering of ExprWithBlock MatchExpr r=philberty a=philberty
When we are lowering blocks using the visitor pattern we must use the
BaseClass of ExprWithBlock to abstract away the notion that this expr
has a block such that we can handle cases like a block expr vs expressions
with a block. This makes the usage of hir lowering of match expressions to
be recursive, if we had more fine grained visitors in the AST we could fix
these types of problems with compile time enforced interfaces.
Fixes#858
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
1121: Fix bad projection substitution r=philberty a=philberty
When we have a Trait such as:
```
pub unsafe trait SliceIndex<T> {
type Output;
fn index(self, slice: &T) -> &Self::Output;
}
unsafe impl<T> SliceIndex<[T]> for Range<usize> {
type Output = [T];
fn index(self, slice: &[T]) -> &[T] {
unsafe { &*self.get_unchecked(slice) }
}
}
```
When we need to verify that the impl index is compatible fir SliceIndex we
get the Type info for the trait-item which is:
fn<Self, T> index(self: Self, slice: &T)
-> &<placeholder=projection<T>=[T]>
This projection gets setup and the types are substituted with
Self=Range<usize> and T=[T] which ended up substituting the projection
twice resulting in a recursive slice [T=[T]]. In this case the associated
type is already setup for the placeholder and does not require generic
substitution. This means we added a flag to the substitution generic
arguments mappings to handle this case.
This patch also addressed memory corruption with the TypeBoundPredicate
as part of the debugging of this issue which resulted in a segv when
trying to debug the mappings. The issue was the copy constructors needed
to update the used argument mappings each time since the substitution param
mappings are copied and the addresses no longer exist, valgrind was great
here to find this issue.
Fixes#1120
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
This reuses our code to handle match-arams within MatchExpressions, we
resolve the pattern's type's and implicitly create types for that binding.
For code-generation we create a tmp var name for the name of the parameter
which is the base type and for the destructuring we reuse the same match
arm code to generate the implicit bindings to the parts of the structure
```c
__attribute__((cdecl))
i32 test::pattern_as_arg (const struct test::Pattern RSTPRM.0)
{
i32 RUSTTMP.1;
return RSTPRM.0.0;
}
```
Fixes#995
When we are lowering blocks using the visitor pattern we must use the
BaseClass of ExprWithBlock to abstract away the notion that this expr
has a block such that we can handle cases like a block expr vs expressions
with a block. This makes the usage of hir lowering of match expressions to
be recursive, if we had more fine grained visitors in the AST we could fix
these types of problems with compile time enforced interfaces.
Fixes#858
1124: CI: do not push Docker image in a fork r=philberty a=liushuyu
- ci: skip docker image push when in a fork
Co-authored-by: liushuyu <liushuyu011@gmail.com>
1118: Add reachability visitor to Enum variants r=CohenArthur a=CohenArthur
This visits all of an enum's variants and their fields if present. To do that properly, this adds a new `EnumItemKind` enum which allows static casting when visiting each variant of the enum (kept as an `EnumItem` class which is derived three times)
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
1107: tests: Improve timeout handling r=philberty a=liushuyu
- add a 10-second timeout for individual compile test
- add a xfail test case to ensure the timeout mechanism is working
Co-authored-by: liushuyu <liushuyu011@gmail.com>
When we have a Trait such as:
```
pub unsafe trait SliceIndex<T> {
type Output;
fn index(self, slice: &T) -> &Self::Output;
}
unsafe impl<T> SliceIndex<[T]> for Range<usize> {
type Output = [T];
fn index(self, slice: &[T]) -> &[T] {
unsafe { &*self.get_unchecked(slice) }
}
}
```
When we need to verify that the impl index is compatible fir SliceIndex we
get the Type info for the trait-item which is:
fn<Self, T> index(self: Self, slice: &T)
-> &<placeholder=projection<T>=[T]>
This projection gets setup and the types are substituted with
Self=Range<usize> and T=[T] which ended up substituting the projection
twice resulting in a recursive slice [T=[T]]. In this case the associated
type is already setup for the placeholder and does not require generic
substitution. This means we added a flag to the substitution generic
arguments mappings to handle this case.
This patch also addressed memory corruption with the TypeBoundPredicate
as part of the debugging of this issue which resulted in a segv when
trying to debug the mappings. The issue was the copy constructors needed
to update the used argument mappings each time since the substitution param
mappings are copied and the addresses no longer exist, valgrind was great
here to find this issue.
Fixes#1120
1116: Move `cfg!()` macro to builtins. Fixes#1039 r=CohenArthur a=antego
Fixes#1039
Hey team, I need help understanding why the test fails.
Compilation succeeds, all the existing tests pass. However the test that I've added fails with the error:
```
FAIL: rust/compile/cfg_macro.rs (test for excess errors)
Excess errors:
/Users/anton/Documents/projects/gcc2/gccrs/gcc/testsuite/rust/compile/cfg_macro.rs:17:8: fatal error: Failed to lower expr: [MacroInvocation:
outer attributes: none
cfg!((A))
has semicolon: false]
compilation terminated.
```
I tried to understand what's happening using a debugger. The only thing that I understood is that the `MacroBuiltin::cfg` function runs.
Appreciate any feedback.
Thank you.
Co-authored-by: antego <antego@users.noreply.github.com>
1110: Add Reachability visitors for items with generics r=CohenArthur a=CohenArthur
This factors generics' predicates visiting in the `ReachabilityVisitor` and calls the function in other items with generic parameters
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
1088: rust-session-manager: better crate name handling logic r=philberty a=liushuyu
- rust-session-manager: set and validate crate name properly
- testsuite/rust: fix the testcases and add more testcases for testing crate name handling
Co-authored-by: liushuyu <liushuyu011@gmail.com>
1111: Add AST Private Visibilities r=CohenArthur a=CohenArthur
When parsing a visibility in `parse_visibility`, it is not an error to
not have a pub token: It simply means we want to create a private
visibility. If we had C++14 or another language, we could instead
represent all visibilities as an optional<AST::Visibility> where the
Visibility class would not need to change. But I think the best course
of action for our case is to instead keep visibilities even when they
are private and have a special case in the `VisKind` enumeration.
This also enables HIR lowering of visibilities to be performed properly for private items
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
1114: rust: Use -Otarget when building and logging warnings r=philberty a=simonpcook
This will provide some synchronization for output lines, and so will
make comparisons with known warnings as part of CI more reliable.
Co-authored-by: Simon Cook <simon.cook@embecosm.com>
When parsing a visibility in `parse_visibility`, it is not an error to
not have a pub token: It simply means we want to create a private
visibility. If we had C++14 or another language, we could instead
represent all visibilities as an optional<AST::Visibility> where the
Visibility class would not need to change. But I think the best course
of action for our case is to instead keep visibilities even when they
are private and have a special case in the `VisKind` enumeration.
1112: rust: Clang/macOS Testing r=philberty a=simonpcook
This adds a version of the build-and-check job that runs with clang on
macOS.
Co-authored-by: Simon Cook <simon.cook@embecosm.com>
1109: rust: Allow gccrs to build on x86_64-apple-darwin with clang/libc++ r=CohenArthur a=simonpcook
This makes changes to the includes such that gccrs can be built with
clang/libc++, and for x86_64-apple-darwin. Similarly, a couple of
changes have been made to creating MacroInvocations and wrapping into
ExprOrStmts for libc++ compatibility.
Co-authored-by: Simon Cook <simon.cook@embecosm.com>
This makes changes to the includes such that gccrs can be built with
clang/libc++, and for x86_64-apple-darwin. Similarly, a couple of
changes have been made to creating MacroInvocations and wrapping into
ExprOrStmts for libc++ compatibility.
1082: Add base for privacy visitor r=CohenArthur a=CohenArthur
This PR is extremely early and implements some building blocks for privacy visitors. I'd like to get some feedback on the architecture and, if satisfactory, merge this first "visitor" which only takes care of visiting HIR struct definitions, to make reviewing easier. We could also merge it to a different branch for now, in order to not add an incomplete pass to the compiler.
Thanks!
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
1108: Add missing unify rules for inference variables r=philberty a=philberty
Inference variables can unify with anything so this includes these
covariant types like references/slices etc. This patch is needed for more
complex type-checking in libcore and generics.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
Inference variables can unify with anything so this includes these
covariant types like references/slices etc. This patch is needed for more
complex type-checking in libcore and generics.
lookup_reachability()
Inserting reach levels in the reachability_map should only be done if
the existing reach level is lower than the provided one. If the node is
not yet present in the reachability map, insert it no matter what
1103: Lower AST::Visibility to HIR::Visibility properly r=CohenArthur a=CohenArthur
Fixes#1093
This should cover every case since the previous code simply created public HIR visibilities.
The PR refactors the HIR::Visibility struct to be tinier and a desugared version of the AST one.
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
1086: Slice support r=philberty a=philberty
Please see the commit a8de089969cb45199008027cd8d1b80dff25746f for
a long explanation of what's going on in the patch. Unfortunately, I have not been
able to split this patch up anymore since supporting slices exposed many bugs
in the implementation of generics in general never main the missing support for
generic associated types.
Fixes#849
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
This is unfortunatly a mega commit, in testing gccrs against the slice code
which is highly generic stress tested our implementation of generics and
poked the hole in or lack of support of generic higher ranked trait bounds
and more specificily generic associated types. More refactoring is needed
to eventually remove the setup_associated_types and replace it entirely
with this new setup_associated_types2 which takes into account the trait
bound receiver and its predicate.
In order to support slices, the code in libcore defines an index lang item
```rust
impl<T, I> Index<I> for [T]
where
I: SliceIndex<[T]>,
{
type Output = I::Output;
fn index(&self, index: I) -> &I::Output {
index.index(self)
}
}
```
This is the entry point where by the self here is a generic slice. So in
our case we have:
```rust
let a = [1, 2, 3, 4, 5];
let b = &a[1..3];
```
'a' is an array and b is our desired slice, so we must remember that from
algebraic data type constructor. But our receiver is still an array, so in
order to be able to call this index lang item we must 'unsize' our array
(see #1045) this allows for method resolution to adjust an array into a
FatPtr which is simply a struct containing reference to the array and the
capacity (GCC MAX_DOMAIN) of the underlying array data type. So now we are
able to infer the substituions for this index fn call to:
```
fn index(&self : [<integer>], index: Range<integer>)
-> &I::Output->placeholder
```
The complex piece here is the Higher ranked trait bound:
```
where I: SliceIndex<[T]>
```
So in this method call no generic arguments are specified so we must try
and infer the types. So during monomorphization the inference variables
need to be recursively propogated into the higher ranked trait bound. So
that the higher ranked trait bound looks like:
```
SliceIndex<[<integer>]> // like we seen earlier for the Self type
```
The monomorphization stage also needs to take into account the higher
ranked trait bound's type which is 'I' and infered to be: Range<integer>.
This is where specialization needs to occur.
```rust
unsafe impl<T> SliceIndex<[T]> for Range<usize> {
type Output = [T];
unsafe fn get_unchecked(self, slice: *const [T]) -> *const [T] {
unsafe {
let a: *const T = slice.as_ptr();
let b: *const T = a.add(self.start);
slice_from_raw_parts(b, self.end - self.start)
}
}
fn index(self, slice: &[T]) -> &[T] {
unsafe { &*self.get_unchecked(slice) }
}
}
```
So now we need to compute the constrained type-parameters for this
specialized impl block. And in this case is fairly simple:
```
impl<T> SliceIndex<[T]> for Range<usize>
vs
I: SliceIndex<[<integer>]> and Range<<integer>>
```
Here we need to compute that T is <integer>, which is required since
associated type Output is used in our original method call and this
is generic which requires us to set it up but both the Self type or
the trait bound here in this impl block could be generic so special
care needs to be taken to compute this safely. Once the constrained
types are computer we can also unify the Self types which specializes
our original Range<integer> type into the correct Range<usize> that
this trait bound expects. We used a callback here when we reusively
pass down the SubstitutionArgumentMappings when any Parameter type
is substitued we get a callback to hold a set of mappings in a generic
way what generic types are being substituted.
From all of this work this stressed our generics implementation to
breaking point due to the use of the generic trait bound which was
not supported and it also exposed many bugs in our implementation.
This is why I feel it is best to keep this a large patch as so much
of this patch will cause regressions if we don't keep it together.
One of the main changes we have made is how we handle parameters
substitution for example we might have a generic such as '&Y' but
this gets substituted with Y=T which is a new type parameter. Before
we used to directly just change this from &Y to &T which is correct
but this looses context from the generic argument bindings. So now
we maintain the information that &Y changes to &(Y=T) so that we see
Y was substutued with T so that subsequent substitutions or inferences
can change Y=?T and correctly map &Y to &(Y=T) to &(Y=?T).
The other major piece which was changed during this patch was how
we perform the method resolution on higher ranked trait bound calls
where we compute the specified bound possible candidates once so that
in the case:
```
trait Bar {
fn baz(&self)
}
fn <T:Bar> foo(a: &T) {
a.baz()
}
```
Here the type parameter T gets derefed to find the specified bound of
Bar which contains the method baz. This means that we try calling baz
with T vs &T which fails then we try the reference type T again. This
results into two useless adjustments of indirection and referencing but
GCC optimizes this away. Before this patch we computed the specified bound
for each attempt which was wrong.
Fixes#849
Previously, the lowering code would simply create public
`HIR::Visibility`s for every AST Node being lowered. We now call
`translate_visibility()` properly to perform the necessary conversions
The HIR::Visibility struct was extremely similar to the AST::Visibility
one. However, we do not need to keep as much information at the HIR
level: Syntactic sugar such as pub(crate) can be kept as the desugared
form, which is pub(in crate). Likewise, pub(self) can be desugared to
pub(in self) which amounts to having a private item.
This commit fed5a41fb1 introduced the concat
builtin macro but the error handling here is producing an infinite loop
which was not caught during code-review. This patch disables the offending
error cases so that it does not impact further development.
Addresses #1102
1090: macros: add concat! macro r=philberty a=liushuyu
- extracts parenthesis-matching logic into a function
- adds `concat!` macro
1097: Support mangling *const ptr and slices like *const [T] r=philberty a=philberty
The legacy mangling scheme needs to convert the canonical path containing
* for pointers and the [] brackets representing slices into:
* = $BP$
[ = $u5b$
] = $u5d$
These symbols are not allowed in asm symbols.
Addresses #849
1098: Ensure unsize method resolutions actually unsize r=philberty a=philberty
This was a typo when unsized method resolution was added, where the
adjustment was wrongly marked as an indirection. The enum is required so
that the code generation adjustment takes place.
Addresses #849
1099: Fix bad inherent overlap error r=philberty a=philberty
When we examine HIR::ImplBlock's we determine if an impl might overlap
another impl based on the Self type. So for example you might have a
generic structure Foo<T>(T), and an associated impl block for Foo<i32>, but
then go on to define an associated impl of Foo<T> the generic one will
overlap any associated impl hiding the generic implementation.
In this case we have two generic impl blocks
*const [T]
*const T
This means the *const T might overlap with the slice one since it is
generic. As bjorn3 pointed out in #1075 , the correct implementation is to
observe that [T] is constrained by size but untill we have the auto trait
of Sized we must example the two generic impls and just determine that
they are not-equal so for now this is the best implementation we can do.
Fixes#1075
1101: Add helper as_string for DefIds r=philberty a=philberty
This just adds a useful helper to as_string DefId's directly
Co-authored-by: liushuyu <liushuyu011@gmail.com>
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
When we examine HIR::ImplBlock's we determine if an impl might overlap
another impl based on the Self type. So for example you might have a
generic structure Foo<T>(T), and an associated impl block for Foo<i32>, but
then go on to define an associated impl of Foo<T> the generic one will
overlap any associated impl hiding the generic implementation.
In this case we have two generic impl blocks
*const [T]
*const T
This means the *const T might overlap with the slice one since it is
generic. As bjorn3 pointed out in #1075, the correct implementation is to
observe that [T] is constrained by size but untill we have the auto trait
of Sized we must example the two generic impls and just determine that
they are not-equal so for now this is the best implementation we can do.
Fixes#1075
1100: Add known lang item const_slice_ptr mappings r=philberty a=philberty
This will allow us to define the const_slice_ptr lang item attribute
without erroring out as an unknown lang item.
Addresses #849
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
This was a typo when unsized method resolution was added, where the
adjustment was wrongly marked as an indirection. The enum is required so
that the code generation adjustment takes place.
Addresses #849
The legacy mangling scheme needs to convert the canonical path containing
* for pointers and the [] brackets representing slices into:
* = $BP$
[ = $u5b$
] = $u5d$
These symbols are not allowed in asm symbols.
Addresses #849
1092: gcc/rust/Make-lang.in: add missing rust compiler driver r=philberty a=RomainNaour
When building gccrs with Buildroot toolchain infrastructure, the gccrs
compiler driver is missing when intalling gcc.
This is due to missing depedency on gccrs$(exeext) in rust.all.cross
target.
With that fixed, the gcc toolchain with Rust support is correctly installed into Buildroot:
$ ./test/gccrs/host/bin/aarch64-linux-gccrs --version
aarch64-linux-gccrs (Buildroot 2022.02-442-g54d638fbd1-dirty) 12.0.1 20220118 (experimental)
Note: We probably needs gccrs-cross target like other supported languages.
Copyright assignment signed between Smile and the FSF to contribute to GNU tools.
Co-authored-by: Romain Naour <romain.naour@smile.fr>
1087: Use loop to initialize repeat arrays r=philberty a=dafaust
This PR changes how we compile initializers for arrays of repeating elements. I use the same approach outlined in the comments of the linked issue, with some tweaks. It is very similar to how the D language front-end compiles, the new function `Gcc_backend::array_initializer` is heavily inspired by the D front-end's `build_array_set`
This fixes the issue where the compiler tries to allocate a vec containing all elements of the array to be constructed, and therefore explodes on huge constructions (e.g. `let x = [0u8; 4 * 1024 * 1024 * 1024 * 1024]`)
However, we can only initialize non-const arrays in this way. For arrays in const contexts we must initialize them at compile time, and therefore continue using the old method.
Fixes: #1068
Co-authored-by: David Faust <david.faust@oracle.com>
When building gccrs with Buildroot toolchain infrastructure, the gccrs
compiler driver is missing when intalling gcc.
This is due to missing depedency on gccrs$(exeext) in rust.all.cross
target.
Signed-off-by: Romain Naour <romain.naour@smile.fr>
---
We probably needs gccrs-cross target like other supported languages.
This commit changes how arrays of repeating elements, e.g. [5; 12] are
compiled. Rather than create a constructor which explicitly initializes
each element to the given value (which causes compiler OOM for large
arrays), we emit instructions to allocate the array then initialize the
elements in a loop.
However, we can only take this approach outside of const contexts -
const arrays must still use the old approach.
1083: bugfix: fix several minor issues r=CohenArthur a=liushuyu
- Fixed `-frust-crate= option` got incorrectly overridden by a default value (`example`)
- Fix a minor typo in `gcc/rust/ast/rust-ast-full-test.cc`
Co-authored-by: liushuyu <liushuyu011@gmail.com>
1071: Allow transcribing of zero nodes in certain cases r=CohenArthur a=CohenArthur
When expanding AST fragments containing multiple nodes, we must be aware
that some cases allow expanding zero or more nodes. Any macro
transcription that gets parsed as many nodes (ie any transcriber function that calls `parse_many`) needs to be able to parse zero of those nodes and still get expanded properly (basically, removed).
Previously, this would cause a failure to lower the macro invocation which would remain as a child instead of getting stripped/erased.
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
When expanding AST fragments containing multiple nodes, we must be aware
that some cases allow expanding zero or more nodes. Any macro
transcription that gets parsed as many nodes (ie any transcriber function that calls `parse_many`) needs to be able to parse zero of those nodes and still get expanded properly (basically, removed).
Previously, this would cause a failure to lower the macro invocation which would remain as a child instead of getting stripped/erased.
Co-authored-by: philberty <philip.herron@embecosm.com>
1069: Handle macro invocations in type contexts r=CohenArthur a=CohenArthur
Closes#1067
This highlighted two issues where parsing types is not entirely correct, which I'll raise. The code necessary to handle macro invocations in these two places should already be implemented.
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
Macro invocations can be present where the language expects types. Thus,
we need to add a new type of parsing context, a new transcriber, as well
as a new way to extract types from the AST Fragments. This adds a lot of
"expansion places" in the attribute visitor, as types can be present in
a wide variety of constructs
1045: Add initial support for unsized method resolution r=philberty a=philberty
In order to support slices, we end up with an operator overload call of:
```
impl<T, I> Index<I> for [T]
where
I: SliceIndex<[T]>,
{
type Output = I::Output;
fn index(&self, index: I) -> &I::Output {
index.index(self)
}
}
```
So this means the self, in this case, is an array[T,capacity] and the index parameter is of type Range<usize>. In order to actually call this method
which has a self parameter of [T] we need to be able to 'unsize' the array
into a slice.
Addresses #849
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
Since all cases in the switch were handled, this was not really a
problem. Still, we should avoid those in case we need to add
delimiters at some point
Co-authored-by: Thomas Schwinge <thomas@schwinge.name>
1063: Handle :meta fragments properly r=CohenArthur a=CohenArthur
This expands :meta fragments properly and allows us to strip assignment expressions
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
1055: Allow keeping list of last matches to check against r=CohenArthur a=CohenArthur
When trying to figure out if a match can follow another, we must figure
out whether or not that match is in the follow-set of the other. If that
match is zeroable (i.e a repetition using the * or ? kleene operators),
then we must be able to check the match after them: should our current
match not be present, the match after must be part of the follow-set.
This commits allows us to performs such checks properly and to "look
past" zeroable matches. This is not done with any lookahead, simply by
keeping a list of pointers to possible previous matches and checking all
of them for ambiguities.
Addresses #947Closes#947
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
AssignmentExpressions could not access their outer attributes properly,
since they were being eagerly moved into the `IdentifierExpr` type they
are based on. The base `OperatorExpr` class would thus end up with an
empty vector of outer attributes
When trying to figure out if a match can follow another, we must figure
out whether or not that match is in the follow-set of the other. If that
match is zeroable (i.e a repetition using the * or ? kleene operators),
then we must be able to check the match after them: should our current
match not be present, the match after must be part of the follow-set.
This commits allows us to performs such checks properly and to "look
past" zeroable matches. This is not done with any lookahead, simply by
keeping a list of pointers to possible previous matches and checking all
of them for ambiguities.
1043: implement include_bytes! and include_str! macros r=CohenArthur a=dafaust
Implement the include_bytes! and include_str! builtin macros.
Addresses: #927
1064: Handle :tt fragments properly r=CohenArthur a=CohenArthur
:tt fragments stand for token trees, and are composed of either a token,
or a delimited token tree, which is a token tree surrounded by
delimiters (parentheses, curly brackets or square brackets).
This should allow us to handle a lot more macros, including extremely
powerful macro patterns such as TT munchers
Co-authored-by: David Faust <david.faust@oracle.com>
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
1054: Fix overzealous follow set ambiguity r=CohenArthur a=CohenArthur
When checking if a follow-up is valid, we previously always returned
false when comparing with MacroMatchRepetitions. This is however
invalid, as we should be comparing with the first match of the
repetition to be sure.
Closes#1053
Addresses #947
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
:tt fragments stand for token trees, and are composed of either a token,
or a delimited token tree, which is a token tree surrounded by
delimiters (parentheses, curly brackets or square brackets).
This should allow us to handle a lot more macros, including extremely
powerful macro patterns such as TT munchers
When checking if a follow-up is valid, we previously always returned
false when comparing with MacroMatchRepetitions. This is however
invalid, as we should be comparing with the first match of the
repetition to be sure.
1052: Add hints for valid follow tokens r=CohenArthur a=CohenArthur
This PR adds hints about the allowed tokens after a certain fragment, and fixes tests to uphold the new error message
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
Adds a new call to `rust_inform()` in order to let the user know about
the tokens allowed after the previous match.
Since this changes the error message, tests also need to be adjusted.
As Thomas Schwinge pointed out, GCC 4.8 is the minimum version to be
used for building current GCC, meaning that we should make an effort to
support it before we consider upstreaming or backporting. The main
differences are probably a less powerful standard template library or
small compilation differences.
1051: macros: Add remaining restrictions for follow-set restrictions r=CohenArthur a=CohenArthur
Adds the remaining restrictions for follow-set ambiguities in macros.
This means adding the remaining allowed tokens for all fragment
specifiers with follow-up restrictions, as well as handling allowed
fragment specifiers in certain cases. For example, :vis specifiers can
sometimes be followed by fragments, if they have the :ident, :ty or
:path specifier. Likewise for :path and :ty which can be followed by a
:block.
Finally, we also allow *any* fragment after a matcher: Since the matcher
is delimiter by parentheses, brackets or curlies, anything is allowed
afterwards.
Some edge cases or allowed tokens that we cannot handle yet remain, for which FIXMEs exist. I'll open up corresponding issues.
Addresses #947
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
1056: Fix '#include <algorithm>' [#159] r=tschwinge a=tschwinge
... recently introduced in #1044 commit 35ca685200
"macros: Add base functions to check for follow-set ambiguities".
GCC doesn't like that:
In file included from [...]
./mm_malloc.h:42:12: error: attempt to use poisoned "malloc"
return malloc (__size);
^
See commit e7b3f654f2, for example.
1057: For use as 'std::unordered_map' key, provide 'std::hash' for 'Rust::AST::MacroFragSpec::Kind' enum class r=tschwinge a=tschwinge
... recently introduced in #1044 commit 35ca685200
"macros: Add base functions to check for follow-set ambiguities".
Otherwise, at least with an oldish GCC 5.2, compilation of
'gcc/rust/parse/rust-parse.cc' fails noisily:
In file included from [GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/hashtable.h:35:0,
from [GCC]/i686-pc-linux-gnu/include/c++/5.2.0/unordered_map:47,
from [GCC/Rust]/gcc/rust/rust-system.h:46,
from [GCC/Rust]/gcc/rust/rust-linemap.h:12,
from [GCC/Rust]/gcc/rust/lex/rust-lex.h:22,
from [GCC/Rust]/gcc/rust/parse/rust-parse.h:20,
from [GCC/Rust]/gcc/rust/parse/rust-parse.cc:17:
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/hashtable_policy.h: In instantiation of 'struct std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> >':
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/type_traits:137:12: required from 'struct std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > >'
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/type_traits:148:38: required from 'struct std::__not_<std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > > >'
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h:100:66: required from 'class std::unordered_map<Rust::AST::MacroFragSpec::Kind, std::vector<Rust::TokenId> >'
[GCC/Rust]/gcc/rust/parse/rust-parse.cc:101:5: required from here
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/hashtable_policy.h:85:34: error: no match for call to '(const std::hash<Rust::AST::MacroFragSpec::Kind>) (const Rust::AST::MacroFragSpec::Kind&)'
noexcept(declval<const _Hash&>()(declval<const _Key&>()))>
^
In file included from [GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/move.h:57:0,
from [GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/stl_pair.h:59,
from [GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/stl_algobase.h:64,
from [GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/char_traits.h:39,
from [GCC]/i686-pc-linux-gnu/include/c++/5.2.0/string:40,
from [GCC/Rust]/gcc/rust/rust-system.h:34,
from [GCC/Rust]/gcc/rust/rust-linemap.h:12,
from [GCC/Rust]/gcc/rust/lex/rust-lex.h:22,
from [GCC/Rust]/gcc/rust/parse/rust-parse.h:20,
from [GCC/Rust]/gcc/rust/parse/rust-parse.cc:17:
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/type_traits: In instantiation of 'struct std::__not_<std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > > >':
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h:100:66: required from 'class std::unordered_map<Rust::AST::MacroFragSpec::Kind, std::vector<Rust::TokenId> >'
[GCC/Rust]/gcc/rust/parse/rust-parse.cc:101:5: required from here
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/type_traits:148:38: error: 'value' is not a member of 'std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > >'
: public integral_constant<bool, !_Pp::value>
^
In file included from [GCC]/i686-pc-linux-gnu/include/c++/5.2.0/unordered_map:48:0,
from [GCC/Rust]/gcc/rust/rust-system.h:46,
from [GCC/Rust]/gcc/rust/rust-linemap.h:12,
from [GCC/Rust]/gcc/rust/lex/rust-lex.h:22,
from [GCC/Rust]/gcc/rust/parse/rust-parse.h:20,
from [GCC/Rust]/gcc/rust/parse/rust-parse.cc:17:
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h: In instantiation of 'class std::unordered_map<Rust::AST::MacroFragSpec::Kind, std::vector<Rust::TokenId> >':
[GCC/Rust]/gcc/rust/parse/rust-parse.cc:101:5: required from here
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h:100:66: error: 'value' is not a member of 'std::__not_<std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > > >'
typedef __umap_hashtable<_Key, _Tp, _Hash, _Pred, _Alloc> _Hashtable;
^
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h:107:45: error: 'value' is not a member of 'std::__not_<std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > > >'
typedef typename _Hashtable::key_type key_type;
^
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h:108:47: error: 'value' is not a member of 'std::__not_<std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > > >'
typedef typename _Hashtable::value_type value_type;
^
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h:109:48: error: 'value' is not a member of 'std::__not_<std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > > >'
typedef typename _Hashtable::mapped_type mapped_type;
^
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h:110:43: error: 'value' is not a member of 'std::__not_<std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > > >'
typedef typename _Hashtable::hasher hasher;
^
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h:111:46: error: 'value' is not a member of 'std::__not_<std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > > >'
typedef typename _Hashtable::key_equal key_equal;
^
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h:112:51: error: 'value' is not a member of 'std::__not_<std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > > >'
typedef typename _Hashtable::allocator_type allocator_type;
^
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h:117:45: error: 'value' is not a member of 'std::__not_<std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > > >'
typedef typename _Hashtable::pointer pointer;
^
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h:118:50: error: 'value' is not a member of 'std::__not_<std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > > >'
typedef typename _Hashtable::const_pointer const_pointer;
^
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h:119:47: error: 'value' is not a member of 'std::__not_<std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > > >'
typedef typename _Hashtable::reference reference;
^
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h:120:52: error: 'value' is not a member of 'std::__not_<std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > > >'
typedef typename _Hashtable::const_reference const_reference;
^
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h:121:46: error: 'value' is not a member of 'std::__not_<std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > > >'
typedef typename _Hashtable::iterator iterator;
^
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h:122:51: error: 'value' is not a member of 'std::__not_<std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > > >'
typedef typename _Hashtable::const_iterator const_iterator;
^
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h:123:51: error: 'value' is not a member of 'std::__not_<std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > > >'
typedef typename _Hashtable::local_iterator local_iterator;
^
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h:124:57: error: 'value' is not a member of 'std::__not_<std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > > >'
typedef typename _Hashtable::const_local_iterator const_local_iterator;
^
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h:125:47: error: 'value' is not a member of 'std::__not_<std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > > >'
typedef typename _Hashtable::size_type size_type;
^
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h:126:52: error: 'value' is not a member of 'std::__not_<std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > > >'
typedef typename _Hashtable::difference_type difference_type;
^
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h:280:7: error: 'value' is not a member of 'std::__not_<std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > > >'
operator=(initializer_list<value_type> __l)
^
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h:379:2: error: 'value' is not a member of 'std::__not_<std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > > >'
emplace(_Args&&... __args)
^
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h:432:7: error: 'value' is not a member of 'std::__not_<std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > > >'
insert(const value_type& __x)
^
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h:439:2: error: 'value' is not a member of 'std::__not_<std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > > >'
insert(_Pair&& __x)
^
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h:499:7: error: 'value' is not a member of 'std::__not_<std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > > >'
insert(initializer_list<value_type> __l)
^
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h:645:7: error: 'value' is not a member of 'std::__not_<std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > > >'
equal_range(const key_type& __x)
^
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h:649:7: error: 'value' is not a member of 'std::__not_<std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > > >'
equal_range(const key_type& __x) const
^
[GCC/Rust]/gcc/rust/parse/rust-parse.cc: In function 'bool Rust::peculiar_fragment_match_compatible(Rust::AST::MacroMatchFragment&, Rust::AST::MacroMatch&)':
[GCC/Rust]/gcc/rust/parse/rust-parse.cc:104:5: error: too many initializers for 'std::unordered_map<Rust::AST::MacroFragSpec::Kind, std::vector<Rust::TokenId> >'
};
^
[GCC/Rust]/gcc/rust/parse/rust-parse.cc:119:16: error: no match for 'operator[]' (operand types are 'std::unordered_map<Rust::AST::MacroFragSpec::Kind, std::vector<Rust::TokenId> >' and 'Rust::AST::MacroFragSpec::Kind')
= follow_set[last_match.get_frag_spec ().get_kind ()];
^
make[2]: *** [[GCC/Rust]/gcc/rust/Make-lang.in:299: rust/rust-parse.o] Error 1
Co-authored-by: Thomas Schwinge <thomas@codesourcery.com>
... recently introduced in #1044 commit 35ca685200
"macros: Add base functions to check for follow-set ambiguities".
Otherwise, at least with an oldish GCC 5.2, compilation of
'gcc/rust/parse/rust-parse.cc' fails noisily:
In file included from [GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/hashtable.h:35:0,
from [GCC]/i686-pc-linux-gnu/include/c++/5.2.0/unordered_map:47,
from [GCC/Rust]/gcc/rust/rust-system.h:46,
from [GCC/Rust]/gcc/rust/rust-linemap.h:12,
from [GCC/Rust]/gcc/rust/lex/rust-lex.h:22,
from [GCC/Rust]/gcc/rust/parse/rust-parse.h:20,
from [GCC/Rust]/gcc/rust/parse/rust-parse.cc:17:
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/hashtable_policy.h: In instantiation of 'struct std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> >':
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/type_traits:137:12: required from 'struct std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > >'
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/type_traits:148:38: required from 'struct std::__not_<std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > > >'
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h:100:66: required from 'class std::unordered_map<Rust::AST::MacroFragSpec::Kind, std::vector<Rust::TokenId> >'
[GCC/Rust]/gcc/rust/parse/rust-parse.cc:101:5: required from here
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/hashtable_policy.h:85:34: error: no match for call to '(const std::hash<Rust::AST::MacroFragSpec::Kind>) (const Rust::AST::MacroFragSpec::Kind&)'
noexcept(declval<const _Hash&>()(declval<const _Key&>()))>
^
In file included from [GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/move.h:57:0,
from [GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/stl_pair.h:59,
from [GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/stl_algobase.h:64,
from [GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/char_traits.h:39,
from [GCC]/i686-pc-linux-gnu/include/c++/5.2.0/string:40,
from [GCC/Rust]/gcc/rust/rust-system.h:34,
from [GCC/Rust]/gcc/rust/rust-linemap.h:12,
from [GCC/Rust]/gcc/rust/lex/rust-lex.h:22,
from [GCC/Rust]/gcc/rust/parse/rust-parse.h:20,
from [GCC/Rust]/gcc/rust/parse/rust-parse.cc:17:
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/type_traits: In instantiation of 'struct std::__not_<std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > > >':
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h:100:66: required from 'class std::unordered_map<Rust::AST::MacroFragSpec::Kind, std::vector<Rust::TokenId> >'
[GCC/Rust]/gcc/rust/parse/rust-parse.cc:101:5: required from here
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/type_traits:148:38: error: 'value' is not a member of 'std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > >'
: public integral_constant<bool, !_Pp::value>
^
In file included from [GCC]/i686-pc-linux-gnu/include/c++/5.2.0/unordered_map:48:0,
from [GCC/Rust]/gcc/rust/rust-system.h:46,
from [GCC/Rust]/gcc/rust/rust-linemap.h:12,
from [GCC/Rust]/gcc/rust/lex/rust-lex.h:22,
from [GCC/Rust]/gcc/rust/parse/rust-parse.h:20,
from [GCC/Rust]/gcc/rust/parse/rust-parse.cc:17:
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h: In instantiation of 'class std::unordered_map<Rust::AST::MacroFragSpec::Kind, std::vector<Rust::TokenId> >':
[GCC/Rust]/gcc/rust/parse/rust-parse.cc:101:5: required from here
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h:100:66: error: 'value' is not a member of 'std::__not_<std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > > >'
typedef __umap_hashtable<_Key, _Tp, _Hash, _Pred, _Alloc> _Hashtable;
^
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h:107:45: error: 'value' is not a member of 'std::__not_<std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > > >'
typedef typename _Hashtable::key_type key_type;
^
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h:108:47: error: 'value' is not a member of 'std::__not_<std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > > >'
typedef typename _Hashtable::value_type value_type;
^
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h:109:48: error: 'value' is not a member of 'std::__not_<std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > > >'
typedef typename _Hashtable::mapped_type mapped_type;
^
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h:110:43: error: 'value' is not a member of 'std::__not_<std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > > >'
typedef typename _Hashtable::hasher hasher;
^
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h:111:46: error: 'value' is not a member of 'std::__not_<std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > > >'
typedef typename _Hashtable::key_equal key_equal;
^
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h:112:51: error: 'value' is not a member of 'std::__not_<std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > > >'
typedef typename _Hashtable::allocator_type allocator_type;
^
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h:117:45: error: 'value' is not a member of 'std::__not_<std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > > >'
typedef typename _Hashtable::pointer pointer;
^
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h:118:50: error: 'value' is not a member of 'std::__not_<std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > > >'
typedef typename _Hashtable::const_pointer const_pointer;
^
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h:119:47: error: 'value' is not a member of 'std::__not_<std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > > >'
typedef typename _Hashtable::reference reference;
^
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h:120:52: error: 'value' is not a member of 'std::__not_<std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > > >'
typedef typename _Hashtable::const_reference const_reference;
^
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h:121:46: error: 'value' is not a member of 'std::__not_<std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > > >'
typedef typename _Hashtable::iterator iterator;
^
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h:122:51: error: 'value' is not a member of 'std::__not_<std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > > >'
typedef typename _Hashtable::const_iterator const_iterator;
^
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h:123:51: error: 'value' is not a member of 'std::__not_<std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > > >'
typedef typename _Hashtable::local_iterator local_iterator;
^
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h:124:57: error: 'value' is not a member of 'std::__not_<std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > > >'
typedef typename _Hashtable::const_local_iterator const_local_iterator;
^
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h:125:47: error: 'value' is not a member of 'std::__not_<std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > > >'
typedef typename _Hashtable::size_type size_type;
^
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h:126:52: error: 'value' is not a member of 'std::__not_<std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > > >'
typedef typename _Hashtable::difference_type difference_type;
^
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h:280:7: error: 'value' is not a member of 'std::__not_<std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > > >'
operator=(initializer_list<value_type> __l)
^
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h:379:2: error: 'value' is not a member of 'std::__not_<std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > > >'
emplace(_Args&&... __args)
^
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h:432:7: error: 'value' is not a member of 'std::__not_<std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > > >'
insert(const value_type& __x)
^
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h:439:2: error: 'value' is not a member of 'std::__not_<std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > > >'
insert(_Pair&& __x)
^
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h:499:7: error: 'value' is not a member of 'std::__not_<std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > > >'
insert(initializer_list<value_type> __l)
^
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h:645:7: error: 'value' is not a member of 'std::__not_<std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > > >'
equal_range(const key_type& __x)
^
[GCC]/i686-pc-linux-gnu/include/c++/5.2.0/bits/unordered_map.h:649:7: error: 'value' is not a member of 'std::__not_<std::__and_<std::__is_fast_hash<std::hash<Rust::AST::MacroFragSpec::Kind> >, std::__detail::__is_noexcept_hash<Rust::AST::MacroFragSpec::Kind, std::hash<Rust::AST::MacroFragSpec::Kind> > > >'
equal_range(const key_type& __x) const
^
[GCC/Rust]/gcc/rust/parse/rust-parse.cc: In function 'bool Rust::peculiar_fragment_match_compatible(Rust::AST::MacroMatchFragment&, Rust::AST::MacroMatch&)':
[GCC/Rust]/gcc/rust/parse/rust-parse.cc:104:5: error: too many initializers for 'std::unordered_map<Rust::AST::MacroFragSpec::Kind, std::vector<Rust::TokenId> >'
};
^
[GCC/Rust]/gcc/rust/parse/rust-parse.cc:119:16: error: no match for 'operator[]' (operand types are 'std::unordered_map<Rust::AST::MacroFragSpec::Kind, std::vector<Rust::TokenId> >' and 'Rust::AST::MacroFragSpec::Kind')
= follow_set[last_match.get_frag_spec ().get_kind ()];
^
make[2]: *** [[GCC/Rust]/gcc/rust/Make-lang.in:299: rust/rust-parse.o] Error 1
... recently introduced in #1044 commit 35ca685200
"macros: Add base functions to check for follow-set ambiguities".
GCC doesn't like that:
In file included from [...]
./mm_malloc.h:42:12: error: attempt to use poisoned "malloc"
return malloc (__size);
^
See commit e7b3f654f2, for example.
Adds the remaining restrictions for follow-set ambiguities in macros.
This means adding the remaining allowed tokens for all fragment
specifiers with follow-up restrictions, as well as handling allowed
fragment specifiers in certain cases. For example, :vis specifiers can
sometimes be followed by fragments, if they have the :ident, :ty or
:path specifier. Likewise for :path and :ty which can be followed by a
:block.
Finally, we also allow *any* fragment after a matcher: Since the matcher
is delimiter by parentheses, brackets or curlies, anything is allowed
afterwards.
1049: Add better restrictions around semicolons in statements r=CohenArthur a=CohenArthur
When parsing macro invocations, rustc does not actually consume the
statement's trailing semicolon.
Let's take the following example:
```rust
macro_rules! one_stmt {
($s:stmt) => {};
}
macro_rules! one_or_more_stmt {
($($s:stmt)*) => {};
}
one_stmt!(let a = 1);
one_stmt!(let b = 2;); // error
one_or_more_stmt!(;); // valid
one_or_more_stmt!(let a = 15;); // valid, two statements!
one_or_more_stmt!(let a = 15 let b = 13); // valid, two statements again
```
A semicolon can count as a valid empty statement, but cannot be part of
a statement (in macro invocations). This commit adds more restrictions
that allow the parser to not always expect a semicolon token after the
statement. Furthermore, this fixes a test that was previously accepted
by the compiler but not by rustc.
Fixes#1046
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
1044: Restrict follow-up tokens on `expr` and `stmt` r=CohenArthur a=CohenArthur
This adds a base for respecting the [Macro Follow-Set Ambiguity specification](https://doc.rust-lang.org/reference/macro-ambiguity.html).
If the design is validated, adding more restrictions on other fragment specifiers should not be difficult
Addresses #947
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
Rust does not allow for all macro fragments to be followed by any kind
of tokens: We must check tokens following those fragments that might
contain restrictions and make sure that they are allowed, conforming to
the Macro Follow-Set Ambiguity specification
Co-authored-by: philberty <philip.herron@embecosm.com>
macro-frag-spec: Transform enum into a class
This allows us to add methods on the fragment specifier, which are
needed to make sure that follow-set ambiguities are respected
tests: Add tests for forbidden follow-up tokens
This also fix a test that was previously accepted but invalid: rustc
also rejected it
1026: Enable -Werror r=tschwinge a=CastilloDel
Fixes#694
- \[x] GCC development requires copyright assignment or the Developer's Certificate of Origin sign-off, see https://gcc.gnu.org/contribute.html or https://gcc.gnu.org/dco.html
- \[x] Read contributing guidelines
- \[ ] `make check-rust` passes locally
- \[ ] Run `clang-format`
- \[ ] Added any relevant test cases to `gcc/testsuite/rust/`
The last three ones shouldn't be necessary for this change.
---
Update the CI to use the bootstrap build process and enable -Werror
Signed-off-by: Daniel del Castillo <delcastillodelarosadaniel@gmail.com>
Co-authored-by: CastilloDel <delcastillodelarosadaniel@gmail.com>
Co-authored-by: Thomas Schwinge <thomas@codesourcery.com>
1047: Add helper debugging function for substituted tokens r=CohenArthur a=CohenArthur
Since this is less noisy, I guess we can keep it in at all times instead
of commenting it. Doing it like so - through a single function call -
means that we avoid creating the string entirely in release builds
Fixes#967
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
When parsing macro invocations, rustc does not actually consume the
statement's trailing semicolon.
Let's take the following example:
```rust
macro_rules! one_stmt {
($s:stmt) => {};
}
macro_rules! one_or_more_stmt {
($($s:stmt)*) => {};
}
one_stmt!(let a = 1);
one_stmt!(let b = 2;); // error
one_or_more_stmt!(;); // valid
one_or_more_stmt!(let a = 15;); // valid, two statements!
one_or_more_stmt!(let a = 15 let b = 13); // valid, two statements again
```
A semicolon can count as a valid empty statement, but cannot be part of
a statement (in macro invocations). This commit adds more restrictions
that allow the parser to not always expect a semicolon token after the
statement. Furthermore, this fixes a test that was previously accepted
by the compiler but not by rustc.
1041: macros: Only expand merged repetitions if they contain the same amount r=CohenArthur a=CohenArthur
Depends on #1040Fixes#948
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
This avoids the supposed issue that in case that 'make' fails, the whole
'jobs.build-and-check' stops, and 'Build logs' isn't executed, and thus there's
no indication in the GitHub UI why 'make' failed.
Using a shell pipeline is OK; the exit code of 'make' isn't lost, as per
<https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsshell>,
'bash' is being run with '-o pipefail'.
That's what I use in my local development enviroment, and I suppose I'll
be the main one touching this file semi-regularly in context of
<https://github.com/Rust-GCC/gccrs/issues/247> "Rebasing against GCC".
1040: Do not propagate parse errors in match repetitions r=CohenArthur a=CohenArthur
Since parsing repetitions is very eager, the parser might accumulate
bogus errors by trying to match more repetitions than there are. We can
avoid this by clearing the parsing errors if parsing repetitions
returned a valid result. This should not be an issue for previous
matchers erroring out, as they would immediately return upon failure and
not reach inside other match functions.
We need to figure out the best way to emit parser errors, as we do not always want to emit them in `match_fragment`. I think for now the easiest is to just *not* emit parse errors and simply error out with "failed to match macro rule". We will need to think about adding a bunch of hints too in order to make using macros easier.
Fixes#958
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
Since this is less noisy, I guess we can keep it in at all times instead
of commenting it. Doing it like so - through a single function call -
means that we avoid creating the string entirely in release builds
Co-authored-by: philberty <philip.herron@embecosm.com>
1042: Parse reserved keywords as valid fragments identifiers r=CohenArthur a=CohenArthur
Per the reference, macro fragments actually accept all identifiers, not
NON_KEYWORD_IDENTIFIERS
Fixes#1013
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
In order to support slices, we end up with an operator overload call of:
```
impl<T, I> Index<I> for [T]
where
I: SliceIndex<[T]>,
{
type Output = I::Output;
fn index(&self, index: I) -> &I::Output {
index.index(self)
}
}
```
So this means the self in this case is an array[T,capacity] and the index parameter is of type Range<usize>. In order to actually call this method
which has a self parameter of [T] we need to be able to 'unsize' the array
into a slice.
Addresses #849
Since parsing repetitions is very eager, the parser might accumulate
bogus errors by trying to match more repetitions than there are. We can
avoid this by clearing the parsing errors if parsing repetitions
returned a valid result. This should not be an issue for previous
matchers erroring out, as they would immediately return upon failure and
not reach inside other match functions.
1029: Macro in trait impl r=CohenArthur a=CohenArthur
Needs #1028
You can just review the last commit to avoid reviewing twice. Sorry about that!
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
This allows us to expand macor invocations in more places, as macro
calls are not limited to statements or expressions. It is quite common
to use macros to abstract writing repetitive boilerplate for type
implementations, for example.
1035: Handle -fsyntax-only r=CohenArthur a=CohenArthur
Handle the -fsyntax-only properly from the rust frontend. This flag
allows checking for syntax and stopping after that, skipping further
passes of the pipeline.
The flag was accepted by the frontend, but was not used anywhere.
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
1037: Support placeholders becoming slices r=philberty a=philberty
When we setup trait-impls the type-alias are allowed to become any type
this interface was missing a visitor. We also need to support constraining
type-parameters behind slices.
The get_root interface is currently unsafe, it needs a flag for allowing
unsized and for keeping a map of adjustments along the way. This will
be added down the line when we support unsized method resolution.
Fixes#1034
Addresses #849
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
Handle the -fsyntax-only properly from the rust frontend. This flag
allows checking for syntax and stopping after that, skipping further
passes of the pipeline.
The flag was accepted by the frontend, but was not used anywhere.
Co-authored-by: philberty <philip.herron@embecosm.com>
1027: parser: Allow parsing stmts without closing semicolon r=CohenArthur a=CohenArthur
In certain cases such as macro matching or macro expansion, it is
important to allow the parser to return a valid statement even if no
closing semicolon is given. This commit adds an optional parameter to
the concerned functions to allow a lack of semicolon those special cases
Closes#1011Closes#1010
1032: Add AST kind information r=CohenArthur a=CohenArthur
Closes#1001
This PR adds a base for adding node information to our AST types. It can be used when requiring to differentiate between multiple kinds of nodes, while not necessarily wanting to do a full static cast. This will open up a lot of cleanup issues and good first issues for Project Pineapple
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
When we setup trait-impls the type-alias are allowed to become any type
this interface was missing a visitor. We also need to support constraining
type-parameters behind slices.
The get_root interface is currently unsafe, it needs a flag for allowing
unsized and for keeping a map of adjustments along the way.
Fixes#1034
1022: attribute expansion: Fix spurious stripping of tail expression r=CohenArthur a=CohenArthur
This commit fixes the issue reported in #391, but highlights another
one, which will be reported.
Closes#391
1033: Fix bad copy-paste in can equal interface for pointer types r=philberty a=philberty
When we perform method resolution we check if the self arguments can be
matched. Here the bug was that pointer types had a bad vistitor and only
could ever match reference types which is wrong and was a copy paste error.
Fixes#1031
Addresses #849
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
1030: Rewrite our unconstrained type-param error checking r=philberty a=philberty
This is a series of patches that were all required to fix this issue. We
now take advantage of our substitutions abstractions and traits
so that our TypeBoundPredicate's which form the basis of our HRTB code
I think this class is almost akin to rustc existential-trait-references. This now
reuses the same code path to give us the same error checking for generics
as we get with ADT's, functions etc.
With this refactoring in place we can then reuse the abstractions to map the
ID's from the used arguments in the type-bound-predicate, the impl block type
substation mappings and the self type itself.
There are quite a few cases to handle and our testsuite picked up all the regressions
so no behaviour of our existing test-cases have changed now. See each commit for
more detailed information.
Fixes#1019
Addresses #849
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
When we perform method resolution we check if the self arguments can be
matched. Here the bug was that pointer types had a bad vistitor and only
could ever match reference types which is wrong and was a copy paste error.
Fixes#1031
This adds a new base class common to all abstract base classes of the
AST: We can use it to store information shared by all nodes, such as the
newly introduced `AST::Kind` which helps in differentiating nodes.
We could also consider using it to store location info, since all AST
nodes probably need it.
1021: macros: Do not try and re-expand if depth has exceeded recursion limit r=CohenArthur a=CohenArthur
We need to limit the amount of times that macro get expanded recursively
during macro-expansion. This limits the amount of times an ASTFragment
can be visited by simply incrementing the depth when setting a fragment,
and decreasing it when taking one. This way, recursive expansion which
happens at the expansion level (instead of the matching level) will
still get caught
Fixes#1012
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
This patch removes our old method of checking for unconstrained type
parameters which only worked for the basic cases such as:
impl<T> Foo { }
But checking for unconstrained types is more complex, we need to handle
covariant types such as:
impl<T> *T { }
Or
struct foo<X,Y>(X,Y);
impl<T> foo<&T,*T> {}
This rewrites the algorithm to take advantage of our substition
abstractions and HirIds so we can map the ids of the type-params to be
constrained and look at the trait-references used-arguments when the
generics are applied (or they may be empty) and then do the same for any
used arguments on an algebraic data type.
Fixes#1019
This will allow us to reuse our generic substitions code to manage generic
traits and their substitions better. It will unify the handling in one
path so we get the same error handling.
The TraitReference wrapper is a class that allows us to work with traits
in a query manar. This patch allows us to keep track of the substitution
mappings that are defined on the trait. This will always be non-empty
since traits always contain an implicit Self type parameter so there
is special handling in how we perform monomorphization.
This means TypeBoundPredicate will now be able to inherit all behaviours
of normal generics so we do not duplicate the work in handling generics
it will also allow us to more easily check for unconstrained type
parameters on traits.
In certain cases such as macro matching or macro expansion, it is
important to allow the parser to return a valid statement even if no
closing semicolon is given. This commit adds an optional parameter to
the concerned functions to allow a lack of semicolon those special cases
1025: Fix memory corruption in generation of builtin functions r=philberty a=philberty
This patch removes the pop_fn calls since no fncontext stack is required here for these intrinsic.
More context on the issues is in the commit message.
Fixes#1024
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
When we compile normal language functions we maintain a stack of the
current function declaration and associated return addresses. This is used
while building up the GCC tree graph. When we generate builtin intrinsic
functions such as offset or size_of were missing their associated push_fn
but still performed a pop_fn on completion this resulted in a corrupt
stack which valgrind shown as bad read/writes.
This patch removes the pop_fn calls since no fncontext stack is required here for these intrinsics.
Fixes#1024
We need to limit the amount of times that macro get expanded recursively
during macro-expansion. This limits the amount of times an ASTFragment
can be visited by simply incrementing the depth when setting a fragment,
and decreasing it when taking one. This way, recursive expansion which
happens at the expansion level (instead of the matching level) will
still get caught
1004: Added column!() macro r=CohenArthur a=mvvsmk
Fixes issue #979
1) Added the column!() macro using the LOCATION_COLUMN() from gcc_linemap
2) To-Do: add relevant test cases.
Signed-off-by : M V V S Manoj Kumar <mvvsmanojkumar@gmail.com>
The test case I added always fails, I can't figure out whether there is a problem in my test case or there is something wrong with my implementation of the column!() macro. Do let me know where I am going wrong and also if I missed something . :)
Co-authored-by: M V V S Manoj Kumar <mvvsmanojkumar@gmail.com>
Addresses issue #979
1) Added the column!() macro using the LOCATION_COLUMN() from gcc_linemap
2) Added relevent test cases
Signed-off-by : M V V S Manoj Kumar <mvvsmanojkumar@gmail.com>
1015: Add code generation for the slice type r=philberty a=philberty
This type must respect the layout of the FatPtr type in libcore. Rust
implements slices using Rustc types in libcore and uses a neat trick.
Addresses #849
1018: builtin-macros: Add more documentation for defining builtins r=CohenArthur a=CohenArthur
`@mvvsmk` you might find this a little more clear. Sorry about the confusion!
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
1017: attr-visitor: Split in its own source and header r=CohenArthur a=CohenArthur
Split up the 4000 lines rust-macro-expand.cc file containing the
AttrVisitor class and the macro expander implementation
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
This type must respect the layout of the FatPtr type in libcore. Rust
implements slices using Rustc types in libcore and uses a neat trick.
The slice is generated into the FatPtr which contains the pointer and
length of the slice. This is then placed into a union called Repr which
has 3 variants a mutable and immutable pointer to the FatPtr and a final
variant which is the raw FatPtr. This means we can use unsafe access to
the union to gain a pointer to the FatPtr.
Addresses #849
1008: Add const_ptr lang item mappings r=philberty a=philberty
In order to support slices, we need to be able to parse and contain
mappings for the const_ptr lang item. We do not need to do any
special handling of this lang item yet but this adds the mappings
so when we hit it we do not output an unknown lang item error.
Addresses #849
1009: Add missing type resolution to slices and arrays r=philberty a=philberty
This adds in the missing type resolution for slices and generic slices
and arrays. Since Arrays and Slices are both covariant types just like
references and pointers for example they need to handle recursive
substitutions where their element type might be a generic type
that can bind substitution parameters such as functions and ADT's.
Addresses #849
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
1007: Add missing canonicalization of slices and raw pointer types r=philberty a=philberty
This is part of my patch series for slices. This adds the missing visitors
for name canonicalization. More information in the patch, once we get
slice support in we need to start taking advantage of `@dkm's` HIR
visitor refactoring to avoid these issues with missing visitors making
simple bugs hard to track down.
Fixes#1005
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
1003: Add more intrinsics and refactor how we implement them r=philberty a=philberty
This patch series implements:
1. offset
2. size_of
3. unreachable
4. abort
It removes the GCC wrapper mappings to make them much easier to implement. It also demonstrates in single commits
the implementation of each of these intrinsic to make it easy to follow in how we implement them.
Addresses #658#849
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
1002: macros: Add abstraction around multiple matches r=CohenArthur a=CohenArthur
Adds an extra layer of abstraction around keeping multiple matches for
the same fragment. This avoids ugly code fetching the first match in
order to get the amounf of matches given by the user, while still
allowing zero-matches to exist.
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
998: Parse macro expansion properly r=CohenArthur a=CohenArthur
This PR adds a base for trying to parse statements or items in macro invocations. We are now able to parse multiple items / expressions / statements properly, but do not lower them properly, which is the last remaining task in #943
New macro parsing logic:
```mermaid
flowchart TD;
has_semi -- Yes --> stmt;
has_semi -- No --> invocation;
invocation -- Is Parens --> expr;
invocation -- Is Square --> expr;
invocation -- Is Curly --> stmt;
```
Closes#943Closes#959Closes#952
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
Different parsing functions need to be called based on the context
surrounding the macro invocation. This commit adds a flowchart trying to
explain the base resolving rules
Macro expansion happens at the same level as stripping, where nodes
might get removed if they are gated behind an unmet predicate. We also
perform macro expansion during this visitor's pass.
What we can do is thus to replace macro invocations with new items that
might have resulted from macro expansion: Since we're already mutating
numerous elements by removing them if they should be stripped, we can
also add elements if they should be expanded.
This commit also "fixes" macro test cases so that they are now accepted
by the new parser, which is more strict than it should for now.
Co-authored-by: SimplyTheOther <simplytheother@gmail.com>
Co-authored-by: philberty <philip.herron@embecosm.com>
Adds an extra layer of abstraction around keeping multiple matches for
the same fragment. This avoids ugly code fetching the first match in
order to get the amounf of matches given by the user, while still
allowing zero-matches to exist.
Co-authored-by: philberty <philip.herron@embecosm.com>
Slices and Arrays are covariant types which means they can contain elements
which bind generics such as ADT or FnTypes. This means substitutions can be
recursive and this gives the typechecker a chance to handle this recursion
on these types.
When we intercept impl blocks for slices or raw pointers we must generate
the canonical path for this for name resolution this adds in the missing
visitors which will generate the path. Previously this was defaulting to
empty path segments and then hitting an assertion when we append the
empty segment.
Fixes#1005
This is another type of intrisic since the function contains no parameters
but the argument for the size_of is the generic parameter T. Which uses
TYPE_SIZE_UNIT to get the type size in bytes. GCC will optimize the
function call away when you turn optimizations on.
Addresses #658
Intrinsics were hidden behind the GCC abstract. This removes it by keeping
all of this logic within rust-intrinsic.cc so that we can make mappings of
the rustc name to GCC ones. We have a big comment from the mappings used
over to LLVM builtins which we can use to help guide how we do this for
GCC.
This patch adds the initial support for generic intrinsics these are do not
map directly to GCC builtins and need to be substited with their specificed
types. This patch allows for custom implementation body for these functions
by specifying handler functions which will generate the applicable
intrinsic when asked for.
Addresses #658
999: Refactor ABI options as part of HIR function qualifiers r=philberty a=philberty
This is a refactor to cleanup HIR::ExternBlock and HIR::FunctionQualifiers
to have an enum of ABI options to improve the error handling.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
994: Parse macro patterns properly in repetitions r=CohenArthur a=CohenArthur
Closes#966
We actually cannot reuse functions from the parser since we're expanding a macro transcriber. This is fine as the "algorithm" is extremely simple
997: macros: Allow any delimiters for invocation r=CohenArthur a=CohenArthur
Closes#946
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
The AST has an ABI string as part of the function qualifiers, this was the
same in the HIR as it was initially a copy-paste. This patch changes the
HIR function qualifiers to have an enum of ABI options, during HIR lowering
the enum is setup and if an unknown ABI option is specified an error is
emitted.
It is not necessary for macro invocations to match the delimiters used
in the matcher. A matcher using parentheses can be invoked with curlies
or brackets, as well as any other combination(curlies matcher can be
invoked with parentheses or brackets)
992: Cleanup bad unused code warnings r=philberty a=philberty
This patchset contains 4 distinct fixes:
When a constant is declared after where it is used the code-generation pass falls
back to a query compilation of the HIR::Item this did not contain a check to verify
if it was already compiled and results in duplicate CONST_DECLS being generated
if query compilation was used.
We were using a zero precision integer to contain unit-type expressions this results
in VAR_DECLS being lost in the GENERIC graph which does not allow us to perform
any static analysis upon the DECL. This changes the unit type to use an empty struct
and for initialization of a VAR_DECL we can simply pass an empty constructor and let
GCC optimize this code for us.
Update our DEAD_CODE scan to take into account modules of items and also respect
if structures are prefixed with an underscore we can ignore generating an unused warning.
Remove our AST scan for unused code and reuse GCC TREE_USED to track wether
VAR_DECL, PARM_DECL, CONST_DECL are actually used or not. We reuse the GCC
walk_tree functions to have this as nice separate lint.
Fixes#676
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
This now uses the TREE_USED fields on GCC tree's to track the usage of
VAR_DECLS, PARM_DECLS and CONST_DECLS. The code does a pass over the body
and parameters of functions as a lint pass.
Fixes#676
991: Match and expand macro separators properly r=CohenArthur a=CohenArthur
More nice recursive macros:
```rust
macro_rules! add {
($e:expr | $($es:expr) | *) => {
$e + add!($($es) | *)
};
($e:expr) => {
$e
};
}
add!(1 | 2 | 3 | 4 | 5 | 6);
```
Closes#968
This PR needs #986 to be merged first, as it depends on it for the test cases. You can skip reviewing the first two commits which are just from #986
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
986: Fix ICE on recursive macro invocation r=CohenArthur a=CohenArthur
Closes#982
We can now do fancy lispy things!
```rust
macro_rules! add {
($e:literal) => {
0 + $e
};
($e:literal $($es:literal)*) => {
$e + add!($($es)*)
};
}
```
I've switched the order of the commits around so that the buildbot is happy
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
985: Parse macro!(); as MacroInvocation with semicolon r=CohenArthur a=CohenArthur
When parsing a macro invocation as a statement, the parser would parse
an expression and then try parsing a semicolon. Since no actual
lookahead was done (which is a good thing), we couldn't convert a
`MacroInvocation` to a `MacroInvocationSemi` after the fact.
Since, unlike function calls, macro invocations can act differently
based on whether or not they are followed by a semicolon, we actually
need to differentiate between the two up until expansion.
This commits adds a new virtual method for ExprWithoutBlock when
converting to ExprStmtWithoutBlock so that classes inheriting
ExprWithoutBlock can specify a new behavior. In the case of our
MacroInvocation class, it simply means toggling a boolean: If we're
converting a macro from an expression to a statement, it must mean that
it should contain a semicolon.
Closes#941
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
990: Add must use attribute support r=philberty a=philberty
This is a port of the CPP front-end nodiscard attribute to be used for
must_use. It contains a patch to clean up how we handle expressions vs
statements and removes more of the GCC abstraction. Its my hope that we
can leverage more and more existing code to get the static analysis where
we want it.
Fixes#856
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
984: Implimented Soluion 1 and solution 2 for issue_734 r=philberty a=mvvsmk
Fixes#734
Done :
- [x] Remove iterate_params function
- [x] Create new get_params function
Solution 1
1) Created a new get_params function which returns the parameters.
2) Changed the references of the iterate_params to use get_params.
Solution 2
1) Added get_params2 which returns `std::vector<TyTy::BaseType*>`
2) Changed the references of the iterate_params to use get_params.
Status :
Currently I have implemented the first solution.
Signed-off-by : M V V S Manoj Kumar <mvvsmanojkumar@gmail.com>
Co-authored-by: M V V S Manoj Kumar <mvvsmanojkumar@gmail.com>
Fixes issue #734
1)Removed iterate_params function
2)Created a get_params function which returns std::vector& params
Signed-off-by : M V V S Manoj Kumar <mvvsmanojkumar@gmail.com>
When creating a sub-map for repetitions, we need to be weary of not
accessing matched-fragments beyond the vector's size. For example, with
the following *fragments*
{ "e": [1], "es": [2, 3, 10]},
the sub-maps we want to create are the following:
{ "e": [1], "es": [2]},
{ "e": [1], "es": [3]},
{ "e": [1], "es": [10]},
Up until this point however, we were trying to access the second index
for the "e" metavar when creating the second submap, then the third, and
so on... which is obviously outside of the vector's bounds.
We can simply check if the metavar only has one match and expand that
one in that case. We still need to work on checking that multiple
metavars in the same transcriber repetition pattern have the same amount
of matched fragments (ie the original vectors of matches in the
original map have the same size)
This ports over the code from the cpp front-end which implements the cpp
nodiscard attribute which has the same behaviour and is also implemented
in the front-end explicitly.
Fixes#856
The gcc abstraction contained a method of turning expressions into
statements which used to contain their own types like Bstatement,
Bexpression this produced awkward interfaces which we no longer require.
This is part of a patch series to introduce the CPP front-end
convert_to_void to port over the support for the nodiscard attribute which
maps nicely over to Rust's must_use attribute.
Fixes the -fself-test invalid memory accesses and adds documentation
regarding a possible future fix.
Co-authored-by: tschwinge <thomas@schwinge.name>
Co-authored-by: philberty <philip.herron@embecosm.com>
When creating a sub-map for repetitions, we need to be weary of not
accessing matched-fragments beyond the vector's size. For example, with
the following *fragments*
{ "e": [1], "es": [2, 3, 10]},
the sub-maps we want to create are the following:
{ "e": [1], "es": [2]},
{ "e": [1], "es": [3]},
{ "e": [1], "es": [10]},
Up until this point however, we were trying to access the second index
for the "e" metavar when creating the second submap, then the third, and
so on... which is obviously outside of the vector's bounds.
We can simply check if the metavar only has one match and expand that
one in that case. We still need to work on checking that multiple
metavars in the same transcriber repetition pattern have the same amount
of matched fragments (ie the original vectors of matches in the
original map have the same size)
981: macro-expand: Add SubstitutionCtx class in its own file r=CohenArthur a=CohenArthur
The `MacroExpander` class had multiple static functions which were constantly passing the same parameters around for expansion. This refactor adds a new `SubstituteCtx` class which keeps track of the three common arguments given to the substitute functions, and offers these implementations in a new source file to keep the original expander light.
Closes#957
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
When parsing a macro invocation as a statement, the parser would parse
an expression and then try parsing a semicolon. Since no actual
lookahead was done (which is a good thing), we couldn't convert a
`MacroInvocation` to a `MacroInvocationSemi` after the fact.
Since, unlike function calls, macro invocations can act differently
based on whether or not they are followed by a semicolon, we actually
need to differentiate between the two up until expansion.
This commits adds a new virtual method for ExprWithoutBlock when
converting to ExprStmtWithoutBlock so that classes inheriting
ExprWithoutBlock can specify a new behavior. In the case of our
MacroInvocation class, it simply means toggling a boolean: If we're
converting a macro from an expression to a statement, it must mean that
it should contain a semicolon.
In order to conform to the rust reference, we must make sure that when
parsing -frust-cfg key-value pairs, we actually parse a valid key and
value. The key must be a valid identifier, while the value must be a
valid identifier surrounded by double quotes
By allowing us to parse strings directly instead of necessarily a
filename, we are now able to reuse the parser and lexer in various
places of the compiler. This is useful for -frust-cfg, but may also come
in handy for
other compiler mechanics such as the include!() builtin macro, where we
do not actually want location info but just a stream of tokens.
954: HIR Visitor refactoring r=philberty a=dkm
This change split the single HIR visitor in smaller abstract ones:
- Stmt
- VisItem
- Pattern
- ExternalItem
- Impl
- Type
- Expression
Instead of providing a Base class with empty visit() methods, they are kept
abstract to avoid the case where a missing visit() is silently ignored:
implementors must explicitely override all visit.
There is also a FullVisitor that covers all HIR nodes and also provides a Base
class with empty behavior.
fixes#825
Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
Co-authored-by: Marc Poulhiès <dkm@kataplop.net>
This change split the single HIR visitor in smaller abstract ones:
- Stmt
- VisItem
- Pattern
- ExternalItem
- Impl
- Type
- Expression
Instead of providing a Base class with empty visit() methods, they are kept
abstract to avoid the case where a missing visit() is silently ignored:
implementors must explicitely override all visit.
There is also a FullVisitor that covers all HIR nodes and also provides a Base
class with empty behavior.
fixes#825
Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
974: Add support for ranges and index lang items along with the TyTy::SliceType r=philberty a=philberty
This PR contains more code to begin supporting Slices which requires support
for more intrinsic, range and index lang items. More work is needed to support
slices such as the const_ptr lang item and the offset intrinsic but this is a big
PR already and adds support for more lang items along the way.
Fixes#975
Addresses #849
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
This reuses our code to resolve operator overloads to call into the index
lang item for the array-index-expression this serves as a basis for
supporting slices.
Fixes#975
This means we can reuse the same code for operations that are not
HIR::OperatorExpr's such as ArrayIndexExpr which can resolve to
core::ops::index lang items.
969: Add builtin macros framework r=CohenArthur a=CohenArthur
This PR adds bases to define new builtin macro functions.
Since we operate at the `insert_macro_def` level, this requires builtin macros to be defined, as is the case in the rust standard library:
```rust
macro_rules! assert {
($cond:expr $(,)?) => {{ /* compiler built-in */ }};
($cond:expr, $($arg:tt)+) => {{ /* compiler built-in */ }};
}
```
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
956: Substitute repetitions r=CohenArthur a=CohenArthur
Needs #955
This PR splits up the `substitute_tokens` function into multiple smaller functions. Still a draft until I can get repetitions working.
Closes#960Closes#961
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
953: Refactor lang item mappings r=philberty a=philberty
This refactors how we find our lang items so that during HIR lowering
we have a generic outer attributes handler on Items. The old code only
done lang item mappings during the type check pass and assumed all
lang items are Traits which is not the case. To implement slices range
syntax actually map to structs within libcore/ops/range.rs which have
lang items on structs. This means we can have lang items on any Item.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
This class keeps track of all known builtin attributes and specifies which
pass they are handled at. This replaces the checks we added for outer
attributes during hir lowering making it a more maintainable data
structure.
964: Forbid unresolved test cases r=CohenArthur a=CohenArthur
Closes#923
965: macro-invoc-lexer: Split implementation in its own file r=CohenArthur a=CohenArthur
Closes#949
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
950: Match macro repetitions r=CohenArthur a=CohenArthur
This PR adds support for matching macro invocations and counting the amount of times they've been matched
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
951: Add name resolution to slices r=philberty a=philberty
This is the first part to support slices where we complete the name
resolution of the SliceType with its element as well as the range
expressions used in construction.
This patch also includes separation of the implementation from the
headers to try and incrementally improve build speed.
Addresses #849
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
944: parser: Add `clear_errors()` method r=CohenArthur a=CohenArthur
Clears all errors from the error table so we can reuse the parser in later situations. I'm unsure whether or not the method should also emit all of the errors if present? In that case, we might want to rename it or add another wrapper that emits then clears
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
942: Removed Lambda Function within AST::PathPattern r=philberty a=mvvsmk
Addresses issue #717
1) Changed the rust-path.h and removed the iterate_path_segments
fuction.
2) Removed the lambda fuction form rust-ast-lower.cc and replaced it
with a for loop.
Do let me know if I missed anything or could improve on something.
Signed-off-by : M V V S Manoj Kumar <mvvsmanojkumar@gmail.com>
Co-authored-by: M V V S Manoj Kumar <mvvsmanojkumar@gmail.com>
940: Add more location info to AST structures r=CohenArthur a=CohenArthur
Two classes still remain locus-less: `TupleStructItems` and `TuplePatternItems` as I do not believe they are constructed at the moment.
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
938: First pass at declarative macro expansion r=philberty a=philberty
This does not support repetition matchers but it supports simple
declarative macros and transcribes them. The approach taken here is that
we reuse our existing parser to call the apropriate functions as specified
as part of the MacroFragmentType enum if the parser does not have errors
parsing that item then it must be a match.
Then once we match a rule we have a map of the token begin/end offsets
for each fragment match, this is then used to adjust and create a new token
stream for the macro rule definition so that when we feed it to the parser
the tokens are already substituted. The resulting expression or item is
then attached to the respective macro invocation and this is then name
resolved and used for hir lowering.
Fixes#17#22
Addresses #573
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
Addresses issue #717
1) Changed the rust-path.h and removed the iterate_path_segments
fuction.
2) Removed the lambda fuction form rust-ast-lower.cc and replaced it
with a for loop.
Signed-off-by : M V V S Manoj Kumar <mvvsmanojkumar@gmail.com>
This allows for macro invocation at the toplevel or as statements. This
patched required us to propogate the delimited token tree fix to include
the delimiter tokens. The rest of the fix was straight forward to call
the apropriate visitors in names resolution and hir lowering.
Some thought will be needed to handle hir lowering for repeating items.
When we parse DelimTokenTree's the delimiter's are synthesised when we
ask for the token stream which results in tokens lacking location info.
This removes the hack by adding the actual tokens from the lexer into the
stream.
This is the first pass at implementing macros more testcases are needed.
This does not support repetition matchers but it supports simple
declarative macros and transcribes them. The approach taken here is that
we reuse our existing parser to call the apropriate functions as specified
as part of the MacroFragmentType enum if the parser does not have errors
parsing that item then it must be a match.
Then once we match a rule we have a map of the token begin/end offsets
for each fragment match, this is then used to adjust and create a new token
stream for the macro rule definition so that when we feed it to the parser
the tokens are already substituted. The resulting expression or item is
then attached to the respective macro invocation and this is then name
resolved and used for hir lowering.
Fixes#17#22
Addresses #573
935: frust-cfg: Only allow double quoted values r=philberty a=CohenArthur
Closes#910
This PR separates the `handle_cfg_option()` function in two, separating the parsing logic from the session logic. The parsing logic is able to be unit tested, and now only allows quoted values.
What remains to be done is to only allow `key` and `value` to be proper rust identifiers. We need to figure out if we'd like to spawn a parser here and parse identifiers, or simply sanitize both strings to make sure they do not contain invalid characters.
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
This commit separates the `handle_cfg_option()` function in two,
separating the parsing logic from the session logic. The parsing logic
is able to be unit tested, and now only allows quoted values.
932: Add location information to MacroRule r=CohenArthur a=CohenArthur
Closes#930
This PR adds location information to the `MacroRule` structure.
The location is from the beginning of the invokation pattern, so that errors look like so:
```rust
test.rs:2:5: error: ...
2 | ($a:expr, $b:expr) => { a + b }
| ^
```
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
933: macrotranscriber: Add location info r=CohenArthur a=CohenArthur
Closes#929
Adds location info to the macro's transcriber. When generating a `MacroRule` error, this PR creates an empty location for the transcriber, since the error function is only called if no fat arrow is present or if there was an error parsing the macro's matcher. Please let me know if this is the expected behavior
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
934: macromatch: Add location to abstract MacroMatch class r=philberty a=CohenArthur
Closes#928
This adds location to the all child classes of the `MacroMatch` abstract class. The current locations are as follow, which I believe is what is expected but might be wrong.
```rust
test.rs:2:6: error: macro match fragment
2 | ($a:expr, $b:expr) => { $a + $b };
| ^
test.rs:2:15: error: macro match fragment
2 | ($a:expr, $b:expr) => { $a + $b };
| ^
test.rs:2:5: error: macro matcher
2 | ($a:expr, $b:expr) => { $a + $b };
| ^
test.rs:3:8: error: macro match fragment
3 | ($($i:ident)*) => { $($i)* }
| ^
test.rs:3:17: error: macro match repetition!
3 | ($($i:ident)*) => { $($i)* }
| ^
test.rs:3:5: error: macro matcher
3 | ($($i:ident)*) => { $($i)* }
| ^
```
I think this should be rebased on #932 so that I can remove the FIXME
937: dockerfile: Install cargo-gccrs alongside gccrs r=philberty a=CohenArthur
Closes#826
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
931: rust-cfg: Quote option name when erroring out r=philberty a=CohenArthur
Removes a warning generated by `-Wformat-diag`
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
926: macros: Add multiple macro syntax tests r=CohenArthur a=CohenArthur
This PR adds test cases for macros, including parsing and execution.
I am unsure on how to check for proper execution: The solution I have chosen so far is to make sure that a correct amount of lines is printed, which I'm not entirely satisfied with.
Another solution would be to increase a global integer to use when exiting, which we can then assert on using dejagnu, which is cleaner but relies on unsafe rust code.
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
922: Support inline never and always options r=philberty a=philberty
This maps over to DECL_UNINLINEABLE and to use the GCC attribute
always_inline.
Fixes#921
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
920: Support deref_mut lang item during method resolution r=philberty a=philberty
This adds in the lookups for the DEREF_MUT lang item for operator overloading
this needs more testing to ensure the behaviour is correct and is the same as
rustc.
Fixes#890
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
When we have method resolution we need to look at any deref lang items for
the receiver. The precise rules need to be tested rigorously to ensure this is right.
Fixes#890
918: Refactor code to reuse a canonical way to compile items r=philberty a=philberty
This is a big cleanup so all paths that compile functions and constants
end up in the same path so we avoid any duplication in how we actually
compile a function or constant.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
This is a big cleanup so all paths that compile functions and constants
end up in the same path so we avoid any duplication in how we actually
compile a function.
917: remove tree addressable context during type checking r=philberty a=philberty
We can reuse more C front-end code c_mark_addressable can be used instead
of trying to track TREE_ADDRESSABLE as part of type-checking. This also
pulls the GCC::Backend::address_expression to be part of the HIRCompileBase
class during code-generation.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
We can reuse more C front-end code c_mark_addressable can be used instead
of trying to track TREE_ADDRESSABLE as part of type-checking. This also
pulls the GCC::Backend::address_expression to be part of the HIRCompileBase
class during code-generation.
916: Support inline attribute by marking as DECL_DECLARED_INLINE_P r=philberty a=philberty
This does a refactor by removing more flags for the fndecl construction
from the rust-gcc wrapper code in favour of using the tree api directly.
The ABI option attributes have also been refactored from the backend
interface in favour of their own package.
The gccgo wrapper tried to mark inline fns as extern inline but this
refactor allows us to control the inline options specificly for the
rust semantics.
Fixes#857
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
This does a refactor by removing more flags for the fndecl construction
from the rust-gcc wrapper code in favour of using the tree api directly.
The ABI option attributes have also been refactored from the backend
interface in favour of their own package.
The gccgo wrapper tried to mark inline fns as extern inline but this
refactor allows us to control the inline options specificly for the
rust semantics.
Fixes#857
912: Handle generic substitution on path expressions r=philberty a=philberty
In this bug the path expression failed to take Foo::<i32> and apply this
bound generic argument into the impl block. The fn type for this function
test is:
fn <T,Y>test(a:T, b:Y);
But the impl block has a Self of Foo<T> so we need to inherit the T
argument from the previous Foo::<i32> which was missing.
Fixes#893
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
911: Refactor to_string from header to impl file r=philberty a=philberty
This is part of the overal cleanup to move implementation into cc files from the headers.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
In this bug the path expression failed to take Foo::<i32> and apply this
bound generic argument into the impl block. The fn type for this function
test is:
fn <T,Y>test(a:T, b:Y);
But the impl block has a Self of Foo<T> so we need to inherit the T
argument from the previous Foo::<i32> which was missing.
Fixes#893
909: Add support for key = value pairs on -frust-cfg= r=philberty a=philberty
This adds in a basic parser to parse out key value pairs for the config
option it needs to be tested poperly once the self-test framework is
merged in.
Fixes#889
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
888: Added location data to Match Arm and removed unused code r=philberty a=mvvsmk
Fixes#863
- Added location data to Match arm in gcc/rust/ast/rust-expr.h and gcc/rust/hir/tree/rust-hir-expr.h
- Updated the respective constructors and copy constructors
- Updated location info for match arm in code generation in gcc/rust/backend/eust-compile-expr.cc
- Removed unused code in the above rust-expr.h and rust-gir-expr.h files as mentioned in the issue by `@philberty.`
- Comment removed form rust-expr.h
- Changed partameterized constructor and static function in
rust-hir-expr.h
- Changed line 697 to pass expr.get_locus() in rust-ast-lower
- Changed parameterised constructor in rust-expr.h
- Changed line 8563 in rust-parse-impl.h to pass location data.
Note :
- I also added a public member funtion for the class MatchArm
`Location get_locus ( ) const { return locus; }`
Do me know if I missed anything or could improve on something.
Signed-off-by : M V V S Manoj Kumar <mvvsmanojkumar@gmail.com>
Co-authored-by: @mvvsmk <mvvsmanojkumar@gmail.com>
908: Fix '-Wformat-diag' issue in 'TypeCheckPattern::visit (HIR::TupleStructPattern &pattern)' r=philberty a=tschwinge
It's alread now diagnosed, non-fatal warning:
[...]/source-gcc/gcc/rust/typecheck/rust-hir-type-check-pattern.cc: In member function ‘virtual void Rust::Resolver::TypeCheckPattern::visit(Rust::HIR::TupleStructPattern&)’:
[...]/source-gcc/gcc/rust/typecheck/rust-hir-type-check-pattern.cc:61:69: warning: unquoted operator ‘::’ in format [-Wformat-diag]
61 | "expected tuple struct or tuple variant, found %s variant %s::%s",
| ^~
A later merge from GCC upstream will bring in
commit 34ba4275dc
"Enable -Werror=format-diag during bootstrap", which then causes:
[...]/source-gcc/gcc/rust/typecheck/rust-hir-type-check-pattern.cc: In member function ‘virtual void Rust::Resolver::TypeCheckPattern::visit(Rust::HIR::TupleStructPattern&)’:
[...]/source-gcc/gcc/rust/typecheck/rust-hir-type-check-pattern.cc:61:69: error: unquoted operator ‘::’ in format [-Werror=format-diag]
61 | "expected tuple struct or tuple variant, found %s variant %s::%s",
| ^~
cc1plus: all warnings being treated as errors
make[3]: *** [rust/rust-hir-type-check-pattern.o] Error 1
Co-authored-by: Thomas Schwinge <thomas@codesourcery.com>
751: Enable the usage of selftests r=tschwinge a=CohenArthur
From what I can understand, self tests seem to only be used in the C family of languages and in no other gcc frontend. And for some reason one of the self test for the gccrs frontend seem to be the parsing of C code and C types, which fails, which is why this PR is a draft. Once this is fixed, selftests should be enabled for the frontend and we should be able to add some to the project.
Co-authored-by: CohenArthur <arthur.cohen@epita.fr>
Co-authored-by: CohenArthur <cohenarthur.dev@gmail.com>
This adds in a basic parser to parse out key value pairs for the config
option it needs to be tested poperly once the self-test framework is
merged in.
Fixes#889
It's alread now diagnosed, non-fatal warning:
[...]/source-gcc/gcc/rust/typecheck/rust-hir-type-check-pattern.cc: In member function ‘virtual void Rust::Resolver::TypeCheckPattern::visit(Rust::HIR::TupleStructPattern&)’:
[...]/source-gcc/gcc/rust/typecheck/rust-hir-type-check-pattern.cc:61:69: warning: unquoted operator ‘::’ in format [-Wformat-diag]
61 | "expected tuple struct or tuple variant, found %s variant %s::%s",
| ^~
A later merge from GCC upstream will bring in
commit 34ba4275dc
"Enable -Werror=format-diag during bootstrap", which then causes:
[...]/source-gcc/gcc/rust/typecheck/rust-hir-type-check-pattern.cc: In member function ‘virtual void Rust::Resolver::TypeCheckPattern::visit(Rust::HIR::TupleStructPattern&)’:
[...]/source-gcc/gcc/rust/typecheck/rust-hir-type-check-pattern.cc:61:69: error: unquoted operator ‘::’ in format [-Werror=format-diag]
61 | "expected tuple struct or tuple variant, found %s variant %s::%s",
| ^~
cc1plus: all warnings being treated as errors
make[3]: *** [rust/rust-hir-type-check-pattern.o] Error 1
907: Support cfg expansions predicates r=philberty a=philberty
Config expansion can be not, any, or all predicate to enforce the config
expansion logic.
This patch refactors the MacroParser to be named AttributeParser as it is
only used to parse attributes into MetaItems that we can work with and
do expansion logic upon. This handles the case of parsing the
inner-meta-item of not(A) to parse it into MetaListNameValueStr and tidies
up some of the code in the area.
Fixes#901
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
Addresses issue #863
1)comment removed form rust-expr.h
2)changed partameterized constructor and static function in
rust-hir-expr.h
3)changed line 697 to pass expr.get_locus() in rust-ast-lower
4)changed parameterised constructor in rust-expr.h
5)changed line 8563 in rust-parse-impl.h to pass location data.
Signed-off-by : M V V S Manoj Kumar <mvvsmanojkumar@gmail.com>
To reduce the differences with GCC upstream, this reverts code formatting
changes of GCC/Rust commit ea5e2aff4e, keeping
just the 'TARGET_RUST_CPU_INFO' definition.
906: GCC/Rust pieces of GCC upstream "Mass rename of C++ .c files to .cc suffix" r=tschwinge a=tschwinge
... in preparation of merge of the latter.
Co-authored-by: Thomas Schwinge <thomas@codesourcery.com>
Config expansion can be not, any, or all predicate to enforce the config
expansion logic.
This patch refactors the MacroParser to be named AttributeParser as it is
only used to parse attributes into MetaItems that we can work with and
do expansion logic upon. This handles the case of parsing the
inner-meta-item of not(A) to parse it into MetaListNameValueStr and tidies
up some of the code in the area.
Fixes#901
903: Add new RustIdent struct to track canonical-path and location info r=philberty a=philberty
This refactors our TyTy type abstractions to contain their repspective
canonical-path and location info. This cleans up alot of location tracking
for example when we have generic structures we create implicit hirids which
may or may not have location info this now tracks the location info of
the declaration of the type avoiding any confustion.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
904: Apply the is_marked_for_strip check to the rest of the crate r=philberty a=philberty
We need to apply this to all levels of the crate:
Item
types
impl-item
trait-item
Stmt
expr's
Fixes#872
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
This refactors our TyTy type abstractions to contain their repspective
canonical-path and location info. This cleans up alot of location tracking
for example when we have generic structures we create implicit hirids which
may or may not have location info this now tracks the location info of
the declaration of the type avoiding any confustion.
902: Fix enum variant discriminant values r=philberty a=philberty
Enum discriminants before this patch were either:
- The hir-id of the tuple/struct variant
- The expression of the specified discriminant
- Computed int64 of the dataless variant
Each of these had tree ways of computing the qualifier this patch changes
this to be more in line with rust to compute the values unless its a
specified discriminant value. In order to compile this we now create an
implicit HIR::LiteralExpr and feed this into our constexpr code so it
reuses the same path as the variants with a specified constant
discriminant.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
Enum discriminants before this patch were either:
- The hir-id of the tuple/struct variant
- The expression of the specified discriminant
- Computed int64 of the dataless variant
Each of these had tree ways of computing the qualifier this patch changes
this to be more in line with rust to compute the values unless its a
specified discriminant value. In order to compile this we now create an
implicit HIR::LiteralExpr and feed this into our constexpr code so it
reuses the same path as the variants with a specified constant
discriminant.
900: Fixup logic in canonical-path for impl-blocks r=philberty a=philberty
Impl blocks canonical prefix when the size is one will only contain the
respective crate name but impl blocks canonical path will be of the Self
type which has its own respective crate and path so this will become the
canonical path of this. If the segment size greater than one this means it
is likely inside a mod block or other item so this means we should just
append as usual.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
Impl blocks canonical prefix when the size is one will only contain the
respective crate name but impl blocks canonical path will be of the Self
type which has its own respective crate and path so this will become the
canonical path of this. If the segment size greater than one this means it
is likely inside a mod block or other item so this means we should just
append as usual.
894: Update name-resolution to build up canonical-path with the crate-name r=philberty a=philberty
The name resolver there are two types of canonical-path object.
1. The relative canonical path to a type for name resolution
2. The full canonical-path including the crate-name (this-was-missing)
The lack of the crate-name being present in the canonical-path meant the
symbol mangling system was required to append it where appropriate but this
was going to be too messy to handle all cases. Such as module blocks
containing impl blocks requires a ```prefix::<impl crate::path>::item``` and
similarly for trait impl blocks.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
In the name resolver there are two types of canonical-path object.
1. The relative canonical path to a type for name resolution
2. The full canonical-path including the crate-name (this-was-missing)
The lack of the crate-name being present in the canonical-path meant the
symbol mangling system was required to append it where apropriate but this
was going to be too messy to handle all cases. Such as module blocks
containing impl blocks requires a prefix::<impl crate::path>::item and
similarly for trait impl blocks.
This patch updates the name-resolution system to build up the
canonical-path of items along side the relative type-paths at the same time
this needs to be done as it is not possible to resolve the canonical path
in the toplevel scan for all names within the crate when it comes to
impl/trait-impl blocks as they may be declared after the block so this
needs to be done at the same time as the normal name resolution mechanisms.
The patch here means the name-manglers no longer need to care about the
crate names of any item which is key for when we need to call functions
in other crates.
The CanonicalPath of an item such as a function at the moment does not
contain the associated crate name but it will eventually. This also updates
the legacy mangling to be even more conformant.
Qualified paths such as:
<A as B> are meant to actually start with _$LT$ and spaces are $u20$.
899: Add -frust-cfg=value option for adding config options r=philberty a=philberty
This adds the initial support for config expansion on custom config values
it need support for parsing options such as feature=test with apropriate
error handling withing Session::handle_cfg_option(const std::string&).
This also applies the mark_for_strip checks only on AST::Functions and
will need applied to the rest of the crate in #872.
Addresses #889
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
897: Remove unused include r=philberty a=philberty
We no longer need the tree within the type modules.
898: Add deref_mut lang_item mappings r=philberty a=philberty
This does not add support for deref_mut lang-items it just adds the mappings
so we can track the lang_item.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
This adds the initial support for config expansion on custom config values
it need support for parsing options such as feature=test with apropriate
error handling withing Session::handle_cfg_option(const std::string&).
This also applies the mark_for_strip checks only on AST::Functions and
will need applied to the rest of the crate in #872.
Addresses #889
Addresses #863
Added location data to Match arm in gcc/rust/ast/rust-expr.h and gcc/rust/hir/tree/rust-hir-expr.h
Updated the respective constructors and copy constructors
Updated location info for match arm in code generation in gcc/rust/backend/eust-compile-expr.cc
Removed unused code in the above rust-expr.h and rust-gir-expr.h files as mentioned in the issue.
Signed-off-by:M V V S Manoj Kumar <mvvsmanojkumar@gmail.com>
892: Remove bad assertion when resolving segments r=philberty a=philberty
When resolving segments in a path generics ones can match types in othe
impl blocks which will not be compiled yet so this assertion is bad.
Fixes#862
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
891: Remove hack to handle forward declared items r=philberty a=philberty
We used to use a compile_fns flag as a method to handle the case of code
such as:
```rust
fn foo() {
bar()
}
fn bar() { }
```
The compile_fns flag when set to false would allow us to do a toplevel
scan to compile the initial fndecl prototype of the functions as a method
of handling the case of the call to bar() within the body of foo.
The backend is setup now that we can 'query_compile' by compiling the
item as required with a cache if we have already done so.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
We used to use a compile_fns flag as a method to handle the case of code
such as:
```rust
fn foo() {
bar()
}
fn bar() { }
```
The compile_fns flag when set to false would allow us to do a toplevel
scan to compile the initial fndecl prototype of the functions as a method
of handling the case of the call to bar() within the body of foo.
The backend is setup now that we can 'query_compile' by compiling the
item as required with a cache if we have already done so.
873: Method resolution should respect deref lang-items r=philberty a=philberty
Method resolution in rust must respect the autoderef cycle by calling into the deref lang items as required. This
allows for method resolution behind boxing for example. See below for an example gimple dump of two levels
of deref operator overloads. The commit message ee794effe3 holds much
more detail on the changes in this patch.
```
void main ()
{
const struct bar;
const struct foo;
const i32 foobar;
try
{
bar.0 = 123;
foo.0 = &bar;
RUSTTMP.3 = <Foo as Deref>::deref<&Bar> (&foo);
RUSTTMP.5 = <&T as Deref>::deref<Bar> (RUSTTMP.3);
foobar = Bar::foobar (*RUSTTMP.5);
}
finally
{
bar = {CLOBBER};
foo = {CLOBBER};
}
}
```
Fixes#884
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
Autoderef includes calling into the deref operator overloads so for
example.
```rust
pub trait Deref {
type Target;
fn deref(&self) -> &Self::Target;
}
impl<T> Deref for &T {
type Target = T;
fn deref(&self) -> &T {
*self
}
}
struct Bar(i32);
impl Bar {
fn foobar(self) -> i32 {
self.0
}
}
struct Foo<T>(T);
impl<T> Deref for Foo<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0
}
}
fn main() {
let bar = Bar(123);
let foo: Foo<&Bar> = Foo(&bar);
let foobar: i32 = foo.foobar();
}
```
So you can see here we have a nested structure of Foo<&Bar> and Foo is a
generic structure, and we have a method call of foo.foobar(). This is an
interesting case of method resolution showing how rust allows for multiple
dereference to find the apropriate method of foobar.
So in this method call expression foo is of type Foo<&Bar> the generic
structure is a covariant Reference Type (&) of the structure Bar. The
method foobar has a receiver type of a simple Bar being passed by value.
So in order for this function to be called the method resolution system
has an algorithm of:
- reciever = Foo<&Bar>
- Find all methods named foobar
- try and match the receiver (self) with this reciever
- so that means we have Foo<&Bar> vs Bar which does not match
- Go back to the start and try by taking an immutable refernece
- &Foo<&Bar> does not match Bar
- Go back to the start and try by taking a mutable reference
- &mut Foo<&Bar> does not match Bar
- Try and dereference the original receiver Foo<&Bar>
- Do we have the deref lang item defined
- if yes resolve the method by the same mechanism for Foo<&Bar> for deref
- Get the result type of this function which is &&Bar do the dereference
- Now we have &Bar and a new adjustment for the original receiver
- Try and match &Bar to the foobar method reciever of Bar
- Try taking an immutable reference &&Bar
- Try taking a mutable reference &mut &Bar
- Try and deref &Bar we have the generic implementation of deref for &T
- Call this derefernece like before to get down to Bar
- Now try Bar on the foobar reciever Bar and it matches
We have now resolved the method with two dereference adjustments so the
function call becomes:
```
void main ()
{
i32 D.110;
const struct bar;
const struct foo;
const i32 foobar;
try
{
bar.0 = 123;
foo.0 = &bar;
RUSTTMP.3 = <Foo as Deref>::deref<&Bar> (&foo);
RUSTTMP.5 = <&T as Deref>::deref<Bar> (RUSTTMP.3);
foobar = Bar::foobar (*RUSTTMP.5);
}
finally
{
bar = {CLOBBER};
foo = {CLOBBER};
}
}
```
Obviously GCC will optimize this with -O2 so that it does not require
function calls but the gimple will show us what is actually going on. As
far as I am aware rustc pre-optimizes this regardless of optimizations
being turned on or not, these lang item functions are easily inlineable
so it makes more sense to me to let GCC's middle-end take care of this for
us.
This is a big patch and very difficult to split up as it reimplements our
method resolution system.
Fixes#884
883: Extract AsyncConstStatus to be a shared enum between AST and HIR r=philberty a=philberty
This allows us to reuse the same enum and fix the uninitilized warning
as it has already been setup before hand in the AST.
Fixes#875
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
885: Improve error message for failure in Method resolution r=philberty a=philberty
Use the locus for the method name segment and print its name as part of the
error message improves the quality of the error handling in the method
resolution.
Fixes#861
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
880: Covariant types should respect the get_name r=philberty a=philberty
This changes the Reference and Pointer types to respect the get_name
convention this means the canonical name for functions with their respective
substitutions string is properly formatted.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
Use the locus for the method name segment and print its name as part of the
error message improves the quality of the error handling in method
resolution.
Fixes#861
881: Add TraitItemKind to HIR TraitItems r=philberty a=philberty
This allows us to safely switch and cast between the items without the
need for visitors.
882: Add Mappings::iterate_trait_items helper r=philberty a=philberty
This helper is part of a larger PR into fixing our implementation of MethodResolution
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
879: Record correct location when compiling ADT types r=philberty a=dafaust
When compiling struct and union types, we were using the wrong HirId
to lookup location information. The resulting GIMPLE nodes therefore
had no source location information, which made them indistinguishable
as user-declarations versus decls created by the compiler. As a result,
the type names were not shown in GIMPLE dumps, e.g. using
-fdump-tree-gimple.
Fix the location lookup, so these types are properly printed, and add a
simple test checking as much.
Fixes: #877
Co-authored-by: David Faust <david.faust@oracle.com>
When compiling ADTTypes, the wrong HirId was being used for location
lookup. This produced an issue where the gimple dump would not write
type names for struct and union types, because they were mistaken for
built-in types.
Also add new test testsuite/rust/compile/torture/struct_decl.rs.
Fixes: #877
874: Track end locus of BlockExpr r=philberty a=dafaust
Capture the closing locus of a block during parsing, and remove the old
hack to get the final statement locus within the block now that it is
properly tracked.
Fixes#864
Co-authored-by: David Faust <david.faust@oracle.com>
Capture the closing locus of a block during parsing, and remove the old
hack to get the final statement locus within the block now that it is
properly tracked.
Fixes#864
870: Add constant folding to const functions r=philberty a=philberty
In Rust the ArrayType has a constant capacity constraint, which means it
allows for bounds checking at compile time as no variable-length arrays are
allowed. In order to typecheck this case we had a constant folding pass as
part of the type checking system which generated gcc tree's for the IR
and enforced the constant checking along the way.
GCC with optimizations turned on is capable of constant folding/propogating
the compilation unit fully, but we need a method that works regardless of
middlle-end optimizations to fold constant expressions at the front-end,
turns out the CPP front-end already does this via its constexpr
mechanism to ensure that these _do_ fold correctly. Another major reason
to do this change is that the original const fold pass was a striped down
copy of what the backend is _already_ doing which is creating a duplication
of the code generation pass. With this all unified into the code generation
pass all we need to do is port over gcc/cp/constexpr.c to enforce the const
rules fully but at the GCC tree level not at the typed HIR level.
Now that we have unified the pass when we hit a const function we can
simply emit a normal GCC function and outside of const expressions GCC
will simply emit a normal CallExpr and depending on optimization level
fully optimize this. If we are in a ConstDecl we will follow the
rust-constexpr.cc and fold the values or error_mark_node with an apropriate
error. By reusing the CPP constexpr code we _know_ it works so reusing it
as much as possible is a good idea in general for this front-end.
Fixes#799
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
BlockExpressions are usually evaluated by create a temporary variable to
hold the result of the tail expression in the correctly. Const expressions
do not have a context of a block so we must fold the value to store it
correctly without the need for temporary variables or a stack. To do this
we can leverage the fact that our constexpr code can fold simple CallExpr's
so in this patch we actually generate an implicit artifical function for
the block but do not add it to the translation unit and we then generate
an artifical CallExpr and pass it to the constant folder system, and then
assign the ConstDecl to this folded value thus reusing all of our existing
BlockExpression code instead of a seperate system.
Fixes#799
In Rust the ArrayType has a constant capacity constraint, this means it
allows for bounds checking at compile time as no variable length arrays are
allowed. In order to typecheck this case we had a constant folding pass as
part of the typechecking system which generated gcc tree's for the IR
and enforced the constant checking along the way.
Also after doing some testing GCC with optimizations turned on is capable
of constant folding/propogating the compilation unit fully. Which meant we
need a method of doing with regardless of optimization level to be able
to be on par with what the Rust language expects we need a full proof
method. Turns out the CPP front-end already does this via its constexpr
mechanism to ensure that these _do_ fold correclty. Another major reason
to do this change is that the original const fold pass was a striped down
copy of what the backend is _already_ doing which is creating a duplication
of the code generation pass. With this all unified into the code generation
pass all we need to do is port over gcc/cp/constexpr.c to enforce the const
rules fully but at the GCC tree level not at the typed HIR level.
Now that we have unified the pass when we hit a const function we can
simply emit a normal GCC function and outside of const expressions GCC
will simply emit a normal CallExpr and depending on optimization level
fully optimize this. If we are in a ConstDecl we will follow the
rust-constexpr.cc and fold the values or error_mark_node with an apropriate
error. By reusing the CPP constexpr code we _know_ it works so reusing it
as much as possible is a good idea in general for this front-end.
Addresses #799
860: Add overflow checking on LiteralExpression r=philberty a=philberty
This checks that the literal value is within the bounds of their respective
types. I have omitted code fixing the other issue in the bug report that
overflow/max_val integers should be saturated to infinity when cast to
REAL_TYPE's this seems like something we really should have documentation
to reference in the code as to why this is the correct Rust behaviour.
Addresses #635
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
868: Add support for Wildcard pattern binding r=philberty a=philberty
Wildcard bindings allow us to bind expression to be unused such as:
let _ = 123;
They are more commonly used in destructuring of tuples such as:
let my_tuple = (1,2);
let (a,_) = my_tuple;
This is the initial basic support for the basic form of let _ = ...; and
it also allows us to ignore parameters within functions as well.
Fixes#557
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
866: Add support for wildcard patterns within MatchExprs r=philberty a=philberty
GCC CASE_LABEL_EXPR's contain operand 0 and 1, operand 0 is used for the
low value of a case label and operand 1 for a high value. So with this
CASE_LABEL_EXPR is is possible to support a range of values from low->high
if set apropriately, but for the wildcard case this is effectively a
default case which means we set both operand 0 and 1 to NULL_TREE.
Fixes#853
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
859: Fix ICE in generic subsitution of enums containing dataless variants r=philberty a=philberty
Dataless variants do not contain fields that can be substituted, which then
hits an assertion on access of the fields for the variant. This patch adds
a guard against the substitution of dataless variants. We could have
removed the assertion which would have also been a good fix but keeping the
assertion for now is very helpful in debugging issues.
Fixs #851
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
847: HIR::ImplBlock items should mangle based from their canonical path's r=philberty a=philberty
Legacy mangling converts the '<', '>' from their canonical paths into '..'
this means we can simply reuse our normal mangle_item code for all types
of symbols. So we can now remove the mangle_impl_item code prior to having
the canonical path code in place.
Fixes#845
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
Wildcard bindings allow us to bind expression to be unused such as:
let _ = 123;
They are more commonly used in destructuring of tuples such as:
let my_tuple = (1,2);
let (a,_) = my_tuple;
This is the initial basic support for the basic form of let _ = ...; and
it also allows us to ignore parameters within functions as well.
Fixes#557
GCC CASE_LABEL_EXPR's contain operand 0 and 1, operand 0 is used for the
low value of a case label and operand 1 for a high value. So with this
CASE_LABEL_EXPR is is possible to support a range of values from low->high
if set apropriately, but for the wildcard case this is effectively a
default case which means we set both operand 0 and 1 to NULL_TREE.
Fixes#853
This checks that the literal value is within the bounds of their respective
types. I have ommited code fixing the other issue in the bug report that
overflow/max_val integers should be saturated to infinity when cast to
REAL_TYPE's this seems like something we really should have documentation
to reference in the code as to why this is the correct Rust behaviour.
Addresses #635
Dataless variants do not contain fields that can be substituted, which then
hits an assertion on access of the fields for the variant. This patch adds
a guard against the substitution of dataless variants. We could have
removed the assertion which would have also been a good fix but keeping the
assertion for now is very helpful in debugging issues.
Fixs #851
Legacy mangling converts the '<', '>' from their canonical paths into '..'
this means we can simply reuse our normal mangle_item code for all types
of symbol. So we can now remove the mangle_impl_item code prior to having
the canonical path code in place.
Fixes#845
846: HIR visitor refactor r=philberty a=dkm
This is the first step of a bigger refactor (see #825).
This patch introduces a new HIRFullVisitor with default implementations for all
visitor methods. This visitor is used as base classe for several existing HIR
visitors that also currently define empty behavior (eg. TypeCheckBase,
ConstFoldBase, ...).
Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
Co-authored-by: Marc Poulhiès <dkm@kataplop.net>
This is the first step of a bigger refactor (see #825).
This patch introduces a new HIRFullVisitor with default implementations for all
visitor methods. This visitor is used as base classe for several existing HIR
visitors that also currently define empty behavior (eg. TypeCheckBase,
ConstFoldBase, ...).
Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
842: add script to graph the changes over time r=philberty a=philberty
This script was used to get metrics and a graph for the 2021 end year report
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
841: Add support for enums on the match expression r=philberty a=philberty
This adds in the initial support MatchExpression which allows us to start testing much
more complex rust code. Ideally we can now start targeing the #682 to find nasty bugs
early as possible.
This takes the MatchExpr and generates a SWITCH_EXPR with associated
CASE_LABEL_EXPR's for the variants that the qualifier contains.
To improve this support in order to take advantage of SWITCH_ALL_CASES_P
to add error checking for all cases being covered. This will require changes
to the enum data structure to use ENUMERAL_TYPES instead of the flat i64
so the enumerable type contains the list of all possible permutations.
This patch is the first pass at the MatchExpr as the patch is already pretty
large and serves as a base to move forward.
Fixes#190
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
This is our initial first pass of adding support for the MatchExpr though
two things stand out here. We need to switch over to using a GCC enumeral
type for the union qualifier so we get advantage of the GCC code to ensure
all variants are being addressed. We also need to fix out enum type to
get better gdb support which might be simply chaning over to the
qual_union_type.
Fixes#190
839: Add typechecking for match-expr r=philberty a=philberty
This adds in the type checking pass for the match expression including static
analysis for errors such as:
- error[E0532]: expected tuple struct or tuple variant, found struct variant `Foo::D`
- error[E0027]: pattern does not mention fields `x`, `y`
- error[E0026]: variant `Foo::D` does not have a field named `b`
- error[E0532]: expected tuple struct or tuple variant, found struct variant `Foo::D`
Addresses #190
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
840: Add missing abstract method HIR::Pattern::get_locus() const r=philberty a=philberty
We have a missing locus here, there many places within the HIR where
we are missing location info such as HIR::MatchCase or HIR::MatchArm
come to mind. We also need to raise an issue to track CanonicalPath's and
location info within the TyTy module as part of a new Identifier structure which
will need to be raised in a separate PR+Issue.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
838: Add mssing mappings to HIR::Pattern r=philberty a=philberty
These mappings are missing within the HIR but are required
to complete typechecking of all patterns in match arms. As the
fields of structures must bind their associated field's types to new
names declared as part of the pattern, these mappings give access
to the associated name-resolved NodeId's to figure this out.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
837: HIR::IdentifierPattern had all fields public r=philberty a=philberty
This makes the fields private again and adds the missing getter for the
identifier.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
836: BugFix NodeId skew on AST::Patterns r=philberty a=philberty
The AST constructors implicitly generate new NodeId's, their associated
copy/move constructors ensure that they preserve the NodeId correctly.
The AST::Pattern's here incorrectly had a constructor in the abstract
base class which was generating the NodeId's but when this is used
within AST::MatchArms the fields contain these patterns which can get
copied/moved to cause new NodeId's to be generated which then throws off
type checking as the NodeId changes during HIR lowering and thus each of the
ID's are all off by one during type checking.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
The AST constructors implicitly generate new NodeId's, their associated
copy/move constructors ensure that they preserve the NodeId correctly.
The AST::Pattern's here incorrectly had a constructor in the abstract
base class which was generating the NodeId's but when this is used
within AST::MatchArms the fields contain these patterns which can get
copied/moved causing new NodeId's to be generated which then throws off
typechecking as the NodeId changes during HIR lowering and thus each of the
ID's are all of by one during typechecking.
835: Add name-resolution and HIR lowering pass for MatchExpr r=philberty a=philberty
This adds the name-resolution and HIR lowering pass for the match-expr
the type checking pass patch needs some work to be split up but these are
two nice isolated commits which are easier to read.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
834: Add enum code generation r=philberty a=philberty
This adds a naieve first pass approach to enum type code generation. The
original idea was to use GCC's QUAL_UNION_TYPE but I have ran into issues
with the DECL_QUALIFIER as my understanding of how this works is incorrect.
This takes an enum such as:
```rust
enum AnEnum {
A,
B,
C (char),
D (x: i64, y: i64),
}
```
And turns this into one big union consisting of all fields as RECORD_TYPES.
```c
union AnEnum {
record A { RUST$ENUM$DISR };
record B { RUST$ENUM$DISR };
record C { RUST$ENUM$DISR, char };
record D { RUST$ENUM$DISR, i64, i64};
}
```
see: 527b8861cd/gdb/dwarf2/read.c (L9010-L9241)
With the RUST$ENUM$DISR being the first field in all of the records this
means the alignment allows for indirect memory access of the struct to
use it as a qualifier field to figure out which variant is currently in
use. The data-less varients use their generated discriminat value during
type-checking the data variants use their HIR ID for their discriminant.
This will likely get redone to get improved GDB integration/updated to use
the QUAL_UNION_TYPE when we learn how to do this properly.
Fixes#79
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
This adds a naieve first pass approach to enum type code generation. The
original idea was to use GCC's QUAL_UNION_TYPE but I have ran into issues
with the DECL_QUALIFIER as my understanding of how this works is incorrect.
This takes an enum such as:
```rust
enum AnEnum {
A,
B,
C (char),
D (x: i64, y: i64),
}
```
And turns this into one big union consisting of all fields as RECORD_TYPES.
```c
union AnEnum {
record A { RUST$ENUM$DISR };
record B { RUST$ENUM$DISR };
record C { RUST$ENUM$DISR, char };
record D { RUST$ENUM$DISR, i64, i64};
}
```
see: 527b8861cd/gdb/dwarf2/read.c (L9010-L9241)
With the RUST$ENUM$DISR being the first field in all of the records this
means the alignment allows for indirect memory access of the struct to
use it as a qualifier field to figure out which variant is currently in
use. The data-less varients use their generated discriminat value during
type-checking the data variants use their HIR ID for their discriminant.
This will likely get redone to get improved GDB integration/updated to use
the QUAL_UNION_TYPE when we learn how to do this properly.
Fixes#79
832: Refactor TyTy::ResolveCompile pass to be in its own file r=philberty a=philberty
This name likely needs to be refactored, this class is used to take TyTy types
and compile them down to GCC tree's but take into account that we may have
already compiled this type before so to preserve the canonical types we
"resolve" the type if possible and then compile.
833: Refactor CallExpr and MethodCallExpr into rust-compile-expr.cc r=philberty a=philberty
Our compile times are very bad for the front-end code and this is part
of the drive to pull more implementation code out of headers and into
code files such that we can have smaller headers and many code files
to reduce recompilation of the same code.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
This name likely needs refactored, this class is used to take TyTy types
and compile them down to GCC tree's but take into account that we may have
already compiled this type before so to preserve the canonical types we
"resolve" the type if possible and then compile.
831: Fix out-of-bounds in typechecking of ADTTypes r=philberty a=philberty
In the case of an enum where there are more variants than the number of
fields within any variant we end up hitting an out of bounds exception
as we are using the wrong iterator on the fields during type checking.
This also means we were missing all possible fields in the case during
type checking.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
The type checking over the fields of each variant was using the wrong
iterator causing the type checker to go out of bound in the case where
there were more variants than fields within the variant.
```
terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check: __n (which is 2) >= this->size() (which is 1)
Program received signal SIGABRT, Aborted.
__GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:50
50 ../sysdeps/unix/sysv/linux/raise.c: No such file or directory.
(gdb) bt
...
-7 0x000000000119dcfc in std::vector<Rust::TyTy::StructFieldType*, std::allocator<Rust::TyTy::StructFieldType*> >::_M_range_check (this=0x426fb90, __n=2) at /usr/include/c++/9/bits/stl_vector.h:1070
-8 0x000000000119a2e5 in std::vector<Rust::TyTy::StructFieldType*, std::allocator<Rust::TyTy::StructFieldType*> >::at (this=0x426fb90, __n=2) at /usr/include/c++/9/bits/stl_vector.h:1091
-9 0x000000000117ead7 in Rust::TyTy::VariantDef::get_field_at_index (this=0x426fb60, index=2) at ../../gccrs/gcc/rust/typecheck/rust-tyty.h:1080
-10 0x00000000011c7523 in Rust::TyTy::ADTRules::visit (this=0x7fffffffce90, type=...) at ../../gccrs/gcc/rust/typecheck/rust-tyty-rules.h:1050
-11 0x00000000011b52a4 in Rust::TyTy::ADTType::accept_vis (this=0x4271120, vis=...) at ../../gccrs/gcc/rust/typecheck/rust-tyty.cc:642
-12 0x00000000011c2d80 in Rust::TyTy::BaseRules::unify (this=0x7fffffffce90, other=0x4271120) at ../../gccrs/gcc/rust/typecheck/rust-tyty-rules.h:85
-13 0x00000000011b552e in Rust::TyTy::ADTType::unify (this=0x426fe30, other=0x4271120) at ../../gccrs/gcc/rust/typecheck/rust-tyty.cc:670
-14 0x000000000118e49f in Rust::Resolver::TypeCheckExpr::visit (this=0x7fffffffd070, expr=...) at ../../gccrs/gcc/rust/typecheck/rust-hir-type-check-expr.h:1302
```
829: Constant folder now returns error_mark_node instead of nullptr r=philberty a=npate012
Removed nullptr checking on results from constant folder because when the
result is already error_mark_node, we no longer need to check if the result
is nullptr.
Fixes#692
Signed-off-by: Nirmal Patel <npate012@gmail.com>
830: Cleanup lambdas within some AST types r=philberty a=dafaust
Cleanup constructs like:
```C
struct_decl.iterate ([&] (AST::TupleField &field) mutable -> bool {
... /* do stuff with field */
});
```
For the following AST classes:
- AST::StructStruct
- AST::TupleStruct
- AST::Union
- AST::ArrayElemsValues
Fixes: #714Fixes: #715Fixes: #716Fixes: #720
Co-authored-by: Nirmal Patel <npate012@gmail.com>
Co-authored-by: David Faust <david.faust@oracle.com>
828: Add script to generate gource r=philberty a=philberty
This script tries to isolate our changes to GCC minus the changes to
gcc/config so that we can visualize our development history.
I will be uploading a video output to youtube shortly, it also includes our cargo-integration project too :D
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
These constructs make working with the IR needlessly complicated for
static analysis. Replace with simple for loops, and delete the old
Union::iterate () method.
Fixes: #716
These constructs make working with the IR needlessly complicated for
static analysis. Replace with simple for loops, and delete the old
StructStruct::iterate () method.
Fixes: #714
These constructs make working with the IR needlessly complicated for
static analysis. Replace with simple for loops, and delete the old
TupleStruct::iterate () method.
Fixes: #715
These constructs make working with the IR needlessly complicated for
static analysis. Replace with simple for loops, and delete the old
ArrayElemsValues::iterate () method.
Fixes: #720
Removed nullptr checking on results from constant folder because when the
result is already error_mark_node, we no longer need to check if the result
is nullptr.
Fixes#692
Signed-off-by: Nirmal Patel <npate012@gmail.com>
818: Deref operator overloading r=philberty a=philberty
This adds initial support for dereferencing operator overloading. We need to be able
to use this as part of the autoderef cycle next.
It has two default impl's one for '&T' and '&mut T' to apply genericly.
The reason it is interesting is from the prototype the deref lang item
always returns &Self::Target in all cases regardless of mutability, the
lang item here is designed to wrap up any dereference such that when
applied it guarentees the type system you will get back an immutable
reference to something. The reason for doing this is more clear when
thinking about autoderef and method-resolution and how you apply
dereference operations to custom types and a test case is included for
that.
Fixes#809
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
This adds in support for deref lang-item operator overloads. Deref operator
overloading is an interesting case of the libcore interaction with the
compiler. The deref operator lang item is:
```rust
pub trait Deref {
type Target;
fn deref(&self) -> &Self::Target;
}
```
It has two default impl's one for '&T' and '&mut T' to apply genericly.
The reason it is interesting is from the prototype the deref lang item
always returns &Self::Target in all cases regardless of mutability, the
lang item here is designed to wrap up any dereference such that when
applied it guarentees the type system you will get back an immutable
reference to something. The reason for doing this is more clear when
thinking about autoderef and method-resolution and how you apply
dereference operations to custom types and a test case is included for
that.
The autoderef mechanism will now need to be updated to support drefs fully.
Fixes#809
823: Support generics on operator overlads. r=philberty a=philberty
This ports over some code from the method-call expr to try and infer the
arguments in the function definition when required.
Addresses #809
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
821: Always update the type context for monoprhized items except type params r=philberty a=philberty
We need to update the type context type with the newly monomorphized types
we guarded against ADT's and functions because they were never added before
though this does not work for generic reference's to ADT's this updates
the check accordingly.
822: Make TyTy::BaseType::contains_type_parameters non-virtual r=philberty a=philberty
This is a second cleanup to the generic interfaces in the type system. The
helper for contains type parameters is akin to asking if a type is concrete
or not. If a type is not concrete ie: contains type parameters then this
can be leveraged instead of adding more complexity.
The TyTy::BaseType::is_concrete is already an abstract method forcing
all types to implement it, this makes it much safer and fixes some bad
infinite recursion bugs if we asked if a type contained type-parameters
which in turn somtimes aksed if it was concrete or not which in turn
again called contains_type_parameters. This cleans it all up. More
cleanup to these interfaces can be done over time.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
820: Bug fix mutability checks in can_eq for autoderef r=philberty a=philberty
Rust is permissive about mutablity in type checking for example, if we have
a function:
fn foo(a:&bar) { ... }
fn caller() {
let a:&mut bar = ...;
foo(a);
}
This is valid since the mutable reference to bar is valid to be turned into
an immutable reference without any conversion. Like in C a non-const
pointer is valid to be passed to a const pointer inferface.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
817: Remove bad mutability check pass r=philberty a=philberty
This was an initial pass to try and ensure all assignments were valid
with respect to the binding mutability. This pass cannot be done at the
name resolution level and in rustc is achieved on mir as part of the borrow
checker. This patch removes this pass and associated test cases.
This set of patches also adds support for indirection around array index
expressions.
Fixes#815
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
819: Update legacy mangling of names r=philberty a=philberty
In rust the mangling of names needs to handle cases such as qualified paths
<&mut T as Deref>::deref. Assemblers cannot handle '&' and whitespace
otherwise we will fail to assemble the functions, the legacy mangling
scheme turns all reference's '&' into 'RF' and all whitespace into '$'
this means we can mangle more complex canonical paths. Which are needed
in order to support the deref operator overloading.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
This operator overloading function was extracted from the callers within
compound assignment etc, where we needed to be able to fall back to code
within the same function. This improves the error handling to return early
when there are no such lang-items or no available method instead of trying
to continue. It flattens the conditional's previously required in the code
path.
This is a second cleanup to the generic interfaces in the type system. The
helper for contains type parameters is akin to asking if a type is concrete
or not. If a type is not concrete ie: contains type parameters then this
can be leveraged instead of adding more complexity.
The TyTy::BaseType::is_concrete is already an abstract method forcing
all types to implement it, this makes it much safer and fixes some bad
infinite recursion bugs if we asked if a type contained type-parameters
which in turn somtimes aksed if it was concrete or not which in turn
again called contains_type_parameters. This cleans it all up. More
cleanup to these interfaces can be done over time.
We need to update the type context type with the newly monomorphized types
we guarded against ADT's and functions because they were never added before
though this does not work for generic reference's to ADT's this updates
the check accordingly.
Rust is permissive about mutablity in type checking for example, if we have
a function:
fn foo(a:&bar) { ... }
fn caller() {
let a:&mut bar = ...;
foo(a);
}
This is valid since the mutable reference to bar is valid to be turned into
an immutable reference without any conversion. Like in C a non-const
pointer is valid to be passed to a const pointer inferface.
In rust the mangling of names needs to handle cases such as qualified paths
<&mut T as Deref>::deref. Assemblers cannot handle '&' and whitespace
otherwise we will fail to assemble the functions, the legacy mangling
scheme turns all reference's '&' into 'RF' and all whitespace into '$'
this means we can mangle more complex canonical paths. Which are needed
in order to support the deref operator overloading.
When we have an array-index expr rust allows the array reference to be a
reference and the compiler is meant to add in the required implicit
indirection. This checks for this senario and injects the indirection
during code-generation.
Fixes#815
This was an initial pass to try and ensure all assignments were valid
with respect to the binding mutability. This pass cannot be done at the
name resolution level and in rustc is achieved on mir as part of the borrow
checker. This patch removes this pass and associated test cases.
We will be able to do this type of validation on the GCC tree's such as
the C/C++ family const checks we may be able to reuse.
Fixes#815
Some HIR::TypeNoBounds have a gcc_unreachable() unpon usage of their
respective copy constructors this change moves the instances of
FunctionParams to avoid the copy.
814: Set TREE_ADDRESSABLE when we need to borrow any expression r=philberty a=philberty
GCC requires VAR_DECL's and PARAM_DECL's to be marked with TREE_ADDRESSABLE
when the declaration will be used in borrow's ('&' getting the address).
This takes into account the implicit addresses when we do autoderef in
method resolution/operator-overloading.
If it is not set we end up in cases like this:
```c
i32 main ()
{
i32 a.1;
i32 D.86;
i32 a;
a = 1;
a.1 = a; // this is wrong
<i32 as AddAssign>::add_assign (&a.1, 2);
D.86 = 0;
return D.86;
}
```
You can see GCC will automatically make a copy of the VAR_DECL resulting bad code-generation.
Fixes#804
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
GCC requires VAR_DECL's and PARAM_DECL's to be marked with TREE_ADDRESSABLE
when the declaration will be used in borrow's ('&' getting the address).
This takes into account the implicit addresses when we do autoderef in
method resolution/operator-overloading.
This patch keeps a seperate side table for the VAR_DECL/PARAM_DECL hir-id's
for lookup. The typechecker marks these id's using
AddressTakenResolver::SetAddressTaken (HIR::Expr&);
Its quite simple as it only cares about paths such as:
- PathInExpression
- QualifiedPathInExpression
- IdentifierExpression
The rest of the expression types will be folded into temporary values
anyway so they don't need to be marked as needs_address.
Fixes#804
813: Support QualifiedPathInType's within the same Trait r=philberty a=philberty
The first implementation of qualified paths assumed that they only exist
within trait-impl blocks. Trait impl blocks have the same canonical paths
of <type as trait_path>::segment form but this type of path is more generic
than this.
see the commit for more details on the implementation.
Fixes#739
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
The first implementation of qualified paths assumed that they only exist
within trait-impl blocks. Trait impl blocks have the same canonical paths
of <type as trait_path>::segment form but this type of path is more generic
than this.
This patch changes the name resolver to allow for failures in looking up
the qualified path within the type namespace since it will not exist in
this case and updates the type checking code to be more permissive when
used outside of trait impl blocks to simply allow us to resolve this type
to the associated trait item as we expect. Usually the code here tries
to setup any associated types based on the associated impl block but this
is a difference case.
Fixes#739
812: Remove implicit paths hack r=philberty a=philberty
The name resolver also created a bunch of duplicates Self::associated_type
paths in the name resolver so associated types paths of this kind could be resolved
at name resolve time.
Addresses #739
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
This removes the implicit Self::associate_type paths from the name resolver
these are unnessecary with the updates in the type system to resolve these.
800: Added Remark markdown automation r=philberty a=mvvsmk
Fixes#487
Remark.yml contains the workflow, and .remarkrc is the linter's config file. The configurations follow the same ones as shown in the reference repo specified by `@philberty` in the issue.
The linter works great, and the Test is shown as unsuccessful if a check fails. I also created a PR ( [here](https://github.com/mvvsmk/gccrs/pull/1) )in my fork to test this. You can check the results out [here.](https://github.com/mvvsmk/gccrs/runs/4126281781?check_suite_focus=true) The test file's name is TEST.md .
Please note that the run mentioned above also shows errors in CONTRIBUTING.md and README.md, which were not part of the commit, but the linter goes over them regardless, as they are part of the Repository.
### The issues that still remain are :
- There are two files CONTRIBUTING.md and README.md which have a few errors, I could configure the linter to skip them, but it would be much easier to correct them.
- The trigger branch for the workflow was not specified. Hence I use master.
- Custom configurations/changes you would like me to add.
This is my first PR, so please let me know if I've missed anything! Thanks.
See: #487
Signed-off-by: M V V S Manoj Kumar <mvvsmanojkumar@gmail.com>
Co-authored-by: @mvvsmk <mvvsmanojkumar@gmail.com>
Co-authored-by: M V V S Manoj Kumar <mvvsmanojkumar@gmail.com>
811: Remove implicit name hack for trait associated types r=philberty a=philberty
There is still another hack I am working through to remove before fixing the issue.
Addresses: #739
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
Before the TypePath resolution was updated to support associated type paths
and projections, we used an implict name hack of Self::<associated-type> as
well as the usual TraitName::<associates-type> this was a hack in the short
term to get things working which can now be removed.
Addresses: #739
810: Fix MethodCalls for covariant impl blocks r=philberty a=philberty
I think we need to research more into how we probe for potential candidates
for method calls. This fixes a few bugs going on in #808 one where the
canonical path was empty and one where we fail to probe directly on the
receiver of reference types to impl blocks but we must be able to also support
that autoderef means that a receiver's root type might actually be the type we
care about for example a reference to a generic type-parameter and we probe
its bounds for candidates for example. Lets consult the rustc code and references on this.
Fixes#808
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
805: Remove Btype, Bexpression, etc. abstractions over gcc trees r=CohenArthur a=dafaust
As discussed in #412, the Rust front end inherits an abstraction over gcc from the initial bootstrap via GCCGO.
This is a cool idea, but adds overhead for the primary goal of gcc compiling Rust. It's not clear that the benefits of maintaining the abstraction are worth the potential extra headaches of maintaining it.
I figured for the sake of discussion, I'd draft an initial step towards removing this abstraction.
The implementations of classes `Bytpe`, `Bexpression`, `Bstatement`, `Bfunction`, and `Bblock` are only wrappers around gcc's GENERIC `tree` structure, with no added functionality. This PR removes them, and changes all the functions for creating and manipulating these abstract types to just use/return `tree` instead. I also deleted a few functions that are vestiges from GCCGO port and aren't used.
Personally, I think the abstraction should be removed in favor of using `tree`s. This is more in line with the other gcc front ends and makes the interface between the frontend and the rest of gcc simpler.
I'm curious to hear other opinions on the matter :)
Addresses: #412
Co-authored-by: David Faust <david.faust@oracle.com>
Impl blocks Self type is a TypeNoBouns which means it can be for types
such as: impl<T> &T {}.
I think we might need to change the probe algorithm for method calls to be
fully based on the autoderef rather than trying to filter based on the Self
type. More investigation is needed for the probe phase here.
Fixes#808
When we must infer the substitutions on method calls we must make sure to
unify the self arguments from the receiver, taking into account the
autoderef mechanism. This enforces the type checks and fixes up any
inference variables along the way.
Addresses #808
This fixes the ice for TypeNoBounds canonical paths for reference types
which was not implemented resulting in empty paths for the canonical
path of impl_blocks for example.
A Fixme has been added to point out that we should update this interface
to only take AST::TypeNoBounds.
Fixes#808
These functions are holdovers from the original port from the Go
frontend for Rust. They aren't used anywhere, so delete them from
rust-backend.h and rust-gcc.cc.
(set_)placeholder_xxx_type ()
(is_)circular_pointer_type ()
801: operator overloading r=philberty a=philberty
This change adds operator overloading by following how the C++ front-end
does it. We are relying on GCC to inline the operator overloads which does
occur once optimizations are enabled. It also brings back the desurgared
compound assignment expression (e2b761b13e)
for lang_items such as add_assign. You can find more information on how the algorithm works in:
- c47d5cbdee
- a7fb60bb62
These were refactored in: 0f74fe23c6Fixes#249
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
Unary operator expressions can be treated as simply having a nullptr
rvalue. This patch updates the shared operator overloading code to allow
for a nullptr rhs to canonicalize the code path for all operator overloads.
Fixes#249
This change incorporates a few changes.
1. Create new gcc/rust/backend/rust-compile-expr.cc to split out
implementation code
2. Create new type check context api calls:
- TypeCheckContext::lookup_operator_overload
- TypeCheckContext::insert_operator_overload
3. Update type checking for ArithmeticOrLogicalExpr to look for any
operator overloading
When we are looking for operator overloads we must look up the associated
lang item type for this paticular operation, to resolve the operation to
any known lang_items by looking up the specified lang_item to DefId. Then
we must probe for the lang_item candidate for this paticular lang_item
DefID to see if we can resolve it to a method call. Then based on the
autoderef rules in a MethodCallExpr we must verify that we don't end up
in a recursive operator overload by checking that the current context
is not the same as the actual operator overload for this type. Finally
we mark this expression as operator overload and setup everything as a
resolved MethodCallExpr.
Fixes#249
Sometimes when we probe for associated items we need to limit it to
items which are directly associated with a trait. This adds an optional
parameter to achieve this.
Lang items are attributes that mark traits for specific behaviour with
compiler support kind of like builtin's/intrinsics.
This change adds parsing support for some of the arithmetic operator
overloads. The string names always correspond to the trait-item function
name too.
803: Partially disable clang-format in rust-diagnostics.h r=dkm a=dkm
clang-format is confused by attribute macros and does a very bad job at
indenting the code.
Changes merged in #779 make all clang-format checks to fail.
Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
Co-authored-by: Marc Poulhiès <dkm@kataplop.net>
802: More help on running clang-format locally r=philberty a=dkm
Add note on using git-clang-format and clang-format-diff.py.
Remove the `clang-format` from the required items of PR as it's not enforced
anymore. It's now handled by regular code review.
Refs #242
Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
Co-authored-by: Marc Poulhiès <dkm@kataplop.net>
clang-format is confused by attribute macros and does a very bad job at
indenting the code.
Changes merged in #779 make all clang-format checks to fail.
Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
Add note on using git-clang-format and clang-format-diff.py.
Remove the `clang-format` from the required items of PR as it's not enforced
anymore. It's now handled by regular code review.
Refs #242
Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
DefId was uint64_t previously but it has been changed to be a struct.
In order to reduce code breakage, ==, !=, and < operators have been implemented
for DefId. Since DefId is now a proper struct, bit manipulation code has been
removed with member accesses.
Fixes#439
Signed-off-by: Nirmal Patel <npate012@gmail.com>
795: Running `clang-format` locally [#242] r=philberty a=tschwinge
Apparently everyone but me knows how to do that; I'm now documenting it for my
own future use.
Co-authored-by: Thomas Schwinge <thomas@codesourcery.com>
Addresses #487
Remark.yml contains the workflow and .remarkrc is the linter's config file.
Signed-off-by: M V V S Manoj Kumar <mvvsmanojkumar@gmail.com>
796: Handle forward declared items within blocks r=philberty a=philberty
This changes the resolution in BlockExpr's to iterate the Items then Stmts
but we might want to handle this by desugaring the HIR BlockExpr to have
items then stmts to ensure we type resolve the items before the stmts.
Fixes#531
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
These three were added in commit cbfc0ee239
"This allows for query based compilation", part of
<https://github.com/Rust-GCC/gccrs/pull/640> "Optional Trait items constants".
Given:
if ([...]
&& [X])
{
rust_error_at ([...]);
rust_assert (![X]);
}
..., this means that the 'rust_assert' always fires, so this is a condition
that is not meant to happen (also, there are no test cases triggering this),
so use 'rust_internal_error_at' instead.
This changes the BlockExpr resolution to iterate Items first, then the
Stmts. This could be handled in HIR by desugaring the BlockExpr by lowering
the block into { <items>; <stmts>; } would also work. But the HIR lowering
of blocks is a little messy right now and we need to clean up the
unreachable lint.
Fixes#531
794: Fix unhandled type bounds in TypeAlias r=philberty a=philberty
This adds support for trait-object-types and desugars HIR::TraitObjectTypeOneBound into a single
HIR::TraitObjectType. This also adds the missing cases of the generic arguments to the TypeBoundPredicates.
It also contains cleanup for helpers used during monomorphization and a recursion limiter which is likely set too
low but it is good enough for the test-cases we have now to get good back-traces.
Fixes#786
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
This changes the coercion code for the dyn vtable to compute addresses
for more complex generic methods such as:
```
impl<'a, T> FnLike<&'a T, &'a T> for Identity {
fn call(&self, arg: &'a T) -> &'a T {
arg
}
}
```
In the above example the fntype for the bound FnLike is generic and
bound to the ParamType 'T' from the generic impl-block. But the bound
which has a signiture which is compatible for the impl block looks like:
```
trait FnLike<A, R> {
fn call(&self, arg: A) -> R;
}
```
This means when we have the trait-object bound:
```
type FnObject<'b> = dyn for<'a> FnLike<&'a isize, &'a isize> + 'b
```
We must be able to figure out that the signiture of the impl block item
```
fn call(&self, arg: &'a T) -> &'a T;
```
T must be substituted with &isize from the arguments used in the bound.
Fixes#786
785: rust: track inline module scopes for module file resolution r=CohenArthur a=mathstuf
The set of inline modules is required to find the expected location of a
module file. Track this information with an RAII object
(`InlineModuleStackScope`) and pass it down to any out-of-line modules
so that, when requested, the set of inline modules can be added to the
search path.
Signed-off-by: Ben Boeckel <mathstuf@gmail.com>
---
Note that this does not include a test case because I have no idea how to mark up this for all the warnings that come out (#676):
```diff
diff --git a/gcc/testsuite/rust/compile/missing_middle/sub/mod.rs b/gcc/testsuite/rust/compile/missing_middle/sub/mod.rs
new file mode 100644
index 00000000000..f099d61e04a
--- /dev/null
+++ b/gcc/testsuite/rust/compile/missing_middle/sub/mod.rs
`@@` -0,0 +1,3 `@@`
+pub fn f() -> u32 {
+ 1
+}
diff --git a/gcc/testsuite/rust/compile/mod_missing_middle.rs b/gcc/testsuite/rust/compile/mod_missing_middle.rs
new file mode 100644
index 00000000000..d9cdf0a54f1
--- /dev/null
+++ b/gcc/testsuite/rust/compile/mod_missing_middle.rs
`@@` -0,0 +1,11 `@@`
+pub mod missing_middle {
+ pub mod sub;
+}
```
Observed warnings:
```
/home/boeckb/code/depot/group-compilers/gcc/src-gccrs/gcc/testsuite/rust/compile/missing_middle/sub/mod.rs:1:5: warning: unused name 'f'
/home/boeckb/code/depot/group-compilers/gcc/src-gccrs/gcc/testsuite/rust/compile/mod_missing_middle.rs:2:9: warning: unused name 'sub'
/home/boeckb/code/depot/group-compilers/gcc/src-gccrs/gcc/testsuite/rust/compile/missing_middle/sub/mod.rs:1:5: warning: unused name 'sub::f'
/home/boeckb/code/depot/group-compilers/gcc/src-gccrs/gcc/testsuite/rust/compile/mod_missing_middle.rs:2:9: warning: unused name 'missing_middle::sub'
/home/boeckb/code/depot/group-compilers/gcc/src-gccrs/gcc/testsuite/rust/compile/mod_missing_middle.rs:1:5: warning: unused name 'missing_middle'
/home/boeckb/code/depot/group-compilers/gcc/src-gccrs/gcc/testsuite/rust/compile/missing_middle/sub/mod.rs:1:5: warning: unused name 'missing_middle::sub::f'
```
Fixes: #645
Here is a checklist to help you with your PR.
- \[x] GCC development requires copyright assignment or the Developer's Certificate of Origin sign-off, see https://gcc.gnu.org/contribute.html or https://gcc.gnu.org/dco.html
- \[x] Read contributing guidlines
- \[x] `make check-rust` passes locally
- \[x] Run `clang-format` (leaving to CI)
- \[x] Added any relevant test cases to `gcc/testsuite/rust/` (see above)
Co-authored-by: Ben Boeckel <mathstuf@gmail.com>
791: Replace TyTy::TupleType::iterate_fields with a new function get_fields r=philberty a=cls
This PR replaces TyTy::TupleType::iterate_fields with a new function get_fields.
In #735, `@philberty` mentions two possible implementations of get_fields, one that returns `std::vector<TyVar>&` and one that returns a new `std::vector<BaseType *>`. I've included two commits, the first doing the former and second going on to do the latter. I'm happy with one or both being merged.
This is my first PR, so please let me know if I've missed anything! Thanks.
Fixes#735
Co-authored-by: Connor Lane Smith <cls@lubutu.com>
We have two ways to represent TraitObjectType's:
- AST::TraitObjectType
- AST::TraitObjectTypeOneBound
This desugars this within HIR into a single HIR::TraitObjectType which
contains a list of bounds.
Addresses #786
The set of inline modules is required to find the expected location of a
module file. Track this information with an RAII object
(`InlineModuleStackScope`) and pass it down to any out-of-line modules
so that, when requested, the set of inline modules can be added to the
search path.
Signed-off-by: Ben Boeckel <mathstuf@gmail.com>
781: Add missing typechecking for enums r=philberty a=philberty
This PR splits up the Algebraic data type into one which can support many variants which is what an enum is.
It then changes the type checking for construction of ADT's to use the VariantDef structures as required. This
does not fully implement but does allow us to have most of the type checking in place to start code-generation work.
This combines work from Mark Wielaard (https://code.wildebeest.org/git/user/mjw/gccrs/commit/?h=enum-type) and Philip
Addresses #79
Co-authored-by: Mark Wielaard <mark@klomp.org>
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
788: gccrs: add the `-frust-crate=` option to set the crate name r=philberty a=mathstuf
Signed-off-by: Ben Boeckel <mathstuf@gmail.com>
Fixes: #627
Co-authored-by: Ben Boeckel <mathstuf@gmail.com>
It is ok for type checking to error/fail on a construct within the crate,
we can try our best to continue on to find as many errors as possible. To
achieve this without running into nullptr's we can use the ErrorType node
to signify an error. This also cleans up alot of noise in our error
handling.
Enums are ADT's with multiple variants where as structs are ADT's with a
single variant, this changes the typechecking on construction of these to
support enums.
Addresses #79
When constructing enums we end up with a path like Enum::discriminant so
we must lookup the variant to figure out how to construct the enum.
Addresses #79
This patch does the type resolution to actually create the types when we
encounter enums within toplevel HIR::Items and HIR::Stmt conext's.
We don't support actual creation of enums yet in this patch but this is
an isolated building block.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
Addresses #79
Algebraic data types represent Structs, Tuple Structs, unit
structs and enums in rust. The key difference here is that
each of these are an ADT with a single variant and enums
are an ADT with multiple variants.
It adds indirection to where the fields of an ADT are
managed.
Co-authored-by: Mark Wielaard <mark@klomp.org>
Addresses #79
783: Get rid of lambda within `AST::TypePath` and provide a method to return a reference r=philberty a=diohabara
## Related issue
This PR will fix <https://github.com/Rust-GCC/gccrs/issues/718>
- \[x] GCC development requires copyright assignment or the Developer's Certificate of Origin sign-off, see https://gcc.gnu.org/contribute.html or https://gcc.gnu.org/dco.html
- \[x] Read contributing guidlines
- \[x] `make check-rust` passes locally
- \[x] Run `clang-format`
- \[x] Added any relevant test cases to `gcc/testsuite/rust/`
Note that you can skip the above if you are just opening a WIP PR in
order to get feedback.
Co-authored-by: Kadoi Takemaru <diohabara@gmail.com>
Remove lambda expressions within AST::TypePath and use get_segments() to
iterate over AST::TypePathSegment
Fixes#718
Signed-off-by: Kadoi Takemaru <diohabara@gmail.com>
780: No side effects in 'assert' expressions r=philberty a=tschwinge
Usually, if 'assert'ions are disabled, 'assert' expressions are not evaluated,
so in that case won't effect any side effects.
Via spurious ICEs/test suite FAILs, this may be observed in GCC/Rust, for
example, if configuring with '--enable-checking=no' and disabling a "more
forgiving" 'gcc/system.h:gcc_assert' definition, so that '0 && (EXPR)' gets
used:
/* Use gcc_assert(EXPR) to test invariants. */
#if ENABLE_ASSERT_CHECKING
#define gcc_assert(EXPR) \
((void)(!(EXPR) ? fancy_abort (__FILE__, __LINE__, __FUNCTION__), 0 : 0))
-#elif (GCC_VERSION >= 4005)
+#elif (0) //GCC_VERSION >= 4005)
#define gcc_assert(EXPR) \
((void)(__builtin_expect (!(EXPR), 0) ? __builtin_unreachable (), 0 : 0))
#else
/* Include EXPR, so that unused variable warnings do not occur. */
#define gcc_assert(EXPR) ((void)(0 && (EXPR)))
#endif
As that one does cause some issues in GCC proper (that I shall fix separately),
may use this change to 'gcc/rust/rust-system.h:rust_assert' instead:
+#if 0
#define rust_assert(EXPR) gcc_assert (EXPR)
+#else
+#define rust_assert(EXPR) ((void) (0 && (EXPR)))
+#endif
To fix these, use the same pattern as is already used in a lot of existing
GCC/Rust code:
bool ok = [expression with side effects];
rust_assert (ok);
I've only done a quick manual review; maybe there is a tool for doing this?
Co-authored-by: Thomas Schwinge <thomas@codesourcery.com>
778: Add location info in AST::TypeBoundWhereClauseItem and HIR::TypeBoundWhereClauseItem r=philberty a=npate012
Location info has been added to AST::TypeBoundWhereClauseItem and HIR::TypeBoundWhereClauseItem. parse_type_bound_where_clause_item () has been modified to fetch location info and store it in AST::TypeBoundWhereClauseItem.
Fixes#766
Signed-off-by: Nirmal Patel <npate012@gmail.com>
Co-authored-by: Nirmal Patel <npate012@gmail.com>
Usually, if 'assert'ions are disabled, 'assert' expressions are not evaluated,
so in that case won't effect any side effects.
Via spurious ICEs/test suite FAILs, this may be observed in GCC/Rust, for
example, if configuring with '--enable-checking=no' and disabling a "more
forgiving" 'gcc/system.h:gcc_assert' definition, so that '0 && (EXPR)' gets
used:
/* Use gcc_assert(EXPR) to test invariants. */
#if ENABLE_ASSERT_CHECKING
#define gcc_assert(EXPR) \
((void)(!(EXPR) ? fancy_abort (__FILE__, __LINE__, __FUNCTION__), 0 : 0))
-#elif (GCC_VERSION >= 4005)
+#elif (0) //GCC_VERSION >= 4005)
#define gcc_assert(EXPR) \
((void)(__builtin_expect (!(EXPR), 0) ? __builtin_unreachable (), 0 : 0))
#else
/* Include EXPR, so that unused variable warnings do not occur. */
#define gcc_assert(EXPR) ((void)(0 && (EXPR)))
#endif
As that one does cause some issues in GCC proper (that I shall fix separately),
may use this change to 'gcc/rust/rust-system.h:rust_assert' instead:
+#if 0
#define rust_assert(EXPR) gcc_assert (EXPR)
+#else
+#define rust_assert(EXPR) ((void) (0 && (EXPR)))
+#endif
To fix these, use the same pattern as is already used in a lot of existing
GCC/Rust code:
bool ok = [expression with side effects];
rust_assert (ok);
I've only done a quick manual review; maybe there is a tool for doing this?
Location info has been added to AST::TypeBoundWhereClauseItem and
HIR::TypeBoundWhereClauseItem. parse_type_bound_where_clause_item () has been
modified to fetch location info and store it in AST::TypeBoundWhereClauseItem
Fixes#766
Signed-off-by: Nirmal Patel <npate012@gmail.com>
These lambda iterators are removed because they make working
with IR more complex. Instead, we are using the get_params ()
to access the parameters with the help of a for loop.
Fixes#722#723
Signed-off-by: Nirmal Patel <npate012@gmail.com>
775: Support const within block-expr's r=philberty a=philberty
This adds support for constant folding within block expr's and constant
ArrayIndexExpression.
Fixes#711
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
BlockExpr's can contain constants these are Items which can exist within
the BlockExpr Stmt list. Items like structs, functions and constants all
inherit from Item so there is some duplication of code but we still
do not support the forward declared Items within a stmt list so the
duplication will need to be fixed as part of that bug.
Fixes#711
771: Add higher ranked trait bounds r=philberty a=philberty
This adds support for where clauses and higher ranked trait bounds more test cases are needed
since where clauses are supported on associated types, impls, ADT's etc. See the individual
commits for more detail on implementation.
Fixes#773#442
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
The loop was eagerly trying to ensure that there was multiple lifetimes
since the predicate assumed there will be a comma or delimiter for the
arguments. This changes the loop to keep reading lifetimes untill we fail to parse a lifetime or hit the end of the arguments.
Fixes#773
This adds the type checking for the bounds which will add the relevant
bounds to the associated types and perform the relevant type checking
required.
Fixes#442
This assertion doesn't protect against bad pointers or behaviour, when we
access the where clause it is simply a wrapper over a vector of where
clause items so we can safely iterate even when the where clause item
vector is empty.
770: TraitImpl: track the polarity of the impl r=philberty a=mathstuf
The internal representation now tracks whether a trait impl is a
positive or negative impl.
Signed-off-by: Ben Boeckel <mathstuf@gmail.com>
Fixes: #732
Co-authored-by: Ben Boeckel <mathstuf@gmail.com>
772: Converted FnType preprocessor defines into constants r=philberty a=npate012
Fixes#737
I have converted FnType preprocessor defines to static const of uint8_t. I did not change the variable case.
Co-authored-by: Nirmal Patel <npate012@gmail.com>
769: LifetimeWhereClauseItem: store the location of the item r=philberty a=mathstuf
Signed-off-by: Ben Boeckel <mathstuf@gmail.com>
---
Fixes: #765
Here is a checklist to help you with your PR.
- \[x] GCC development requires copyright assignment or the Developer's Certificate of Origin sign-off, see https://gcc.gnu.org/contribute.html or https://gcc.gnu.org/dco.html
- \[x] Read contributing guidlines
- \[x] `make check-rust` passes locally
- \[x] Run `clang-format` (letting CI handle this)
- \[x] Added any relevant test cases to `gcc/testsuite/rust/`
I didn't find any ctor calls for the `HIR` type, but it's updated as well.
Co-authored-by: Ben Boeckel <mathstuf@gmail.com>
768: CompileExpr: fix copy pasta error message r=philberty a=mathstuf
Also downgrade from a fatal error to a compilation error.
Signed-off-by: Ben Boeckel <mathstuf@gmail.com>
---
Fixes: #702
Here is a checklist to help you with your PR.
- \[x] GCC development requires copyright assignment or the Developer's Certificate of Origin sign-off, see https://gcc.gnu.org/contribute.html or https://gcc.gnu.org/dco.html
- \[x] Read contributing guidlines
- \[x] `make check-rust` passes locally
- \[x] Run `clang-format` (letting CI handle this)
- \[ ] Added any relevant test cases to `gcc/testsuite/rust/` (I don't see any existing tests that seem to test things like this; it's a gccrs internal error about lookup up the type it seems?)
Co-authored-by: Ben Boeckel <mathstuf@gmail.com>
767: gccrs: StructExprStructFields: remove `iterate` method r=philberty a=mathstuf
This provides a getter for the set of fields in a struct expression
rather than a visitor with a callback which is more complicated for
callers, especially static analysis.
Signed-off-by: Ben Boeckel <mathstuf@gmail.com>
Fixes: #721
Co-authored-by: Ben Boeckel <mathstuf@gmail.com>
This provides a getter for the set of fields in a struct expression
rather than a visitor with a callback which is more complicated for
callers, especially static analysis.
Signed-off-by: Ben Boeckel <mathstuf@gmail.com>
762: Add missing coercion site code to MethodCallExpr's r=philberty a=philberty
Arguments to methods are coercion sites and may have implicit conversions
to be performed this adds this missing code for this case.
Fixes#755
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
763: Cleanup IR symbol names in gimple r=philberty a=philberty
When we have generic code the full as_string is too verbose for symbol
names. This changes the ir_symbol_names to become the name of the types
not the full debug as_string version.
Fixes#745
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
This evidently has originally been copied from 'gcc/go/gofrontend/go-linemap.h'
(with a bit too much 's%go%rust'). Restore the original notes, and extend
suitably.
When we have generic code the full as_string is too verbose for symbol
names. This changes the ir_symbol_names to become the name of the types
not the full debug as_string version.
Fixes#745
752: Bugfix ICE in trait resolution r=philberty a=philberty
This is a series of patches which need to go in order to fix the linked bugs.
- Fix type resolution of associated types in the generic context
- Ensure autoderef is applied on generic receivers
- Support generic substitutions on type-bounds
Fixes#743#753#744#741
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
This adds support to managing generic arguments within type bounds. Such
as:
```rust
fn test<T: GenericBound<i32>>(a:T) { ... }
```
The interesting piece here is that for any usage of the bounds on T the
items must be substituted with the inherited arguments specified within
the bound.
This fixes the test case from #743 by removing the lifetimes and where
constraint which needs to be implemented in #442. This associated test
case will fail the rust borrow checker but we need a way to work though
bugs in the short term in some senario's.
Fixes#743
This changes our TyTy::BaseType::can_eq interface to allow
ParamTypes to be compatable with everything except reference
and pointer types to ensure we apply autoderef adjustments
correctly.
Fixes#753
When we have a generic function with specified type bounds this allows rust
code to actually then look up the relevant bounds for associated types,
functions or constants. This means at code generation the relevant
associated mappings msut be setup such that we compile to the
implementaiton if available or the default implementation if possible.
The bug here was that the resolution for associated types were auto setting
up the associated type mappings even when the receiver was generic. So for
example:
```rust
pub trait Foo {
type A;
fn bar(self) -> Self::A;
}
struct S(i32);
impl Foo for S {
type A = i32;
fn bar(self) -> Self::A {
self.0
}
}
fn test_bar<T: Foo>(x: T) -> T::A {
x.bar()
}
```
The generic function of test_bar was auto resolving the T::A to A=i32 since
it found the type-bound Foo was specified and the only implementation of
Foo is on S. This is usually the correct flow to auto setup these mappings
but in the conjtext of a generic receiver this needs to still result in
a Placeholder type of the bound Foo to type check correctly.
Fixes: #744#741
761: Squash unused parameter warning. r=philberty a=philberty
This should fix out bootstrap build again.
Fixes#750
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
757: Fix TypePath resolution to iterate segments r=philberty a=philberty
Associated types in rust can be of the form:
```rust
trait Foo {
type A;
...
}
fn test<T:Foo>(a:T) -> T::A { .. }
```
Where the type-bound of Foo is applied to T this allows for a the associated type T::A to exist
which is a placeholder type within the trait definition. This path cannot be resolved at name-resolution
time and requires a path probe.
Fixes#746
758: The number of required substituions is offset from inherited ones r=philberty a=philberty
When doing HIR::GenericArgs substitutions we must offset from the already
partially substituted arguments.
759: Remove second lookup for query compiled functions r=philberty a=philberty
This cleans up the code here to make use of the query based
compilation which returns the address of the function which
removes extra lookups.
760: Cleanup lookup interfaces r=philberty a=philberty
These patches change the associated impl mapping's to use a boolean
return type for error handling, to stop looking for UNKNOWN_HIRID for
error handling which is too easy to make mistakes with.
It also updates instances of code to use TyTy::ErrorType node instead of
nullptr's for error handling.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
756: Add const to enforce ownership over pointers r=philberty a=philberty
This consify's a bunch of interfaces in the code base which helps make the ownership
over pointers more clear. These are building blocks from a wider cleanup of the type-checking
code to make it more readable.
- BaseType::get_root
- SubstitutionArgumentMappings::solve_mappings_from_receiver_for_self
- Autoderef adjustments
- GetUsedSubstArgs
- SubstitutionArg field SubstitutionParamMapping
- Backend resolve compile interface
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
When compiling method calls we need to compile functions in a query based
manar sometimes, recently there was a query mode api added to the relevant
functions which will return the address of the function when asked to try
and compile. This patch uses this returned address avoiding a duplicate
lookup for the compiled function
TypePath's can be fully resolved at name resolution time for example a
primitive types are single segments which can be resolved. But in the event
of a generic TypeBound path such as: T::A where T is the generic type param
in a function and A is its own associated type this require's the
resolution to be split over the name resolver and type resolver.
Like PathInExpression's the name resolver is able to resolve the root
segment of 'T' but requires a path probe on the type-bounds of T to find
the associated type 'A'.
Fixes#746
The TypePath resolver is a naieve and assumes all paths are fully
resolveable at name resolution time. This is the first patch to update
this to resolve each segement in turn.
Addresses #746
Argument mappings need to reference the generic parameter they are going
to substitute this should really be const since this class does not own
the mapping pointer here.
This is a bad name for this class, but it will compile a TyTy type into a
GCC Backend::Btype* node. The class also tries to determine if we have
already compiled this node for monomorphization and canonicalization of
types which will avoid unnessecary conversion code based on type equality.
This patch simply makes this a const visitor to enforce pointer ownership
rules.
754: Add new unafety enum r=philberty a=npate012
Fixes#733
unsafety enum has been implemented in rust/util/rust-common.h. Occurrences of has_unsafe boolean variable has been replaced with an unsafety variable of new enum type.
Co-authored-by: Nirmal Patel <npate012@gmail.com>
747: Base v0 mangling grammar r=philberty a=CohenArthur
This PR adds base functions to deal with the v0 mangling grammar, [found here](https://rust-lang.github.io/rfcs/2603-rust-symbol-name-mangling-v0.html#syntax-of-mangled-names).
I have a few questions regarding this implementation:
1/ Is there any existing implementation for the base62 algorithm used here? This is directly adapted from [rustc's base_n module](6f53ddfa74/compiler/rustc_data_structures/src/base_n.rs (L16)) which I'm assuming is relatively standard and might already exist in the compiler. I haven't been able to find it however.
2/ gccrs cannot yet deal with unicode identifiers, as pointed out by `@bjorn3` in #418. This means that a big chunk of the `v0_add_identifier` implementation is missing. Should it be added in this PR too?
3/ As mentionned in zulip, it would be great to be able to create unit tests for this piece of code. It would be quite easy to generate a bunch of base62 strings and ensure that the algorithm here matches with them.
Co-authored-by: CohenArthur <arthur.cohen@epita.fr>
748: Const fold ArrayElemsCopied r=philberty a=rodrigovalle
Added support for const fold inside of an ArrayElemsCopied expression, e.g. `const array: [i32; 10] = [0; 10];`. I also removed a .swp file that I accidentally merged in a previous commit and added a test for this new functionality.
Co-authored-by: Rodrigo Valle <rdan.valle@gmail.com>
Added support for const fold inside of an ArrayElemsCopied expression, e.g.
`const array: [i32; 10] = [0; 10];`. I also removed a .swp file that I
accidentally merged in a previous commit and added a test for this new
functionality.
Signed-off-by: Rodrigo Valle <rdan.valle@gmail.com>
725: Add array constant folding r=philberty a=rodrigovalle
Fixes#681
I created a new ConstFoldArrayElems folder to visit ArrayElemsCopied and ArrayElemsValues while holding onto the original ArrayExpr object that we recurse into.
Co-authored-by: Rodrigo Valle <rdan.valle@gmail.com>
Create a new ConstFoldArrayElems folder to visit ArrayElemsValues while holding
onto the original ArrayExpr object that we recurse into.
Fixes#681
Signed-off-by: Rodrigo Valle <rdan.valle@gmail.com>
740: Add boiler plate for TyTy::ClosureType r=philberty a=philberty
This simply adds in the boilerplate for closure types for type-checking.
The closure branch is blocked until we get lang-item support in next.
Addresses #195
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
This adds all the nesecary boiler plate to introduce the ClosureType. More
work is needed to be make this actually useable for type resolution.
Addresses #195
730: GCC allows for the DCO sign-off r=philberty a=philberty
This updates the contributor guide to let people know the update applies to
gccrs.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
Co-authored-by: Thomas Schwinge <thomas@schwinge.name>
738: Refactor HIR to use new Mutability enum r=philberty a=dafaust
Introduce a new header rust/util/rust-common.h and move the enum
previously Rust::TyTy::TypeMutability there as Rust::Mutability.
Update the following objects to use Mutability enum rather than a bool:
- HIR::IdentifierPattern
- HIR::ReferencePattern
- HIR::StructPatternFieldIdent
- HIR::BorrowExpr
- HIR::RawPointerType
- HIR::ReferenceType
- HIR::StaticItem
- HIR::ExternalStaticItem
Also add a HIR::SelfParam::get_mut () helper, mapping its internal
custom mutability to the common Rust::Mutability.
Fixes: #731
Co-authored-by: David Faust <david.faust@oracle.com>
Introduce a new header rust/util/rust-common.h and move the enum
previously Rust::TyTy::TypeMutability there as Rust::Mutability.
Update the following objects to use Mutability enum rather than a bool:
- HIR::IdentifierPattern
- HIR::ReferencePattern
- HIR::StructPatternFieldIdent
- HIR::BorrowExpr
- HIR::RawPointerType
- HIR::ReferenceType
- HIR::StaticItem
- HIR::ExternalStaticItem
Also add a HIR::SelfParam::get_mut () helper, mapping its internal
custom mutability to the common Rust::Mutability.
Fixes: #731
This updates the contributor guide to let people know the update applys to
gccrs.
Co-authored-by: CohenArthur <arthur.cohen@epita.fr>
Co-authored-by: Marc Poulhiès <dkm@kataplop.net>
728: Remove `AST::BlockExpr` lambda and add `get_statements` r=philberty a=wan-nyan-wan
This PR Fixes#724.
This patch removes lambda iterators in `AST::BlockExpr` and replace these with `get_statements`. These lambda iterators need to be removed they make working with the IR's more complex for static analysis.
Co-authored-by: wan-nyan-wan <distributed.system.love@gmail.com>
710: Ensure for Coercion Sites we emit the code nessecary r=philberty a=philberty
Coercion sites in Rust can require extra code generation for
CallExpressions arguments for example. This ensures we detect
those cases and emit the extra code necessary. Please read the individual
commit messages for more detail on how this works.
Fixes#700#708#709
727: Remove lambda iterators in various HIR classes r=philberty a=dafaust
(This is a revision of #726 with formatting fixes)
This patch removes the lambda iterators used in various HIR objects.
These iterators make interacting with the IR for static analysis more
difficult. Instead, get_X () helpers are added for accessing elements,
and uses of the iterators replaced with for loops.
The following objects are adjusted in this patch:
- HIR::ArrayElemsValues
- HIR::TupleExpr
- HIR::StructExprField
- HIR::StructStruct
- HIR::TupleStruct
Fixes: #703Fixes: #704Fixes: #705Fixes: #706Fixes: #707
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
Co-authored-by: David Faust <david.faust@oracle.com>
729: Refactor TyTy with new TypeMutability enum r=philberty a=dafaust
Add `TyTy::TypeMutability` enum and start using it instead of `bool is_mut`.
This is just a start, the new enum could be used in many places.
Fixes: #677
Co-authored-by: David Faust <david.faust@oracle.com>
Add a new TyTy::TypeMutability enum for describing mutability. Use it
for ReferenceType and PointerType, rather than a boolean is_mut, to make
the code more readable.
TyTy::TypeMutability can be used in several other places in the future.
Fixes: #677
This patch removes the lambda iterators used in various HIR objects.
These iterators make interacting with the IR for static analysis more
difficult. Instead, get_X () helpers are added for accessing elements,
and uses of the iterators replaced with for loops.
The following objects are adjusted in this patch:
- HIR::ArrayElemsValues
- HIR::TupleExpr
- HIR::StructExprField
- HIR::StructStruct
- HIR::TupleStruct
Fixes: #703, #704, #705, #706, #707
When we coerce the types of arguments to the parameters of functions for
example we must store the actual type of the argument at that HIR ID not
the coerced ones. This gives the backend a chance to then figure out
when to actually implement any coercion site code. such as computing the
dynamic objects.
Fixes: #700
Coercion sites like CallExpr arguments must coerce the arguments for
type checking, but we must still insert the type of the actual argument
for that mapping not the coerced type. For example we might have:
```rust
fn dynamic_dispatch(t: &dyn Bar) {
t.baz();
}
fn main() {
let a = &Foo(123);
dynamic_dispatch(a);
}
```
Here the argument 'a' has a type of (&ADT{Foo}) but this is coerceable to
(&dyn{Bar}) which is fine. The backend needs to be able to detect the
coercion from the two types in order to generate the vtable code. This
patch fixes the type checking such that we store the actual type of
(&ADT{Foo}) at that argument mapping instead of the coerced one.
Addresses: #700
This removes the bad code style lambda iterators for arguments. They are
a bad design choice for static analysis code since the user of the api
looses scope to break/return outside from the caller api. This will need
to be added to a style-guide in the future.
Fixes: #709
This removes the bad code style lambda iterators for arguments. They are
a bad design choice for static analysis code since the user of the api
looses scope to break/return outside from the caller api. This will need
to be added to a style-guide in the future.
Fixes: #708
698: Implement Byte Strings r=philberty a=philberty
Byte strings are not str's they are arrays of [u8; capacity], this
preserves their type guarantees as a byte string.
This patch merges work from Mark to implement the correct typing, the
missing piece was that each implicit type needed its own implicit id, other
wise their is a loop in looking up the covariant types.
Fixes#697
Co-authored-by: Mark Wielaard <mark@klomp.org>
701: Fix lexer to not produce bad unicode escape values r=philberty a=CohenArthur
There were a couple of issues in the lexer unicode escape code.
Unicode escape sequences must always start with an opening curly
bracket (and end with a closing one). Underscores are not allowed as
starting character. And the produced values must be unicode scalar
values, which excludes surrogate values (D800 to DFFF) or values
larger than 10FFFF.
Also try to recover more gracefully from errors by trying to skip past
any bad characters to the end of the escape sequence.
Test all of the above in a new testcase unicode_escape.rs.
Patch: https://git.sr.ht/~mjw/gccrs/commit/unicode_escape
Mail: https://gcc.gnu.org/pipermail/gcc-rust/2021-October/000231.html
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
Co-authored-by: Mark Wielaard <mark@klomp.org>
699: Remove raw string and raw byte string references from ast and hir r=philberty a=philberty
Raw strings and raw byte strings are simply different ways to
create string and byte string literals. Only the lexer cares
how those literals are constructed and which escapes are used
to construct them. The parser and hir simply see strings or
byte strings.
Co-authored-by: Mark Wielaard <mark@klomp.org>
There were a couple of issues in the lexer unicode escape code.
Unicode escape sequences must always start with an opening curly
bracket (and end with a closing one). Underscores are not allowed as
starting character. And the produced values must be unicode scalar
values, which excludes surrogate values (D800 to DFFF) or values
larger than 10FFFF.
Also try to recover more gracefully from errors by trying to skip past
any bad characters to the end of the escape sequence.
Test all of the above in a new testcase unicode_escape.rs.
Raw strings and raw byte strings are simply different ways to
create string and byte string literals. Only the lexer cares
how those literals are constructed and which escapes are used
to construct them. The parser and hir simply see strings or
byte strings.
Byte strings are not str's they are arrays of [u8; capacity], this
preserves their type guarantees as a byte string.
This patch merges work from Mark to implement the correct typing, the
missing piece was that each implicit type needed its own implicit id, other
wise their is a loop in looking up the covariant types.
Fixes#697
Co-authored-by: Mark Wielaard <mark@klomp.org>
Allow \0 escape in raw byte string and reject non-ascii byte
values. Change parse_partial_hex_escapes to not skip bad characters to
provide better error messages.
Add rawbytestring.rs testcase to check string, raw string, byte string
and raw byte string parsing.
689: x86: Instead of 'TARGET_ISA_[...]', 'TARGET_ISA2_[...]', use 'TARGET_[...]' [#247] r=philberty a=tschwinge
... in preparation for a merge from GCC upstream, where the former disappear.
Co-authored-by: Thomas Schwinge <thomas@codesourcery.com>
690: A bit of 'RichLocation' C++ tuning [#247], [#97, #374] r=philberty a=tschwinge
... in preparation for a merge from GCC upstream, where we otherwise run into
several different build errors.
Follow-up to commit ed651fcdec
"Add basic wrapper over gcc rich_location".
Co-authored-by: Thomas Schwinge <thomas@codesourcery.com>
... in preparation for a merge from GCC upstream, where we otherwise run into
several different build errors.
Follow-up to commit ed651fcdec
"Add basic wrapper over gcc rich_location".
688: Remove warnings from v0_mangle functions in rust-mangle.cc r=CohenArthur a=philberty
With this and that patch applied there are no more warnings building
the rust frontend, so a --enable-bootstrap (-Werror) build completes
successfully.
Fixes#336
Co-authored-by: Mark Wielaard <mark@klomp.org>
There were two warnings in rust-mangle.cc
rust-mangle.cc: In function ‘std::string Rust::Compile::v0_mangle_item
(const Rust::TyTy::BaseType*, const Rust::Resolver::CanonicalPath&, const string&)’:
rust-mangle.cc:198:1: warning: no return statement in function returning non-void
rust-mangle.cc: At global scope:
rust-mangle.cc:201:1: warning: ‘std::string Rust::Compile::v0_mangle_impl_item
(const Rust::TyTy::BaseType*, const Rust::TyTy::BaseType*, const string&, const string&)’
declared ‘static’ but never defined [-Wunused-function]
The first results in undefined behaviour, the second points out that the
function isn't ever called/used.
Fix the first by adding a gcc_unreachable () to turn the calling of the
function into an abort (). Fix the second by adding the call in
Mangler::mangle_impl_item. And add an implementation simply calling
gcc-unreachable (). This turns the warnings and undefined behaviour into
explicit runtime aborts when these functions are actually called.
687: Fix byte char and byte string lexing code r=philberty a=tschwinge
There were two warnings in lexer parse_byte_char and parse_byte_string
code for arches with signed chars:
```
rust-lex.cc: In member function
‘Rust::TokenPtr Rust::Lexer::parse_byte_char(Location)’:
rust-lex.cc:1564:21: warning: comparison is always false due to limited
range of data type [-Wtype-limits]
1564 | if (byte_char > 127)
| ~~~~~~~~~~^~~~~
rust-lex.cc: In member function
‘Rust::TokenPtr Rust::Lexer::parse_byte_string(Location)’:
rust-lex.cc:1639:27: warning: comparison is always false due to limited
range of data type [-Wtype-limits]
1639 | if (output_char > 127)
| ~~~~~~~~~~~~^~~~~
```
The fix would be to cast to an unsigned char before the comparison.
But that is actually wrong, and would produce the following errors
parsing a byte char or byte string:
```
bytecharstring.rs:3:14: error: ‘byte char’ ‘�’ out of range
3 | let _bc = b'\x80';
| ^
bytecharstring.rs:4:14: error: character ‘�’ in byte string out of range
4 | let _bs = b"foo\x80bar";
| ^
```
Both byte chars and byte strings may contain up to \xFF (255)
characters. It is utf-8 chars or strings that can only
Remove the faulty check and add a new testcase bytecharstring.rs
that checks byte chars and strings do accept > 127 hex char
escapes, but utf-8 chars and strings reject such hex char escapes.
---
<http://mid.mail-archive.com/20210921225430.166550-1-mark@klomp.org>
---
Addresses: #336Fixes: #343, #344
Co-authored-by: Mark Wielaard <mark@klomp.org>
There were two warnings in lexer parse_byte_char and parse_byte_string
code for arches with signed chars:
rust-lex.cc: In member function
‘Rust::TokenPtr Rust::Lexer::parse_byte_char(Location)’:
rust-lex.cc:1564:21: warning: comparison is always false due to limited
range of data type [-Wtype-limits]
1564 | if (byte_char > 127)
| ~~~~~~~~~~^~~~~
rust-lex.cc: In member function
‘Rust::TokenPtr Rust::Lexer::parse_byte_string(Location)’:
rust-lex.cc:1639:27: warning: comparison is always false due to limited
range of data type [-Wtype-limits]
1639 | if (output_char > 127)
| ~~~~~~~~~~~~^~~~~
The fix would be to cast to an unsigned char before the comparison.
But that is actually wrong, and would produce the following errors
parsing a byte char or byte string:
bytecharstring.rs:3:14: error: ‘byte char’ ‘�’ out of range
3 | let _bc = b'\x80';
| ^
bytecharstring.rs:4:14: error: character ‘�’ in byte string out of range
4 | let _bs = b"foo\x80bar";
| ^
Both byte chars and byte strings may contain up to \xFF (255)
characters. It is utf-8 chars or strings that can only
Remove the faulty check and add a new testcase bytecharstring.rs
that checks byte chars and strings do accept > 127 hex char
escapes, but utf-8 chars and strings reject such hex char escapes.
685: Add v0 type mangling prefixing for simple types r=philberty a=CohenArthur
This PR adds the generation of type prefixes for simple types, which are numeric types, booleans, chars, strings, empty tuples/unit types and placeholder types.
I'm unsure as to how to test this, even in the long run. There might be some shenanigans we can pull using an elf reader and regexes in order to compare ABI names with rustc.
The entire implementation of v0 name mangling is very large, so I thought I'd split it up in multiple PRs.
Co-authored-by: CohenArthur <arthur.cohen@epita.fr>
684: Initial Dynamic dispatch support r=philberty a=philberty
This rebases my branch for dynamic dispatch (dyn bound) support it supports
the HIR::TraitObjectOneBound for now but can be easily extended. The computation
of the addresses of the methods only supports impl items and does not support
optional trait methods yet but the change set was already 10 commits and this seems like
a good initial stab at support here.
Please see the git commits for more detail information on each change.
Fixes#197
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
This is the first pass at implementing dynamic dispatch, it creates a
vtable object and trait object to store the vtable and reciever. The
method resolution during type checking acts the same as if it was a
generic type bound method call. This detects this case during code
generation to access the dynamic object appropriately to get the fnptr
and call it with the stored reciever.
Fixes: #197
Support method resolution via probe of the type bound on the dynamic objects. This acts the same way as when we probe for methods like this:
```rust
trait Foo {
fn bar(&self);
}
fn test<T: Foo>(a:T) {
a.bar();
}
```
Addresses: #197
We should insert the error node into the type context when we have a type
error such that covariant types using TyVar can still work, and avoid the
assertion to ensure something exists within the context for that id upon
creation.
This is the initial support for allowing a coercion of something like:
```rust
let a = Foo(123);
let b:&dyn Bound = &a;
```
The coercion will need to ensure that 'a' meets the specified bounds of the
dynamic object.
Addresses #197
This changes all type checking of arguments to function calls to be
coercion sites instead of unifications. This allows for cases like mutable
pointers being coerced to immutable reference for example.
Call Expressions need to type check the argument passing but the type
system will return TyTy::Error nodes, it used to return nullptr about a
year ago. Returning error nodes are safer and more flexible for detailed
error handling and diagnostics.
Addresses: #539
This is the stub implementation for dynamic object types within the type
system. More work is needed to actually support dynamic trait objects.
The next change requires us to support type coercions in for arguments
to functions such as a fat-reference to a type being coerced into this
dynamic trait object for dynamic dispatch.
Addresses: #197
680: Building blocks for TraitObject Types r=philberty a=philberty
This adds name resolution and HIR lowering for TraitObjectTypeOneBound
This is the most basic form of dynamic dispatch but all forms derive from
this piece of work.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
This uses a little bit of a hack to get a plain old object for the
TraitBound but we need to create an issue to refactor and remove the clone
support for these types to be able to cleanup this work to use a simple
std::unique_ptr.
Addresses #197
We can resolve the TypeBound during name resolution here but this is all
encapsulated within TraitObjectTypeOneBound which needs its own TyTy
abstraction during type checking.
Addresses #197
679: Fix bug when calling method from generic reciever type-bound r=philberty a=philberty
When we have a generic function with a specified type bound, this means the
method resolution can only resolve this to the trait item. During code
generation we must then monomorphize this and lookup the associated impl
block item for this trait (if it exists) and call this function.
Fixes#678
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
When we have a generic function with a specified type bound, this means the
method resolution can only resolve this to the trait item. During code
generation we must then monomorphize this and lookup the associated impl
block item for this trait (if it exists) and call this function.
Fixes#678
674: Add test case to close out generics bug r=philberty a=philberty
It seems this issue was fixed by 58637abaea. This added a test case
to close out the issue.
Fixes#368
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
673: Allow GCC to decide to inline functions is possible r=philberty a=philberty
By default the forked GCC wrapper from the go front-end was marking
all functions as DECL_UNINLINABLE this changes the behaviour to
allow GCC to decide what can be inlined.
Fixes#547
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
672: Initial autoderef support for method calls r=philberty a=philberty
The commit message contains more detail but this reference is good:
https://doc.rust-lang.org/nightly/nomicon/dot-operator.html
This is not 100% complete since we do not yet support operator overloading
so we will require an update to support the Deref operator overload for
more complex types.
Fixes: #241
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
The GCC wrapper here was forked from the go front-end and by default all
functions are marked as DECL_UNINLINABLE such that the stack frame info
is preserved for panic recovery. This is not the case for Rust and by
default allows for inline optimizations here.
This patch changes the flag to be that if you wish to ensure a function
is uninlineable you msut specify that specific flag for that function and
by default GCC what optimisations to perform.
There is compiler magic for method calls the self parameter can be of
several forms:
- specified type (self: Type)
- immutable Self (self)
- mutable Self (mut self)
- immutable reference (&self)
- mutable reference (&mut self)
This updates our HIR lowering to actually lower this correctly and apply
the apropriate Self type to the TyTy::FnDef. The code used to just default
to plain Self ignoring any modifiers.
Rust also allows something called the autoderef cycle to coerce the
receiver to the correct type for the function such as:
```rust
struct Foo(i32);
impl Foo {
fn bar(&self) { }
}
fn main() {
let a = Foo(123);
a.bar();
}
```
In this example the method call is expected to apply an implict reference
to variable 'a' such that the method call becomes:
```
Foo::bar(&a);
```
The algorithm is detailed here:
https://doc.rust-lang.org/nightly/nomicon/dot-operator.html
1. Try to match Self
2. Apply an immutable Reference and Try again
3. Apply an mutable Reference and Try again
4. Can we dereference ? [deref and go back to 1] else [quit]
This is not 100% complete since we do not yet support operator overloading
so we wil require an update to support the Deref operator overload for
more complex types.
Fixes: #241
671: Support indirection for struct and tuple field access r=philberty a=philberty
This allows for fat pointers to be used for tuple or struct field access by
supporting the GCC indirect references by binding the type to the reference.
This might get updated when we support the autoderef mechanism and if the
type supports the deref trait.
Addresses #241
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
When we have a fat pointer to a structure the GCC needs to know the RECORD
or UNION type of the type before it can access fields, this can be
supported by C'stye indirection such as '->'.
This might get updated when we support the autoderef mechanism and if the
type supports the deref trait.
Addresses #241
669: Fix bug with monomorphizing of trait items r=philberty a=philberty
When we monomorphize functions we need to check if we have already
generated this function already. All function items have a DefId which is
unique for the crate and HIR item this means for generic implementations
of an item we end up with mappings of:
DefId -> [ (concete-tyty-fntype, GCC::Function), ... ]
So for any function we can lookup for that DefId is there a suitable
version of this function already compiled. This was working untill we have
generic trait items which also need to be handled in the same way.
Fixes#668
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
When we monomorphize functions we need to check if we have already
generated this function already. All function items have a DefId which is
unique for the crate and HIR item this means for generic implementations
of an item we end up with mappings of:
DefId -> [ (concete-tyty-fntype, GCC::Function), ... ]
So for any function we can lookup for that DefId is there a suitable
version of this function already compiled. This was working untill we have
generic trait items which also need to be handled in the same way.
Fixes#668
666: Super Traits Support r=philberty a=philberty
This adds initial super traits support. Super traits are implemented by
explicitly adding the super trait bound to the implicit Self type parameter
on traits. This will improve as we enhance the type system to handle bounds
and where constraints in general as they reuse all that same code path.
Fixes#565
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
661: Add support for choosing other builtin GCC calling conventions r=philberty a=philberty
Add support for some other ABI options.
I was able to test this with linking against some C code but
these options like stdcall seem to be limited to 32 bit mode
```rust
extern "stdcall" {
pub fn test(a: i32) -> i32;
}
extern "C" {
fn printf(s: *const i8, ...);
}
fn main() -> i32 {
unsafe {
let a = 3;
let res = test(a);
let a = "%i\n\0";
let b = a as *const str;
let c = b as *const i8;
printf(c, res);
}
0
}
```
```c
__attribute__ ((stdcall)) int test(int x) {
return x + 3;
}
```
Compiling like this:
```
$ gccrs -g -O0 -m32 -c test.rs -o test.o
$ gcc -g -O0 -m32 -c lib.c -o lib.o
$ gcc -m32 -o test test.o lib.o
```
More testing will be required over time here but this was
kind of fun to see that it worked.
663: Move module output test case from compile/ to execute/ r=philberty a=CohenArthur
Fixes [this issue](https://github.com/Rust-GCC/gccrs/pull/639#discussion_r705922519) by `@tschwinge`
I think this shows that we need to figure out a better way to keep test files and their modules, as pointed out by `@dkm` [here](https://github.com/Rust-GCC/gccrs/pull/639#issuecomment-905457557). Here, the modules/ directory is a straight up duplicate of the other one in compile/ which I'm not a fan of.
I have no experience with having a separate .exp in the subdir but I can try and I think that it would be better. Maybe it can also be simpler if the regex to match *.rs files only looks inside one level of subdirectories? But I can think of a few places where this might be an issue
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
Co-authored-by: CohenArthur <arthur.cohen@epita.fr>
664: Fix usage of path attributes and module filename processing r=philberty a=CohenArthur
`#[path]` attributes were used wrongly in two ways:
- The attribute's value would still contain extra data such as an equal
sign and whitespaces, which need to be discarded in order to fetch the
proper file path.
- `#[path]`s are relative to the directory where the current source file
is located. So we actually need to compute them later on down the line,
once the including directory has been figured out.
Another issue was that in the case that no candidates were found, or too
many were founds, the function `process_file_path` would still return
"successfully" despite erroring out. This causes the function to return
early and thus not assign any string to the `module_file` member.
We also have the ability to emit an error for the module's location,
which looks better for the user, instead of using a new `Location()`
like the session manager does (because it cannot do otherwise, as it
is starting to parse a file and thus has no file location information)
Co-authored-by: CohenArthur <arthur.cohen@epita.fr>
Super Traits are simply TraitBounds upon the implict Self TypeParameter,
such that a trait with a super trait bound almost ends up looking like this
trait A : B { } -> trait A where Self: B { }
When we have generic code that calls other generic code the type system
will have already setup the side tables for substituions and at this point
the referenced generic code does not need to be substituted again.
path attributes were used wrongly in two ways:
1/ The attribute's value would still contain extra data such as an equal
sign and whitespaces, which need to be discarded in order to fetch the
proper file path.
2/ #[path]s are relative to the directory where the current source file
is located. So we actually need to compute them later on down the line,
once the including directory has been figured out.
Another issue was that in the case that no candidates were found, or too
many were founds, the function `process_file_path` would still return
"successfully" despite erroring out. This causes the function to return
early and thus not assign any string to the `module_file` member.
We also have the ability to emit an error for the module's location,
which looks better for the user, instead of using a new `Location()`
like the session manager does (because it can't do otherwise)
662: Add building blocks for super-traits r=philberty a=philberty
Add name resolution and HIR lowering to trait-bounds
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
GCC adds these as options to the function type as far as I can see, I was
able to test this with linking against some C code. More testing is
required here.
659: Initial intrinsics builtin block r=philberty a=philberty
This is the initial piece to get the simple intrinsic's mapped over to GCC ones. The
GCC wrapper contains a mapping system of rust names over to the builtin gcc names
as far as I can tell gcc will allow for fallback onto linking against -lm.
I think this will be a nice piece of work for new contributors, given the number of intrinsics
Addresses #658
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
Co-authored-by: Thomas Schwinge <thomas@codesourcery.com>
639: External module expansion r=philberty a=CohenArthur
Needs #638
This PR parses the file associated with an external module and allows their compilation. The two test cases are not currently passing, and the locations will be inexact (the filename for the parsed module will just show as random characters), so the PR is still a draft.
Co-authored-by: CohenArthur <arthur.cohen@epita.fr>
Avoid proliferation of such execution tests: such builtins typically are mapped
to regular function calls (which we already do have confidence that they work
correctly), so it ought to suffice to just scan '-fdump-tree-original'.
660: Support '-fdump-tree-original' before 'cgraph_node::finalize_function' r=tschwinge a=tschwinge
Co-authored-by: Thomas Schwinge <thomas@codesourcery.com>
We need a way to be able to turn intrinsic function prototypes and
associated function calls into the GCC builtin. The GCC wrapper was
reused from GO and the math builtin's don't seem to be correct, here
I changed __builtin_sin to __builtin_sinf to get the float version.
See builtins.def for the other builtins.
We need to know the specified ABI in order to determine the linkage, it
might be a plain old rust function, an extern C function or a compiler
intrinsic and each of these needed to be handled differently.
656: Add mangling switch r=philberty a=CohenArthur
Add option to choose mangling scheme.
Closes#429
This PR splits the `Mangler` class in its own set of header and source and adds the base for v0 name mangling.
You are now able to specify the mangling scheme to use using `-frust-mangling=<value>`.
When inputting an invalid value, the compiler errors out using `unrecognized command-line option `-frust-mangling=<not_valid>`. Is there a better way to do this? Is there also a way to test this behaviour using dejagnu?
Co-authored-by: CohenArthur <arthur.cohen@epita.fr>
657: Add building blocks for enum support r=philberty a=philberty
see https://gcc.gnu.org/pipermail/gcc-rust/2021-September/000174.html
This set of patches adds support for parsing, name resolution and HIR lowering for enums.
Typechecking and code-generation are still in progress but these patches are ready to merge now.
Co-authored-by: Mark Wielaard <mark@klomp.org>
Make HIT EnumItem class an Item, not VisItem like in the AST. At the
HIR level EnumItems shouldn't have visibility anymore.
Move struct_field_name_exists to rust-ast-lower.cc with the
declaration in rust-ast-lower.h to make it reusable in the different
visitors.
Add a new ASTLoweringEnumItem that can be used from ASTLoweringItem
and ASTLoweringStmt. It checks the EnumItems don't have visibility and
that EnumItemStruct fields are not duplicated.
Add a new testcase 'bad_pub_enumitems.rs' to check the no-visibility and
no-duplicates properties hold.
Generate paths for Enum and EnumItem AST NodeIds and resolve the types
of tuple and struct enum items.
EnumItems always have the Enum as prefix. To make this work for
ResolveStms (declaration statements are not given a canonical path) we
add an enum_prefix to be used when resolving EnumItems.
For ResolveType the tuple and struct fields get resolved using the
Enum type scope.
Add tests for toplevel or stmt enums with duplicate variant names. And
adjust the tuple_enum_variants.rs testcase to expect unused name
warnings.
Syntactically enum items can have a visibility. The visibility has to
be removed (through a cfg attribute or macro) before they get lowered.
The semantic checking will be done when we implement lowering enum items.
Make the AST EnumItem class a VisItem. This simplifies things a little
for cloning items, handling outer attributes and will help when adding
EnumItem (sub)classes to AST visitors (so they can be handled as
Items). Also add a get_identifier method to Enum and EnumItem.
655: Generic Qualified Paths r=philberty a=philberty
This fixes how we handle associated types in relation to generic
traits. Generic traits are interesting because, a TypePath usually
resolves to a normal TyTy type which can be substituted using the
mapper classes, but a trait is a definition of behaviour which
is made up of types, constants or functions. In order to handle
generic traits we must add substitution support to the associated types
which are represented by projections see this commit for detail on the changes
0798add3d3
Also see https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/ty/sty/struct.ProjectionTy.htmlFixes#434
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
This extends the ProjectionType which represents an implemented associated
type with its own substitution mappings. The problem is a TypePath to a
trait does not represent a single TyTy primitive type, the type system
handles generics in an interesting way. Take for instance the case of a
generic impl block:
impl<T> Foo<T> {
fn Bar<Y>(self, a:T, b:Y) {}
}
The compiler treats an impl block as the parent so that all items inherit
from this, which is why rustc calls these inherent-impl-blocks. So
in order to handle generic arguments we need to "bind" them, and in rust
only some types actually support generic argument binding, at the moment
for gccrs it is, ADTTypes, FnTypes and Projections. Going back to the
example the TyTy for this function turns into:
fn Bar<T,Y>(Foo<T>, T, Y)
So when it comes to the generic traits its a similar process but the
difference is that traits contain associated types, these must be able
to bind the generic arguments such that we can substitute any covariant
types fully. But there is a layer of complexity and indirection here
consider the following example:
trait Foo<T> {
type A;
fn test(a: T, b: Self::A) -> (T, Self::A) {
(a, b)
}
}
struct Bar<T>(T);
impl<T> Foo<T> for Bar<T> {
type A = T;
}
When we deal with a trait with an optional trait function that uses the
associated types what actually happens here is that the type A in this
trait context is considered just a simple PlaceHolder which gets
setup within relation to its relevant impl block, so when we setup the
associated types it turns into:
Placeholder(A) ->
Projection<T>(Bar<T> as Foo<T>) ->
T
So it forms an recursive chain that must be substituted in relation to
what the paticular query is.
The canonical path for a traits does not include the generic arguments
but they must be resolved. This ensures we can actually resolve a generic
trait reference to the correct trait.
When we resolve a TypePath we expect this to resolve to a TyTy and to
substitute arguments accordingly. Qualified paths contain a trait reference
which can contain generic arguments, the problem here is that traits are
not a TyTy type since traits define behaviour not types. In order to
actually apply the substitutions in a future commit we must be able
to access these arguments in a sensible way first.
Traits implement self by creating an implicit Self TypeParam but when
we need to support generic arguments we must ensure Self is substituted
first so that the reset of the arguments are handled as we expect.
654: Cleanup some StructExpr related classes r=philberty a=dkm
From Mark Wielaard: https://gcc.gnu.org/pipermail/gcc-rust/2021-September/000163.html
> There are various Structure Expressions that don't actually "exist"
> because they are syntactically equivalent to other constructs. So we
> never really construct or use these classes. But they are still listed
> in various visitors, which is somewhat confusing. Removing the AST and
> HIR variants of these classes really cleans up the code IMHO.
Co-authored-by: Mark Wielaard <mark@klomp.org>
An Enumeration Expression is just like a Struct Expression. Old
versions of the Rust Reference described them separately. But since
they are syntactically exactly like a Struct Expression they are never
actually parsed. A Struct Expression can also be used to initialize
enums (and unions).
Remove the AST and HIR classes EnumExprField, EnumExprFieldIdentifier,
EnumExprFieldWithVal, EnumExprFieldIdentifierValue,
EnumExprFieldIndexValue, EnumExprStruct, EnumExprTuple,
EnumExprFieldless and EnumVariantExpr.
A StructExprUnit is parsed as an IdentifierExpr. An IdentifierExpr,
which is what we call a single segment PathInExpression.
After type checking, when generating gcc generic trees, if the
IdentifierExpr is a type reference (which must be a unit struct), then
a unit expression is generated.
Remove the AST and HIR StructExprUnit classes which are never used.
A StructExprTuple is parsed as a CallExpr. Both (can) start with a
PathInExpression followed by zero or more Expressions between
brackets.
Only, after type checking, when actually generating gcc generic trees
is a distinction made between a function call or tuple constructor.
Remove the AST and HIR StructExprTuple classes which are never used.
Qualified type paths are similar to qualified path expressions, in that
they must resolve the projection of the trait onto a type to receive the
correct associated type information.
Placeholder types are containers for associated types, the code-generation
pass has a check for is_unit on return types for functions so we can inject
void_type_node. This was a false positive for placeholders, placeholders
must resolve to check what their concrete implementation type actually is
for this type of query.
Qualified path in type's initial segment is mandatory (+) any other
segments are optional after the fact. see
https://doc.rust-lang.org/reference/paths.html#qualified-paths
This change makes the AST have a mandatory field for the initial segment
the segment list now only contains the optional remaining segments.
650: Stop shadowing of hir mappings with substitution mappings r=philberty a=philberty
There was a hidden segv nullptr in the check for unconstrained
type parameters. Since the util mappings class name is being shadowed
by the substitution mappings we never actually hit the segv. As part
of my work in traits and qualified paths we need access to the hir mappings
class which was shadowed. This removes shadowing and fixes the segv
for unconstrained type parameters.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
Name shadowing in C++ is annoying, it can cause subtle errors like here,
the mappings which are substitition mappings, for example from an impl
block, impl<X,Y> Foo(X), the type resolver here looks for any unconstrained
type parameters by passing the relative mappings which can be null. Since
the util mappings class shadowed this we never actually got this hidden
nullptr segv. For QualifiedTypes we need to resolve the path similar to
path expressions and we will need to be able to access the shadowed util
hir mappings class.
648: Fix issue with mangled name on function items with substitutions r=philberty a=philberty
Rust legacy name mangling does not contain the substitutions as part of
its mangled name for Item's. Rust avoids duplicate symbol collisions with
the legacy mangling scheme, but including a 128bit hash at the end of the
symbol, which is made up with metadata and in this case the mangled symbol
contains a hash of the type which this function is.
Fixes#647
649: Get rid of get_locus_slow r=philberty a=dkm
From Mark Wielaard: https://gcc.gnu.org/pipermail/gcc-rust/2021-August/000154.html
>
> In various places there was the following hack:
>
> /* HACK: slow way of getting location from base expression through
> virtual methods. */
> virtual Location get_locus_slow () const { return Location (); }
>
> The problem with get_locus_slow () is that if a subclass didn't
> override it then there was no real location. get_locus_slow was
> missing for Module, ExternCrate, UseDeclaration, Function, TypeAlias,
> StructStruct, TupleStruct, Enum, Union, ConstantItem, StaticItem,
> Trait, ImplBlock, ExternBlock, EmptyStmt, ExprStmtWithoutBlock and
> ExprStmtWithBlock. All do have a get_locus () function.
>
> Simply replace the get_locus_slow virtual method with a real virtual
> Location get_locus () const = 0 method so we know if something
> really doesn't have a location. This was only the case for
> MacroRulesDefinition.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
Co-authored-by: Mark Wielaard <mark@klomp.org>
646: Resolve module filename from path attribute r=philberty a=CohenArthur
Allow for the user to specify the path of a module using the `#[path]` attribute
Co-authored-by: CohenArthur <arthur.cohen@epita.fr>
In various places there was the following hack:
/* HACK: slow way of getting location from base expression through
virtual methods. */
virtual Location get_locus_slow () const { return Location (); }
The problem with get_locus_slow () is that if a subclass didn't
override it then there was no real location. get_locus_slow was
missing for Module, ExternCrate, UseDeclaration, Function, TypeAlias,
StructStruct, TupleStruct, Enum, Union, ConstantItem, StaticItem,
Trait, ImplBlock, ExternBlock, EmptyStmt, ExprStmtWithoutBlock and
ExprStmtWithBlock. All do have a get_locus () function.
Simply replace the get_locus_slow virtual method with a real virtual
Location get_locus () const = 0 method so we know if something
really doesn't have a location. This was only the case for
MacroRulesDefinition.
Rust legacy name mangling does not contain the substitutions as part of
its mangled name for Item's. Rust avoids duplicate symbol collisions with
the legacy mangling scheme, but including a 128bit hash at the end of the
symbol, which is made up with metadata and in this case the mangled symbol
contains a hash of the type which this function is.
Fixes#647
642: Reject duplicate field names in structs and unions. r=philberty a=dkm
From Mark Wielaard : https://gcc.gnu.org/pipermail/gcc-rust/2021-August/000150.html
> Odd things happen if structs or unions have duplicate field names.
> Emit an error when lowering an struct/union item or declaration
> statement and a duplicate field name is detected. A new testcase
> 'dup_fields.rs' checks an error is actually produced.
Co-authored-by: Mark Wielaard <mark@klomp.org>
Odd things happen if structs or unions have duplicate field names.
Emit an error when lowering an struct/union item or declaration
statement and a duplicate field name is detected. A new testcase
'dup_fields.rs' checks an error is actually produced.
641: Ignore impl trait blocks in overlap pass r=philberty a=philberty
Ignore trait-impls in overlapping check this needs some though for generics traits.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
Impls can have items which overlap mostly when generics are involved. Trait
impls are slightly different beacuse they can be handled via qualified
paths. This ignores trait-impls in this pass and some thought should be
required to handle his case later on.
640: Optional Trait items constants r=philberty a=philberty
This adds more support for optional trait items such as constants.
Some fixes come along with this PR such as improved query-based
compilation for trait items which is now a canonical implementation for
qualified and normal paths in HIR.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
This changes Path resolution to check for impl items first, then extensions
second. This stops some invalid multiple canidate errors such as the case
when the trait implements a function but the reciever also implements it
to override the behaviour.
Rust can forward declare items to avoid the need for prototypes for
example. This means when a path resolved to a node we must look it up
and see if it is already compiled or go and compiler it. This also applies
to generics which are monomorphized and might have already been compiled.
This adds two new keyword arguments bool query_mode and ref_locus, these
say to the classes that this is query based mode and ICE when we get
error_mark_node when we fail to compile something. This will need to be
changed once we get to a certain level of maturity but this helps
diagnose bugs for now. The ref_locus refers to the location of the
reference to this item such that the compilation of an item can give us
a reference expression to this item with this ref_locus. For example:
call (123)
And call is query compiled and the ref_locus is this call_expression.
This adds a probe to lookup candidates for a segment for any impl block
for this receiver and trait. This simplifies some query based compilation
code. When the item is resolved to a trait item but might be overriden by
a reciever impl block instead.
Post type checking we need to be able to lookup trait references, but do
not need to resolve the trait with error messages. We simple want to look
it up if it exists.
638: hir: Merge both module classes in one r=philberty a=CohenArthur
At this point in the pipeline, all modules are either internal and
contain items, or external and have been previously expanded in the
macro-expand phase. Thus, all HIR modules will contain their final set
of items
Co-authored-by: CohenArthur <arthur.cohen@epita.fr>
At this point in the pipeline, all modules are either internal and
contain items, or external and have been previously expanded in the
macro-expand phase. Thus, all HIR modules WILL contain their final set
of items
626: Optional trait items r=philberty a=philberty
Optional trait items like function may contain associated types. These
are dependant on the associated impl block for this type in order to
correctly propagate the correct types for the associated trait item during
type checking and compilation.
Fixes#542
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
QualifiedPathInExpressions resolve to trait items which require careful
management of substitutions which still need to be implemented. This is the
building block to get that work done.
This is a special type in the rust implementation which contains all the
info to generate the relevant declarations to compile trait items which
might be fully optional.
Qualified paths such as: <Foo as Bar>::A give the ability to resolve to
trait-impls or trait-items directly. It is a type of projection.
Remember trait impl blocks have the relevant canonical path so we can
resolve with canonical paths and reuse the existing path in expression
code.
This adds compilation support for optional trait functions with a function
block. This does not support constants or default types yet.
Trait references must do type resolution of their block, but this is only
performed once a trait is resolved. In order to avoid recursive trait
resolution we use a on_resolved callback to invoke this to occur. The trait
resolver works as a query based system so you have to avoid the case of
recursively resolving the trait untill it is stored in the internal
mappings.
Addresses #542
509: Initial support for module r=philberty a=dkm
Adds name resolution, HIR lowering and type checking. For modules
which should allow for initial multiple file parsing support.
Fixes#432
636: Suppress uninitialized candidate_type warning in process_traits_for_candidates r=philberty a=dkm
From Mark Wielaard : https://gcc.gnu.org/pipermail/gcc-rust/2021-August/000142.html
> Without handling the default case in the switch statement gcc 10.2.1 will warn:
>
> rust-hir-path-probe.h:75:40: warning: ‘candidate_type’ may be used uninitialized
> in this function [-Wmaybe-uninitialized]
Co-authored-by: Mark Wielaard <mark@klomp.org>
Co-authored-by: Marc Poulhiès <dkm@kataplop.net>
637: Add support for const bool and const float r=philberty a=dkm
From Mark Wielaard : https://gcc.gnu.org/pipermail/gcc-rust/2021-August/000143.html
> Handle BOOL and FLOAT in ConstFoldExpr::visit (HIR::LiteralExpr) to
> make it possible to create const bool, f32 and f64 constants. Add a
> new testcase "primconsts.rs". Not yet handled are const char and &str
> types.
Co-authored-by: Mark Wielaard <mark@klomp.org>
The gcc constant folding code uses the type_for_size langhook. Use the
default implementation instead of crashing when the langhook is
called. Add a new testcase "prims_struct_eq.rs" that creates trees
that triggers the constant folding.
Also remove the write_globals langhook which was removed when early
debug was integrated into gcc.
bools and chars can be cast to any integer type, but not to floats or
each other. Adjust the BoolCastRule and CharCastRule to allow these
casts. Add a postive test "as_bool_char.rs" and negative test
"bad_as_bool_char.rs" to check the correct casts are accepted and the
illegal casts produce errors.
Resolves: https://github.com/Rust-GCC/gccrs/issues/629
632: Use default type_for_size langhook r=philberty a=dkm
From Mark Wielaard : https://gcc.gnu.org/pipermail/gcc-rust/2021-August/000144.html
> The gcc constant folding code uses the type_for_size langhook. Use the
> default implementation instead of crashing when the langhook is
> called. Add a new testcase "prims_struct_eq.rs" that creates trees
> that triggers the constant folding.
>
> Also remove the write_globals langhook which was removed when early
> debug was integrated into gcc.
Co-authored-by: Mark Wielaard <mark@klomp.org>
633: Allow bool and char to be cast as any integer type r=philberty a=dkm
From Mark Wielaard : https://gcc.gnu.org/pipermail/gcc-rust/2021-August/000147.html
> bools and chars can be cast to any integer type, but not to floats or
> each other. Adjust the BoolCastRule and CharCastRule to allow these
> casts. Add a postive test "as_bool_char.rs" and negative test
> "bad_as_bool_char.rs" to check the correct casts are accepted and the
> illegal casts produce errors.
>
> Resolves: https://github.com/Rust-GCC/gccrs/issues/629
Co-authored-by: Mark Wielaard <mark@klomp.org>
631: Use builtin bool instead of creating new bool types for ComparisonExpr r=dkm a=dkm
From Mark Wielaard : https://gcc.gnu.org/pipermail/gcc-rust/2021-August/000141.html
> The TypeCheckExpr creates a new TyTy::BoolType for a
> ComparisonExpr. This new BoolType is unknown to TyTyResolveCompile
> which causes a crash when trying to compile the inferred new
> BoolType. Resolve this by looking up the builtin bool type.
> The new "bools_eq.rs" testcase uses several bools which show
> this issue.
>
> Also the lhs and rhs types need to be compatible, but don't
> need to be bool type themselves. So don't append the reference
> to the inferred type. The existing "ifunaryexpr.rs" testcase
> will fail without this fix.
Co-authored-by: Mark Wielaard <mark@klomp.org>
The TypeCheckExpr creates a new TyTy::BoolType for a
ComparisonExpr. This new BoolType is unknown to TyTyResolveCompile
which causes a crash when trying to compile the inferred new
BoolType. Resolve this by looking up the builtin bool type.
The new "bools_eq.rs" testcase uses several bools which show
this issue.
Also the lhs and rhs types need to be compatible, but don't
need to be bool type themselves. So don't append the reference
to the inferred type. The existing "ifunaryexpr.rs" testcase
will fail without this fix.
bools and chars can be cast to any integer type, but not to floats or
each other. Adjust the BoolCastRule and CharCastRule to allow these
casts. Add a postive test "as_bool_char.rs" and negative test
"bad_as_bool_char.rs" to check the correct casts are accepted and the
illegal casts produce errors.
Resolves: https://github.com/Rust-GCC/gccrs/issues/629
The gcc constant folding code uses the type_for_size langhook. Use the
default implementation instead of crashing when the langhook is
called. Add a new testcase "prims_struct_eq.rs" that creates trees
that triggers the constant folding.
Also remove the write_globals langhook which was removed when early
debug was integrated into gcc.
Handle BOOL and FLOAT in ConstFoldExpr::visit (HIR::LiteralExpr) to
make it possible to create const bool, f32 and f64 constants. Add a
new testcase "primconsts.rs". Not yet handled are const char and &str
types.
Without handling the default case in the switch statement gcc 10.2.1 will warn:
rust-hir-path-probe.h:75:40: warning: ‘candidate_type’ may be used uninitialized
in this function [-Wmaybe-uninitialized]
630: parse if expression with unary minus or not expression r=philberty a=dkm
From Mark Wielaard : https://gcc.gnu.org/pipermail/gcc-rust/2021-August/000140.html
> An if conditional expression doesn't need brackets, but that means
> that it doesn't accept struct expressions. Those are not easy to
> distinquish from the block that follows. What isn't immediately clear
> from the grammar is that unary conditions like minus '-' or not '!'
> also shouldn't accept struct expressions (when part of an if
> conditional expression) because those also cannot be easily
> distinquished from the block that follows.
>
> Add a testcase "ifunaryexpr.rs" that shows a couple of contructs that
> should be accepted as if conditional expressions and fix the parser to
> pass the restriction of not accepting struct expressions after a unary
> expression.
Co-authored-by: Mark Wielaard <mark@klomp.org>
An if conditional expression doesn't need brackets, but that means
that it doesn't accept struct expressions. Those are not easy to
distinquish from the block that follows. What isn't immediately clear
from the grammar is that unary conditions like minus '-' or not '!'
also shouldn't accept struct expressions (when part of an if
conditional expression) because those also cannot be easily
distinquished from the block that follows.
Add a testcase "ifunaryexpr.rs" that shows a couple of contructs that
should be accepted as if conditional expressions and fix the parser to
pass the restriction of not accepting struct expressions after a unary
expression.
628: typecheck: add assert on resolve_root_path return value r=philberty a=dkm
resolve_root_path can return nullptr in case of error.
Better raise an error than dereference the pointer.
Co-authored-by: Marc Poulhiès <dkm@kataplop.net>
613: Resolve module filename r=philberty a=CohenArthur
This PR is a first attempt at resolving the filename corresponding to an external module correctly. Some of the cases are not handled yet and a lot of FIXMEs are still here, as I am looking for feedback on certain things:
* Am I correct in assuming that we have to go through directories the C way because we are using C++11 and the `filesystem` header is not available until C++17? Is there some gcc abstraction for this that I'm overlooking?
* How important is the existence of a separate SEPARATOR macro for Windows? From what I'm understanding, the OS also understands normal slashes `/` on top of the backward slashes it usually uses `\`. I don't know what happens when they are mixed and matched or how the file system handles it.
* For review simplicity, outer attributes could be accessed in a later PR. I believe they can already be accessed and looked at but haven't looked into it. I'm also unsure if this would be the right place to implement that outer_attr lookup
Co-authored-by: CohenArthur <arthur.cohen@epita.fr>
When parsing an external module, it is important to be able to access
the original "including" file in order to resolve the path of the
desired module. Take the following example
```rust
// /project/src/foo.rs
mod bar; /* External module */
```
The file which contains the `bar` module could be located at
`/project/src/bar.rs`, or at `/project/src/foo/bar.rs` (careful, this isn't an exhaustive list
of all possible cases). We must therefore be able to access the
`/project/src` directory in order to find valid candidates for `mod
bar`
625: Change name resolver's iterate_* functions to allow early exit r=philberty a=dkm
The callback now returns a bool for continuing the iteration (true) or stopping
it (false).
Fixed the scanning for unused names without changing its behavior (always doing
full iteration).
Co-authored-by: Marc Poulhiès <dkm@kataplop.net>
The callback now returns a bool for continuing the iteration (true) or stopping
it (false).
Fixed the scanning for unused names without changing its behavior (always doing
full iteration).
623: Add mappings for canonical paths r=philberty a=philberty
We need to be able to lookup canonical paths in order
to do proper name mangling as well as give more meaning
full names to the GENERIC IR. This is important since
the gcc IR is flat and makes it hard to distinguish which function
is which, especially when modules support will be added.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
This uses the mappings for canonical paths to give more meaning ful names
to the flat GENERIC IR. This will also be used to cleanup the duplications
in code-generation for two distinct methods to compile functions.
This code will also be needed to enhance name mangling.
We need to be able to lookup the canonical path for items to persue
correct naming and name mangling in code generation.
We allow for duplicates node-ids in the mapper so long as the paths are
equal or assert and ignore the new path so long as it is shorter than the
existing one.
This is the case because we are inserting relative paths for names which
will be shorter that the fully qualified path but also have the same NodeId
621: Add docker image builds though github actions. r=philberty a=philberty
Recently dockerhub is now charging for automated builds on dockerhub. This
means we no longer have regular updated docker builds of gccrs.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
620: Pass pratt parsed location to expr parser functions to fix expr locus r=philberty a=philberty
This change fixes the location to provide better error tracking.
Co-authored-by: Mark Wielaard <mark@klomp.org>
The pratt parser skips the first token of an expression before
invoking the actual expression parsing function. This makes getting
the correct starting location of a pratt parsed expression hard. The
"correction" of the location by subtracting an integer is often wrong
(since there may be arbitrary whitespace or comments between
tokens). Fix this by passing the location of the skipped token to the
expression parsing functions (instead of just providing a pratt_parse
boolean). Use this location to set the start of the expression (and as
indicator to not try to parse the first token of the expression).
Before gccrs would generate the following error message:
return.rs:3:22: error: cannot ‘break’ outside of a loop
3 | let x = 5 - break return (16 + 2);
| ^~~~~~~~~~~~~~~~~
Now we get:
return.rs:3:17: error: cannot ‘break’ outside of a loop
3 | let x = 5 - break return (16 + 2);
| ^
619: Rename CanonicalPath::is_error to is_empty r=philberty a=dkm
`is_error` connotes that an error has been found or that the object is faulty.
It is possible to `create_empty` paths and pass them around. Having to use
`is_error` to test for valid emptiness can be misleading.
Co-authored-by: Marc Poulhiès <dkm@kataplop.net>
`is_error` connotes that an error has been found or that the object is faulty.
It is possible to `create_empty` paths and pass them around. Having to use
`is_error` to test for valid emptiness can be misleading.
618: Make insert_new_definition permissive of the same mapping. r=philberty a=philberty
This was a fix required for `@dkm` work on the module support.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
Definition provide child-parent relation ships within the name scope. This
was used for let stmts such that the let stmt pattern can reference its
parent during type-resolution/code-generation such that we can lookup
the parent mappings for typing etc.
It should be permissive to allow overriding definition mappings when the
definition items are equal. This is important during module name resolution
since it should be able to run the toplevel scan to gather the relevant
names into the top of the scope as well as the relative paths which contain
the same ids within the uppermost scope.
611: Add check for TypeBounds on argument substitutions r=philberty a=philberty
TypeParameters contain specified bounds, when we substitute them we need
to ensure that the argument satisfies those bounds otherwise... it fails
the contract.
Addreses #440
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
615: lex: accept zero codepoints in strings r=philberty a=dkm
From Mark Wielaard : https://gcc.gnu.org/pipermail/gcc-rust/2021-August/000127.html
>
> Zero characters (codepoints) are acceptable in strings. The current
> Lexer::parse_string skipped such zero codepoints by accidents. The
> zero codepoint was also used as error/skip indicator, but that is only
> true if the third argument of utf8_escape_pair is true (yes, it is
> called pair, but is a triple).
>
> Add a testcase that checks the (sub)strings are separated by zero
> chars. Since we cannot slice strings yet this uses extern "C"
> functions, printf and memchr.
Co-authored-by: Mark Wielaard <mark@klomp.org>
We emit one error for all unsatisfied bounds such as:
test.rs:26:31: error: bounds not satisfied for Test ‘Bar, Baz’ is not satisfied
21 | fn type_bound_test<T: Foo + Bar + Baz>() -> i32 {
| ~ ~
......
26 | let a = type_bound_test::<Test>();
| ^
Zero characters (codepoints) are acceptable in strings. The current
Lexer::parse_string skipped such zero codepoints by accidents. The
zero codepoint was also used as error/skip indicator, but that is only
true if the third argument of utf8_escape_pair is true (yes, it is
called pair, but is a triple).
Add a testcase that checks the (sub)strings are separated by zero
chars. Since we cannot slice strings yet this uses extern "C"
functions, printf and memchr.
612: Turn Session Manager into basic singleton r=philberty a=CohenArthur
This PR changes the behavior of the compiler's session manager: Instead of keeping a single static instance in `rust-lang.cc`, the class now exposes a static instance via a `get_instance()` method. This is important for external module parsing as a new lexer and parser need to be instantiated during macro expansion, and a lexer must rely on a linemap, of which a single instance exists and is contained in the `Session` instance.
I ran into a few issues trying to make this a bit smarter (for example, by calling `init()` on the first `get_instance()` invocation) because I ran into a race condition. I haven't looked into it, but it seems that the calls to the various language hooks are sometimes multithreaded.
Co-authored-by: CohenArthur <arthur.cohen@epita.fr>
614: rust to gcc glue layer: Remove excess precision when done r=philberty a=karcherm
Fixes#467
- \[ ] GCC code require copyright assignment: https://gcc.gnu.org/contribute.html
This is not a large contribution, so copyright assignment seems not needed. Signed-Off-By has been added.
- \[x] Read contributing guidlines
- \[x] `make check-rust` passes locally
- \[x] Run `clang-format`
- \[x] Added any relevant test cases to `gcc/testsuite/rust/`
Co-authored-by: Michael Karcher <debian@mkarcher.dialup.fu-berlin.de>
TypeParameters contain specified bounds, when we substitute them we need
to ensure that the argument satisfies those bounds otherwise... it fails
the contract.
This change only checks this specific case as a nice isolated PR to
demonstrate the mechanism's we require. Specified bounds are checked but
we must also probe for what bounds are available for the type.
Addreses #440
610: More rustspec.cc cleanups r=philberty a=dkm
From Mark Wielaard : https://gcc.gnu.org/pipermail/gcc-rust/2021-August/000117.html
> rustspec.cc was based on the Go frontend gospec.cc. Remove special
> handling of math and pthread libraries and profiling option. Handle
> .rs files instead of .go files. Keep support for linking with (static)
> librust which is currently commented out. Add generic static-librust
> option to common.opt.
Co-authored-by: Mark Wielaard <mark@klomp.org>
rustspec.cc was based on the Go frontend gospec.cc. Remove special
handling of math and pthread libraries and profiling option. Handle
.rs files instead of .go files. Keep support for linking with (static)
librust which is currently commented out. Add generic static-librust
option to common.opt.
609: Initial TypeBounds support r=philberty a=philberty
This allows us to specify bounds on type parameters that influence
path resolution to allow us to resolve to trait items. More error
checking is required to actually enforce the trait constraint but
this patch is getting rather large and does not cause regressions.
Fixes#583
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
Preserve type-bounds into HIR for type resolution and code generation. This
follows the same style of classes in the AST and might need some tweaks
for where constraints.
608: Add `parse_items()` function from `parse_crate()` r=philberty a=CohenArthur
In order to support multiple file parsing, we will need to be able to parse items from a file without specifically parsing an entire crate. This PR splits up the `parse_crate()` function in two and exposes the `parse_items()` function.
The function was previously hidden and didn't have the exact same behavior as the main loop of `parse_crate()`.
This will be especially useful when trying to expand
```rust
mod <file>;
```
to
```rust
mod <file> {
<items>
}
```
in the AST as we will need to parse the items present in the file.
Co-authored-by: CohenArthur <arthur.cohen@epita.fr>
605: Merge both module classes in one r=philberty a=CohenArthur
This PR merges both kinds of Modules (formerly `ModuleBodied` and `ModuleNoBody`) as one class with an enum. This is the [behavior used by rustc](2939249f29/compiler/rustc_ast/src/ast.rs (L2274)), where both variants are kept in an enum with one holding a vector of items.
This change is important for multiple file parsing: An external mod (`mod foo; // defined in foo.rs or foo/mod.rs`) will see its items expanded during expansion, which occurs after parsing. This means that the previous directive will be "replaced" by `mod foo { <items> }` at the AST level. In order to achieve this, we need to be able to modify a previously parsed instance of an AST element.
In rustc, this is done [here](2939249f29/compiler/rustc_expand/src/expand.rs (L1427)), where `mod_kind` was previously `ModKind::Unloaded` and becomes `ModKind::Loaded(parsed_items, ...)`.
Co-authored-by: CohenArthur <arthur.cohen@epita.fr>
607: Remove split-stack from backend r=tschwinge a=dkm
From Mark Wielaard : https://gcc.gnu.org/pipermail/gcc-rust/2021-August/000110.html
> The backend was derived from the go backend which enables split stack
> support by default. This inserts a __morestack call at the start of
> each function. This is not needed for the rust backend. Remove the
> split stack support code from the rust backend and spec.
Co-authored-by: Mark Wielaard <mark@klomp.org>
When expect_token fails it produces an error and return a
nullptr. Make sure to always check the result of expect_token so we
don't use a nullptr token and crash.
Resolves: https://github.com/Rust-GCC/gccrs/issues/603
The backend was derived from the go backend which enables split stack
support by default. This inserts a __morestack call at the start of
each function. This is not needed for the rust backend. Remove the
split stack support code from the rust backend and spec.
602: Add locus to TupleField and pass it and union variants to HIR class r=philberty a=dkm
From Mark Wielaard : https://gcc.gnu.org/pipermail/gcc-rust/2021-August/000108.html
> TupleField was missing a Location field and we dropped to locus when
> lowering Union fields to HIR.
Co-authored-by: Mark Wielaard <mark@klomp.org>
601: union support for hir type checking and gcc backend r=dkm a=dkm
From Mark Wielaard : https://gcc.gnu.org/pipermail/gcc-rust/2021-August/000107.html
>
> Treat a union as a Struct variant like a tuple struct. Add an
> iterator and get_identifier functions to the AST Union class. Same
> for the HIR Union class, plus a get_generics_params method. Add a new
> ADTKind enum and adt_kind field to the ADTType to select the
> underlying abstract data type (struct struct, tuple struct or union,
> with enum as possible future variant).
>
> An union constructor can have only one field. Add an union_index field
> to StructExprStruct which is set during type checking in the
> TypeCheckStructExpr HIR StructExprStructFields visitor.
>
> For the Gcc_backend class rename fill_in_struct to fill_in_fields and
> use it from a new union_type method. Handle union_index in
> constructor_expression (so only one field is initialized).
Fixes#157
Co-authored-by: Mark Wielaard <mark@klomp.org>
Treat a union as a Struct variant like a tuple struct. Add an
iterator and get_identifier functions to the AST Union class. Same
for the HIR Union class, plus a get_generics_params method. Add a new
ADTKind enum and adt_kind field to the ADTType to select the
underlying abstract data type (struct struct, tuple struct or union,
with enum as possible future variant).
An union constructor can have only one field. Add an union_index field
to StructExprStruct which is set during type checking in the
TypeCheckStructExpr HIR StructExprStructFields visitor.
For the Gcc_backend class rename fill_in_struct to fill_in_fields and
use it from a new union_type method. Handle union_index in
constructor_expression (so only one field is initialized).
600: Use correct lookahead to peek after 'while' token when parsing expression with block (parse_expr_with_block). r=dkm a=asakovets
Co-authored-by: Alexey Sakovets <alexeysakovets@gmail.com>
598: Hello world r=philberty a=philberty
```rust
extern "C" {
fn puts(s: *const i8);
}
fn main() {
unsafe {
let a = "Hello World\0";
let b = a as *const str;
let c = b as *const i8;
puts(c);
}
}
```
Fixes#421
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
This adds extern block compilation support. It currently assumes the C abi
and does not perform any name mangling. It does not support varadic
arguments yet but its the initial support to get this working.
Fixes#421
599: Fix assertion for trait item mappings r=philberty a=philberty
These assertions defend against duplicate/bad mappings
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
597: Add name-resolution and HIR lowering for extern blocks r=philberty a=philberty
Addresses #421
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
This is the initial patch to do the ground work to support extern blocks.
Type resolution and Generic output still needs to be done to actually
support extern blocks.
Addresses #421
596: Fix crash when extern function item has no return type r=philberty a=philberty
Addresses #421Fixes#595
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
592: TypeCastExpr r=philberty a=philberty
This is the initial type casting rules more test cases will be added over time. To find gaps.
Fixes#158
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
Co-authored-by: Mark Wielaard <mark@klomp.org>
This gives us full explicit control for all casting. Just like other
rules. More test cases are needed to close out type-casts by the the end of
the traits milestone.
Fixes#592
593: Support RangeFrom ([x..]) and RangeFromTo ([x..y]) in the parser r=philberty a=dkm
Parsing the .. (DOT_DOT) operator to get a range had two
issues. Trying to compile:
let block = [1,2,3,4,5];
let _rf = &block[1..];
let _rt = &block[..3];
let _rft = &block[2..4];
range.rs:4:23: error: found unexpected token ‘]’ in null denotation
4 | let _rf = &block[1..];
| ^
range.rs:4:24: error: expecting ‘]’ but ‘;’ found
4 | let _rf = &block[1..];
| ^
Since .. can represent either a range from or a range from-to it can
be followed by an expression or not. We do have a hack in our
pratt-parser so that it is allowed to return a nullptr. But even in
that case it will have swallowed the next token. Add another hack to
the pratt-parser so that if the next token is one that cannot start an
expression and the caller allows a nullptr return then don't skip the
token and return immediately.
After this patch we can parse the above range expressions, but we
still don't handle them fully:
range.rs:4:20: fatal error: Failed to lower expr: [1..]
4 | let _rf = &block[1..];
| ^
Ranges are actually syntactic sugar for std::ops::Range[From|To].
Co-authored-by: Mark Wielaard <mark@klomp.org>
594: Support byte and byte string literals r=philberty a=dkm
A byte literal is an u8 created as a ascii char or hex escape
e.g. b'X'. A byte string literal is a string created from ascii or
hex chars. bytes are represented as u8 and byte strings as str (with
just ascii < 256 chars), but it should really be &'static [u8; n].
Co-authored-by: Mark Wielaard <mark@klomp.org>
Parsing the .. (DOT_DOT) operator to get a range had two
issues. Trying to compile:
let block = [1,2,3,4,5];
let _rf = &block[1..];
let _rt = &block[..3];
let _rft = &block[2..4];
range.rs:4:23: error: found unexpected token ‘]’ in null denotation
4 | let _rf = &block[1..];
| ^
range.rs:4:24: error: expecting ‘]’ but ‘;’ found
4 | let _rf = &block[1..];
| ^
Since .. can represent either a range from or a range from-to it can
be followed by an expression or not. We do have a hack in our
pratt-parser so that it is allowed to return a nullptr. But even in
that case it will have swallowed the next token. Add another hack to
the pratt-parser so that if the next token is one that cannot start an
expression and the caller allows a nullptr return then don't skip the
token and return immediately.
After this patch we can parse the above range expressions, but we
still don't handle them fully:
range.rs:4:20: fatal error: Failed to lower expr: [1..]
4 | let _rf = &block[1..];
| ^
Ranges are actually syntactic sugar for std::ops::Range[From|To].
A byte literal is an u8 created as a ascii char or hex escape
e.g. b'X'. A byte string literal is a string created from ascii or
hex chars. bytes are represented as u8 and byte strings as str (with
just ascii < 256 chars), but it should really be &'static [u8; n].
591: Remove error handling in parse_type_no_bounds for PLUS token r=philberty a=philberty
parse_type_no_bounds tries to be helpful and greedily looks for a PLUS
token after having parsed a typepath so it can produce an error. But
that error breaks parsing expressions that contain "as" Cast
Expressions like "a as usize + b as usize". Drop the explicit error on
seeing a PLUS token and just return the type path parsed.
Co-authored-by: Mark Wielaard <mark@klomp.org>
parse_type_no_bounds tries to be helpful and greedily looks for a PLUS
token after having parsed a typepath so it can produce an error. But
that error breaks parsing expressions that contain "as" Cast
Expressions like "a as usize + b as usize". Drop the explicit error on
seeing a PLUS token and just return the type path parsed.
590: Better union support in the parser r=philberty a=philberty
union is a weak keyword which means it isn't reserved and can be used
as a generic identifier. When we see an identifier where a union could
be declared we check whether the identifier is "union", but only when
the next token is also an identifier. In parse_union we shouldn't skip
the first identifier token, because it is already skipped when we call
expect_token.
Co-authored-by: Mark Wielaard <mark@klomp.org>
union is a weak keyword which means it isn't reserved and can be used
as a generic identifier. When we see an identifier where a union could
be declared we check whether the identifier is "union", but only when
the next token is also an identifier. In parse_union we shouldn't skip
the first identifier token, because it is already skipped when we call
expect_token.
587: Add testcase to cover parse errors in unsafe expressions r=philberty a=philberty
Fixes#584
589: Support dereference of pointers r=philberty a=philberty
Dereference expressions can also be pointer types not just references.
Fixes#588
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
585: Add iterate impl_blocks helper r=philberty a=philberty
This helper will allow use to use mappings to iterate
all impl blocks within the specified crate.
586: Add mappings for trait items r=philberty a=philberty
Add mappings for trait items that can be used for
query-based compilation and type checking
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
582: unsafe blocks can be used in expressions r=philberty a=philberty
This fixes an issue to allow unsafe within an expression.
Co-authored-by: Mark Wielaard <mark@klomp.org>
To use an unsafe block expression handle it in null_denotation for the
pratt parser. Adjust parse_unsafe_block_expr to take a pratt_parse
bool that defaults to false.
579: Raw pointer support r=philberty a=philberty
We will need to add the remaining coercion calls for the relevant sites
to get the full support we need but this will serve as the initial support.
Fixes#124
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
581: HIR and GENERIC lowering for unsafe blocks r=philberty a=philberty
This wires up the code nessecary to compile an unsafe block
it does not implement any rules or checks yet.
Fixes#382
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
This does not implement the rules for unsafe this wires up the code so we
can compile unsafe blocks. No checks are being performed on the code yet.
Fixes#382
This adds the initial support for raw pointers. Pointers rely on coercion
rules to be able to coerce the raw fat pointers from a borrow expression
into a normal raw pointer.
Fixes#124
577: Initial type coercion code r=philberty a=philberty
This is the initial type coercion code. Coercions are necessary to implement
mutability on reference types and for raw pointers in general.
Fixes#576#352
Addresses #434
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
This implements the reference mutability coercion rules, where the base
types must be compatible and the base can turn a mutable reference into
a constant one.
Address #434Fixes#576
Refs refers to the reference chain used in the type checking resolution of
this type. We use to eagerly replace the Inference Vars when they unify or
are coerced or default.
Fixes#352
572: Cleanup and add const modifiers to equlity interface r=philberty a=philberty
As part of an effort to cleanup some of the interfaces within the TyTy module
this PR adds a const visitor for accessing each type and updates the can_eq
interface to also be const as it should not require mutability.
These changes fell out of a branch for optional trait items support.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
When we are trying to check for possible equivalence such as a simple
generic function against a substituted one we do not and should not require
mutability. This enforces some code tidy up by providing a const visitor
pattern for types.
If we keep track of the impl blocks within the crate's we can use this
as another way to stream line looking up of specific HIR::Items. This
will be used to find possible bounds for a receiver in a path probe.
571: call accept_vis directly instead of call it after get r=philberty a=thomasyonug
call accept_vis directly instead of calling it after get().
Co-authored-by: Thomas Young <wenzhang5800@gmail.com>
568: Add missing DefId mappings r=philberty a=philberty
DefIds need to be managed for fntypes which will help in the compilation
of optional traitt functions
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
569: Some trait items are optional and should not cause an error r=philberty a=philberty
When a trait item is optional this is not a missing trait item.
570: Add missing test case to close out unit-structs r=philberty a=philberty
This test case will catch regressions in changes to initializing unit structs.
Fixes#155
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
567: warn the unused associated functions r=philberty a=thomasyonug
warn the unused associated functions
Co-authored-by: Thomas Young <wenzhang5800@gmail.com>
Some trait items can be optional such as constants with an expression or
functions with a body. This change only warns when there are non optional
items missing.
This adds DefId mappings for impl items, this is a building block where
the TyTy::FnType will include the DefId of the respective function, which
will simplify the backend a bit in relation to optional trait functions
with a body.
566: Further error checking for trait impl blocks r=philberty a=philberty
This PR introduces enhanced type checking for trait constants
and associated types. It also brings in the check to ensure all
mandatory trait items are implemented. Note optional trait items
cannot be referenced or used yet and will be done in a separate PR.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
564: Add some comments about what's kind of unused item will be warned r=philberty a=thomasyonug
Add some comments about what's kind of unused item will be warned
Co-authored-by: Thomas Young <wenzhang5800@gmail.com>
If an impl block does not implement all trait-items it is an error. This
also takes into account that functions and constants may actually have
values and may not need to be implemented by the impl block.
Addresses #542
When we are checking a trait impl block, associated types can equal any
type this ensures we update the traits associated types inline with
respective trait-impl-block that implements this trait.
Fixes#456
562: add some comments about how scan dead code pass handle PathInExpression and PathExprSegment r=philberty a=thomasyonug
Add some comments about how scan dead code pass handles PathInExpression and PathExprSegment.
Co-authored-by: Thomas Young <wenzhang5800@gmail.com>
561: Handle doc comments strings r=philberty a=philberty
This adds support for inner and outer doc comments within the parser.
Co-authored-by: Mark Wielaard <mark@klomp.org>
559: add some comments about FindEntryPoints and MarkLive in dead code sca… r=philberty a=thomasyonug
Add some comments about FindEntryPoints and MarkLive in dead code scan
Co-authored-by: Thomas Young <wenzhang5800@gmail.com>
560: Remove HIR MacroItem and other hir macro forward declarations r=philberty a=philberty
Remove trailing macro items from HIR
Fixes#69
Co-authored-by: Mark Wielaard <mark@klomp.org>
Remove (unused) comment related tokens and replace them with
INNER_DOC_COMMENT and OUTER_DOC_COMMENT tokens, which keep the comment
text as a string. These can be constructed with the new
make_inner_doc_comment and make_outer_doc_comment methods.
Make sure to not confuse doc strings with normal comments in the lexer
when detecting shebang lines. Both single line //! and /*! */ blocks
are turned into INNER_DOC_COMMENT tokens. And both single line /// and
/** */ blocks are turned into OUTER_DOC_COMMENT tokens.
Also fixes some issues with cr/lf line endings and keeping the line
map correct when seeing \n in a comment.
In the parser handle INNER_DOC_COMMENT and OUTER_DOC_COMMENTS where
inner (#[]) and outer (#![]) attributes are handled. Add a method
parse_doc_comment which turns the tokens into an "doc" Attribute with
the string as literal expression.
Add get_locus method to Attribute class for better error reporting.
Tests are added for correctly placed and formatted doc strings, with
or without cr/lf line endings. Incorrect formatted (isolated CRs) doc
strings and badly placed inner doc strings. No tests add handling of
the actual doc attributes yet. These could be tested once we add
support for the #![warn(missing_docs)] attribute.
551: Initial AssociatedType support r=philberty a=philberty
Traits can define Type aliasses which must enforce the correct resolution
onto their respective TraitImplBlocks. This PR adds all the necessary building
blocks for the initial support.
More work is needed in checking for trait-impl-item consistency with its respective
Trait item types.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
558: Call MarkLive inside ScanDeadcode, then the pass entrance will be single in session::parse_file r=philberty a=thomasyonug
Call MarkLive inside ScanDeadcode, then the pass entrance will be single in session::parse_file
Co-authored-by: Thomas Young <wenzhang5800@gmail.com>
This is the initial support for associated types, by creating placeholder
types for each trait type alias.
When it comes to checking for compatibility we are missing the piece to
ensure that the type is defintly the same as the associated type.
Addresses #471#456
With the desuagaring of AST::TraitImpl and AST::InherentImpl into a generic
HIR::ImplBlock we must ensure the existing passes can support TypeAliases
accordingly.
With the type system we can check for equality explicitly which is useful.
When it comes to TypeParameters or Placeholders can_eq allows for:
fn bla<T>() -> <T>
fn bla() -> i32
The type parameter can be subsituted which means the generic function can
equal the subsituted one if it was given the right substituion arguments.
This can emit errors such as expected [X] got [Y] or we might want to
have silent errors so we can filter impl items such as the impl item
overlapping pass
This is used in Traits with associated types that can contain TypeBounds
but provides an ability to reuse out type system to check that trait items
are compatible with their respective ImplBlock Items
When we translate AST::InherentImplItems or AST::TraitImplItem's these get
lowered into a generic ImplBlock with ImplItems these must be non null.
TraitImpl blocks can contains associated types but normal InherentImpl's
do not this unifies the path to turn both into an HIR::ImplBlock
555: use rust_assert in dead code pass instead of rust_error_at r=dkm a=thomasyonug
use rust_assert in dead code pass instead of rust_error_at
Fixed#550
Co-authored-by: Thomas Young <wenzhang5800@gmail.com>
548: Fix bad naming of primitive types such as u64 which ended up as usize r=philberty a=philberty
In #547 it was found that u64's ended up as usize in gimple which confuses
debugging sessions. This take the original implementation of named type
from gccgo showing it was the TYPE_NAME tree getting confused.
Addresses #547
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
554: make the warning msg be searched easier r=philberty a=thomasyonug
make the warning msg be searched easier.
Fixed#545
Co-authored-by: Thomas Young <wenzhang5800@gmail.com>
552: UTF-8 BOM handling r=dkm a=dkm
Mark Wielaard (https://gcc.gnu.org/pipermail/gcc-rust/2021-July/000072.html ) :
> A rust source file can start with a UTF-8 BOM sequence (EF BB
> BF). This simply indicates that the file is encoded as UTF-8 (all rust
> input is interpreted as asequence of Unicode code points encoded in
> UTF-8) so can be skipped before starting real lexing.
>
> It isn't necessary to keep track of the BOM in the AST or HIR Crate
> classes. So I removed the has_utf8bom flag.
>
> Also included are a couple of simple tests to show we handle the BOM
> correctly now.
Co-authored-by: Mark Wielaard <mark@klomp.org>
The lexer deals with the UTF-8 BOM and the parser cannot detect
whether there is or isn't a BOM at the start of a file. The flag isn't
relevant or useful in the AST and HIR Crate classes.
The very first thing in a rust source file might be the optional UTF-8
BOM. This is the 3 bytes 0xEF 0xBB 0xBF. They can simply be skipped,
they just mark the file as UTF-8. Add some testcases to show we now
handle such files.
546: shebang handling r=philberty a=dkm
Mark Wielaard:
> Shebang handling, the first line starting with #! was not done fully
> correct and it isn't necessary to keep track of the shebang line in
> the AST or HIR Crate classes.
>
> Because an inner attribute also starts with #! the first line isn't
> regarded as a shebang line if the #! is followed by (optional)
> whitespace and comments and a [. In that case the #! is seen as the
> start of an inner attribute.
>
> I added various testcases that hopefully show the funny things you can
> get when the first line starts with #!.
Co-authored-by: Mark Wielaard <mark@klomp.org>
544: mark live symbol support type alias and tuple struct r=philberty a=thomasyonug
mark live symbol support type alias and tuple struct
Co-authored-by: Thomas Young <wenzhang5800@gmail.com>
There was a bad port over of the gccgo named_type implementation to try
be simple but this ended up overwriting the names of other primitive types
leading to confusing gimple debug sessions.
In debugging this I have added a set of ids which are the builtin primitive
types ids and we assert that this range of ids will never be overriten by
other types during compilation.
The lexer deals with the shebang and the parser cannot detect whether
there is or isn't a shebang line. The flag isn't relevant or useful in
the AST and HIR Crate classes.
The lexer tried to handle the shebang line but used loc directly,
instead of the current_column. And it assumed a '/' should immediately
follow the "#!". But if the "#!" is followed by whitespace and/or
comments and a '[' character, then the first line isn't see as a
shebang line (even if the kernel or shell would) but as the start of
an inner attribute.
Add various tests for when the first line starting with "#!" is seen
as a shebang line (and should be skipped). And some tests there is a
'[' character following some whitespace and/or comments and the "#!"
is seen as part of an inner attribute.
543: mark live symbol in if expr family except if let expr r=philberty a=thomasyonug
mark live symbol in if expr family except if let expr
Co-authored-by: Thomas Young <wenzhang5800@gmail.com>
534: Unused struct fields r=philberty a=thomasyonug
1. make struct field carry the location info. Fixed#533
2. detect unused struct field.
Co-authored-by: Thomas Young <wenzhang5800@gmail.com>
540: Add trait-impl support for methods r=philberty a=philberty
This PR strips HIR::Method and reuses the HIR::Function with a HIR::SelfParam.
It reduces complexity in type checking and GENERIC generation.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
Self is actually an implicit inherited type parameter on Trait
declarations. This adds this akin to impl blocks, and substitutes the
actual impl self type into the trait-impl item for type checking.
Fixes#473
538: exit immediately when the type checker find an error r=philberty a=thomasyonug
exit immediately when the type checker find an error
Co-authored-by: Thomas Young <wenzhang5800@gmail.com>
536: Revert change to ScanUnused to not scan Types r=philberty a=philberty
The scan dead-code pass will take over this role, but let's keep both
running for a while and then we can update ScanUnused to only scan for
unused labels and variables. Dead Code pass is important as it is not possible
to rely on name resolution to know what symbols are used or not used.
Further resolution occurs during type resolution and the dead code pass runs after type resolution.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
The scan dead-code pass will take over this role, but lets keep both
running for a while and then we can update ScanUnused to only scan for
unused labels and variables. Its not possible to rely on name resolution
to know what symbols are used or not used. Further resolution occurs during
type resolution and the dead code pass runs after type resolution.
535: Suppress warning in rust-ast-lower-type.h ASTLowerGenericParam.visit. r=philberty a=dkm
Translating the AST LifetimeType to the HIR LifetimeType causes a warning:
warning: ‘ltt’ may be used uninitialized
Add a default clause to the switch statement calling gcc_unreachable.
This will suppress the warning and make sure that if the AST lifetime type
is invalid or a new unknown type we immediately know when lowering the AST.
Co-authored-by: Mark Wielaard <mark@klomp.org>
532: Marking live symbol for struct construction. r=philberty a=thomasyonug
Marking live symbol for struct construction.
Co-authored-by: Thomas Young <wenzhang5800@gmail.com>
Translating the AST LifetimeType to the HIR LifetimeType causes a warning:
warning: ‘ltt’ may be used uninitialized
Add a default clause to the switch statement calling gcc_unreachable.
This will suppress the warning and make sure that if the AST lifetime type
is invalid or a new unknown type we immediately know when lowering the AST.
530: Fix inner attribute parsing r=philberty a=dkm
parse_inner_attribute tried to skip the right square token twice. This caused odd error
messages in case there were multiple inner attributes. This bug masked another bug in
parse_attr_input where when the (optional) attr input was an assignment to a literal
the parser failed to skip the literal.
The existing top_attr.rs testcase relied on the two bugs cancelling each other out.
Add a new testcase inner_attributes.rs for the first bug.
Resolves: https://github.com/Rust-GCC/gccrs/issues/510
Co-authored-by: Mark Wielaard <mark@klomp.org>
502: Trait Obligations building block r=philberty a=philberty
This is a building block for actually enforcing the obligations of a trait.
It includes a query-based lookup of the trait to avoid reloading it so
we only do the hard work once. Then provides the enforcement for
basic functions. Constants, methods and associated types are still
WIP.
Addresses: #440
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
When we create an impl for a trait each item must be part of the trait,
these are the obligations of the trait. This means we know this type
definetly implements the trait.
This only supports functions so far. Methods, constants and associated
types are still in progress. This is an isolated building block that can
be merged without any regression so far.
Addresses #440
parse_inner_attribute tried to skip the right square token twice. This caused odd error
messages in case there were multiple inner attributes. This bug masked another bug in
parse_attr_input where when the (optional) attr input was an assignment to a literal
the parser failed to skip the literal.
The existing top_attr.rs testcase relied on the two bugs cancelling each other out.
Add a new testcase inner_attributes.rs for the first bug.
Resolves: https://github.com/Rust-GCC/gccrs/issues/510
529: Marking live symbol in break, return, while, whilelet, for expr r=philberty a=thomasyonug
Marking live symbol in break, return, while, whilelet, for expr without test case for last two due to unimplemented.
Co-authored-by: Thomas Young <wenzhang5800@gmail.com>
527: Reject non-pure decimal tuple indexes. r=philberty a=dkm
Tuple indexes should be pure decimal integer literals. But the parser just sees an
integer literal. Fix this by introducing a new type hint CORETYPE_PURE_DECIMAL. This
doesn't conflict with any existing type hints since a pure decimal doesn't have a
type suffix.
Introduce a new method is_pure_decimal that the parser can use in parse_tuple_index_expr.
get_type_hint will return CORETYPE_UNKNOWN for pure decimals.
parse_decimal_int_or_float will check whether there are no execissive leading zeros.
parse_in_decimal checks the literal doesn't contain any underscores.
Add two testcases. bad_tuple_index.rs with all variants of integer literals which aren't
pure decimals. And tuple_index.rs with various correct tuple indexes.
Resolves: https://github.com/Rust-GCC/gccrs/issues/511
Co-authored-by: Mark Wielaard <mark@klomp.org>
528: Marking live symbols in tuple expr, array expr, grouped expr, type cast expr, lazy boolean expr. r=philberty a=thomasyonug
Marking live symbols in tuple expr, array expr, grouped expr, type cast expr, lazy boolean expr.
Co-authored-by: Thomas Young <wenzhang5800@gmail.com>
Tuple indexes should be pure decimal integer literals. But the parser just sees an
integer literal. Fix this by introducing a new type hint CORETYPE_PURE_DECIMAL. This
doesn't conflict with any existing type hints since a pure decimal doesn't have a
type suffix.
Introduce a new method is_pure_decimal that the parser can use in parse_tuple_index_expr.
get_type_hint will return CORETYPE_UNKNOWN for pure decimals.
parse_decimal_int_or_float will check whether there are no execissive leading zeros.
parse_in_decimal checks the literal doesn't contain any underscores.
Add two testcases. bad_tuple_index.rs with all variants of integer literals which aren't
pure decimals. And tuple_index.rs with various correct tuple indexes.
Resolves: https://github.com/Rust-GCC/gccrs/issues/511
526: Add unit-type support for Identifier expressions r=philberty a=philberty
Unit type can be reference via an identifier expression. Other type references via an identifier expression are not supported yet.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
Rust supports unit struct initilization such as S{} this takes this tree
and resolves it fully. This should really be all desugared via HIR but that
is in progress in another PR.
525: Support BorrowExpr, DereferenceExpr, NegationExpr in marking live symbols and corresponding test cases. r=philberty a=thomasyonug
Support BorrowExpr, DereferenceExpr, NegationExpr in marking live symbols and corresponding test cases.
Co-authored-by: Thomas Young <wenzhang5800@gmail.com>
524: Change unit-type from void_type_node to a zero sized unsigned integer r=philberty a=philberty
Functions with return type of unit are still using void_type_node as there is an ICE in GCC:
```
test.rs: In function ‘main’:
test.rs:16:1: internal compiler error: in min_value, at wide-int.cc:346
16 | fn main() {
| ^
0x1d551d5 wi::min_value(unsigned int, signop)
../../gccrs/gcc/wide-int.cc:346
0x1146ca5 irange::set_varying(tree_node*)
../../gccrs/gcc/value-range.h:476
0x1ce5970 value_range_equiv::set_varying(tree_node*)
../../gccrs/gcc/value-range-equiv.cc:71
0x1d3da07 vr_values::set_def_to_varying(tree_node const*)
../../gccrs/gcc/vr-values.c:230
0x1d3da70 vr_values::set_defs_to_varying(gimple*)
../../gccrs/gcc/vr-values.c:241
0x1c78b2f vrp_prop::visit_stmt(gimple*, edge_def**, tree_node**)
../../gccrs/gcc/tree-vrp.c:4001
0x1ad8519 ssa_propagation_engine::simulate_stmt(gimple*)
../../gccrs/gcc/tree-ssa-propagate.c:230
0x1ad8a0e ssa_propagation_engine::simulate_block(basic_block_def*)
../../gccrs/gcc/tree-ssa-propagate.c:337
0x1ad9f2e ssa_propagation_engine::ssa_propagate()
../../gccrs/gcc/tree-ssa-propagate.c:800
0x1c7a0b0 execute_vrp
../../gccrs/gcc/tree-vrp.c:4512
0x1c7a3e4 execute
../../gccrs/gcc/tree-vrp.c:4620
Please submit a full bug report,
```
Addresses #155
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
GCC does not support unit-type when it is represented as void, unsigned
integer of precision zero seems to work. The missing piece here is that
functions with return type of unit are still represented by a void type
node there is an ICE in
```
0x1d551d5 wi::min_value(unsigned int,signop)
../../gccrs/gcc/wide-int.cc:346
```
Addresses #155
523: Add support for nested functions r=philberty a=philberty
This is a missed pieces of functionality for statements in rust.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
We missed that stmts in rust can be items like functions. This adds support
for resolution and compilation of nested functions. Rust allows nested
functions which are distinct to closures. Nested functions are not allowed
to encapsulate the enclosing scope so they can be extracted as normal functions.
522: Handle empty/unit tuple enum variants in the parser. r=philberty a=philberty
A tuple enum variant can be empty, in which case it is a unit enum variant.
Handle this in Parser<ManagedTokenSource>::parse_enum_item by creating
a empty tuple_field vector instead of calling parse_tuple_fields.
Add a testcase to show empty tuple enum variant types are now accepted.
But note some part of the test is commented out because using the enum
type isn't actually possible right now.
Addresses #79
Co-authored-by: Mark Wielaard <mark@klomp.org>
A tuple enum variant can be empty, in which case it is a unit enum variant.
Handle this in Parser<ManagedTokenSource>::parse_enum_item by creating
a empty tuple_field vector instead of calling parse_tuple_fields.
Add a testcase to show empty tuple enum variant types are now accepted.
But note some part of the test is commented out because using the enum
type isn't actually possible right now.
521: Handle empty/unit tuple structs in the parser. r=philberty a=philberty
A tuple struct can be empty, in which case it is a unit tuple struct.
Handle this in Parser<ManagedTokenSource>::parse_struct by creating
a empty tuple_field vector instead of calling parse_tuple_fields.
Add a testcase to show empty tuple structs are now accepted.
Addresses: #385
Co-authored-by: Mark Wielaard <mark@klomp.org>
A tuple struct can be empty, in which case it is a unit tuple struct.
Handle this in Parser<ManagedTokenSource>::parse_struct by creating
a empty tuple_field vector instead of calling parse_tuple_fields.
Add a testcase to show empty tuple structs are now accepted.
Addresses: #385
520: Add support for struct definitions to be within a block r=philberty a=philberty
We still have bugs handling unit-structs but this allows for Tuple Structs
and normal named field structs to be declared within a block and referenced
lexically. This allows rust statements to follow the correct grammar.
Fixes#519
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
We still have bugs handling unit-structs but this allows for Tuple Structs
and normal named field structs to be declared within a block and referenced
lexically. This allows rust statements to follow the correct grammar.
Fixes#519
518: Token strings r=philberty a=tromey
This series implements a couple of small changes to improve the handling
of strings attached to Token.
Co-authored-by: Tom Tromey <tom@tromey.com>
517: Fix RAIIFile buglet r=philberty a=tromey
RAIIFile's implementation of operator= can leak a file, because it
doesn't handle the case where the assignee holds an open file handle.
Co-authored-by: Tom Tromey <tom@tromey.com>
Token currently uses a "std::string *". There's a comment proposing
that perhaps this should be changed; but meanwhile, it's slightly
cleaner to use unique_ptr rather than have Token manage the string's
lifetime manually.
514: Rename tuple field names r=philberty a=tromey
Tuples currently use plain integer field names in the DWARF. However,
rustc prefixes these with "__", and GDB understands this convention.
This patch changes gccrs to match, and adds an explanatory comment.
Co-authored-by: Tom Tromey <tom@tromey.com>
512: Fix various Wformat-diag diagnostics r=philberty a=dkm
Fix warnings mainly coming from ` being used instead of %< and %>.
Also fixing occurences of :
```
../../gcc/rust/lex/rust-token.cc:126:40: warning: unquoted sequence of 2 consecutive punctuation characters ‘',’ in format [-Wformat-diag]
126 | "attempted to get string for '%s', which has no string. "
| ^~
../../gcc/rust/lex/rust-token.cc:127:39: warning: spurious trailing punctuation sequence ‘.’ in format [-Wformat-diag]
127 | "returning empty string instead.",
| ^
../../gcc/rust/lex/rust-token.cc:126:37: warning: unterminated quote character ‘'’ in format [-Wformat-diag]
126 | "attempted to get string for '%s', which has no string. "
| ^
```
and various occurences of :
```
../../gcc/rust/lex/rust-lex.cc:1326:11: warning: unquoted keyword ‘char’ in format [-Wformat-diag]
1326 | "byte char %<%c%> out of range", byte_char);
| ^~~~
```
Also using full word for arguments, integer, character, declaration, variable,
floting-point instead of args, int, char, decl, var, float when applicable.
Co-authored-by: Marc Poulhiès <dkm@kataplop.net>
Tuples currently use plain integer field names in the DWARF. However,
rustc prefixes these with "__", and GDB understands this convention.
This patch changes gccrs to match, and adds an explanatory comment.
Fix warnings mainly coming from ` being used instead of %< and %>.
Also fixing occurences of :
../../gcc/rust/lex/rust-token.cc:126:40: warning: unquoted sequence of 2 consecutive punctuation characters ‘',’ in format [-Wformat-diag]
126 | "attempted to get string for '%s', which has no string. "
| ^~
../../gcc/rust/lex/rust-token.cc:127:39: warning: spurious trailing punctuation sequence ‘.’ in format [-Wformat-diag]
127 | "returning empty string instead.",
| ^
../../gcc/rust/lex/rust-token.cc:126:37: warning: unterminated quote character ‘'’ in format [-Wformat-diag]
126 | "attempted to get string for '%s', which has no string. "
| ^
and various occurences of :
../../gcc/rust/lex/rust-lex.cc:1326:11: warning: unquoted keyword ‘char’ in format [-Wformat-diag]
1326 | "byte char %<%c%> out of range", byte_char);
| ^~~~
Also using full word for arguments, integer, character, declaration, variable,
floting-point instead of args, int, char, decl, var, float when applicable.
513: Fix up test suite buglets r=philberty a=tromey
Mark Wielaard pointed out that the i8u8.rs test that I recently
introduced has a bug: it checks the DW_AT_language attribute, not
DW_AT_encoding.
Sorry about this.
This patch fixes this problem. I've verified that this notices the
failure after temporarily backing out the corresponding GCC change.
This patch also fixes another problem that he found, namely that it's
possible for these tests to find the wrong answer, because the hex
value that is checked for might be a prefix of some longer value.
This patch also adds a whitespace check to avoid this potential
problem.
Co-authored-by: Tom Tromey <tom@tromey.com>
Mark Wielaard pointed out that the i8u8.rs test that I recently
introduced has a bug: it checks the DW_AT_language attribute, not
DW_AT_encoding.
Sorry about this.
This patch fixes this problem. I've verified that this notices the
failure after temporarily backing out the corresponding GCC change.
This patch also fixes another problem that he found, namely that it's
possible for these tests to find the wrong answer, because the hex
value that is checked for might be a prefix of some longer value.
This patch also adds a whitespace check to avoid this potential
problem.
506: Fix: do not use object after it has been moved r=philberty a=dkm
After std::move(mapping), mapping is unspecified
<!-- THIS COMMENT IS INVISIBLE IN THE FINAL PR, BUT FEEL FREE TO REMOVE IT
Thank you for making Rust GCC better!
If your PR fixes an issue, you can add "Fixes #issue_number" into this
PR description and the git commit message. This way the issue will be
automatically closed when your PR is merged. If your change addresses
an issue but does not fully fix it please mark it as "Addresses #issue_number"
in the git commit message.
Here is a checklist to help you with your PR.
- \[ ] GCC code require copyright assignment: https://gcc.gnu.org/contribute.html
- \[ ] Read contributing guidlines
- \[ ] `make check-rust` passes locally
- \[ ] Run `clang-format`
- \[ ] Added any relevant test cases to `gcc/testsuite/rust/`
Note that you can skip the above if you are just opening a WIP PR in
order to get feedback.
---
-->
507: Add more info in HIR dump for struct r=philberty a=dkm
Make struct fields more visible in dumps and add the mapping in the dump string.
<!-- THIS COMMENT IS INVISIBLE IN THE FINAL PR, BUT FEEL FREE TO REMOVE IT
Thank you for making Rust GCC better!
If your PR fixes an issue, you can add "Fixes #issue_number" into this
PR description and the git commit message. This way the issue will be
automatically closed when your PR is merged. If your change addresses
an issue but does not fully fix it please mark it as "Addresses #issue_number"
in the git commit message.
Here is a checklist to help you with your PR.
- \[ ] GCC code require copyright assignment: https://gcc.gnu.org/contribute.html
- \[ ] Read contributing guidlines
- \[ ] `make check-rust` passes locally
- \[ ] Run `clang-format`
- \[ ] Added any relevant test cases to `gcc/testsuite/rust/`
Note that you can skip the above if you are just opening a WIP PR in
order to get feedback.
---
-->
508: Make 3 error messages slightly more informational r=philberty a=dkm
Add more context to some internal error messages (ie. not intended for user)
<!-- THIS COMMENT IS INVISIBLE IN THE FINAL PR, BUT FEEL FREE TO REMOVE IT
Thank you for making Rust GCC better!
If your PR fixes an issue, you can add "Fixes #issue_number" into this
PR description and the git commit message. This way the issue will be
automatically closed when your PR is merged. If your change addresses
an issue but does not fully fix it please mark it as "Addresses #issue_number"
in the git commit message.
Here is a checklist to help you with your PR.
- \[ ] GCC code require copyright assignment: https://gcc.gnu.org/contribute.html
- \[ ] Read contributing guidlines
- \[ ] `make check-rust` passes locally
- \[ ] Run `clang-format`
- \[ ] Added any relevant test cases to `gcc/testsuite/rust/`
Note that you can skip the above if you are just opening a WIP PR in
order to get feedback.
---
-->
Co-authored-by: Marc Poulhiès <dkm@kataplop.net>
505: DWARF for Rust primitive types r=philberty a=tromey
I found a couple of small bugs in the DWARF that is emitted for primitive types.
These two patches fix these.
Co-authored-by: Tom Tromey <tom@tromey.com>
Currently, the i8 and u8 types use the DWARF character encoding, like:
<1><113>: Abbrev Number: 3 (DW_TAG_base_type)
<114> DW_AT_byte_size : 1
<115> DW_AT_encoding : 8 (unsigned char)
<116> DW_AT_name : u8
This happens because gccrs uses signed_char_type_node and
unsigned_char_type_node for i8 and u8, respectively.
This patch fixes this problem by arranging to use a custom integer
type instead. Another option is to clear TYPE_STRING_FLAG on these
types, but it was unclear to me whether this would impact other parts
of GCC.
503: Use DW_LANG_Rust in DWARF r=philberty a=tromey
This changes the GCC DWARF emitterto use DW_LANG_Rust or
DW_LANG_Rust_old as appropriate.
Co-authored-by: Tom Tromey <tom@tromey.com>
501: Update README.md for building steps on MacOS. r=philberty a=thomasyonug
The path of header dir and sysroot should be specified when you configure the project.
Fixed#500
Co-authored-by: Thomas Young <wenzhang5800@gmail.com>
499: Cleanup warnings r=philberty a=philberty
This adds the missing override specifier to as_string on identifier
patterns and ensures rust_debug gains printf specifier checks.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
498: Remove HIR::TraitItemMethod, this can be represented by TraitItemFunction r=philberty a=philberty
Canonicalizing the paths of the compiler to treat functions and methods
the same way will ensure we avoid duplication.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
497: Avoid abort macro override the abort of std r=philberty a=thomasyonug
Fixing the build issue in macos by avoiding abort macro override the abort call of std.
Co-authored-by: Thomas Young <wenzhang5800@gmail.com>
496: TraitImpl blocks have a different CanonicalPath to normal impl blocks r=philberty a=philberty
TraitImpls have a canonical path which is a trait projection such as
```rust
pub trait Trait { // ::a::Trait
fn f(&self); // ::a::Trait::f
}
impl Trait for Struct {
fn f(&self) {} // <::a::Struct as ::a::Trait>::f
}
```
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
495: HIR cleanup r=philberty a=philberty
The HIR implementation has been bootstrapped from the AST, this has lead to a lot of missed desugaring. This PR removes TraitImpls and refactors the InerhentImpls to be an ImplBlock. The class hierarchy has been simplified in tandem here such that all impl items are of the same base class.
More cleanup is required but this is an isolated change that can go in now.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
TraitImpls have a canonical path which is a trait projection such as
```rust
pub trait Trait { // ::a::Trait
fn f(&self); // ::a::Trait::f
}
impl Trait for Struct {
fn f(&self) {} // <::a::Struct as ::a::Trait>::f
}
```
This folds the abstract Impl class directly into HIR::ImplBlock since the
TraitImplBlock is removed. It also refactors InherentImplItem to become
simply ImplItem.
HIR should desugar the AST as best it can. Trait impl blocks are just impl
blocks. The HIR impl block can just have an optional<TraitRef> in order to
represent a trait impl block.
494: replace analysis dir with lint dir and rename liveness to marklive r=philberty a=thomasyonug
replace analysis dir with lint dir and rename liveness to marklive
Co-authored-by: Thomas Young <wenzhang5800@gmail.com>
492: HIR should not contain any macros r=philberty a=philberty
This removes the macros tree's from HIR. HIR should be an expanded and
simplifed representation of the compilation unit.
Fixes#70
493: Path resolution fixes r=philberty a=philberty
In order to support Modules, we need to do path resolution properly. The old code assumed a basic A::B but this is not generic enough in order to support modules.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
In order to support modules the path expression will fail here since a
module is not a value and does not have a TyTy type, so this is ok to
continue the rest of resolution so long as there are more segments.
Addresses: #432
There are cases where the name resolver can fully resolve a path such as:
```rust
struct Foo(i32);
impl Foo{
fn new() { ... }
}
fn main() {
let a;
a = Foo::new();
}
```
This case does not require a PathProbe. This enhances the Path resolution
to iterate each segment untill we are unable to resolve the root segment
at that point we can fall back to a PathProbe and lookup any impl item that
might satisfy the path instead.
Addresses #432
Name resolution tried to greedily resolve the entire CanonicalPath in one
lookup which was ok for simple paths like A::B. This changes the name
resolver to resolve each segment which allows the type resolution to
determine the root path to be up until the segment is unresolved which
will then require a PathProbe or its a failure. This will be required to
support modules which extend the resolution to be much more generic than
is assumed here.
Addresses: #432
484: Trait impls and initial start of traits work r=philberty a=philberty
This does not start enforcing anything to do with traits. in order to
implement the traits milestone we need to be able to implement a
trait first.
This makes the Trait impls follow a normal impl block. As the starting
point.
Fixes#395#472
485: All toplevel items must respect the prefix for their path r=philberty a=philberty
The commit message has a more detailed explanation as to why.
But some toplevel items were not respecting their prefix which is
important for module support.
486: Use PRIx64 to print 64bit hex values in legacy_hash r=philberty a=philberty
* gcc/rust/backend/rust-compile.cc (legacy_hash): lo and hi are uint64_t use
PRIx64 to print them as hex values instead of %lx which is target specific.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
Co-authored-by: Mark Wielaard <mark@klomp.org>
* gcc/rust/backend/rust-compile.cc (legacy_hash): lo and hi are uint64_t use
PRIx64 to print them as hex values instead of %lx which is target specific.
455: Update CONTRIBUTING.md r=philberty a=philberty
We have been accepting patches via mail from developers following the normal GCC processes. Let's update our guidelines to reflect this.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
We have been accepting patches via mail from developers following the normal GCC processes. Let's update our guidelines to reflect this.
Co-authored-by: CohenArthur <arthur.cohen@epita.fr>
Co-authored-by: Thomas Schwinge <thomas@codesourcery.com>
Co-authored-by: Miguel Ojeda <ojeda@users.noreply.github.com>
Name resolution is split into two parts, one for the toplevel canonical
paths and then a second to actually drill down into new scopes for blocks
for example.
Consider a rust program:
```rust
fn foo() -> bar { ... }
struct bar(..);
```
In that example the function foo references bar which is declared later on.
The compiler is partly query based in that we use ids to get away from
looking up things via strings as quickly as possible.
The toplevel scan follows the rust documentation over on:
This assigns canonical names for all toplevel items but ignore the details
like return types, or body.
So the name resolver ends up with:
::foo
::bar
Then we can drill down into foo and check the return type and see that
::bar is already defined.
The prefix is important for the case of modules for example. This should
be a toplevel scan within the same scope.
Addresses: #432
We can compile TraitImpls, since before we can actually start checking
trait obligations we need to be able to implement the trait first.
More desugaring is needed in HIR to make TraitImpls contain normal impl
items to avoid seperation in how impl blocks are handled.
Fixes#395#472
This will change to desugar trait-impls to be just like a normal impl block
later on. This will simplify things for method resolution. This is the
initial building block so we can move forward and refactor as the
trait resolution evolves.
Addresses #395#472
We need to add name resolution for traits and trait impls. We cannot start
working with trait obligations untill we can actually implment a basic trait first.
Addresses: #395
NodeMappings are used to map HIR items into the type system and back to
NodeIds as part of name Resolution. LocalDefId signify local crate
defintions and DefId are cratenum + localdefids for cross crate
definitions.
Addresses: #395
482: arm: Override TARGET_RUST_OS_INFO in bpabi.h r=tschwinge a=glaubitz
Similar to PowerPC, 32-bit ARM has the issue that TARGET_RUST_OS_INFO
is defined in two separate headers, namely config/arm/bpabi.h and
config/arm/linux-elf.h. We can apply the same fix that was already
used for PowerPC.
gcc/ChangeLog:
2021-06-04 John Paul Adrian Glaubitz <glaubitz@physik.fu-berlin.de>
* config/arm/bpabi.h: Undefine TARGET_RUST_OS_INFO before
defining it.
Co-authored-by: John Paul Adrian Glaubitz <glaubitz@physik.fu-berlin.de>
Similar to PowerPC, 32-bit ARM has the issue that TARGET_RUST_OS_INFO
is defined in two separate headers, namely config/arm/bpabi.h and
config/arm/linux-elf.h. We can apply the same fix that was already
used for PowerPC.
gcc/ChangeLog:
2021-06-04 John Paul Adrian Glaubitz <glaubitz@physik.fu-berlin.de>
* config/arm/bpabi.h: Undefine TARGET_RUST_OS_INFO before
defining it.
480: Use '-frust-debug' to control dumping of various Rust front end internals r=philberty a=tschwinge
... as discussed in #479, and elsewhere.
Co-authored-by: Thomas Schwinge <thomas@codesourcery.com>
479: Remove diagnostics pruning from 'rust_target_compile' [#301, #466] r=dkm a=tschwinge
This is no longer necessary after #466 "Expose rust debug and use it", where
commit 665df329a2 "rust_debug: Replace fprintf
(stderr) with rust_debug" turned all 'fprintf' to 'stderr' into standard GCC
'inform' ('note: [...]') diagnostics -- which do get pruned by default.
Adjust the testsuite: instead of 'dg-excess-errors', spell out the additional
diagnostics now seen.
Co-authored-by: Thomas Schwinge <thomas@codesourcery.com>
This is no longer necessary after #466 "Expose rust debug and use it", where
commit 665df329a2 "rust_debug: Replace fprintf
(stderr) with rust_debug" turned all 'fprintf' to 'stderr' into standard GCC
'inform' ('note: [...]') diagnostics -- which do get pruned by default.
Adjust the testsuite: instead of 'dg-excess-errors', spell out the additional
diagnostics now seen.
466: Expose rust debug and use it r=tschwinge a=CohenArthur
Fixes#464
@philberty I've checked and rust_debug does output on stderr correctly :)
This PR exposes the rust_debug prototype and replaces debug printfs (`fprintf (stderr, ...)`) with calls to rust_debug. This also removes the extra newlines that were added at the end of the fprintf format strings, since calling rust_debug already adds one. Without this, the tests fail due to blank lines in the output.
I have used a template to overload the rust_debug function and pass variadic arguments to the complete version. While the code looks cleaner than using `va_args`, it's also heavier C++. I'm open to changing it and definitely not attached to this implementation.
Most of the PR was made using sed and then clang-format
Co-authored-by: CohenArthur <arthur.cohen@epita.fr>
478: mips: Fix incorrect name for target feature flag TARGET_ODD_SPREG r=tschwinge a=glaubitz
Fixes#476
Co-authored-by: John Paul Adrian Glaubitz <glaubitz@physik.fu-berlin.de>
475: rs6000: Override TARGET_RUST_OS_INFO in linux.h r=tschwinge a=glaubitz
Like 64-bit PowerPC, 32-bit PowerPC has the issue that
TARGET_RUST_OS_INFO is defined in both config/rs6000/sysv4.h
and config/rs6000/linux.h which triggers an error directive.
Thus, apply the same fix which undefines TARGET_RUST_OS_INFO
in linux.h first before redefining it, eliminating the error
directive.
gcc/ChangeLog:
2021-06-02 John Paul Adrian Glaubitz <glaubitz@physik.fu-berlin.de>
* config/rs6000/linux.h: Undefine TARGET_RUST_OS_INFO before
defining it.
Fixes#468
Co-authored-by: John Paul Adrian Glaubitz <glaubitz@physik.fu-berlin.de>
Like 64-bit PowerPC, 32-bit PowerPC has the issue that
TARGET_RUST_OS_INFO is defined in both config/rs6000/sysv4.h
and config/rs6000/linux.h which triggers an error directive.
Thus, apply the same fix which undefines TARGET_RUST_OS_INFO
in linux.h first before redefining it, eliminating the error
directive.
gcc/ChangeLog:
2021-06-02 John Paul Adrian Glaubitz <glaubitz@physik.fu-berlin.de>
* config/rs6000/linux.h: Undefine TARGET_RUST_OS_INFO before
defining it.
Fixes#468
469: lowering attribute by copying attribute from AST to HIR directly r=philberty a=thomasyonug
lowering attribute by copying attribute from AST to HIR directly.
Addresses #459
Co-authored-by: Thomas Young <wenzhang5800@gmail.com>
465: Re-organize GCC/Rust testsuites r=dkm a=tschwinge
... as discussed in
<https://gcc-rust.zulipchat.com/#narrow/stream/266897-general/topic/Testsuite.20results>:
> [...] best practice from what other GCC testsuites are doing), which I hope
> makes clearer the difference between the individual GCC/Rust testsuites:
> 'rust.test/compile' -> 'rust/compile/torture'
> 'rust.test/execute' -> 'rust/execute/torture'
> 'rust.test/unsupported' -> 'rust/compile/xfail'
> 'rust.test/xfail_compile' -> 'rust/compile'
... plus corresponding documentation updates in the '*.exp' files and
elsewhere.
Co-authored-by: Thomas Schwinge <thomas@codesourcery.com>
... as discussed in
<https://gcc-rust.zulipchat.com/#narrow/stream/266897-general/topic/Testsuite.20results>:
> [...] best practice from what other GCC testsuites are doing), which I hope
> makes clearer the difference between the individual GCC/Rust testsuites:
> 'rust.test/compile' -> 'rust/compile/torture'
> 'rust.test/execute' -> 'rust/execute/torture'
> 'rust.test/unsupported' -> 'rust/compile/xfail'
> 'rust.test/xfail_compile' -> 'rust/compile'
... plus corresponding documentation updates in the '*.exp' files and
elsewhere.
462: Update README.md with GCC mailing list r=philberty a=philberty
GCC Rust now has an associated mailing list and irc channel on the usual GCC locations.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
463: Always print compiler debug info on stderr r=philberty a=CohenArthur
I am starting my work on cargo-gccrs, and the output from the compiler messes with what cargo expects as output. Since much of the debug prints are already done on `stderr` instead of `stdout`, this PR fixes what I believe to be the few remaining cases using `stdout`.
I used the following regexes (with ripgrep) to find all remaining instances of debug prints on `stdout`: `[^f]printf` and `fprintf \(stdout`
Co-authored-by: CohenArthur <arthur.cohen@epita.fr>
460: raiifile: Allow dash-prefixed files to be parsed r=tschwinge a=CohenArthur
Thanks to @tschwinge for finding the bug.
I added a test case, but not a lot of programs know how to handle this file. Unless there is some specific option, `gcc` complains about no input files, and `cat` does not understand it either. So I'm not sure the test case is actually useful.
Co-authored-by: CohenArthur <arthur.cohen@epita.fr>
458: stdin: Allow compilation from standard input r=philberty a=CohenArthur
Fixes#457
I'm not really sure how to test it with `dejagnu` or if it is even possible.
This PR adds a check for the `-` filename in the `RAIIFile` class. In that case, the inner pointer should simply be `stdin`. We also have to be careful not to `fclose(stdin)` upon deallocation.
Co-authored-by: CohenArthur <arthur.cohen@epita.fr>
454: Fix rs6000 r=dkm a=dkm
Applying 2 patches sent on GCC mailing-list.
These changes fix errors in the current Rust testsuite.
Co-authored-by: Thomas Fitzsimmons <fitzsim@fitzsim.org>
Handling the GNU Rust language when writing a function's epilogue is
necessary to avoid an internal compiler error.
gcc/ChangeLog:
2021-05-27 Thomas Fitzsimmons <fitzsim@fitzsim.org>
Mark Wielaard <mark@klomp.org>
* config/rs6000/rs6000-logue.c (rs6000_output_function_epilogue):
Set language type field to 0 for GNU Rust.
Co-Authored-By: Mark Wielaard <mark@klomp.org>
Both config/rs6000/sysv4.h and config/rs6000/linux64.h define
TARGET_RUST_OS_INFO, and both are included in that order in tm.h. This
change eliminates the error directive, permitting the more specific
definition in linux64.h to override the prior definition in sysv4.h.
gcc/ChangeLog:
2021-05-27 Thomas Fitzsimmons <fitzsim@fitzsim.org>
* config/rs6000/linux64.h: Undefine TARGET_RUST_OS_INFO before
defining it.
448: Fix v8.1a typo in gcc/config/aarch64/aarch64-rust.c r=dkm a=dkm
commit dcb3a7b62 "Fix aarch64 config for rust" fixed the build
on arm64, but introduced a typo in the aarch64_isa_flags check.
AARCH64_FL_V8_2 should have been AARCH64_FL_V8_1 for "v8.1a".
Co-authored-by: Mark Wielaard <mark@klomp.org>
commit dcb3a7b62 "Fix aarch64 config for rust" fixed the build
on arm64, but introduced a typo in the aarch64_isa_flags check.
AARCH64_FL_V8_2 should have been AARCH64_FL_V8_1 for "v8.1a".
443: Fix raw identifier parsing. r=dkm a=dkm
Lexer::parse_raw_identifier added the first character twice.
Adds tests for a simple raw identifier, a keyword as raw identifier and
xfail tests for a single underscore and forbidden keyword (crate) as raw
identifier.
To help error diagnostics continue after parse_raw_identifier failed in
Lexer::build_token.
Fixes: https://github.com/Rust-GCC/gccrs/issues/426
444: Initialize crateNumItr in rust-hir-map to zero. r=dkm a=dkm
valgrind complains whenever a crate number is used because they are all
derived from the initial crateNumItr in the rust-hir-map Mapping which
is never initialized. This isn't technically a bug because all that is
required is for crate numbers to be unique. But it could cause
non-deterministic behaviour when crate numbers are used for sorting.
And it makes the valgrind output really noisy.
With this patch and configure --enable-valgrind-annotations running
rust1 should not give any valgrind errors.
447: Mention the identifier that was unused in ScanUnused. r=dkm a=dkm
The ScanUnused class would only mention some name was unused.
Add the actual identifier name that is unused to help the user.
Note that this warning might produce a similar warning as the
ScanDeadcode class produces if the indentifier is a function.
Co-authored-by: Mark Wielaard <mark@klomp.org>
The ScanUnused class would only mention some name was unused.
Add the actual identifier name that is unused to help the user.
Note that this warning might produce a similar warning as the
ScanDeadcode class produces if the indentifier is a function.
Lexer::parse_raw_identifier added the first character twice.
Adds tests for a simple raw identifier, a keyword as raw identifier and
xfail tests for a single underscore and forbidden keyword (crate) as raw
identifier.
To help error diagnostics continue after parse_raw_identifier failed in
Lexer::build_token.
Fixes: https://github.com/Rust-GCC/gccrs/issues/426
445: Fix assert in rust-buffered-queue peek r=dkm a=dkm
When end + num_items_to_read > buffer.size the buffer is extended to make sure it
can hold at least the extra num_items_to_read. The assert at the end of this block
however checks against end + num_queued_items. Fix the assert. This makes check-rust
zero fail on arm64.
446: Fix aarch64 config for rust r=dkm a=dkm
Define aarch64_rust_target_cpu_info in aarch64-protos.h.
AARCH64_ISA_V8_1 isn't defined directly, check aarch64_isa_flags.
Co-authored-by: Mark Wielaard <mark@klomp.org>
When end + num_items_to_read > buffer.size the buffer is extended to make sure it
can hold at least the extra num_items_to_read. The assert at the end of this block
however checks against end + num_queued_items. Fix the assert. This makes check-rust
zero fail on arm64.
valgrind complains whenever a crate number is used because they are all
derived from the initial crateNumItr in the rust-hir-map Mapping which
is never initialized. This isn't technically a bug because all that is
required is for crate numbers to be unique. But it could cause
non-deterministic behaviour when crate numbers are used for sorting.
And it makes the valgrind output really noisy.
With this patch and configure --enable-valgrind-annotations running
rust1 should not give any valgrind errors.
438: DefId is a bit mask of CrateNum & LocalDefId r=philberty a=philberty
The DefId was being constructed wrongly by not fully shifting the CrateNum
over to be masked correctly.
Addresses #437
I am not sure if this fixes#437 but this definitely was not correct.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
436: Fixed#419: only parse inner_attributes if it starts with "#!" not only "#" r=philberty a=thomasyonug
Fixed#419
only parse inner_attributes if it starts with "#!" not only "#"
Co-authored-by: Thomas Young <wenzhang5800@gmail.com>
372: Create CODE_OF_CONDUCT.md r=philberty a=philberty
Adding a code of conduct lays out rules that we can all follow in the project.
Although GCC does not have one of these we can at least adopt one here for the project development.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
393: Add support for 'unsupported' test cases in testsuite r=philberty a=dkm
Add support for 'unsupported' test cases in testsuite
Introduce an 'unsupported/' directory in the testsuite. It should contains tests
case for which the compiler currently has an incorrect behavior:
- its accepts invalid input
- it rejects valid input
Some basic guidelines are provided in unsupported.exp.
431: Add Issue and PR templates r=philberty a=philberty
This removes the greetings automation and adds in PR and issue templates in github. These were taken from rust-clippy as a base and changed for GCC Rust.
Co-authored-by: Marc Poulhiès <dkm@kataplop.net>
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
Introduce an 'unsupported/' directory in the testsuite. It should contains tests
case for which the compiler currently has an incorrect behavior:
- its accepts invalid input
- it rejects valid input
Some basic guidelines are provided in unsupported.exp.
430: Add FNV-128 hash for legacy symbol mangling r=philberty a=philberty
Rustc uses a SIP128 hash for the legacy symbol mangling but an FNV hash is
simpler to implement. This is a port of the implementation from golang
stdlib hash package.
The fingerprint for the hash is simply the function signature for now.
Rustc takes into account options such as -Cmetadata to generate uniqueness.
We still need to implement a SIP128 hasher and the V0 symbol mangling but this
will do in the interim.
Addresses: #305Fixes: #428
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
373: Create CONTRIBUTING.md r=philberty a=philberty
This contributing guide should answer frequently asked questions when people submit code to GCCRS.
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
This provides context for people learning to submit code or issues back to
the project. It will help answer frequently asked questions and a set of
rules for all of us to follow.
This is something that should evolve over time.
Rustc uses a SIP128 hash for the legacy symbol mangling but an FNV hash is
simpler to implement this is a port of the implementation from golang
stdlib hash package.
The fingerprint for the hash is simple the function signiture for now.
Rustc takes into account options such as -Cmetadata to generate uniqueness.
We still need to implement an SIP128 and the V0 symbol mangling but this
will do in the interim.
Addresses: #305Fixes: #428
427: Fix duplicate function generation in the backend r=philberty a=philberty
Fix duplicated function generation for generics
When emitting the backend IR we need to check if we have already compiled
one already. This is all due to the fact when we do generic substitutions
in type resolution its only upon usage of a function the function is
substituted it gains a new unique ty_ref HIR ID to make sure new
substituted versions of a type have unique ids.
Fixes#403
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
When emitting the backend IR we need to check if we have already compiled
one already. This is all due to the fact when we do generic substitutions
in type resolution its only upon usage of a function the function is
substituted it gains a new unique ty_ref HIR ID to make sure new
substituted versions of a type have unique ids.
This means we can end up with multiple substitued versions of the same
function which end up being compiled multiple times. This was also the case
for generic data types but is already fixed.
Fixes#403
ParamTypes are a strange case because we can say a type parameter T
was substituted by an i32 so if you do an is_equal for:
T:i32 vs i32
The type kinds won't match but they are equal in the actual type they
represent. The missing piece was that Type parameters can match each other
if their symbols match.
425: Basic implementation of legacy symbol mangling r=philberty a=philberty
Implement basic rustc legacy symbol mangling
Rust supports two different symbol mangling methods legacy and V0. V0 is
the goal but its not yet stable. This implements the legacy method but
with a dummy hash value since it requires a sip128 implementation to
generate the apropriate hash which can be done in a sperate change.
This change allows us to actually assemble generic functions and avoid
bad symbol duplications.
Addresses #305
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
Rust supports two different symbol mangling methods legacy and V0. V0 is
the goal but its not yet stable. This implements the legacy method but
with a dummy hash value since it requires a sip128 implementation to
generate the apropriate hash which can be done in a sperate change.
This change allows us to actually assemble generic functions and avoid
bad symbol duplications.
Addresses #305
We need to track crate names including the translation units one for symbol
mangling purposes. This defaults to TestCrate for now and will need more
work to actually make this a compiler option as part of imports and
visbility.
422: Add testcase to cover case where type param cannot be infered r=philberty a=philberty
When the Type paramater is not used we cannot infer the type and we should
error this was fixed in #375.
Fixes#420
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
424: Support Impl items to also be generic r=philberty a=philberty
Handle inherited type arguments for methods
MethodCallExpr's support generic arguments so we need to handle adjusting
any inherited type arguments from the receiver and apply them to the func.
This changes the handle_substitutions function for ADT, FnType and Params
to be permissive that we can send single arguments to partially substitute
the type such as the case when we inherit arguments in methods calls. This
is safe because the other interfaces enforce the type checking and number
of arguments etc.
Fixes#423#417
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
MethodCallExpr's support generic arguments so we need to handle adjusting
any inherited type arguments from the receiver and apply them to the func.
This changes the handle_substitutions function for ADT, FnType and Params
to be permissive that we can send single arguments to partially substitute
the type such as the case when we inherit arguments in methods calls. This
is safe because the other interfaces enforce the type checking and number
of arguments etc.
Fixes#423
When we infer substitutions it means to infer for all type parameters
regardless of defaults. This means we need to also not simply ignore
any type paramters which are already been substituted.
Method calls also support a turbo fish such as: instance.method()::<a,b>,
these need to name resolved before they can be type resolved even though
the actual method is resolved in the type resolution phase.
This is a building block to support generic impl blocks with a generic
method. We need to adjust the Self type parameters to the turbo fish for
the method call expr.
416: We need to monomorphize tuples as well as ADT's r=philberty a=philberty
When we have generic data types or types that can contain type parameters
we need to make sure to avoid duplicating record types and abusing
structural equality rules in GCC. We do this by looking for already
compiled types that the item is equal to so they refer to the canoncial
record type.
Fixes#415
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
When we have generic data types or types that can contain type parameters
we need to make sure to avoid duplicating record types and abusing
structural equality rules in GCC. We do this by looking for already
compiled types that the item is equal to so they refer to the canoncial
record type.
Fixes#415
410: Fix#407, #409 testcases r=philberty a=tschwinge
@teromene, for your information/learning. ;-D
Co-authored-by: Thomas Schwinge <thomas@codesourcery.com>
409: Fix crashing in assignment operation r=philberty a=teromene
This should fix#407
The output now looks like:
```
test1.rs:9:17: error: found unexpected token ‘=’ in null denotation
9 | a + = 1;
| ^
test1.rs:9:13: error: failed to parse expression for expression without block (pratt-parsed expression is null)
9 | a + = 1;
| ^
test1.rs:9:13: error: failed to parse statement or expression without block in block expression
test1.rs:9:19: error: failed to parse if body block expression in if expression
9 | a + = 1;
| ^
test1.rs:8:9: error: failed to parse expr with block in parsing expr statement
8 | if a < 40 {
| ^
test1.rs:8:9: error: failed to parse statement or expression without block in block expression
test1.rs:10:11: error: could not parse loop body in (infinite) loop expression
10 | } else {
| ^
test1.rs:7:5: error: failed to parse expr with block in parsing expr statement
7 | loop {
| ^
test1.rs:7:5: error: failed to parse statement or expression without block in block expression
test1.rs:14:5: error: unrecognised token ‘return’ for start of item
14 | return a;
| ^
test1.rs:14:5: error: failed to parse item in crate
```
Co-authored-by: Lyra <teromene@teromene.fr>
406: Add locations to implicit inference variables r=philberty a=philberty
When we have expression paths to generic functions we need to resolve all
type parameters to something otherwise we are left with orphaned inference
variables.
This adds the same checks from rustc back in, previously the
PathInExpression resolver abused inference variables as it was implemented
incorrectly since this is fixed in previous PRs we can bring this back in
to make typing more strict again.
Fixes#375
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
When we have expression paths to generic functions we need to resolve all
type parameters to something otherwise we are left with orphaned inference
variables.
This adds the same checks from rustc back in, previously the
PathInExpression resolver abused inference variables as it was implemented
incorrectly since this is fixed in previous PRs we can bring this back in
to make typing more strict again.
Fixes#375
401: Add defaults support for generics r=philberty a=philberty
This adds in the basic support for default arguments for generics such as:
```rust
struct Foo<A,B=f32>(A,B);
```
or recursive type params such as:
```rust
struct Foo<A, B = (A, A)>(A, B);
```
Fixes#307
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
When we get defaults specified to Type parameters we must resolve the type
before insert the name into the name scope otherwise we can end up with
forward declared type parameters being resolved.
When we need to apply defaults during substitution we must check if they
themseleves need substitutions also with the mappings we have generated
so far.
Fixes#307
399: Improve error diagnostics in generic argument handling r=philberty a=philberty
When we get GenericBindings such as ::<A=...> this is not allowed
in this context. We can also improve the unexpected number of argument
errors to print the number of expected vs received arguments
An example error message looks like:
```
test.rs:4:12: error: generic item takes at least 1 type arguments but 0 were supplied
1 | struct Foo<A>(A);
| ~
......
4 | let a: Foo = Foo::<i32>(123);
| ^
```
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
Co-authored-by: Marc Poulhiès <dkm@kataplop.net>
In the case that the GenericArgs to a type/fn are less than the expected
number of required substitutions we need to look for what is the min
number of required substitutions which might be zero if each TypeParam
has a default.
In the event we have less than expected arguments we can substitute the
defaults if available as the GenericArgumentMappings.
Addresses: #307
We need to lower the bindings for defaults in the GenericArgs structure.
We can also take advantage of RichLocations further improving the
diagnostic errors here.
When we get GenericBindings such as ::<A=...> this is not allowed
int this context. We can also improve the unexpected number of argument
errors to print the number of expected vs received arguments.
398: ReferenceTypes and Tuple can hold Type Parameters r=philberty a=philberty
We need to perform internal substitutions on Reference and Tuple Types in order to type check them.
These types cannot hold substitution parameters so they need to be performed with the internal substitution mapper.
Fixes#396
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
397: Name resolve any specified types in TypeParams r=philberty a=philberty
Type parameters can have defaults these need to be name resolved.
Addresses: #307
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
394: Partial substitions of generic data types r=philberty a=philberty
Handle the case where we have a generic type:
```rust
struct Foo<A,B>(A,B);
impl<T> Foo<i32, T> { ... }
```
In this case the impl block only defines 1 type parameter but the generic datatype has two type parameters.
Fixes#386
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
When we have a generic data type with 2 type parameters A,B but then
add an impl block for this type and this impl block only defines 1 Type
parameter and substitutes the other type parameter with a concrete type
we need to use the passed in mappings and the existing mappings to figure
out how to adjust the type parameters to complete the substitution.
Fixes: #386
390: Clean up the compilation of block expressions r=philberty a=lrh2000
The original implementation of compiling block expressions and function bodies is incorrect. Here is an example.
```rust
fn foo() -> i32 {
1;
2;
0
}
```
The above Rust code will compile into the below GIMPLE code.
```c
i32 foo ()
{
i32 D.199;
D.199 = 1;
return D.199;
D.199 = 2;
return D.199;
D.199 = 0;
return D.199;
}
```
It is obviously incorrect.
*(Original in https://github.com/Rust-GCC/gccrs/pull/364)*
Co-authored-by: lrh2000 <lrh2000@pku.edu.cn>
388: Assign outer_attrs in IfLetExpr constructor r=philberty a=CohenArthur
Closes#360
This fixes IfLetExpr's behavior and removes the previous unused warning as well
Co-authored-by: CohenArthur <arthur.cohen@epita.fr>
387: Don't remove unreachable statements at HIR lowering r=philberty a=lrh2000
This is a legal code segment:
```rust
fn foo() -> i32 {
return 1;
let a = 1;
a
}
```
And this is illegal:
```rust
fn foo() -> i32 {
return 1;
let a = 1.5;
a
}
```
So we shouldn't remove unreachable statements at HIR lowering. We can issue warnings for them, but they need to be kept so that their types can be checked.
*(Original in https://github.com/Rust-GCC/gccrs/pull/364)*
Co-authored-by: lrh2000 <lrh2000@pku.edu.cn>
The `outer_attrs` member was not used in the IfLetExpr type, as it was
believed to be forbidden. However, that assumption was false and
outer_attrs are indeed allowed here. This commit also fixes the unused
warning for the `outer_attrs` constructor's argument, which was not
assigned before.
380: Fix issues about block expression evaluation r=philberty a=lrh2000
I've tried my best to split https://github.com/Rust-GCC/gccrs/pull/364. Its core part is here. All unrelated fixes should have been removed and I will make them separate PRs, but this PR still has to contain 2 commits and introduce limited support for the never type.
935aff52a6/gcc/testsuite/rust.test/compile/deadcode1.rs (L7-L15)935aff52a6/gcc/testsuite/rust.test/compile/implicit_returns1.rs (L44-L50)
The reason is that the above two tests failed to pass simultaneously after the first commit. The first test requires the `if/else` expression resolves to `()` but the second test requires the `if/else` expression resolves to `<integer>`. They are conflicted.
I wonder whether or not this PR is OK, and anyway thanks for your review.
Co-authored-by: lrh2000 <lrh2000@pku.edu.cn>
383: Reuse fold-const.c from GCC to enforce const array capacities r=philberty a=philberty
Rust allows for constant eval for cases like array capacity, the initial
version of this code forced the programmer to only use literals which was
not correct but got the type system off the ground.
This now takes advantage of the GCC backend object to offer 3 helprs.
1. check for constant Bexpression* are equal
2. extract a size_t constant value from the Bexpression*
3. to string the Bexpression constant
We can get away with the extraction of the value here because we know its going to be a usize for array capacity but some thought is needed if these methods are to be reused in other cases.
There is a new ConstFold namespace which should be extensible for const
functions later on and const generics.
Fixes: #296
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
384: Fix dg-ice handling in rust testsuite r=tschwinge a=dkm
Fix the pruning regex to also match ICE message and allow for dg-ice use.
Add the test from #382 as a sample example.
Should help #308
Co-authored-by: Marc Poulhiès <dkm@kataplop.net>
Rust allows for constant eval for cases like array capacity, the initial
version of this code forced the programmer to only use literals which was
not correct but got the type system off the ground.
This now takes advantage of the GCC backend object to offer 3 helpers.
1. check for constant Bexpression* are equal
2. extract a size_t constant value from the Bexpression*
3. to string the Bexpression constant
We can get away with the extraction of the value here because we know its
going to be a usize for array capacity but some thought is needed if these
methods are to be reused in other cases.
There is a new ConstFold namespace which should be extensible for const
functions later on and const generics.
Fixes: #296
381: Fix crash on empty parameters to generic data type r=philberty a=philberty
When no parameters are passed to generic data types we cannot properly
infer the usage of the generic block.
This brings in a canonicalized check for `rustc --explain E0107`
Fixes#379
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
When no parameters are passed to generic data types we cannot properly
infer the usage of the generic block.
This brings in a canonicalized check for `rustc --explain E0107`
Fixes#379
374: Add basic wrapper over gcc rich_location r=philberty a=philberty
Adding rich location will improve our error message diagnostics, this is
an initial building block to keep a wrapper over the GCC stuff we call.
Addresses: #97Fixes: #327
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
This fatal error stops the compiler in its tracks and will mean the Typed
HIR dump will not occur limiting how much we can debug errors/bugs in the
compiler.
Fixes#327
Adding rich location will improve our error message diagnostics, this is
an initial building block to keep a wrapper over the GCC stuff we call.
Addresses: #97
378: Add Check for unconstrained type parameters r=philberty a=philberty
When we have an impl<X,Y> Foo<X>, the type parameter Y is unconstrained
so that we cannot be sure how Y should be substituted later on.
Fixes#354
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
377: Fix crash when mapping of Generic argument changes. r=philberty a=philberty
When we have a struct Foo <T>(T) but the fntype in impl block is different
fn <X> Bar(a:X) -> Foo<X>(X) { } we must take advantage of the adjustment
code in the substitution mapper.
This affects MethodCallExpr and PathInExpressions where it used to resolve
the root segment and leave the arguments as inference variables when we
lack a segement with generic arguments.
This also fixes a bug in name resolution where the Self keyword resolved
to the struct/type the impl block resolves to but it needed to resolve
to the impl block type explicitly which ensures the parameter mappings
reflect what the parent impl block is.
Fixes: #376
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
When we have a struct Foo <T>(T) but the fntype in impl block is different
fn <X> Bar(a:X) -> Foo<X>(X) { } we must take advantage of the adjustment
code in the substitution mapper.
This affects MethodCallExpr and PathInExpressions where it used to resolve
the root segment and leave the arguments as inference variables when we
lack a segement with generic arguments.
This also fixes a bug in name resolution where the Self keyword resolved
to the struct/type the impl block resolves to but it needed to resolve
to the impl block type explicitly which ensures the parameter mappings
reflect what the parent impl block is.
Fixes: #376
369: Implement the inline visitor r=philberty a=YizhePKU
This is a clean implementation of the inline visitor. Should be useful for various cleanups such as #366.
Co-authored-by: YizhePKU <yizhe@pku.edu.cn>
358: Canonical Paths for Name Resolution and handle TurboFish properly r=philberty a=philberty
Add Canonical paths to name resolution
In order to support name resolution and checks for duplicate definitions
of names we need canonical paths for all DefId items such as inherent impl
items and normal items. Consider:
```rust
struct Foo<T>(T);
impl Foo<f32> {
fn name()...
}
impl Foo<i32> {
fn name()...
}
```
Each of the impl blocks have a name function but these are separate due to
the concrete impl of the Parameter type passed in.
The caveat here is that to call this Function name the programmer must be
explicit in which implentation they wish to call such as:
```rust
let a = Foo::<f32>::name();
```
This lets the Path probe lookup the appropriate impl block. The problem here
is that rust also allows for the compiler to infer the impl you wish such
as:
```rust
let a = Foo::name();
```
This should fail since there are multiple candidates possible for this
Path. Unless there might have only been one name function in which case
it would have worked.
This patch is also responsible to implement PathInExpression by iterating
each segment and applying generic arguments as we go.
Fixes#355#335#325#353
Co-authored-by: Philip Herron <philip.herron@embecosm.com>
When we have impl blocks for a generic type rust allows the programmer
to reuse impl item names but if you give a generic implementation it means
this generic implementation will overlap meaning it will not be possible
to determine the Path. See rustc error: rustc --explain E0592
rustc_typeck/src/coherence/inherent_impls_overlap.rs
Fixes#353
In order to support name resolution and checks for duplicate definitions
of names we need canonical paths for all DefId items such as inherent impl
items and normal items.
Consider:
struct Foo<T>(T);
impl Foo<f32> {
fn name()...
}
impl Foo<i32> {
fn name()...
}
Each of the impl blocks have a name function but these are seperate due to
the concrete impl of the Parameter type passed in.
The caveat here is that to call this Function name the programmer must be
explicit in which implentation they wish to call such as:
let a = Foo::<f32>::name();
This lets the Path probe lookup the apropriate impl block. The problem here
is that rust also allows for the compiler to infer the impl you wish such
as:
let a = Foo::name();
This should fail since there are multiple candidates possible for this
Path. Unless there might have only been one name function in which case
it would have worked.
This does not support looking for any inherent impl items overlapping such
as: rustc_typeck/src/coherence/inherent_impls_overlap.rs - see #353Fixes#355#335#325
When performing PathInExpression resolution we need to probe for candidates
in impl blocks which can_eq to the Self type. This could be reused to clean
up Method resolution and implement PathInExpression resolution properly.
When lowering impl blocks to HIR we keep track of all the inherent impl
items for lookup later but we also need to be able to reverse lookup impl
items back to their respective impl block.
When we are probing paths we dont want to unify types as we are testing
to find something so a can_eq method simialr to unify but does not throw
errors allows for testing if types could be compatible.
When unifying algebraic data types we must check the identifiers match
as well as everything else. We also should not be relying on nullptr
checks for resolution failures but use TyTy::Error nodes.
When we do full PathInExpression resolution we can end up with orphaned
Inference Variables which never get unified with real concrete types. This
is to be expected. What we really care about are that all name declarations
are fully typed before we move into the next pass.
..., and update testcases as appropriate.
In addition to (very) few 'unreachable expression', 'unreachable statement', or
'function is never used', most of these are to catch expected 'unused name'
warning diagnostics. Of the latter, a few are XFAILed for
<https://github.com/Rust-GCC/gccrs/issues/361> "Names prefixed with underscore
shouldn't get 'unused name' diagnostic".
357: Create liveness analysis for dead code detection r=philberty a=thomasyonug
This is the very beginning work for dead code detection. #330
1. create a new test for this feature.
2. handle an extremely simple case.
After compiling the rust1, and feed "testsuite/rust.test/xfail_compile/unused.rs" to it.
``` rust
fn bar() { // {dg-warning "function is never used: `bar`"}
foo();
}
fn foo() { // {dg-warning "function is never used: `foo`"}
bar();
}
fn f() {
}
fn main() {
f();
}
```
we will get some warnings.
``` bash
../gccrs/gcc/testsuite/rust.test/xfail_compile/unused.rs:2:1: warning: function is never used: `[bar]`
2 | fn bar() { // {dg-warning "function is never used: `bar`"}
| ^
../gccrs/gcc/testsuite/rust.test/xfail_compile/unused.rs:6:1: warning: function is never used: `[foo]`
6 | fn foo() { // {dg-warning "function is never used: `foo`"}
| ^
```
Co-authored-by: Thomas Young <wenzhang5800@gmail.com>
In order to find more examples of dead code we must create liveness variables
and scan after type resolution. In this case, if a function is unused and it calls
another function the 2nd function is now unused since the caller is not used etc.
This is a WIP but demonstrates the pattern we can follow to add more dead code
analysis warnings like rustc does.
Addresses #330
288: Fix crash with zero length array r=philberty a=YizhePKU
This PR fixes the crash that results from zero-length arrays, such as `let arr = []`(issue #260). `ArrayExpr` now uses `ArrayElemsValues` to represent an empty array like that, instead of `nullptr`.
However, currently such code still doesn't compile. Four tests were added, two of which report an error:
```Rust
// compilable/array_empty_list.rs
fn main() {
let arr = [];
}
// rust1: error: unable to determine type: please give this a type: 24
```
```Rust
// compilable/array_zero_length_fold.rs
fn main() {
let arr = ["Hello"; 123 - 123];
}
// array_zero_length_fold.rs:2:25: fatal error: failed to fold capacity constant
```
I think these are best treated as separate bugs. We can merge first and fix later, or we can delay this PR. Either is OK.
Co-authored-by: Yizhe <yizhe@pku.edu.cn>
Co-authored-by: YizhePKU <yizhe@pku.edu.cn>
Co-authored-by: YizhePKU <42838469+YizhePKU@users.noreply.github.com>
... by doing the same as in the "assignment operator to deep copy pointers" a
few lines later. I have not verified what's (supposed to be) going on here;
that code seems unused, and thus untested, and thus I marked it up as such.
In file included from [...]/gcc/rust/hir/tree/rust-hir-full.h:29,
from [...]/gcc/rust/backend/rust-compile.h:23,
from [...]/gcc/rust/backend/rust-compile.cc:19:
[...]/gcc/rust/hir/tree/rust-hir-type.h: In copy constructor ‘Rust::HIR::ArrayType::ArrayType(const Rust::HIR::ArrayType&)’:
[...]/gcc/rust/hir/tree/rust-hir-type.h:607:21: error: ‘*<unknown>.Rust::HIR::ArrayType::<anonymous>.Rust::HIR::TypeNoBounds::<anonymous>.Rust::HIR::Type::mappings’ is used uninitialized [-Werror=uninitialized]
607 | : TypeNoBounds (mappings), elem_type (other.elem_type->clone_type ()),
| ^~~~~~~~
In file included from [...]/gcc/rust/parse/rust-parse.h:645:0,
from [...]/gcc/rust/rust-session-manager.cc:34:
[...]/gcc/rust/parse/rust-parse-impl.h: In instantiation of 'std::unique_ptr<Rust::AST::AttrInput> Rust::Parser<ManagedTokenSource>::parse_attr_input() [with ManagedTokenSource = Rust::Lexer]':
[...]/gcc/rust/parse/rust-parse-impl.h:522:66: required from 'Rust::AST::Attribute Rust::Parser<ManagedTokenSource>::parse_attribute_body() [with ManagedTokenSource = Rust::Lexer]'
[...]/gcc/rust/parse/rust-parse-impl.h:493:59: required from 'Rust::AST::Attribute Rust::Parser<ManagedTokenSource>::parse_inner_attribute() [with ManagedTokenSource = Rust::Lexer]'
[...]/gcc/rust/parse/rust-parse-impl.h:444:58: required from 'std::vector<Rust::AST::Attribute> Rust::Parser<ManagedTokenSource>::parse_inner_attributes() [with ManagedTokenSource = Rust::Lexer]'
[...]/gcc/rust/parse/rust-parse-impl.h:402:69: required from 'Rust::AST::Crate Rust::Parser<ManagedTokenSource>::parse_crate() [with ManagedTokenSource = Rust::Lexer]'
[...]/gcc/rust/rust-session-manager.cc:458:43: required from here
[...]/gcc/rust/parse/rust-parse-impl.h:734:9: error: could not convert 'input_tree' from 'std::unique_ptr<Rust::AST::DelimTokenTree>' to 'std::unique_ptr<Rust::AST::AttrInput>'
return input_tree;
^
[...]/gcc/rust/parse/rust-parse-impl.h:792:9: error: could not convert 'attr_input_lit' from 'std::unique_ptr<Rust::AST::AttrInputLiteral>' to 'std::unique_ptr<Rust::AST::AttrInput>'
return attr_input_lit;
^
In file included from [...]/gcc/rust/parse/rust-parse.h:645:0,
from [...]/gcc/rust/rust-session-manager.cc:34:
[...]/gcc/rust/parse/rust-parse-impl.h: In instantiation of 'std::unique_ptr<Rust::AST::TraitItem> Rust::Parser<ManagedTokenSource>::parse_trait_item() [with ManagedTokenSource = Rust::Lexer]':
[...]/gcc/rust/parse/rust-parse-impl.h:4693:70: required from 'std::unique_ptr<Rust::AST::Trait> Rust::Parser<ManagedTokenSource>::parse_trait(Rust::AST::Visibility, std::vector<Rust::AST::Attribute>) [with ManagedTokenSource = Rust::Lexer]'
[...]/gcc/rust/parse/rust-parse-impl.h:1268:67: required from 'std::unique_ptr<Rust::AST::VisItem> Rust::Parser<ManagedTokenSource>::parse_vis_item(std::vector<Rust::AST::Attribute>) [with ManagedTokenSource = Rust::Lexer]'
[...]/gcc/rust/parse/rust-parse-impl.h:1048:53: required from 'std::unique_ptr<Rust::AST::Item> Rust::Parser<ManagedTokenSource>::parse_item(bool) [with ManagedTokenSource = Rust::Lexer]'
[...]/gcc/rust/parse/rust-parse-impl.h:410:58: required from 'Rust::AST::Crate Rust::Parser<ManagedTokenSource>::parse_crate() [with ManagedTokenSource = Rust::Lexer]'
[...]/gcc/rust/rust-session-manager.cc:458:43: required from here
[...]/gcc/rust/parse/rust-parse-impl.h:4876:13: error: could not convert 'macro_invoc' from 'std::unique_ptr<Rust::AST::MacroInvocationSemi>' to 'std::unique_ptr<Rust::AST::TraitItem>'
return macro_invoc;
^
In file included from [...]/gcc/rust/hir/tree/rust-hir-full.h:29,
from [...]/gcc/rust/hir/rust-ast-lower.h:25,
from [...]/gcc/rust/hir/rust-ast-lower.cc:19:
[...]/gcc/rust/hir/tree/rust-hir-type.h: In member function ‘virtual void Rust::HIR::ASTLoweringType::visit(Rust::AST::BareFunctionType&)’:
[...]/gcc/rust/hir/tree/rust-hir-type.h:785:3: error: ‘kind’ may be used uninitialized in this function [-Werror=maybe-uninitialized]
785 | MaybeNamedParam (MaybeNamedParam &&other) = default;
| ^~~~~~~~~~~~~~~
In file included from [...]/gcc/rust/hir/rust-ast-lower-item.h:25,
from [...]/gcc/rust/hir/rust-ast-lower.cc:20:
[...]/gcc/rust/hir/rust-ast-lower-type.h:58:41: note: ‘kind’ was declared here
58 | HIR::MaybeNamedParam::ParamKind kind;
| ^~~~
... by doing the same as in the "assignment operator with vector clone" a few
lines later. I have not verified what's (supposed to be) going on here; that
code seems unused, and thus untested, and thus I marked it up as such.
In file included from [...]/gcc/rust/hir/tree/rust-hir-expr.h:23,
from [...]/gcc/rust/hir/tree/rust-hir-full.h:24,
from [...]/gcc/rust/backend/rust-compile.h:23,
from [...]/gcc/rust/backend/rust-compile.cc:19:
[...]/gcc/rust/hir/tree/rust-hir-path.h: In copy constructor ‘Rust::HIR::QualifiedPathInType::QualifiedPathInType(const Rust::HIR::QualifiedPathInType&)’:
[...]/gcc/rust/hir/tree/rust-hir-path.h:820:21: error: ‘*<unknown>.Rust::HIR::QualifiedPathInType::<anonymous>.Rust::HIR::TypeNoBounds::<anonymous>.Rust::HIR::Type::mappings’ is used uninitialized [-Werror=uninitialized]
820 | : TypeNoBounds (mappings), path_type (other.path_type), locus (other.locus)
| ^~~~~~~~
In file included from [...]/gcc/rust/hir/tree/rust-hir-full.h:24,
from [...]/gcc/rust/hir/rust-ast-lower.h:25,
from [...]/gcc/rust/hir/rust-ast-lower.cc:19:
[...]/gcc/rust/hir/tree/rust-hir-expr.h: In member function ‘virtual void Rust::HIR::ASTLoweringExpr::visit(Rust::AST::CompoundAssignmentExpr&)’:
[...]/gcc/rust/hir/tree/rust-hir-expr.h:426:7: error: ‘op’ may be used uninitialized in this function [-Werror=maybe-uninitialized]
426 | expr_type (expr_kind), right_expr (std::move (right_value))
| ^~~~~~~~~~~~~~~~~~~~~
In file included from [...]/gcc/rust/hir/rust-ast-lower-type.h:24,
from [...]/gcc/rust/hir/rust-ast-lower-item.h:25,
from [...]/gcc/rust/hir/rust-ast-lower.cc:20:
[...]/gcc/rust/hir/rust-ast-lower-expr.h:471:33: note: ‘op’ was declared here
471 | ArithmeticOrLogicalOperator op;
| ^~
has_array_elems() is mostly used as a nullptr check. We don't need it
anymore.
To implement has_array_elems() correctly(i.e. return true when the array
is zero length) would be difficult, because we may need to perform
constant folding first.
A handy helper function. I copied the code from Effective Modern C++.
The code is too short to be considered "legally significant", so
copyright should not be an issue.
Also, GCC copyright notice is not needed on such small files as well.
Testcase added in recent commit ff1eca9a57 "Fix
infinite loop when expanding cfg attributes (#319)", but isn't actually
expected to fail, so re-categorize from 'xfail_compile' into 'compile'.
When we have Types capable of type substitution it only needs substituted
if it was not already substituted and it actually has substitutions defined
Fixes#311
This allows for a typedef style alias of any type in rust code, as the
types are abstracted behind the TyTy interface this falls out quite nicely.
In order to support TypeAliases we needed to be able to supported already
substituted types in #311.
More testing is needed here the GenericParameters on TypeAlias are not
being used in the type resolution pass here.
Fixes#312
Addresses #311
When implementing generics we need to keep track of used arguments to
recursively substitute ParamTypes when nessecary. This also applies for
cases such as: Foo<i32> where we can check wether we need to actually
perform a substitution.
rust-macro-expand: Fix infinite loop in cfg_attr expansion
Expanding the cfg_attrs wasn't incrementing the index at which to access
the attribute to expand, so the compiler was stuck in expanding the same
attribute over and over again in some cases.
Fixes#320
the PR #302 and #301 were conflicting because they are both modifying the tests.
Move the conflicting test and add correct dg-error directive.
continue1.rs is less verbose after #286, remove the dg-excess-error.
This extends the support from #237 to extend this to MethodCallExpr, this
now follows a similar path to normal CallExprs and ensures the used
arguments in substitution are preserved during unification of types. Part
of method resolution is fixed here by taking advantage if is_equal instead
of unify calls which could result in bad errors which are just part of the
probe process to lookup possible candidates for method resolution.
Fixes#306
We resolve methods during type resolution since it depends on the receiver
type being used. To ensure the function is marked as used we must then
mark the method name as resolved, this is also used in the backend
GENERIC compilation to lookup the function definition to be compiled.
When this was unset multiple method calls would fail.
Fixes#310
Removed TyTy::UnitType and TyTy::TypeKind::UNIT.
Replaced by TyTy::TupleType with an empty list of fields.
Added default empty vector for fields in ctor for TyTy::TypeType.
Use more standard layout for DejaGNU testsuite.
3 subdirectories are used for tests:
- compile/*: tests are build using default torture options.
- xfail_compile/*: tests are expected to fail early in the frontend and are only
build once.
- execute/*: tests are executed and exit status is checked.
The previous .exp files were copied from D tests and were expected to be used in
a different way not really applicable for the current Rust tests.
Fixes#281
Adds recursive generic argument handling for structs and functions. With a
new substitution mapper class to coerce the HIR::GenericArgs appropriately.
This is the building block to work on impl blocks with generics and
better Monomorphization support to handle duplicate functions etc.
Fixes: #236#234#235
Addresses: #237
When we resolve the type of an expression such as a LiteralExpr with HIR id
10, but is the final expression in a BlockExpr of HirId 11. The same type
is infered for the entire BlockExpr as well as the final Expr but we
override the reference id on the TyTy::Type. This means if there is a
change in reference id the old ID must be added to the combined reference
chain for type inference to take place.
Fixes#293
virtual loop_expression and exit_expression were not marked pure and do not have
a default impl, causing error during linking when optimisation are disabled.
This is a refactoring/cleanup effort to stop using raw fields of
HIR::Items. It also removes an old set of locals since before the TyTy
module and move to HIR from the AST::Function.
Function definitions can have substations (generics) where as function
pointers cannot. These are distinct elements and their separation is
important to support wildcards (inference variables) on BareFunctionTypes.
To fix this the patch leverages the wrapper TyCtx which denotes a type that
must be infered.
Fixes#269
ArrayTypes for example can have an inference variable for an element type
which requires the Type system to lookup what type it is when requested.
TyCtx acts as this wrapper that takes an HirId reference that cleans up the
code for ArrayTypes, ReferenceTypes and TupleTypes where elements can be
inference variables.
When we have a General inference G? variable as part of an array that is
unified with integeral inference variables I? the context left the General
inference variable but really this changed to tbe I? and can default to
i32.
Fixes#258
With AST and HIR using the same operator enum, we no longer need to
perform conversions. Except for CompoundAssignmentExpr, which gets
compiled away and therefore still needs conversion.
Now that everyone uses the 4 enums in the global namespace, the process
of lowering HIR to Bexpression can be simplified by removing the
intermediate translation.
Gcc_backend::unary_expression and Gcc_backend::binary_expression has
been split into 4 smaller functions corresponding to the 4 enums.
It turns out that keeping the 4 enums distinct helps simplify the logic
a lot. A lot of if-else branches were eliminated just by inlining the
type infomation.
There were also some minor cleanup. `operator_to_tree_code` function has
been modified to omit the `tree` parameter and offload floating-point
check to the caller.
`operator.h` has been rewritten from scratch. 5 enums are extracted from
the AST namespace, while only 4 of them are used in the HIR namespace.
There're still code that uses the old Operator enum. We also need to
change code that uses the AST enum to point to the new global enum.
This removes StructFieldType from the TyTy base as it is not a type that
can be unified against.
It adds in a substition mapper implementation which will likely change
over time when this this support is extended over to Functions and
TupleStructs.
Note generic argument binding is not supported as part of this yet.
Fixes#235
Now the base(pointer to Ty) is only stored in derived rules. It is
accessible in `BaseRules` with `get_base` method, which is implemented
in derived rules.
Initially I thought `equals` is a better name because it fits the java
usage. However there will be another `can_eq` method that adjust types,
and in that case `is_equal` is a more consistent name.
The resulting code looks quite similar to `unify`, except that it
doesn't save refs, so it should be more efficient. However the
introduced complexity is a bit worrying.
This commit also adjusted some const qualifiers of `BaseType`
methods where necessary.
This also adds in the mising InferenceType _ which was mostly implemented
before as part of Data Structures 1.
We create GENERIC REFERENCE_TYPES for these this is the building block
to finish work on mutability rules and pointers.
Fixes: #196
Addresses: #169#170
The parser has the same bug as in #225 for break expressions. This
tidies up the type resolver and GENERIC translation to handle the
case where there is no return expression as well.
Fixes#226
The null_denotion function expects to find the beginning of an expression
but breaks can be empty and the parser will fail with unexpected ';'.
Fixes#225
This is the building block for the rest of loops where we have a basic
infinite loop. Break/Continue reliest on the resolution of labels and
breaks can also make a loop into a BlockExpr
Fixes#106
We output each debug IR to file which makes it easier to debug larger
test cases. Beaware not all dumps are complete such as name resolution
is not implemented yet, HIR is badly formatted and type resolution dump is
not finished.
When we have a function that is for example a FieldAccessExpression the
compiler must resolve and compile that field into a reference which can be
called. This is not simple direct call to a function in that senario.
Fixes#217
When we compile if blocks the else gives us a final branch that can
resolve. Single IfExpr cannot resolve as there is no final branch.
This also fixes a small regression in compiling elif blocks where the
gimple body was empty.
Fixes#213
Further testing found regressions with implicit returns and type
resolution.
This unifies the type resolution in block expressions to be more strict
and ensure everything bar the final statement should be UnitType.
There is more work to be done here with adjustments to the self argument
such as borrows and mutability checking.
Method resolution is basic, for now there is code to scan for all possible
matches but traits are not supported at the moment so this resolves quite
simply for now.
Fixes#191#112
This is simply a type reference so we can use the name resolver to resolve
Self as a type reference back to the Type used for the impl block.
Fixes#204
We keep temporary's for each block in order for the result to be
referenced. For example:
let x = { test() + 1 };
This can be resolved into:
{
let x:i32;
_tmp1:i32;
{
_tmp2:i32 = test();
_tmp1 = _tmp2 + 1;
}
x = _tmp1;
}
Fixes#189
This supports basic function pointers in rust most of the code was already
there to infer this but this has now helped tidy it up and make it work.
Fixes#184
In order to assign to a name we must ensure the LHS is a valid expression
to assign to. This leads onto actually checking if this is a mutable
declaration or not.
Once these checks pass the name resolver we can in GIMPLE create immutable
types for these declarations to help with optimization.
Fixes#77
In order to properly handle all integer types and infer we must follow HM
algorithm. This means when we unify every type in the resolver this should
keep a chain of HirId of references such that when/if the type is resolved
it lookup tables can be updated for the Backend to compile to Gimple.
Consider the case:
fn test(x:u32) -> u32 {...}
let a = test(1);
The VarDecl here will have the type let a:<I?> = test<u32>(1<I?>).
Since this integer combines with the parameter x:u32 the type resolver
knows at this point these must be a u32.
let a;
a = 1;
let b:u32 = a;
This is more subtle
let a:<?>
a:<?> = 1<I?>
let b:u32 = a<I?>;
Since the integer inference variable combines with u32 all previous
references can be updated to u32 at this point.
In the basic case of:
let a;
a = 1;
This resolves down to:
let a:<I?>;
a<I?> = 1<I?>
It is not until we complete type-inference we can iterate all the
resolved types and HirIds and default any <I?> to i32 and any <F?> to f32.
Any remaining general inference variable are errors.
This expands the AST::CompoundAssignmentExpr into and HIR::AssignmentExpr
with the asignee being referenced for lhs and a new artificial
HIR::ArithmeticOrLogicalExpression with lhs asignee and rhs the rhs
of the original CompoundAssignment expr.
This is an example of a unary expression in gimple. The rules for enforcing
the types are observed in the type resolver here too.
Unary negate cannot be applied to bools but only integers and floats.
Unary not cannot be applied to floating points but can be applied to
integers and bools.
The input needed to be skipped once the operator was parsed to ensure
the lexer did not duplicate the operator. |= still fails but this looks
to be a parser problem.
When we use anything other than builtin types for returns or parameters
the type resolver was missing the NodeId mappings meaning it would
alawys fail to resolve them.
Then in gimple conversion we need to be able to reference the already
created RECORD types instead of always creating new instances.
This resolves each identifier for its respective field. It includes fixes
for the TypeResolver to print errors instead of asserts where we loose
decent debug info.
This adds in tuple struct support with name and type resolution. The
arguments and number of arguments are validated against. Test cases
added for those errors too.
The type resolver must ensure LHS for assignments where the LHS was
infered to be ? and the node mappings have a definition ID we know
the declaration id and can reassign the TyTy so further references know
its type.
... as used otherwise, in this file. And, this avoids:
[...]/source-gcc/gcc/rust/parse/rust-parse-impl.h:12243:72: error: could not convert '{false, true}' from '<brace-enclosed initializer list>' to 'Rust::ParseRestrictions'
= {/* can_be_struct_expr = */ false, /* entered_from_unary = */ true};
^
GCC doesn't like that:
In file included from [...]
./mm_malloc.h:42:12: error: attempt to use poisoned "malloc"
return malloc (__size);
^
See commit e7b3f654f2, for example.
This was using LetStmt->Pattern.as_string which included mut in the string
dump. This makes the gimple nodes harder to debug as the name is (mut a)
insteaad of a for example.
We must ensure the backend can support compilation of things declared
lexically after they are referenced. This scans the toplevel except
functions which are handled as we reference them. To make that generic
enough for all toplevel items will be a move to query based compilation
which still needs planning.
More testing is required but this adds tuples apart from TupleStructs
which are parsed as CallExpr. This will be the primitives required to
finish that work.
This change enforces strict type checkon on all ExprWithBlock. This
includes unreachable tail expressions. Specific test cases have been added
for context to ensure the failure cases are hit accordingly.
This change also improves the diagnostic errors for mismatched types
where the reference HirId was lost leading to default locations.
It is possible to assign and declare variables of unit-type which
translate down to zero sized void_type_node.
More work is needed to handle array and ADT types using unit-type
when emiting gimple. The name+type resolution should be generic enough.
This lead to cleanup of the name resolver as the usage of mappings means
that in a given rib if there are no references to a decl NodeId that
means it was not used.
To get on par with the offical rust compiler it should be allowed to have
a reference where the name was assigned but not used but this might be a seperate pass.
This means that paramters are scoped and shadowed correctly. Currently
the resolver is treating all paramters are shadowing each other if they
have the same name which is incorrect.
pattern first before the init expression. This lead to a situation
where shadowing rules were broken.
Example:
let x = 1;
let x = x + 1;
In this example the code was referencing the 2nd LetStmt as the resolved
name for the Identifier reference.
For implict returns we must consider cases with a block having multiple
returns:
HIR::BlockExpr Stmts {
...
return x
}
HIR::BlockExpr final_expression {
x + 1
}
Although the code above is bad this is valid rust code and the rust
compiler correctly identifies the final_expression as unreachable.
This dead code eliminiation is done as part of AST to HIR lowering.
Type resolution examines all blocks to identifiy if they terminate
a function with a return/final expression it must correspond accordngly.
If the block is the final block the resulting termination of the block
must match the return type of the function, else the block must conform
to unit type.
ArrayExpr, ArrayExprElems and ArrayIndexExpr. Still need to do
ArrayElemsCopied.
I expect there to be some changes to cleanup the rust-tyty-resolver
this code is to resolve all ribs within a scope but its getting a bit
hairy in there now.
When a new name is defined the name resolver freezes the previous
declartion such that all new references point to the latest decl.
This patch fixes a crash when we shadow and get a type mismatch and the
combination of types fails. See the failure test case for the crash.
resolved yet. Such as:
fn main() -> i32 { call() }
fn call() -> i32 { return 1; }
The compilation pass acts on the first function main and detects the other
node call is not compiled yet we can go resolve it. This is a toplevel
item since it has a local_def_id and therefore it has a NULL enclosing
scope for the block.
Fixes#72
Rust must examine each usage of a name and unify their types. For example:
let mut x;
x = 1
This means the declaration is determined to be an inference variable then
the assignment can be resolved to an Integer TyTy which can be combined
as part of the rules to now make the let x decl be an i32.
Resolution must implement the Gathering specified in the rust-dev guide.
We need to be able to handle cases such as:
let mut x;
x = 1;
or
let mut x = vec!{}
x.push(1)
Now the TyTy module has a combine abstract method to allow the combination
of types to condense down from their integral parts.
We can use the NodeId from the AST to generate apropriate mappings for all
names and types. Ribs are the scopes for names being instansiated, and
reference to defintion tables allows all names to be resolved to NodeId's.
Later on NodeIds will map over to HIR ids allowing for type resolution.
This is an IR based off the AST its almost a copy but with NodeMappings
on the parent Tree Types. This should ideally have all macro tree's
removed during the lowering process.
This is the start of a bigger refactor of the compiler to follow the
rustc internals. This introduces a mapping system for.
- HirId which maps to any Hir Node within the current crate
- LocalDefId any toplevel Hir Node HIR::Item within current crate
- NodeId maps any AST node akin to HirId such that they can map back
- DefId Cratea and localDefId combination
Fixed lack of AST:: prepending in rust-parse-impl.h - should prevent compilation error
Fixed expr renaming in Method as_string, should prevent compile error
Fixed issue with changing location accessibility for AST nodes
Fixed rust-compile.cc not using get_locus() instead of .locus
Rearranged order of definitions in rust-ast.h, should fix compile error
Attempted error fix for Attribute-AttrInput interaction and Crate stripping
Fixed constructor arguments for MacroExpander
We need to have test cases for when the compilation should xfail this will
help add more tests for name/type resolutions. This is needed as there is
a large code changes on the horizon and this will help spot regressions.
This adds type inferencing and validation for arrays such as:
let x: [i32, 5] = [1,2,3,4,5]
ley y = [1,2,3];
It checks that each element is of a valid type and they line up correctly.
There needs to be some refactoring of the type resolution to handle the
array index expressions so this is a good save point for now.
Addresses: #27#55
In the case where there is no init_expression for a variable declaration
and the type was defined on the name we dont need to then assign
that the variable was infered.
Debug for parsing failure with partially consolidated lifetime parsing
More debug for parsing failure
Corrected the apparent lack of skip_token in parse_lifetime_param()
First step toward consolidation of similar parsing functions (ComparisonExpr in this case)
Debug output for apparent parsing failure
Attempt to fix problem with non-digit character after 0 being mistaken as
non-decimal int literal
Attempt to fix incorrect tokenisation of a dot then a decimal
Try new implementation of token splitting rather than token replacing
Attempt to fix compile errors caused by make_shared with private constructor
Attempt to fix compile errors
Attempt to fix appearance of no characters in lexer
Minor changes to parse_non_decimal_int_literal to fix naming
Another minor fix regarding naming in lexer
More lexer refactoring to reduce size of build_token() method
This still requires more type resolution work to ensure field ordering
on the initilizer and defaults if required.
struct Foo struct_test;
try
{
struct_test.one = 1;
struct_test.two = 2;
}
finally
{
struct_test = {CLOBBER};
}
More work is required but it takes advantage of the vistior pattern
from the AST so we can do this without RTTI and dynamic_casts.
More passes on the AST AKA our HIR should follow this pattern.
Addresses: #12
Creation of basic target_os, target_env, target_vendor, and target_family for all GCC targets. Also target_cpu and target_features for i386 - will do target_features for other targets when I can find exactly what is considered a target_feature by rustc
Thanks for taking the time to contribute to GCC! Please be advised that if you are
viewing this on `github.com`, that the mirror there is unofficial and unmonitored.
The GCC community does not use `github.com` for their contributions. Instead, we use
a mailing list (`gcc-patches@gcc.gnu.org`) for code submissions, code reviews, and
bug reports. Please send patches there instead.
Thank you for making Rust GCC better!
If your PR fixes an issue, you can add "Fixes #issue_number" into this
PR description and the git commit message. This way the issue will be
automatically closed when your PR is merged. If your change addresses
an issue but does not fully fix it please mark it as "Addresses #issue_number"
in the git commit message.
Here is a checklist to help you with your PR.
- \[ ] GCC development requires copyright assignment or the Developer's Certificate of Origin sign-off, see https://gcc.gnu.org/contribute.html or https://gcc.gnu.org/dco.html
- \[ ] Read contributing guidlines
- \[ ] `make check-rust` passes locally
- \[ ] Run `clang-format`
- \[ ] Added any relevant test cases to `gcc/testsuite/rust/`
Note that you can skip the above if you are just opening a WIP PR in
order to get feedback.
---
*Please write a comment explaining your change. This is the message
../../../libgcc/soft-fp/fixdfbitint.c:51:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/fixdfbitint.c:51:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/fixdfbitint.c:57:22: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/fixdfbitint.c:57:22: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/fixdfbitint.c:61:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/fixdfbitint.c:61:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/fixsfbitint.c:51:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/fixsfbitint.c:51:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/fixsfbitint.c:57:22: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/fixsfbitint.c:57:22: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/fixsfbitint.c:61:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/fixsfbitint.c:61:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/fixtfbitint.c:61:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/fixtfbitint.c:61:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/fixtfbitint.c:67:22: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/fixtfbitint.c:67:22: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/fixtfbitint.c:71:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/fixtfbitint.c:71:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/fixxfbitint.c:62:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/fixxfbitint.c:62:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/fixxfbitint.c:68:22: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/fixxfbitint.c:68:22: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/fixxfbitint.c:72:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/fixxfbitint.c:72:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/op-common.h:1477:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/op-common.h:1477:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/op-common.h:1477:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/op-common.h:1477:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/op-common.h:1477:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/op-common.h:1477:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/op-common.h:1477:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/op-common.h:1477:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/op-common.h:1492:26: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/op-common.h:1492:26: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/op-common.h:1492:26: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/op-common.h:1492:26: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/op-common.h:1492:26: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/op-common.h:1492:26: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/op-common.h:1492:26: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/op-common.h:1492:26: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/op-common.h:1515:24: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/op-common.h:1515:24: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/op-common.h:1515:24: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/op-common.h:1515:24: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/op-common.h:1515:24: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/op-common.h:1515:24: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/op-common.h:1515:24: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/op-common.h:1515:24: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/op-common.h:1560:39: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/op-common.h:1560:39: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/op-common.h:1560:39: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/op-common.h:1560:39: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/op-common.h:1560:39: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/op-common.h:1560:39: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/op-common.h:1560:39: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/op-common.h:1560:39: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/op-common.h:1563:25: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/op-common.h:1563:25: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/op-common.h:1563:25: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/op-common.h:1563:25: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/op-common.h:1563:25: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/op-common.h:1563:25: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/op-common.h:1563:25: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libgcc/soft-fp/op-common.h:1563:25: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../gcc/../libgcc/libgcov-util.c:214:59: warning: 'void* calloc(size_t, size_t)' sizes specified with 'sizeof' in the earlier argument and not in the later argument [-Wcalloc-transposed-args]
../../gcc/../libgcc/libgcov-util.c:529:43: warning: 'void* calloc(size_t, size_t)' sizes specified with 'sizeof' in the earlier argument and not in the later argument [-Wcalloc-transposed-args]
../../gcc/analyzer/store.h:310:5: warning: 'size_in_bytes.generic_wide_int<fixed_wide_int_storage<128> >::fixed_wide_int_storage<128>.fixed_wide_int_storage<128>::val[1]' may be used uninitialized [-Wmaybe-uninitialized]
../../gcc/expmed.cc:1845:45: warning: '*(unsigned int*)((char*)&imode + offsetof(scalar_int_mode, scalar_int_mode::m_mode))' may be used uninitialized [-Wmaybe-uninitialized]
../../gcc/text-art/style.cc:150:25: warning: spurious leading punctuation sequence ';' in format [-Wformat-diag]
../../gcc/text-art/style.cc:160:25: warning: spurious leading punctuation sequence ';' in format [-Wformat-diag]
../../gcc/text-art/table.cc:981:62: warning: unquoted keyword 'char' in format [-Wformat-diag]
../../gcc/text-art/table.cc:981:69: warning: spurious trailing punctuation sequence '])' in format [-Wformat-diag]
gengtype-lex.cc:356:15: warning: this statement may fall through [-Wimplicit-fallthrough=]
gengtype-lex.cc:356:15: warning: this statement may fall through [-Wimplicit-fallthrough=]
gengtype-lex.cc:356:15: warning: this statement may fall through [-Wimplicit-fallthrough=]
gengtype-lex.cc:356:15: warning: this statement may fall through [-Wimplicit-fallthrough=]
libtool: install: warning: remember to run `libtool --finish /usr/local/libexec/gcc/i586-alpine-linux-musl/14.0.1'
../../../../libgcc/generic-morestack.c:397:16: warning: comparison of integer expressions of different signedness: ‘unsigned int’ and ‘long int’ [-Wsign-compare]
../../../../libgcc/soft-fp/fixdfbitint.c:51:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/fixdfbitint.c:51:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/fixdfbitint.c:57:22: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/fixdfbitint.c:57:22: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/fixdfbitint.c:61:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/fixdfbitint.c:61:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/fixsfbitint.c:51:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/fixsfbitint.c:51:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/fixsfbitint.c:57:22: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/fixsfbitint.c:57:22: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/fixsfbitint.c:61:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/fixsfbitint.c:61:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/fixtfbitint.c:61:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/fixtfbitint.c:61:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/fixtfbitint.c:67:22: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/fixtfbitint.c:67:22: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/fixtfbitint.c:71:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/fixtfbitint.c:71:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/fixxfbitint.c:62:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/fixxfbitint.c:62:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/fixxfbitint.c:68:22: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/fixxfbitint.c:68:22: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/fixxfbitint.c:72:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/fixxfbitint.c:72:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1477:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1477:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1477:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1477:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1477:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1477:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1477:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1477:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1492:26: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1492:26: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1492:26: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1492:26: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1492:26: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1492:26: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1492:26: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1492:26: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1515:24: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1515:24: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1515:24: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1515:24: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1515:24: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1515:24: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1515:24: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1515:24: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1560:39: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1560:39: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1560:39: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1560:39: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1560:39: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1560:39: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1560:39: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1560:39: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1563:25: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1563:25: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1563:25: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1563:25: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1563:25: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1563:25: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1563:25: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1563:25: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libcpp/expr.cc:842:35: warning: format not a string literal and no format arguments [-Wformat-security]
../../../libcpp/expr.cc:845:38: warning: format not a string literal and no format arguments [-Wformat-security]
../../../libcpp/expr.cc:855:33: warning: format not a string literal and no format arguments [-Wformat-security]
../../../libcpp/expr.cc:867:42: warning: format not a string literal and no format arguments [-Wformat-security]
../../../libcpp/expr.cc:870:39: warning: format not a string literal and no format arguments [-Wformat-security]
../../../libcpp/expr.cc:877:35: warning: format not a string literal and no format arguments [-Wformat-security]
../../../libcpp/macro.cc:185:26: warning: format not a string literal and no format arguments [-Wformat-security]
../../../libcpp/macro.cc:214:34: warning: format not a string literal and no format arguments [-Wformat-security]
../../../libcpp/macro.cc:3710:25: warning: format not a string literal and no format arguments [-Wformat-security]
../../../libcpp/macro.cc:3725:25: warning: format not a string literal and no format arguments [-Wformat-security]
../../gcc/analyzer/program-state.cc:1498:15: warning: format not a string literal and no format arguments [-Wformat-security]
../../gcc/c-family/c-common.cc:6763:14: warning: format not a string literal and no format arguments [-Wformat-security]
../../gcc/c-family/c-common.cc:6767:16: warning: format not a string literal and no format arguments [-Wformat-security]
../../gcc/c/c-convert.cc:84:13: warning: format not a string literal and no format arguments [-Wformat-security]
../../gcc/c/c-typeck.cc:12453:16: warning: format not a string literal and no format arguments [-Wformat-security]
../../gcc/c/c-typeck.cc:3878:17: warning: format not a string literal and no format arguments [-Wformat-security]
../../gcc/c/c-typeck.cc:4648:16: warning: format not a string literal and no format arguments [-Wformat-security]
../../gcc/c/c-typeck.cc:6913:23: warning: format not a string literal and no format arguments [-Wformat-security]
../../gcc/collect-utils.cc:237:21: warning: format not a string literal and no format arguments [-Wformat-security]
../../gcc/collect2.cc:2400:21: warning: format not a string literal and no format arguments [-Wformat-security]
../../gcc/diagnostic.cc:2316:15: warning: format not a string literal and no format arguments [-Wformat-security]
../../gcc/fold-const.cc:384:13: warning: format not a string literal and no format arguments [-Wformat-security]
../../gcc/gcc.cc:2412:30: warning: too many arguments for format [-Wformat-extra-args]
../../gcc/gcc.cc:2413:32: warning: unknown conversion type character ‘t’ in format [-Wformat=]
../../gcc/gcc.cc:2432:30: warning: too many arguments for format [-Wformat-extra-args]
../../gcc/gcc.cc:2433:32: warning: unknown conversion type character ‘t’ in format [-Wformat=]
../../gcc/gcc.cc:2458:30: warning: too many arguments for format [-Wformat-extra-args]
../../gcc/gcc.cc:2459:32: warning: unknown conversion type character ‘t’ in format [-Wformat=]
../../gcc/gcc.cc:2467:30: warning: too many arguments for format [-Wformat-extra-args]
../../gcc/gcc.cc:2468:32: warning: unknown conversion type character ‘t’ in format [-Wformat=]
../../gcc/gcc.cc:2477:30: warning: too many arguments for format [-Wformat-extra-args]
../../gcc/gcc.cc:2478:32: warning: unknown conversion type character ‘t’ in format [-Wformat=]
../../gcc/gcc.cc:2487:30: warning: too many arguments for format [-Wformat-extra-args]
../../gcc/gcc.cc:2488:32: warning: unknown conversion type character ‘t’ in format [-Wformat=]
../../gcc/gcc.cc:2527:26: warning: too many arguments for format [-Wformat-extra-args]
../../gcc/gcc.cc:2527:59: warning: unknown conversion type character ‘t’ in format [-Wformat=]
../../gcc/gcc.cc:2539:22: warning: too many arguments for format [-Wformat-extra-args]
../../gcc/gcc.cc:2539:51: warning: unknown conversion type character ‘t’ in format [-Wformat=]
../../gcc/gcc.cc:2553:22: warning: too many arguments for format [-Wformat-extra-args]
../../gcc/gcc.cc:2553:51: warning: unknown conversion type character ‘t’ in format [-Wformat=]
../../gcc/gimple-range-gori.cc:318:19: warning: format not a string literal and no format arguments [-Wformat-security]
../../gcc/ipa-devirt.cc:967:10: warning: format not a string literal and no format arguments [-Wformat-security]
../../gcc/lto-wrapper.cc:1369:10: warning: format not a string literal and no format arguments [-Wformat-security]
../../gcc/lto-wrapper.cc:1971:23: warning: format not a string literal and no format arguments [-Wformat-security]
../../gcc/text-art/style.cc:150:25: warning: spurious leading punctuation sequence ‘;’ in format [-Wformat-diag]
../../gcc/text-art/style.cc:160:25: warning: spurious leading punctuation sequence ‘;’ in format [-Wformat-diag]
../../gcc/text-art/table.cc:981:62: warning: unquoted keyword ‘char’ in format [-Wformat-diag]
../../gcc/text-art/table.cc:981:69: warning: spurious trailing punctuation sequence ‘])’ in format [-Wformat-diag]
../../gcc/tree-ssa-sccvn.cc:286:21: warning: format not a string literal and no format arguments [-Wformat-security]
../../libcpp/expr.cc:842:35: warning: format not a string literal and no format arguments [-Wformat-security]
../../libcpp/expr.cc:845:38: warning: format not a string literal and no format arguments [-Wformat-security]
../../libcpp/expr.cc:855:33: warning: format not a string literal and no format arguments [-Wformat-security]
../../libcpp/expr.cc:867:42: warning: format not a string literal and no format arguments [-Wformat-security]
../../libcpp/expr.cc:870:39: warning: format not a string literal and no format arguments [-Wformat-security]
../../libcpp/expr.cc:877:35: warning: format not a string literal and no format arguments [-Wformat-security]
../../libcpp/macro.cc:185:26: warning: format not a string literal and no format arguments [-Wformat-security]
../../libcpp/macro.cc:214:34: warning: format not a string literal and no format arguments [-Wformat-security]
../../libcpp/macro.cc:3710:25: warning: format not a string literal and no format arguments [-Wformat-security]
../../libcpp/macro.cc:3725:25: warning: format not a string literal and no format arguments [-Wformat-security]
/home/runner/work/gccrs/gccrs/gccrs-build/x86_64-pc-linux-gnu/32/libssp/../../../../libssp/gets-chk.c:73: warning: the `gets' function is dangerous and should not be used.
/home/runner/work/gccrs/gccrs/gccrs-build/x86_64-pc-linux-gnu/libssp/../../../libssp/gets-chk.c:73: warning: the `gets' function is dangerous and should not be used.
gengtype-lex.cc:357:15: warning: this statement may fall through [-Wimplicit-fallthrough=]
gengtype-lex.cc:357:15: warning: this statement may fall through [-Wimplicit-fallthrough=]
gengtype-lex.cc:357:15: warning: this statement may fall through [-Wimplicit-fallthrough=]
gengtype-lex.cc:357:15: warning: this statement may fall through [-Wimplicit-fallthrough=]
install.texi:2236: warning: `.' or `,' must follow @xref, not f
libtool: install: warning: remember to run `libtool --finish /usr/local/libexec/gcc/x86_64-pc-linux-gnu/14.0.1'
../../../../libgcc/generic-morestack.c:397:16: warning: comparison of integer expressions of different signedness: ‘unsigned int’ and ‘long int’ [-Wsign-compare]
../../../../libgcc/soft-fp/fixdfbitint.c:51:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/fixdfbitint.c:51:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/fixdfbitint.c:57:22: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/fixdfbitint.c:57:22: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/fixdfbitint.c:61:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/fixdfbitint.c:61:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/fixsfbitint.c:51:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/fixsfbitint.c:51:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/fixsfbitint.c:57:22: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/fixsfbitint.c:57:22: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/fixsfbitint.c:61:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/fixsfbitint.c:61:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/fixtfbitint.c:61:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/fixtfbitint.c:61:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/fixtfbitint.c:67:22: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/fixtfbitint.c:67:22: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/fixtfbitint.c:71:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/fixtfbitint.c:71:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/fixxfbitint.c:62:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/fixxfbitint.c:62:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/fixxfbitint.c:68:22: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/fixxfbitint.c:68:22: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/fixxfbitint.c:72:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/fixxfbitint.c:72:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1477:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1477:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1477:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1477:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1477:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1477:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1477:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1477:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1492:26: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1492:26: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1492:26: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1492:26: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1492:26: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1492:26: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1492:26: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1492:26: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1515:24: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1515:24: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1515:24: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1515:24: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1515:24: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1515:24: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1515:24: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1515:24: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1560:39: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1560:39: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1560:39: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1560:39: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1560:39: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1560:39: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1560:39: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1560:39: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1563:25: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1563:25: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1563:25: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1563:25: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1563:25: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1563:25: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1563:25: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../../libgcc/soft-fp/op-common.h:1563:25: warning: comparison of integer expressions of different signedness: ‘int’ and ‘USItype’ {aka ‘unsigned int’} [-Wsign-compare]
../../../libcpp/expr.cc:842:35: warning: format not a string literal and no format arguments [-Wformat-security]
../../../libcpp/expr.cc:845:38: warning: format not a string literal and no format arguments [-Wformat-security]
../../../libcpp/expr.cc:855:33: warning: format not a string literal and no format arguments [-Wformat-security]
../../../libcpp/expr.cc:867:42: warning: format not a string literal and no format arguments [-Wformat-security]
../../../libcpp/expr.cc:870:39: warning: format not a string literal and no format arguments [-Wformat-security]
../../../libcpp/expr.cc:877:35: warning: format not a string literal and no format arguments [-Wformat-security]
../../../libcpp/lex.cc:2120:39: warning: ‘loc’ may be used uninitialized [-Wmaybe-uninitialized]
../../../libcpp/macro.cc:185:26: warning: format not a string literal and no format arguments [-Wformat-security]
../../../libcpp/macro.cc:214:34: warning: format not a string literal and no format arguments [-Wformat-security]
../../../libcpp/macro.cc:3710:25: warning: format not a string literal and no format arguments [-Wformat-security]
../../../libcpp/macro.cc:3725:25: warning: format not a string literal and no format arguments [-Wformat-security]
../../c++tools/server.cc:490:11: warning: ignoring return value of ‘ssize_t write(int, const void*, size_t)’ declared with attribute ‘warn_unused_result’ [-Wunused-result]
../../c++tools/server.cc:620:10: warning: ignoring return value of ‘int pipe(int*)’ declared with attribute ‘warn_unused_result’ [-Wunused-result]
../../gcc/../libgcc/libgcov-util.c:455:9: warning: ignoring return value of ‘int chdir(const char*)’ declared with attribute ‘warn_unused_result’ [-Wunused-result]
../../gcc/analyzer/program-state.cc:1498:15: warning: format not a string literal and no format arguments [-Wformat-security]
../../gcc/analyzer/store.h:310:5: warning: ‘size_in_bytes.generic_wide_int<fixed_wide_int_storage<128> >::<anonymous>.fixed_wide_int_storage<128>::val[1]’ may be used uninitialized [-Wmaybe-uninitialized]
../../gcc/c-family/c-common.cc:6763:14: warning: format not a string literal and no format arguments [-Wformat-security]
../../gcc/c-family/c-common.cc:6767:16: warning: format not a string literal and no format arguments [-Wformat-security]
../../gcc/c/c-convert.cc:84:13: warning: format not a string literal and no format arguments [-Wformat-security]
../../gcc/c/c-typeck.cc:12453:16: warning: format not a string literal and no format arguments [-Wformat-security]
../../gcc/c/c-typeck.cc:3878:17: warning: format not a string literal and no format arguments [-Wformat-security]
../../gcc/c/c-typeck.cc:4648:16: warning: format not a string literal and no format arguments [-Wformat-security]
../../gcc/c/c-typeck.cc:6913:23: warning: format not a string literal and no format arguments [-Wformat-security]
../../gcc/collect-utils.cc:237:21: warning: format not a string literal and no format arguments [-Wformat-security]
../../gcc/collect2.cc:2400:21: warning: format not a string literal and no format arguments [-Wformat-security]
../../gcc/diagnostic.cc:2316:15: warning: format not a string literal and no format arguments [-Wformat-security]
../../gcc/expmed.cc:1845:45: warning: ‘*(unsigned int*)((char*)&imode + offsetof(scalar_int_mode, scalar_int_mode::m_mode))’ may be used uninitialized in this function [-Wmaybe-uninitialized]
../../gcc/fold-const.cc:384:13: warning: format not a string literal and no format arguments [-Wformat-security]
../../gcc/gcc.cc:10668:12: warning: ignoring return value of ‘ssize_t read(int, void*, size_t)’ declared with attribute ‘warn_unused_result’ [-Wunused-result]
../../gcc/gcc.cc:2412:30: warning: too many arguments for format [-Wformat-extra-args]
../../gcc/gcc.cc:2413:32: warning: unknown conversion type character ‘t’ in format [-Wformat=]
../../gcc/gcc.cc:2432:30: warning: too many arguments for format [-Wformat-extra-args]
../../gcc/gcc.cc:2433:32: warning: unknown conversion type character ‘t’ in format [-Wformat=]
../../gcc/gcc.cc:2458:30: warning: too many arguments for format [-Wformat-extra-args]
../../gcc/gcc.cc:2459:32: warning: unknown conversion type character ‘t’ in format [-Wformat=]
../../gcc/gcc.cc:2467:30: warning: too many arguments for format [-Wformat-extra-args]
../../gcc/gcc.cc:2468:32: warning: unknown conversion type character ‘t’ in format [-Wformat=]
../../gcc/gcc.cc:2477:30: warning: too many arguments for format [-Wformat-extra-args]
../../gcc/gcc.cc:2478:32: warning: unknown conversion type character ‘t’ in format [-Wformat=]
../../gcc/gcc.cc:2487:30: warning: too many arguments for format [-Wformat-extra-args]
../../gcc/gcc.cc:2488:32: warning: unknown conversion type character ‘t’ in format [-Wformat=]
../../gcc/gcc.cc:2527:26: warning: too many arguments for format [-Wformat-extra-args]
../../gcc/gcc.cc:2527:59: warning: unknown conversion type character ‘t’ in format [-Wformat=]
../../gcc/gcc.cc:2539:22: warning: too many arguments for format [-Wformat-extra-args]
../../gcc/gcc.cc:2539:51: warning: unknown conversion type character ‘t’ in format [-Wformat=]
../../gcc/gcc.cc:2553:22: warning: too many arguments for format [-Wformat-extra-args]
../../gcc/gcc.cc:2553:51: warning: unknown conversion type character ‘t’ in format [-Wformat=]
../../gcc/gcc.cc:7897:9: warning: ignoring return value of ‘ssize_t write(int, const void*, size_t)’ declared with attribute ‘warn_unused_result’ [-Wunused-result]
../../gcc/gcc.cc:7900:13: warning: ignoring return value of ‘ssize_t write(int, const void*, size_t)’ declared with attribute ‘warn_unused_result’ [-Wunused-result]
../../gcc/gcc.cc:7901:13: warning: ignoring return value of ‘ssize_t write(int, const void*, size_t)’ declared with attribute ‘warn_unused_result’ [-Wunused-result]
../../gcc/gcc.cc:7903:9: warning: ignoring return value of ‘ssize_t write(int, const void*, size_t)’ declared with attribute ‘warn_unused_result’ [-Wunused-result]
../../gcc/genhooks.cc:112:17: warning: ignoring return value of ‘int fscanf(FILE*, const char*, ...)’ declared with attribute ‘warn_unused_result’ [-Wunused-result]
../../gcc/genhooks.cc:121:14: warning: ignoring return value of ‘int fscanf(FILE*, const char*, ...)’ declared with attribute ‘warn_unused_result’ [-Wunused-result]
../../gcc/genhooks.cc:174:14: warning: ignoring return value of ‘int fscanf(FILE*, const char*, ...)’ declared with attribute ‘warn_unused_result’ [-Wunused-result]
../../gcc/genhooks.cc:180:14: warning: ignoring return value of ‘int fscanf(FILE*, const char*, ...)’ declared with attribute ‘warn_unused_result’ [-Wunused-result]
../../gcc/gimple-range-gori.cc:318:19: warning: format not a string literal and no format arguments [-Wformat-security]
../../gcc/ipa-devirt.cc:967:10: warning: format not a string literal and no format arguments [-Wformat-security]
../../gcc/lto-wrapper.cc:1151:8: warning: ignoring return value of ‘ssize_t read(int, void*, size_t)’ declared with attribute ‘warn_unused_result’ [-Wunused-result]
../../gcc/lto-wrapper.cc:1369:10: warning: format not a string literal and no format arguments [-Wformat-security]
../../gcc/lto-wrapper.cc:1971:23: warning: format not a string literal and no format arguments [-Wformat-security]
../../gcc/lto/lto-common.cc:2084:10: warning: ignoring return value of ‘int fscanf(FILE*, const char*, ...)’ declared with attribute ‘warn_unused_result’ [-Wunused-result]
../../gcc/lto/lto-common.cc:2086:9: warning: ignoring return value of ‘size_t fread(void*, size_t, size_t, FILE*)’ declared with attribute ‘warn_unused_result’ [-Wunused-result]
../../gcc/lto/lto-common.cc:2106:10: warning: ignoring return value of ‘int fscanf(FILE*, const char*, ...)’ declared with attribute ‘warn_unused_result’ [-Wunused-result]
../../gcc/text-art/style.cc:150:25: warning: spurious leading punctuation sequence ‘;’ in format [-Wformat-diag]
../../gcc/text-art/style.cc:160:25: warning: spurious leading punctuation sequence ‘;’ in format [-Wformat-diag]
../../gcc/text-art/table.cc:981:62: warning: unquoted keyword ‘char’ in format [-Wformat-diag]
../../gcc/text-art/table.cc:981:69: warning: spurious trailing punctuation sequence ‘])’ in format [-Wformat-diag]
../../gcc/tree-ssa-sccvn.cc:286:21: warning: format not a string literal and no format arguments [-Wformat-security]
../../gcc/tree-vect-stmts.cc:10397:47: warning: ‘stride_step’ may be used uninitialized in this function [-Wmaybe-uninitialized]
../../gcc/vec.h:347:10: warning: ‘void free(void*)’ called on unallocated object ‘dest_bbs’ [-Wfree-nonheap-object]
../../libcpp/expr.cc:842:35: warning: format not a string literal and no format arguments [-Wformat-security]
../../libcpp/expr.cc:845:38: warning: format not a string literal and no format arguments [-Wformat-security]
../../libcpp/expr.cc:855:33: warning: format not a string literal and no format arguments [-Wformat-security]
../../libcpp/expr.cc:867:42: warning: format not a string literal and no format arguments [-Wformat-security]
../../libcpp/expr.cc:870:39: warning: format not a string literal and no format arguments [-Wformat-security]
../../libcpp/expr.cc:877:35: warning: format not a string literal and no format arguments [-Wformat-security]
../../libcpp/lex.cc:2120:39: warning: ‘loc’ may be used uninitialized [-Wmaybe-uninitialized]
../../libcpp/macro.cc:185:26: warning: format not a string literal and no format arguments [-Wformat-security]
../../libcpp/macro.cc:214:34: warning: format not a string literal and no format arguments [-Wformat-security]
../../libcpp/macro.cc:3710:25: warning: format not a string literal and no format arguments [-Wformat-security]
../../libcpp/macro.cc:3725:25: warning: format not a string literal and no format arguments [-Wformat-security]
/home/runner/work/gccrs/gccrs/gccrs-build/x86_64-pc-linux-gnu/32/libssp/../../../../libssp/gets-chk.c:73: warning: the `gets' function is dangerous and should not be used.
/home/runner/work/gccrs/gccrs/gccrs-build/x86_64-pc-linux-gnu/libssp/../../../libssp/gets-chk.c:73: warning: the `gets' function is dangerous and should not be used.
gengtype-lex.cc:357:15: warning: this statement may fall through [-Wimplicit-fallthrough=]
gengtype-lex.cc:357:15: warning: this statement may fall through [-Wimplicit-fallthrough=]
gengtype-lex.cc:357:15: warning: this statement may fall through [-Wimplicit-fallthrough=]
gengtype-lex.cc:357:15: warning: this statement may fall through [-Wimplicit-fallthrough=]
install.texi:2236: warning: `.' or `,' must follow @xref, not f
libtool: install: warning: remember to run `libtool --finish /usr/local/libexec/gcc/x86_64-pc-linux-gnu/14.0.1'
* **Ensure the bug was not already reported** by searching on GitHub under [Issues](https://github.com/Rust-GCC/gccrs/issues).
* If you're unable to find an open issue addressing the problem, [open a new one](https://github.com/Rust-GCC/gccrs/issues/new).
* If you're unable to find an open issue addressing the problem,
[open a new one](https://github.com/Rust-GCC/gccrs/issues/new).
Be sure to include a **title and clear description**, as much relevant information as possible, and a **code sample**
or an **executable test case** demonstrating the expected behavior that is not occurring.
@@ -15,7 +16,8 @@
* Ensure the PR description clearly describes the problem and solution. Include the relevant issue number if applicable.
* Before submitting, GCC development requires copyright assignment or the Developer's Certificate of Origin sign-off.
Please see the [Contributing to GCC](https://gcc.gnu.org/contribute.html) guide or [Developer's Certificate of Origin (DCO) Sign-off](https://gcc.gnu.org/dco.html) guide.
Please see the [Contributing to GCC](https://gcc.gnu.org/contribute.html) guide or
[Developer's Certificate of Origin (DCO) Sign-off](https://gcc.gnu.org/dco.html) guide.
* Patches sent to the [`gcc-rust` mailing list](https://gcc.gnu.org/mailman/listinfo/gcc-rust) are likewise welcome.
These will be imported into a GitHub PR to follow the normal review process,
@@ -37,7 +39,7 @@ and the link to the GitHub PR sent to the submitter.
* The PR policy: Everything has to go through a PR
- An exception to this rule will be the merge commits of updating the repo against upstream GCC
* Reviewers/Maintainers of the project (aka people who have bors rights) should be pinged for reviews/questions.
* Reviewers/Maintainers of the project should be pinged for reviews/questions.
* A PR can have one or several commits (split should have a technical/logical reason, ie. no fixup-ish commit)
You can also setup your shell to automatically find the installed compiler. For example for `bash`,
@@ -210,7 +222,8 @@ If you want to contribute to GCC Rust, you can find more information in [CONTRIB
Please be aware this project is designed to be pushed upstream to GCC when we reach some milestones,
and this means we require copyright assignment or the Developer's Certificate of Origin sign-off.
Please see the [Contributing to GCC](https://gcc.gnu.org/contribute.html) guide or [Developer's Certificate of Origin (DCO) Sign-off](https://gcc.gnu.org/dco.html) guide.
Please see the [Contributing to GCC](https://gcc.gnu.org/contribute.html) guide or
[Developer's Certificate of Origin (DCO) Sign-off](https://gcc.gnu.org/dco.html) guide.
Not all contributions must be code; we would love to see new test cases or bugs and issues to be reported.
Feel free to add any comments on open PRs
@@ -247,7 +260,7 @@ With that, we're missing out on the aspect that _enforces that GCC compiles with
To encounter that, the default CI has a [_check for new warnings_ step](https://github.com/Rust-GCC/gccrs/pull/1026)
that verifies in the CI `--disable-bootstrap` build configuration that no new warnings are introduced.
If that step fails, it usually points out a new _warning_ you've introduced erroneously, and should address.
Occasionally it means that simply the `.github/bors_log_expected_warnings` file needs to be updated,
Occasionally it means that simply the `.github/log_expected_warnings` file needs to be updated,
for example if due to any kind of "environmental changes" (for example, CI "initial" compiler changes).
Unless diligently reproducing the CI configuration (in particular "initial" compiler, GCC version),
it's not really feasible to reproduce this check locally.
Some files were not shown because too many files have changed in this diff
Show More
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.