Compare commits

...

4863 Commits

Author SHA1 Message Date
Arthur Cohen
7e42c1ee80 const-block: Add testcase
gcc/testsuite/ChangeLog:

	* rust/execute/torture/const_block1.rs: New test.
2025-05-27 11:18:07 +00:00
Arthur Cohen
70fab4b0ce hir: Add const blocks
gcc/rust/ChangeLog:

	* hir/tree/rust-hir-expr.h: New classes.
	* hir/tree/rust-hir-full-decls.h: Likewise.
	* hir/tree/rust-hir.cc: Handle AnonConst and ConstBlock.
	* backend/rust-compile-block.cc: Likewise.
	* backend/rust-compile-block.h: Likewise.
	* backend/rust-compile-expr.cc (CompileExpr::visit): Likewise.
	* backend/rust-compile-expr.h: Likewise.
	* checks/errors/borrowck/rust-bir-builder-expr-stmt.cc (ExprStmtBuilder::visit): Likewise.
	* checks/errors/borrowck/rust-bir-builder-expr-stmt.h: Likewise.
	* checks/errors/borrowck/rust-bir-builder-lazyboolexpr.h: Likewise.
	* 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: Likewise.
	* checks/errors/rust-const-checker.cc (ConstChecker::visit): Likewise.
	* checks/errors/rust-const-checker.h: Likewise.
	* checks/errors/rust-hir-pattern-analysis.cc (PatternChecker::visit): Likewise.
	* checks/errors/rust-hir-pattern-analysis.h: Likewise.
	* checks/errors/rust-unsafe-checker.cc (UnsafeChecker::visit): Likewise.
	* checks/errors/rust-unsafe-checker.h: Likewise.
	* hir/rust-ast-lower-expr.cc (ASTLoweringExpr::visit): Likewise.
	(translate_operand_out): Likewise.
	(translate_operand_inout): Likewise.
	(translate_operand_const): Likewise.
	* hir/rust-ast-lower-expr.h: Likewise.
	* hir/rust-hir-dump.cc (Dump::visit): Likewise.
	* hir/rust-hir-dump.h: Likewise.
	* hir/tree/rust-hir-expr-abstract.h: Likewise.
	* hir/tree/rust-hir-expr.cc (AnonConst::AnonConst): Likewise.
	(AnonConst::operator=): Likewise.
	(ConstBlock::ConstBlock): Likewise.
	(ConstBlock::operator=): Likewise.
	* hir/tree/rust-hir-visitor.h:
	* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit): Likewise.
	(typecheck_inline_asm_operand): Likewise.
	* typecheck/rust-hir-type-check-expr.h: Likewise.
2025-05-27 11:18:07 +00:00
Arthur Cohen
01b433d67a parser: Add base for parsing const blocks
gcc/rust/ChangeLog:

	* parse/rust-parse-impl.h (Parser::parse_const_block_expr): New function.
	* parse/rust-parse.h: Declare it.
2025-05-27 11:18:07 +00:00
Arthur Cohen
81836d3528 ast: Add ConstBlock and AnonConst nodes
gcc/rust/ChangeLog:

	* ast/rust-expr.h: Declare AnonConst and ConstBlock and use them.
	* ast/rust-ast-full-decls.h: Likewise.
	* ast/rust-ast.cc: Add implementation for AnonConst and ConstBlock.
	* ast/rust-ast.h: Likewise.
	* ast/rust-ast-collector.cc (TokenCollector::visit): Likewise.
	* ast/rust-ast-collector.h: Likewise.
	* ast/rust-ast-visitor.cc (DefaultASTVisitor::visit): Likewise.
	* ast/rust-ast-visitor.h: 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-expr.cc (translate_operand_const): Likewise.
	* resolve/rust-ast-resolve-base.cc (ResolverBase::visit): Likewise.
	* resolve/rust-ast-resolve-base.h: Likewise.
	* resolve/rust-ast-resolve-expr.h: Likewise.
	* resolve/rust-ast-resolve-expr.cc: Likewise.
2025-05-27 11:18:07 +00:00
Philip Herron
c77c3494f8 gccrs: Always emit the error highest in the type hierarchy
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>
2025-05-27 09:27:15 +00:00
Owen Avery
ba32a6e460 nr2.0: Fix IfLet pattern handling
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>
2025-05-27 08:08:14 +00:00
Owen Avery
57a1b01347 Adjust included headers in rust-lang.cc
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>
2025-05-27 08:06:47 +00:00
Philip Herron
a497ed0835 gccrs: Initial support for Return Position Impl Trait
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>
2025-05-26 19:18:47 +00:00
Philip Herron
b401e72ba5 gccrs: Fix non canonical type bug with tuples
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>
2025-05-26 19:18:47 +00:00
Philip Herron
894e6951cf gccrs: Remove unneeded clones untill we have an arena allocator for these tmps
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>
2025-05-26 18:09:21 +00:00
Philip Herron
457b3d1e29 gccrs: refactor default infer vars to be its own function
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>
2025-05-26 18:09:16 +00:00
Owen Avery
c087dd8bb0 nr2.0: Fix some paths in test files
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>
2025-05-23 14:46:49 +00:00
Owen Avery
d188df1814 nr2.0: Fix test builtin_abort.rs
gcc/testsuite/ChangeLog:

	* rust/execute/torture/builtin_abort.rs: Fix path to
	intrinsics::abort.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2025-05-23 14:43:39 +00:00
Tom Schollenberger
f870c29e2c gccrs: Fix NR2 ICE in visit_attributes
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>
2025-05-19 09:42:09 +00:00
Owen Avery
2dc57afa16 Remove rvalue reference binding
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>
2025-05-19 09:35:05 +00:00
Owen Avery
4f772da8df Small improvements to DefaultASTVisitor and nr2.0
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>
2025-05-15 10:32:23 +00:00
Marc Poulhiès
7a562bcec1 gccrs: remove unused file
gcc/rust/ChangeLog:

	* Make-lang.in (GRS_OBJS): Remove rust-macro.o.
	* ast/rust-macro.cc: Removed.

Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
2025-05-14 15:47:03 +00:00
Owen Avery
dceaabbe55 Fix Attr metavariable binding
gcc/rust/ChangeLog:

	* parse/rust-parse-impl.h
	(Parser::parse_attr_input): Handle more delimeter tokens and the
	END_OF_FILE token.
	(Parser::skip_after_end_attribute): Handle the END_OF_FILE
	token.

gcc/testsuite/ChangeLog:

	* rust/compile/macros/mbe/meta-param.rs: New test.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2025-05-13 09:29:13 +00:00
Owen Avery
f33bae65a1 Fix test same_field_name.rs
gcc/rust/ChangeLog:

	* hir/rust-ast-lower-item.cc
	(ASTLoweringItem::visit): Keep going after a duplicate field is
	found.

gcc/testsuite/ChangeLog:

	* rust/execute/same_field_name.rs: Move to...
	* rust/compile/same_field_name.rs: ...here and adjust expected
	errors.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2025-05-13 09:20:07 +00:00
Owen Avery
dfc026ce0a nr2.0: Fix borrow checking
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>
2025-05-13 09:18:03 +00:00
Philip Herron
4e63248e89 gccrs: We cant clone types as it will dup the node-id
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>
2025-05-13 09:16:28 +00:00
Marc Poulhiès
0d56350755 gccrs: Adapt attribute lang hook and do some cleanup
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>
2025-05-09 18:47:19 +00:00
Owen Avery
d90770b538 nr2.0: Adjust resolution of impl items
gcc/rust/ChangeLog:

	* ast/rust-path.cc
	(TypePath::make_debug_string): Add definition.
	* ast/rust-path.h
	(TypePath::make_debug_string): Add declaration.
	* resolve/rust-default-resolver.cc
	(DefaultResolver::visit): Adjust InherentImpl and TraitImpl
	visitors to better handle associated item scope.
	* resolve/rust-default-resolver.h
	(DefaultResolver::maybe_insert_big_self): Add.
	* resolve/rust-late-name-resolver-2.0.cc
	(Late::visit): Adjust type path resolution errors.
	* resolve/rust-rib.h
	(Rib::Kind): Add Generics kind.
	* resolve/rust-toplevel-name-resolver-2.0.cc
	(TopLevel::visit): Remove InherentImpl and TraitImpl visitor
	overrides.
	(TopLevel::maybe_insert_big_self): Add override in order to add
	a definition of 'Self'.
	* resolve/rust-toplevel-name-resolver-2.0.h
	(TopLevel::visit): Remove InherentImpl and TraitImpl visitor
	overrides.
	(TopLevel::maybe_insert_big_self): Add override.

gcc/testsuite/ChangeLog:

	* rust/compile/nr2/exclude: Remove entries.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2025-05-08 15:39:40 +00:00
0xn4utilus
dd3de3f0e5 ast: collector: visit InlineAsm node during ast dump
gcc/rust/ChangeLog:

	* ast/rust-ast-collector.cc (TokenCollector::visit): Implement for InlineAsm.
	* ast/rust-ast-full-decls.h (enum class): Move InlineAsmOption enum inside InlineAsm.
	* ast/rust-expr.h (enum class): Likewise.
	(class InlineAsm): Likewise.
	* expand/rust-macro-builtins-asm.cc (check_and_set): Likewise.
	(parse_options): Likewise.
	* expand/rust-macro-builtins-asm.h (check_and_set): Likewise.
	* hir/tree/rust-hir-expr.cc (InlineAsm::InlineAsm): Likewise.
	* hir/tree/rust-hir-expr.h: Likewise.
	* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit): Likewise.
2025-05-08 15:38:58 +00:00
Tom Schollenberger
339415a5a8 gccrs: fix ICE on empty constexpr loops
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>
2025-05-08 15:37:43 +00:00
Philip Herron
fc6b543657 gccrs: Prevent passing generic arguments to impl traits in argument position
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>
2025-05-08 09:01:20 +00:00
Owen Avery
11d46d45c3 nr2.0: Adjust enum item visitors
gcc/rust/ChangeLog:

	* ast/rust-ast-visitor.cc
	(DefaultASTVisitor::visit): Make call to EnumItem visitor from
	EnumItem derived class visitors non-virtual.
	* ast/rust-collect-lang-items.cc
	(CollectLangItems::visit): Handle visitation of classes derived
	from EnumItem.
	* ast/rust-collect-lang-items.h
	(CollectLangItems::visit): Likewise.
	* resolve/rust-toplevel-name-resolver-2.0.cc
	(TopLevel::visit): Call DefaultResolver::visit on EnumItem
	instances.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2025-05-07 15:42:12 +00:00
Owen Avery
23f933b90b Improve struct pattern compilation
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>
2025-05-07 15:34:59 +00:00
Owen Avery
8592769349 Revert "backend: Remove checks on StructFieldIdentPattern"
This reverts commit 92323dd3bb.
2025-05-07 15:34:59 +00:00
Owen Avery
98573bd61e Improve canonical path handling for impl items
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>
2025-05-07 15:33:20 +00:00
Philip Herron
927d067721 gccrs: desugar APIT impl traits
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>
2025-05-07 15:07:22 +00:00
Philip Herron
ef44f64965 gccrs: Emit error diagnostic for bad impl type usage
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>
2025-05-07 12:04:19 +00:00
CohenArthur
5599bf49cd derive(PartialEq): Fix raw strings in test
gcc/testsuite/ChangeLog:

	* rust/execute/torture/derive-partialeq2.rs: Add missing terminating nul char.

Co-authored-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2025-05-02 14:46:25 +00:00
Arthur Cohen
5d01bb8c55 derive(PartialEq): Allow deriving enum structs
gcc/rust/ChangeLog:

	* expand/rust-derive-partial-eq.cc (DerivePartialEq::match_enum_tuple): Remove debug call.
	(DerivePartialEq::match_enum_struct): Add proper implementation.
	(DerivePartialEq::visit_enum): Call it.

gcc/testsuite/ChangeLog:

	* rust/execute/torture/derive-partialeq2.rs: New test.
2025-05-02 14:46:25 +00:00
Arthur Cohen
ecf19aca75 ast: builder: Allow building struct ident patterns
gcc/rust/ChangeLog:

	* ast/rust-ast-builder.cc (Builder::struct_pattern_ident_pattern): New.
	* ast/rust-ast-builder.h: New declaration.
2025-05-02 14:46:25 +00:00
Arthur Cohen
92323dd3bb backend: Remove checks on StructFieldIdentPattern
gcc/rust/ChangeLog:

	* backend/rust-compile-pattern.cc (CompilePatternCheckExpr::visit): Remove old invalid
	checks.
2025-04-30 10:35:43 +00:00
Arthur Cohen
515e1692ff backend: Compile struct rebinding patterns
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.
2025-04-30 10:35:43 +00:00
Arthur Cohen
0a316f44a0 backend: Refactor struct pattern compilation
gcc/rust/ChangeLog:

	* backend/rust-compile-pattern.h: Split struct pattern compilation into three functions.
	* backend/rust-compile-pattern.cc: Implement them.
2025-04-30 10:35:43 +00:00
Arthur Cohen
e9514b851e nr2.0: late: Correctly initialize funny_error member
gcc/rust/ChangeLog:

	* resolve/rust-late-name-resolver-2.0.cc (Late::Late): False initialize the
	funny_error field.
2025-04-29 08:16:19 +00:00
Owen Avery
161e3c684c Fix narrowing conversion warnings
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>
2025-04-28 13:14:05 +00:00
Pierre-Emmanuel Patry
8166a86ae5 Visit visibility in UseDeclaration
Default visitor should visit all it's children.

gcc/rust/ChangeLog:

	* ast/rust-ast-visitor.cc (DefaultASTVisitor::visit): Visit visibility.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2025-04-28 11:32:12 +00:00
Owen Avery
7409c28ee0 Some assorted tweaks and bug fixes
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>
2025-04-28 11:13:51 +00:00
Pierre-Emmanuel Patry
b22c7d8df0 Completely duplicate path node
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>
2025-04-28 11:08:30 +00:00
Pierre-Emmanuel Patry
ee61e8917f Use specialized param visit function for params
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>
2025-04-24 16:53:44 +00:00
Pierre-Emmanuel Patry
38b913483f Remove passing test from exclusion list
gcc/testsuite/ChangeLog:

	* rust/compile/nr2/exclude: Remove passing test from exclusion list.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2025-04-24 16:53:44 +00:00
Pierre-Emmanuel Patry
7acf75a3af Use stacked context for nested bindings.
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>
2025-04-24 16:53:44 +00:00
Pierre-Emmanuel Patry
5d6320ceb3 Add pattern bindings
gcc/rust/ChangeLog:

	* resolve/rust-late-name-resolver-2.0.cc (Late::visit): Add binding
	creation in visitor.
	* resolve/rust-late-name-resolver-2.0.h: Add function prototypes.
	* resolve/rust-name-resolution-context.h: Add binding context.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2025-04-24 16:53:44 +00:00
Pierre-Emmanuel Patry
ca4175b0e5 Add binding context class
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>
2025-04-24 16:53:44 +00:00
Pierre-Emmanuel Patry
22c008cc52 Add hash function for Identifiers
gcc/rust/ChangeLog:

	* ast/rust-ast.h: Add hash function.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2025-04-24 16:53:44 +00:00
Pierre-Emmanuel Patry
7f52357ff7 Add equality operator for identifiers
gcc/rust/ChangeLog:

	* ast/rust-ast.h: Add equality operator.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2025-04-24 16:53:44 +00:00
Pierre-Emmanuel Patry
7c7d476b27 Add fn_once and Sized lang items to the test
gcc/testsuite/ChangeLog:

	* rust/compile/multiple_bindings1.rs: Add missing lang items.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2025-04-24 16:53:44 +00:00
Pierre-Emmanuel Patry
7df713d599 Change expected error output to match nr2
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>
2025-04-24 13:01:09 +00:00
Pierre-Emmanuel Patry
f2eb4e9a01 Update generics9 expected error message
gcc/testsuite/ChangeLog:

	* rust/compile/generics9.rs: Change expected error message.
	* rust/compile/nr2/exclude: Remove test from exclusion list.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2025-04-24 09:46:13 +00:00
Pierre-Emmanuel Patry
589c8bbcce Prevent forward declaration in type parameters
gcc/rust/ChangeLog:

	* resolve/rust-default-resolver.cc (DefaultResolver::visit): Add visit
	function for TypeParam.
	* resolve/rust-default-resolver.h: Add function prototype.
	* resolve/rust-forever-stack.h: Add function to check for forward
	declaration ban.
	* resolve/rust-late-name-resolver-2.0.cc (Late::visit): Check forward
	declarations.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2025-04-24 09:46:13 +00:00
Pierre-Emmanuel Patry
06b6c5559a Remove error state for GenericArg
gcc/rust/ChangeLog:

	* ast/rust-ast-collector.cc (TokenCollector::visit): Remove error kind
	and change function call.
	* ast/rust-ast-visitor.cc (DefaultASTVisitor::visit): Change call name.
	* ast/rust-path.cc (ConstGenericParam::as_string): Likewise.
	* ast/rust-path.h: Remove error kind.
	* hir/rust-ast-lower-type.cc (ASTLowerGenericParam::visit): Change call
	name.
	* parse/rust-parse-impl.h (Parser::parse_generic_param): Use optional
	on parsing failure.
	(Parser::parse_generic_arg): Likewise.
	(Parser::parse_path_generic_args): Likewise.
	* parse/rust-parse.h: Likewise.
	* resolve/rust-ast-resolve-type.h: Change call name.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2025-04-24 09:46:13 +00:00
Pierre-Emmanuel Patry
a7f51b8b4b Change error message to match expected test output
gcc/rust/ChangeLog:

	* resolve/rust-late-name-resolver-2.0.cc (Late::visit): Change error
	message.

gcc/testsuite/ChangeLog:

	* rust/compile/nr2/exclude: Remove passing test from exclusion list.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2025-04-23 16:14:46 +00:00
Owen Avery
6b0dd465e7 nr2.0: Improve error handling
gcc/rust/ChangeLog:

	* resolve/rust-early-name-resolver-2.0.cc
	(Early::build_import_mapping): Avoid outputting an "unresolved
	import" error if other errors are outputted during resolution.
	* resolve/rust-early-name-resolver-2.0.h
	(Early::resolve_path_in_all_ns): Collect path resolution errors
	while avoiding duplicate errors for resolutions in each
	namespace.
	* resolve/rust-forever-stack.h
	(ForeverStack::resolve_path): Add parameter for collecting
	errors.
	(ForeverStack::find_starting_point): Likewise.
	(ForeverStack::resolve_segments): Likewise.
	* resolve/rust-forever-stack.hxx
	(check_leading_kw_at_start): Likewise.
	(ForeverStack::find_starting_point): Likewise.
	(ForeverStack::resolve_segments): Likewise.
	(ForeverStack::resolve_path): Likewise.
	* resolve/rust-name-resolution-context.h
	(NameResolutionContext::resolve_path): Add optional parameter
	for collecting errors.

gcc/testsuite/ChangeLog:

	* rust/compile/nr2/exclude: Remove entry.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2025-04-22 16:49:37 +00:00
Owen Avery
6c68119d57 nr2.0: Fix derive-debug1.rs
gcc/testsuite/ChangeLog:

	* rust/compile/derive-debug1.rs: Adjust a path.
	* rust/compile/nr2/exclude: Remove derive-debug1.rs.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2025-04-22 16:47:30 +00:00
Thomas Schwinge
2753c6f3b8 Disable parallel testing for 'rust/compile/nr2/compile.exp' [PR119508]
..., 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)
2025-04-19 22:34:24 +00:00
Philip Herron
ad951b9c26 gccrs: prealloc the initilizer vector
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>
2025-04-19 12:10:53 +00:00
Philip Herron
4d70c16011 gccrs: Fix ICE with empty generic arguments
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>
2025-04-18 16:06:33 +00:00
Owen Avery
47d55fe8cb Adjust segment start position errors
gcc/rust/ChangeLog:

	* resolve/rust-ast-resolve-path.cc
	(ResolvePath::resolve_path): Adjust error messages.
	* resolve/rust-ast-resolve-type.cc
	(ResolveRelativeTypePath::go): Likewise.
	* resolve/rust-forever-stack.hxx
	(check_leading_kw_at_start): Likewise.

gcc/testsuite/ChangeLog:

	* rust/compile/issue-3568.rs: Adjust expected errors.
	* rust/compile/name_resolution9.rs: Likewise.
	* rust/compile/self-path2.rs: Likewise.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2025-04-18 15:34:51 +00:00
Philip Herron
f81ec04bfd gccrs: Fix ICE when handling case of unknown field in HIR::FieldAccess
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>
2025-04-18 14:01:15 +00:00
Philip Herron
0a34f7bb91 gccrs: Add test case to show ice is fixed
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>
2025-04-18 14:01:03 +00:00
Owen Avery
f220fe8cf7 nr2.0: Remove unnecessary copy of Node
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>
2025-04-18 10:39:59 +00:00
Philip Herron
e77b7c22ab gccrs: Fix ICE in struct expressions
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>
2025-04-18 09:45:18 +00:00
Owen Avery
5a2d06037c nr2.0: Handle StructPatternFieldIdent
gcc/rust/ChangeLog:

	* resolve/rust-late-name-resolver-2.0.cc
	(Late::visit): Handle StructPatternFieldIdent.
	* resolve/rust-late-name-resolver-2.0.h
	(Late::visit): Likewise.

gcc/testsuite/ChangeLog:

	* rust/compile/nr2/exclude: Remove entry.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2025-04-18 09:43:10 +00:00
Philip Herron
838b583c66 gccrs: Add test case to show ICE is fixed
Fixes Rust-GCC#3662

gcc/testsuite/ChangeLog:

	* rust/compile/issue-3662.rs: New test.

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2025-04-18 09:42:38 +00:00
Philip Herron
701094f490 gccrs: Add test case to show issue is fixed
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>
2025-04-18 09:42:18 +00:00
Pierre-Emmanuel Patry
d85328baf0 Add gimple test for black box intrinsic
gcc/testsuite/ChangeLog:

	* rust/compile/black_box.rs: New test.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2025-04-17 18:05:17 +00:00
Pierre-Emmanuel Patry
78fcf63b60 Add execute test for black_box intrinsic
gcc/testsuite/ChangeLog:

	* rust/execute/black_box.rs: New test.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2025-04-17 18:05:17 +00:00
Pierre-Emmanuel Patry
f7952fe9d3 Add LlvmInlineAsm node dump
gcc/rust/ChangeLog:

	* ast/rust-ast-collector.cc (TokenCollector::visit): Dump llvm inline
	asm tokens.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2025-04-17 18:05:17 +00:00
Pierre-Emmanuel Patry
3e8955884c Parse and lower llvm asm node
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>
2025-04-17 18:05:17 +00:00
Pierre-Emmanuel Patry
435b346f47 Add llvmInlineAsm node
InlineAsm node does not support memory clobbers.

gcc/rust/ChangeLog:

	* ast/rust-ast-collector.cc (TokenCollector::visit): Make visitor
	unreachable.
	* ast/rust-ast-collector.h: Add visit for LlvmInlineAsmNode.
	* ast/rust-ast-visitor.cc (DefaultASTVisitor::visit): Add visit
	function for the default ast visitor.
	* ast/rust-ast-visitor.h: Add function prototype.
	* ast/rust-ast.cc (LlvmInlineAsm::accept_vis): Add accept_vis to
	LlvmInlineAsm node.
	* ast/rust-ast.h: Add LlvmInlineAsm node kind.
	* ast/rust-expr.h (class LlvmInlineAsm): Add LlvmInlineAsm node.
	* expand/rust-derive.h: Add visit function for LlvmInlineAsm node.
	* expand/rust-macro-builtins-asm.cc (MacroBuiltin::llvm_asm_handler):
	Add handler for llvm inline assembly nodes.
	(parse_llvm_asm): Add function to parse llvm assembly nodes.
	* expand/rust-macro-builtins-asm.h (parse_llvm_asm): Add function
	prototypes.
	* expand/rust-macro-builtins.cc (inline_llvm_asm_maker): Add macro
	transcriber.
	* expand/rust-macro-builtins.h: Add transcriber function prototype.
	* hir/rust-ast-lower-base.cc (ASTLoweringBase::visit): Add visit
	function for LlvmInlineAsm node.
	* hir/rust-ast-lower-base.h: Add visit function prototype.
	* resolve/rust-ast-resolve-base.cc (ResolverBase::visit): Add visit
	function for LlvmInlineAsm node.
	* resolve/rust-ast-resolve-base.h: Add visit function prototype.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2025-04-17 18:05:17 +00:00
Pierre-Emmanuel Patry
56ccda1142 Emit error with old asm syntax in new asm blocks
gcc/rust/ChangeLog:

	* expand/rust-macro-builtins-asm.cc (parse_asm_arg): Emit error
	message.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2025-04-17 18:05:17 +00:00
Philip Herron
bb01719f0e gccrs: Add check for placeholder (infer) type in return position
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>
2025-04-17 09:28:24 +00:00
Philip Herron
50a90f12af gccrs: Fix ICE when checking shift's which are behind array refs
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>
2025-04-16 22:19:17 +00:00
Philip Herron
95615a1ab4 gccrs: Fix crash in hir dump as labels are optional
gcc/rust/ChangeLog:

	* hir/rust-hir-dump.cc (Dump::visit): add guard for optional label

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2025-04-16 22:19:07 +00:00
Yap Zhi Heng
a59e57efe2 gccrs: Update comments in repr parsing code
gcc/rust/ChangeLog:

	* typecheck/rust-tyty.h: Remove extra redundant comment.
	* typecheck/rust-hir-type-check-base.cc: Update comment on repr
	handling.

Signed-off-by: Yap Zhi Heng <yapzhhg@gmail.com>
2025-04-16 11:03:05 +00:00
Zhi Heng
654d79b98a gccrs: Implement integer representation for enums
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>
2025-04-16 11:03:05 +00:00
Zhi Heng
2c109a2e8a gccrs: Implement typecheck for zero-variant enums
gcc/rust/ChangeLog:

	* typecheck/rust-tyty.h: Add new `ReprKind` enum to
	`ReprOptions`.
	* typecheck/rust-hir-type-check-base.cc: Handle setting of
	`repr_kind`.
	* typecheck/rust-hir-type-check-item.cc: New check for
	zero-variant enums.

Signed-off-by: Yap Zhi Heng <yapzhhg@gmail.com>
2025-04-16 11:03:05 +00:00
Philip Herron
5ac41dce35 gccrs: Fix segv in unsafe chcker
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>
2025-04-16 09:04:47 +00:00
Arthur Cohen
daf5dbc027 lang-items: Add ManuallyDrop<T>
gcc/rust/ChangeLog:

	* util/rust-lang-item.h: Add new manually_drop lang item.
	* util/rust-lang-item.cc: Likewise.
2025-04-14 12:35:00 +00:00
Arthur Cohen
6068e7aac6 attributes: Handle external tool annotations like rustfmt::
gcc/rust/ChangeLog:

	* util/rust-attribute-values.h: Add RUSTFMT value.
	* util/rust-attributes.cc: Define the attribute.
	* util/rust-attributes.h (enum CompilerPass): Add EXTERNAL variant.
	* expand/rust-macro-builtins.cc: Fix formatting.
2025-04-14 12:35:00 +00:00
Arthur Cohen
5bd41f9677 nr2.0: Only insert derive macros if they exist
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.
2025-04-14 12:35:00 +00:00
Arthur Cohen
43b413664f attributes: Add missing attributes used in core
gcc/rust/ChangeLog:

	* util/rust-attribute-values.h: Add missing attributes.
	* util/rust-attributes.cc: Likewise.
	* util/rust-attributes.h (enum CompilerPass): Mention adding something for const
	functions.
2025-04-14 12:35:00 +00:00
beamandala
ecb649973a Add #[track_caller] as known attribute
gcc/rust/ChangeLog:

	* expand/rust-macro-builtins.cc (MacroBuiltin::builtin_transcribers):
	Add entry for track_caller.
	* util/rust-attribute-values.h: add `TRACK_CALLER` attribute.
	* util/rust-attributes.cc: add `track_caller` attribute definition.

gcc/testsuite/ChangeLog:

	* rust/compile/track_caller.rs: New test.

Signed-off-by: Bhavesh Mandalapu <mandalapubhavesh@gmail.com>
2025-04-14 09:32:06 +00:00
Arthur Cohen
a283cdcf85 ci: Update warnings for new location in install.texi
ChangeLog:

	* .github/glibcxx_ubuntu64b_log_expected_warnings: Change line number
	for warning from 2230 to 2236.
	* .github/log_expected_warnings: Likewise.
2025-04-14 09:30:17 +00:00
Arthur Cohen
8934acdd48 install.texi: Mention Rust requirement for building gccrs
Addresses PR#117869

https://gcc.gnu.org/bugzilla/show_bug.cgi?id=117869

gcc/ChangeLog:

	* doc/install.texi: Add requirements for building gccrs.
2025-04-14 09:30:17 +00:00
Owen Avery
f8c661350e Fix const checking of enum discriminants
gcc/rust/ChangeLog:

	* checks/errors/rust-const-checker.cc
	(ConstChecker::visit): Visit the enum items of enums.
	* resolve/rust-ast-resolve-item.cc
	(ResolveItem::visit): Resolve enum discriminants during nr1.0.

gcc/testsuite/ChangeLog:

	* rust/compile/enum_discriminant2.rs: New test.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2025-04-14 09:29:40 +00:00
Arthur Cohen
0c6c73c531 format_args: Allow extraneous commas, improve safety
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.
2025-04-14 08:27:47 +00:00
Arthur Cohen
486ca997e9 expansion: Desugar doc comments into attributes before expansion
gcc/rust/ChangeLog:

	* expand/rust-macro-expand.cc (MacroExpander::expand_decl_macro): Call into
	TokenTreeDesugar.
	* expand/rust-token-tree-desugar.cc: New file.
	* expand/rust-token-tree-desugar.h: New file.
	* Make-lang.in: Compile them.

gcc/testsuite/ChangeLog:

	* rust/compile/macros/mbe/macro-issue3709-1.rs: New test.
	* rust/compile/macros/mbe/macro-issue3709-2.rs: New test.
2025-04-14 08:03:49 +00:00
Arthur Cohen
780ebba8a9 expansion: Only add fragments if the matcher succeeded
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.
2025-04-14 08:03:49 +00:00
Arthur Cohen
688b8d8b0e session: Desugar question mark operator after expansion instead.
gcc/rust/ChangeLog:

	* rust-session-manager.cc (Session::compile_crate): Call the visitor later in the pipeline.
2025-04-14 08:03:49 +00:00
Arthur Cohen
64d4e0f1e5 ast: Add get_locus() to DelimTokenTree
gcc/rust/ChangeLog:

	* ast/rust-ast.h (DelimTokenTree::get_locus): New function.
2025-04-14 08:03:49 +00:00
Arthur Cohen
4d09dd4aba ast: Support outer attributes for AST::RangeExpr
gcc/rust/ChangeLog:

	* ast/rust-expr.h (class RangeExpr): Add empty outer attributes and allow getting them
	and setting them.
2025-04-14 08:03:49 +00:00
Arthur Cohen
fd6257bc28 nr2.0: Do not resolve modules this run if they are unloaded
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.
2025-04-14 07:40:11 +00:00
Arthur Cohen
b9fdd60c28 typecheck: Properly select methods when dealing with specialization
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.
2025-04-14 07:32:30 +00:00
Andrew Pinski
7ef77dad7c rust: Add comment inside block [PR119342]
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>
2025-04-10 15:53:50 +00:00
Andrew Pinski
f202611159 rust: use range for inside rust-gcc.cc [PR119341]
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>
2025-04-10 15:53:50 +00:00
Andrew Pinski
4b64c35a8f rust: Use error_operand_p in rust-gcc.cc
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>
2025-04-10 15:53:50 +00:00
Andrew Pinski
2a46a5a37a rust: Use FLOAT_TYPE_P instead of manual checking
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>
2025-04-10 15:53:50 +00:00
Owen Avery
d61c219766 nr2.0: Adjust test macro6.rs
gcc/testsuite/ChangeLog:

	* rust/compile/macros/mbe/macro6.rs: Remove call of undefined
	function.
	* rust/compile/nr2/exclude: Remove macros/mbe/macro6.rs.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2025-04-07 09:54:09 +00:00
Owen Avery
22bf192a72 nr2.0: Adjust test issue-2812.rs
gcc/testsuite/ChangeLog:

	* rust/compile/issue-2812.rs: Avoid multiple definition error.
	* rust/compile/nr2/exclude: Remove issue-2812.rs.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2025-04-07 08:59:25 +00:00
Matty Kuhn
3f2e8aef6f gccrs: fix ICE segfault with empty feature gate
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>
2025-04-07 08:27:17 +00:00
Pierre-Emmanuel Patry
1d07cf75d5 Rename label getter to unchecked
gcc/rust/ChangeLog:

	* ast/rust-ast-collector.cc (TokenCollector::visit): Update label
	getter call.
	* ast/rust-ast-visitor.cc (DefaultASTVisitor::visit): Likewise.
	* ast/rust-ast.cc (BreakExpr::as_string): Likewise.
	* hir/rust-ast-lower-expr.cc (ASTLoweringExpr::visit): Likewise.
	* resolve/rust-ast-resolve-expr.cc (ResolveExpr::visit): Likewise.
	* resolve/rust-late-name-resolver-2.0.cc (Late::visit): Likewise.
	* ast/rust-expr.h: Add optional getter and rename label getter to
	get_label_unchecked.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2025-04-07 08:18:19 +00:00
Pierre-Emmanuel Patry
416e4b8449 Rename label getter in ContinueExpr
gcc/rust/ChangeLog:

	* ast/rust-ast-collector.cc (TokenCollector::visit):
	Call unchecked getter.
	* ast/rust-ast-visitor.cc (DefaultASTVisitor::visit):
	Likewise.
	* ast/rust-ast.cc (ContinueExpr::as_string): Likewise.
	* hir/rust-ast-lower-expr.cc (ASTLoweringExpr::visit): Likewise.
	* resolve/rust-ast-resolve-expr.cc (ResolveExpr::visit): Likewise.
	* resolve/rust-late-name-resolver-2.0.cc (Late::visit): Likewise.
	* ast/rust-expr.h: Add new getter for the optional and rename getter
	to get_label_unchecked.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2025-04-07 08:18:19 +00:00
Pierre-Emmanuel Patry
5ab8589e09 Change optional to expected for parse_loop_label
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>
2025-04-07 08:18:19 +00:00
Pierre-Emmanuel Patry
a179c05f22 Adapt testcase to name resolution 2.0
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>
2025-04-07 08:18:19 +00:00
Pierre-Emmanuel Patry
429897c851 Resolve labels within break or continue expressions
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>
2025-04-07 08:18:19 +00:00
Pierre-Emmanuel Patry
5562e72c96 Fix unresolved label error message
gcc/rust/ChangeLog:

	* resolve/rust-ast-resolve-expr.cc (ResolveExpr::visit):
	Change error message to match rustc.

gcc/testsuite/ChangeLog:

	* rust/compile/undeclared_label.rs: Change test
	expected string.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2025-04-07 08:18:19 +00:00
Pierre-Emmanuel Patry
46673ec062 Migrate error state to optionals
gcc/rust/ChangeLog:

	* ast/rust-ast-builder.cc (Builder::self_ref_param): Remove error state
	and use optional.
	* ast/rust-ast-visitor.cc (DefaultASTVisitor::visit): Check label
	before visiting.
	* ast/rust-ast.cc (ContinueExpr::as_string): Retrieve label value.
	(Lifetime::as_string): Retrieve lifetime value.
	(ReferenceType::as_string): Likewise.
	(SelfParam::as_string): Likewise.
	* ast/rust-ast.h: Remove lifetime and LifetimeParam error state.
	* ast/rust-desugar-for-loops.cc (DesugarForLoops::DesugarCtx::make_break_arm):
	Use optional instead of error state.
	* ast/rust-expr.h (class ContinueExpr): Make label optional.
	* ast/rust-item.h (class SelfParam): Make lifetime optional.
	* ast/rust-type.h (class ReferenceType): Likewise.
	* backend/rust-compile-base.cc: Use optional for self param instead
	of error state.
	* backend/rust-compile-base.h: Update function prototype.
	* expand/rust-derive-clone.cc (DeriveClone::clone_fn): Use optional.
	* hir/rust-ast-lower-base.cc (ASTLoweringBase::lower_self): Lower
	lifetime only if it exists.
	* hir/rust-ast-lower-block.h: Lower loop label only if it exists.
	* hir/rust-ast-lower-expr.cc (ASTLoweringExpr::visit): Likewise.
	* hir/rust-ast-lower-implitem.cc (ASTLowerImplItem::visit): Remove
	references to error state.
	(ASTLowerTraitItem::visit): Lower self param only if it exists.
	* hir/rust-ast-lower-item.cc (ASTLoweringItem::visit): Use nullopt
	for default value instead of SelfParam error state.
	* hir/rust-ast-lower.cc (ASTLoweringExprWithBlock::visit): Lower label
	only if it exists.
	* hir/rust-hir-dump.cc (Dump::do_traitfunctiondecl): Print self only if
	it exists.
	(Dump::visit): Liewise.
	* hir/tree/rust-hir-bound.h: Remove error state.
	* hir/tree/rust-hir-expr.cc (ContinueExpr::ContinueExpr): Use optional
	in constructor for loop label.
	(BreakExpr::BreakExpr): Likewise.
	* hir/tree/rust-hir-expr.h (class ContinueExpr): Remove error state
	implementation.
	(class BreakExpr): Likewise.
	* hir/tree/rust-hir-generic-param.h: Likewise.
	* hir/tree/rust-hir-item.cc (SelfParam::SelfParam): Make lifetime
	optional.
	(Function::Function): Make self param optional.
	* hir/tree/rust-hir-item.h (class Function): Likewise.
	* hir/tree/rust-hir-type.cc (ReferenceType::ReferenceType): Make
	lifetime optional.
	* hir/tree/rust-hir-type.h (class ReferenceType): Likewise.
	* hir/tree/rust-hir.cc (ContinueExpr::as_string): Use new getter.
	(BreakExpr::as_string): Likewise.
	(Lifetime::as_string): Likewise.
	(ReferenceType::as_string): Likewise.
	(TraitFunctionDecl::as_string): Likewise.
	(SelfParam::as_string): Remove error state checking.
	* parse/rust-parse-impl.h (Parser::parse_generic_param): Adapt to
	optional.
	(Parser::parse_lifetime_params): Likewise.
	(Parser::parse_lifetime_params_objs): Likewise.
	(Parser::parse_lifetime_param): Likewise.
	(Parser::parse_lifetime_where_clause_item): Likewise.
	(Parser::parse_type_param_bound): Likewise.
	(Parser::parse_lifetime_bounds): Likewise.
	(Parser::parse_path_generic_args): Likewise.
	(Parser::parse_self_param): Likewise.
	(Parser::parse_break_expr): Likewise.
	(Parser::parse_continue_expr): Likewise.
	(Parser::parse_reference_type_inner): Likewise.
	* parse/rust-parse.h (class ParseLifetimeParamError): Add new class for
	lifetime param parsing errors.
	(class ParseLifetimeError): Add new class for lifetime parsing errors.
	(enum ParseSelfError): Add new class for self param parsing errors.
	* typecheck/rust-hir-type-check-implitem.cc (TypeCheckImplItem::visit):
	Use unchecked getter in checked context. And make anonymous region.
	* typecheck/rust-hir-type-check.cc (TraitItemReference::get_type_from_fn):
	Likewise.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2025-04-07 08:18:19 +00:00
Pierre-Emmanuel Patry
8a65b913d4 Update ast visitor with proper check for looplabel
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>
2025-04-07 08:18:19 +00:00
Pierre-Emmanuel Patry
75b7b7c210 Remove unused error constructor and getter
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>
2025-04-07 08:18:19 +00:00
Pierre-Emmanuel Patry
f77aeb99dd Make loop label truly optional
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>
2025-04-07 08:18:19 +00:00
Pierre-Emmanuel Patry
b079d612f6 Visit loop label before predicate expression
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>
2025-04-07 08:18:19 +00:00
Pierre-Emmanuel Patry
676e3eacc3 Add check for label
gcc/rust/ChangeLog:

	* ast/rust-ast-visitor.cc (DefaultASTVisitor::visit): Visit loop label
	only if it exists.

gcc/testsuite/ChangeLog:

	* rust/compile/nr2/exclude: Remove passing test.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2025-04-07 08:18:19 +00:00
Pierre-Emmanuel Patry
be0d148065 Resolve labels
gcc/rust/ChangeLog:

	* hir/rust-ast-lower.cc (ASTLoweringBlock::visit): Lower label only if
	it exists.
	* hir/tree/rust-hir-expr.cc (BlockExpr::BlockExpr): Make loop label
	optional.
	(BaseLoopExpr::BaseLoopExpr): Likewise.
	(LoopExpr::LoopExpr): Likewise.
	(WhileLoopExpr::WhileLoopExpr): Likewise.
	* hir/tree/rust-hir-expr.h: Use optional for lifetime and labels.
	* hir/tree/rust-hir.cc (WhileLoopExpr::as_string): Use getter.
	(WhileLetLoopExpr::as_string): Likewise.
	(LoopExpr::as_string): Likewise.
	* resolve/rust-late-name-resolver-2.0.cc (Late::visit): Resolve labels.
	* resolve/rust-late-name-resolver-2.0.h: Add visit function prototype
	for loop labels.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2025-04-07 08:18:19 +00:00
Pierre-Emmanuel Patry
227a2b77d3 Revert part of 44ffe11932
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>
2025-04-07 08:18:19 +00:00
Sri Ganesh Thota
9554470e7f gccrs: refactoring rust_error_at "redefined multiple times"
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>
2025-04-04 15:54:14 +00:00
Owen Avery
b9aaa6192f nr2.0: Improve test script
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>
2025-04-04 12:10:15 +00:00
Owen Avery
ea91cee92d nr2.0: Remove duplicate self visit
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>
2025-04-04 10:41:51 +00:00
Philip Herron
641f9a4061 gccrs: Fix ICE for reserved lifetime name
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>
2025-04-04 09:44:59 +00:00
Arthur Cohen
861dcf6f8f hir: Add default qualifier to function, lower it properly
gcc/rust/ChangeLog:

	* ast/rust-ast.cc (Function::Function): Rename is_default -> has_default.
	(Function::operator=): Likewise.
	* ast/rust-item.h (class Function): Add `is_default` method.
	* hir/rust-ast-lower-implitem.cc (ASTLowerImplItem::visit): Lower default qualifier.
	* hir/rust-ast-lower-item.cc (ASTLoweringItem::visit): Likewise.
	* hir/tree/rust-hir-item.cc (Function::Function): Add `is_default` member.
	(Function::operator=): Likewise.
	* hir/tree/rust-hir-item.h (enum class Defaultness): New enum.
	(class Function): Use it.

gcc/testsuite/ChangeLog:

	* rust/compile/min_specialization1.rs: New test.
2025-04-04 08:24:54 +00:00
Arthur Cohen
9684625ab8 feature: Add min_specialization feature
gcc/rust/ChangeLog:

	* checks/errors/rust-feature.cc (Feature::create): Handle `#![feature(min_specialization)]`.
	* checks/errors/rust-feature.h: Likewise.
2025-04-04 08:24:54 +00:00
Philip Herron
8022ca11ed gccrs: Fix ICE when hitting invalid types for generics
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>
2025-04-04 08:19:30 +00:00
Philip Herron
314090971a gccrs: Fix ICE on raw reference
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>
2025-04-03 16:40:47 +00:00
Philip Herron
002c349b6d gccrs: Fix ICE on invalid match arms
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>
2025-04-03 16:40:33 +00:00
Philip Herron
67017c92b8 gccrs: Fix recusive type query and nullptr on type path
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>
2025-04-03 14:53:54 +00:00
Philip Herron
8cd24f8338 gccrs: Fix ICE when there are 2 functions named main
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>
2025-04-02 17:49:58 +00:00
Philip Herron
20c8539a23 gccrs: Fix ICE when resolving lifetimes without name
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>
2025-04-01 10:43:12 +00:00
Philip Herron
eecf0cd685 gccrs: Fix ICE when doing shift checks on const decl
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>
2025-04-01 10:43:04 +00:00
Owen Avery
bdfdaef906 nr2.0: Handle global paths
gcc/rust/ChangeLog:

	* resolve/rust-forever-stack.h
	(ForeverStack::ForeverStack): Initialize extern_prelude.
	(ForeverStack::resolve_path): Add parameter
	has_opening_scope_resolution.
	(ForeverStack::extern_prelude): Add field.
	* resolve/rust-forever-stack.hxx: Include rust-edition.h.
	(ForeverStacl::resolve_path): Handle global paths (paths with an
	opening scope resolution operator).
	* resolve/rust-late-name-resolver-2.0.cc
	(Late::visit): Handle global paths.
	* resolve/rust-name-resolution-context.h
	(NameResolutionContext::resolve_path): Handle global paths.

gcc/testsuite/ChangeLog:

	* rust/compile/nr2/exclude: Remove entries.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2025-04-01 09:19:04 +00:00
Ryutaro Okada
b8ef598308 Evaluate the enum's discriminant in a const context
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>
2025-03-31 14:55:15 +00:00
Philip Herron
765121736d gccrs: Fix SEGV when type path resolver fails outright
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>
2025-03-28 20:04:21 +00:00
Philip Herron
1d93ebb1ca gccrs: fix crash in parse repr options and missing delete call
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>
2025-03-28 20:04:18 +00:00
Philip Herron
8b5f1f296b gccrs: fix ice when setting up regions
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>
2025-03-28 19:10:35 +00:00
Philip Herron
6130523c8b gccrs: FIX ICE for malformed repr attribute
Fixes Rust-GCC#3614

gcc/rust/ChangeLog:

	* typecheck/rust-hir-type-check-base.cc (TypeCheckBase::parse_repr_options): check for input

gcc/testsuite/ChangeLog:

	* rust/compile/issue-3614.rs: New test.

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2025-03-28 18:34:45 +00:00
Philip Herron
8d1c01c818 gccrs: FIX ICE when working with HIR::BareFunctionType
Fixes Rust-GCC#3615

gcc/rust/ChangeLog:

	* hir/rust-hir-dump.cc (Dump::visit): check has type
	* hir/tree/rust-hir-type.cc (BareFunctionType::BareFunctionType): likewise

gcc/testsuite/ChangeLog:

	* rust/compile/issue-3615.rs: New test.

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2025-03-28 18:34:27 +00:00
Philip Herron
a0b21c9415 gccrs: Fix ICE in array ref constexpr
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>
2025-03-28 18:34:20 +00:00
Owen Avery
ebac3ab5be Add ending newline to rust-macro-builtins-log-debug.cc
gcc/rust/ChangeLog:

	* expand/rust-macro-builtins-log-debug.cc:
	Add newline to end of file.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2025-03-28 18:34:12 +00:00
Owen Avery
d60a925642 nr2.0: Rename prelude to lang_prelude
gcc/rust/ChangeLog:

	* resolve/rust-forever-stack.h
	(ForeverStack::get_prelude): Rename to...
	(ForeverStack::get_lang_prelude): ...here.
	(ForeverStack::prelude): Rename to...
	(ForeverStack::lang_prelude): ...here.
	(ForeverStack::ForeverStack): Handle renames.
	* resolve/rust-forever-stack.hxx
	(ForeverStack::push_inner): Likewise.
	(ForeverStack::resolve_segments): Likewise.
	(ForeverStack::resolve_path): Likewise.
	(ForeverStack::get_prelude): Rename to...
	(ForeverStack::get_lang_prelude): ...here and handle renames.
	* resolve/rust-late-name-resolver-2.0.cc
	(Late::visit): Handle renames.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2025-03-28 12:45:55 +00:00
Owen Avery
4019d70517 nr2.0: Fix test macros/mbe/macro43.rs
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>
2025-03-28 12:10:51 +00:00
Philip Herron
898d55ad7e gccrs: Fix ICE during const expr eval on array expressions
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>
2025-03-27 18:19:43 +00:00
Philip Herron
08bfb3550e gccrs: Fix ICE when compiling path which resolves to trait constant
Fixes Rust-GCC#3552

gcc/rust/ChangeLog:

	* backend/rust-compile-resolve-path.cc (HIRCompileBase::query_compile): check for Expr trait
	* hir/rust-hir-dump.cc (Dump::visit): expr is optional

gcc/testsuite/ChangeLog:

	* rust/compile/issue-3552.rs: New test.

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2025-03-27 18:07:48 +00:00
Pierre-Emmanuel Patry
ce8e35fc28 Add new test to highlight namespace for self import
gcc/testsuite/ChangeLog:

	* rust/compile/self_import_namespace.rs: New test.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2025-03-27 17:29:15 +00:00
Pierre-Emmanuel Patry
45f70e36a9 Update exclusion list
gcc/testsuite/ChangeLog:

	* rust/compile/nr2/exclude: Remove now passing tests from exclusion
	list.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2025-03-27 17:29:15 +00:00
Pierre-Emmanuel Patry
9c4e2a7814 Resolve module final self segment in use decls
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>
2025-03-27 17:29:15 +00:00
Philip Herron
29cace33c1 gccrs: Give the builtin unit struct an actual locus
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>
2025-03-27 16:35:26 +00:00
Philip Herron
1a2f56a9d5 gccrs: Fix ICE when doing method resolution on trait predicates
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>
2025-03-27 15:23:52 +00:00
Philip Herron
34b0a68159 gccrs: Fix ICE when using super mid way though path
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>
2025-03-27 13:22:39 +00:00
Philip Herron
6c14a3b702 gccrs: Fix ICE when compiling block expressions in array capacity
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>
2025-03-27 13:22:30 +00:00
Philip Herron
31ee9259a7 gccrs: Add check for super traits being implemented by Self
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>
2025-03-27 13:22:19 +00:00
Philip Herron
23097f8132 gccrs: Fix ICE when array elements are not a value
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>
2025-03-27 13:21:56 +00:00
Pierre-Emmanuel Patry
b322656cdc Fix core library test with proper canonical path
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>
2025-03-26 16:46:08 +00:00
Philip Herron
65574f04d6 gccrs: fix unconstrained infer vars on generic associated type
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>
2025-03-26 16:19:07 +00:00
Owen Avery
46ed038945 Fix validation of constant items
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>
2025-03-26 14:59:58 +00:00
Arthur Cohen
510b73dc40 testsuite: Add more testcases for cfg() in core
gcc/testsuite/ChangeLog:

	* rust/compile/cfg-core1.rs: New test.
	* rust/compile/cfg-core2.rs: New test.
2025-03-26 14:45:31 +00:00
Owen Avery
75ef9fd3ff Lower raw string literals
gcc/rust/ChangeLog:

	* hir/rust-ast-lower-base.cc
	(ASTLoweringBase::lower_literal): Lower raw string literals into
	normal string literals.

gcc/testsuite/ChangeLog:

	* rust/compile/issue-3549.rs: New test.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2025-03-26 11:46:24 +00:00
Arthur Cohen
248a1393b2 rust: Lower minimum supported Rust version to 1.49
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.
2025-03-26 11:33:01 +00:00
Owen Avery
a988708b4b nr2.0: Fix test const_generics_3.rs
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>
2025-03-25 15:12:36 +00:00
Arthur Cohen
f608c02f03 lower: Handle let-else properly
gcc/rust/ChangeLog:

	* hir/tree/rust-hir-stmt.h (class LetStmt): Add optional diverging else expression.
	* hir/tree/rust-hir-stmt.cc: Likewise.
	* hir/rust-ast-lower-stmt.cc (ASTLoweringStmt::visit): Add handling for lowering
	diverging else.
2025-03-25 14:26:53 +00:00
Arthur Cohen
29586bb60a name-resolution: Handle let-else properly
gcc/rust/ChangeLog:

	* resolve/rust-ast-resolve-stmt.h: Add handling for diverging else.
	* resolve/rust-late-name-resolver-2.0.cc (Late::visit): Likewise.
2025-03-25 14:26:53 +00:00
Arthur Cohen
7215522d64 dump: Handle let-else properly
gcc/rust/ChangeLog:

	* ast/rust-ast-collector.cc (TokenCollector::visit): Add handling for diverging else
	expression.
2025-03-25 14:26:53 +00:00
Arthur Cohen
effefe8803 parser: Parse let-else statements
gcc/rust/ChangeLog:

	* parse/rust-parse-impl.h (Parser::parse_let_stmt): Add new parsing in case of `else` token.
2025-03-25 14:26:53 +00:00
Arthur Cohen
b257ae69e1 ast: Add optional diverging else to AST::LetStmt
gcc/rust/ChangeLog:

	* ast/rust-stmt.h (class LetStmt): Add optional expression for diverging else.
	* ast/rust-ast-builder.cc (Builder::let): Use new API.
2025-03-25 14:26:53 +00:00
Pierre-Emmanuel Patry
b79c452e07 Remove now passing test from exclusion list
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>
2025-03-24 13:15:51 +00:00
Pierre-Emmanuel Patry
1d4306f7bc Fix testcase module path
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>
2025-03-24 13:15:51 +00:00
Pierre-Emmanuel Patry
bb08a82b12 Fix function name to printf
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>
2025-03-24 11:13:57 +00:00
Sam James
97daf31a4a ci: disable network
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.
2025-03-24 10:52:08 +00:00
Philip Herron
8c91ed5dc3 gccrs: support generic super traits recursively
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>
2025-03-23 13:41:47 +00:00
Owen Avery
b4895dae9b nr2.0: Fix StructExprFieldIdentifier handling
gcc/rust/ChangeLog:

	* resolve/rust-late-name-resolver-2.0.cc
	(Late::visit): Add visitor for StructExprFieldIdentifier.
	* resolve/rust-late-name-resolver-2.0.h
	(Late::visit): Likewise.

gcc/testsuite/ChangeLog:

	* rust/compile/nr2/exclude: Remove entries.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2025-03-21 15:14:02 +00:00
Marc Poulhiès
30ff37aa16 rust: force cargo to build offline
gcc/rust/Changelog:
	PR rust/119333

	* Make-lang.in: Force offline mode for cargo

Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
2025-03-21 14:52:46 +00:00
Arthur Cohen
d17dc68c72 polonius: Vendor Rust dependencies
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.
2025-03-21 14:52:46 +00:00
Owen Avery
0a2bc0a252 nr2.0: Adjust indentifier expression handling
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>
2025-03-21 14:44:35 +00:00
Owen Avery
3c89c3105d Modify multiple definition error
gcc/rust/ChangeLog:

	* resolve/rust-ast-resolve-expr.cc
	(ResolveExpr::visit): Modify error message.
	* resolve/rust-ast-resolve-implitem.h
	(ResolveToplevelImplItem::visit): Likewise.
	(ResolveTopLevelTraitItems::visit): Likewise.
	(ResolveToplevelExternItem::visit): Likewise.
	* resolve/rust-ast-resolve-stmt.cc
	(ResolveStmt::visit): Likewise.
	* resolve/rust-ast-resolve-stmt.h
	(ResolveStmt::visit): Likewise.
	* resolve/rust-ast-resolve-toplevel.h
	(ResolveTopLevel::visit): Likewise.
	* resolve/rust-ast-resolve-type.h
	(ResolveGenericParams::visit): Likewise.

gcc/testsuite/ChangeLog:

	* rust/compile/nr2/exclude: Remove entries.
	* rust/compile/redef_error2.rs: Modify expected error.
	* rust/compile/redef_error5.rs: Likewise.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2025-03-21 14:43:37 +00:00
Owen Avery
0d7c150572 nr2.0: Adjust visitors for struct expressions
gcc/rust/ChangeLog:

	* ast/rust-ast-visitor.cc
	(DefaultASTVisitor::visit): Make sure to always visit the struct
	name.
	* resolve/rust-late-name-resolver-2.0.cc
	(Late::visit): Avoid visiting the struct name twice.

gcc/testsuite/ChangeLog:

	* rust/compile/nr2/exclude: Remove entries.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2025-03-20 16:59:17 +00:00
Owen Avery
c185688b63 Prevent multiple resolution insertion
gcc/rust/ChangeLog:

	* expand/rust-derive-clone.cc
	(DeriveClone::clone_impl): Avoid using the same node id multiple
	times.
	(DeriveClone::clone_enum_identifier): Likewise.
	(DeriveClone::clone_enum_tuple): Likewise.
	* expand/rust-derive-copy.cc
	(DeriveCopy::copy_impl): Likewise.
	* resolve/rust-ast-resolve-item.cc
	(flatten_list): Likewise.
	* resolve/rust-ast-resolve-path.cc
	(ResolvePath::resolve_path): Prevent reinsertion of resolutions.
	* resolve/rust-ast-resolve-type.cc
	(ResolveRelativeTypePath::go): Likewise.
	* typecheck/rust-hir-type-check-expr.cc
	(TypeCheckExpr::resolve_fn_trait_call): Likewise.
	* resolve/rust-name-resolver.cc
	(Resolver::insert_resolved_name): Catch multiple resolution
	insertions.
	(Resolver::insert_resolved_type): Likewise.

gcc/testsuite/ChangeLog:

	* rust/compile/nr2/exclude: Remove entries.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2025-03-19 11:42:16 +00:00
Owen Avery
c27eac3b57 nr2.0: Fix test self-path2.rs
gcc/rust/ChangeLog:

	* resolve/rust-ast-resolve-path.cc
	(ResolvePath::resolve_path): Adjust the error message for a lower
	self segment in the middle of a path.
	* resolve/rust-ast-resolve-type.cc
	(ResolveRelativeTypePath::go): Likewise.

gcc/testsuite/ChangeLog:

	* rust/compile/nr2/exclude: Remove self-path2.rs
	* rust/compile/self-path2.rs: Adjust expected errors.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2025-03-19 11:20:29 +00:00
Ryutaro Okada
2c05d5858b emit an error for type or const parameters on foreign items
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>
2025-03-19 10:07:47 +00:00
Liam Naddell
199b540046 Fix modules with same name as builtins causing ICE (#3315)
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>
2025-03-18 13:39:52 +00:00
Owen Avery
6a4363f83a nr2.0: Check compile/torture/*.rs tests
gcc/testsuite/ChangeLog:

	* rust/compile/nr2/compile.exp: Adjust to cover tests in the
	torture subdirectory.
	* rust/compile/nr2/exclude: Add entries.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2025-03-18 09:48:40 +00:00
Pierre-Emmanuel Patry
8d0c1192e2 Remove mangling tests from exclusion list
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>
2025-03-17 10:42:53 +00:00
Pierre-Emmanuel Patry
d4a6f60866 Fix canonical path parent resolution
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>
2025-03-17 10:42:53 +00:00
Pierre-Emmanuel Patry
2c744b1332 Insert crate name in canonical path
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>
2025-03-17 10:42:53 +00:00
Pierre-Emmanuel Patry
b08becd6cb Add a function to get the crate number from node id
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>
2025-03-17 10:42:53 +00:00
Pierre-Emmanuel Patry
2472da2b12 Remove finalize import visitor
This visitor is not used anymore.

gcc/rust/ChangeLog:

	* resolve/rust-finalize-imports-2.0.cc (FinalizeImports::FinalizeImports):
	Remove constructor.
	(FinalizeImports::go): Remove function.
	(FinalizeImports::visit): Likewise.
	* resolve/rust-finalize-imports-2.0.h (class FinalizeImports): Remove
	FinalizeImports class.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2025-03-17 10:41:21 +00:00
Pierre-Emmanuel Patry
b3a065af7a Remove tests from exclusion list
gcc/testsuite/ChangeLog:

	* rust/compile/nr2/exclude: Remove issue-1786 and issue-3033 from
	exclusion list.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2025-03-17 10:41:21 +00:00
Pierre-Emmanuel Patry
34db31fb05 Move import mapping resolution to in tree visit
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>
2025-03-17 10:41:21 +00:00
Philip Herron
9d88bcce6d gccrs: check for recursion trait cycle with bounds checks
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>
2025-03-14 19:11:22 +00:00
Philip Herron
aa88863a0f gccrs: track DefId on ADT Types this could be useful information
gcc/rust/ChangeLog:

	* typecheck/rust-hir-type-check-item.cc (TypeCheckItem::visit): track DefId of origin
	* typecheck/rust-tyty.cc (BaseType::monomorphized_clone): likewise
	(ADTType::ADTType): likewise
	(ADTType::get_id): likewise
	(ADTType::clone): likewise
	* typecheck/rust-tyty.h: likewise

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2025-03-14 16:36:36 +00:00
Philip Herron
d93efa777e gccrs: remove visitor which is not needed here
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>
2025-03-14 16:36:36 +00:00
Owen Avery
3621c8d3a8 Fix some small issues
gcc/rust/ChangeLog:

	* backend/rust-compile-intrinsic.cc
	(assume_handler): Fix copy/paste error.
	* typecheck/rust-hir-type-check-pattern.cc
	(TypeCheckPattern::visit): Fix spelling mistake.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2025-03-14 15:02:03 +00:00
Pierre-Emmanuel Patry
d6c5c64449 Add a test for enum variant name resolution
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>
2025-03-11 14:06:30 +00:00
Pierre-Emmanuel Patry
30c9879f77 Remove nr2 exhaustiveness test from exclusion list
gcc/testsuite/ChangeLog:

	* rust/compile/nr2/exclude: Remove test.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2025-03-11 14:06:30 +00:00
Pierre-Emmanuel Patry
39bf05c149 Add enum variant string information to definition
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>
2025-03-11 14:06:30 +00:00
Pierre-Emmanuel Patry
c67466b2b2 Keep definition provenance to skip enum variants
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>
2025-03-11 14:06:30 +00:00
Pierre-Emmanuel Patry
126680c611 Add rib kind debug representation
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>
2025-03-11 14:06:30 +00:00
Owen Avery
6029cc9f25 nr2.0: Set the node id of the root node
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>
2025-03-10 10:52:37 +00:00
Arthur Cohen
f88af6176e expansion: Correctly expand $crate metavar
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.
2025-03-06 15:44:14 +00:00
Owen Avery
912ebb6b74 nr2.0: Make sure PathInExpression is default resolved
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>
2025-03-06 13:26:18 +00:00
Owen Avery
bee59d62a9 Reduce usage of rust-session-manager.h
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>
2025-03-05 10:21:36 +00:00
Arthur Cohen
9e6d06e93d session-manager: Call into DesugarQuestionMark
gcc/rust/ChangeLog:

	* rust-session-manager.cc (Session::compile_crate): Call DesugarQuestionMark::go().
2025-02-26 16:00:58 +00:00
Arthur Cohen
8dc275b79d lower: Error out when lowering ErrorPropagationExpr
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.
2025-02-26 16:00:58 +00:00
Arthur Cohen
950a193451 ast: Add base for desugaring try expressions
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.
2025-02-26 16:00:58 +00:00
Owen Avery
3ebd4c90f8 Adjust unknown macro error message
gcc/rust/ChangeLog:

	* resolve/rust-early-name-resolver-2.0.cc
	(Early::visit): Adjust error produced when macro resolution
	fails.
	* resolve/rust-early-name-resolver.cc
	(EarlyNameResolver::visit): Likewise.

gcc/testsuite/ChangeLog:

	* rust/compile/macros/mbe/macro43.rs: Adjust expected errors.
	* rust/compile/macros/mbe/macro44.rs: Likewise.
	* rust/compile/nested_macro_use2.rs: Likewise.
	* rust/compile/nr2/exclude: Remove entries.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2025-02-25 15:45:53 +00:00
Owen Avery
b1e30683d9 nr2.0: Handle lang item type path segments
gcc/rust/ChangeLog:

	* resolve/rust-forever-stack.hxx
	(ForeverStack::find_starting_point): Stop when hitting a lang
	item segment.
	(ForeverStack::resolve_segments): Resolve lang item segments.
	(ForeverStacl::resolve_path): Handle single segment lang item
	paths and add comment.
	* util/rust-unwrap-segment.cc
	(unwrap_segment_get_lang_item): Add.
	* util/rust-unwrap-segment.h
	(unwrap_segment_get_lang_item): Add.

gcc/testsuite/ChangeLog:

	* rust/compile/nr2/exclude: Remove entries.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2025-02-25 15:30:19 +00:00
Arthur Cohen
9075c9918f expansion: Expand generic args in generic type path segments
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.
2025-02-25 12:26:38 +00:00
Arthur Cohen
5b32082a34 name-resolution: early: Remove overzealous overrides
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.
2025-02-25 12:26:38 +00:00
Arthur Cohen
6e4573a34e lower: Always crash when lowering macro invocations
gcc/rust/ChangeLog:

	* hir/rust-ast-lower-base.cc (ASTLoweringBase::visit): Add base implementation
	for visitor.
2025-02-25 12:26:38 +00:00
Owen Avery
e4ebd02d45 nr2.0: Implement macro_use for modules
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>
2025-02-25 12:23:55 +00:00
Owen Avery
2ba365c372 Adjust type path resolution error message
gcc/rust/ChangeLog:

	* resolve/rust-ast-resolve-type.cc
	(ResolveRelativeTypePath::go): Adjust error message to match
	the 2.0 name resolver.

gcc/testsuite/ChangeLog:

	* rust/compile/additional-trait-bounds2.rs: Adjust expected
	errors.
	* rust/compile/const_generics_4.rs: Likewise.
	* rust/compile/const_generics_7.rs: Likewise.
	* rust/compile/generic-default1.rs: Likewise.
	* rust/compile/generics5.rs: Likewise.
	* rust/compile/generics9.rs: Likewise.
	* rust/compile/issue-2423.rs: Likewise.
	* rust/compile/method2.rs: Likewise.
	* rust/compile/nr2/exclude: Remove entries.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2025-02-25 09:42:37 +00:00
Arthur Cohen
ac5abbd6e0 hir-dump: Fix more segfaults in the HIR dump
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.
2025-02-25 09:12:54 +00:00
Arthur Cohen
1361615946 derive(Hash): Add implementation.
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.
2025-02-24 08:53:25 +00:00
Arthur Cohen
6a02fdab62 derive(Debug): Use builder's ptrify function instead
gcc/rust/ChangeLog:

	* expand/rust-derive-debug.cc (ptrify): Remove function.
2025-02-24 08:53:25 +00:00
Arthur Cohen
e5b7e27532 ast: builder: Add new builder methods
gcc/rust/ChangeLog:

	* ast/rust-ast-builder.cc (Builder::statementify): New.
	(Builder::function): Add generic params optional argument.
	(Builder::path_in_expression): Add opening_scope_resolution optional argument.
	(Builder::block): Add function for creating empty blocks.
	(Builder::generic_type_param):  New.
	* ast/rust-ast-builder.h (ptrify): New.
2025-02-24 08:53:25 +00:00
Owen Avery
22333202dc Remove some member functions from SingleASTNode
gcc/rust/ChangeLog:

	* ast/rust-ast.h
	(SingleASTNode::take_trait_item): Remove.
	(SingleASTNode::take_impl_item): Remove.
	(SingleASTNode::take_trait_impl_item): Remove.
	* expand/rust-expand-visitor.cc
	(ExpandVisitor::visit): Replace calls to aforementioned
	functions with calls to SingleASTNode::take_assoc_item.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2025-02-24 08:32:40 +00:00
Owen Avery
c3a707ae42 Fix expansion of macros inside modules
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>
2025-02-23 19:54:11 +00:00
Owen Avery
5c675798ed Remove PathInExpression::get_pattern_node_id
gcc/rust/ChangeLog:

	* ast/rust-path.h
	(PathInExpression::get_pattern_node_id): Remove.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2025-02-23 19:52:43 +00:00
Arthur Cohen
35afe3943c derive(Eq): Create copies of Eq typepath to avoid NodeId confusion
gcc/rust/ChangeLog:

	* expand/rust-derive-eq.cc: Copy `Eq` typepath.
2025-02-20 09:37:09 +00:00
Arthur Cohen
a969379df8 derive(Eq): Also derive StructuralEq
gcc/rust/ChangeLog:

	* expand/rust-derive-eq.cc: Adapt functions to return two generated impls.
	* expand/rust-derive-eq.h: Likewise.
	* expand/rust-derive.cc (DeriveVisitor::derive): Likewise.
2025-02-20 09:37:09 +00:00
Arthur Cohen
eca2228561 derive(PartialEq): Also derive StructuralPartialEq
gcc/rust/ChangeLog:

	* expand/rust-derive-partial-eq.cc: Adapt signatures to generate two impls.
	* expand/rust-derive-partial-eq.h: Likewise.
	* expand/rust-derive.cc (DeriveVisitor::derive): Adapt to multiple item generation.

gcc/testsuite/ChangeLog:

	* rust/compile/derive-eq-invalid.rs: Declare StructuralPartialEq.
	* rust/compile/derive-partialeq1.rs: Likewise.
	* rust/execute/torture/derive-partialeq1.rs: Likewise.
2025-02-20 09:37:09 +00:00
Arthur Cohen
bad70abc60 expand: Allow built-in derives to generate multiple items
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.
2025-02-20 09:37:09 +00:00
Arthur Cohen
d45dfed78f derive(PartialEq): Add partial implementation
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.
2025-02-20 09:37:09 +00:00
Arthur Cohen
699dc7b64e derive(Clone): chore: Cleanup
gcc/rust/ChangeLog:

	* expand/rust-derive-clone.cc: Cleanup implementation, avoid repetitions.
	* expand/rust-derive-clone.h: Likewise.
2025-02-20 09:37:09 +00:00
Arthur Cohen
d2f6b12889 ast-builder: Add new methods for creating operator expressions
gcc/rust/ChangeLog:

	* ast/rust-ast-builder.cc (Builder::literal_bool): New method.
	(Builder::comparison_expr): Likewise.
	(Builder::boolean_operation): Likewise.
	* ast/rust-ast-builder.h: Declare them.
2025-02-20 09:37:09 +00:00
Arthur Cohen
f85babd713 ast-builder: Improve function generation.
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.
2025-02-20 09:37:09 +00:00
Arthur Cohen
e3cebdda0d derive(Eq): Add implementation.
gcc/rust/ChangeLog:

	* expand/rust-derive.cc (DeriveVisitor::derive): Call into DeriveEq.
	* expand/rust-derive-eq.cc: New file.
	* expand/rust-derive-eq.h: New file.
	* Make-lang.in: Compile them.

gcc/testsuite/ChangeLog:

	* rust/compile/derive-eq-invalid.rs: New test.
2025-02-20 09:37:09 +00:00
Owen Avery
c638b4f52c nr2.0: Run DefaultResolver::visit on PathInExpression
gcc/rust/ChangeLog:

	* resolve/rust-late-name-resolver-2.0.cc
	(Late::visit): When visiting a PathInExpression instance, call
	into DefaultResolver::visit, ensuring generic arguments are
	visited.

gcc/testsuite/ChangeLog:

	* rust/compile/nr2/exclude: Remove entries.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2025-02-19 08:37:52 +00:00
Owen Avery
9a1162dc57 nr2.0: Fix issue with external crates
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>
2025-02-19 08:37:03 +00:00
Owen Avery
8dc95df84e Add comments to resolve_segments
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>
2025-02-19 08:36:23 +00:00
Benjamin Thos
7afc39068e Add type check on if-expr
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>
2025-02-17 09:40:03 +00:00
Owen Avery
681805f7ee nr2.0: Resolve paths which start with Self
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>
2025-02-17 09:08:38 +00:00
Philip Herron
de2446d576 gccrs: initial setup for new OpaqueType to represent Impl types
This completes the initial setup and boilerplate for the new type in the
typesystem. This is not functional yet but its a big patch already.

gcc/rust/ChangeLog:

	* backend/rust-compile-type.cc (TyTyResolveCompile::visit): new tyty::OpaqueType
	* backend/rust-compile-type.h: likewise
	* checks/errors/borrowck/rust-bir-fact-collector.h: likewise
	* checks/errors/borrowck/rust-bir-place.h: likewise
	* checks/errors/privacy/rust-privacy-reporter.cc (PrivacyReporter::check_base_type_privacy):
	likewise
	* typecheck/rust-hir-type-check-type.cc (TypeCheckType::visit): likewise
	* typecheck/rust-hir-type-check-type.h: likewise
	* typecheck/rust-substitution-mapper.cc (SubstMapperInternal::visit): likewise
	* typecheck/rust-substitution-mapper.h: likewise
	* typecheck/rust-tyty-bounds.cc (TypeBoundsProbe::assemble_sized_builtin): likewise
	* typecheck/rust-tyty-call.h: likewise
	* typecheck/rust-tyty-cmp.h (class OpaqueCmp): likewise
	* typecheck/rust-tyty-variance-analysis-private.h: likewise
	* typecheck/rust-tyty-visitor.h: likewise
	* typecheck/rust-tyty.cc (TypeKindFormat::to_string): likewise
	(BaseType::is_unit): likewise
	(BaseType::destructure): likewise
	(BaseType::has_substitutions_defined): likewise
	(BaseType::needs_generic_substitutions): likewise
	(OpaqueType::OpaqueType): likewise
	(OpaqueType::can_resolve): likewise
	(OpaqueType::accept_vis): likewise
	(OpaqueType::as_string): likewise
	(OpaqueType::get_name): likewise
	(OpaqueType::can_eq): likewise
	(OpaqueType::clone): likewise
	(OpaqueType::resolve): likewise
	(OpaqueType::is_equal): likewise
	(OpaqueType::handle_substitions): likewise
	* typecheck/rust-tyty.h (enum TypeKind): likewise
	(class OpaqueType): likewise
	* typecheck/rust-unify.cc (UnifyRules::go): likewise
	(UnifyRules::expect_inference_variable): likewise
	(UnifyRules::expect_adt): likewise
	(UnifyRules::expect_str): likewise
	(UnifyRules::expect_reference): likewise
	(UnifyRules::expect_pointer): likewise
	(UnifyRules::expect_param): likewise
	(UnifyRules::expect_array): likewise
	(UnifyRules::expect_slice): likewise
	(UnifyRules::expect_fndef): likewise
	(UnifyRules::expect_fnptr): likewise
	(UnifyRules::expect_tuple): likewise
	(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
	(UnifyRules::expect_placeholder): likewise
	(UnifyRules::expect_projection): likewise
	(UnifyRules::expect_dyn): likewise
	(UnifyRules::expect_opaque): likewise
	* typecheck/rust-unify.h: likewise

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2025-02-16 18:12:31 +00:00
Philip Herron
65a3af955f gccrs: Add name resolution and HIR lowering for ImplTraitType's
Our AST has ImplTraitType for multiple bounds and a singular
ImplTraitTypeOneBound, this patch desugars these into a simple
HIR::ImplTraitType. It also does the name resolution for this.

gcc/rust/ChangeLog:

	* checks/errors/borrowck/rust-bir-builder-struct.h: remove HIR::ImplTraitTypeOneBound
	* checks/errors/borrowck/rust-function-collector.h: likewise
	* checks/errors/rust-const-checker.cc (ConstChecker::visit): likewise
	* checks/errors/rust-const-checker.h: likewise
	* checks/errors/rust-hir-pattern-analysis.cc (PatternChecker::visit): likewise
	* checks/errors/rust-hir-pattern-analysis.h: likewise
	* checks/errors/rust-unsafe-checker.cc (UnsafeChecker::visit): likewise
	* checks/errors/rust-unsafe-checker.h: likewise
	* hir/rust-ast-lower-type.cc (ASTLoweringType::translate): likewise
	(ASTLoweringType::visit): likewise
	* hir/rust-ast-lower-type.h: cleanup
	* hir/rust-hir-dump.cc (Dump::visit): remove ImplTraitTypeOneBound
	* hir/rust-hir-dump.h: likewise
	* hir/tree/rust-hir-full-decls.h (class ImplTraitTypeOneBound): likewise
	* hir/tree/rust-hir-type.h (class ImplTraitTypeOneBound): likewise
	* hir/tree/rust-hir-visitor.h: likewise
	* hir/tree/rust-hir.cc (ImplTraitTypeOneBound::as_string):  likewise
	(ImplTraitTypeOneBound::accept_vis):  likewise
	* resolve/rust-ast-resolve-type.cc (ResolveType::go): likewise
	(ResolveType::visit): likewise
	* resolve/rust-ast-resolve-type.h: add name resolution
	* typecheck/rust-hir-type-check-type.h: likewise

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2025-02-15 22:17:55 +00:00
Philip Herron
f21bf4bd6c gccrs: improve error diagnostic for bad type-resolution in CallExpr
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>
2025-02-14 18:03:54 +00:00
Philip Herron
1eb46203ce gccrs: self paths are patterns but we dont have mappings for it
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>
2025-02-13 18:26:59 +00:00
Philip Herron
45fc433d0f gccrs: fix name resolution for generics where type param is declared later
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>
2025-02-13 17:35:40 +00:00
Philip Herron
5f7213e820 gccrs: fix unconstrained generics check to handle recursive generics
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>
2025-02-13 16:29:10 +00:00
Philip Herron
c005754701 gccrs: add diagnostic for E0229 no associated type arguments allowed here
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>
2025-02-12 19:35:14 +00:00
Philip Herron
eee682ce81 gccrs: remove name resolution inserts from type-path
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>
2025-02-12 19:35:14 +00:00
Philip Herron
dbb51c03ab gccrs: enum type layout needs to respect the enum repr type
Addresses Rust-GCC#3352

gcc/rust/ChangeLog:

	* backend/rust-compile-type.cc (TyTyResolveCompile::get_implicit_enumeral_node_type):
	use repr
	(TyTyResolveCompile::visit): update prototype
	* backend/rust-compile-type.h: likewise

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2025-02-11 20:53:06 +00:00
Philip Herron
262040ea66 gccrs: add variant_count intrinsic
Addresses Rust-GCC#3348

gcc/rust/ChangeLog:

	* backend/rust-compile-intrinsic.cc (variant_count_handler): new intrinsic

gcc/testsuite/ChangeLog:

	* rust/execute/torture/enum_intrinsics2.rs: New test.

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2025-02-11 17:42:44 +00:00
Philip Herron
3fd738ca7b gccrs: add discriminant value intrinsic
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>
2025-02-11 15:44:05 +00:00
GS-GOAT
af234dd6a9 Get rid of duplicate interface #3396
gcc/rust/ChangeLog:

	* typecheck/rust-autoderef.cc
	(insert_implicit_type): Update single-parameter call to
	pass explicit HirId.
	* typecheck/rust-hir-type-check-expr.cc: Same.
	* typecheck/rust-hir-type-check-pattern.cc: Same.
	* typecheck/rust-hir-type-check.h: Removed call
	to the duplicate interface.
	* typecheck/rust-typecheck-context.cc
	(TypeCheckContext::insert_implicit_type): Removed the
	interface with no HirId field.

Signed-off-by: Guransh Singh <guransh766@gmail.com>
2025-02-08 12:52:57 +05:30
Philip Herron
7691105e19 gccrs: remove bad type checking diagnostic
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>
2025-02-04 17:19:12 +00:00
Arthur Cohen
5fb06c9be8 session manager: Call into DesugarForLoops
gcc/rust/ChangeLog:

	* rust-session-manager.cc (Session::compile_crate): Call the visitor.
2025-02-04 15:09:51 +00:00
Arthur Cohen
0d4b15cb70 ast: Add DesugarForLoop class
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
2025-02-04 15:09:51 +00:00
Arthur Cohen
28a87acaff ast: builder: Fix arguments of Builder::let
gcc/rust/ChangeLog:

	* ast/rust-ast-builder.h: Mark all arguments as &&.
	* ast/rust-ast-builder.cc (Builder::let): Likewise.
2025-02-04 15:09:51 +00:00
Owen Avery
ca227ed872 nr2.0: Resolve instances of TypePath more accurately
gcc/rust/ChangeLog:

	* util/rust-unwrap-segment.cc: New file.
	* util/rust-unwrap-segment.h: New file.
	* Make-lang.in: Add rust-unwrap-segment.o to the object list.
	* resolve/rust-forever-stack.hxx: Include rust-unwrap-segment.h.
	(ForeverStack::find_starting_point): Use unwrap_type_segment.
	(ForeverStack::resolve_segments): Likewise.
	(ForeverStack::resolve_path): Likewise.
	* resolve/rust-late-name-resolver-2.0.cc
	(Late::visit): Resolve type paths using
	NameResolutionContext::resolve_path.
	* resolve/rust-name-resolution-context.h
	(NameResolutionContext::resolve_path): Use
	unwrap_segment_node_id.

gcc/testsuite/ChangeLog:

	* rust/compile/nr2/exclude: Remove entries.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2025-02-04 14:55:12 +00:00
Arthur Cohen
e7306a9312 inline-asm: Fix some warnings
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!.
2025-02-04 13:52:51 +00:00
Pierre-Emmanuel Patry
b3bcaeba11 Add warning about default visitor usage
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>
2025-02-04 13:22:02 +00:00
Philip Herron
4d7e7d94c5 gccrs: Add test case to show issue is fixed
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>
2025-02-04 11:36:49 +00:00
Arthur Cohen
f2164b7040 derive(Default): Add implementation
gcc/rust/ChangeLog:

	* expand/rust-derive.cc (DeriveVisitor::derive): Call DeriveDefault.
	* expand/rust-derive-default.cc: New file.
	* expand/rust-derive-default.h: New file.
	* Make-lang.in: Compile them.

gcc/testsuite/ChangeLog:

	* rust/compile/derive-default1.rs: New test.
	* rust/execute/torture/derive-default1.rs: New test.
	* rust/compile/nr2/exclude: Exclude them.
2025-02-04 08:30:18 +00:00
Arthur Cohen
4ab7564dd2 ast-builder: Add methods for QualifiedPathInExpressions
gcc/rust/ChangeLog:

	* ast/rust-ast-builder.cc (Builder::qualified_path_in_expression): New.
	(Builder::function): Change the return type.
	* ast/rust-ast-builder.h: Declare qualified_path_in_expression functions.
	* expand/rust-derive-debug.cc (DeriveDebug::stub_debug_fn): Adapt to new APIs.
2025-02-04 08:30:18 +00:00
Philip Herron
d3c98218ea gccrs: Fix compilation of trait-items which map to impl items
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>
2025-02-04 00:14:23 +00:00
Philip Herron
68e24e2562 gccrs: Fix bad generic substitution error on fn/adt types
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>
2025-02-03 20:35:58 +00:00
Philip Herron
842c1cf95d gccrs: Fix crash in privay reporter for placeholder types
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>
2025-02-03 20:35:50 +00:00
Philip Herron
12e9f5d02a gccrs: coercion sites allow for type inference as well.
Addresses Rust-GCC#3382 and Rust-GCC#3381

gcc/rust/ChangeLog:

	* typecheck/rust-type-util.cc (coercion_site): allow inference vars

gcc/testsuite/ChangeLog:

	* rust/compile/reference1.rs: fix error message

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2025-02-03 19:46:20 +00:00
Philip Herron
218df42d73 gccrs: Fix ICE during path probe
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>
2025-02-03 19:20:26 +00:00
Philip Herron
9449c935b3 gccrs: Fix ICE when fn_once and fn_once_output lang item is not defined
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>
2025-02-03 19:20:22 +00:00
Owen Avery
668c3bf7b7 Fix bug in type resolution of paths
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>
2025-02-03 11:44:49 +00:00
Owen Avery
a4a3183322 nr2.0: Remove accidental copies of resolver
gcc/rust/ChangeLog:

	* backend/rust-compile-expr.cc
	(CompileExpr::generate_closure_function): Take
	NameResolutionContext by reference instead of by value.
	* backend/rust-compile-item.cc
	(CompileItem::visit): Likewise.
	* backend/rust-compile-resolve-path.cc
	(ResolvePathRef::resolve): Likewise.
	* checks/lints/rust-lint-marklive.cc
	(MarkLive::find_ref_node_id): 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-path.cc
	(TypeCheckExpr::resolve_root_path): Likewise.
	* typecheck/rust-hir-type-check-type.cc
	(TypeCheckType::resolve_root_path): Likewise.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2025-02-03 10:46:41 +00:00
Arthur Cohen
4a053730c5 ast: builder: Add Return expression builder
gcc/rust/ChangeLog:

	* ast/rust-ast-builder.h: Declare it.
	* ast/rust-ast-builder.cc (Builder::return_expr): Define it.
2025-02-02 18:31:22 +00:00
Arthur Cohen
df1a65d6d2 derive(Debug): Add stub implementation.
gcc/rust/ChangeLog:

	* expand/rust-derive-debug.cc: New file.
	* expand/rust-derive-debug.h: New file.
	* Make-lang.in: Compile them.
	* expand/rust-derive.cc (DeriveVisitor::derive): Call into DeriveDebug.

gcc/testsuite/ChangeLog:

	* rust/compile/derive-debug1.rs: New test.
	* rust/compile/nr2/exclude: Exclude it.
2025-02-02 18:29:35 +00:00
Arthur Cohen
3d5355f06c derive(Clone, Copy): Cleanup using new method from DeriveVisitor
gcc/rust/ChangeLog:

	* expand/rust-derive-clone.cc: Cleanup using DeriveVisitor::setup_impl_generics.
	* expand/rust-derive-copy.cc: Likewise.
2025-02-02 18:29:35 +00:00
Arthur Cohen
8a768c72cc derive-visitor: Add method for setting up derived impl generics
gcc/rust/ChangeLog:

	* expand/rust-derive.cc (DeriveVisitor::setup_impl_generics): New method.
	* expand/rust-derive.h: Declare it, define DeriveVisitor::ImplGenerics struct.
2025-02-02 18:29:35 +00:00
Arthur Cohen
f4c396ce22 ast-builder: Add new methods for functions, traits and tuples.
gcc/rust/ChangeLog:

	* ast/rust-ast-builder.cc: New methods.
	* ast/rust-ast-builder.h: Declare them.
2025-02-02 18:29:35 +00:00
Arthur Cohen
b57ab7aaa7 ast-builder: Add new functions to create type paths.
gcc/rust/ChangeLog:

	* ast/rust-ast-builder.cc (Builder::type_path): New functions.
	* ast/rust-ast-builder.h: Declare them.
2025-02-02 18:29:35 +00:00
Arthur Cohen
e42c64242b scan-deadcode: Do not warn unused fields if they start with '_'
gcc/rust/ChangeLog:

	* checks/lints/rust-lint-scan-deadcode.h: Check if the field name starts with an
	underscore before warning.
2025-02-02 18:29:18 +00:00
Arthur Cohen
9d6bd59e86 lang-items: Add structural_{peq, teq}
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.
2025-02-02 18:28:58 +00:00
Arthur Cohen
adf6afb820 nr2.0: late: Add proper handling for lang item PathInExpressions
gcc/rust/ChangeLog:

	* resolve/rust-late-name-resolver-2.0.cc (Late::visit): Special case lang item paths.
2025-02-02 18:28:48 +00:00
Owen Avery
af2fdca5a3 Fix an issue with ForeverStack::dfs_rib
gcc/rust/ChangeLog:

	* resolve/rust-forever-stack.hxx
	(ForeverStack::dfs_rib): Fix const implementation.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2025-02-02 18:27:53 +00:00
Liam Naddell
761d424d2a Add option_env! support
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
2025-01-31 15:44:25 +00:00
Arthur Cohen
51a2da3d56 ast: Add new Expr::Kinds
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()
2025-01-30 12:06:37 +00:00
Philip Herron
ad46f0871d gccrs: add support for ref literal patterns
Fixes Rust-GCC#3174

gcc/rust/ChangeLog:

	* backend/rust-compile-pattern.cc (CompilePatternBindings::visit): make recursive
	* typecheck/rust-hir-type-check-pattern.cc (TypeCheckPattern::visit): handle ref flag

gcc/testsuite/ChangeLog:

	* rust/compile/nr2/exclude: nr2 cant handle this
	* rust/compile/issue-3174.rs: New test.

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2025-01-29 17:41:24 +00:00
Arthur Cohen
3c21102b73 lang-items: Add From::from
gcc/rust/ChangeLog:

	* util/rust-lang-item.h: Declare it.
	* util/rust-lang-item.cc: Use it.
2025-01-29 16:26:25 +00:00
Philip Herron
618f41a3cd gccrs: add new -frust-overflow-checks flag to control overflow checks
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>
2025-01-29 15:29:48 +00:00
Pierre-Emmanuel Patry
84bca6f271 Remove some passing test from exclude file
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>
2025-01-29 10:45:07 +00:00
Pierre-Emmanuel Patry
7ba77d01d7 Compile unit struct with constructor
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>
2025-01-29 10:45:07 +00:00
Pierre-Emmanuel Patry
05348933bd Resolved item type shall be differentiated later
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>
2025-01-29 10:45:07 +00:00
Pierre-Emmanuel Patry
47fd13da4f Make foreverstack debug string const
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>
2025-01-29 10:45:07 +00:00
Pierre-Emmanuel Patry
22d1661fd1 Clone expr instead of taking it
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>
2025-01-29 10:45:07 +00:00
Pierre-Emmanuel Patry
88fa2ca42f Remove some tests from nr2 exclusion file
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>
2025-01-29 10:45:07 +00:00
Pierre-Emmanuel Patry
e9659126e7 Remove query mode on CompileItem
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>
2025-01-29 10:45:07 +00:00
Pierre-Emmanuel Patry
a7419e6998 Add unit struct to name namespace in old resolver
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>
2025-01-29 10:45:07 +00:00
Pierre-Emmanuel Patry
55c047ebe1 Add debug dump to old name resolver
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>
2025-01-29 10:45:07 +00:00
Pierre-Emmanuel Patry
b6a77c4640 Labels shall be pushed within label namespace
Labels were using the wrong namespace.

gcc/rust/ChangeLog:

	* resolve/rust-ast-resolve-expr.cc (ResolveExpr::visit): Change label
	push function from type rib to label rib.
	* resolve/rust-ast-resolve-item.cc (ResolveTraitItems::visit):
	Likewise.
	(ResolveItem::visit): Likewise.
	(ResolveExternItem::visit): Likewise.
	* resolve/rust-ast-resolve-stmt.h: Likewise.
	* resolve/rust-ast-resolve.cc (NameResolution::go): Likewise.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2025-01-29 10:45:07 +00:00
Arthur Cohen
6a2346279b backend: Improve handling of lang-item PathInExpressions
gcc/rust/ChangeLog:

	* backend/rust-compile-resolve-path.cc (ResolvePathRef::visit): Call into
	resolve_path_like instead.
	(ResolvePathRef::resolve_path_like): New.
	(ResolvePathRef::resolve): Call into resolve_with_node_id.
	* backend/rust-compile-resolve-path.h: Declare new functions and document them.
2025-01-28 17:35:37 +00:00
Arthur Cohen
9f2c6de835 ast: Add Path::is_lang_item()
gcc/rust/ChangeLog:

	* ast/rust-path.h: New function.
2025-01-28 17:35:37 +00:00
Arthur Cohen
df15601da5 marklive: Fix handling for lang item PathInExpressions.
gcc/rust/ChangeLog:

	* checks/lints/rust-lint-marklive.cc (MarkLive::visit): Adapt to lang items.
2025-01-28 17:35:37 +00:00
Arthur Cohen
a7d273ca77 hir: Adapt visitors to lang item PathInExpressions
gcc/rust/ChangeLog:

	* backend/rust-compile-resolve-path.cc (ResolvePathRef::visit): Adapt visitor to lang item
	HIR::PathInExpressions.
	* typecheck/rust-hir-type-check-path.cc (TypeCheckExpr::visit): Likewise.
2025-01-28 17:35:37 +00:00
Arthur Cohen
068e33b4f8 hir: Add LangItem paths to PathPattern class
gcc/rust/ChangeLog:

	* hir/tree/rust-hir-path.h: Adapt PathPattern to accept lang-item paths.
	* hir/tree/rust-hir-path.cc: Assert we are dealing with a segmented path, create lang-item
	constructors.
	* hir/tree/rust-hir.cc (PathPattern::convert_to_simple_path): Likewise.
2025-01-28 17:35:37 +00:00
Arthur Cohen
38bee03f98 ast: More visitors to allow lang item paths in expressions
gcc/rust/ChangeLog:

	* ast/rust-ast-collector.cc (TokenCollector::visit): Adapt visitor to lang item
	PathInExpressions.
	* 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.cc (ASTLoweringExprWithBlock::visit): Likewise.
	(ASTLowerPathInExpression::visit): Likewise.
	* resolve/rust-ast-resolve-path.cc (ResolvePath::resolve_path): Likewise.
	* resolve/rust-early-name-resolver.cc (EarlyNameResolver::visit): Likewise.
2025-01-28 17:35:37 +00:00
Arthur Cohen
52ffcb82ec lang-items: Add LangItem::IsEnumVariant
gcc/rust/ChangeLog:

	* util/rust-lang-item.cc (LangItem::IsEnumVariant): New function.
	* util/rust-lang-item.h: Declare it.
2025-01-28 17:35:37 +00:00
Arthur Cohen
e6a2ce133f mappings: Improve error message for get_lang_item_node
gcc/rust/ChangeLog:

	* util/rust-hir-map.cc (Mappings::get_lang_item_node): Better formatting when a lang
	item does not exist when it should.
2025-01-28 17:35:37 +00:00
Arthur Cohen
33d901d127 lang-items: Collect enum variants as lang items
gcc/rust/ChangeLog:

	* ast/rust-collect-lang-items.h: Declare visitor.
	* ast/rust-collect-lang-items.cc (CollectLangItems::visit): New.
2025-01-28 17:35:37 +00:00
Philip Herron
60e0d0453f gccrs: catch missing guard for optional result
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>
2025-01-28 14:08:06 +00:00
Dylan Gardner
a3e147802e Infer crate name after file opening
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.
2025-01-28 08:07:02 +00:00
Pierre-Emmanuel Patry
98d89d58d7 Add captures for ClosureExprInnerTyped with nr2
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>
2025-01-24 16:31:36 +00:00
Pierre-Emmanuel Patry
2b473162d3 Add environment capture to NR2
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>
2025-01-24 16:31:36 +00:00
Owen Avery
dd750c98ce Update upload-artifact to v4
ChangeLog:

	* .github/workflows/ccpp.yml: Update actions/upload-artifact
	from v3 to v4, handle any artifact name conflicts.
	* .github/workflows/ccpp32alpine.yml: Likewise.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2025-01-24 01:30:03 +00:00
Owen Avery
0a12536655 Check for type paths nr2.0 can't handle yet
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>
2025-01-23 13:48:47 +00:00
Arthur Cohen
3638b0551e backend: Allow anything as a match scrutinee
gcc/rust/ChangeLog:

	* backend/rust-compile-expr.cc (check_match_scrutinee): Allow anything to be used as a
	match scrutinee, not just ADTs.
2025-01-23 13:19:27 +00:00
Arthur Cohen
b87fd67fa8 lang-items: Add Result and Try lang items
gcc/rust/ChangeLog:

	* util/rust-lang-item.h: Add handling for Result::Ok, Result::Err, Try, Try::into_result,
	Try::from_ok, Try::from_err.
	* util/rust-lang-item.cc: Likewise.

gcc/testsuite/ChangeLog:

	* rust/compile/try-trait.rs: New test.
2025-01-21 17:53:36 +00:00
Pierre-Emmanuel Patry
289bf52597 Fix rust breakage with nr2
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>
2025-01-21 16:45:34 +00:00
Arthur Cohen
490c70374d derive(Copy): Improve bounds when deriving Copy
gcc/rust/ChangeLog:

	* expand/rust-derive-copy.cc: Always add an extra Copy bound on generic Copy impls.
2025-01-21 15:18:52 +00:00
Arthur Cohen
1f39e0f2cb derive(Clone): Use lang item bounds on AssertParamIsCopy
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.
2025-01-21 13:54:14 +00:00
Arthur Cohen
2d76d473f7 derive(Clone): Add Clone bound on generated impl blocks
gcc/rust/ChangeLog:

	* expand/rust-derive-clone.cc: Add extra bound when deriving generic Clone
2025-01-21 13:54:14 +00:00
Arthur Cohen
c53c8d70e8 ast-builder: Add extra parameter for TypeParam builder
gcc/rust/ChangeLog:

	* ast/rust-ast-builder.cc (Builder::new_type_param): Add optional extra trait bounds.
	* ast/rust-ast-builder.h: Likewise.
2025-01-21 13:54:14 +00:00
Arthur Cohen
c84c92ac0f hir-dump: Improve handling of typepathsegments that are lang items.
gcc/rust/ChangeLog:

	* hir/rust-hir-dump.cc (Dump::do_typepathsegment): Add handling for lang items.
2025-01-21 13:54:14 +00:00
lishin
8a50054579 lang-item:Add LangItem::Kind::RECEIVER
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>
2025-01-21 13:47:20 +00:00
Arthur Cohen
53dfc6acf9 typecheck: Add basic handling for applying auto trait bounds
gcc/rust/ChangeLog:

	* hir/rust-ast-lower-item.cc (ASTLoweringItem::visit): Register auto traits in mappings.
	* util/rust-hir-map.cc (Mappings::insert_auto_trait): New.
	(Mappings::get_auto_traits): New.
	* util/rust-hir-map.h: Declare them.
	* typecheck/rust-tyty-bounds.cc (TypeBoundsProbe::scan): Add auto trait bounds when
	scanning.

gcc/testsuite/ChangeLog:

	* rust/compile/nr2/exclude: Some parts of nr2.0 can't handle auto traits yet.
	* rust/compile/auto_traits3.rs: Removed in favor of...
	* rust/compile/auto_traits2.rs: ...this one.
	* rust/compile/auto_traits4.rs: New test.
2025-01-21 13:45:16 +00:00
Arthur Cohen
9e876359e3 typecheck: Separate assemble_builtin_candidate in two
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.
2025-01-21 13:45:16 +00:00
Arthur Cohen
9c6e09e2f7 nr2.0: late: Better format PathInExpression resolution
gcc/rust/ChangeLog:

	* resolve/rust-late-name-resolver-2.0.cc (Late::visit): Improve formatting.
2025-01-20 12:09:26 +00:00
Arthur Cohen
1c47dbe119 derive(Clone): Add lang item typepaths failure testcases to nr2 exclude
gcc/testsuite/ChangeLog:

	* rust/compile/nr2/exclude: Add failing lang item typepaths tests.
	* rust/execute/torture/derive_macro4.rs: Mark Clone as lang item.
2025-01-20 12:09:26 +00:00
Arthur Cohen
f027f0a605 derive(Clone): Implement derive clone for enum struct variants
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.
2025-01-20 12:09:26 +00:00
Arthur Cohen
40574e5eb0 derive(Clone): Implement clone for enum tuple variants
gcc/rust/ChangeLog:

	* expand/rust-derive-clone.cc (DeriveClone::variant_match_path): New function.
	(DeriveClone::clone_enum_identifier): Rename.
	(DeriveClone::clone_enum_tuple): New function.
	(DeriveClone::visit_enum): Visit tuple variants properly.
	* expand/rust-derive-clone.h: Declare new functions.
2025-01-20 12:09:26 +00:00
Arthur Cohen
78d4fe9d25 ast-builder: Add new methods for building structs
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.
2025-01-20 12:09:26 +00:00
Arthur Cohen
43747f4062 derive(Clone): Add deriving of simple enum variants
gcc/rust/ChangeLog:

	* expand/rust-derive-clone.cc: Clone enum identifier variants properly
	* expand/rust-derive-clone.h: Declare new functions used.
2025-01-20 12:09:26 +00:00
Arthur Cohen
0722d35b69 derive(Clone): Improve existing testcase
gcc/testsuite/ChangeLog:

	* rust/compile/derive_macro4.rs: Mark Copy and Clone as lang items.
2025-01-20 12:09:26 +00:00
Arthur Cohen
0c52c4c271 derive(Clone): Add note about Clone::clone()
gcc/rust/ChangeLog:

	* expand/rust-derive-clone.cc (DeriveClone::clone_call): Mention using `clone_fn`
	lang item in the future.
2025-01-20 12:09:26 +00:00
Arthur Cohen
e8d3ccf05d derive(Clone): Use lang item for PhantomData in Clone
gcc/rust/ChangeLog:

	* expand/rust-derive-clone.cc (DeriveClone::visit_union): Create a lang item path
	instead of a regular path.
2025-01-20 12:09:26 +00:00
Arthur Cohen
4b3588023e ast-builder: Add new methods around type paths.
gcc/rust/ChangeLog:

	* ast/rust-ast-builder.cc: New functions.
	* ast/rust-ast-builder.h: Declare them.
2025-01-20 12:09:26 +00:00
Arthur Cohen
1a0ec0ec4c derive(Copy): Use copy lang item when deriving Copy.
gcc/rust/ChangeLog:

	* expand/rust-derive-copy.cc: Use lang item path.
2025-01-20 12:09:26 +00:00
Arthur Cohen
533abf7e53 derive(Clone): Mark PhantomData as a lang item
gcc/testsuite/ChangeLog:

	* rust/compile/derive_macro4.rs: Make PhantomData a lang item.
2025-01-20 12:09:26 +00:00
Arthur Cohen
d970cf081f derive(Clone): Manually generate AssertParamIsCopy struct for unions
gcc/rust/ChangeLog:

	* expand/rust-derive-clone.cc (DeriveClone::visit_union): Manually generate
	the struct used for asserting a union implements Copy.
2025-01-20 12:09:26 +00:00
Arthur Cohen
cd7930c162 builder: Allow generating struct statements
gcc/rust/ChangeLog:

	* ast/rust-ast-builder.cc (Builder::struct_struct): New function.
	* ast/rust-ast-builder.h (vec): New function.
2025-01-20 12:09:26 +00:00
Arthur Cohen
3351befe04 lang-items: Mark Clone trait as a lang item in testsuite
gcc/testsuite/ChangeLog:

	* rust/compile/derive_macro1.rs: Add #[lang = "clone"] to Clone trait.
	* rust/compile/derive_macro3.rs: Likewise.
	* rust/compile/derive_macro6.rs: Likewise.
	* rust/execute/torture/derive_macro3.rs: Likewise.
2025-01-20 12:09:26 +00:00
Arthur Cohen
aacecbae35 ast-collector: Fix tuple struct pattern collection
gcc/rust/ChangeLog:

	* ast/rust-ast-collector.cc (TokenCollector::visit): Visit tuple pattern items as
	separated by commas.
2025-01-16 14:00:31 +00:00
Arthur Cohen
b8eb6cd447 ast-collector: Adapt to lang item type path segments
gcc/rust/ChangeLog:

	* ast/rust-ast-collector.cc (TokenCollector::visit): Fix collector to better
	handle lang item type path segments.
2025-01-16 14:00:31 +00:00
Arthur Cohen
115df22636 mappings: Add get_lang_item_node
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.
2025-01-16 14:00:31 +00:00
Arthur Cohen
68f142a0e9 lang-item: Add LangItem::PrettyString
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.
2025-01-16 14:00:31 +00:00
Arthur Cohen
0bde282a59 lang-items: Collect struct lang items.
gcc/rust/ChangeLog:

	* ast/rust-collect-lang-items.cc (CollectLangItems::visit): New.
	* ast/rust-collect-lang-items.h: New.
2025-01-16 14:00:31 +00:00
Arthur Cohen
15b928c77f lower: Properly lower non-generic lang item type path segments.
gcc/rust/ChangeLog:

	* hir/rust-ast-lower-type.cc (ASTLowerTypePath::visit): Adapt code to lang item
	type path segments.
2025-01-16 14:00:31 +00:00
Arthur Cohen
e7011f6293 tychk: resolve lang item type paths properly
gcc/rust/ChangeLog:

	* typecheck/rust-hir-type-check-type.cc (TypeCheckType::resolve_root_path): Adapt
	code to handle lang item type paths.
2025-01-16 14:00:31 +00:00
Arthur Cohen
432859bf78 ast: Refactor how lang item paths are handled.
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.
2025-01-16 14:00:31 +00:00
Arthur Cohen
955c4f7e58 collect-lang-items: Display attribute upon error finding it
gcc/rust/ChangeLog:

	* ast/rust-collect-lang-items.cc (get_lang_item_attr): Show unknown attribute upon error.
2025-01-16 14:00:31 +00:00
Arthur Cohen
e530ccb311 attributes: Add #[derive] as a built-in attribute
gcc/rust/ChangeLog:

	* util/rust-attribute-values.h: Declare new attribute value.
	* util/rust-attributes.cc: Use it.
2025-01-16 14:00:31 +00:00
Arthur Cohen
035990c57b ast: Fix warning about copy elision for moved expr
gcc/rust/ChangeLog:

	* ast/rust-ast.cc (BlockExpr::normalize_tail_expr): Remove overzealous
	std::move
2025-01-16 14:00:31 +00:00
Owen Avery
bb580033c6 Remove dead code related to external functions
gcc/rust/ChangeLog:

	* ast/rust-ast-collector.cc
	(TokenCollector::visit): Remove visitor for NamedFunctionParam.
	* ast/rust-ast-collector.h
	(TokenCollector::visit): Likewise.
	* ast/rust-ast-full-decls.h
	(class NamedFunctionParam): Remove forward declaration.
	* ast/rust-ast-visitor.cc
	(DefaultASTVisitor::visit): Remove visitor for
	NamedFunctionParam.
	* ast/rust-ast-visitor.h
	(DefaultASTVisitor::visit): Likewise.
	* ast/rust-ast.cc
	(NamedFunctionParam::as_string): Remove.
	* ast/rust-item.h
	(class NamedFunctionParam): Remove.
	(class ExternalFunctionItem): Remove.
	* parse/rust-parse-impl.h
	(Parser::parse_named_function_param): Remove.
	(Parser::parse_named_function_params): Remove.
	* parse/rust-parse.h
	(Parser::parse_named_function_param): Remove.
	(Parser::parse_named_function_params): Remove.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2025-01-13 13:14:06 +00:00
Owen Avery
c6b3dab560 nr2.0: Early resolve pending eager macro invocations
gcc/rust/ChangeLog:

	* resolve/rust-early-name-resolver-2.0.cc
	(Early::visit): Resolve the pending eager invocations inside
	builtin macro invocations.

gcc/testsuite/ChangeLog:

	* rust/compile/nr2/exclude: Remove entries.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2025-01-13 13:13:46 +00:00
Philip Herron
0a935444fb gccrs: Add missing name resolution to static items in blocks
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>
2025-01-13 13:13:19 +00:00
CohenArthur
5db9ab5426 Revert "gcc/rust/ChangeLog:"
This reverts commit 600fd806b8.
2025-01-10 14:54:18 +00:00
Arthur Cohen
aa8d6981fd gccrs: Fix scan-gimple testcases on LE platforms.
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.
2025-01-10 13:34:58 +00:00
Arthur Cohen
3474059707 testsuite: Fix missing handling of little endian.
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.
2025-01-10 13:34:58 +00:00
Owen Avery
248633dd1e Add ForeverStackStore
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>
2025-01-10 12:59:22 +00:00
Om Swaroop Nayak
600fd806b8 gcc/rust/ChangeLog:
* ast/rust-collect-lang-items.cc (get_lang_item_attr): "removed checker fn"
	* util/rust-attributes.cc (Attributes::is_lang_item): "added fn"
	* util/rust-attributes.h: "added fn"

Signed-off-by: Om Swaroop Nayak <96killerat96@gmail.com>
2025-01-10 12:34:55 +00:00
Philip Herron
c957f18575 gccrs: improve mutability checks
This ensures that we handle var decls readonly checks much better

Addresses: Rust-GCC#807 Rust-GCC#3287

gcc/rust/ChangeLog:

	* checks/errors/rust-readonly-check.cc (check_decl): improve mut check
	(emit_error): helper
	(check_modify_expr): likewise
	(readonly_walk_fn): reuse helper
	(ReadonlyCheck::Lint): cleanup context each run

gcc/testsuite/ChangeLog:

	* rust/execute/torture/builtin_macro_include_bytes.rs: needs mut
	* rust/compile/mutability_checks1.rs: New test.

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2025-01-10 10:43:13 +00:00
Owen Avery
f68fbff016 Visit the trait paths of trait implementations
gcc/rust/ChangeLog:

	* ast/rust-ast-visitor.cc
	(DefaultASTVisitor::visit): When visiting a TraitImpl, visit its
	trait path.

gcc/testsuite/ChangeLog:

	* rust/compile/nr2/exclude: Remove entries.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2025-01-10 10:11:30 +00:00
liushuyu
c82a879f21 gccrs: add two more tests to test try-catch (unwind) code generation
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
2025-01-10 10:10:01 +00:00
liushuyu
66669cd668 rust/intrinsic: add new "catch_unwind" variant of API
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`.
2025-01-10 10:10:01 +00:00
liushuyu
077bd4618b rust/intrinsic: add try intrinsic and panic strategy options
gcc/rust/ChangeLog:
	* backend/rust-compile-intrinsic.cc: add `try` intrinsic handler.
	* lang.opt: add `-frust-panic` option.
	* rust-lang.cc: enable exception handler code generation.
	* rust-session-manager.cc: add getter and setter for panic
	strategy option.
	* rust-session-manager.h: Likewise.

Signed-off-by: Zixing Liu <liushuyu011@gmail.com>
2025-01-10 10:10:01 +00:00
Philip Herron
b4a525ce39 gccrs: match arms are a LUB
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>
2025-01-10 09:28:52 +00:00
Nobel
c960e034f3 Allow float type to be casted as integer type
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>
2025-01-10 09:08:00 +00:00
Philip Herron
806166db9d gccrs: cleanup our enum type layout to be closer to rustc
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>
2025-01-10 09:04:48 +00:00
Owen Avery
1eaf085607 nr2.0: Resolve Self inside impl blocks
gcc/rust/ChangeLog:

	* resolve/rust-toplevel-name-resolver-2.0.cc
	(TopLevel::visit): Insert a definition for Self when visiting
	InherentImpl and TraitImpl instances.
	* resolve/rust-toplevel-name-resolver-2.0.h
	(TopLevel::visit): Add visitors for InherentImpl and TraitImpl.

gcc/testsuite/ChangeLog:

	* rust/compile/nr2/exclude: Remove entries.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2025-01-08 13:10:22 +00:00
Philip Herron
02601c7470 gccrs: fix ICE with hir dump on closure
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>
2025-01-07 21:04:56 +00:00
Philip Herron
e891887bf6 gccrs: add support for lang_item eq and PartialEq trait
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>
2025-01-07 21:04:52 +00:00
Philip Herron
5bccf14d99 gccrs: fix ICE in borrows to invalid expressions
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>
2025-01-07 16:33:05 +00:00
Owen Avery
fa6747f326 nr2.0: Improve default, top-level, and late resolvers
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>
2025-01-07 13:30:29 +00:00
Philip Herron
48aa71c3a7 gccrs: fix ICE during HIR dump
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>
2025-01-06 12:31:50 +00:00
Prajwal S N
a62630f990 gccrs: use StackedContexts for block context
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>
2025-01-06 11:13:30 +00:00
Arthur Cohen
26d3103c2d ast: Add new Kind enums for more precise downcasting
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.
2025-01-06 10:08:17 +00:00
Owen Avery
43369f262c nr2.0: Resolve type aliases inside trait definitions
gcc/rust/ChangeLog:

	* resolve/rust-toplevel-name-resolver-2.0.cc
	(TopLevel::visit): Add visitor for TraitItemType.
	* resolve/rust-toplevel-name-resolver-2.0.h
	(TopLevel::visit): Likewise.

gcc/testsuite/ChangeLog:

	* rust/compile/nr2/exclude: Remove entries.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2025-01-06 10:06:02 +00:00
Arthur Cohen
9de42352bb tychk: Add more support for additional trait bounds in functions
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.
2025-01-03 11:19:08 +00:00
Arthur Cohen
31d3f550ba lower: Correctly lower parenthesized types
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.
2025-01-03 11:19:08 +00:00
Owen Avery
de8606fc72 Remove Rust::make_unique
Since our bootstrap requirement has been bumped to C++14, we don't need
a custom implementation of std::make_unique anymore.

gcc/rust/ChangeLog:

	* ast/rust-ast-builder-type.cc: Remove inclusion of
	rust-make-unique.h.
	* ast/rust-ast-builder.cc: Likewise.
	(Builder::array): Use std::make_unique instead of
	Rust::make_unique.
	* ast/rust-ast.cc (Attribute::get_traits_to_derive): Likewise.
	* ast/rust-macro.h: Remove inclusion of rust-make-unique.h.
	(MacroRulesDefinition::mbe): Use std::make_unique instead of
	Rust::make_unique.
	(MacroRulesDefinition::decl_macro): Likewise.
	* ast/rust-path.h
	(PathInExpression::PathInExpression): Likewise.
	(QualifiedPathInExpression::QualifiedPathInExpression):
	Likewise.
	* backend/rust-compile-pattern.cc
	(CompilePatternCheckExpr::visit): Likewise.
	* expand/rust-derive-copy.cc
	(DeriveCopy::copy_impl): Likewise.
	* expand/rust-expand-format-args.cc
	(expand_format_args): Likewise.
	* expand/rust-macro-builtins-asm.cc: Remove inclusion of
	rust-make-unique.h.
	(parse_asm): Use std::make_unique instead of Rust::make_unique.
	* hir/rust-ast-lower-expr.cc
	(ASTLoweringExpr::visit): Likewise.
	* hir/tree/rust-hir-expr.cc
	(StructExprStructFields::StructExprStructFields): Likewise.
	(StructExprStructFields::operator=): Likewise.
	* hir/tree/rust-hir.cc
	(TypePath::to_trait_bound): Likewise.
	* lex/rust-token.h: Remove inclusion of rust-make-unique.h.
	(Token::Token): Use std::make_unique instead of
	Rust::make_unique.
	* metadata/rust-import-archive.cc: Remove inclusion of
	rust-make-unique.h.
	(Import::find_archive_export_data): Use std::make_unique instead
	of Rust::make_unique.
	* metadata/rust-imports.cc: Remove inclusion of
	rust-make-unique.h.
	(Import::find_export_data): Use std::make_unique instead of
	Rust::make_unique.
	(Import::find_object_export_data): Likewise.
	* parse/rust-parse-impl.h: Remove inclusion of
	rust-make-unique.h.
	(Parser::parse_function_param): Use std::make_unique instead of
	Rust::make_unique.
	(Parser::parse_self_param): Likewise.
	(Parser::parse_array_expr): Likewise.
	* typecheck/rust-hir-type-check-enumitem.cc
	(TypeCheckEnumItem::visit): Likewise.
	* typecheck/rust-hir-type-check-implitem.cc
	(TypeCheckTopLevelExternItem::visit): Likewise.
	(TypeCheckImplItem::visit): Likewise.
	* typecheck/rust-hir-type-check-type.cc
	(TypeResolveGenericParam::visit): Likewise.
	* typecheck/rust-hir-type-check.cc: Remove inclusion of
	rust-make-unique.h.
	(TraitItemReference::get_type_from_fn): Use std::make_unique
	instead of Rust::make_unique.
	* typecheck/rust-tyty-bounds.cc
	(TypeCheckBase::get_predicate_from_bound): Likewise.
	* util/rust-make-unique.h: Removed.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2025-01-03 11:16:48 +00:00
Arthur Cohen
daf98a1495 ast: Add EnumItem::Kind
gcc/rust/ChangeLog:

	* ast/rust-item.h: Add EnumItem::Kind for differentiating all variants that may be
	used inside an enum declaration.
2025-01-03 10:51:46 +00:00
Owen Avery
db11825344 nr2.0: Handle "Self" properly in trait definitions
gcc/rust/ChangeLog:

	* ast/rust-ast-visitor.cc
	(DefaultASTVisitor::visit): Visit implicit Self parameters of
	traits.
	* resolve/rust-late-name-resolver-2.0.cc
	(Late::visit): Resolve implicit Self parameters of traits.
	* resolve/rust-late-name-resolver-2.0.h:
	(Late::visit): Add trait visitor.
	* resolve/rust-toplevel-name-resolver-2.0.cc
	(TopLevel::visit): Insert resolutions for Self type parameters
	as well.

gcc/testsuite/ChangeLog:

	* rust/compile/nr2/exclude: Remove entries.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2025-01-02 09:39:46 +00:00
Liam Naddell
198d3ee34f Fix NR2.0 compiler ICE caused by Generics in Enums
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>
2025-01-02 09:34:36 +00:00
Arthur Cohen
62058776ed ast-builder: Add more methods
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.
2024-12-31 17:24:55 +00:00
Arthur Cohen
ec1cf23240 ast: Add new constructors for PathInExpression
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.
2024-12-31 17:24:55 +00:00
Arthur Cohen
9a07804e4d lang-items: Collect trait functions that are lang items
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.
2024-12-31 17:24:49 +00:00
Arthur Cohen
699fdd4546 lang-item: Add Option::{None, Some}, Iterator::next, IntoIter::into_iter
gcc/rust/ChangeLog:

	* util/rust-lang-item.h: Add new lang items.
	* util/rust-lang-item.cc: Likewise.
2024-12-31 17:24:49 +00:00
Arthur Cohen
5c647947f4 lang-item: Add Sync trait
gcc/rust/ChangeLog:

	* util/rust-lang-item.h: Add Sync marker trait.
	* util/rust-lang-item.cc: Likewise.
2024-12-31 17:00:14 +00:00
Arthur Cohen
1d8041b36c typecheck: Add note about erorring out on additional trait bounds.
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.
2024-12-31 17:00:14 +00:00
Arthur Cohen
5ab3543b1b resolve: Name resolve trait bounds properly
gcc/rust/ChangeLog:

	* resolve/rust-ast-resolve-type.cc (ResolveTypeToCanonicalPath::visit): Resolve additional
	trait bounds.
	* resolve/rust-late-name-resolver-2.0.cc (Late::visit): Error out properly on unresolved
	type-path instead of crashing.

gcc/testsuite/ChangeLog:

	* rust/compile/nr2/exclude: Exclude additional-trait-bounds2 for different error message.
	* rust/compile/additional-trait-bounds1.rs: New test.
	* rust/compile/additional-trait-bounds2.rs: New test.
	* rust/compile/additional-trait-bounds2nr2.rs: New test.
2024-12-31 17:00:14 +00:00
Arthur Cohen
b33f6348b7 parser: Add testcases for multiline strings
Regression checks for Rust-GCC#1399

gcc/testsuite/ChangeLog:

	* rust/compile/multiline-string.rs: New test.
	* rust/execute/torture/multiline-string.rs: New test.
2024-12-31 14:48:34 +00:00
Arthur Cohen
af5fdeebdc typecheck-path: Fix typo (reciever -> receiver)
gcc/rust/ChangeLog:

	* typecheck/rust-hir-path-probe.cc: Fix typos.
	* typecheck/rust-hir-path-probe.h: Likewise.
	* typecheck/rust-hir-type-check-path.cc: Likewise.
2024-12-24 16:23:02 +00:00
Nobel
d28cae596d add ptr to int and int to ptr type cast rules
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>
2024-12-23 14:28:42 +00:00
Philip Herron
b5c354d038 gccrs: disable macos github workflow
Its broken at the moment.

ChangeLog:

	* .github/workflows/ccpp.yml: comment it out

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2024-12-19 14:02:26 +00:00
Sri Ganesh Thota
19fa68dbb0 gccrs: Made changes to AST::TraitImpl constructor for TypePath
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>
2024-12-19 13:41:06 +00:00
Philip Herron
daa2977f3d gccrs: implement the TuplePattern and use it for function patterns
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>
2024-12-13 16:55:07 +00:00
Philip Herron
cc2445cd79 gccrs: fix bad not expression in rust
Fixes Rust-GCC#3229

gcc/rust/ChangeLog:

	* rust-gcc.cc (operator_to_tree_code): ! expressions are BIT_NOT_EXPR

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2024-12-13 11:57:33 +00:00
Sam James
55a9d8d451 ci: update warnings after C++14 change
ChangeLog:
	* .github/glibcxx_ubuntu64b_log_expected_warnings: Update.
	* .github/log_expected_warnings: Update.
2024-12-10 08:14:09 +00:00
Jason Merrill
f3b1216cc6 build: update bootstrap req to C++14
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.
2024-12-10 08:14:09 +00:00
Arthur Cohen
ed1b4d72d9 lang-item: Remove unused NodeId from LangItemPath
gcc/rust/ChangeLog:

	* ast/rust-path.h: Adapt children of Path to fix some NodeId issues.
2024-12-09 14:46:13 +00:00
Arthur Cohen
c0513af26d nr2.0: Resolve lang item paths properly.
gcc/rust/ChangeLog:

	* resolve/rust-late-name-resolver-2.0.cc (Late::visit): New.
	* resolve/rust-late-name-resolver-2.0.h: New.
2024-12-09 14:46:13 +00:00
Arthur Cohen
625c811ed5 hir: Lower lang-item paths
gcc/rust/ChangeLog:

	* hir/rust-ast-lower-type.cc (ASTLowerTypePath::translate): Adapt to
	handle lang item paths.
	(ASTLowerTypePath::visit): Likewise.
	(ASTLowerTypePath::translate_type_path): New.
	(ASTLowerTypePath::translate_lang_item_type_path): New.
	* hir/rust-ast-lower-type.h: Adapt to handle lang item paths.
	* resolve/rust-ast-resolve-type.h: Likewise.
2024-12-09 14:46:13 +00:00
Arthur Cohen
d812c793ef nr1.0: Resolve lang item paths properly.
gcc/rust/ChangeLog:

	* resolve/rust-ast-resolve-item.cc (ResolveItem::visit): Adapt resolver
	to lang item paths.
	* resolve/rust-ast-resolve-type.h: Likewise.
2024-12-09 14:46:13 +00:00
Arthur Cohen
3d2f58db04 hir: Start adapting visitors to accept multiple kinds of Paths
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.
2024-12-09 14:46:13 +00:00
Arthur Cohen
3630428e54 derive(Copy): Use new LangItemPath
gcc/rust/ChangeLog:

	* expand/rust-derive-copy.cc: Use new LangItemPath for derive(Copy).
2024-12-09 14:46:13 +00:00
Arthur Cohen
d2025fe536 ast: Add LangItemPath class
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.
2024-12-09 14:46:13 +00:00
Arthur Cohen
b1273464c2 ci: Update expected warnings list for 32 bits build.
ChangeLog:

	* .github/alpine_32bit_log_warnings: Update with new warnings.
2024-12-09 13:24:42 +00:00
Owen Avery
e6e62d4823 Fix ForeverStack::find_starting_point output parameter
gcc/rust/ChangeLog:

	* resolve/rust-forever-stack.h
	(ForeverStack::find_starting_point): Use type
	'std::reference_wrapper<Node> &' instead of 'Node &' for
	parameter starting_point.
	* resolve/rust-forever-stack.hxx
	(ForeverStack::find_starting_point): Likewise.
	(ForeverStack::resolve_path): Handle change to
	ForeverStack::find_starting_point.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2024-12-09 13:01:42 +00:00
Arthur Cohen
1995c83808 type-check: Remove unused capture in nr2.0
gcc/rust/ChangeLog:

	* typecheck/rust-hir-type-check-type.cc (TypeCheckType::resolve_root_path):
	Remove unused capture in lambda.
2024-12-05 12:39:57 +00:00
Arthur Cohen
72081086d6 attributes: Add class for sharing methods on attributes.
gcc/rust/ChangeLog:

	* util/rust-attributes.h (class Attributes): New.
	* util/rust-attributes.cc: Implement Attributes::is_known().
	* ast/rust-collect-lang-items.cc (is_known_attribute): Remove.
	(get_lang_item_attr): Call Attributes::is_known() instead.
	* hir/rust-ast-lower-base.cc (ASTLoweringBase::handle_outer_attributes): Likewise.
	(ASTLoweringBase::is_known_attribute): Remove.
2024-12-04 17:39:53 +00:00
Arthur Cohen
6b7e055ecc lang-items: Add lang-items AST collector
gcc/rust/ChangeLog:

	* Make-lang.in: Add new object file.
	* rust-session-manager.cc (Session::compile_crate): Call CollectLangItems.
	* ast/rust-collect-lang-items.cc: New file.
	* ast/rust-collect-lang-items.h: New file.
2024-12-04 17:39:53 +00:00
Arthur Cohen
6374da82b7 lang-items: Store NodeId mappings for lang items
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.
2024-12-04 17:39:53 +00:00
Philip Herron
9e07940629 gccrs: fix crash in hir dump
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>
2024-12-02 21:26:55 +00:00
Philip Herron
7a081b0d71 gccrs: add test case to show issue is fixed
Fixes Rust-GCC#266

gcc/testsuite/ChangeLog:

	* rust/compile/nr2/exclude: nr2 cant handle this
	* rust/compile/issue-266.rs: New test.

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2024-12-02 17:48:27 +00:00
Philip Herron
0d00f79134 gccrs: add checks for division by zero and left shift overflow
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>
2024-12-02 17:31:30 +00:00
Philip Herron
db3d8fb22c gccrs: constant evaluation like these are coercion sites
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>
2024-12-02 17:30:59 +00:00
Philip Herron
fa93e280ed gccrs: Remove bad assertion in name resolution
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>
2024-12-02 16:15:54 +00:00
Arthur Cohen
5434de60b9 ast: Use StackedContexts class in ContextualASTVisitor
gcc/rust/ChangeLog:

	* ast/rust-ast-visitor.h: Replace context with StackedContexts.
	* ast/rust-ast-visitor.cc (ContextualASTVisitor::visit): Use new APIs.
	* checks/errors/rust-ast-validation.cc (ASTValidation::visit): Likewise.
2024-12-02 14:35:30 +00:00
Arthur Cohen
3abf72465b stacked-contexts: Add peek() method
gcc/rust/ChangeLog:

	* util/rust-stacked-contexts.h: Add new method to see what context we are currently in.
2024-12-02 14:35:30 +00:00
Arthur Cohen
afbd87358c hir: Remove duplicate function in TraitItemFunc
Both TraitItemFunc::has_definition() and TraitItemFunc::has_block_defined()
were exactly the same implementation, so remove one.

gcc/rust/ChangeLog:

	* hir/tree/rust-hir-item.h: Remove TraitItemFunc::has_block_defined()
	* backend/rust-compile-implitem.cc (CompileTraitItem::visit):
	Call TraitItemFunc::has_definition() instead.
	* checks/errors/rust-const-checker.cc (ConstChecker::visit): Likewise.
	* checks/errors/rust-hir-pattern-analysis.cc (PatternChecker::visit): Likewise.
	* checks/errors/rust-unsafe-checker.cc (UnsafeChecker::visit): Likewise.
	* typecheck/rust-hir-trait-resolve.cc (ResolveTraitItemToRef::visit): Likewise.
2024-11-30 14:24:59 +00:00
Arthur Cohen
10cc6e8e6c mappings: Move lang_item definitions to .cc
gcc/rust/ChangeLog:

	* util/rust-hir-map.h: Move definitions from header...
	* util/rust-hir-map.cc: ...to source file.
2024-11-28 12:35:46 +00:00
Arthur Cohen
1d5f710bfb lang-items: Move comment about arithmetic lang items
gcc/rust/ChangeLog:

	* util/rust-lang-item.h: Fix comment location to align with other comments.
2024-11-28 12:35:46 +00:00
Philip Herron
7bdbcb7564 gccrs: ensure packed and aligned is applied properly
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>
2024-11-27 22:41:32 +00:00
Philip Herron
2aff74974e gccrs: allow casts from numeric types to floats
Fixes Rust-GCC#3261

gcc/rust/ChangeLog:

	* typecheck/rust-casts.cc (TypeCastRules::cast_rules): allow casts to float

gcc/testsuite/ChangeLog:

	* rust/compile/issue-3261.rs: New test.

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2024-11-27 22:41:12 +00:00
Philip Herron
c11ee4f562 gccrs: improve handling of Self Type paths
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>
2024-11-27 22:40:59 +00:00
Philip Herron
a4abbbcffe gccrs: fix crash in hir dump with missing guards
gcc/rust/ChangeLog:

	* hir/rust-hir-dump.cc (Dump::visit): add missing null checks

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2024-11-27 22:40:30 +00:00
Jarkko Sakkinen
f49ec2867b Add build dependencies for Fedora
ChangeLog:

	* README.md: Add fedora deps.

Signed-off-by: Jarkko Sakkinen <jarkko.sakkinen@iki.fi>
2024-11-27 18:33:42 +00:00
Pierre-Emmanuel Patry
79e4295018 Prepend crate name to functions with nr2
gcc/rust/ChangeLog:

	* backend/rust-compile-base.cc: Prepend crate name to function's ir
	name.

gcc/testsuite/ChangeLog:

	* rust/compile/nr2/exclude: Remove passing tests from exclude list.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2024-11-27 15:33:38 +00:00
Marc Poulhiès
8d401933dd ci: change the gcc-5 testing
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>
2024-11-27 15:04:10 +00:00
Marc Poulhiès
c4024137a3 ci: bump actions/checkout from v3 to v4
ChangeLog:

	* .github/workflows/Remark.yml: Use v4.
	* .github/workflows/bootstrap.yml: Likewise.
	* .github/workflows/ccpp.yml: Likewise.
	* .github/workflows/ccpp32alpine.yml: Likewise.
	* .github/workflows/clang-format.yml: Likewise.
	* .github/workflows/commit-format.yml: Likewise.
	* .github/workflows/docker.yml: Likewise.

Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
2024-11-27 15:04:10 +00:00
Sam James
898f2e83a1 CI: upgrade GCC baseline from 4.8 -> 5.4 (5.5)
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.
2024-11-25 21:41:40 +01:00
Marc Poulhiès
fa547376d4 ci: remove bors mention
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>
2024-11-23 17:08:04 +00:00
Owen Avery
eb1c8e462d Prevent execution of some nr1.0 functions with nr2.0
gcc/rust/ChangeLog:

	* resolve/rust-name-resolver.cc: Include options.txt.
	(Resolver::insert_resolved_name): Assert that name resolution
	2.0 is disabled.
	(Resolver::lookup_resolved_name): Likewise.
	(Resolver::insert_resolved_type): Likewise.
	(Resolver::lookup_resolved_type): Likewise.
	(Resolver::insert_resolved_label): Likewise.
	(Resolver::lookup_resolved_label): Likewise.
	(Resolver::insert_resolved_macro): Likewise.
	(Resolver::lookup_resolved_macro): Likewise.
	(Resolver::insert_resolved_misc): Likewise.
	(Resolver::lookup_resolved_misc): Likewise.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2024-11-22 14:18:52 +00:00
Philip Herron
433a092782 gccrs: empty match expressions should resolve to !
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.

Fixes Rust-GCC/gccrs#3231
Fixes Rust-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>
2024-11-22 13:53:47 +00:00
Philip Herron
b3f0d72ba8 gccrs: fix crashes in hir dump since move to references
gcc/rust/ChangeLog:

	* hir/rust-hir-dump.cc (Dump::visit): add guards

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2024-11-22 13:53:47 +00:00
Pierre-Emmanuel Patry
b3a8a1a7c2 Clean up some system includes
System includes shall use rust-system header instead.

gcc/rust/ChangeLog:

	* ast/rust-stmt.h: Remove stdlib include and use rust-system instead.
	* backend/rust-compile-expr.cc: Likewise.
	* backend/rust-mangle-legacy.cc: Likewise.
	* backend/rust-mangle-v0.cc: Likewise.
	* hir/rust-hir-dump.cc: Likewise.
	* typecheck/rust-hir-type-check-type.cc: Likewise.
	* typecheck/rust-tyty.cc: Likewise.
	* typecheck/rust-tyty.h: Likewise.
	* util/rust-common.h: Likewise.
	* util/rust-token-converter.cc: Likewise.
	* util/rust-token-converter.h: Likewise.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2024-11-22 12:08:24 +00:00
Pierre-Emmanuel Patry
0cb51bb0c1 Add a new CI step to detect raw issue references
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>
2024-11-22 11:32:12 +00:00
Owen Avery
90454a91a0 Use nr2.0 in typechecker
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>
2024-11-21 14:20:42 +00:00
Owen Avery
fc59e9c3f8 Handle type path segments during late resolution 2.0
gcc/rust/ChangeLog:

	* resolve/rust-late-name-resolver-2.0.cc
	(Late::visit): Call DefaultResolver::visit when visiting
	TypePath.

gcc/testsuite/ChangeLog:

	* rust/compile/nr2/exclude: Remove entries.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2024-11-20 19:12:27 +00:00
Owen Avery
a969fd7e38 Use nr2.0 in PrivacyReporter
gcc/rust/ChangeLog:

	* checks/errors/privacy/rust-privacy-reporter.cc
	(PrivacyReporter::check_for_privacy_violation): Use name
	resolver 2.0.

gcc/testsuite/ChangeLog:

	* rust/compile/nr2/exclude: Remove entries.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2024-11-20 15:34:25 +00:00
Pierre-Emmanuel Patry
65e5335d9c Use a reference wrapper to please GCC 4.8
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>
2024-11-20 13:36:42 +00:00
Pierre-Emmanuel Patry
a163db5bc4 Use default constructor for default arguments
GCC 4.8 complains about the initializer list.

gcc/rust/ChangeLog:

	* typecheck/rust-tyty.h: Change initializer list to default constructor
	call.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2024-11-20 13:36:42 +00:00
Pierre-Emmanuel Patry
d29ab973ae Add optional template arguments to please GCC4.8
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>
2024-11-20 13:36:42 +00:00
Pierre-Emmanuel Patry
e4b68a6cd5 Fix FnParam pattern location ternary logic
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>
2024-11-20 13:36:42 +00:00
Pierre-Emmanuel Patry
690eb22f6c Refactor optional initializers
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>
2024-11-20 13:36:42 +00:00
Pierre-Emmanuel Patry
cd37d69a63 FnParam cloning now keeps projections
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>
2024-11-20 13:36:42 +00:00
Pierre-Emmanuel Patry
d424b0b467 Fix Generic type retrieval
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>
2024-11-20 13:36:42 +00:00
Pierre-Emmanuel Patry
33df697af5 Fixes some tests appearing with a moved variant
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>
2024-11-20 13:36:42 +00:00
Pierre-Emmanuel Patry
448ea276e6 Refactor hir to avoid raw pointers and unneeded fwd
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>
2024-11-20 13:36:42 +00:00
Pierre-Emmanuel Patry
6b5039f20e Refactor HIR with optionals, references & newtypes
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>
2024-11-20 13:36:42 +00:00
Pierre-Emmanuel Patry
2d6d91a776 Refactor HIR to reduce the amount of raw pointers
Attempt to use references and smart pointers whenever possible.

gcc/rust/ChangeLog:

	* backend/rust-compile-base.cc (HIRCompileBase::compile_function_body):
	Remove usage of get function to retrieve a raw pointer.
	* backend/rust-compile-base.h:
	Change API usage from raw pointer to a reference.
	* backend/rust-compile-block.cc (CompileBlock::compile): Likewise.
	(CompileBlock::visit): Likewise.
	(CompileConditionalBlocks::visit): Likewise.
	* backend/rust-compile-block.h: Likewise.
	* backend/rust-compile-expr.cc (CompileExpr::Compile): Likewise.
	(CompileExpr::visit): Likewise.
	(check_match_scrutinee): Likewise.
	(CompileExpr::array_value_expr): Likewise.
	(CompileExpr::array_copied_expr): Likewise.
	(CompileExpr::generate_closure_function): Likewise.
	(CompileExpr::generate_possible_fn_trait_call): Likewise.
	* backend/rust-compile-expr.h: Likewise.
	* backend/rust-compile-fnparam.cc (CompileFnParam::compile): Likewise.
	(CompileFnParam::visit): Likewise.
	* backend/rust-compile-fnparam.h: Likewise.
	* backend/rust-compile-implitem.cc (CompileTraitItem::visit): Likewise.
	* backend/rust-compile-intrinsic.cc (compile_fn_params): Likewise.
	* backend/rust-compile-item.cc (CompileItem::visit): Likewise.
	* backend/rust-compile-pattern.cc (CompilePatternCheckExpr::visit):
	Likewise.
	(compile_range_pattern_bound): Likewise.
	(CompilePatternBindings::visit): Likewise.
	(CompilePatternLet::visit): Likewise.
	* backend/rust-compile-pattern.h: Likewise.
	* backend/rust-compile-resolve-path.cc (ResolvePathRef::resolve):
	Likewise.
	(HIRCompileBase::query_compile): Likewise.
	* backend/rust-compile-stmt.cc (CompileStmt::visit): Likewise.
	* backend/rust-compile-struct-field-expr.cc (CompileStructExprField::Compile):
	Likewise.
	(CompileStructExprField::visit): Likewise.
	* backend/rust-compile-struct-field-expr.h: Likewise.
	* backend/rust-compile-type.cc (TyTyResolveCompile::visit): Likewise.
	* backend/rust-compile-var-decl.h: Likewise.
	* backend/rust-compile.cc: Likewise.
	* backend/rust-mangle-v0.cc (v0_inherent_or_trait_impl_path): Likewise.
	* checks/errors/borrowck/rust-bir-builder-expr-stmt.cc (ExprStmtBuilder::visit):
	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-struct.h: Likewise.
	* checks/errors/borrowck/rust-bir-builder.h: Likewise.
	* checks/errors/borrowck/rust-function-collector.h: Likewise.
	* checks/errors/privacy/rust-privacy-reporter.cc (PrivacyReporter::check_type_privacy):
	Likewise.
	(PrivacyReporter::visit): Likewise.
	* checks/errors/privacy/rust-privacy-reporter.h: Likewise.
	* checks/errors/privacy/rust-reachability.cc (ReachabilityVisitor::visit):
	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.
	* checks/lints/rust-lint-marklive.h: Likewise.
	* hir/rust-hir-dump.cc (Dump::visit): Likewise.
	* hir/tree/rust-hir-expr.h: Likewise.
	* hir/tree/rust-hir-item.h: Likewise.
	* 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.h: Likewise.
	* typecheck/rust-autoderef.cc: Likewise.
	* typecheck/rust-hir-dot-operator.cc (MethodResolver::select):
	Likewise.
	* typecheck/rust-hir-inherent-impl-overlap.h: Likewise.
	* typecheck/rust-hir-path-probe.cc (PathProbeType::process_impl_item_candidate):
	Likewise.
	(PathProbeImplTrait::process_trait_impl_items_for_candidates): Likewise.
	* typecheck/rust-hir-trait-resolve.cc (TraitResolver::resolve_trait):
	Likewise.
	(TraitItemReference::resolve_item): Likewise.
	* typecheck/rust-hir-type-check-base.cc: Likewise.
	* typecheck/rust-hir-type-check-base.h: Likewise.
	* typecheck/rust-hir-type-check-enumitem.cc (TypeCheckEnumItem::Resolve):
	Likewise.
	(TypeCheckEnumItem::visit): Likewise.
	* typecheck/rust-hir-type-check-enumitem.h: Likewise.
	* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::Resolve):
	Likewise.
	(TypeCheckExpr::visit): Likewise.
	(TypeCheckExpr::resolve_fn_trait_call): Likewise.
	* typecheck/rust-hir-type-check-expr.h: Likewise.
	* typecheck/rust-hir-type-check-implitem.cc (TypeCheckTopLevelExternItem::Resolve):
	Likewise.
	(TypeCheckTopLevelExternItem::visit): Likewise.
	(TypeCheckImplItem::visit): Likewise.
	(TypeCheckImplItemWithTrait::visit): Likewise.
	* typecheck/rust-hir-type-check-implitem.h: Likewise.
	* typecheck/rust-hir-type-check-item.cc (TypeCheckItem::visit): Likewise.
	(TypeCheckItem::resolve_impl_item): Likewise.
	(TypeCheckItem::resolve_impl_block_substitutions): Likewise.
	(TypeCheckItem::resolve_impl_block_self): Likewise.
	* typecheck/rust-hir-type-check-path.cc (TypeCheckExpr::visit): Likewise.
	(TypeCheckExpr::resolve_segments): Likewise.
	* typecheck/rust-hir-type-check-pattern.cc (TypeCheckPattern::Resolve):
	Likewise.
	(TypeCheckPattern::visit): Likewise.
	(ClosureParamInfer::Resolve): Likewise.
	(ClosureParamInfer::visit): Likewise.
	* typecheck/rust-hir-type-check-pattern.h: Likewise.
	* typecheck/rust-hir-type-check-stmt.cc (TypeCheckStmt::Resolve):
	Likewise.
	(TypeCheckStmt::visit): Likewise.
	* typecheck/rust-hir-type-check-stmt.h: Likewise.
	* typecheck/rust-hir-type-check-struct-field.h: Likewise.
	* typecheck/rust-hir-type-check-struct.cc (TypeCheckStructExpr::TypeCheckStructExpr):
	Likewise.
	(TypeCheckStructExpr::Resolve): Likewise.
	(TypeCheckStructExpr::resolve): Likewise.
	(TypeCheckStructExpr::visit): Likewise.
	* typecheck/rust-hir-type-check-type.cc (TypeCheckResolveGenericArguments::resolve):
	Likewise.
	(TypeCheckType::Resolve): Likewise.
	(TypeCheckType::visit): Likewise.
	(TypeCheckType::resolve_root_path): Likewise.
	(TypeResolveGenericParam::Resolve): Likewise.
	(TypeResolveGenericParam::visit): Likewise.
	(ResolveWhereClauseItem::visit): Likewise.
	* typecheck/rust-hir-type-check-type.h: Likewise.
	* typecheck/rust-hir-type-check.cc (TraitItemReference::get_type_from_fn):
	Likewise.
	* typecheck/rust-hir-type-check.h: Likewise.
	* typecheck/rust-type-util.cc (query_type): Likewise.
	* typecheck/rust-typecheck-context.cc (TypeCheckContextItem::TypeCheckContextItem):
	Likewise.
	* typecheck/rust-tyty-bounds.cc (TypeBoundsProbe::scan): Likewise.
	(TypeCheckBase::get_predicate_from_bound): Likewise.
	* typecheck/rust-tyty-call.cc (TypeCheckCallExpr::visit): Likewise.
	(TypeCheckMethodCallExpr::go): Likewise.
	(TypeCheckMethodCallExpr::check): Likewise.
	* typecheck/rust-tyty-subst.cc: Likewise.
	* typecheck/rust-tyty.cc (BaseType::monomorphized_clone): Likewise.
	(VariantDef::VariantDef): Remove copy constructor.
	(VariantDef::operator=): Change to move operator.
	(VariantDef::get_discriminant): Replace return type to a reference
	instead of a reference to a unique pointer.
	(VariantDef::clone): Change to references.
	(VariantDef::monomorphized_clone): Likewise.
	(FnType::as_string): Likewise.
	(FnType::clone): Likewise.
	* typecheck/rust-tyty.h: Likewise.
	* util/rust-hir-map.cc (Mappings::insert_hir_impl_block): Likewise.
	* backend/rust-compile-asm.cc: Use a reference instead of the raw
	pointer value.
	* checks/errors/borrowck/rust-bir-builder-pattern.cc: Use references.
	* checks/errors/rust-hir-pattern-analysis.cc: Likewise.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2024-11-20 13:36:42 +00:00
Owen Avery
41a12471b5 Improve handling of static items in toplevel 2.0
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>
2024-11-14 16:39:02 +00:00
Owen Avery
eda3bfdd82 Push ribs by kind rather than by value
gcc/rust/ChangeLog:

	* resolve/rust-forever-stack.h
	(ForeverStack::push): Accept argument of type Rib::Kind rather
	than Rib.
	* resolve/rust-forever-stack.hxx
	(ForeverStack::push): Likewise.
	* resolve/rust-name-resolution-context.cc
	(NameResolutionContext::scoped): Likewise.
	* resolve/rust-name-resolution-context.h
	(NameResolutionContext::scoped): Likewise.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2024-11-14 16:33:55 +00:00
Philip Herron
680ad46255 gccrs: Fix bad handling for recursive type query
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>
2024-11-12 14:53:02 +00:00
Arthur Cohen
b0d6abb923 asm: Fix clang warnings
Fixes a couple of warnings thrown by clang, with mismatched class/struct
usages and unused members.

gcc/rust/ChangeLog:

	* ast/rust-expr.h: Remove invalid usage of `struct`.
	* backend/rust-compile-asm.h: Remove unused `translated` member.
	* backend/rust-compile-asm.cc (CompileAsm::CompileAsm): Remove usage
	of `translated` member.
	* checks/errors/rust-unsafe-checker.h: Mark visitor as `override`.
	* hir/tree/rust-hir-expr.h (struct AnonConst): Remove unused `locus`
	member.
2024-11-07 16:26:04 +00:00
Arthur Cohen
5edb13bb18 typecheck: Remove unused parameter in TyTyCheckCallExpr
gcc/rust/ChangeLog:

	* typecheck/rust-tyty-call.h: Remove unused context member.
2024-11-07 16:26:04 +00:00
Arthur Cohen
a6aa012f64 hir: Mark AttrVec::get_outer_attrs as override
gcc/rust/ChangeLog:

	* hir/tree/rust-hir.h: Add override qualifier to overriden method.
2024-11-07 16:26:04 +00:00
Philip Herron
977a72ca06 gccrs: add test case to show issue is fixed
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>
2024-11-06 12:01:00 +00:00
Owen Avery
335f6c2b09 Improve handling of implicit Self parameter in AST
gcc/rust/ChangeLog:

	* ast/rust-item.h
	(Trait::self_param): Add.
	(Trait::Trait): Initialize self_param.
	(Trait::operator=): Copy self_param.
	(Trait::insert_implicit_self): Remove.
	(Trait::get_implicit_self): Add.
	* hir/rust-ast-lower-item.cc
	(ASTLoweringItem::visit): Make sure implicit self is still
	lowered to HIR.
	* resolve/rust-ast-resolve-item.cc
	(ResolveItem::visit): Adjust handling of implicit self.
	* resolve/rust-early-name-resolver.cc
	(EarlyNameResolver::visit): Add commit to Trait visitor
	mentioning that implicit self is not visited.
	* resolve/rust-toplevel-name-resolver-2.0.cc
	(TopLevel::visit): Remove call to Trait::insert_implicit_self.

gcc/testsuite/ChangeLog:

	* rust/compile/nr2/exclude: Remove entries.
	* rust/link/generic_function_0.rs: No longer expect failure.
	* rust/link/trait_import_0.rs: Likewise.
	* rust/link/trait_import_1.rs
	(trait Sized): Add.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2024-11-06 11:13:22 +00:00
Philip Herron
e82d79c4f3 gccrs: fix typechecking of Fn trait calls using ADT types
Fixes RustGcc#2953

gcc/rust/ChangeLog:

	* typecheck/rust-hir-type-check-item.cc (TypeCheckItem::visit): fix the ty_id

gcc/testsuite/ChangeLog:

	* rust/compile/nr2/exclude: nr2 cant handle these
	* rust/compile/issue-2953-1.rs: New test.
	* rust/compile/issue-2953-2.rs: New test.

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2024-11-05 18:34:21 +00:00
Philip Herron
dfbd71a9ed gccrs: fix ICE for placeholder which is not setup
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>
2024-11-05 18:34:21 +00:00
Antoni Boucher
9bcd87f488 Reorganize the CPU feature detection
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.
2024-11-05 11:00:48 +00:00
Owen Avery
5ceba7f95c Use name resolver 2.0 for module descendance checks
gcc/rust/ChangeLog:

	* checks/errors/privacy/rust-privacy-reporter.cc:
	Include rust-immutable-name-resolution-context.h.
	(is_child_module): Use ForeverStack::is_module_descendant if name
	resolution 2.0 is enabled.
	* resolve/rust-forever-stack.h
	(ForeverStack::is_module_descendant): Add.
	(ForeverStack::dfs_node): Add.
	* resolve/rust-forever-stack.hxx
	(ForeverStack::dfs_rib): Use ForeverStack::dfs_node.
	(ForeverStack::dfs_node): Add.
	(ForeverStack::is_module_descendant): Add.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2024-11-05 10:57:53 +00:00
Owen Avery
76fcedad2f Use name resolver 2.0 in VisibilityResolver
gcc/rust/ChangeLog:

	* checks/errors/privacy/rust-visibility-resolver.cc:
	Add includes.
	(VisibilityResolver::resolve_module_path): Use name resolver 2.0
	(when enabled) to lookup path resolutions.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2024-11-05 10:11:25 +00:00
Philip Herron
d76edc3891 gccrs: fix bad type inference on local patterns
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>
2024-11-04 16:17:14 +00:00
Owen Avery
efcf4d4db0 Improve handling of struct expressions in nr2.0
gcc/rust/ChangeLog:

	* resolve/rust-late-name-resolver-2.0.cc
	(Late::visit): Handle StructExprStruct and use
	ForeverStack::resolve_path instead of ForeverStack::get to
	resolve struct expression paths.
	* resolve/rust-late-name-resolver-2.0.h
	(Late::visit): Handle StructExprStruct.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2024-11-04 09:46:50 +00:00
Owen Avery
d3968ea82f Remove usage of Resolver::get_builtin_types
gcc/rust/ChangeLog:

	* backend/rust-compile-context.cc
	(Context::setup_builtins): Use TypeCheckContext::get_builtins
	instead of Resolver::get_builtin_types,
	TypeCheckContext::lookup_type_by_node_id, and
	TypeCheckContext::lookup_type.
	* typecheck/rust-hir-type-check.h
	(TypeCheckContext::get_builtins): Add.
	* typecheck/rust-typecheck-context.cc
	(TypeCheckContext::get_builtins): Add.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2024-11-01 17:47:31 +00:00
Philip Herron
4686e63c4e gccrs: fix bad type inferencing on path's
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>
2024-11-01 17:03:01 +00:00
Owen Avery
94957c0502 Make TyTy::TupleType::get_unit_type cache its return value
This removes a usage of Resolver::get_unit_type_node_id in
rust-hir-type-check-expr.cc (the HIR::TupleExpr overload of
TypeCheckExpr::visit).

gcc/rust/ChangeLog:

	* typecheck/rust-tyty.cc
	(TupleType::get_unit_type): Remove parameter, cache return
	value.
	* typecheck/rust-tyty.h
	(TupleType::get_unit_type): Remove parameter.
	* resolve/rust-late-name-resolver-2.0.cc
	(Late::setup_builtin_types): Adjust calls to get_unit_type.
	* resolve/rust-name-resolver.cc
	(Resolver::generate_builtins): Likewise.
	* typecheck/rust-hir-type-check-expr.cc
	(TypeCheckExpr::visit): Likewise.
	* typecheck/rust-hir-type-check-implitem.cc
	(TypeCheckTopLevelExternItem::visit): Likewise.
	(TypeCheckImplItem::visit): Likewise.
	* typecheck/rust-hir-type-check-item.cc
	(TypeCheckItem::visit): Likewise.
	* typecheck/rust-hir-type-check-stmt.cc
	(TypeCheckStmt::visit): Likewise.
	* typecheck/rust-hir-type-check-type.cc
	(TypeCheckType::visit): Likewise.
	* typecheck/rust-hir-type-check.cc
	(TraitItemReference::get_type_from_fn): Likewise.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2024-11-01 15:25:53 +00:00
Philip Herron
c5ae11b632 gccrs: add test case to show method resolution is working
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>
2024-11-01 15:19:22 +00:00
Owen Avery
d800490dd9 Resolve SelfParam in name resolution 2.0
gcc/rust/ChangeLog:

	* resolve/rust-late-name-resolver-2.0.cc
	(Late::visit): Handle SelfParam.
	* resolve/rust-late-name-resolver-2.0.h
	(Late::visit): Likewise.

gcc/testsuite/ChangeLog:

	* rust/compile/nr2/exclude: Remove entries.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2024-10-29 10:20:27 +00:00
Owen Avery
5ad1d886a9 Use name resolution 2.0 in TraitResolver
gcc/rust/ChangeLog:

	* typecheck/rust-hir-trait-resolve.cc: Add includes.
	(TraitResolver::resolve_path_to_trait):
	Use name resolution 2.0 resolver when enabled.

gcc/testsuite/ChangeLog:

	* rust/compile/nr2/exclude: Remove entries.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2024-10-29 10:18:26 +00:00
Marc Poulhiès
5fe9110bbf rust: Desugar IfLet* into MatchExpr
Replace the "regular" AST->HIR lowering for IfLet* with a desugaring
into a MatchExpr.

Desugar a simple if let:

   if let Some(y) = some_value {
     bar();
   }

into:

   match some_value {
     Some(y) => {bar();},
     _ => ()
   }

Same applies for IfLetExprConseqElse (if let with an else block).

Desugar:

   if let Some(y) = some_value {
     bar();
   } else {
     baz();
   }

into:

   match some_value {
     Some(y) => {bar();},
     _ => {baz();}
   }

Fixes https://github.com/Rust-GCC/gccrs/issues/1177

gcc/rust/ChangeLog:

	* backend/rust-compile-block.h: Adjust after removal of
	HIR::IfLetExpr and HIR::IfLetExprConseqElse.
	* backend/rust-compile-expr.h: Likewise.
	* checks/errors/borrowck/rust-bir-builder-expr-stmt.cc
	(ExprStmtBuilder::visit): Likewise.
	* checks/errors/borrowck/rust-bir-builder-expr-stmt.h: Likewise.
	* checks/errors/borrowck/rust-bir-builder-lazyboolexpr.h:
	Likewise.
	* 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: 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-block.h (ASTLoweringIfLetBlock::translate):
	Change return type.
	* hir/rust-ast-lower.cc (ASTLoweringIfLetBlock::desugar_iflet):
	New.
	(ASTLoweringIfLetBlock::visit(AST::IfLetExpr &)): Adjust and use
	desugar_iflet.
	* hir/rust-ast-lower.h: Add comment.
	* hir/rust-hir-dump.cc (Dump::do_ifletexpr): Remove.
	(Dump::visit(IfLetExpr&)): Remove.
	(Dump::visit(IfLetExprConseqElse&)): Remove.
	* hir/rust-hir-dump.h (Dump::do_ifletexpr): Remove.
	(Dump::visit(IfLetExpr&)): Remove.
	(Dump::visit(IfLetExprConseqElse&)): Remove.
	* hir/tree/rust-hir-expr.h (class IfLetExpr): Remove.
	(class IfLetExprConseqElse): Remove.
	* hir/tree/rust-hir-full-decls.h (class IfLetExpr): Remove.
	(class IfLetExprConseqElse): Remove.
	* hir/tree/rust-hir-visitor.h: Adjust after removal of
	HIR::IfLetExpr and HIR::IfLetExprConseqElse.
	* hir/tree/rust-hir.cc (IfLetExpr::as_string): Remove.
	(IfLetExprConseqElse::as_string): Remove.
	(IfLetExpr::accept_vis): Remove.
	(IfLetExprConseqElse::accept_vis): Remove.
	* hir/tree/rust-hir.h: Adjust after removal of HIR::IfLetExpr and
	HIR::IfLetExprConseqElse.
	* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit):
	Likewise.
	* typecheck/rust-hir-type-check-expr.h: Likewise.
	* checks/errors/rust-hir-pattern-analysis.cc
	(PatternChecker::visit (IfLetExpr &)): Remove.
	(PatternChecker::visit (IfLetExprConseqElse &)): Remove.
	* checks/errors/rust-hir-pattern-analysis.h (visit(IfLetExpr &)): Remove.
	(visit(IfLetExprConseqElse &)): Remove.

gcc/testsuite/ChangeLog:

	* rust/compile/if_let_expr.rs: Adjust.
	* rust/compile/if_let_expr_simple.rs: New test.
	* rust/compile/iflet.rs: New test.
	* rust/execute/torture/iflet.rs: New test.
	* rust/compile/nr2/exclude: Add iflet.rs and if_let_expr_simple.rs

Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
2024-10-28 20:08:01 +00:00
Owen Avery
4564a4f159 Fix name resolution 2.0 definition lookups in unsafe checker
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>
2024-10-28 10:28:22 +00:00
Owen Avery
c220250e93 Improve path handling while testing name resolution 2.0
gcc/testsuite/ChangeLog:

	* rust/compile/nr2/compile.exp: Handle paths using "file join"
	and "file split".
	* rust/compile/nr2/exclude: Remove debug-diagnostics-on.rs.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2024-10-28 08:29:27 +00:00
Owen Avery
98f04ecc1c Use name resolver 2.0 in CompileTraitItem
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>
2024-10-28 08:22:22 +00:00
Owen Avery
f9f690f500 Use name resolution 2.0 in TraitItemReference
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>
2024-10-28 08:21:55 +00:00
Owen Avery
549fe6d3a0 Rename some PathIdentSegment functions
This makes PathIdentSegment more similar to other classes used to
represent path segments.

gcc/rust/ChangeLog:

	* ast/rust-path.h
	(PathIdentSegment::is_super_segment): Rename to...
	(PathIdentSegment::is_super_path_seg): ...here.
	(PathIdentSegment::is_crate_segment): Rename to...
	(PathIdentSegment::is_crate_path_seg): ...here.
	(PathIdentSegment::is_lower_self): Rename to...
	(PathIdentSegment::is_lower_self_seg): ...here.
	(PathIdentSegment::is_big_self): Rename to...
	(PathIdentSegment::is_big_self_seg): ...here.

	(PathExprSegment::is_super_path_seg): Handle renames.
	(PathExprSegment::is_crate_path_seg): Likewise.
	(PathExprSegment::is_lower_self_seg): Likewise.
	(TypePathSegment::is_crate_path_seg): Likewise.
	(TypePathSegment::is_super_path_seg): Likewise.
	(TypePathSegment::is_big_self_seg): Likewise.
	(TypePathSegment::is_lower_self_seg): Likewise.
	* ast/rust-ast-collector.cc
	(TokenCollector::visit): Likewise.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2024-10-28 08:17:01 +00:00
Owen Avery
7a23231a7b Add a newline to the end of nr2/exclude
gcc/testsuite/ChangeLog:

	* rust/compile/nr2/exclude: Add trailing newline along with
	comment.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2024-10-27 22:27:32 +00:00
Owen Avery
e52fa08837 Fix variable shadowing in late resolution 2.0
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>
2024-10-27 20:10:32 +00:00
Owen Avery
daa5fd3713 Insert trait names during toplevel resolution 2.0
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>
2024-10-27 12:23:22 +00:00
Philip Herron
8f23349aaf gccrs: Fix bad recursive operator overload call
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>
2024-10-25 10:59:25 +00:00
Owen Avery
d222c9356e Handle external static items in toplevel resolver 2.0
gcc/rust/ChangeLog:

	* resolve/rust-toplevel-name-resolver-2.0.cc
	(TopLevel::visit): Handle ExternalStaticItem.
	* resolve/rust-toplevel-name-resolver-2.0.h
	(TopLevel::visit): Likewise.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2024-10-24 10:50:12 +00:00
Owen Avery
e7de54ddae Use name resolver 2.0 in pattern checker
gcc/rust/ChangeLog:

	* checks/errors/rust-hir-pattern-analysis.cc: Add includes.
	(PatternChecker::visit): Use name resolver 2.0 when enabled.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2024-10-24 08:07:22 +00:00
Owen Avery
b7eb4b0af5 Use name resolver 2.0 for compiling break/continue
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>
2024-10-24 08:06:50 +00:00
Owen Avery
120b23495f Use name resolver 2.0 in const checker
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>
2024-10-24 08:06:00 +00:00
Owen Avery
bcc83c32a7 Load unloaded modules during toplevel resolution 2.0
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>
2024-10-24 07:35:23 +00:00
Owen Avery
d833d233c2 Make const references to ForeverStack more useful
gcc/rust/ChangeLog:

	* resolve/rust-forever-stack.h
	(ForeverStack::to_canonical_path): Make const.
	(ForeverStack::to_rib): Add const overload.
	(ForeverStack::reverse_iter): Add const overloads.
	(ForeverStack::ConstDfsResult): Add.
	(ForeverStack::dfs): Add const overload.
	(ForeverStack::dfs_rib): Likewise.
	* resolve/rust-forever-stack.hxx
	(ForeverStack::reverse_iter): Add const overloads.
	(ForeverStack::dfs): Add const overload.
	(ForeverStack::to_canonical_path): Make const.
	(ForeverStack::dfs_rib): Likewise.
	(ForeverStack::to_rib): Add const overload.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2024-10-24 06:57:31 +00:00
Owen Avery
20ef282192 Use name resolver 2.0 in MarkLive
gcc/rust/ChangeLog:

	* checks/lints/rust-lint-marklive.cc
	(MarkLive::visit_path_segment): Use name resolver 2.0 when
	enabled.
	(MarkLive::visit): Likewise.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2024-10-17 13:43:32 +00:00
Owen Avery
2b74b5cb75 Handle const generic parameters during resolution 2.0
gcc/rust/ChangeLog:

	* resolve/rust-toplevel-name-resolver-2.0.cc
	(TopLevel::visit): Handle ConstGenericParam.
	* resolve/rust-toplevel-name-resolver-2.0.h
	(TopLevel::visit): Likewise.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2024-10-17 11:42:03 +00:00
Owen Avery
a9931e9c4f Disambiguate generic args during name resolution 2.0
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>
2024-10-17 11:37:14 +00:00
badumbatish
6708d35b95 Fix compiler error on ast wrong implicit construct push_back
gcc/rust/ChangeLog:

	* expand/rust-macro-builtins-asm.cc (parse_reg_operand_in): Fix
	compiler error on ast wrong implicit construct push_back
2024-10-17 08:38:08 +00:00
badumbatish
2d95e156b4 Provide input operand for gccrs
gcc/rust/ChangeLog:

	* backend/rust-compile-asm.cc (CompileAsm::asm_construct_inputs):
	Provide input operand for gccrs
	* expand/rust-macro-builtins-asm.cc (parse_reg_operand_in):
	Move expr to In
	(expand_inline_asm_strings):
	Add comments to debug strings

gcc/testsuite/ChangeLog:

	* rust/compile/inline_asm_parse_operand.rs:
	Remove inout, functionality not supported. Remove redundant {}
	* rust/execute/torture/inline_asm_mov_x_5_ARM.rs: Add operand in
	* rust/execute/torture/inline_asm_mov_x_5_x86_64.rs: Likewise
2024-10-17 08:38:08 +00:00
Owen Avery
0b18baee05 Use name resolver 2.0 during pattern typechecking
gcc/rust/ChangeLog:

	* typecheck/rust-hir-type-check-pattern.cc: Add includes.
	(TypeCheckPattern::visit): Use name resolver 2.0 if enabled.

	* resolve/rust-name-resolution-context.cc
	(NameResolutionContext::lookup): Make const qualified.
	* resolve/rust-name-resolution-context.h
	(NameResolutionContext::lookup): Likewise.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2024-10-16 09:29:59 +00:00
Owen Avery
eb863f60b6 Allow identifiers and paths to reference types during nr2.0
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>
2024-10-16 08:45:35 +00:00
Owen Avery
ab15db3908 Improve handling of InlineAsm in DefaultASTVisitor
gcc/rust/ChangeLog:

	* ast/rust-ast-visitor.cc
	(DefaultASTVisitor::visit): Visit fields of InlineAsm.

gcc/testsuite/ChangeLog:

	* rust/compile/nr2/exclude: Remove
	inline_asm_parse_output_operand.rs.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2024-10-15 08:23:04 +00:00
Owen Avery
71d2084edc Insert static items into the value namespace
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>
2024-10-14 08:15:40 +00:00
Owen Avery
583eb22ce1 Rework InlineAsmOperand
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>
2024-10-13 23:50:45 +00:00
Owen Avery
3bff5cf047 Handle TypeAlias during toplevel resolution 2.0
gcc/rust/ChangeLog:

	* resolve/rust-toplevel-name-resolver-2.0.cc
	(TopLevel::visit): Handle TypeAlias.
	* resolve/rust-toplevel-name-resolver-2.0.h
	(TopLevel::visit): Likewise.

gcc/testsuite/ChangeLog:

	* rust/compile/nr2/exclude: Remove type-alias1.rs.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2024-10-10 17:37:51 +00:00
Owen Avery
1a030d34cd Check for writes outside of the build directory
ChangeLog:

	* .github/workflows/ccpp.yml: Make files outside the build
	directory read-only.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2024-10-10 10:11:54 +00:00
Owen Avery
bad1ebacd1 Fix some issues with canonical path fetching in name resolution 2.0
gcc/rust/ChangeLog:

	* typecheck/rust-hir-type-check-enumitem.cc: Add includes.
	(TypeCheckEnumItem::visit): Fetch canonical paths properly when
	name resolution 2.0 is enabled.
	* typecheck/rust-hir-type-check-implitem.cc: Add includes.
	(TypeCheckImplItem::visit): Fetch canonical paths properly when
	name resolution 2.0 is enabled.
	* typecheck/rust-hir-type-check-item.cc: Add include.
	(TypeCheckItem::visit): Fetch canonical paths properly 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>
2024-10-10 09:59:08 +00:00
Owen Avery
14994668b5 Improve Rib::Definition shadowing
gcc/rust/ChangeLog:

	* resolve/rust-finalize-imports-2.0.cc
	(GlobbingVisitor::visit): Replace calls to insert_shadowable with
	insert_globbed.
	* resolve/rust-forever-stack.h
	(ForeverStack::insert_globbed): Add.
	* resolve/rust-forever-stack.hxx
	(ForeverStack::insert_globbed): Add.
	(ForeverStack::dfs): Handle modifications to Rib::Definition
	fields.
	* resolve/rust-late-name-resolver-2.0.cc
	(Late::visit): Make IdentifierPattern-based declarations
	shadowable.
	* resolve/rust-name-resolution-context.cc
	(NameResolutionContext::insert_globbed): Add.
	* resolve/rust-name-resolution-context.h
	(NameResolutionContext::insert_globbed): Add.
	* resolve/rust-rib.cc
	(Rib::Definition::Definition): Use Rib::Definition::Mode to
	indicate shadowing mode instead of boolean, handle modifications
	to Rib::Definition fields.
	(Rib::Definition::is_ambiguous): Handle modifications to
	Rib::Definition fields.
	(Rib::Definition::to_string): Likewise.
	(Rib::Definition::Shadowable): Handle changed constructor
	signature.
	(Rib::Definition::NonShadowable): Likewise.
	(Rib::Definition::Globbed): Add.
	(Rib::insert): Handle changes to Rib::Definition fields.
	* resolve/rust-rib.h
	(Rib::Definition::Globbed): Add.
	(Rib::Definition::ids): Remove.
	(Rib::Definition::ids_shadowable): Add.
	(Rib::Definition::ids_non_shadowable): Add.
	(Rib::Definition::ids_globbed): Add.
	(Rib::Definition::get_node_id): Handle modifications to
	Rib::Definition fields.
	(Rib::Definition::Mode): Add.
	(Rib::Definition::Definition): Use Rib::Definition::Mode to
	indicate shadowing mode instead of boolean.

gcc/testsuite/ChangeLog:

	* rust/compile/nr2/exclude: Remove shadow1.rs.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2024-10-09 09:05:29 +00:00
Philip Herron
af0f0e3f53 gccrs: Fix ICE when typechecking non-trait item when we expect one
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>
2024-10-02 16:42:01 +00:00
Philip Herron
ad1c8b1d45 gccrs: Add test case to show ICE is fixed
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>
2024-10-02 14:13:29 +00:00
Pierre-Emmanuel Patry
409beeb8b6 Change alpine allowed warning list
ChangeLog:

	* .github/alpine_32bit_log_warnings: Update alpine warning list.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2024-09-27 13:43:28 +00:00
Philip Herron
b60ec4fe0b gccrs: add test case to show impl block on ! works
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>
2024-09-27 13:23:20 +00:00
Philip Herron
18422c9c38 rust: fix ICE during name resolution for impls on unit-types
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>
2024-09-27 11:55:56 +00:00
Philip Herron
c6a479fb93 rust: Add support for Clone and Copy derive on generic types
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
2024-09-27 10:01:40 +00:00
Pierre-Emmanuel Patry
423122c2f0 Remove some passing test from nr2 passing list
gcc/testsuite/ChangeLog:

	* rust/compile/nr2/exclude: Remove cast_generics.rs, issue-1131.rs,
	issue-1383.rs and unsafe10.rs

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2024-09-26 22:48:32 +00:00
Pierre-Emmanuel Patry
b408e04a5e Postpone break on error after name resolution
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>
2024-09-26 22:48:32 +00:00
Pierre-Emmanuel Patry
0f614e06cc Resolve TypeParam with name resolution 2.0
Resolve TypeParam unless it is Self.

gcc/rust/ChangeLog:

	* resolve/rust-toplevel-name-resolver-2.0.cc (TopLevel::visit): Resolve
	TypeParam.
	* resolve/rust-toplevel-name-resolver-2.0.h: Add visit function
	prototype.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2024-09-26 22:48:32 +00:00
Pierre-Emmanuel Patry
90a8ae7cca Add box definition to avoid error
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>
2024-09-26 22:48:32 +00:00
Pierre-Emmanuel Patry
e4394ac6ff This test requires the standard library
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>
2024-09-26 22:48:32 +00:00
Pierre-Emmanuel Patry
d87b067b2d Make node id getter const.
gcc/rust/ChangeLog:

	* ast/rust-ast.h: Node id getter could be const.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2024-09-26 22:48:32 +00:00
Pierre-Emmanuel Patry
5257adfe81 Change resolved type segment
gcc/rust/ChangeLog:

	* resolve/rust-late-name-resolver-2.0.h: Add visit function prototype.
	* resolve/rust-late-name-resolver-2.0.cc (Late::visit): Change resolved
	type segment.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2024-09-26 22:48:32 +00:00
Pierre-Emmanuel Patry
feba3ba1b5 Update exclude list with working tests
gcc/testsuite/ChangeLog:

	* rust/compile/nr2/exclude: Remove working tests from nr2 exclude list.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2024-09-26 22:48:32 +00:00
Pierre-Emmanuel Patry
c8fbbd472c Do not assert insertion result
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>
2024-09-26 22:48:32 +00:00
Pierre-Emmanuel Patry
a4f64b9c64 Move bir builder function implementation
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>
2024-09-26 22:48:32 +00:00
Pierre-Emmanuel Patry
49f0300a40 Move failing test to xfail
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>
2024-09-26 22:48:32 +00:00
Pierre-Emmanuel Patry
deb94244cb Make AST default visitor visit functions public
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>
2024-09-26 22:48:32 +00:00
Pierre-Emmanuel Patry
fef6b34334 Add default resolver parent functions by default
gcc/rust/ChangeLog:

	* resolve/rust-finalize-imports-2.0.h: Add parent member functions
	from default resolver.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2024-09-26 22:48:32 +00:00
Pierre-Emmanuel Patry
384de9b928 Change lambda content with default visitor call
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>
2024-09-26 22:48:32 +00:00
Pierre-Emmanuel Patry
468d24b5d9 Remove regular visit code
Regular visit code can be replaced with default visit functions.

gcc/rust/ChangeLog:

	* resolve/rust-default-resolver.cc (DefaultResolver::visit): Remove
	default visit code and replace it with call to default visitor.
	* resolve/rust-default-resolver.h: Remove removed function's
	prototypes.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2024-09-26 22:48:32 +00:00
Pierre-Emmanuel Patry
a01ac121a3 Remove empty visit functions
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>
2024-09-26 22:48:32 +00:00
Pierre-Emmanuel Patry
9a8545f6e1 Mark virtual function override in default resolver
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>
2024-09-26 22:48:32 +00:00
Pierre-Emmanuel Patry
ab8a0b5cc0 Loop on expansion if a new export has been defined
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>
2024-09-26 22:48:32 +00:00
Pierre-Emmanuel Patry
76131dd1d5 Fix missing error on duplicated nodes
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>
2024-09-26 22:48:32 +00:00
Arthur Cohen
f899498e03 nr2.0: Cleanup import mappings and factor into a class.
gcc/rust/ChangeLog:

	* resolve/rust-early-name-resolver-2.0.h: New class for imports.
	* resolve/rust-finalize-imports-2.0.cc (finalize_simple_import): Use
	the new API.
	(finalize_glob_import): Likewise.
	(finalize_rebind_import): Likewise.
	(FinalizeImports::FinalizeImports): Likewise.
	(FinalizeImports::visit): Likewise.
	* resolve/rust-finalize-imports-2.0.h: Likewise.
	* resolve/rust-early-name-resolver-2.0.cc (Early::resolve_glob_import): Likewise.
	(Early::resolve_simple_import): Likewise.
	(Early::resolve_rebind_import): Likewise.
2024-09-26 22:48:32 +00:00
Arthur Cohen
9f6c179099 Insert imports in all namespaces they were resolved in
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.
2024-09-26 22:48:32 +00:00
Arthur Cohen
c67b14ccc5 early: Do not emit errors for unresolved imports, store them instead
gcc/rust/ChangeLog:

	* resolve/rust-early-name-resolver-2.0.cc (Early::visit_attributes):
	Store errors for later.
2024-09-26 22:48:32 +00:00
Arthur Cohen
bd669c43f2 imports: Make FinalizeImports a resolver visitor as well
gcc/rust/ChangeLog:

	* resolve/rust-finalize-imports-2.0.cc (FinalizeImports::go): Turn
	static method into method.
	(FinalizeImports::visit): New.
	* resolve/rust-finalize-imports-2.0.h (class FinalizeImports): Make
	FinalizeImports a visitor.
	* resolve/rust-early-name-resolver-2.0.cc (Early::go): Use new FinalizeImports API.
	(Early::resolve_glob_import): Use new API.
	(Early::resolve_simple_import): Likewise.
	(Early::resolve_rebind_import): Likewise.
	(Early::build_import_mapping): Likewise.
	* resolve/rust-early-name-resolver-2.0.h: Likewise.
	* resolve/rust-toplevel-name-resolver-2.0.cc (TopLevel::visit): Likewise.
	* resolve/rust-toplevel-name-resolver-2.0.h: Likewise.
2024-09-26 22:48:32 +00:00
Arthur Cohen
6a47e726ea imports: Start storing Ribs in ImportKind
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.
2024-09-26 22:48:32 +00:00
Arthur Cohen
d86cee5955 imports: Create ImportData class and use it in import_mappings
gcc/rust/ChangeLog:

	* resolve/rust-early-name-resolver-2.0.cc (Early::resolve_glob_import):
	Use ImportData class.
	(Early::resolve_simple_import): Likewise.
	(Early::resolve_rebind_import): Likewise.
	(Early::build_import_mapping): Likewise.
	* resolve/rust-early-name-resolver-2.0.h: Likewise.
	* resolve/rust-finalize-imports-2.0.cc (finalize_simple_import): Likewise.
	(finalize_glob_import): Likewise.
	(finalize_rebind_import): Likewise.
	(FinalizeImports::go): Likewise.
	* resolve/rust-finalize-imports-2.0.h: Likewise.
	* resolve/rust-name-resolution-context.h: Likewise.
	* resolve/rust-rib.h: Define ImportData class.
2024-09-26 22:48:32 +00:00
Arthur Cohen
a4b593400d imports: Add FinalizeImports class
gcc/rust/ChangeLog:

	* Make-lang.in: Add new object file.
	* ast/rust-item.h: Constify method.
	* resolve/rust-early-name-resolver-2.0.cc (Early::go): Call into
	the imports finalizer.
	(Early::resolve_glob_import): Remove old resolution.
	(Early::resolve_rebind_import): Likewise.
	* resolve/rust-toplevel-name-resolver-2.0.cc (GlobbingVisitor::go):
	New function.
	(GlobbingVisitor::visit): Likewise.
	(TopLevel::visit): Do not call into handle_use_* functions anymore.
	* resolve/rust-toplevel-name-resolver-2.0.h (class GlobbingVisitor):
	New.
	* resolve/rust-finalize-imports-2.0.cc: New file.
	* resolve/rust-finalize-imports-2.0.h: New file.
2024-09-26 22:48:32 +00:00
Arthur Cohen
8f835f8cec early: Resolve imports and create import mappings
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.
2024-09-26 22:48:32 +00:00
Arthur Cohen
0377c9ae21 toplevel: Build list of imports for Early to resolve
gcc/rust/ChangeLog:

	* resolve/rust-toplevel-name-resolver-2.0.cc: Comment out handle_use
	call and error emission.
	* resolve/rust-toplevel-name-resolver-2.0.h: Create ImportKind class.
2024-09-26 22:48:32 +00:00
Arthur Cohen
dcc146b341 toplevel: Add note for resolving use declarations
gcc/rust/ChangeLog:

	* resolve/rust-toplevel-name-resolver-2.0.cc (TopLevel::handle_use_dec):
	Add notes on the problem.
	* resolve/rust-toplevel-name-resolver-2.0.h: Likewise.
2024-09-26 22:48:32 +00:00
Arthur Cohen
5e8da717fe nr2.0: default-visitor: Conditionally visit type in self parameters.
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.
2024-09-26 22:48:32 +00:00
Philip Herron
438470e8e3 rust fix ICE when hir lowering qualified path expressions without an as
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>
2024-09-26 20:22:13 +00:00
Philip Herron
09cfe530f9 rust: fix ICE when compiling impl block for !
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>
2024-09-26 11:01:20 +00:00
Owen Avery
71affd2021 Remove some overloaded methods from DefaultResolver.
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>
2024-09-26 10:51:41 +00:00
Owen Avery
1a9f70b2ab Add extra assertions to tl::optional
gcc/rust/ChangeLog:

	* util/optional.h
	(optional): Add assertions to dereference operator overloads
	when C++14 is available.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2024-09-24 08:06:05 +00:00
Arthur Cohen
b282387d5a mingw: Fix build with patch from Liu Hao
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.
2024-09-23 10:56:14 +00:00
Marc Poulhiès
263b1c8541 gccrs: adjust hir dump of BlockExpr
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>
2024-09-23 09:27:53 +00:00
Philip Herron
39eb3a4412 rust: negative polarity removes restrictions on validation of impl blocks
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>
2024-09-20 18:32:10 +00:00
benjamin.thos
5d703a35ca Fix ICE on error propagation with generic
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>
2024-09-20 16:23:42 +00:00
Owen Avery
d65c6c9edb Adjust expected warnings for alpine 32 bit
ChangeLog:

	* .github/alpine_32bit_log_warnings: Adjust.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2024-09-20 16:17:01 +00:00
Pierre-Emmanuel Patry
522576d07f Check if the type has been correctly resolved
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>
2024-09-19 13:16:16 +00:00
Pierre-Emmanuel Patry
67bc0f69b4 Change upload artifact github action version
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>
2024-09-18 12:21:23 +00:00
Marc Poulhiès
ebbc172442 github: adjust footer detection for Tested-by
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>
2024-09-18 09:03:49 +00:00
Owen Avery
483ee3ae4b Create new test system for name resolution 2.0
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>
2024-09-17 09:55:38 +00:00
JoanVC
b0c8579ee6 [#3141] Remove double negation by returning CompileExpr::Compile early
Fixes #3141.

gcc/rust/ChangeLog:

	* backend/rust-compile-expr.cc

Signed-off-by: Joan Vilardaga <github-91yu@joanvc.cat>
2024-09-16 16:07:50 +00:00
JoanVC
ba7b5a4230 [#3141] Fix incorrect handling of overflow in numeric types
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>
2024-09-16 16:07:50 +00:00
Arthur Cohen
f8e46bb8a8 session-manager: Fix typos in -frust-incomplete message
gcc/rust/ChangeLog:

	* rust-session-manager.cc (Session::compile_crate): Use less repetition,
	fix a typo in `reports`, fix word order.
2024-09-12 15:24:29 +00:00
benjamin.thos
f2e03227e0 Emit error on auto-traits
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>
2024-09-11 23:03:02 +00:00
Raiki Tamura
9941d6f3dd gccrs: Implement initial pattern analysis pass.
gcc/rust/ChangeLog:

	* Make-lang.in: Add rust-hir-pattern-analysis.o.
	* rust-session-manager.cc (Session::compile_crate):
		Add pattern analysis pass.
	* typecheck/rust-hir-type-check-pattern.cc (TypeCheckPattern::visit):
		Do typecheck for subpatterns.
	* checks/errors/rust-hir-pattern-analysis.cc: New file.
	* checks/errors/rust-hir-pattern-analysis.h: New file.

gcc/testsuite/ChangeLog:

	* rust/compile/exhaustiveness1.rs: New test.
	* rust/compile/exhaustiveness2.rs: New test.
	* rust/compile/exhaustiveness3.rs: New test.

Signed-off-by: Raiki Tamura <tamaron1203@gmail.com>
2024-09-11 14:59:57 +00:00
Owen Avery
7e0feecb56 Compile using ASAN on the github CI
ChangeLog:

	* .github/workflows/ccpp.yml: Add job for running tests with
	ASAN.
	* .github/no-bootstrap-asan.mk: New file.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2024-09-10 16:33:34 +00:00
Liam Naddell
c5f9d6ddf9 Dynamic dispatch with supertraits
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>
2024-09-10 10:58:22 +00:00
Kushal Pal
65b00cc654 Used IndexVec for place_map
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>
2024-09-09 08:33:02 +00:00
Kushal Pal
4a6cccfbf1 Use IndexVec for bb_fold_map
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>
2024-09-09 08:33:02 +00:00
Kushal Pal
170223717e Used IndexVec for Places
gcc/rust/ChangeLog:

	* checks/errors/borrowck/rust-bir-place.h: Use strong types as
	index.

Signed-off-by: Kushal Pal <kushalpal109@gmail.com>
2024-09-09 08:33:02 +00:00
Kushal Pal
1fcfec23a4 Used IndexVec for BasicBlocks
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>
2024-09-09 08:33:02 +00:00
Kushal Pal
5f42a91bd2 Used IndexVec for Loans
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>
2024-09-09 08:33:02 +00:00
Kushal Pal
a912ffbf32 Used IndexVec for Scopes
gcc/rust/ChangeLog:

	* checks/errors/borrowck/rust-bir-place.h:
	Used `IndexVec` with ScopeId as index.

Signed-off-by: Kushal Pal <kushalpal109@gmail.com>
2024-09-09 08:33:02 +00:00
Kushal Pal
fe780d77db Introduce IndexVec
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>
2024-09-09 08:33:02 +00:00
Kushal Pal
4050bf70e2 Strong type BasicBlockId
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>
2024-09-09 08:33:02 +00:00
Kushal Pal
ffeb37619e Strong type ScopeId
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>
2024-09-09 08:33:02 +00:00
Kushal Pal
b3dd18c0ef Strong type LoanId
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>
2024-09-09 08:33:02 +00:00
Kushal Pal
5b8299d769 Use FreeRegions inplace of std::vector<FreeRegion>
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>
2024-09-09 08:33:02 +00:00
Kushal Pal
d479eb583e Strong type FreeRegion
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>
2024-09-09 08:33:02 +00:00
Kushal Pal
5819537947 Strong type PlaceId
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>
2024-09-09 08:33:02 +00:00
Owen Avery
14528a8cf0 Avoid accidental insertion into map
gcc/rust/ChangeLog:

	* resolve/rust-ast-resolve-pattern.cc
	(PatternDeclaration::check_bindings_consistency): Check if
	outer_bindings_map contains an entry before indexing.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2024-09-07 20:49:52 +00:00
Owen Avery
84f772c15b Add virtual destructor to AbstractExpr
gcc/rust/ChangeLog:

	* checks/errors/borrowck/rust-bir.h
	(class AbstractExpr): Add virtual destructor.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2024-09-06 11:00:45 +00:00
Owen Avery
12af831615 Fix v0-mangle1.rs test when run with ASAN
gcc/rust/ChangeLog:

	* util/rust-canonical-path.h
	(CanonicalPath::CanonicalPath): Properly initialize crate_num
	with copy constructor.

gcc/testsuite/ChangeLog:

	* rust/compile/v0-mangle1.rs: Make v0-mangle test more crate_num
	agnostic.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2024-09-06 10:59:08 +00:00
Pierre-Emmanuel Patry
8ab5dd8e65 Bump action version to avoid missing distutils
ChangeLog:

	* .github/workflows/clang-format.yml: Bump action version to 18.2

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2024-09-05 14:42:34 +00:00
badumbatish
e4953b4d1d Provide new asm test case for amd64
gcc/testsuite/ChangeLog:

	* rust/execute/torture/inline_asm_mov_x_5.rs: Move to...
	* rust/execute/torture/inline_asm_mov_x_5_ARM.rs: ...here.
	* rust/execute/torture/inline_asm_mov_x_5_x86_64.rs: New test.
2024-09-02 09:44:55 +00:00
badumbatish
3aca66b673 Rehaul, Apply code review from Arthur
gcc/rust/ChangeLog:

	* backend/rust-compile-asm.cc (CompileAsm::visit):
	Change API, public/private, comments, formatting from code
	review
	(CompileAsm::asm_build_expr): Likewise.
	(CompileAsm::tree_codegen_asm): Likewise.
	* backend/rust-compile-asm.h (class CompileAsm): Likewise.
	* backend/rust-compile-expr.cc (CompileExpr::visit): Likewise.
	* checks/errors/privacy/rust-privacy-reporter.cc (PrivacyReporter::visit): Likewise.
	* expand/rust-macro-builtins-asm.cc (strip_double_quotes): Likewise.
	(parse_options): Likewise.
	(parse_asm_arg): Likewise.
	(expand_inline_asm_strings): Likewise.
	(parse_asm): Likewise.
	* expand/rust-macro-builtins-asm.h (strip_double_quotes): Likewise.
	(expand_inline_asm_strings): Likewise.
	(expand_inline_asm_string): Likewise.
	* hir/tree/rust-hir-expr.h: Likewise.

gcc/testsuite/ChangeLog:

	* rust/compile/inline_asm_typecheck.rs: Change comments
2024-09-02 09:44:55 +00:00
badumbatish
73a1510814 Fix return type of asm mov 5 to i32:0, tortured
gcc/testsuite/ChangeLog:

	* rust/execute/inline_asm_mov_x_5.rs: Move to...
	* rust/execute/torture/inline_asm_mov_x_5.rs: ...here.
2024-09-02 09:44:55 +00:00
badumbatish
c324dcf459 Make inline mov compiles
gcc/rust/ChangeLog:

	* backend/rust-compile-asm.cc (CompileAsm::asm_build_expr):
	Remove debug
	* expand/rust-macro-builtins-asm.cc (expand_inline_asm_strings):
	properly formatted via rust instead of c
	(parse_asm): formatted comment
	(parse_format_strings): formatted comment
	* hir/tree/rust-hir-expr.h: fix is_simple_asm()

gcc/testsuite/ChangeLog:

	* rust/compile/inline_asm_parse_operand.rs: Fix format asm
	* rust/compile/inline_asm_parse_output_operand.rs:
	Fix format asm
	* rust/execute/torture/inline_asm_mov_x_5.rs: Move to...
	* rust/execute/inline_asm_mov_x_5.rs: ...here.
2024-09-02 09:44:55 +00:00
badumbatish
9597d3c088 Use's array type when constring string tree
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
2024-09-02 09:44:55 +00:00
badumbatish
bc341ac3bd Added noreturn checking for nevertype, new test
gcc/rust/ChangeLog:

	* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit):
	Added noreturn checking for nevertype

gcc/testsuite/ChangeLog:

	* rust/compile/inline_asm_typecheck.rs: New test.
2024-09-02 09:44:55 +00:00
badumbatish
20db1716d9 Perform lowering hir output operand to 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
2024-09-02 09:44:55 +00:00
badumbatish
43d38bbb18 Perform type check on InlineAsm's operand
gcc/rust/ChangeLog:

	* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit):
	Perform type check on InlineAsm's operand
	(typecheck_inline_asm_operand): Likewise
2024-09-02 09:44:55 +00:00
badumbatish
c00fd2aeaa Lower the HIR to tree with CompileExpr
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
2024-09-02 09:44:55 +00:00
badumbatish
596bf6946d Move strip double quotes, add scaffold expand
gcc/rust/ChangeLog:

	* backend/rust-compile-asm.cc (strip_double_quotes):
	Move strip double quotes to parse phase
	(CompileAsm::asm_construct_string_tree): Likewise
	* backend/rust-compile-asm.h (strip_double_quotes): Likewise
	* expand/rust-macro-builtins-asm.cc (strip_double_quotes):
	Likewise
	(expand_inline_asm): Renamed to expand_inline_asm_strings
	(expand_inline_asm_strings): Renamed from expand_inline_asm
	(parse_asm): Move strip double quotes to parse phase
	(parse_format_strings): Likewise
	* expand/rust-macro-builtins-asm.h (strip_double_quotes):
	Likewise
	(expand_inline_asm_strings): Inline asm expansion fn
	(expand_inline_asm_string): Inline asm expansion fn
2024-09-02 09:44:55 +00:00
badumbatish
8d157b6367 Start work on expand inline asm
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.
2024-09-02 09:44:55 +00:00
badumbatish
f0df558069 Added counting to check for asm_construct_outputs
gcc/rust/ChangeLog:

	* backend/rust-compile-asm.cc (CompileAsm::asm_construct_outputs):
	Set up counting to check
2024-09-02 09:44:55 +00:00
badumbatish
95674a0a35 Added new test for prep of output {}
gcc/testsuite/ChangeLog:

	* rust/compile/inline_asm_parse_output_operand.rs: New test.
2024-09-02 09:44:55 +00:00
badumbatish
d645c55912 Minor fix to asm codegen pr
gcc/rust/ChangeLog:

	* backend/rust-compile-asm.cc (CompileAsm::asm_build_expr):
	Use expr's is_simple_asm and is_inline_asm
	(CompileAsm::asm_is_simple): removed
	(CompileAsm::asm_is_inline): removed
	* backend/rust-compile-asm.h: Add docs to ASM_TREE_ARRAY_LENGTH
	* hir/tree/rust-hir-expr.h: Add is_simple_asm, is_inline_asm
	and remove #include tree
2024-09-02 09:44:55 +00:00
badumbatish
63bccfc7f1 Refactor compile-asm for first round review
gcc/rust/ChangeLog:

	* backend/rust-compile-asm.cc (strip_double_quotes):
	Refactor compile-asm for first round review
	(CompileAsm::asm_build_asm_stmt): Likewise.
	(CompileAsm::asm_build_expr): Likewise.
	(CompileAsm::asm_get_locus): Likewise.
	(CompileAsm::asm_construct_string_tree): Likewise.
	(CompileAsm::asm_construct_outputs): Likewise.
	(CompileAsm::asm_construct_inputs): Likewise.
	(CompileAsm::asm_construct_clobber_tree): Likewise.
	(CompileAsm::asm_construct_label_tree): Likewise.
	(CompileAsm::asm_is_simple): Likewise.
	(CompileAsm::asm_is_inline): Likewise.
	* backend/rust-compile-asm.h (strip_double_quotes): Likewise.
	(class CompileAsm): Likewise.
2024-09-02 09:44:55 +00:00
badumbatish
f627811f55 Successfully produce pseudo-nop
gcc/rust/ChangeLog:

	* backend/rust-compile-asm.cc (CompileAsm::add_stmt):
	Deleted
	(CompileAsm::CompileAsm):
	Successfully produce pseudo-nop
	(CompileAsm::visit): Likewise
	(CompileAsm::asm_build_asm_stmt): Likewise
	(CompileAsm::asm_construct_string_tree): Likewise
	(CompileAsm::asm_is_inline): Likewise
	* backend/rust-compile-asm.h (class CompileAsm): Likewise
	* backend/rust-compile-expr.cc (CompileExpr::visit): Likewise
2024-09-02 09:44:55 +00:00
badumbatish
20cd09b19e Scaffolding code
gcc/rust/ChangeLog:

	* backend/rust-compile-asm.cc (CompileAsm::add_stmt):
	Scaffolding code.
	(CompileAsm::asm_build_asm_stmt): Likewise.
	(CompileAsm::asm_build_expr): Likewise.
	(CompileAsm::asm_construct_string_tree): Likewise.
	* backend/rust-compile-asm.h: Likewise.
	* backend/rust-compile-expr.cc (CompileExpr::visit): Likewise.
2024-09-02 09:44:55 +00:00
badumbatish
177ce2688f Scaffolding new compile-asm files
gcc/rust/ChangeLog:

	* Make-lang.in:
	Scaffolding new compile-asm files
	* backend/rust-compile-expr.cc (CompileExpr::visit): Likewise
	* hir/tree/rust-hir-expr.h: Likewise
	* backend/rust-compile-asm.cc: New file. Likewise
	* backend/rust-compile-asm.h: New file. Likewise
2024-09-02 09:44:55 +00:00
jjasmine
f9374ddf47 Setting up interfaces for codegen
gcc/rust/ChangeLog:

	* backend/rust-compile-expr.cc (CompileExpr::visit):
	Setting up interfaces for codegen
	* hir/tree/rust-hir-expr.h: Likewise.
2024-09-02 09:44:55 +00:00
jjasmine
163bd13671 Local testing for build_string and debug()
gcc/rust/ChangeLog:

	* backend/rust-compile-expr.cc (CompileExpr::visit):
	Local testing for build_string and debug()
2024-09-02 09:44:55 +00:00
jjasmine
c3e69be4e6 Make sure CompileExpr::visit is reached
gcc/rust/ChangeLog:

	* hir/tree/rust-hir.cc (InlineAsm::accept_vis):
	Make sure CompileExpr::visit is reached
	* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit):
	Likewise
gcc/testsuite/ChangeLog:

	* rust/compile/inline_asm_compile_nop.rs: New test.
2024-09-02 09:44:55 +00:00
jjasmine
b088273a2c Scaffolding asm codegen
gcc/rust/ChangeLog:

	* backend/rust-compile-block.h:
	Scaffolding asm codegen
	* backend/rust-compile-expr.cc (CompileExpr::visit): Likewise.
	* backend/rust-compile-expr.h: Likewise.
	* checks/errors/borrowck/rust-bir-builder-expr-stmt.cc (ExprStmtBuilder::visit): Likewise.
	* checks/errors/borrowck/rust-bir-builder-expr-stmt.h: Likewise.
	* checks/errors/borrowck/rust-bir-builder-lazyboolexpr.h: Likewise.
	* checks/errors/privacy/rust-privacy-reporter.cc (PrivacyReporter::visit): Likewise.
	* checks/errors/privacy/rust-privacy-reporter.h: Likewise.
	* hir/tree/rust-hir-expr.h: Likewise.
	* hir/tree/rust-hir-visitor.h: Likewise.
	* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit): Likewise.
	* typecheck/rust-hir-type-check-expr.h: Likewise.
2024-09-02 09:44:55 +00:00
badumbatish
716dadc800 Fix the parser's operand and flags storage
gcc/rust/ChangeLog:

	* expand/rust-macro-builtins-asm.cc (parse_reg_operand):
	Fix parsing logic & reassignment logic
	(parse_reg_operand_in): Fix parsing
	(parse_reg_operand_out): Fix parsing
	(parse_reg_operand_inout): Fix parsing
	(parse_reg_operand_unexpected): Remove rust_unreachable()
	(parse_asm_arg): Fix parsing logic
2024-09-02 09:44:55 +00:00
badumbatish
5b5aadb643 Add pop guard for binder
gcc/rust/ChangeLog:

	* typecheck/rust-hir-type-check.h:
	Add pop guard for binder
2024-08-29 13:00:17 +00:00
badumbatish
c2770bdd22 Add glibcxx_assertion check
ChangeLog:

	* .github/workflows/ccpp.yml:
	Add glibcxx_assertion check

	* .github/glibcxx_ubuntu64b_log_expected_warnings: New file.
2024-08-29 13:00:17 +00:00
badumbatish
369b51527a Add running cicd 32bit
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
2024-08-29 12:58:54 +00:00
Raiki Tamura
2501644463 gccrs: emit error code for E0758
gcc/rust/ChangeLog:

	* lex/rust-lex.cc (Lexer::build_token): Emit error code.
	* lex/rust-lex.h: Fix comment.

Signed-off-by: Raiki Tamura <tamaron1203@gmail.com>
2024-08-28 18:34:23 +00:00
Raiki Tamura
5da381ffd1 gccrs: Add typecheck for path patterns.
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>
2024-08-28 18:19:41 +00:00
Raiki Tamura
af7e8fda83 rust: Add checking for union patterns
gcc/rust/ChangeLog:

	* typecheck/rust-hir-type-check-pattern.cc (TypeCheckPattern::visit):
		Add check for union patterns.

gcc/testsuite/ChangeLog:

	* rust/compile/match8.rs: New test.

Signed-off-by: Raiki Tamura <tamaron1203@gmail.com>
2024-08-27 09:29:27 +00:00
Arthur Cohen
084789ed26 feature-gate: Cleanup visitor and constructor
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.
2024-08-22 13:44:34 +00:00
Arthur Cohen
06e8b826d7 attributes: Start handling prelude_import properly
This commit adds basic handling for the `#[prelude_import]` attribute,
without doing anything functionality wise.

gcc/rust/ChangeLog:

	* checks/errors/rust-feature-gate.cc (FeatureGate::visit): Add base
	feature gating for `#[feature(prelude_import)]`.
	* checks/errors/rust-feature-gate.h: Likewise.
	* checks/errors/rust-feature.cc (Feature::create): Likewise.
	* checks/errors/rust-feature.h: Likewise.
	* util/rust-attribute-values.h: Add base handling for `#[prelude_import]`
	attribute.
	* util/rust-attributes.cc: Likewise.

gcc/testsuite/ChangeLog:

	* rust/compile/prelude_import.rs: New test.
2024-08-22 12:30:27 +00:00
badumbatish
51948d296c Fix the disorder struct and class in inline asm
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
2024-08-21 15:03:09 +00:00
Arthur Cohen
d44051dea3 ast: Introduce class hierarchy for lang item paths
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.
2024-08-19 12:39:49 +00:00
Arthur Cohen
530b6121cf ast: Remove PathExpr abstract class
Inherit directly from ExprWithoutBlock instead.

gcc/rust/ChangeLog:

	* ast/rust-ast.h (class PathExpr): Remove class.
	* ast/rust-path.h (class PathInExpression): Inherit from ExprWithoutBlock.
	(class QualifiedPathInExpression): Likewise.
2024-08-19 12:39:49 +00:00
Arthur Cohen
fd916bed72 ast: PathPattern: Remove remove_all_segments method
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.
2024-08-19 12:39:49 +00:00
Muhammad Mahad
0f2062b77a Attempted to access a nonexistent field [E0609]
gcc/rust/ChangeLog:

	* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit):
	Add error code and update error message

gcc/testsuite/ChangeLog:

	* rust/compile/nonexistent-field.rs: New test.

Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
2024-08-16 14:24:07 +00:00
Kushal Pal
e61d37aae9 Move errors with locations
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>
2024-08-16 12:31:47 +00:00
Kushal Pal
c6d0824f09 Subset errors with locations
gcc/rust/ChangeLog:

	* checks/errors/borrowck/rust-borrow-checker-diagnostics.cc
	(BorrowCheckerDiagnostics::report_subset_errors): Highlight
	lifetime locations while reporting subset errors.
	(BorrowCheckerDiagnostics::get_lifetime_param): Helper function
	to fetch HIR::Lifetime node from Polonius::Origin.
	* checks/errors/borrowck/rust-borrow-checker-diagnostics.h:
	Definition of helper function.

gcc/testsuite/ChangeLog:

	* rust/borrowck/subset.rs: Better subset errors.

Signed-off-by: Kushal Pal <kushalpal109@gmail.com>
2024-08-16 12:31:02 +00:00
Kushal Pal
ddda47c4fe Map locations to placeholder regions
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>
2024-08-16 12:31:02 +00:00
Kushal Pal
44664e3875 Fixed testcase
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>
2024-08-14 13:45:13 +00:00
Liam Naddell
be1e78ba33 [#2324] Add error message for E0532
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>
2024-08-06 15:28:58 +00:00
Arthur Cohen
6a05b0ada8 borrowck: Avoid overloading issues on 32bit architectures
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)`
2024-08-06 13:38:34 +00:00
Arthur Cohen
bccb35bca0 borrowck: Fix debug prints on 32-bits architectures
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.
2024-08-06 13:38:34 +00:00
Liam Naddell
d2f032feb0 Eager expansion for include* #1805 #1865
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
2024-08-06 11:39:34 +00:00
Marc Poulhiès
47c16d7c81 rust: avoid clobbering LIBS
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>
2024-08-06 08:07:02 +00:00
Kushal Pal
177660eabd Simplify construction of BIR::Statement
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>
2024-08-02 11:41:15 +00:00
Kushal Pal
65bf72fcfb Loan errors with locations
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>
2024-08-02 11:41:15 +00:00
Kushal Pal
155f6a9c80 Add location to BIR::Statement of kind RETURN
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>
2024-08-02 11:41:15 +00:00
badumbatish
812c5347bc Implement resolve expr for inline asm ast
gcc/rust/ChangeLog:

	* resolve/rust-ast-resolve-expr.cc (ResolveExpr::visit):
	Implement resolve expr for inline asm ast
	(translate_operand): Likewise.
	* resolve/rust-ast-resolve-expr.h: Likewise.
2024-08-02 11:39:01 +00:00
Kushal Pal
bcd860f7f5 Add location to BIR::Loan
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>
2024-08-01 10:38:50 +00:00
Kushal Pal
f2c807127b Add location support to BIR::Statement
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>
2024-08-01 10:38:50 +00:00
badumbatish
e941015a2a Turn to switch case, use new helper functions
gcc/rust/ChangeLog:

	* hir/rust-ast-lower-expr.cc (translate_operand_in):
	Turn to switch case, use new helper functions
	(translate_operand_out): Likewise.
	(translate_operand_inout): Likewise.
	(translate_operand_split_in_out): Likewise.
	(translate_operand_const): Likewise.
	(translate_operand_sym): Likewise.
	(translate_operand_label): Likewise.
	(from_operand): Likewise.
	(ASTLoweringExpr::visit): Likewise.
2024-08-01 09:11:08 +00:00
badumbatish
78a1f763a9 Set up the hir lowering for operand
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
2024-08-01 09:11:08 +00:00
Kushal Pal
d6a7e71570 Improve compressed point bit manipulation
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>
2024-07-31 17:15:19 +00:00
badumbatish
a395a81095 Use new constructors and control flow for operand
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
2024-07-31 16:59:40 +00:00
badumbatish
96a8914ba0 Fix the parser's operand and flags storage
gcc/rust/ChangeLog:

	* ast/rust-expr.h (struct InlineAsmOperand):
	Add construction for register_type
	* expand/rust-macro-builtins-asm.cc (parse_reg_operand):
	Fix parsing logic & reassignment logic
	(parse_reg_operand_in): Fix parsing
	(parse_reg_operand_out): Fix parsing
	(parse_reg_operand_inout): Fix parsing
	(parse_reg_operand_unexpected): Remove rust_unreachable()
	(parse_asm_arg): Fix parsing logic
	* expand/rust-macro-builtins-asm.h: Add = operator overloading

gcc/testsuite/ChangeLog:

	* rust/compile/inline_asm_illegal_operands.rs: Test now passing
	* rust/compile/inline_asm_parse_operand.rs: Remove _, not
	supported right now
2024-07-31 16:59:40 +00:00
Kushal Pal
3b5801409d Fixed bitwise operation in extract_stmt
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>
2024-07-31 06:59:09 +00:00
Pierre-Emmanuel Patry
d55bbc2e8f Move mbe macro tests to their own directory
gcc/testsuite/ChangeLog:

	* rust/compile/macro-delim.rs: Move to...
	* rust/compile/macros/mbe/macro-delim.rs: ...here.
	* rust/compile/macro-issue1053-2.rs: Move to...
	* rust/compile/macros/mbe/macro-issue1053-2.rs: ...here.
	* rust/compile/macro-issue1053.rs: Move to...
	* rust/compile/macros/mbe/macro-issue1053.rs: ...here.
	* rust/compile/macro-issue1224.rs: Move to...
	* rust/compile/macros/mbe/macro-issue1224.rs: ...here.
	* rust/compile/macro-issue1233.rs: Move to...
	* rust/compile/macros/mbe/macro-issue1233.rs: ...here.
	* rust/compile/macro-issue1395-2.rs: Move to...
	* rust/compile/macros/mbe/macro-issue1395-2.rs: ...here.
	* rust/compile/macro-issue1395.rs: Move to...
	* rust/compile/macros/mbe/macro-issue1395.rs: ...here.
	* rust/compile/macro-issue1400-2.rs: Move to...
	* rust/compile/macros/mbe/macro-issue1400-2.rs: ...here.
	* rust/compile/macro-issue1400.rs: Move to...
	* rust/compile/macros/mbe/macro-issue1400.rs: ...here.
	* rust/compile/macro-issue2092.rs: Move to...
	* rust/compile/macros/mbe/macro-issue2092.rs: ...here.
	* rust/compile/macro-issue2192.rs: Move to...
	* rust/compile/macros/mbe/macro-issue2192.rs: ...here.
	* rust/compile/macro-issue2194.rs: Move to...
	* rust/compile/macros/mbe/macro-issue2194.rs: ...here.
	* rust/compile/macro-issue2229.rs: Move to...
	* rust/compile/macros/mbe/macro-issue2229.rs: ...here.
	* rust/compile/macro-issue2264.rs: Move to...
	* rust/compile/macros/mbe/macro-issue2264.rs: ...here.
	* rust/compile/macro-issue2268.rs: Move to...
	* rust/compile/macros/mbe/macro-issue2268.rs: ...here.
	* rust/compile/macro-issue2273.rs: Move to...
	* rust/compile/macros/mbe/macro-issue2273.rs: ...here.
	* rust/compile/macro-issue2653.rs: Move to...
	* rust/compile/macros/mbe/macro-issue2653.rs: ...here.
	* rust/compile/macro-issue2983_2984.rs: Move to...
	* rust/compile/macros/mbe/macro-issue2983_2984.rs: ...here.
	* rust/compile/macro1.rs: Move to...
	* rust/compile/macros/mbe/macro1.rs: ...here.
	* rust/compile/macro10.rs: Move to...
	* rust/compile/macros/mbe/macro10.rs: ...here.
	* rust/compile/macro11.rs: Move to...
	* rust/compile/macros/mbe/macro11.rs: ...here.
	* rust/compile/macro12.rs: Move to...
	* rust/compile/macros/mbe/macro12.rs: ...here.
	* rust/compile/macro13.rs: Move to...
	* rust/compile/macros/mbe/macro13.rs: ...here.
	* rust/compile/macro14.rs: Move to...
	* rust/compile/macros/mbe/macro14.rs: ...here.
	* rust/compile/macro15.rs: Move to...
	* rust/compile/macros/mbe/macro15.rs: ...here.
	* rust/compile/macro16.rs: Move to...
	* rust/compile/macros/mbe/macro16.rs: ...here.
	* rust/compile/macro17.rs: Move to...
	* rust/compile/macros/mbe/macro17.rs: ...here.
	* rust/compile/macro18.rs: Move to...
	* rust/compile/macros/mbe/macro18.rs: ...here.
	* rust/compile/macro19.rs: Move to...
	* rust/compile/macros/mbe/macro19.rs: ...here.
	* rust/compile/macro2.rs: Move to...
	* rust/compile/macros/mbe/macro2.rs: ...here.
	* rust/compile/macro20.rs: Move to...
	* rust/compile/macros/mbe/macro20.rs: ...here.
	* rust/compile/macro21.rs: Move to...
	* rust/compile/macros/mbe/macro21.rs: ...here.
	* rust/compile/macro22.rs: Move to...
	* rust/compile/macros/mbe/macro22.rs: ...here.
	* rust/compile/macro23.rs: Move to...
	* rust/compile/macros/mbe/macro23.rs: ...here.
	* rust/compile/macro25.rs: Move to...
	* rust/compile/macros/mbe/macro25.rs: ...here.
	* rust/compile/macro26.rs: Move to...
	* rust/compile/macros/mbe/macro26.rs: ...here.
	* rust/compile/macro27.rs: Move to...
	* rust/compile/macros/mbe/macro27.rs: ...here.
	* rust/compile/macro28.rs: Move to...
	* rust/compile/macros/mbe/macro28.rs: ...here.
	* rust/compile/macro29.rs: Move to...
	* rust/compile/macros/mbe/macro29.rs: ...here.
	* rust/compile/macro3.rs: Move to...
	* rust/compile/macros/mbe/macro3.rs: ...here.
	* rust/compile/macro30.rs: Move to...
	* rust/compile/macros/mbe/macro30.rs: ...here.
	* rust/compile/macro31.rs: Move to...
	* rust/compile/macros/mbe/macro31.rs: ...here.
	* rust/compile/macro32.rs: Move to...
	* rust/compile/macros/mbe/macro32.rs: ...here.
	* rust/compile/macro33.rs: Move to...
	* rust/compile/macros/mbe/macro33.rs: ...here.
	* rust/compile/macro34.rs: Move to...
	* rust/compile/macros/mbe/macro34.rs: ...here.
	* rust/compile/macro35.rs: Move to...
	* rust/compile/macros/mbe/macro35.rs: ...here.
	* rust/compile/macro36.rs: Move to...
	* rust/compile/macros/mbe/macro36.rs: ...here.
	* rust/compile/macro37.rs: Move to...
	* rust/compile/macros/mbe/macro37.rs: ...here.
	* rust/compile/macro38.rs: Move to...
	* rust/compile/macros/mbe/macro38.rs: ...here.
	* rust/compile/macro39.rs: Move to...
	* rust/compile/macros/mbe/macro39.rs: ...here.
	* rust/compile/macro4.rs: Move to...
	* rust/compile/macros/mbe/macro4.rs: ...here.
	* rust/compile/macro40.rs: Move to...
	* rust/compile/macros/mbe/macro40.rs: ...here.
	* rust/compile/macro41.rs: Move to...
	* rust/compile/macros/mbe/macro41.rs: ...here.
	* rust/compile/macro42.rs: Move to...
	* rust/compile/macros/mbe/macro42.rs: ...here.
	* rust/compile/macro43.rs: Move to...
	* rust/compile/macros/mbe/macro43.rs: ...here.
	* rust/compile/macro44.rs: Move to...
	* rust/compile/macros/mbe/macro44.rs: ...here.
	* rust/compile/macro45.rs: Move to...
	* rust/compile/macros/mbe/macro45.rs: ...here.
	* rust/compile/macro46.rs: Move to...
	* rust/compile/macros/mbe/macro46.rs: ...here.
	* rust/compile/macro47.rs: Move to...
	* rust/compile/macros/mbe/macro47.rs: ...here.
	* rust/compile/macro48.rs: Move to...
	* rust/compile/macros/mbe/macro48.rs: ...here.
	* rust/compile/macro49.rs: Move to...
	* rust/compile/macros/mbe/macro49.rs: ...here.
	* rust/compile/macro5.rs: Move to...
	* rust/compile/macros/mbe/macro5.rs: ...here.
	* rust/compile/macro50.rs: Move to...
	* rust/compile/macros/mbe/macro50.rs: ...here.
	* rust/compile/macro51.rs: Move to...
	* rust/compile/macros/mbe/macro51.rs: ...here.
	* rust/compile/macro52.rs: Move to...
	* rust/compile/macros/mbe/macro52.rs: ...here.
	* rust/compile/macro53.rs: Move to...
	* rust/compile/macros/mbe/macro53.rs: ...here.
	* rust/compile/macro54.rs: Move to...
	* rust/compile/macros/mbe/macro54.rs: ...here.
	* rust/compile/macro55.rs: Move to...
	* rust/compile/macros/mbe/macro55.rs: ...here.
	* rust/compile/macro56.rs: Move to...
	* rust/compile/macros/mbe/macro56.rs: ...here.
	* rust/compile/macro57.rs: Move to...
	* rust/compile/macros/mbe/macro57.rs: ...here.
	* rust/compile/macro6.rs: Move to...
	* rust/compile/macros/mbe/macro6.rs: ...here.
	* rust/compile/macro7.rs: Move to...
	* rust/compile/macros/mbe/macro7.rs: ...here.
	* rust/compile/macro8.rs: Move to...
	* rust/compile/macros/mbe/macro8.rs: ...here.
	* rust/compile/macro9.rs: Move to...
	* rust/compile/macros/mbe/macro9.rs: ...here.
	* rust/compile/macro_call_statement.rs: Move to...
	* rust/compile/macros/mbe/macro_call_statement.rs: ...here.
	* rust/compile/macro_export_1.rs: Move to...
	* rust/compile/macros/mbe/macro_export_1.rs: ...here.
	* rust/compile/macro_return.rs: Move to...
	* rust/compile/macros/mbe/macro_return.rs: ...here.
	* rust/compile/macro_rules_macro_rules.rs: Move to...
	* rust/compile/macros/mbe/macro_rules_macro_rules.rs: ...here.
	* rust/compile/macro_use1.rs: Move to...
	* rust/compile/macros/mbe/macro_use1.rs: ...here.
	* rust/compile/macros/mbe/mbe_macro.exp: New test.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2024-07-30 10:03:01 +00:00
Pierre-Emmanuel Patry
3854f5e4bc Move builtin macro tests to their own directory
We need a finer grain to filter tests and organise them.

gcc/testsuite/ChangeLog:

	* rust/compile/builtin_macro_compile_error.rs: Move to...
	* rust/compile/macros/builtin/compile_error.rs: ...here.
	* rust/compile/builtin_macro_concat.rs: Move to...
	* rust/compile/macros/builtin/concat.rs: ...here.
	* rust/compile/builtin_macro_eager1.rs: Move to...
	* rust/compile/macros/builtin/eager1.rs: ...here.
	* rust/compile/builtin_macro_eager2.rs: Move to...
	* rust/compile/macros/builtin/eager2.rs: ...here.
	* rust/compile/builtin_macro_eager3.rs: Move to...
	* rust/compile/macros/builtin/eager3.rs: ...here.
	* rust/compile/builtin_macro_env.rs: Move to...
	* rust/compile/macros/builtin/env.rs: ...here.
	* rust/compile/builtin_macro_include_bytes.rs: Move to...
	* rust/compile/macros/builtin/include_bytes.rs: ...here.
	* rust/compile/builtin_macro_include_bytes_location_info.rs: Move to...
	* rust/compile/macros/builtin/include_bytes_location_info.rs: ...here.
	* rust/compile/builtin_macro_include_str.rs: Move to...
	* rust/compile/macros/builtin/include_str.rs: ...here.
	* rust/compile/builtin_macro_include_str_location_info.rs: Move to...
	* rust/compile/macros/builtin/include_str_location_info.rs: ...here.
	* rust/compile/builtin_macro_not_found.rs: Move to...
	* rust/compile/macros/builtin/not_found.rs: ...here.
	* rust/compile/builtin_macro_recurse2.rs: Move to...
	* rust/compile/macros/builtin/recurse2.rs: ...here.
	* rust/compile/macros/builtin/builtin_macro.exp: New test.
	* rust/compile/invalid_utf8: Move invalid-utf8 data to...
	* rust/compile/macros/builtin/invalid_utf8: ...here.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2024-07-30 10:03:01 +00:00
Arthur Cohen
5d215e0748 github: Remove nightly Rust installation
ChangeLog:

	* .github/workflows/ccpp.yml: Install Rust 1.72 instead of nightly.
	* .github/workflows/bootstrap.yml: Likewise.
2024-07-29 14:55:40 +00:00
Arthur Cohen
9de294a684 ffi-polonius: Remove usage of extern types.
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
2024-07-29 14:55:40 +00:00
Pierre-Emmanuel Patry
c83b22a693 Move procedural macro test to their own directory
gcc/testsuite/ChangeLog:

	* rust/compile/macros/proc/proc_macro.exp: New deja gnu file to execute
	proc-macro tests.
	* rust/compile/proc_macro_attribute_crate_type.rs: Move to...
	* rust/compile/macros/proc/attribute_crate_type.rs: ...here.
	* rust/compile/proc_macro_attribute_non_function.rs: Move to...
	* rust/compile/macros/proc/attribute_non_function.rs: ...here.
	* rust/compile/proc_macro_attribute_non_root_function.rs: Move to...
	* rust/compile/macros/proc/attribute_non_root_function.rs: ...here.
	* rust/compile/proc_macro_attribute_non_root_method.rs: Move to...
	* rust/compile/macros/proc/attribute_non_root_method.rs: ...here.
	* rust/compile/proc_macro_attribute_non_root_module.rs: Move to...
	* rust/compile/macros/proc/attribute_non_root_module.rs: ...here.
	* rust/compile/proc_macro_attribute_private.rs: Move to...
	* rust/compile/macros/proc/attribute_private.rs: ...here.
	* rust/compile/proc_macro_crate_type.rs: Move to...
	* rust/compile/macros/proc/crate_type.rs: ...here.
	* rust/compile/proc_macro_derive_crate_type.rs: Move to...
	* rust/compile/macros/proc/derive_crate_type.rs: ...here.
	* rust/compile/proc_macro_derive_malformed.rs: Move to...
	* rust/compile/macros/proc/derive_malformed.rs: ...here.
	* rust/compile/proc_macro_derive_non_function.rs: Move to...
	* rust/compile/macros/proc/derive_non_function.rs: ...here.
	* rust/compile/proc_macro_derive_non_root_function.rs: Move to...
	* rust/compile/macros/proc/derive_non_root_function.rs: ...here.
	* rust/compile/proc_macro_derive_non_root_module.rs: Move to...
	* rust/compile/macros/proc/derive_non_root_module.rs: ...here.
	* rust/compile/proc_macro_derive_private.rs: Move to...
	* rust/compile/macros/proc/derive_private.rs: ...here.
	* rust/compile/proc_macro_non_function.rs: Move to...
	* rust/compile/macros/proc/non_function.rs: ...here.
	* rust/compile/proc_macro_non_root_function.rs: Move to...
	* rust/compile/macros/proc/non_root_function.rs: ...here.
	* rust/compile/proc_macro_non_root_method.rs: Move to...
	* rust/compile/macros/proc/non_root_method.rs: ...here.
	* rust/compile/proc_macro_non_root_module.rs: Move to...
	* rust/compile/macros/proc/non_root_module.rs: ...here.
	* rust/compile/proc_macro_derive_non_root_method.rs: Move to...
	* rust/compile/macros/proc/non_root_trait_method.rs: ...here.
	* rust/compile/proc_macro_private.rs: Move to...
	* rust/compile/macros/proc/private.rs: ...here.
	* rust/compile/proc_macro_pub_function.rs: Move to...
	* rust/compile/macros/proc/pub_function.rs: ...here.
	* rust/compile/proc_macro_pub_module.rs: Move to...
	* rust/compile/macros/proc/pub_module.rs: ...here.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2024-07-26 10:28:45 +00:00
Liam Naddell
a218b0335d [#3045] #[may_dangle] in safe impl
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>
2024-07-25 09:04:43 +00:00
Muhammad Mahad
47c947cfd9 gccrs: Add rustc test directory for testsuite adaptor
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>
2024-07-25 08:54:11 +00:00
Antonio Gomes
1eb42b0e34 Properly striping struct fields when using attrs
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>
2024-07-25 08:52:31 +00:00
Muhammad Mahad
8c357fd007 gccrs: [E0576] Associated item not found in given type
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>
2024-07-24 11:44:33 +00:00
Pierre-Emmanuel Patry
34a0835087 Change bug report issue template
ChangeLog:

	* .github/ISSUE_TEMPLATE/bug_report.yml: New file.
	* .github/ISSUE_TEMPLATE/bug_report.md: Deleted old template.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2024-07-24 10:49:44 +00:00
Liam Naddell
665d3014ce [#2987] Patch ICE when deriving Clone and Copy
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>
2024-07-24 10:27:38 +00:00
badumbatish
0d0530b65f Fix ffi and enum conventions
gcc/rust/ChangeLog:

	* ast/rust-fmt.h (enum ParseMode):
	Drop typedef in Cpp

libgrust/ChangeLog:

	* libformat_parser/generic_format_parser/src/lib.rs:
	Remove repr(C)
	* libformat_parser/src/bin.rs: Use ffi
	* libformat_parser/src/lib.rs: pub ffi, create ParseMode and match
	rustc's parse mode
2024-07-24 08:19:01 +00:00
badumbatish
a79d297dcc Added options for ParseMode
gcc/rust/ChangeLog:

	* ast/rust-fmt.cc (Pieces::collect):
	Added options for ParseMode
	* ast/rust-fmt.h (collect_pieces): Likewise.
	(struct Pieces): Likewise.
	* expand/rust-macro-builtins-format-args.cc (MacroBuiltin::format_args_handler):
	Likewise.

libgrust/ChangeLog:

	* libformat_parser/generic_format_parser/src/lib.rs: Likewise.
	* libformat_parser/src/bin.rs: Likewise.
	* libformat_parser/src/lib.rs: Likewise.
2024-07-24 08:19:01 +00:00
badumbatish
440b82882b Change assertion of constructor
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
2024-07-24 07:41:34 +00:00
Liam Naddell
bfee9e02cd [#3046] ICE on failing to find enum variant
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>
2024-07-18 12:43:05 +00:00
Pierre-Emmanuel Patry
043ce276e5 Fix CI bootstrap build with a nightly rust compiler
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>
2024-07-18 12:39:56 +00:00
badumbatish
0c2b03650f Update pattern with \r* for dg-output tests
First scan with "rg -v '\\r' gcc/testsuite/rust | rg 'dg-output'"

gcc/testsuite/ChangeLog:

	* rust/execute/torture/issue-2187.rs:
	Update pattern with \r* for dg-output tests
	* rust/execute/xfail/macro1.rs: Likewise
2024-07-18 11:08:24 +00:00
Antonio Gomes
5f001bab74 Improve error messages for operator expressions
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>
2024-07-17 11:41:19 +00:00
Kushal Pal
c1ba8985c6 Introduce new class to handle borrow errors
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>
2024-07-16 15:35:39 +00:00
Kushal Pal
ff59d15273 Fix nightly rustc warnings
libgrust/ChangeLog:

	* libformat_parser/Cargo.toml:
	Used crate-type instead of depricated crate_type.
	* libformat_parser/generic_format_parser/src/lib.rs:
	Remove dead code.
	* libformat_parser/src/lib.rs: Likewise.

Signed-off-by: Kushal Pal <kushalpal109@gmail.com>
2024-07-16 11:29:33 +00:00
Kushal Pal
48c94c4927 Added FFIVector to get Polonius output on C++ side
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>
2024-07-16 11:29:33 +00:00
Marc Poulhiès
e2b6a02937 rust: fix HIR dump for MatchExpr
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>
2024-07-15 12:05:54 +00:00
Liam Naddell
d674058318 [#3051] Remove unnecessary #include from rust-expr.h
gcc/rust/ChangeLog:
	* ast/rust-expr.h:
	Remove unnecessary include.

Signed-off-by: Liam Naddell <liam.naddell@mail.utoronto.ca>
2024-07-11 08:48:22 +00:00
badumbatish
fde617aede Pin node16 by allowing old version
ChangeLog:

	* .github/workflows/ccpp.yml:
	Pin node16 by allowing old version
2024-07-10 20:09:08 +00:00
badumbatish
61bf444797 Safe-guard InlineAsm structs
gcc/rust/ChangeLog:

	* ast/rust-expr.h (struct AnonConst):
	Safe-guard InlineAsm structs
	(struct InlineAsmOperand): Likewise.
	* expand/rust-macro-builtins-asm.cc (parse_reg_operand_in):
	Likewise.
	(parse_reg_operand_out): Likewise.
	(parse_reg_operand_inout): Likewise.

Signed-off-by: badumbatish <tanghocle456@gmail.com>
2024-07-03 09:25:47 +00:00
badumbatish
b657fa0c78 Store parse result of parse_format_string(s)
gcc/rust/ChangeLog:

	* ast/rust-expr.h (struct TupleTemplateStr):
	Store parse result of parse_format_string(s)
	* expand/rust-macro-builtins-asm.cc (parse_format_strings):
	Likewise

Signed-off-by: badumbatish <tanghocle456@gmail.com>
2024-07-01 13:30:38 +00:00
jjasmine
7fd14aafa3 Clean up monadic operations on expected<>
gcc/rust/ChangeLog:

	* expand/rust-macro-builtins-asm.cc (parse_asm):
	Clean up monadic operations on expected<>

Signed-off-by: badumbatish <tanghocle456@gmail.com>
2024-06-28 09:59:34 +00:00
jjasmine
69e06b2b6e Addresses warning, put warn unused in right place
gcc/rust/ChangeLog:

	* expand/rust-macro-builtins-asm.cc (parse_reg_operand):
	Addresses warning, put warn unused in right place
	(parse_reg_operand_inout): Likewise.
	(parse_asm_arg): Likewise.
	* expand/rust-macro-builtins-asm.h (enum WARN_UNUSED_RESULT): Likewise.
	(enum InlineAsmParseError): Likewise.
	(validate): Likewise.
	(parse_asm_arg): Likewise.
	(parse_format_strings): Likewise.
	(parse_clobber_abi): Likewise.
	(parse_reg_operand): Likewise.
	(parse_reg_operand_in): Likewise.
	(parse_reg_operand_out): Likewise.
	(parse_reg_operand_lateout): Likewise.
	(parse_reg_operand_inout): Likewise.
	(parse_reg_operand_inlateout): Likewise.
	(parse_reg_operand_const): Likewise.
	(parse_reg_operand_sym): Likewise.
	(parse_reg_operand_unexpected): Likewise.
	(parse_asm): Likewise.
	(check_and_set): Likewise.
	(parse_options): Likewise.
	(parse_reg): Likewise.
	(parse_format_string): Likewise.

Signed-off-by: badumbatish <tanghocle456@gmail.com>
2024-06-28 09:59:34 +00:00
jjasmine
6749034ca9 Add WARN_UNUSED_RESULT parse error
gcc/rust/ChangeLog:

	* expand/rust-macro-builtins-asm.h (enum InlineAsmParseError):
	Add WARN_UNUSED_RESULT parse error
	(enum WARN_UNUSED_RESULT): Likewise.

Signed-off-by: badumbatish <tanghocle456@gmail.com>
2024-06-28 09:59:34 +00:00
jjasmine
12cc79fe8f Added a test that is expected to fail
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>
2024-06-28 09:59:34 +00:00
jjasmine
76ba4a6580 Added tl::expected to parse_operand
Added tl::expected to parse_operand by implementing the validation
inside the parse_reg_operand function.

gcc/rust/ChangeLog:

	* ast/rust-expr.h:
	Added tl::expected to parse_operand
	* expand/rust-macro-builtins-asm.cc (parse_reg): Likewise.
	(parse_reg_operand): Likewise.
	(parse_reg_operand_const): Likewise.
	(parse_reg_operand_inout): Likewise.
	(parse_asm_arg): Likewise.
	* expand/rust-macro-builtins-asm.h: Likewise.

Signed-off-by: badumbatish <tanghocle456@gmail.com>
2024-06-28 09:59:34 +00:00
jjasmine
74b6c7e4f9 Scaffold expected on parse_options and asm_arg
gcc/rust/ChangeLog:

	* expand/rust-macro-builtins-asm.cc (check_and_set):
	Scaffold expected on parse_options and asm_arg
	(parse_options): Likewise
	(parse_asm_arg): Likewise
	* expand/rust-macro-builtins-asm.h (check_and_set): Likewise
	(parse_label): Likewise

Signed-off-by: badumbatish <tanghocle456@gmail.com>
2024-06-28 09:59:34 +00:00
jjasmine
c37eb03de6 Finish expected parse_reg_operand
gcc/rust/ChangeLog:

	* expand/rust-macro-builtins-asm.cc (parse_reg_operand_in):
	Finish expected parse_reg_operand
	(parse_reg_operand_unexpected): Likewise
	* expand/rust-macro-builtins-asm.h (parse_reg_operand_unexpected): Likewise

Signed-off-by: badumbatish <tanghocle456@gmail.com>
2024-06-28 09:59:34 +00:00
jjasmine
79a2eaa693 Finish incorporating expected of parse_reg_operand
gcc/rust/ChangeLog:

	* expand/rust-macro-builtins-asm.cc (parse_clobber_abi):
	Finish incorporating expected of parse_reg_operand
	(parse_reg): Likewise.
	(parse_reg_operand): Likewise.
	(parse_reg_operand_in): Likewise.
	(parse_reg_operand_out): Likewise.
	(parse_reg_operand_lateout): Likewise.
	(parse_reg_operand_const): Likewise.
	(parse_reg_operand_inout): Likewise.
	(parse_reg_operand_sym): Likewise.
	(MacroBuiltin::asm_handler): Likewise.
	(parse_asm_arg): Likewise.
	(parse_asm): Likewise.
	(parse_format_strings): Likewise.
	(validate): Likewise.
	* expand/rust-macro-builtins-asm.h (class InlineAsmParseError): Likewise.
	(enum InlineAsmParseError): Likewise.
	(validate): Likewise.
	(parse_format_strings): Likewise.
	(parse_reg_operand_in): Likewise.
	(parse_reg_operand_out): Likewise.
	(parse_reg_operand_lateout): Likewise.
	(parse_reg_operand_inout): Likewise.
	(parse_reg_operand_inlateout): Likewise.
	(parse_reg_operand_const): Likewise.
	(parse_reg_operand_sym): Likewise.
2024-06-28 09:59:34 +00:00
ansh
9e5a4b410d Add RAW_STRING_LITERAL
gcc/rust/ChangeLog:

	* ast/rust-ast-collector.cc (TokenCollector::visit):
	Handle case for RAW_STRING_LITERAL.
	* ast/rust-ast.cc (AttributeParser::parse_meta_item_inner):
	Likewise.
	(AttributeParser::parse_literal): Likewise.
	* ast/rust-ast.h: Likewise.
	* hir/rust-ast-lower-base.cc (ASTLoweringBase::lower_literal):
	Likewise.
	* lex/rust-lex.cc (Lexer::parse_raw_string): Likewise.
	* lex/rust-token.cc (Token::as_string): Likewise.
	* lex/rust-token.h (enum PrimitiveCoreType): Likewise.
	* parse/rust-parse-impl.h (Parser::parse_attr_input): Likewise.
	(Parser::parse_literal_expr): Likewise.
	(Parser::parse_pattern_no_alt): Likewise.

Signed-off-by: ansh <anshmalik2002@gmail.com>
2024-06-27 11:25:11 +00:00
jjasmine
40d5292246 Added ExprType::InlineAsm
gcc/rust/ChangeLog:

	* hir/tree/rust-hir-expr.h:
	Added ExprType::InlineAsm
	* hir/tree/rust-hir.h:
	Added ExprType::InlineAsm
2024-06-24 13:18:26 +00:00
jjasmine
2ce6c08f21 Add test case for using asm! outside of unsafe {}
gcc/testsuite/ChangeLog:

	* rust/compile/inline_asm_outside_unsafe.rs: New test.
2024-06-24 13:16:02 +00:00
Arthur Cohen
7d22e900b0 expand: Switch semicolon boolean to an enum instead.
gcc/rust/ChangeLog:

	* ast/rust-ast-fragment.h (enum class): Add InvocKind and AsmKind enums.
	* ast/rust-macro.h: Switch semicolon boolean to InvocKind enum.
	* expand/rust-expand-visitor.cc (ExpandVisitor::visit): Likewise.
	* 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.
	(enum class): 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_eager_invocations): Likewise.
	(MacroExpander::expand_invoc): Likewise.
	* expand/rust-macro-expand.h (struct MacroExpander): Likewise.
2024-06-18 12:24:32 +00:00
Arthur Cohen
fb906a41a4 expand: Keep track of semicoloned builtin macros
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.
2024-06-18 12:24:32 +00:00
dave
89c056bf37 Fix optional trait parsing
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>
2024-06-17 10:28:46 +00:00
jjasmine
7fa14d4f64 Partial second layer of expected in parsing asm
gcc/rust/ChangeLog:

	* expand/rust-macro-builtins-asm.cc (parseDirSpec):
	Partial second layer of expected in parsing asm
	(parse_clobber_abi): Likewise
	(parse_operand): Likewise
	(parse_reg_operand): Likewise
	(parse_asm_arg): Likewise
	* expand/rust-macro-builtins-asm.h (parse_clobber_abi): Likewise
	(parse_reg_operand): Likewise
	(parse_operand): Likewise
2024-06-13 15:31:07 +00:00
jjasmine
1d3031a9c8 Expected first layer done
gcc/rust/ChangeLog:

	* expand/rust-macro-builtins-asm.cc (parse_reg):
	Expected first layer done
	(parse_reg_operand): Likewise.
	(parse_asm_arg): Likewise.
	(parse_format_strings): Likewise.
	(parse_asm): Likewise.
	(validate): Likewise.
	* expand/rust-macro-builtins-asm.h (parse_asm_arg): Likewise.
	(validate): Likewise.
	(parse_format_strings): Likewise.
2024-06-13 15:31:07 +00:00
jjasmine
da324bc6ee Move parser and last_token_id to InlineAsmCtx
gcc/rust/ChangeLog:

	* expand/rust-macro-builtins-asm.cc (parse_clobber_abi):
	Move parser and last_token_id to InlineAsmCtx to prepapre
	for tl::expected.
	(parse_reg): Likewise.
	(parse_operand): Likewise.
	(parse_reg_operand): Likewise.
	(check_and_set): Likewise.
	(parse_options): Likewise.
	(parse_format_string): Likewise.
	(parse_asm_arg): Likewise.
	(parse_asm): Likewise.
	* expand/rust-macro-builtins-asm.h (class InlineAsmParseError): Likewise.
	(parse_asm_arg): Likewise.
	(check_and_set): Likewise.
	(parse_operand): Likewise.
	(parse_reg_operand): Likewise.
	(parse_options): Likewise.
	(parse_reg): Likewise.
	(parse_clobber_abi): Likewise.
	(parse_format_string): Likewise.
2024-06-13 15:31:07 +00:00
jjasmine
9202993a57 Update parser to parse strings in the first stage
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
2024-06-13 15:31:07 +00:00
jjasmine
07a48d90e0 Scaffolding validation of asm!
gcc/rust/ChangeLog:

	* expand/rust-macro-builtins-asm.cc (parse_asm):
	Scaffolding validation of asm!
	(validate): Likewise
	* expand/rust-macro-builtins-asm.h (validate): Likewise
2024-06-13 15:31:07 +00:00
jjasmine
9d812b8af7 Partial support for operand
gcc/rust/ChangeLog:

	* ast/rust-expr.h (struct InlineAsmOperand):
	Partial support for operand
	* expand/rust-macro-builtins-asm.cc (parse_reg_operand): Likewise.
	(parse_label): Likewise.
	* expand/rust-macro-builtins-asm.h (parse_label): Likewise.
2024-06-13 15:31:07 +00:00
jjasmine
57c1f3a0f0 Refactoring and supporting more parse_reg_operand
gcc/rust/ChangeLog:

	* ast/rust-expr.h (struct InlineAsmOperand):
	Refactoring and supporting more parse_reg_operand
	* expand/rust-macro-builtins-asm.cc (parse_reg_operand):
	Likewise.
	(rust_debug): Likewise.
2024-06-13 15:31:07 +00:00
jjasmine
4eb63c929f Fix visitor-related warnings
gcc/rust/ChangeLog:

	* ast/rust-ast-collector.cc (TokenCollector::visit):
	Fix visitor-related warnings
	* ast/rust-ast-collector.h: Likewise.
	* ast/rust-ast-visitor.cc (DefaultASTVisitor::visit): Likewise.
	* ast/rust-ast-visitor.h: Likewise.
	* checks/errors/borrowck/rust-bir-builder-struct.h: Likewise.
	* checks/errors/borrowck/rust-function-collector.h: Likewise.
	* checks/errors/rust-const-checker.cc (ConstChecker::visit): Likewise.
	* checks/errors/rust-const-checker.h: Likewise.
	* expand/rust-derive.h: Likewise.
	* expand/rust-macro-builtins-asm.cc (parse_reg_operand): Likewise.
	* hir/rust-hir-dump.cc (Dump::visit): Likewise.
	* hir/rust-hir-dump.h: Likewise.
	* hir/tree/rust-hir-visitor.h: Likewise.
	* resolve/rust-ast-resolve-base.cc (ResolverBase::visit): Likewise.
	* resolve/rust-ast-resolve-base.h: Likewise.
2024-06-13 15:31:07 +00:00
jjasmine
4ec940e39c Add potentially_nonpromoted_keywords set str
gcc/rust/ChangeLog:

	* expand/rust-macro-builtins-asm.cc (parse_reg_operand):
	Add potentially_nonpromoted_keywords set str
	(check_identifier): likewise
	* expand/rust-macro-builtins-asm.h (parse_format_string):
	likewise

gcc/testsuite/ChangeLog:

	* rust/compile/inline_asm_parse_operand.rs: fix warnings
2024-06-13 15:31:07 +00:00
jjasmine
d24c338399 Successful parse of in and inout, albeit with str
gcc/rust/ChangeLog:

	* expand/rust-macro-builtins-asm.cc (parse_reg_operand):
	Successful parse of in and inout, albeit with str
	(check_identifier): Likewise.
	(parse_asm_arg): Likewise.
	* expand/rust-macro-builtins-asm.h (parse_format_string): Likewise.

gcc/testsuite/ChangeLog:

	* rust/compile/inline_asm_parse_operand.rs: New test.
2024-06-13 15:31:07 +00:00
jjasmine
ba44023899 Scaffolding HIRFullVisitor for inline asm
gcc/rust/ChangeLog:

	* ast/rust-ast-visitor.h:
	Scaffolding HIRFullVisitor for inline asm
	* ast/rust-ast.cc (InlineAsm::accept_vis): Likewise.
	* hir/tree/rust-hir-visitor.h (RUST_HIR_VISITOR_H): Likewise.
	* hir/tree/rust-hir.cc (InlineAsm::accept_vis): Likewise.
2024-06-13 15:31:07 +00:00
jjasmine
5075dee97b Scaffolding ast visitor for InlineAsm
gcc/rust/ChangeLog:

	* ast/rust-ast-visitor.h:
	Scaffolding ast visitor for InlineAsm
	* ast/rust-ast.cc (InlineAsm::accept_vis): Likewise.
	* ast/rust-expr.h: Likewise.
2024-06-13 15:31:07 +00:00
jjasmine
379670e7f6 Fix warnings
gcc/rust/ChangeLog:

	* expand/rust-macro-builtins-asm.cc (parse_reg_operand):
	Fix compile warnings.
	(parse_options): Likewise.
	(parse_asm): Likewise.

gcc/testsuite/ChangeLog:

	* rust/compile/inline_asm_illegal_options.rs:
2024-06-13 15:31:07 +00:00
jjasmine
914777653e Partial unsafe support for inline asm
gcc/rust/ChangeLog:

	* checks/errors/rust-unsafe-checker.cc (UnsafeChecker::visit):
	Partial unsafe support for inline asm
	* checks/errors/rust-unsafe-checker.h: Likewise.
	* hir/tree/rust-hir-expr.h: Likewise.
	* hir/tree/rust-hir.cc (InlineAsm::accept_vis): Likewise.
2024-06-13 15:31:07 +00:00
jjasmine
520d279b5d Add support for AST to HIR inline asm translation
gcc/rust/ChangeLog:

	* ast/rust-expr.h:
	Add support for AST to HIR inline asm translation
	* hir/rust-ast-lower-base.cc (ASTLoweringBase::visit): Likewise.
	* hir/rust-ast-lower-base.h: Likewise.
	* hir/rust-ast-lower-expr.cc (ASTLoweringExpr::visit): Likewise.
	* hir/rust-ast-lower-expr.h: Likewise.
	* hir/tree/rust-hir-expr.h (class InlineAsm): Likewise.
2024-06-13 15:31:07 +00:00
jjasmine
dd03ef700b Slim down the test cases
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.
2024-06-13 15:31:07 +00:00
jjasmine
e63fba72a6 Refactoring for inline asm pr
gcc/rust/ChangeLog:

	* ast/rust-expr.h (struct AnonConst):
	major refactoring of inline asm, mostly concerns
	naming convention, trinary conditionals, warnings,
	adding rust_unreachables in not-yet supported errors.
	(struct InlineAsmRegOrRegClass): Likewise.
	(struct InlineAsmOperand): Likewise.
	* expand/rust-macro-builtins-asm.cc (parse_clobber_abi): Likewise.
	(parse_reg): Likewise.
	(parse_operand): Likewise.
	(parse_reg_operand): Likewise.
	(check_and_set): Likewise.
	(parse_options): Likewise.
	(parse_format_string): Likewise.
	(parse_asm_arg): Likewise.
	(parse_asm): Likewise.
	* expand/rust-macro-builtins-asm.h (parse_asm_arg): Likewise.
	(check_identifier): Likewise.
	(check_and_set): Likewise.
	(parse_operand): Likewise.
	(parse_reg_operand): Likewise.
	(parse_options): Likewise.
	(parse_reg): Likewise.
	(parse_clobber_abi): Likewise.
	* expand/rust-macro-builtins.cc (enum class): Likewise.
	(inline_asm_maker): Likewise.
	* checks/errors/borrowck/ffi-polonius/Cargo.lock: Removed. Likewise.

gcc/testsuite/ChangeLog:
	* rust/compile/inline_asm_faulty_clobber.rs: Likewise.
	* rust/compile/inline_asm_faulty_clobber_1.rs: Likewise.
	* rust/compile/inline_asm_faulty_clobber_2.rs: Likewise.
	* rust/compile/inline_asm_illegal_options.rs: Likewise.
2024-06-13 15:31:07 +00:00
jjasmine
bfcebbf7e1 Got AST::Fragment to be created from InlineAsm
gcc/rust/ChangeLog:

	* ast/rust-expr.h (struct AnonConst):
	Got AST::Fragment to be created from InlineAsm.
	(struct InlineAsmOperand): Likewise.
	(class InlineAsm): Likewise.
	* expand/rust-macro-builtins-asm.cc (parse_reg_operand): Likewise.
	(parse_asm): likewise
2024-06-13 15:31:07 +00:00
jjasmine
a5c3c7615f Working towards parse_reg and parse_reg_operand
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.
2024-06-13 15:31:07 +00:00
jjasmine
4b1fa28ff5 Renamed parseAsmArg to conform to other function names
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.
2024-06-13 15:31:07 +00:00
jjasmine
0eafcc2799 Big Refactor after meeting
gcc/rust/ChangeLog:

	* ast/rust-expr.h (struct InlineAsmRegOrRegClass):
	Remove union
	(struct InlineAsmOperand): Make instances of inside struct.
	* expand/rust-macro-builtins-asm.cc (parse_clobber_abi):
	Change signature with inlineAsmCtx.
	(parse_reg): Likewise.
	(parse_operand): Likewise.
	(parse_reg_operand): Likewise.
	(check_and_set): Likewise.
	(parse_options): Likewise.
	(parse_format_string): Likewise.
	(parseAsmArg): Likewise.
	(parse_asm): Likewise.
	* expand/rust-macro-builtins-asm.h (class InlineAsmContext): Likewise.
	(parseAsmArg): Likewise.
	(check_and_set): Likewise.
	(parse_reg_operand): Likewise.
	(parse_options): Likewise.
	(parse_reg): Likewise.
	(parse_clobber_abi): Likewise.
2024-06-13 15:31:07 +00:00
jjasmine
56c687a5f6 Remove global_asm and non_global_asm handler
gcc/rust/ChangeLog:

	* expand/rust-macro-builtins-asm.cc
	(MacroBuiltin::global_asm_handler):
	Remove global_asm and non_global_asm handler
	(MacroBuiltin::nonglobal_asm_handler): Likewise.
	(MacroBuiltin::asm_handler): Likewise.
	* expand/rust-macro-builtins.cc (enum class): Likewise.
	(inline_asm_maker): Likewise.
	* expand/rust-macro-builtins.h: Likewise.
2024-06-13 15:31:07 +00:00
jjasmine
69265253d1 Safegaurd InlineAsm's clone_expr_...
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.
2024-06-13 15:31:07 +00:00
jjasmine
93e27fa1b2 Rename InlineAsmOptions to InlineAsmOption
Rename InlineAsmOptions to InlineAsmOption for clarity

gcc/rust/ChangeLog:

	* ast/rust-ast-full-decls.h (enum class):
	Rename InlineAsmOptions to InlineAsmOption for clarity
	* ast/rust-expr.h (enum class): Likewise.
	* expand/rust-macro-builtins-asm.cc (check_and_set): Likewise.
	(parse_options): Likewise.
	* expand/rust-macro-builtins-asm.h (check_and_set): Likewise.
	* hir/tree/rust-hir-expr.h: Likewise.
2024-06-13 15:31:07 +00:00
jjasmine
387917381a Scaffolding parse_reg
gcc/rust/ChangeLog:

	* ast/rust-expr.h (struct InlineAsmRegOrRegClass):
	Scaffolding parse_reg
	* expand/rust-macro-builtins-asm.cc (parse_reg): Likewise.
	(parse_operand): Likewise.
	(parseAsmArg): Likewise.
2024-06-13 15:31:07 +00:00
jjasmine
24fa822edf Resolve static decl warning
gcc/rust/ChangeLog:

	* expand/rust-macro-builtins-asm.h (parseAsmArg):
	Resolve static decl warning
	(parse_nonglobal_asm):
	Resolve static decl warning
2024-06-13 15:31:07 +00:00
jjasmine
a4cbd38f06 Add checks for duplicate options in inline asm
gcc/rust/ChangeLog:

	* expand/rust-macro-builtins-asm.cc (check_and_set):
	Add checks for duplicate options in inline asm
	(parse_options): likewise.

gcc/testsuite/ChangeLog:

	* rust/compile/inline_asm_illegal_options.rs: New test.
2024-06-13 15:31:07 +00:00
jjasmine
ed17ab77c3 Wraps inline_asm tests in unsafe {}
gcc/testsuite/ChangeLog:

	* rust/compile/inline_asm_faulty_clobber.rs:
	Wraps inline_asm tests in unsafe {}
	* rust/compile/inline_asm_faulty_clobber_1.rs: likewise.
	* rust/compile/inline_asm_faulty_clobber_2.rs: likewise.
	* rust/compile/inline_asm_ident_first.rs: likewise.
	* rust/compile/inline_asm_nop.rs: likewise.
	* rust/compile/inline_asm_nop_2.rs: likewise.
2024-06-13 15:31:07 +00:00
jjasmine
0044275c34 Parsing of options(...) done.
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.
2024-06-13 15:31:07 +00:00
jjasmine
4ca3eaaad7 Implemented parse_clobber_abi to pass new tests
gcc/rust/ChangeLog:

	* expand/rust-macro-builtins-asm.cc (parse_clobber_abi):
	implemented parse_clobber_abi
	(parse_format_string): likewise.
	(parseAsmArg): likewise.
	(parse_asm): likewise.
	* expand/rust-macro-builtins-asm.h (parseAsmArg): likewise.
2024-06-13 15:31:07 +00:00
jjasmine
de7dbe64f8 Added faulty tests for inline asm cloberring
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.
2024-06-13 15:31:07 +00:00
jjasmine
a4fe2a1016 Add tests parsing with trailing commas inline asm
gcc/testsuite/ChangeLog:

	* rust/compile/inline_asm_nop_2.rs: New test.
2024-06-13 15:31:07 +00:00
jjasmine
2822845b16 Top level parsing test for asm!
gcc/testsuite/ChangeLog:

	* rust/compile/inline_asm_ident_first.rs: New test.
2024-06-13 15:31:07 +00:00
jjasmine
af74733fa9 Add a simple no-op test for asm!
gcc/testsuite/ChangeLog:

	* rust/compile/inline_asm_nop.rs: Simple test for asm!
2024-06-13 15:31:07 +00:00
jjasmine
1e78474682 Replace scaffolded InlineAsm with real InlineAsm.
Replace scaffolded InlineAsm with real InlineAsm node in rust-expr.h

gcc/rust/ChangeLog:

	* expand/rust-macro-builtins-asm.cc (parseDirSpec): replace
	scaffolded InlineAsm with real InlineAsm.
	(parse_clobber_abi): likewise.
	(check_and_set): likewise.
	(parse_options): likewise.
	(parseAsmArg): likewise.
	(parse_asm): likewise.
	* expand/rust-macro-builtins-asm.h (struct AsmParseError): likewise.
	(enum InlineAsmDirSpec): likewise.
	(enum InlineAsmRegOrRegClass): likewise.
	(struct AsmArg): likewise.
	(parseAsmArg): likewise.
	(check_and_set): likewise.
	(parse_operand): likewise.
	(parse_options): likewise.
	(parse_reg): likewise.
	(parse_clobber_abi): likewise.
2024-06-13 15:31:07 +00:00
jjasmine
3c93736b8b Make InlineAsm non-abstract for usage in parsing.
gcc/rust/ChangeLog:

	* ast/rust-expr.h: Make InlineAsm non-abstract for usage in parsing.
2024-06-13 15:31:07 +00:00
jjasmine
c3bdf2dda8 Introduced is_global_asm to InlineAsm AST
gcc/rust/ChangeLog:

	* ast/rust-expr.h: Introduced is_global_asm to InlineAsm AST
2024-06-13 15:31:07 +00:00
jjasmine
666e43bde8 First draft of parse_option finished
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
2024-06-13 15:31:07 +00:00
jjasmine
b923da77f0 Fix clobber_api brackets
gcc/rust/ChangeLog:

	* expand/rust-macro-builtins-asm.cc (parse_clobber_abi): title.
2024-06-13 15:31:07 +00:00
jjasmine
edd623c58e Working on parse_options for a bit more
gcc/rust/ChangeLog:

	* expand/rust-macro-builtins-asm.cc (parse_options): title.
2024-06-13 15:31:07 +00:00
jjasmine
68d60cf538 Introduce first implementation of parse_clobber_abi
gcc/rust/ChangeLog:

	* expand/rust-macro-builtins-asm.cc (parse_clobber_abi): title.
	(parseAsmArg): title.
	* expand/rust-macro-builtins-asm.h (parse_clobber_abi): title.
2024-06-13 15:31:07 +00:00
jjasmine
424224a0a4 Working on parseAsmArg
gcc/rust/ChangeLog:

	* expand/rust-macro-builtins-asm.cc (enum InlineAsmRegOrRegClass): title.
	(parseAsmArg): title.
	(check_identifier): title.
	(parse_operand): title.
	(parse_options): title.
	(parse_reg): title.
	(parseDirSpec): title.
	(parse_asm): title.
2024-06-13 15:31:07 +00:00
jjasmine
3f23987dab Almost done with top level parsing
gcc/rust/ChangeLog:

	* expand/rust-macro-builtins-asm.cc (struct AsmParseError): title.
	(enum InlineAsmDirSpec): title.
	(enum InlineAsmOptions): title.
	(struct AsmArg): title.
	(parseAsmArg): title.
	(parse_global_asm): title.
	(parse_nonglobal_asm): title.
	(parse_asm): title.
	(parseDirSpec): title.
	(parse_format_string): title.
	(MacroBuiltin::global_asm_handler): title.
	(MacroBuiltin::nonglobal_asm_handler): title.
	* expand/rust-macro-builtins.cc: title.
	* expand/rust-macro-builtins.h: title.
2024-06-13 15:31:07 +00:00
Pierre-Emmanuel Patry
f88aa88faf Add regression tests for exclusive range pattern
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>
2024-06-12 11:11:56 +00:00
Pierre-Emmanuel Patry
956542656f Add exclusive_range_pattern feature gate
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>
2024-06-12 11:11:56 +00:00
Pierre-Emmanuel Patry
a178a07e43 Parse exclusive range pattern
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>
2024-06-12 11:11:56 +00:00
Pierre-Emmanuel Patry
6fc8ad5340 Add some test for raw_ref_op to prevent regressions
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>
2024-06-12 09:56:01 +00:00
Pierre-Emmanuel Patry
bd97356fbb Add raw_ref_op feature gate
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>
2024-06-12 09:56:01 +00:00
Pierre-Emmanuel Patry
ef8821745e Prevent raw reference from being lowered silently
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>
2024-06-12 09:56:01 +00:00
Pierre-Emmanuel Patry
a8e63c472f Parse raw ref operator
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>
2024-06-12 09:56:01 +00:00
Pierre-Emmanuel Patry
53a857ac94 Add a new regression test over struct expr field
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>
2024-06-12 09:11:18 +00:00
Pierre-Emmanuel Patry
8de769bfc5 Add outer attributes to struct expr fields
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>
2024-06-12 09:11:18 +00:00
Arthur Cohen
a45362e582 rust: Do not link with libdl and libpthread unconditionally
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.
2024-06-12 08:29:11 +00:00
Pierre-Emmanuel Patry
14c4c2f142 Add two new tests related to may_dangle attribute
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>
2024-06-11 15:53:17 +00:00
Pierre-Emmanuel Patry
85967c8781 Add dropck_eyepatch feature gate for may_dangle
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>
2024-06-11 15:53:17 +00:00
Pierre-Emmanuel Patry
2a1e169956 Allow multiple outer attributes on generic params
Previously generic params only allowed one outer attribute in front of
them.

gcc/rust/ChangeLog:

	* ast/rust-ast-collector.cc (TokenCollector::visit): Visit outer
	attributes.
	* ast/rust-ast-visitor.cc (DefaultASTVisitor::visit): Change outer
	attribute visit, we need to visit all of them.
	* ast/rust-ast.cc (LifetimeParam::as_string): Change as_string
	implementation to allow multiple outer attributes.
	(TypeParam::as_string): Likewise.
	* ast/rust-ast.h (class LifetimeParam): Allow multiple outer
	attributes.
	* ast/rust-item.h (class TypeParam): Likewise.
	* ast/rust-path.h: Likewise.
	* parse/rust-parse-impl.h (Parser::parse_generic_param): Change call
	to outer attribute parsing to collect several attributes.
	(Parser::parse_lifetime_param): Likewise.
	(Parser::parse_type_param): Likewise.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2024-06-11 15:53:17 +00:00
Pierre-Emmanuel Patry
50862befdb Fix generic parameter parsing
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>
2024-06-11 15:53:17 +00:00
Pierre-Emmanuel Patry
36a21ef17c Add new test for box syntax
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>
2024-06-11 11:19:26 +00:00
Pierre-Emmanuel Patry
ca178958c4 Add feature gate for box syntax
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>
2024-06-11 11:19:26 +00:00
Pierre-Emmanuel Patry
32ccdf41a0 Parse box expressions
Add support for old box expression syntax.

gcc/rust/ChangeLog:

	* ast/rust-ast-collector.cc (TokenCollector::visit): Add visit member
	function for BoxExpr nodes.
	* ast/rust-ast-collector.h: Add visit function prototype.
	* ast/rust-ast-visitor.cc (DefaultASTVisitor::visit): Add visit member
	function to default ast visitor.
	* ast/rust-ast-visitor.h: Add visit function's prototype.
	* ast/rust-ast.cc (BoxExpr::as_string): Add as_string function
	implementation for BoxExpr.
	(BoxExpr::accept_vis): Add accept_vis implementation to BoxExpr.
	* ast/rust-expr.h (class BoxExpr): Add BoxExpr class to represent boxed
	expressions.
	* expand/rust-derive.h: Add BoxExpr visit function prototype.
	* hir/rust-ast-lower-base.cc (ASTLoweringBase::visit): Add BoxExpr
	visitor implementation.
	* hir/rust-ast-lower-base.h: Add visit function's prototype.
	* hir/rust-ast-lower-expr.cc (ASTLoweringExpr::visit): Add BoxExpr
	visitor implementation.
	* hir/rust-ast-lower-expr.h: Add visit function's prototype.
	* parse/rust-parse-impl.h (Parser::parse_box_expr): Add parse_box_expr
	function's implementation.
	* parse/rust-parse.h: Add parse_box_expr function's prototype.
	* resolve/rust-ast-resolve-base.cc (ResolverBase::visit): Add resolver
	visit implementation.
	* resolve/rust-ast-resolve-base.h: Add resolver's visit function
	prototype.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2024-06-11 11:19:26 +00:00
Owen Avery
75049a3bfe Improve handling of ConstantItem during name resolution 2.0
gcc/rust/ChangeLog:

	* resolve/rust-default-resolver.cc
	(DefaultResolver::visit):
	Scope with Rib::Kind::ConstantItem instead
	of Rib::Kind::Item.
	* resolve/rust-toplevel-name-resolver-2.0.cc
	(TopLevel::visit): Remove redundancy in override of
	ConstantItem visitor.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2024-06-06 17:50:18 +00:00
Owen Avery
646046091b Allow rustc_const_stable and rustc_const_unstable
gcc/rust/ChangeLog:

	* expand/rust-macro-builtins.cc
	(MacroBuiltin::builtin_transcribers):
	Add entries for "rustc_const_stable" and "rustc_const_unstable".
	* util/rust-attributes.cc
	(__definitions): Add entries for RUSTC_CONST_STABLE and
	RUSTC_CONST_UNSTABLE.
	* util/rust-attribute-values.h
	(Attributes::RUSTC_CONST_STABLE): New.
	(Attributes::RUSTC_CONST_UNSTABLE): New.

gcc/testsuite/ChangeLog:

	* rust/compile/rustc_const_stable.rs:
	Enable feature rustc_attrs, expect no errors.
	* rust/compile/rustc_const_unstable.rs: New test.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2024-05-29 08:58:48 +00:00
Kushal Pal
9ade15d37e Corrected access specifiers
gcc/rust/ChangeLog:

	* ast/rust-expr.h (class OperatorExpr):
	Location should be private.
	* hir/tree/rust-hir-expr.h (class OperatorExpr): Likewise.

Signed-off-by: Kushal Pal <kushalpal109@gmail.com>
2024-05-28 11:08:52 +00:00
jjasmine
84666c6eec Make gccrs recognize negative_impls
gcc/rust/ChangeLog:

	* checks/errors/rust-feature-gate.cc (FeatureGate::visit): make
	gccrs recognize negative_impls
	* checks/errors/rust-feature-gate.h: likewise.
	* checks/errors/rust-feature.cc (Feature::create): likewise.
	* checks/errors/rust-feature.h: likewise.

gcc/testsuite/ChangeLog:

	* rust/compile/negative_impls.rs: New test.
	* rust/compile/negative_impls_2.rs: New test.
2024-05-24 09:27:42 +00:00
SIGMazer
219cea7881 Add system include to gcc/rust/rust-system.h
gcc/rust/ChangeLog:

	* rust-system.h: Add system include <stack>

Signed-off-by: SIGMazer <mazinasd7@gmail.com>
2024-05-21 12:42:09 +00:00
Owen Avery
80e0560b54 Add call and method call default visitors
gcc/rust/ChangeLog:

	* resolve/rust-default-resolver.cc
	(DefaultResolver::visit):
	New for AST::CallExpr and AST::MethodCallExpr.
	* resolve/rust-default-resolver.h
	(DefaultResolver::visit): Likewise.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2024-05-21 11:27:46 +00:00
jjasmine
9ff8ac9275 Remove useless cstddef header from rust-fmt
gcc/rust/ChangeLog:

	* ast/rust-fmt.h:  Remove useless cstddef header from rust-fmt
2024-05-21 09:55:11 +00:00
Pierre-Emmanuel Patry
06bc336010 Change lookup_ast_item's return type
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>
2024-05-17 15:28:30 +00:00
Pierre-Emmanuel Patry
f13cb854c0 Change lookup_visibility's return type
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>
2024-05-17 15:28:30 +00:00
Pierre-Emmanuel Patry
435f227c25 Change lookup_macro_invocation's return type
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>
2024-05-17 15:28:30 +00:00
Pierre-Emmanuel Patry
c3493829b7 Change lookup_macro_def return type
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>
2024-05-17 15:28:30 +00:00
Pierre-Emmanuel Patry
291068b42e Change lookup_canonical_path's return path
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>
2024-05-17 15:28:30 +00:00
Pierre-Emmanuel Patry
36518ef25d Change lookup_hir_pattern return type
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>
2024-05-17 15:28:30 +00:00
Pierre-Emmanuel Patry
e956f3a7bb Change lookup_hir_struct_field return type
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>
2024-05-17 15:28:30 +00:00
Pierre-Emmanuel Patry
1d8efec4f7 Change lookup_hir_self_param return type
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>
2024-05-17 15:28:30 +00:00
Pierre-Emmanuel Patry
b4927ee8b1 Change lookup_hir_param return type with optional
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>
2024-05-17 15:28:30 +00:00
Pierre-Emmanuel Patry
0e7cff81b2 Change lookup_hir_smt's return type with optional
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>
2024-05-17 15:28:30 +00:00
Pierre-Emmanuel Patry
1746979fc5 Change lookup_hir_type return type with an optional
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>
2024-05-17 15:28:30 +00:00
Pierre-Emmanuel Patry
1e6a3ee55e Change lookup_hir_generic_param return type
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>
2024-05-17 15:28:30 +00:00
Pierre-Emmanuel Patry
d1dad032de Change lookup_hir_path_expr_seg return type
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>
2024-05-17 15:28:30 +00:00
Pierre-Emmanuel Patry
478c227c86 Change lookup_hir_expr return type to optional
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>
2024-05-17 15:28:30 +00:00
Pierre-Emmanuel Patry
1fcb7198e4 Change lookup_hir_implitem return type
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>
2024-05-17 15:28:30 +00:00
Pierre-Emmanuel Patry
6f0e06c04f Change return type to optional in get_lang_item
Wrap the function's return type with an optional.

gcc/rust/ChangeLog:

	* typecheck/rust-autoderef.cc: Adapt calling code to new return type.
	* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit):
	Likewise.
	(TypeCheckExpr::resolve_operator_overload): Likewise.
	* typecheck/rust-tyty-bounds.cc (TypeBoundsProbe::assemble_builtin_candidate):
	Likewise.
	* typecheck/rust-tyty.cc (ClosureType::setup_fn_once_output): Likewise.
	* util/rust-hir-map.cc (Mappings::get_lang_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>
2024-05-17 15:28:30 +00:00
Pierre-Emmanuel Patry
395aab3787 Change lookup_module function return type
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>
2024-05-17 15:28:30 +00:00
Pierre-Emmanuel Patry
fa24d0d08e Change lookup_hir_extern_item return type
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>
2024-05-17 15:28:30 +00:00
Pierre-Emmanuel Patry
310081b7d6 Change return type of lookup trait defid functions.
Wrap the return type with an optional.

gcc/rust/ChangeLog:

	* backend/rust-compile-base.cc (HIRCompileBase::resolve_method_address):
	Update code around lookup return type.
	* typecheck/rust-tyty-bounds.cc (TypeCheckBase::get_predicate_from_bound):
	Likewise.
	* typecheck/rust-tyty.cc (ClosureType::setup_fn_once_output):
	Likewise.
	* util/rust-hir-map.cc (Mappings::insert_defid_mapping): Likewise.
	(Mappings::lookup_trait_item_defid): Update return type with an
	optional.
	(Mappings::get_lang_item): Likewise.
	* util/rust-hir-map.h: Update the functions prototype.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2024-05-17 15:28:30 +00:00
Pierre-Emmanuel Patry
a83bc198e1 Change lookup_local_defid return type to optional
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>
2024-05-17 15:28:30 +00:00
Pierre-Emmanuel Patry
d1f2064d64 Change return type of lookup_defid
Change the return type to an optional.

gcc/rust/ChangeLog:

	* backend/rust-compile-base.cc (HIRCompileBase::resolve_method_address):
	Change calling code to accomodate new return type.
	* checks/errors/privacy/rust-privacy-reporter.cc:
	Likewise.
	* typecheck/rust-hir-type-check-base.cc (TypeCheckBase::get_marker_predicate):
	Likewise.
	* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit):
	Likewise.
	* typecheck/rust-tyty-bounds.cc (TypeBoundsProbe::assemble_builtin_candidate):
	Likewise.
	* typecheck/rust-tyty.cc (ClosureType::setup_fn_once_output): Likewise.
	* util/rust-hir-map.cc (Mappings::lookup_defid): Change function's
	return type.
	* util/rust-hir-map.h: Update function's prototype.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2024-05-17 15:28:30 +00:00
Pierre-Emmanuel Patry
ade76488cb Change crate name retrieval function return types
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>
2024-05-17 15:28:30 +00:00
Pierre-Emmanuel Patry
dc06ff16b4 Change crate_num_to_nodeid return type
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>
2024-05-17 15:28:30 +00:00
Pierre-Emmanuel Patry
5f1b593393 Change return type of lookup_crate_name
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>
2024-05-17 15:28:30 +00:00
Pierre-Emmanuel Patry
1be4fa36f0 Change return type of lookup_impl_block_type
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>
2024-05-17 15:28:30 +00:00
Pierre-Emmanuel Patry
9af30ca752 Change return type for lookup_hir_impl_block
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>
2024-05-17 15:28:30 +00:00
Pierre-Emmanuel Patry
6dbaa5dbfb Change return type of lookup_hir_extern_block
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>
2024-05-17 15:28:30 +00:00
Pierre-Emmanuel Patry
dcd3837563 Change return type of lookup_hir_trait_item
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>
2024-05-17 15:28:30 +00:00
Pierre-Emmanuel Patry
69e1835807 Change return type for lookup_hir_item to optional
gcc/rust/ChangeLog:

	* backend/rust-compile-resolve-path.cc (HIRCompileBase::query_compile):
	Adapt function call to new return type.
	* backend/rust-mangle-v0.cc (v0_path): Likewise.
	* 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.
	(UnsafeChecker::check_function_attr): Likewise.
	* checks/lints/rust-lint-marklive.cc (MarkLive::go): Likewise.
	(MarkLive::visit): Likewise.
	* typecheck/rust-hir-trait-resolve.cc (TraitResolver::resolve_path_to_trait):
	Likewise.
	* typecheck/rust-type-util.cc (query_type): Likewise.
	* util/rust-hir-map.cc (Mappings::insert_hir_item): Likewise.
	(Mappings::lookup_hir_item): Change function return type to use
	optional.
	* util/rust-hir-map.h: Update function prototype.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2024-05-17 15:28:30 +00:00
Pierre-Emmanuel Patry
73f87d81c0 Change return type of resolve_nodeid_to_stmt
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>
2024-05-17 15:28:30 +00:00
Pierre-Emmanuel Patry
402d329819 Change lookup_hir_to_node return type to optional
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>
2024-05-17 15:28:30 +00:00
Pierre-Emmanuel Patry
6dff797adf Change lookup_node_to_hir return type to optional
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>
2024-05-17 15:28:30 +00:00
Owen Avery
c7687ef1f7 Visit constant items without expressions properly
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>
2024-05-16 10:55:42 +00:00
Owen Avery
1c52754ee1 Improve matching on non-enum ADTs
gcc/rust/ChangeLog:

	* backend/rust-compile-expr.cc
	(check_match_scrutinee): Add assertion.
	* backend/rust-compile-pattern.cc
	(CompilePatternCheckExpr::visit):
	Handle HIR::PathInExpression matching a non-enum.

gcc/testsuite/ChangeLog:

	* rust/compile/match-struct-path.rs: New test.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2024-05-16 09:10:48 +00:00
Nobel Singh
154ce770c6 Add testcases for handling struct as scrutinee for match expr
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>
2024-05-15 13:54:29 +00:00
Nobel Singh
9e45b86996 Handle structs as scrutinee for match expressions
gcc/rust/ChangeLog:

	* backend/rust-compile-expr.cc (check_match_scrutinee): Handle structs

Signed-off-by: Nobel Singh <nobel2073@gmail.com>
2024-05-15 13:54:29 +00:00
Owen Avery
add0e45fc9 Remove unused Context parameter for some backend methods
gcc/rust/ChangeLog:

	* backend/rust-compile-base.cc
	(HIRCompileBase::compile_function_body):
	Adjust unit_expression calls.
	(HIRCompileBase::unit_expression):
	Remove unused Context parameter.
	* backend/rust-compile-base.h
	(HIRCompileBase::unit_expression): Likewise.
	* backend/rust-compile-block.cc
	(CompileBlock::visit): Adjust unit_expression calls.
	* backend/rust-compile-expr.cc
	(CompileExpr::visit): Likewise.
	* backend/rust-compile-pattern.cc
	(CompilePatternLet::visit): Likewise.
	* backend/rust-compile-resolve-path.cc
	(ResolvePathRef::attempt_constructor_expression_lookup):
	Likewise.
	* backend/rust-compile-type.cc
	(TyTyResolveCompile::get_implicit_enumeral_node_type):
	Remove unused Context parameter.
	(TyTyResolveCompile::get_unit_type):
	Likewise.
	(TyTyResolveCompile::visit):
	Adjust get_implicit_enumeral_node_type and get_unit_type calls.
	* backend/rust-compile-type.h
	(TyTyResolveCompile::get_implicit_enumeral_node_type):
	Remove unused Context parameter.
	(TyTyResolveCompile::get_unit_type):
	Likewise.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2024-05-15 13:47:58 +00:00
Arthur Cohen
7680f97ee8 libformat_parser: Lower minimum Rust version to 1.49
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.
2024-05-15 09:18:41 +00:00
Pierre-Emmanuel Patry
8a7256676e Change singleton returned type to a reference
We do not need a raw pointer for this singleton,
nor we need having it on the heap through a
smart pointer.

gcc/rust/ChangeLog:

	* ast/rust-ast.h: Change dereference from a pointer to a reference
	accessor.
	* ast/rust-expr.h: Likewise.
	* ast/rust-item.h: Likewise.
	* ast/rust-macro.h: Likewise.
	* ast/rust-path.h: Likewise.
	* ast/rust-pattern.h: Likewise.
	* ast/rust-type.h: Likewise.
	* backend/rust-compile-base.cc (HIRCompileBase::resolve_method_address):
	Likewise.
	* backend/rust-compile-context.h: Likewise.
	* backend/rust-compile-expr.cc (CompileExpr::visit): Likewise.
	(CompileExpr::generate_closure_function): Likewise.
	* backend/rust-compile-extern.h: Likewise.
	* backend/rust-compile-implitem.cc (CompileTraitItem::visit): Likewise.
	* backend/rust-compile-intrinsic.cc (Intrinsics::compile): Likewise.
	* backend/rust-compile-item.cc (CompileItem::visit): Likewise.
	* backend/rust-compile-resolve-path.cc (ResolvePathRef::resolve):
	Likewise.
	(HIRCompileBase::query_compile): Likewise.
	* backend/rust-compile-type.cc (TyTyResolveCompile::visit): Likewise.
	(TyTyResolveCompile::create_dyn_obj_record): Likewise.
	* backend/rust-compile.cc (HIRCompileBase::coerce_to_dyn_object):
	Likewise.
	* backend/rust-mangle-v0.cc (v0_path): Likewise.
	(v0_mangle_item): Likewise.
	* checks/errors/borrowck/rust-borrow-checker.cc (BorrowChecker::go):
	Likewise.
	* checks/errors/privacy/rust-privacy-check.cc (Resolver::resolve):
	Likewise.
	* checks/errors/rust-const-checker.cc (ConstChecker::ConstChecker):
	Likewise.
	* checks/errors/rust-unsafe-checker.cc (UnsafeChecker::UnsafeChecker):
	Likewise.
	* checks/lints/rust-lint-marklive-base.h: Likewise.
	* checks/lints/rust-lint-marklive.cc (MarkLive::go): Likewise.
	(MarkLive::visit): Likewise.
	(MarkLive::visit_path_segment): Likewise.
	* checks/lints/rust-lint-marklive.h: Likewise.
	* checks/lints/rust-lint-scan-deadcode.h: Likewise.
	* expand/rust-macro-expand.cc (MacroExpander::expand_invoc): Likewise.
	* expand/rust-macro-expand.h (struct MacroExpander): Change mapping
	from pointer to a reference.
	* expand/rust-proc-macro.cc (BangProcMacro::BangProcMacro): Replace
	pointer accessor with reference accessor.
	(AttributeProcMacro::AttributeProcMacro): Likewise.
	(CustomDeriveProcMacro::CustomDeriveProcMacro): Likewise.
	* hir/rust-ast-lower-base.cc (ASTLoweringBase::lower_lifetime):
	Likewise.
	(ASTLoweringBase::lower_loop_label): Likewise.
	(ASTLoweringBase::lower_path_expr_seg): Likewise.
	(ASTLoweringBase::lower_self): Likewise.
	(ASTLoweringBase::handle_lang_item_attribute): Likewise.
	(ASTLoweringBase::lower_extern_block): Likewise.
	(ASTLoweringBase::lower_macro_definition): Likewise.
	* hir/rust-ast-lower-base.h: Likewise.
	* hir/rust-ast-lower-block.h: Likewise.
	* hir/rust-ast-lower-enumitem.h: Likewise.
	* hir/rust-ast-lower-expr.cc (ASTLoweringExpr::translate): Likewise.
	(ASTLoweringExpr::visit): Likewise.
	* hir/rust-ast-lower-extern.h: Likewise.
	* hir/rust-ast-lower-implitem.cc (ASTLowerImplItem::translate):
	Likewise.
	(ASTLowerImplItem::visit): Likewise.
	(ASTLowerTraitItem::translate): Likewise.
	(ASTLowerTraitItem::visit): Likewise.
	* hir/rust-ast-lower-item.cc (ASTLoweringItem::translate): Likewise.
	(ASTLoweringItem::visit): Likewise.
	(ASTLoweringSimplePath::lower): Likewise.
	* hir/rust-ast-lower-pattern.cc (ASTLoweringPattern::translate):
	Likewise.
	(ASTLoweringPattern::visit): Likewise.
	* hir/rust-ast-lower-stmt.cc (ASTLoweringStmt::translate): Likewise.
	(ASTLoweringStmt::visit): Likewise.
	* hir/rust-ast-lower-struct-field-expr.h: Likewise.
	* hir/rust-ast-lower-type.cc (ASTLowerTypePath::visit): Likewise.
	(ASTLowerQualifiedPathInType::visit): Likewise.
	(ASTLoweringType::translate): Likewise.
	(ASTLoweringType::visit): Likewise.
	(ASTLowerGenericParam::translate): Likewise.
	(ASTLowerGenericParam::visit): Likewise.
	(ASTLoweringTypeBounds::translate): Likewise.
	(ASTLoweringTypeBounds::visit): Likewise.
	(ASTLowerWhereClauseItem::translate): Likewise.
	(ASTLowerWhereClauseItem::visit): Likewise.
	* hir/rust-ast-lower.cc (ASTLowering::go): Likewise.
	(ASTLoweringBlock::visit): Likewise.
	(ASTLoweringIfBlock::visit): Likewise.
	(ASTLoweringIfLetBlock::visit): Likewise.
	(ASTLowerStructExprField::visit): Likewise.
	(ASTLoweringExprWithBlock::visit): Likewise.
	(ASTLowerPathInExpression::visit): Likewise.
	(ASTLoweringBase::lower_qual_path_type): Likewise.
	(ASTLowerQualPathInExpression::visit): Likewise.
	* metadata/rust-export-metadata.cc (ExportContext::emit_trait):
	Likewise.
	(ExportContext::emit_function): Likewise.
	(ExportContext::emit_macro): Likewise.
	(PublicInterface::PublicInterface): Likewise.
	(PublicInterface::expected_metadata_filename): Likewise.
	* metadata/rust-export-metadata.h: Likewise.
	* resolve/rust-ast-resolve-base.h: Likewise.
	* resolve/rust-ast-resolve-implitem.h: Likewise.
	* resolve/rust-ast-resolve-item.cc (ResolveTraitItems::visit):
	Likewise.
	(ResolveItem::visit): Likewise.
	(ResolveExternItem::visit): Likewise.
	* resolve/rust-ast-resolve-path.cc (ResolvePath::resolve_path):
	Likewise.
	* resolve/rust-ast-resolve-stmt.h: Likewise.
	* resolve/rust-ast-resolve-toplevel.h: Likewise.
	* resolve/rust-ast-resolve-type.cc (ResolveRelativeTypePath::go):
	Likewise.
	(ResolveTypeToCanonicalPath::visit): Likewise.
	* resolve/rust-ast-resolve-type.h: Likewise.
	* resolve/rust-ast-resolve.cc (NameResolution::NameResolution):
	Likewise.
	(NameResolution::go): Likewise.
	* resolve/rust-ast-resolve.h: Likewise.
	* resolve/rust-early-name-resolver-2.0.cc (Early::visit_attributes):
	Likewise.
	* resolve/rust-early-name-resolver.cc (EarlyNameResolver::EarlyNameResolver):
	Likewise.
	* resolve/rust-late-name-resolver-2.0.cc (next_node_id): Likewise.
	(next_hir_id): Likewise.
	* resolve/rust-name-resolution-context.cc (NameResolutionContext::NameResolutionContext):
	Likewise.
	* resolve/rust-name-resolver.cc (Resolver::Resolver): Likewise.
	(Resolver::generate_builtins): Likewise.
	(Resolver::setup_builtin): Likewise.
	* resolve/rust-name-resolver.h: Likewise.
	* resolve/rust-toplevel-name-resolver-2.0.cc (TopLevel::visit):
	Likewise.
	(TopLevel::handle_use_glob): Likewise.
	* rust-session-manager.cc (Session::get_instance): Likewise.
	(Session::handle_input_files): Likewise.
	(Session::handle_crate_name): Likewise.
	(Session::compile_crate): Likewise.
	(Session::load_extern_crate): Likewise.
	* rust-session-manager.h: Likewise.
	* typecheck/rust-autoderef.cc (Adjuster::try_unsize_type): Likewise.
	* typecheck/rust-coercion.cc (TypeCoercionRules::do_coercion):
	Likewise.
	(TypeCoercionRules::coerce_unsafe_ptr): Likewise.
	(TypeCoercionRules::coerce_borrowed_pointer): Likewise.
	(TypeCoercionRules::coerce_unsized): Likewise.
	* typecheck/rust-coercion.h: Likewise.
	* typecheck/rust-hir-dot-operator.cc (MethodResolver::select):
	Likewise.
	* typecheck/rust-hir-inherent-impl-overlap.h: Likewise.
	* typecheck/rust-hir-path-probe.cc (PathProbeType::process_enum_item_for_candiates):
	Likewise.
	(PathProbeType::process_impl_items_for_candidates): Likewise.
	(PathProbeImplTrait::process_trait_impl_items_for_candidates):
	Likewise.
	* typecheck/rust-hir-trait-resolve.cc (TraitResolver::resolve_path_to_trait):
	Likewise.
	(TraitItemReference::get_parent_trait_mappings): Likewise.
	* typecheck/rust-hir-type-check-base.cc (TypeCheckBase::resolve_literal):
	Likewise.
	(TypeCheckBase::get_marker_predicate): Likewise.
	* typecheck/rust-hir-type-check-base.h: Likewise.
	* typecheck/rust-hir-type-check-enumitem.cc (TypeCheckEnumItem::visit):
	Likewise.
	* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit):
	Likewise.
	(TypeCheckExpr::resolve_operator_overload): Likewise.
	(TypeCheckExpr::resolve_fn_trait_call): Likewise.
	* typecheck/rust-hir-type-check-implitem.cc (TypeCheckTopLevelExternItem::visit):
	Likewise.
	(TypeCheckImplItem::visit): Likewise.
	* typecheck/rust-hir-type-check-item.cc (TypeCheckItem::visit):
	Likewise.
	* typecheck/rust-hir-type-check-path.cc (TypeCheckExpr::resolve_root_path):
	Likewise.
	(TypeCheckExpr::resolve_segments): Likewise.
	* typecheck/rust-hir-type-check-pattern.cc (TypeCheckPattern::emit_pattern_size_error):
	Likewise.
	(ClosureParamInfer::Resolve): Likewise.
	* typecheck/rust-hir-type-check-struct.cc (TypeCheckStructExpr::resolve):
	Likewise.
	* typecheck/rust-hir-type-check-type.cc (TypeCheckType::visit): Likewise.
	(TypeCheckType::resolve_root_path): Likewise.
	(TypeResolveGenericParam::visit): Likewise.
	(ResolveWhereClauseItem::visit): Likewise.
	* typecheck/rust-hir-type-check.cc (TraitItemReference::get_type_from_fn):
	Likewise.
	* typecheck/rust-type-util.cc (query_type): Likewise.
	* typecheck/rust-typecheck-context.cc (TypeCheckContext::compute_inference_variables):
	Likewise.
	* typecheck/rust-tyty-bounds.cc (TypeBoundsProbe::scan): Likewise.
	(TypeBoundsProbe::assemble_builtin_candidate): Likewise.
	(TypeCheckBase::get_predicate_from_bound): Likewise.
	* typecheck/rust-tyty-call.cc (TypeCheckCallExpr::visit): Likewise.
	(TypeCheckMethodCallExpr::check): Likewise.
	* typecheck/rust-tyty-call.h: Likewise.
	* typecheck/rust-tyty-cmp.h: Likewise.
	* typecheck/rust-tyty-subst.cc (SubstitutionParamMapping::override_context):
	Likewise.
	(SubstitutionRef::monomorphize): Likewise.
	* typecheck/rust-tyty-util.cc (TyVar::get_implicit_infer_var):
	Likewise.
	(TyVar::monomorphized_clone): Likewise.
	(TyWithLocation::TyWithLocation): Likewise.
	* typecheck/rust-tyty.cc (BaseType::satisfies_bound): Likewise.
	(InferType::clone): Likewise.
	(ADTType::handle_substitions): Likewise.
	(TupleType::handle_substitions): Likewise.
	(FnType::handle_substitions): Likewise.
	(ClosureType::setup_fn_once_output): Likewise.
	(ArrayType::handle_substitions): Likewise.
	(SliceType::handle_substitions): Likewise.
	(ReferenceType::handle_substitions): Likewise.
	(PointerType::handle_substitions): Likewise.
	(ParamType::handle_substitions): Likewise.
	* typecheck/rust-tyty.h: Likewise.
	* typecheck/rust-unify.cc (UnifyRules::UnifyRules): Likewise.
	(UnifyRules::commit): Likewise.
	* util/rust-hir-map.cc: Change getter return type to a reference.
	* util/rust-hir-map.h: Update function's prototype.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2024-05-06 15:17:29 +00:00
Mael Cravero
3a31617b48 Remove unnecessary SIDE_EFFECTS/READONLY macros
Closes #2357

gcc/rust/ChangeLog:

	* rust-gcc.cc: remove unnecessary TREE_SIDE_EFFECTS and TREE_READONLY
	macros used in arithmetic overflow checks.

Signed-off-by: Mael Cravero <mael.cravero@embecosm.com>
2024-05-06 13:06:59 +00:00
Jakub Dupak
45d5c01fdb borrowck: Use std::ignore
gcc/rust/ChangeLog:

	* checks/errors/borrowck/rust-bir-builder-expr-stmt.cc
	(ExprStmtBuilder::visit): Use std::ignore.
2024-05-06 12:23:49 +00:00
Jakub Dupak
35e028f58c borrowck: Testsuite
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.
2024-05-06 12:23:49 +00:00
Jakub Dupak
a926ad27cd borrowck: Polonius error reporting
gcc/rust/ChangeLog:

	* checks/errors/borrowck/ffi-polonius/src/gccrs_ffi_generated.rs: Error reporting.
	* checks/errors/borrowck/ffi-polonius/src/lib.rs: Error reporting.
	* checks/errors/borrowck/polonius/rust-polonius-ffi.h (struct FactsView):
	Error reporting.
	(struct Output): Error reporting.
	* checks/errors/borrowck/polonius/rust-polonius.h (struct Facts): Error reporting.
	* checks/errors/borrowck/rust-borrow-checker.cc: Error reporting.

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2024-05-06 12:23:49 +00:00
Jakub Dupak
5f0db57567 borrowck: Link Polonius and run it
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>
2024-05-06 12:23:49 +00:00
Jakub Dupak
ab8b4cc388 borrowck: Build Polonius automatically
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>
2024-05-06 12:23:49 +00:00
Jakub Dupak
509c286cb0 borrowck: Polonius dump
gcc/rust/ChangeLog:

	* checks/errors/borrowck/polonius/rust-polonius.h (struct FullPoint):
	Polonius facts dump.
	(struct Facts): Polonius facts dump.
	* checks/errors/borrowck/rust-bir-dump.cc (Dump::go):
	Polonius facts dump.
	(Dump::visit): Polonius facts dump.
	(Dump::visit_place): Polonius facts dump.
	(Dump::visit_move_place): Polonius facts dump.
	(Dump::visit_scope): Polonius facts dump.
	* checks/errors/borrowck/rust-borrow-checker.cc (BorrowChecker::go): Polonius facts dump.

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2024-05-06 12:23:49 +00:00
Kushal Pal
3b9a0405f4 Removed obsolete objects
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>
2024-05-06 08:57:42 +00:00
Pierre-Emmanuel Patry
ba8ce7e66c Pin macos CI to version 13
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>
2024-04-30 13:24:38 +00:00
zhanghe9702
fa86c37a57 Remove redundant macro definition
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>
2024-04-23 10:45:50 +00:00
Pierre-Emmanuel Patry
5b6c982855 Add a test for inherent impl type name resolve
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>
2024-04-22 16:00:27 +00:00
Pierre-Emmanuel Patry
973e60a2be Visit type during resolution of inherent impl
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>
2024-04-22 16:00:27 +00:00
Thomas Schwinge
611d0bdc55 Rust: Move 'libformat_parser' build into libgrust
Addresses #2883.

	contrib/
	* gcc_update (files_and_dependencies): Update for
	'libformat_parser' in libgrust.
	gcc/rust/
	* Make-lang.in (LIBFORMAT_PARSER): Point to 'libformat_parser'
	build in libgrust.
	(%.toml:, $(LIBFORMAT_PARSER):): Remove.
	libgrust/
	* libformat_parser/Makefile.am: New.
	* Makefile.am [!TARGET_LIBRARY] (SUBDIRS): Add 'libformat_parser'.
	* configure.ac: Handle it.
	(TARGET_LIBRARY): New 'AM_CONDITIONAL'.
	* libformat_parser/Makefile.in: Generate.
	* Makefile.in: Regenerate.
	* configure: Likewise.
2024-04-16 07:46:13 +00:00
Thomas Schwinge
8dde956e18 Rust: Move 'libformat_parser' build into the GCC build directory
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.
2024-04-16 07:46:13 +00:00
Thomas Schwinge
34a70f4875 Rust: Don't cache 'libformat_parser.a'
gcc/rust/
	* Make-lang.in (LIBFORMAT_PARSER): Point to the actual build artifact.
	($(LIBFORMAT_PARSER)): Don't cache it.
2024-04-16 07:46:13 +00:00
Thomas Schwinge
e1c80b39a6 Inline 'gcc/rust/Make-lang.in:RUST_LIBDEPS'
gcc/rust/
	* Make-lang.in (RUST_LIBDEPS): Inline into all users.
2024-04-16 07:46:13 +00:00
Thomas Schwinge
fb9ff2f155 Add 'gcc/rust/Make-lang.in:LIBFORMAT_PARSER'
... to avoid verbatim repetition.

	gcc/rust/
	* Make-lang.in (LIBPROC_MACRO_INTERNAL): New.
	(RUST_LIBDEPS, crab1$(exeext), rust/libformat_parser.a): Use it.
2024-04-16 07:46:13 +00:00
Thomas Schwinge
00d5896b31 Add 'gcc/rust/Make-lang.in:LIBPROC_MACRO_INTERNAL'
... to avoid verbatim repetition.

	gcc/rust/
	* Make-lang.in (LIBPROC_MACRO_INTERNAL): New.
	(RUST_LIBDEPS, crab1$(exeext)): Use it.
2024-04-16 07:46:13 +00:00
Thomas Schwinge
1e97d748f4 Inline 'gcc/rust/Make-lang.in:RUST_LDFLAGS'
Unused.

	gcc/rust/
	* Make-lang.in (RUST_LDFLAGS): Inline into all users.
2024-04-16 07:46:13 +00:00
Thomas Schwinge
97759a56aa Remove 'libgrust/libproc_macro_internal' from 'gcc/rust/Make-lang.in:RUST_LDFLAGS'
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'.
2024-04-16 07:46:13 +00:00
Thomas Schwinge
9dda7062e0 Remove 'libgrust/librustc_format_parser' from 'gcc/rust/Make-lang.in:RUST_LDFLAGS'
That directory doesn't even exist.

	gcc/rust/
	* Make-lang.in (RUST_LDFLAGS): Remove
	'libgrust/librustc_format_parser'.
2024-04-16 07:46:13 +00:00
Arthur Cohen
a24871e1bd chore: Fix Remark CI
ChangeLog:

	* CONTRIBUTING.md: Fix invalid line length.
	* README.md: Likewise.
2024-04-12 21:04:59 +02:00
Arthur Cohen
2dff71f6fc rust: Add --offline flag to cargo when building Rust components.
gcc/rust/ChangeLog:

	* Make-lang.in: Add --offline flag to cargo invocation.
2024-04-10 13:24:42 +00:00
Arthur Cohen
b6e047e928 libgrust: Vendor Rust dependencies
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.
2024-04-10 13:24:42 +00:00
Thomas Schwinge
0201fa189f Merge commit '013b520529d5f1bddec27dd921eab5e917663693' into HEAD [#2944]
This resolves #2802 "Merge gcc/trunk into us".
2024-04-10 15:49:21 +02:00
Thomas Schwinge
013b520529 Adjust '.github/bors_log_expected_warnings' 2024-04-10 15:06:24 +02:00
Thomas Schwinge
c53dd85183 Merge commit 'f5a805d82902fe2d6e0a7af8c0e6519f9d25a8f3' into HEAD 2024-04-10 11:07:18 +02:00
Thomas Schwinge
30a67f581f Merge commit '767698ff6c8f07047ad90bef89f3dc4c4515f0df' into HEAD 2024-04-10 11:05:52 +02:00
Thomas Schwinge
17d389c4a3 Merge commit '8534cc772def8142379c0e72ab6392d40f3f60f6^' into HEAD 2024-04-10 11:05:29 +02:00
Thomas Schwinge
31fed215c2 Merge commit 'f0b1cf01782ba975cfda32800c91076df78058d6' into HEAD [#2857] 2024-04-10 11:02:28 +02:00
Thomas Schwinge
9575360bad Merge commit 'f0b1cf01782ba975cfda32800c91076df78058d6^' into HEAD 2024-04-10 11:01:28 +02:00
Thomas Schwinge
1cae91f78a Merge commit 'af3f0482367232d2d655e51bee382e98ddbfb117' into HEAD 2024-04-10 10:56:34 +02:00
Thomas Schwinge
1af2c40d75 Merge commit 'f89186f962421f6d972035fc4b4c20490e7b1c5b^' into HEAD 2024-04-10 10:55:56 +02:00
Thomas Schwinge
17ee9c68cb Merge commit '2a9881565c7b48d04cf891666a66a1a2e560bce8' into HEAD 2024-04-10 10:55:46 +02:00
Thomas Schwinge
e02c6e686b Merge commit 'ceed844b5284aeabbdfe25ccf099e7ebeeb14a9b^' into HEAD 2024-04-10 10:55:10 +02:00
Thomas Schwinge
0de2032ecf Merge commit '2341df1cb9b3681bfefe29207887b2b3dc271a95' into HEAD [#2801] 2024-04-10 10:52:58 +02:00
Thomas Schwinge
d1a0609b7e Merge commit '2341df1cb9b3681bfefe29207887b2b3dc271a95^' into HEAD 2024-04-10 10:51:48 +02:00
Thomas Schwinge
c9e59de17d Merge commit 'e621b174d7c622aa4b677a4c812e5061e311cc5c' into HEAD 2024-04-10 10:48:27 +02:00
Thomas Schwinge
d2bcecd7fd Merge commit 'a5258f3a11ab577835ef5e93be5cb65ec9e44132^' into HEAD 2024-04-10 10:45:56 +02:00
Thomas Schwinge
ca224bde29 Merge commit '4bd09ce06f50d266c992c984cc993384d5e6655e' into HEAD 2024-04-10 10:45:29 +02:00
Thomas Schwinge
4966574bdc Merge commit '7a6906c8d80e437a97c780370a8fec4e00561c7b' into HEAD [#2288] 2024-04-10 10:43:34 +02:00
Thomas Schwinge
041fef1b58 Merge commit 'fc59a3995cb46c190c0efb0431ad204e399975c4' into HEAD [#2183] 2024-04-10 10:34:02 +02:00
Thomas Schwinge
0ba53bfa81 Merge commit 'fc59a3995cb46c190c0efb0431ad204e399975c4^' into HEAD 2024-04-10 10:20:22 +02:00
Jasmine Tang
edd018d8c7 Fix grammar as pointed out by Marc
ChangeLog:

	* README.md (gccrs-workspace]): like-wise.
2024-04-09 15:18:08 +00:00
Jasmine Tang
19719f4f2d Add an alternative solution on MacOS
For #2937.
ChangeLog:

	* README.md (gccrs-workspace]): like-wise.
2024-04-09 15:18:08 +00:00
Jakub Dupak
ff196e451c borrowck: Bump copyright notice
gcc/rust/ChangeLog:

	* checks/errors/borrowck/ffi-polonius/src/gccrs_ffi.rs: Bump copyright.
	* checks/errors/borrowck/ffi-polonius/src/lib.rs: Bump copyright.
	* checks/errors/borrowck/polonius/rust-polonius-ffi.h: Bump copyright.
	* checks/errors/borrowck/polonius/rust-polonius.h: Bump copyright.
	* checks/errors/borrowck/rust-bir-dump.cc: Bump copyright.
	* checks/errors/borrowck/rust-bir-fact-collector.h: Bump copyright.
	* checks/errors/borrowck/rust-bir-free-region.h: Bump copyright.

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2024-04-04 16:21:10 +00:00
Jakub Dupak
c90a9ada24 borrowck: Remove block braces to satisfy GNU style
gcc/rust/ChangeLog:

	* checks/errors/borrowck/rust-bir-dump.cc (renumber_places):
	Remove unecessary braces.
	(Dump::go): Remove unecessary braces.
	(Dump::visit): Remove unecessary braces.
	(Dump::visit_scope): Remove unecessary braces.
	* checks/errors/borrowck/rust-bir-fact-collector.h (class FactCollector):
	Remove unecessary braces.
	(points): Remove unecessary braces.
	* checks/errors/borrowck/rust-bir-free-region.h: Remove unecessary braces.
	* checks/errors/borrowck/rust-bir-place.h: Remove unecessary braces.
	* checks/errors/borrowck/rust-borrow-checker.cc (BorrowChecker::go):
	Remove unecessary braces.
	* checks/errors/borrowck/rust-function-collector.h: Remove unecessary braces.

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2024-04-04 16:21:10 +00:00
Jakub Dupak
74745b1e35 borrowck: Fact collector
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>
2024-04-04 16:21:10 +00:00
Jakub Dupak
da3a8fca37 borrowck: Regions in BIR
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>
2024-04-04 16:21:10 +00:00
Jakub Dupak
a019aa9fbd borrowck: extract regions from types using VA
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>
2024-04-04 16:21:10 +00:00
Jakub Dupak
b783c3ce70 borrowck: Free region representation
gcc/rust/ChangeLog:

	* checks/errors/borrowck/rust-bir-free-region.h: New file.

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2024-04-04 16:21:10 +00:00
Jakub Dupak
28d1c14a53 borrowck: Polonius FFI
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>
2024-04-04 16:21:10 +00:00
Jakub Dupak
42ec29cacf borrowck: BIR: make BIR visitor const
gcc/rust/ChangeLog:

	* checks/errors/borrowck/rust-bir-dump.cc (Dump::visit): const
	visitor
	* checks/errors/borrowck/rust-bir-dump.h: const visitor
	* checks/errors/borrowck/rust-bir-visitor.h: const visitor
	* checks/errors/borrowck/rust-bir.h: const getter

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2024-04-04 16:21:10 +00:00
Jakub Dupak
400324882a borrowck: BIR: emit moves
gcc/rust/ChangeLog:

	* checks/errors/borrowck/rust-bir-builder-expr-stmt.cc (ExprStmtBuilder::visit): Emit moves.
	* checks/errors/borrowck/rust-bir-builder-internal.h: Emit moves.
	* checks/errors/borrowck/rust-bir-builder-lazyboolexpr.h: Emit moves.
	* checks/errors/borrowck/rust-bir-dump.cc (Dump::visit_move_place): Emit moves.
	(Dump::visit): Emit moves.
	* checks/errors/borrowck/rust-bir-place.h (struct Place): Emit moves.
	* checks/errors/borrowck/rust-bir-visitor.h: Emit moves.
	* checks/errors/borrowck/rust-bir.h (enum class): Emit moves.
	(class AbstractExpr): Emit moves.
	(BasicBlock::is_terminated): Emit moves.

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2024-04-04 16:21:10 +00:00
Jakub Dupak
de18440f92 borrowck: BIR: scope handling
gcc/rust/ChangeLog:

	* checks/errors/borrowck/rust-bir-builder-expr-stmt.cc (ExprStmtBuilder::setup_loop):
	Loop handling.
	(ExprStmtBuilder::visit): Handle scopes.
	* checks/errors/borrowck/rust-bir-builder-internal.h (struct BuilderContext):
	Handle scopes.
	* checks/errors/borrowck/rust-bir-dump.cc (Dump::go): Dump scopes.
	(Dump::visit): Add scopes dump.
	(Dump::indent): Add indentation logic.
	(Dump::visit_scope): Dump scope.
	* checks/errors/borrowck/rust-bir-dump.h: Dump methods.
	* checks/errors/borrowck/rust-bir-place.h (std::numeric_limits::max): Scope constants.
	(struct Scope): Scope representation.
	(class PlaceDB): Scope tracking.

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2024-04-04 16:21:10 +00:00
Jakub Dupak
e023b08672 borrowck: BIR: Place tree traverse API
gcc/rust/ChangeLog:

	* checks/errors/borrowck/rust-bir-place.h:
	Create place tree traverse API.

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2024-04-04 16:21:10 +00:00
Jakub Dupak
ba7e9a78f6 borrowck: BIR: use callable API
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>
2024-04-04 16:21:10 +00:00
Jakub Dupak
02d788d14c borrowck: Unify BIR terminilogy (node->statement)
gcc/rust/ChangeLog:

	* checks/errors/borrowck/bir-design-notes.md (nodes): Rename node to statement.
	(Nodes): Rename node to statement.
	* checks/errors/borrowck/rust-bir-builder-expr-stmt.cc (ExprStmtBuilder::visit):
	Rename node to statement.
	* checks/errors/borrowck/rust-bir-builder-internal.h: Rename node to statement.
	* checks/errors/borrowck/rust-bir-builder.h: Rename node to statement.
	* checks/errors/borrowck/rust-bir-dump.cc (Dump::go): Rename node to statement.
	(Dump::visit): Rename node to statement.
	* checks/errors/borrowck/rust-bir-dump.h (class Dump): Rename node to statement.
	* checks/errors/borrowck/rust-bir-visitor.h (class Node): Rename node to statement.
	(class Statement): Rename node to statement.
	* checks/errors/borrowck/rust-bir.h (class Node): Rename node to statement.
	(class Statement): Rename node to statement.
	(class AbstractExpr): Rename node to statement.
	(struct Function): Rename node to statement.
	(struct BasicBlock): Rename node to statement.

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2024-04-04 16:21:10 +00:00
Jakub Dupak
e06d74b8bf borrowck: Use rust-system.h
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>
2024-04-04 16:21:10 +00:00
Arthur Cohen
fbf35de5dc unify: Always coerce ! to the target type.
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.
2024-04-03 19:39:19 +00:00
Arthur Cohen
d9f7604e8e raw-strings: Remove dg-excess-error directive
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.
2024-04-03 19:39:08 +00:00
Owen Avery
e36c3ece68 Improve parsing of raw string literals
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>
2024-03-28 11:23:31 +00:00
Owen Avery
01092b8391 Avoid parsing const unsafe/extern functions as async
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>
2024-03-27 12:38:45 +00:00
Owen Avery
fd621e1133 Recognize unstable as a builtin attribute
gcc/rust/ChangeLog:

	* util/rust-attribute-values.h
	(Attributes::UNSTABLE): New.
	* util/rust-attributes.cc
	(__definitions): Add Attributes::UNSTABLE.

gcc/testsuite/ChangeLog:

	* rust/compile/unstable-fn.rs: New test.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2024-03-27 10:57:40 +00:00
Owen Avery
581c430918 Recognize rustc_deprecated as a builtin attribute
gcc/rust/ChangeLog:

	* util/rust-attribute-values.h
	(Attributes::RUSTC_DEPRECATED): New.
	* util/rust-attributes.cc
	(__definitions): Add Attributes::RUSTC_DEPRECATED.

gcc/testsuite/ChangeLog:

	* rust/compile/deprecated-fn.rs: New test.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2024-03-27 10:57:30 +00:00
Owen Avery
67928be5b0 Improve parsing of raw byte string literals
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>
2024-03-27 10:56:04 +00:00
Pierre-Emmanuel Patry
65f283df77 Change dfs function return type to support gcc 4.8
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>
2024-03-26 17:35:02 +00:00
Pierre-Emmanuel Patry
2ac4591650 Add globbing name resolution 2.0 test
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>
2024-03-26 17:35:02 +00:00
Arthur Cohen
db7d499157 nr2.0: Add new test cases.
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.
2024-03-26 17:35:02 +00:00
Arthur Cohen
e1064ca147 compile: resolve-path-ref: properly resolve nodeId with nr2.0
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.
2024-03-26 17:35:02 +00:00
Pierre-Emmanuel Patry
a8d1604cb3 Fix use rebind name resolution.
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>
2024-03-26 17:35:02 +00:00
Pierre-Emmanuel Patry
15a37afd98 Add mappings for struct base and struct fields
Definition/usage mapping during name resolution was missing.

gcc/rust/ChangeLog:

	* resolve/rust-late-name-resolver-2.0.cc (Late::visit): Add mapping
	implementation.
	* resolve/rust-late-name-resolver-2.0.h: Add function visitor prototype
	override.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2024-03-26 17:35:02 +00:00
Pierre-Emmanuel Patry
7697c1e9f5 Fix quoted string format
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>
2024-03-26 17:35:02 +00:00
Pierre-Emmanuel Patry
a63f0ac77e Prevent getting immutable context with classic nr
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>
2024-03-26 17:35:02 +00:00
Pierre-Emmanuel Patry
0874163bbf Update assignment operator with cratenum
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>
2024-03-26 17:35:02 +00:00
Pierre-Emmanuel Patry
f95ca338ec Reinject Self parameter in new resolver
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>
2024-03-26 17:35:02 +00:00
Pierre-Emmanuel Patry
4d64d55f5a Use new name resolver to compile constant items
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>
2024-03-26 17:35:02 +00:00
Pierre-Emmanuel Patry
c14e44a53c Remove unsafe block empty visit function
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>
2024-03-26 17:35:02 +00:00
Pierre-Emmanuel Patry
2ad57d7229 Remove extern block scoping
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>
2024-03-26 17:35:02 +00:00
Pierre-Emmanuel Patry
b0f27e8d81 Add constant identifiers to the value namespace
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>
2024-03-26 17:35:02 +00:00
Pierre-Emmanuel Patry
01f3f7b846 Struct are types, not values
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>
2024-03-26 17:35:02 +00:00
Pierre-Emmanuel Patry
08a6f1a118 Change enum namespace from value to type
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>
2024-03-26 17:35:02 +00:00
Pierre-Emmanuel Patry
26bbc73e76 Add tuple struct to the type namespace
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>
2024-03-26 17:35:02 +00:00
Pierre-Emmanuel Patry
e19483da43 Unit struct constructor shall be resolved
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>
2024-03-26 17:35:02 +00:00
Pierre-Emmanuel Patry
7bd829ea8c Values shall be inserted in the value namespace
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>
2024-03-26 17:35:02 +00:00
Pierre-Emmanuel Patry
82c7199a15 Raw pointer type visitor didn't require overload
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>
2024-03-26 17:35:02 +00:00
Pierre-Emmanuel Patry
ea376da532 Visit constant item type in default resolver
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>
2024-03-26 17:35:02 +00:00
Pierre-Emmanuel Patry
e84d67febe Visit function return type in default resolver
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>
2024-03-26 17:35:02 +00:00
Pierre-Emmanuel Patry
124d56a328 Change error message to match test
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>
2024-03-26 17:35:02 +00:00
Pierre-Emmanuel Patry
4c40ba4bb2 Add tuple struct constructor to value namespace
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>
2024-03-26 17:35:02 +00:00
Pierre-Emmanuel Patry
6b1d14b72e Add support for ambiguous use declarations
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>
2024-03-26 17:35:02 +00:00
Pierre-Emmanuel Patry
ac867c000d Make globbing definition shadowable by default
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>
2024-03-26 17:35:02 +00:00
Pierre-Emmanuel Patry
8c771ad54e Add call to globbing visitor
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>
2024-03-26 17:35:02 +00:00
Pierre-Emmanuel Patry
1230910d4f Shape up name resolver for normal direct calls
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>
2024-03-26 17:35:02 +00:00
Pierre-Emmanuel Patry
f8a6a62409 Add name resolution for on globbing use decl
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>
2024-03-26 17:35:02 +00:00
Pierre-Emmanuel Patry
c9ac90ba4f Add modules to type namespace
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>
2024-03-26 17:35:02 +00:00
Arthur Cohen
5f117eec55 late: Add bool builtin type
gcc/rust/ChangeLog:

	* resolve/rust-late-name-resolver-2.0.cc (Late::setup_builtin_types):
	Setup bool as builtin type.
2024-03-26 17:35:02 +00:00
Pierre-Emmanuel Patry
f88db85c02 Prevent error emission on resolver reentry
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>
2024-03-26 17:35:02 +00:00
Pierre-Emmanuel Patry
73901b2b89 Change error message on unresolved import
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>
2024-03-26 17:35:02 +00:00
Pierre-Emmanuel Patry
8a5a1b4d61 Emit error on identical use declarations
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>
2024-03-26 17:35:02 +00:00
Pierre-Emmanuel Patry
6d4c2c9f5d Fix duplicate detection
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>
2024-03-26 17:35:02 +00:00
Arthur Cohen
a62e1c6002 late: Setup builtin types properly, change Rib API
gcc/rust/ChangeLog:

	* resolve/rust-forever-stack.hxx: Start using Rib::Definition for
	shadowable information.
	* resolve/rust-late-name-resolver-2.0.cc (next_node_id): New.
	(next_hir_id): New.
	(Late::setup_builtin_types): Improve builtin type setup.
	* resolve/rust-rib.cc (Rib::Definition::Definition): New constructor.
	(Rib::Definition::Shadowable): Likewise.
	(Rib::Definition::NonShadowable): Likewise.
	(Rib::Rib): Fix general constructor.
	(Rib::insert): Use Definition class.
	(Rib::get): Likewise.
	* resolve/rust-rib.h: New Definition class, new prototypes.
2024-03-26 17:35:02 +00:00
Arthur Cohen
81f2edc5d1 nr2.0: Start using newtype pattern for Usage and Declaration
gcc/rust/ChangeLog:

	* resolve/rust-name-resolution-context.cc (NameResolutionContext::map_usage):
	Use newtype pattern.
	(NameResolutionContext::lookup): Likewise.
	* resolve/rust-name-resolution-context.h (class Usage): New class.
	(class Definition): Likewise.
	* resolve/rust-late-name-resolver-2.0.cc (Late::visit): Create instances
	of Usage and Definition.
2024-03-26 17:35:02 +00:00
Arthur Cohen
fd2ec3a52b backend: Use new name resolver where necessary
gcc/rust/ChangeLog:

	* backend/rust-compile-base.cc: Use new ImmutableNrCtx.
	* backend/rust-compile-context.h: Likewise.
	* backend/rust-compile-expr.cc: Likewise.
	* backend/rust-compile-item.cc: Likewise.
2024-03-26 17:35:02 +00:00
Arthur Cohen
a8b5f28aec typecheck: Start using nr2.0 properly
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.
2024-03-26 17:35:02 +00:00
Arthur Cohen
77a6a631b4 nr2.0: Add lookup of resolved nodes.
gcc/rust/ChangeLog:

	* resolve/rust-name-resolution-context.cc (NameResolutionContext::lookup):
	Add lookup function.
	* resolve/rust-name-resolution-context.h: Include mappings and optional.
2024-03-26 17:35:02 +00:00
Arthur Cohen
3f04e82780 session manager: Init Immutable name resolver.
gcc/rust/ChangeLog:

	* rust-session-manager.cc (Session::compile_crate): Create an immutable
	view of the name resolution context.
2024-03-26 17:35:02 +00:00
Arthur Cohen
111c4f0101 session-manager: Dump name resolution pass.
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.
2024-03-26 17:35:02 +00:00
Arthur Cohen
b281eb02d4 sesh: Add late name resolution 2.0
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.
2024-03-26 17:35:02 +00:00
Arthur Cohen
3e3f5c6602 nr2.0: Add new ImmutableNameResolutionCtx class.
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.
2024-03-26 17:35:02 +00:00
Thomas Schwinge
d74728eaed Merge commit 'f3f2065910a02b0099d3d5f2ad3389d0e479c782' into HEAD [#2926] 2024-03-25 08:19:46 +01:00
Thomas Schwinge
f3f2065910 Merge commit '2f334bb12e3ba947714771408b9d49d398abb5df' into HEAD 2024-03-24 23:37:24 +01:00
Thomas Schwinge
8c40edc1a2 Adjust '.github/bors_log_expected_warnings' 2024-03-24 23:25:31 +01:00
Thomas Schwinge
1cb7e9000e Placate clang-format re 'gcc/rust/lex/rust-lex.cc'
Reformat the upstream GCC commit 61644aea34
"gccrs: tokenize Unicode identifiers" change to 'gcc/rust/lex/rust-lex.cc'
to clang-format's liking.

	gcc/rust/
	* lex/rust-lex.cc (is_identifier_start): Placate clang-format.
2024-03-24 23:09:08 +01:00
Thomas Schwinge
8f9b47500d Merge commit '9f7afa99c67f039e43019ebd08d14a7f01e2d89c' into HEAD 2024-03-22 10:07:29 +01:00
Thomas Schwinge
b177dc6b03 Merge commit 'cde6f1085b7027f6a42fdb71c786d422606a8765' into HEAD 2024-03-22 09:58:10 +01:00
Thomas Schwinge
000c6d0a37 Merge commit 'cde6f1085b7027f6a42fdb71c786d422606a8765^' into HEAD 2024-03-22 09:58:02 +01:00
Thomas Schwinge
59bc3e7924 Merge commit '00dea7e8c41b672730d6e2c891b6012a83d8842c' into HEAD [#2284] 2024-03-22 09:55:35 +01:00
Thomas Schwinge
4c445f0015 Merge commit '00dea7e8c41b672730d6e2c891b6012a83d8842c^' into HEAD 2024-03-22 09:49:13 +01:00
Thomas Schwinge
83c5b0292a Merge commit 'a945c346f57ba40fc80c14ac59be0d43624e559d' into HEAD [#2842] 2024-03-22 09:48:31 +01:00
Thomas Schwinge
884c2b766e Merge commit 'a945c346f57ba40fc80c14ac59be0d43624e559d^' into HEAD 2024-03-22 09:26:05 +01:00
Thomas Schwinge
a8514ae513 Merge commit '725fb3595622a4ad8cd078a42fab1c395cbf90cb' into HEAD [#1913, #2288] 2024-03-22 01:22:07 +01:00
Thomas Schwinge
f96582527e Merge commit 'f37c55c14bc1176ef9a15fe584fb6d1bf2e6162f' into HEAD [#1913] 2024-03-22 01:04:40 +01:00
Thomas Schwinge
af14cc24cb Merge commit 'f37c55c14bc1176ef9a15fe584fb6d1bf2e6162f^' into HEAD 2024-03-22 00:30:43 +01:00
Thomas Schwinge
77d55deb8b Merge commit 'e4f0eb725d836ef0eec780cbb9e7be0d31c6fe8b' into HEAD [#2690, #2692, #2853] 2024-03-22 00:25:42 +01:00
jjasmine
2f334bb12e Split up rust-macro-builtins.cc
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.
2024-03-21 23:07:03 +00:00
Guillaume Gomez
b4c3a6ca4f Fix typo
gcc/rust/ChangeLog:

	* expand/rust-derive.cc (DeriveVisitor::derive): Fix typo
2024-03-21 16:08:01 +00:00
zhanghe9702
f568f3b3e2 fixed README.md , dump ast using correct option
ChangeLog:

	* README.md: remove error dump option.

Signed-off-by: Zhang He <zhanghe9702@163.com>
2024-03-21 14:59:57 +00:00
jjasmine
aa395781af Store visibility properly in ExternalTypeItem
Fix issue 2897

gcc/rust/ChangeLog:

	* hir/rust-ast-lower-extern.h: Add translate_visiblity
	* hir/tree/rust-hir-item.h: Fix constructor of ExternalTypeItem
2024-03-21 14:52:42 +00:00
Jakub Dupak
ac45444926 TyTy: Collect variance info from types
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>
2024-03-21 11:35:06 +00:00
Jakub Dupak
4a54a8b5ee TyTy: Variance analysis module
gcc/rust/ChangeLog:

	* Make-lang.in: Add new .cc file.
	* rust-session-manager.cc (Session::compile_crate): Run
	analysis.
	* typecheck/rust-tyty-variance-analysis-private.h: New file.
	* typecheck/rust-tyty-variance-analysis.cc: New file.
	* typecheck/rust-tyty-variance-analysis.h: New file.
	* typecheck/rust-typecheck-context.cc
	(TypeCheckContext::get_variance_analysis_ctx):
	Variance analysis context.
	* typecheck/rust-hir-type-check.h (TypeCheckItem::visit):
	Variance analysis context.

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2024-03-21 11:35:06 +00:00
Jakub Dupak
fdba6c5d00 TyTy: add common SubstitutionRef API
gcc/rust/ChangeLog:

	* typecheck/rust-tyty-subst.cc (SubstitutionRef::get_arg_at):
	Add unified API.

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2024-03-21 11:35:06 +00:00
Arthur Cohen
677a8866e0 format-args: Only pass the format string to the parser.
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.
2024-03-19 17:37:38 +00:00
Arthur Cohen
b4de854a53 format-args: Add basic test case
gcc/testsuite/ChangeLog:

	* rust/compile/format_args_basic_expansion.rs: New test.
2024-03-19 17:37:38 +00:00
Arthur Cohen
36aeecfb22 format-args: Add basic expansion of unnamed Display::fmt arguments.
gcc/rust/ChangeLog:

	* ast/rust-ast-builder.h: Rename AST::AstBuilder -> AST::Builder
	* ast/rust-ast-builder.cc: Likewise.
	* expand/rust-derive.cc: Use new AST::Builder name.
	* expand/rust-derive.h: Likewise.
	* ast/rust-builtin-ast-nodes.h: Add required getters.
	* expand/rust-expand-format-args.cc (format_arg): New.
	(get_trait_name): New.
	(expand_format_args): Properly expand basic format_args!() invocations.
	* expand/rust-expand-format-args.h (expand_format_args): Fix signature.
	* expand/rust-macro-builtins.cc (MacroBuiltin::format_args_handler):
	Call into expand_format_args().
2024-03-19 17:37:38 +00:00
Arthur Cohen
246b6316c0 format-args: Start storing string in Rust memory
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.
2024-03-19 17:37:38 +00:00
Arthur Cohen
da10bf56cf format-args: Add base for expanding FormatArgs nodes
gcc/rust/ChangeLog:

	* Make-lang.in: Add new object.
	* hir/rust-ast-lower-expr.cc (ASTLoweringExpr::visit): Remove calls to
	FormatArgsLowering.
	* expand/rust-expand-format-args.cc: New file.
	* expand/rust-expand-format-args.h: New file.
2024-03-19 17:37:38 +00:00
Thomas Schwinge
6eba95e992 Merge commit 'a857ec6aada08d8c334c389c7b682198d749b6c9^' into HEAD 2024-03-19 16:47:48 +01:00
Thomas Schwinge
136c428abb Merge commit '8fc4e6c397e1ce64bec6f9fed148950821cc79e7' into HEAD
Accordingly also adjust #2086 "break rust 💥" code, to avoid:

    [...]/source-gcc/gcc/rust/resolve/rust-ast-resolve-expr.cc: In member function ‘virtual void Rust::Resolver::ResolveExpr::visit(Rust::AST::IdentifierExpr&)’:
    [...]/source-gcc/gcc/rust/resolve/rust-ast-resolve-expr.cc:164:42: error: invalid conversion from ‘void (*)(diagnostic_context*, diagnostic_info*, diagnostic_t)’ to ‘diagnostic_finalizer_fn’ {aka ‘void (*)(diagnostic_context*, con
iagnostic_info*, diagnostic_t)’} [-fpermissive]
      164 |       diagnostic_finalizer (global_dc) = funny_ice_finalizer;
          |                                          ^~~~~~~~~~~~~~~~~~~
          |                                          |
          |                                          void (*)(diagnostic_context*, diagnostic_info*, diagnostic_t)
2024-03-19 16:46:40 +01:00
Thomas Schwinge
d374f52a69 Merge commit '8fc4e6c397e1ce64bec6f9fed148950821cc79e7^' into HEAD 2024-03-19 16:45:27 +01:00
Thomas Schwinge
f4530cab2c Merge commit 'f7884f7673444b8a2c10ea0981d480f2e82dd16a'; commit 'adb56ef014effb17af27ab7baf0d87bc8bc48a0c' into HEAD [#2916]
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
    [...]
2024-03-19 16:42:45 +01:00
Thomas Schwinge
e8c161211f Merge commit 'f7884f7673444b8a2c10ea0981d480f2e82dd16a^' into HEAD 2024-03-19 16:37:35 +01:00
Arthur Cohen
b85dc7014c macro: Use MacroInvocation's node_id in ExternalItem constructor.
gcc/rust/ChangeLog:

	* ast/rust-macro.h: Use proper node id instead of the one in the base
	Expr class - which is uninitialized.
2024-03-19 15:28:36 +00:00
Arthur Cohen
f4379ba00a ci: Install Rust directly from rustup instead of apt
ChangeLog:

	* .github/workflows/ccpp.yml: Install Rust manually.
2024-03-19 15:25:31 +00:00
Arthur Cohen
adb56ef014 macro: Use MacroInvocation's node_id in ExternalItem constructor.
gcc/rust/ChangeLog:

	* ast/rust-macro.h: Use proper node id instead of the one in the base
	Expr class - which is uninitialized.
2024-03-19 13:15:24 +01:00
Richard Biener
ebc1fc6853 tree-optimization/112653 - PTA and return
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)
2024-03-18 13:08:56 +01:00
Martin Jambor
70a5ad7506 sra: SRA of non-escaped aggregates passed by reference to calls
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)
2024-03-18 13:08:37 +01:00
Thomas Schwinge
f0fdff9b6d Merge commit '56ca59a03150cf44cea340f58967c990ed6bf43c' into HEAD 2024-03-17 00:10:10 +01:00
Thomas Schwinge
b3a1373731 Merge commit '56ca59a03150cf44cea340f58967c990ed6bf43c^' into HEAD 2024-03-17 00:10:04 +01:00
Thomas Schwinge
0a9e0719ea Merge commit 'db50aea62595452db12565186cb520728540d987' into HEAD 2024-03-17 00:06:54 +01:00
Thomas Schwinge
fc5b92bc61 Merge commit 'db50aea62595452db12565186cb520728540d987^' into HEAD 2024-03-16 23:57:22 +01:00
Thomas Schwinge
79be34b6dc Merge commit '4968e4844a3ce30143ae2e267895c418f5c636a1' into HEAD 2024-03-16 23:55:02 +01:00
Thomas Schwinge
9d6e836c2c Merge commit '28064d6430f3fa71e79d11ac9d4bf3e6adf52145' into HEAD 2024-03-16 23:54:33 +01:00
Thomas Schwinge
28064d6430 Revert "Add files to discourage submissions of PRs to the GitHub mirror."
This is not applicable for GCC/Rust, which does use GitHub.

This reverts commit 2b9778c8d9.
2024-03-16 23:32:57 +01:00
Thomas Schwinge
595789c2c3 Merge commit '2b9778c8d9d33174de63716b74b2f114d700e104^' into HEAD 2024-03-16 23:32:07 +01:00
Thomas Schwinge
e86610f33d Merge commit '6a6d3817afa02bbcd2388c8e005da6faf88932f1' into HEAD [#2714] 2024-03-16 23:10:42 +01:00
Thomas Schwinge
155817d33e Merge commit '6a6d3817afa02bbcd2388c8e005da6faf88932f1^' into HEAD 2024-03-16 23:03:21 +01:00
Pierre-Emmanuel Patry
75dc00584e Replace unique_ptr references with references
This kind of double indirection is pointless and prone to error. This
commit change the api of all getters from the AST to use references
directly instead of references to unique pointers.

gcc/rust/ChangeLog:

	* ast/rust-ast-collector.cc (TokenCollector::visit): Remove reference
	to unique pointer and replace it with a direct reference to the wrapped
	data.
	* ast/rust-ast.cc (VariadicParam::as_string): Likewise.
	(BlockExpr::normalize_tail_expr): Likewise.
	* ast/rust-expr.h: Likewise and add pointer getter in order to allow
	pointer reseat.
	* ast/rust-item.h: Likewise and add pointer getter for reseat.
	* ast/rust-path.h: Likewise.
	* ast/rust-pattern.h: Likewise.
	* ast/rust-stmt.h: Likewise.
	* ast/rust-type.h: Likewise.
	* expand/rust-cfg-strip.cc (CfgStrip::maybe_strip_struct_fields):
	Remove references to unique pointers and replace it with direct
	references to the wrapped object.
	(CfgStrip::maybe_strip_tuple_fields): Likewise.
	(CfgStrip::maybe_strip_generic_args): Likewise.
	(CfgStrip::maybe_strip_qualified_path_type): Likewise.
	(CfgStrip::visit): Likewise.
	* expand/rust-expand-visitor.cc (ExpandVisitor::maybe_expand_expr):
	Likewise.
	(ExpandVisitor::maybe_expand_type): Likewise.
	(ExpandVisitor::visit): Likewise.
	* expand/rust-expand-visitor.h: Likewise.
	* hir/rust-ast-lower-base.cc (ASTLoweringBase::lower_binding):
	Likewise.
	(ASTLoweringBase::lower_generic_args): Likewise.
	(ASTLoweringBase::lower_self): Likewise.
	(ASTLoweringBase::lower_type_no_bounds): Likewise.
	(ASTLoweringBase::lower_bound): Likewise.
	(ASTLoweringBase::lower_range_pattern_bound): Likewise.
	* hir/rust-ast-lower-base.h: Likewise.
	* hir/rust-ast-lower-block.h: Likewise.
	* hir/rust-ast-lower-enumitem.h: Likewise.
	* hir/rust-ast-lower-expr.cc (ASTLoweringExpr::translate): Likewise.
	(ASTLoweringExpr::visit): Likewise.
	* hir/rust-ast-lower-expr.h: Likewise.
	* hir/rust-ast-lower-extern.h: Likewise.
	* hir/rust-ast-lower-implitem.cc (ASTLowerImplItem::translate):
	Likewise.
	(ASTLowerImplItem::visit): Likewise.
	(ASTLowerTraitItem::translate): Likewise.
	(ASTLowerTraitItem::visit): Likewise.
	* hir/rust-ast-lower-implitem.h: Likewise.
	* hir/rust-ast-lower-item.cc (ASTLoweringItem::translate): Likewise.
	(ASTLoweringItem::visit): Likewise.
	* hir/rust-ast-lower-item.h: Likewise.
	* hir/rust-ast-lower-pattern.cc (ASTLoweringPattern::translate):
	Likewise.
	(ASTLoweringPattern::visit): Likewise.
	* hir/rust-ast-lower-pattern.h: Likewise.
	* hir/rust-ast-lower-stmt.cc (ASTLoweringStmt::visit): Likewise.
	* hir/rust-ast-lower-struct-field-expr.h: Likewise.
	* hir/rust-ast-lower-type.cc (ASTLowerTypePath::visit): Likewise.
	(ASTLowerQualifiedPathInType::visit): Likewise.
	(ASTLoweringType::translate): Likewise.
	(ASTLoweringType::visit): Likewise.
	(ASTLowerGenericParam::translate): Likewise.
	(ASTLowerGenericParam::visit): Likewise.
	(ASTLoweringTypeBounds::translate): Likewise.
	(ASTLoweringTypeBounds::visit): Likewise.
	(ASTLowerWhereClauseItem::visit): Likewise.
	* hir/rust-ast-lower-type.h: Likewise.
	* hir/rust-ast-lower.cc (ASTLowering::go): Likewise.
	(ASTLoweringBlock::visit): Likewise.
	(ASTLoweringIfBlock::visit): Likewise.
	(ASTLoweringIfLetBlock::visit): Likewise.
	(ASTLowerStructExprField::visit): Likewise.
	(ASTLoweringExprWithBlock::visit): Likewise.
	(ASTLoweringBase::lower_qual_path_type): Likewise.
	(ASTLoweringBase::lower_closure_param): Likewise.
	* resolve/rust-ast-resolve-base.cc (ResolverBase::resolve_visibility):
	Likewise.
	* resolve/rust-ast-resolve-expr.cc (ResolveExpr::go): Likewise.
	(ResolveExpr::visit): Likewise.
	(ResolveExpr::resolve_closure_param): Likewise.
	* resolve/rust-ast-resolve-expr.h: Likewise.
	* resolve/rust-ast-resolve-implitem.h: Likewise.
	* resolve/rust-ast-resolve-item.cc (ResolveTraitItems::visit):
	Likewise.
	(ResolveItem::go): Likewise.
	(ResolveItem::visit): Likewise.
	(ResolveItem::resolve_impl_item): Likewise.
	(ResolveItem::resolve_extern_item): Likewise.
	(ResolveImplItems::go): Likewise.
	(ResolveExternItem::go): Likewise.
	(ResolveExternItem::visit): Likewise.
	* resolve/rust-ast-resolve-item.h: Likewise.
	* resolve/rust-ast-resolve-path.cc (ResolvePath::go): Likewise.
	(ResolvePath::resolve_path): Likewise.
	* resolve/rust-ast-resolve-path.h: Likewise.
	* resolve/rust-ast-resolve-pattern.cc (PatternDeclaration::go):
	Likewise.
	(PatternDeclaration::visit): Likewise.
	(resolve_range_pattern_bound): Likewise.
	* resolve/rust-ast-resolve-pattern.h: Likewise.
	* resolve/rust-ast-resolve-stmt.cc (ResolveStmt::visit): Likewise.
	* resolve/rust-ast-resolve-stmt.h: Likewise.
	* resolve/rust-ast-resolve-struct-expr-field.cc (ResolveStructExprField::go):
	Likewise.
	(ResolveStructExprField::visit): Likewise.
	* resolve/rust-ast-resolve-struct-expr-field.h: Likewise.
	* resolve/rust-ast-resolve-toplevel.h: Likewise.
	* resolve/rust-ast-resolve-type.cc (ResolveType::visit): Likewise.
	(ResolveRelativeTypePath::go): Likewise.
	(ResolveRelativeQualTypePath::resolve_qual_seg): Likewise.
	(ResolveTypeToCanonicalPath::go): Likewise.
	(ResolveTypeToCanonicalPath::visit): Likewise.
	(ResolveGenericArgs::resolve_disambiguated_generic): Likewise.
	(ResolveGenericArgs::go): Likewise.
	* resolve/rust-ast-resolve-type.h: Likewise.
	* resolve/rust-ast-resolve.cc (NameResolution::go): Likewise.
	* resolve/rust-default-resolver.cc (DefaultResolver::visit): Likewise.
	* resolve/rust-early-name-resolver.cc (EarlyNameResolver::resolve_qualified_path_type):
	Likewise.
	(EarlyNameResolver::visit): Likewise.
	* resolve/rust-toplevel-name-resolver-2.0.cc (TopLevel::visit):
	Likewise.
	* checks/errors/rust-ast-validation.cc: Likewise.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2024-03-13 11:58:12 +00:00
Pierre-Emmanuel Patry
843d7d7b46 Replace reference to unique pointer with reference
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>
2024-03-13 11:58:12 +00:00
Thomas Schwinge
444d1a98e7 Merge commit '1a9974d08bc1478a98f52b2ea95475a583747724' into HEAD [#2912] 2024-03-12 09:41:55 +01:00
Thomas Schwinge
1a9974d08b Placate clang-format re 'gcc/rust/backend/rust-tree.cc'
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.
2024-03-12 09:38:41 +01:00
Thomas Schwinge
3651af8535 Adjust '.github/bors_log_expected_warnings' 2024-03-11 23:44:18 +01:00
Jakub Jelinek
879c99355c cse: Workaround GCC < 5 bug in cse_insn [PR111852]
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)
2024-03-11 23:41:16 +01:00
Thomas Schwinge
a95e21151a Merge commit 'af4bb221153359f5948da917d5ef2df738bb1e61' into HEAD 2024-03-11 22:51:28 +01:00
Thomas Schwinge
02d394b273 Merge commit '46595ce72e5855189e3c60a140c3ca5aaddfb58c' into HEAD 2024-03-11 22:43:19 +01:00
Thomas Schwinge
4235574518 Merge commit '46595ce72e5855189e3c60a140c3ca5aaddfb58c^' into HEAD 2024-03-11 22:38:33 +01:00
Thomas Schwinge
2cd7fb664c Merge commit '7439f40dc17f47480620beadf5b2f5784b59aefe' into HEAD [#1543] 2024-03-11 01:05:15 +01:00
Thomas Schwinge
ec26db5351 Merge commit 'b1c06fd9723453dd2b2ec306684cb806dc2b4fbb^' into HEAD 2024-03-11 00:59:26 +01:00
Thomas Schwinge
333fe5b0f1 Merge commit 'ce7a757fd9ecb99c4f54cfde5cf5ef9a9e7819fc' into HEAD 2024-03-11 00:59:03 +01:00
Thomas Schwinge
20bb2dac9e Merge commit 'ce7a757fd9ecb99c4f54cfde5cf5ef9a9e7819fc^' into HEAD 2024-03-11 00:57:51 +01:00
Thomas Schwinge
a88f480434 Merge commit 'af91934c2f6b8efc67d625c99068b4761ae5edd0' into HEAD 2024-03-11 00:56:06 +01:00
Thomas Schwinge
7f7da6c240 Merge commit 'af91934c2f6b8efc67d625c99068b4761ae5edd0^' into HEAD 2024-03-11 00:47:49 +01:00
Thomas Schwinge
a1bd74ba1d Merge commit '1aee5d2ace9ea8f35baf5b18e36caf44fe018ea3' into HEAD [#1408] 2024-03-11 00:45:13 +01:00
Thomas Schwinge
43106fa899 Merge commit '1ad5ae5a45f2e3fc6948b35a3b052fdd48453704' into HEAD [#1408] 2024-03-11 00:37:42 +01:00
Thomas Schwinge
afd1220e0b Merge commit '1ad5ae5a45f2e3fc6948b35a3b052fdd48453704^' into HEAD 2024-03-11 00:34:22 +01:00
Thomas Schwinge
ddbb4d3a41 Merge commit 'f3f6ff7b16861cd0651eccff14689536550762ae' into HEAD [#2414] 2024-03-11 00:33:08 +01:00
Thomas Schwinge
b2ccc44dfb Merge commit 'f3f6ff7b16861cd0651eccff14689536550762ae^' into HEAD 2024-03-11 00:26:50 +01:00
Thomas Schwinge
08d817df8c Merge commit 'dc17ceb3055f56aa3a59c6ef3ae32043d58502d1' into HEAD 2024-03-11 00:25:40 +01:00
Thomas Schwinge
11150fff5e Merge commit 'dc17ceb3055f56aa3a59c6ef3ae32043d58502d1^' into HEAD 2024-03-11 00:25:10 +01:00
Thomas Schwinge
b1617efc6e Merge commit '9fc0ae6033f3e41c9b4605531a6a8543414b0d2d' into HEAD 2024-03-11 00:24:32 +01:00
Thomas Schwinge
190facd2b3 Merge commit '9fc0ae6033f3e41c9b4605531a6a8543414b0d2d^' into HEAD 2024-03-11 00:24:01 +01:00
Thomas Schwinge
a22ac0f9ff Merge commit 'ead5103cc6f526bcc5a30c8c7185e9dd5de73d55' into HEAD 2024-03-11 00:21:36 +01:00
Thomas Schwinge
41d0438ad2 Merge commit 'f330710912229678b65def1f6f52765baa3d0f7a' into HEAD 2024-03-11 00:20:26 +01:00
Thomas Schwinge
a42ae24824 Merge commit 'ab422974567ae73926c2308c3400b5974d6e09f1' into HEAD 2024-03-11 00:18:51 +01:00
Thomas Schwinge
198badab34 Merge commit 'ab422974567ae73926c2308c3400b5974d6e09f1^' into HEAD 2024-03-11 00:17:15 +01:00
Thomas Schwinge
cd9de752bd Merge commit '9c7797a8c2d707ba4516d3d96d8dff6201476fb6' into HEAD 2024-03-11 00:16:01 +01:00
Thomas Schwinge
ee90365c80 Merge commit '126f707efbb5184178701cbdc753a10fd831374e' into HEAD 2024-03-11 00:13:43 +01:00
Thomas Schwinge
d0bf4b8fcb Merge commit '126f707efbb5184178701cbdc753a10fd831374e^' into HEAD 2024-03-10 23:54:17 +01:00
Thomas Schwinge
9267ffafb3 Merge commit 'f4a2ae2338962208b8039f154f5912402e94c378' into HEAD 2024-03-10 23:42:52 +01:00
Thomas Schwinge
6915bdb8fc Merge commit 'f4a2ae2338962208b8039f154f5912402e94c378^' into HEAD 2024-03-10 23:42:46 +01:00
Thomas Schwinge
ffba2ab00f Merge commit '8a30775b0d3037123ee540f7b65a736ad49e05ce' into HEAD 2024-03-10 23:38:46 +01:00
Thomas Schwinge
3d92284aab Merge commit '8a30775b0d3037123ee540f7b65a736ad49e05ce^' into HEAD 2024-03-10 23:38:38 +01:00
Thomas Schwinge
a9de2770f2 Merge commit '33ebb0dff9bb022f1e0709e0e73faabfc3df7931' into HEAD 2024-03-10 23:35:31 +01:00
Thomas Schwinge
acd9cdbb8f Merge commit '33ebb0dff9bb022f1e0709e0e73faabfc3df7931^' into HEAD 2024-03-10 23:34:09 +01:00
Thomas Schwinge
84994ca72b Merge commit '4f01ae3761ca1f8dd7a33b833ae30624f047ac9c' into HEAD 2024-03-10 23:24:35 +01:00
Thomas Schwinge
2157ebb067 Merge commit '4f01ae3761ca1f8dd7a33b833ae30624f047ac9c^' into HEAD 2024-03-10 23:22:34 +01:00
Thomas Schwinge
bcc6fe5825 Merge commit 'ea1cd66f2200839d46a8b4dc140d18c00b849c82' into HEAD 2024-03-10 23:19:31 +01:00
Thomas Schwinge
be82a46963 Merge commit 'ea1cd66f2200839d46a8b4dc140d18c00b849c82^' into HEAD 2024-03-10 23:18:49 +01:00
Thomas Schwinge
320b0c28d3 Merge commit 'bc45e18d433f879a02e369d027829f90f9e85724' into HEAD 2024-03-10 23:16:49 +01:00
Thomas Schwinge
02250442a2 Merge commit 'bc45e18d433f879a02e369d027829f90f9e85724^' into HEAD 2024-03-10 23:15:52 +01:00
Thomas Schwinge
fe4ff2101a Merge commit '0a85544e1aaeca41133ecfc438cda913dbc0f122' into HEAD 2024-03-10 22:57:58 +01:00
Thomas Schwinge
f1e5b36df0 Merge commit '0a85544e1aaeca41133ecfc438cda913dbc0f122^' into HEAD 2024-03-10 22:56:03 +01:00
0xn4utilus
53d8e04c0b Remove dead code associated with AST::ExternalFunctionItem
gcc/rust/ChangeLog:

	* ast/rust-ast-collector.cc (TokenCollector::visit):
	Remove dead code.
	* ast/rust-ast-collector.h: Likewise.
	* ast/rust-ast-full-decls.h (class ExternalFunctionItem):
	Likewise.
	* ast/rust-ast-visitor.cc (DefaultASTVisitor::visit):
	Likewise.
	* ast/rust-ast-visitor.h: Likewise.
	* ast/rust-ast.cc (ExternalFunctionItem::as_string): Likewise.
	(ExternalFunctionItem::accept_vis): Likewise.
	* checks/errors/rust-ast-validation.cc (ASTValidation::visit):
	Likewise.
	* checks/errors/rust-ast-validation.h: Likewise.
	* checks/errors/rust-feature-gate.h: Likewise.
	* expand/rust-cfg-strip.cc (CfgStrip::visit):
	Likewise.
	* expand/rust-cfg-strip.h: Likewise.
	* expand/rust-derive.h: Likewise.
	* expand/rust-expand-visitor.cc (ExpandVisitor::visit):
	Likewise.
	* expand/rust-expand-visitor.h: Likewise.
	* hir/rust-ast-lower-base.cc (ASTLoweringBase::visit):
	Likewise.
	* hir/rust-ast-lower-base.h: Likewise.
	* metadata/rust-export-metadata.cc (ExportContext::emit_function):
	Likewise.
	* parse/rust-parse-impl.h: Likewise.
	* parse/rust-parse.h: Likewise.
	* resolve/rust-ast-resolve-base.cc (ResolverBase::visit):
	Likewise.
	* resolve/rust-ast-resolve-base.h: Likewise.
	* resolve/rust-default-resolver.cc (DefaultResolver::visit):
	Likewise.
	* resolve/rust-default-resolver.h: Likewise.
	* util/rust-attributes.cc (AttributeChecker::visit): Likewise.
	* util/rust-attributes.h: Likewise.

gcc/testsuite/ChangeLog:

	* rust/compile/extern_func_with_body.rs: New test.

Signed-off-by: 0xn4utilus <gyanendrabanjare8@gmail.com>
2024-03-05 15:08:36 +00:00
0xn4utilus
87f797f0e8 Update resolver to use AST::Function instead of AST::ExternalFunctionItem
gcc/rust/ChangeLog:

	* checks/errors/rust-feature-gate.cc (FeatureGate::visit):
	Check if function is_external or not.
	* hir/rust-ast-lower-extern.h: Use AST::Function
	instead of AST::ExternalFunctionItem.
	* parse/rust-parse-impl.h (Parser::parse_external_item):
	Likewise.
	(Parser::parse_pattern): Fix clang format.
	* resolve/rust-ast-resolve-implitem.h: Likewise.
	* resolve/rust-ast-resolve-item.cc (ResolveExternItem::visit):
	Likewise.
	* resolve/rust-ast-resolve-item.h: Likewise.
	* resolve/rust-default-resolver.cc (DefaultResolver::visit):
	Check if param has_pattern before using get_pattern.

Signed-off-by: 0xn4utilus <gyanendrabanjare8@gmail.com>
2024-03-05 15:08:36 +00:00
0xn4utilus
0177e3cb13 Unify ASTValidation::visit for ExternalFunctionItem and Function
gcc/rust/ChangeLog:

	* checks/errors/rust-ast-validation.cc (ASTValidation::visit):
	Add external function validation support. Add ErrorCode::E0130.
	* parse/rust-parse-impl.h (Parser::parse_function): Parse
	external functions from `parse_function`.
	(Parser::parse_external_item): Clang format.
	(Parser::parse_pattern): Clang format.
	* parse/rust-parse.h: Add default parameter
	`is_external` in `parse_function`.

Signed-off-by: 0xn4utilus <gyanendrabanjare8@gmail.com>
2024-03-05 15:08:36 +00:00
0xn4utilus
1c467c0a86 Add get_pattern_kind to Pattern
gcc/rust/ChangeLog:

	* ast/rust-ast.h: Add Kind Enum to
	Pattern.
	* ast/rust-macro.h: Add get_pattern_kind().
	* ast/rust-path.h: Likewise.
	* ast/rust-pattern.h: Likewise.

Signed-off-by: 0xn4utilus <gyanendrabanjare8@gmail.com>
2024-03-05 15:08:36 +00:00
0xn4utilus
48add29a63 Add support for external functions
gcc/rust/ChangeLog:

	* ast/rust-ast.cc (Function::Function): Add `is_external_function` field.
	(Function::operator=): Likewise.
	* ast/rust-ast.h: New constructor for ExternalItem.
	* ast/rust-item.h (class Function): Add `is_external_function`
	field. Update `get_node_id`.
	* ast/rust-macro.h: Update copy constructor.

Signed-off-by: 0xn4utilus <gyanendrabanjare8@gmail.com>
2024-03-05 15:08:36 +00:00
Sourabh Jaiswal
452345f0f8 Clean BiMap to use tl::optional for lookups
gcc/rust/Changelog:

	* expand/rust-expand-visitor.cc
	(ExpandVisitor::expand_inner_items): Adjust to use has_value ()
	(ExpandVisitor::expand_inner_stmts): Likewise
	* expand/rust-macro-builtins.cc (builtin_macro_from_string): Likewise
	(make_macro_path_str): Likewise
	* util/rust-hir-map.cc (Mappings::insert_macro_def): Likewise
	* util/rust-lang-item.cc (LangItem::Parse): Adjust to return tl::optional
	(LangItem::toString) Likewise
	* util/rust-token-converter.cc (handle_suffix): Adjust to use value.or ()
	(from_literal) Likewise
	* util/bi-map.h (BiMap::lookup): Adjust to use tl::optional for
	lookups

Signed-off-by: Sourabh Jaiswal <sourabhrj31@gmail.com>
2024-03-05 10:26:25 +00:00
Owen Avery
dae69e86c0 Ensure TupleStructPattern and TuplePattern have items
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>
2024-03-04 11:22:29 +00:00
jjasmine
ede65c2801 Add curly brackets, formatted clang
gcc/rust/ChangeLog:

	* resolve/rust-late-name-resolver-2.0.cc (Late::visit): Add error emitting
2024-03-04 11:17:45 +00:00
jjasmine
92874edab8 Add error emitting when we can't resolve id expr
gcc/rust/ChangeLog:

	* resolve/rust-late-name-resolver-2.0.cc (Late::visit): Add error emitting
2024-03-04 11:17:45 +00:00
Arthur Cohen
61b5a058a4 format-args: Add documentation for future expansion of function
gcc/rust/ChangeLog:

	* expand/rust-macro-builtins.cc (MacroBuiltin::format_args_handler): Add
	documentation regarding future tasks.
2024-03-01 15:42:36 +00:00
Arthur Cohen
3ff0f1a7bf lower: Add base for lowering FormatArgs nodes
gcc/rust/ChangeLog:

	* Make-lang.in: Compile the new source file.
	* ast/rust-ast-collector.cc (TokenCollector::visit): Error out when
	visiting FormatArgs nodes.
	* resolve/rust-ast-resolve-base.cc (ResolverBase::visit): Likewise.
	* hir/rust-ast-lower-expr.cc (ASTLoweringExpr::visit): Likewise.
	* ast/rust-ast.cc (FormatArgs::get_locus): New.
	* ast/rust-builtin-ast-nodes.h: Improve FormatArgs API.
	* ast/rust-fmt.cc (Pieces::~Pieces): Cleanup.
	(Pieces::Pieces): Likewise.
	* ast/rust-fmt.h (struct Pieces): Add pieces_vector member.
	* hir/rust-ast-lower-format-args.cc: New file.
	* hir/rust-ast-lower-format-args.h: New file.
2024-03-01 15:42:36 +00:00
Arthur Cohen
afed72d713 format-args: Fix Rust interface and add input parsing.
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.
2024-03-01 15:42:36 +00:00
Arthur Cohen
38e3cffdbd parser: Add peek(n) method to parser
gcc/rust/ChangeLog:

	* parse/rust-parse.h: New method.
2024-03-01 15:42:36 +00:00
Arthur Cohen
d802ca9c05 macro-builtins: Add newline generic format_args!() handler
gcc/rust/ChangeLog:

	* expand/rust-macro-builtins.cc (format_args_maker): New function.
	(try_expand_many_expr): Add comment about reworking function.
	(MacroBuiltin::format_args_handler): Add newline parameter.
	* expand/rust-macro-builtins.h: Likewise.
2024-03-01 15:42:36 +00:00
Arthur Cohen
12ca8dbb4b ast: Add base nodes for FormatArgs
This commit adds a base for creating AST FormatArgs nodes after expanding
invocations of `format_args!()`. These nodes will then be expanded to
the proper runtime function calls (to core::fmt::rt) during the AST
lowering.

gcc/rust/ChangeLog:

	* ast/rust-builtin-ast-nodes.h: New file.
	* ast/rust-ast-full-decls.h (class FormatArgs): Declare new class.
	* ast/rust-ast-collector.cc: Handle FormatArgs nodes properly.
	* ast/rust-ast-collector.h: Likewise.
	* ast/rust-ast-full.h: Likewise.
	* ast/rust-ast-visitor.cc: Likewise.
	* ast/rust-ast-visitor.h: Likewise.
	* ast/rust-ast.cc: Likewise.
	* ast/rust-ast.h: Likewise.
	* expand/rust-derive.h: Likewise.
	* hir/rust-ast-lower-base.cc: Likewise.
	* hir/rust-ast-lower-base.h: Likewise.
	* hir/rust-ast-lower-expr.cc: Likewise.
	* hir/rust-ast-lower-expr.h: Likewise.
	* resolve/rust-ast-resolve-base.cc: Likewise.
	* resolve/rust-ast-resolve-base.h: Likewise.
2024-03-01 15:42:36 +00:00
Owen Avery
7064be37a3 Make DefaultResolver visit more of the AST
gcc/rust/ChangeLog:

	* resolve/rust-default-resolver.cc
	(DefaultResolver::visit): Visit inner AST nodes of ClosureExprInner,
	ClosureExprInnerTyped, IfExpr, IfExprConseqElse, MatchExpr,
	PathInExpression, EnumItemTuple, EnumItemStruct, and
	EnumItemDiscriminant.
	* ast/rust-item.h
	(EnumItemDiscriminant::has_expr): New function.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2024-03-01 09:51:22 +00:00
Arthur Cohen
9ee5b51f57 extern-types: Lower to HIR::ExternalTypeItem properly
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.
2024-02-29 15:53:03 +00:00
Arthur Cohen
8e3c34aa04 hir: Add ExternalTypeItem node
gcc/rust/ChangeLog:

	* hir/tree/rust-hir-item.h (class ExternalTypeItem): New class.
	* hir/tree/rust-hir.cc (ExternalTypeItem::as_string): Likewise.
	* backend/rust-compile-extern.h: Add base for handling HIR::ExternalTypeItem
	node.
	* checks/errors/borrowck/rust-bir-builder-struct.h: Likewise.
	* checks/errors/borrowck/rust-function-collector.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-extern.h: Likewise.
	* hir/rust-hir-dump.cc (Dump::visit): Likewise.
	* hir/rust-hir-dump.h: Likewise.
	* hir/tree/rust-hir-full-decls.h (class ExternalTypeItem): Likewise.
	* hir/tree/rust-hir-visitor.h: Likewise.
	(ExternalTypeItem::accept_vis): Likewise.
	* typecheck/rust-hir-type-check-implitem.cc (TypeCheckTopLevelExternItem::visit): Likewise.
	* typecheck/rust-hir-type-check-implitem.h: Likewise.
2024-02-29 15:53:03 +00:00
Arthur Cohen
7b3fa7ac97 extern-types: Declare external types in name resolver.
gcc/rust/ChangeLog:

	* resolve/rust-ast-resolve-implitem.h: Declare external types as new
	types.
2024-02-29 15:53:03 +00:00
Arthur Cohen
6895e0bb24 lang-items: Make lang items enum stronger, rename class, cleanup ns.
gcc/rust/ChangeLog:

	* util/rust-lang-item.h (class RustLangItem): Renamed to...
	(class LangItem): ...this. Rename ItemType enum to Kind
	* util/rust-lang-item.cc: Rename methods to use new class name.
	* backend/rust-compile-expr.cc (CompileExpr::visit): Use new lang-item API.
	(CompileExpr::resolve_operator_overload): Likewise.
	* backend/rust-compile-expr.h: Likewise.
	* hir/rust-ast-lower-base.cc (ASTLoweringBase::handle_lang_item_attribute): Likewise.
	* typecheck/rust-autoderef.cc (Adjuster::try_deref_type): Likewise.
	(AutoderefCycle::cycle): Likewise.
	* typecheck/rust-autoderef.h: Likewise.
	* typecheck/rust-hir-type-bounds.h: Likewise.
	* typecheck/rust-hir-type-check-base.cc (TypeCheckBase::get_marker_predicate): Likewise.
	* typecheck/rust-hir-type-check-base.h: Likewise.
	* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit): Likewise.
	* typecheck/rust-hir-type-check-expr.h: Likewise.
	* typecheck/rust-hir-type-check-type.cc (TypeResolveGenericParam::visit): Likewise.
	* typecheck/rust-tyty-bounds.cc (TypeBoundsProbe::assemble_sized_builtin): Likewise.
	(TypeBoundsProbe::assemble_builtin_candidate): Likewise.
	(TypeCheckBase::get_predicate_from_bound): Likewise.
	* typecheck/rust-tyty.cc (ClosureType::setup_fn_once_output): Likewise.
	* util/rust-hir-map.cc (Mappings::get_lang_item): Likewise.
	(Mappings::lookup_trait_item_lang_item): Likewise.
	* util/rust-hir-map.h: Likewise.
2024-02-29 15:52:44 +00:00
Arthur Cohen
e9de5b410d lang-items: Cleanup parsing and lookups of lang items.
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.
2024-02-29 15:52:44 +00:00
Thomas Schwinge
4e51e84d86 Merge commit '705de6d54ca95b8277a15fe9a2255af6168ae086' into HEAD [#2123] 2024-02-29 14:04:29 +01:00
jjasmine
75424e6ccb Fix small FixMe task in rust macro builtins
gcc/rust/ChangeLog:

	* expand/rust-macro-builtins.cc: Change BuiltinMacro in
	builtin_macro_from_string to tl::optional<>
	* expand/rust-macro-builtins.h (enum class): Change BuiltinMacro
	in builtin_macro_from_string to tl::optional<>
	* resolve/rust-early-name-resolver.cc (EarlyNameResolver::visit):
	Resolved wrong type dependency of builtin_macro_from_string

Signed-off-by: jjasmine <tanghocle456@gmail.com>
2024-02-27 11:57:50 +00:00
Owen Avery
4ef924f761 Adjust error checks to match name resolution 2.0
gcc/testsuite/ChangeLog:

	* rust/compile/bad_stmt_enums.rs: Adjust redefinition error.
	* rust/compile/bad_toplevel_enums.rs: Likewise.
	* rust/compile/redef_error1.rs: Likewise.
	* rust/compile/redef_error3.rs: Likewise.
	* rust/compile/redef_error4.rs: Likewise.
	* rust/compile/redef_error6.rs: Likewise.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2024-02-27 10:40:36 +00:00
Arthur Cohen
420d50cabd ci: Install cargo on ubuntu 18.04 container.
ChangeLog:

	* .github/workflows/ccpp.yml: Install cargo for GCC 4.8 job.
2024-02-26 17:32:38 +00:00
Arthur Cohen
fa2a861457 format-parser: Add is_some_and method for Option<T>
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>.
2024-02-26 17:32:38 +00:00
Arthur Cohen
25839a8761 libformat_parser: Fix Rust warnings.
libgrust/ChangeLog:

	* libformat_parser/generic_format_parser/src/lib.rs: Remove
	unused deprecated attribute and unused import.
	* libformat_parser/src/lib.rs: Remove unused import.
2024-02-26 17:32:38 +00:00
Arthur Cohen
2d22cc0f7f rust-fmt: Store parsed string in Pieces struct
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.
2024-02-26 17:32:38 +00:00
Arthur Cohen
b9b2c92b3a format_args: Parse entire token invocation
gcc/rust/ChangeLog:

	* expand/rust-macro-builtins.cc (MacroBuiltin::format_args_handler):
	Transform entire invocation token stream into string for the parser.
2024-02-26 17:32:38 +00:00
Arthur Cohen
bdba3fae4c format_args: Parse format string properly
gcc/rust/ChangeLog:

	* expand/rust-macro-builtins.cc (MacroBuiltin::format_args_handler):
	Construct string to parser properly.
2024-02-26 17:32:38 +00:00
Arthur Cohen
ad905fe516 libformat_parser: Send boxed values across FFI properly
gcc/rust/ChangeLog:

	* ast/rust-fmt.cc (Pieces::~Pieces): Call libformat_parser's release
	function in destructor.
	* ast/rust-fmt.h (struct PieceSlice): Add capacity.
	(destroy_pieces): New.
	(struct Pieces): Add destructor.

libgrust/ChangeLog:

	* libformat_parser/src/lib.rs: Leak Boxes properly for C++ to
	see them, add memory release function.
2024-02-26 17:32:38 +00:00
Arthur Cohen
b49f87f693 libformat_parser: Update header and remove old interface
gcc/rust/ChangeLog:

	* ast/rust-fmt.cc (Pieces::collect): Use new Pieces API.
	* ast/rust-fmt.h: Update interface with new FFI bindings.

libgrust/ChangeLog:

	* libformat_parser/src/lib.rs: Add IntoFFI trait.
	* libformat_parser/libformat-parser.h: Removed.
2024-02-26 17:32:38 +00:00
Arthur Cohen
e3fca6ffc7 git: Ignore libgrust build folders
ChangeLog:

	* .gitignore: Add libgrust target folders to the ignore list.
2024-02-26 17:32:38 +00:00
Arthur Cohen
82f7ee3c59 libformat_parser: Start experimenting with cbindgen
libgrust/ChangeLog:

	* libformat_parser/cbindgen.toml: New file.
	* libformat_parser/libformat-parser.h: New file.

gcc/rust/ChangeLog:

	* ast/rust-fmt.h: Add remaining FFI types.
2024-02-26 17:32:38 +00:00
Arthur Cohen
23e029d958 libformat_parser: Add FFI safe interface
libgrust/ChangeLog:

	* libformat_parser/generic_format_parser/src/lib.rs: Add generic
	library.
	* libformat_parser/src/lib.rs: Add base for FFI interface.
2024-02-26 17:32:38 +00:00
Arthur Cohen
7b25f53a41 libgrust: Add format_parser library
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.
2024-02-26 17:32:38 +00:00
Arthur Cohen
486b2043a0 fmt: Start working on format_args!() parser
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.
2024-02-26 17:32:38 +00:00
Marc Poulhiès
84477fc832 gccrs: minor cleanup in langhook.type_for_mode
gcc/rust/ChangeLog:

	* rust-lang.cc (grs_langhook_type_for_mode): simplify code for
	xImode. Add missing long_double_type_node.

Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
2024-02-20 13:56:48 +00:00
Owen Avery
5989e3d614 Fix false positive for top-level AltPattern
gcc/rust/ChangeLog:

	* hir/rust-ast-lower-pattern.cc
	(ASTLoweringPattern::visit):
	Reset is_let_top_level while visiting GroupedPattern.

gcc/testsuite/ChangeLog:

	* rust/compile/let_alt.rs: Check for false positive.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2024-02-20 10:45:15 +00:00
Marc Poulhiès
f2e19364bc gccrs: fix powif64 intrinsic
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>
2024-02-20 10:37:54 +00:00
Pierre-Emmanuel Patry
8566844dac libgrust: Add entry for maintainers
ChangeLog:

	* MAINTAINERS: Add maintainers for libgrust.

contrib/ChangeLog:

	* gcc-changelog/git_commit.py: Add libgrust.

(cherry picked from commit e4f0eb725d)

Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2024-02-16 16:33:12 +00:00
Pierre-Emmanuel Patry
1b6ac2229b libgrust: Add ChangeLog file
libgrust/ChangeLog:

	* ChangeLog: New file.

(cherry picked from commit a857ec6aad)

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2024-02-16 16:33:12 +00:00
Jakub Jelinek
b1f11b31bf gccrs: Avoid *.bak suffixed tests - use dg-skip-if instead
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.
2024-02-16 13:43:06 +00:00
Sahil Yeole
b01124f128 Update copyright years.
Signed-off-by: Sahil Yeole <sahilyeole93@gmail.com>
2024-02-16 10:47:39 +00:00
Sahil Yeole
1725714f16 contrib: Add libgrust to update-copyright.py script
contrib/ChangeLog:
	* update-copyright.py: Add libgrust folder.

Signed-off-by: Sahil Yeole <sahilyeole93@gmail.com>
2024-02-16 10:47:39 +00:00
0xn4utilus
d0233c620d Add variadic check on function params
gcc/rust/ChangeLog:

	* checks/errors/rust-ast-validation.cc (ASTValidation::visit):
	Add variadic check on all parameters.

gcc/testsuite/ChangeLog:

	* rust/compile/issue-2850.rs: New test.

Signed-off-by: 0xn4utilus <gyanendrabanjare8@gmail.com>
2024-02-15 10:55:22 +00:00
Owen Avery
a4716752fb Fix lookup of TuplePattern sub-pattern types
gcc/rust/ChangeLog:

	* backend/rust-compile-pattern.cc
	(CompilePatternLet::visit):
	Lookup type of sub-pattern, not tuple pattern itself.

gcc/testsuite/ChangeLog:

	* rust/compile/issue-2847-b.rs: New test.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2024-02-13 15:08:02 +00:00
Marc Poulhiès
50f8ca9800 gccrs: add powi intrinsics
gcc/rust/ChangeLog:

	* backend/rust-builtins.cc
	(BuiltinsContext::register_rust_mappings): Add powi and reformat.
	* backend/rust-builtins.h: Add missing copyright header.

gcc/testsuite/ChangeLog:

	* rust/compile/torture/intrinsics-math.rs: Adjust pow test, add
	test for powi.

Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
2024-02-13 12:58:41 +00:00
Arthur Cohen
0a0549eaba gccrs: Add testcase for #[rustc_const_stable]
To ensure we don't introduce regressions back to issue #2314

gcc/testsuite/ChangeLog:

	* rust/compile/rustc_const_stable.rs: New test.
2024-02-13 11:21:47 +00:00
Arthur Cohen
02f7befb8a expand: Fix formatting for "macro not found" error
gcc/rust/ChangeLog:

	* expand/rust-macro-expand.h (struct MacroExpander): Nitpick: fix
	formatting of emitted error.
2024-02-13 11:21:47 +00:00
Owen Avery
239247a0f4 Fix rebinding imports
gcc/rust/ChangeLog:

	* resolve/rust-ast-resolve-item.cc
	(flatten_glob): Use Import class.
	(flatten_rebind): Likewise.
	(flatten_list): Likewise.
	(flatten): Likewise.
	(flatten_use_dec_to_paths): Likewise.
	(flatten_use_dec_to_imports): Likewise.
	(ResolveItem::visit): Likewise.
	(Import::add_prefix): New.
	(rust_flatten_nested_glob): Adjust test.
	(rust_flatten_glob): Likewise.
	(rust_flatten_rebind_none): Likewise.
	(rust_flatten_rebind): Likewise.
	(rust_flatten_rebind_nested): Likewise.
	(rust_flatten_list): Likewise.
	* resolve/rust-ast-resolve-item.h
	(class Import): New.

gcc/testsuite/ChangeLog:

	* rust/compile/use_2.rs: New test.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2024-02-13 11:20:23 +00:00
Arthur Cohen
1d8f5d5853 gccrs: Add testcase for matches!() macro
This adds a testcase for issue #2129.

gcc/testsuite/ChangeLog:

	* rust/execute/torture/matches_macro.rs: New test.
2024-02-08 10:23:23 +00:00
Arthur Cohen
da5e5ee467 gccrs: Fix typo in RegionConstraints instance
gcc/rust/ChangeLog:

	* typecheck/rust-hir-type-check-implitem.h: Fix typo in field
	(region_costraints -> region_constraints).
2024-02-08 10:16:46 +00:00
Kushal Pal
1e0e6a46ab Fix macro parsing for trait items.
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>
2024-02-05 17:08:39 +00:00
Kushal Pal
df78aec1a2 Remove obsolete classes and functions.
Trait functions now use AST::Function class, so classes
AST::TraitItemFunc, AST::TraitItemMethod, AST::TraitFunctionDecl,
AST::TraitMethodDecl and their related functions can be removed.

gcc/rust/ChangeLog:

	* ast/rust-ast-collector.cc (TokenCollector::visit):
	Remove obsolete classes and functions.
	* ast/rust-ast-collector.h:
	Likewise.
	* ast/rust-ast-full-decls.h (class TraitFunctionDecl):
	Likewise.
	(class TraitItemFunc):
	Likewise.
	(class TraitMethodDecl):
	Likewise.
	(class TraitItemMethod):
	Likewise.
	* ast/rust-ast-visitor.cc (DefaultASTVisitor::visit):
	Likewise.
	* ast/rust-ast-visitor.h:
	Likewise.
	* ast/rust-ast.cc (TraitItemFunc::TraitItemFunc):
	Likewise.
	(TraitItemFunc::operator=):
	Likewise.
	(TraitItemFunc::as_string):
	Likewise.
	(TraitFunctionDecl::as_string):
	Likewise.
	(TraitItemMethod::TraitItemMethod):
	Likewise.
	(TraitItemMethod::operator=):
	Likewise.
	(TraitItemMethod::as_string):
	Likewise.
	(TraitMethodDecl::as_string):
	Likewise.
	(TraitItemFunc::accept_vis):
	Likewise.
	(TraitItemMethod::accept_vis):
	Likewise.
	* ast/rust-item.h (class TraitFunctionDecl):
	Likewise.
	(class TraitItemFunc):
	Likewise.
	(class TraitMethodDecl):
	Likewise.
	(class TraitItemMethod):
	Likewise.
	* checks/errors/rust-ast-validation.cc (ASTValidation::visit):
	Likewise.
	* checks/errors/rust-ast-validation.h:
	Likewise.
	* checks/errors/rust-feature-gate.h:
	Likewise.
	* expand/rust-cfg-strip.cc (CfgStrip::maybe_strip_trait_function_decl):
	Likewise.
	(CfgStrip::maybe_strip_trait_method_decl):
	Likewise.
	(CfgStrip::visit):
	Likewise.
	* expand/rust-cfg-strip.h:
	Likewise.
	* expand/rust-derive.h:
	Likewise.
	* expand/rust-expand-visitor.cc (ExpandVisitor::expand_trait_function_decl):
	Likewise.
	(ExpandVisitor::expand_trait_method_decl):
	Likewise.
	(ExpandVisitor::visit):
	Likewise.
	* expand/rust-expand-visitor.h:
	Likewise.
	* hir/rust-ast-lower-base.cc (ASTLoweringBase::visit):
	Likewise.
	* hir/rust-ast-lower-base.h:
	Likewise.
	* hir/rust-ast-lower-implitem.cc (ASTLowerTraitItem::visit):
	Likewise.
	* hir/rust-ast-lower-implitem.h:
	Likewise.
	* resolve/rust-ast-resolve-base.cc (ResolverBase::visit):
	Likewise.
	* resolve/rust-ast-resolve-base.h:
	Likewise.
	* resolve/rust-ast-resolve-implitem.h (visit):
	Likewise.
	* resolve/rust-ast-resolve-item.cc (ResolveTraitItems::visit):
	Likewise.
	* resolve/rust-ast-resolve-item.h:
	Likewise.
	* resolve/rust-default-resolver.cc (DefaultResolver::visit):
	Likewise.
	* resolve/rust-default-resolver.h:
	Likewise.
	* resolve/rust-toplevel-name-resolver-2.0.cc (TopLevel::visit):
	Likewise.
	* resolve/rust-toplevel-name-resolver-2.0.h:
	Likewise.
	* util/rust-attributes.cc (AttributeChecker::visit):
	Likewise.
	* util/rust-attributes.h:
	Likewise.

Signed-off-by: Kushal Pal <kushalpal109@gmail.com>
2024-02-05 17:08:39 +00:00
Kushal Pal
a10b39d164 Parse trait functions as AST::Function.
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>
2024-02-05 17:08:39 +00:00
Kushal Pal
16936de7c1 Fix inconsistent formatting.
gcc/testsuite/ChangeLog:

	* rust/compile/issue-2040.rs:
	Enclose 'const' in single quotes.

Signed-off-by: Kushal Pal <kushalpal109@gmail.com>
2024-02-05 17:08:39 +00:00
Kushal Pal
f1b6506982 Add missing visitors for AST::Function.
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>
2024-02-05 17:08:39 +00:00
Kushal Pal
37a6e44c4c Add checks for Trait functions
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>
2024-02-05 17:08:39 +00:00
Kushal Pal
a9ed0b1594 Use AssociatedItem in place of TraitItem
gcc/rust/ChangeLog:

	* ast/rust-ast.h: Replace TraitItem with AssociatedItem.
	* ast/rust-item.h (class Trait): Likewise.
	* expand/rust-expand-visitor.cc (ExpandVisitor::visit):
	Likewise.
	* parse/rust-parse-impl.h (Parser::parse_trait): Likewise.
	* parse/rust-parse.h: Likewise.

Signed-off-by: Kushal Pal <kushalpal109@gmail.com>
2024-02-05 17:08:39 +00:00
Philip Herron
38af9fef52 gccrs: fix bug in pattern check for tuples
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>
2024-02-05 01:57:04 +00:00
Philip Herron
e2cb2a7f02 gccrs: Add testcase to show issue is already fixed
Fixes #2782

gcc/testsuite/ChangeLog:

	* rust/compile/issue-2782.rs: New test.

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2024-02-04 17:18:35 +00:00
Nobel Singh
5b7d6744e6 Move the Implementation of implitem lowering into its own file.
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>
2024-02-04 16:27:04 +00:00
Philip Herron
a99206505f gccrs: refactor inference variable computation into a seperate method
gcc/rust/ChangeLog:

	* typecheck/rust-hir-type-check.cc (TypeResolution::Resolve): refactor
	* typecheck/rust-hir-type-check.h: new prototype
	* typecheck/rust-typecheck-context.cc (TypeCheckContext::compute_inference_variables): x
2024-02-04 00:21:21 +00:00
Philip Herron
f8e4a9c660 gccrs: remove similar hack in type paths as we had in path expressions
This keeps the resolution code in line with paths.

Addresses #2723

gcc/rust/ChangeLog:

	* typecheck/rust-hir-type-check-type.cc: remove hack
2024-02-04 00:21:21 +00:00
Philip Herron
ce4e7944cf gccrs: remove old generics hack to reuse generic symbols from previous seg
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.
2024-02-04 00:21:21 +00:00
Philip Herron
d6c97f6d03 gccrs: Fix ICE accessing empty vector without check
Fixes #2747

gcc/rust/ChangeLog:

	* typecheck/rust-tyty-subst.cc (SubstitutionRef::get_mappings_from_generic_args): fix

gcc/testsuite/ChangeLog:

	* rust/compile/issue-2747.rs: New test.
2024-02-03 23:05:17 +00:00
Philip Herron
74c85f3694 gccrs: add test cases to prove type inference is working
Fixes #2772

gcc/testsuite/ChangeLog:

	* rust/compile/issue-2772-1.rs: New test.
	* rust/compile/issue-2772-2.rs: New test.
2024-02-03 23:04:43 +00:00
Philip Herron
838eab4a46 gccrs: add testcase to prove issue has already been fixed
Fixes #1483

gcc/testsuite/ChangeLog:

	* rust/compile/issue-1483.rs: New test.
2024-02-03 23:04:33 +00:00
Nobel Singh
7c0daba10e Set the default ABI to C for extern blocks and extern functions
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>
2024-02-03 15:51:51 +00:00
Jakub Dupak
22aee650ee TyTy: Store reference to type before any substitutions
gcc/rust/ChangeLog:

	* typecheck/rust-tyty.cc (BaseType::BaseType): Store orig ref.
	(BaseType::get_orig_ref): Add getter.
	* typecheck/rust-tyty.h: Store orig ref.

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2024-02-03 15:25:30 +00:00
Jakub Dupak
39ee37bc79 TyTy: Store region constraints
gcc/rust/ChangeLog:

	* typecheck/rust-hir-type-check-implitem.cc (TypeCheckTopLevelExternItem::visit):
	Add region constraints.
	(TypeCheckImplItem::visit): Add region constraints.
	* typecheck/rust-hir-type-check-implitem.h: Add region constraints.
	* typecheck/rust-hir-type-check-item.cc (TypeCheckItem::ResolveImplBlockSelf):
	Add region constraints.
	(TypeCheckItem::visit): Add region constraints.
	(TypeCheckItem::resolve_impl_item): Add region constraints.
	(TypeCheckItem::resolve_impl_block_substitutions): Add region constraints.
	* typecheck/rust-hir-type-check-item.h: Add region constraints.
	* typecheck/rust-hir-type-check-type.cc (ResolveWhereClauseItem::Resolve):
	Add region constraints.
	(ResolveWhereClauseItem::visit): Add region constraints.
	* typecheck/rust-hir-type-check-type.h (class ResolveWhereClauseItem):
	Add region constraints.
	* typecheck/rust-hir-type-check.cc (TraitItemReference::get_type_from_fn):
	Add region constraints.
	* typecheck/rust-tyty-bounds.cc (TypeBoundPredicate::TypeBoundPredicate):
	Add region constraints.
	* typecheck/rust-tyty-subst.cc (SubstitutionRef::get_region_constraints):
	Add region constraints.
	* typecheck/rust-tyty-subst.h (class BaseType): Add region constraints.
	(struct RegionConstraints): Add region constraints.
	* typecheck/rust-tyty.cc (BaseType::monomorphized_clone): Add region constraints.
	(ADTType::clone): Add region constraints.
	(FnType::clone): Add region constraints.
	(ProjectionType::clone): Add region constraints.
	* typecheck/rust-tyty.h: Add region constraints.

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2024-02-03 15:25:30 +00:00
Jakub Dupak
4635157e93 Typecheck: add regions (lifetimes) to TyTy
gcc/rust/ChangeLog:

	* typecheck/rust-hir-trait-resolve.cc: add regions
	* typecheck/rust-hir-type-check-base.cc (TypeCheckBase::resolve_literal):
	add regions, resolve generic lifetimes
	* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit): add regions
	* typecheck/rust-hir-type-check-implitem.cc (TypeCheckTopLevelExternItem::visit):
	add regions, resolve lifetimes
	(TypeCheckImplItem::visit): add regions, resove lifetimes
	* typecheck/rust-hir-type-check-implitem.h: add default value for result
	* typecheck/rust-hir-type-check-item.cc (TypeCheckItem::visit): add regions,
	resove lifetimes
	(TypeCheckItem::resolve_impl_block_substitutions): add regions, resove lifetimes
	* typecheck/rust-hir-type-check-path.cc (TypeCheckExpr::visit): add regions,
	resove lifetimes
	(TypeCheckExpr::resolve_root_path): add regions, resove lifetimes
	(TypeCheckExpr::resolve_segments): add regions, resove lifetimes
	* typecheck/rust-hir-type-check-type.cc (TypeCheckType::visit): add regions,
	resove lifetimes
	(TypeCheckType::resolve_root_path): add regions, resove lifetimes
	(ResolveWhereClauseItem::Resolve): add regions, resove lifetimes
	(ResolveWhereClauseItem::visit): add regions, resove lifetimes
	* typecheck/rust-hir-type-check.cc (TypeCheckContext::LifetimeResolver::resolve):
	add regions, resolve lifetimes
	(TraitItemReference::get_type_from_fn): add regions, resove lifetimes
	* typecheck/rust-hir-type-check.h: add regions, resove lifetimes
	* typecheck/rust-substitution-mapper.cc (SubstMapper::SubstMapper): add regions,
	resove lifetimes
	(SubstMapper::Resolve): add regions, resove lifetimes
	(SubstMapper::InferSubst): add regions, resove lifetimes
	(SubstMapper::visit): add regions, resove lifetimes
	* typecheck/rust-substitution-mapper.h: add regions, resove lifetimes
	* typecheck/rust-typecheck-context.cc (TypeCheckContext::TypeCheckContext):
	lifetime resolution
	(TypeCheckContext::regions_from_generic_args): lifetime resolution helper
	* typecheck/rust-tyty-bounds.cc (TypeBoundPredicate::TypeBoundPredicate):
	add regions, resove lifetimes
	(TypeBoundPredicate::operator=): add regions, resove lifetimes
	(TypeBoundPredicate::apply_generic_arguments): add regions, resove lifetimes
	(TypeBoundPredicateItem::get_tyty_for_receiver): add regions, resove lifetimes
	* typecheck/rust-tyty-subst.cc (SubstitutionArgumentMappings::get_regions):
	add regions, resove lifetimes
	(SubstitutionArgumentMappings::get_mut_regions): getter
	(SubstitutionArgumentMappings::error): split error and empty
	(SubstitutionArgumentMappings::empty): split error and empty
	(SubstitutionArgumentMappings::find_symbol): helper
	(SubstitutionRef::get_num_lifetime_params): getter
	(SubstitutionRef::get_num_type_params): getter
	(SubstitutionRef::needs_substitution): extend to regions
	(SubstitutionRef::get_mappings_from_generic_args): helper
	(SubstitutionRef::infer_substitions): add regions
	* typecheck/rust-tyty-subst.h (class RegionParamList): region param handler
	* typecheck/rust-tyty.cc (BaseType::monomorphized_clone): add regions, resove lifetimes
	(InferType::default_type): add regions, resove lifetimes
	(FnType::clone): add regions, resove lifetimes
	(ReferenceType::ReferenceType): add regions
	(ReferenceType::get_region): getter
	(ReferenceType::clone): add regions
	* typecheck/rust-tyty.h: add regions, resove

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2024-02-03 15:25:30 +00:00
Jakub Dupak
909439d266 HIR: Add mising getter
gcc/rust/ChangeLog:

	* hir/tree/rust-hir-item.h: Add missing getter

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2024-02-03 15:25:30 +00:00
Jakub Dupak
3cfacb21cf TyTy: Region (lifetime) representation
gcc/rust/ChangeLog:

	* typecheck/rust-tyty-region.h: New file.

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2024-02-03 15:25:30 +00:00
Jakub Dupak
d42498b69e Typecheck: lifetime interning and resolution tool
gcc/rust/ChangeLog:

	* typecheck/rust-hir-type-check.h (class Lifetime): add interned lifetime class
	* typecheck/rust-typecheck-context.cc (TypeCheckContext::TypeCheckContext): add
	resolution tool
	(TypeCheckContext::intern_lifetime): add method to intern lifetime from tyctx
	(TypeCheckContext::lookup_lifetime): add method to lookup lifetime from tyctx
	(TypeCheckContext::intern_and_insert_lifetime): add a helper method

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2024-02-03 15:25:30 +00:00
Raiki Tamura
d6e10d2dab gccrs: Implement quick-check for Unicode
gcc/rust/ChangeLog:

	* rust-lang.cc (run_rust_tests): Add test.
	* rust-system.h: Add <algorithm>.
	* util/make-rust-unicode.py: Output NFC_Quick_Check table.
	* util/rust-codepoint.h (struct Codepoint): Add is_supplementary
	method.
	* util/rust-unicode-data.h: Generated.
	* util/rust-unicode.cc (binary_search_sorted_array): Removed.
	(lookup_cc): Remove namespace.
	(is_alphabetic): Use std::binary_search
	(nfc_quick_check): New function.
	(nfc_normalize): Use nfc_quick_check.
	(is_nfc_qc_maybe): New function.
	(is_nfc_qc_no): New function.
	(rust_nfc_qc_test): New test.
	* util/rust-unicode.h (is_nfc_qc_no): New function.
	(is_nfc_qc_maybe): New function.
	(enum class): New enum class.
	(nfc_quick_check): New function.
	(rust_nfc_qc_test): New test.

Signed-off-by: Raiki Tamura <tamaron1203@gmail.com>
2024-01-29 12:09:31 +00:00
Kushal Pal
bef49670f6 Parse normal functions with self parameter correctly
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>
2024-01-26 10:11:04 +00:00
Arthur Cohen
396565b340 gccrs: Fix output line ending patterns.
gcc/testsuite/ChangeLog:

	* rust/execute/torture/builtin_macros1.rs: Fix output pattern.
	* rust/execute/torture/coercion3.rs: Likewise.
	* rust/execute/torture/issue-2080.rs: Likewise.
	* rust/execute/torture/issue-2179.rs: Likewise.
	* rust/execute/torture/issue-2180.rs: Likewise.
	* rust/execute/torture/iter1.rs: Likewise.
2024-01-25 14:07:10 +00:00
Owen Avery
9a622724c3 Remove TraitImplItem
gcc/rust/ChangeLog:

	* ast/rust-ast-full-decls.h
	(class TraitImplItem): Remove forward declaration.
	(class AssociatedItem): Add forward declaration.
	* ast/rust-ast.h
	(class TraitImplItem): Remove.
	(class TraitItem): Inherit from AssociatedItem.
	(SingleASTNode::take_trait_impl_item):
	Return std::unique_ptr<AssociatedItem> instead of
	std::unique_ptr<TraitImplItem>.
	* ast/rust-item.h
	(class Function): Inherit from AssociatedItem instead of
	TraitImplItem.
	(class TypeAlias): Likewise.
	(class ConstantItem): Likewise.
	(class TraitImpl): Store items as AssociatedItem.
	* expand/rust-derive-clone.cc
	(DeriveClone::clone_fn): Return std::unique_ptr<AssociatedItem>.
	(DeriveClone::clone_impl): Take std::unique_ptr<AssociatedItem>.
	* expand/rust-derive-clone.h
	(DeriveClone::clone_fn): Return std::unique_ptr<AssociatedItem>.
	(DeriveClone::clone_impl): Take std::unique_ptr<AssociatedItem>.
	* expand/rust-expand-visitor.cc
	(ExpandVisitor::visit): Handle changes to
	SingleASTNode::take_trait_impl_item.
	* parse/rust-parse-impl.h
	(Parser::parse_impl): Parse TraitImpl as containing AssociatedItem.
	(Parser::parse_trait_impl_item): Return
	std::unique_ptr<AssociatedItem>.
	(Parser::parse_trait_impl_function_or_method): Likewise.
	* parse/rust-parse.h
	(Parser::parse_trait_impl_item): Return
	std::unique_ptr<AssociatedItem>.
	(Parser::parse_trait_impl_function_or_method): Likewise.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2024-01-24 09:19:59 +00:00
Robert Goss
7b203f66c1 Add improved error when no fields in initializer
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>
2024-01-23 16:13:10 +00:00
Jakub Dupak
1586de85db Test: check implemented for lifetime handling
gcc/testsuite/ChangeLog:

	* rust/compile/for_lifetimes.rs: New test.

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2024-01-22 10:05:47 +00:00
Jakub Dupak
83b8634024 AST: Fix for lifetime lowering
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>
2024-01-22 10:05:47 +00:00
Jakub Dupak
d7485af7f5 AST: Fix for lifetime parsing
gcc/rust/ChangeLog:

	* parse/rust-parse-impl.h (Parser::parse_where_clause): fix parsing
	(Parser::parse_where_clause_item): fix parsing
	(Parser::parse_type_bound_where_clause_item): fix parsing
	(Parser::parse_trait_bound): fix parsing
	* parse/rust-parse.h: fix parsing

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2024-01-22 10:05:47 +00:00
Jakub Dupak
ddb7f13402 Test: fix missing lifetime in a test
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>
2024-01-22 10:05:47 +00:00
Kushal Pal
184da62a4d Added newline to get more readable lexdump
Fixes #2783

gcc/rust/ChangeLog:

	* lex/rust-lex.cc (Lexer::dump_and_skip):
	Changed " " to '\n'

Signed-off-by: Kushal Pal <kushalpal109@gmail.com>
2024-01-18 16:31:11 +00:00
Owen Avery
43bb497160 Unify storage of associated items in SingleASTNode
gcc/rust/ChangeLog:

	* ast/rust-ast-fragment.cc
	(Fragment::assert_single_fragment): Update.

	* ast/rust-ast.h
	(class TraitImplItem): Move definition before that of TraitItem.
	(class TraitItem):
	Inherit from TraitImplItem instead of AssociatedItem.

	(class SingleASTNode): Unify handling of associated items.
	(SingleASTNode::take_assoc_item): Move from...
	(SingleASTNode::take_impl_item): ...here, but leave stub calling
	take_assoc_item behind.
	(SingleASTNode::take_trait_item):
	Cast associated item to TraitItem.
	(SingleASTNode::take_trait_impl_item):
	Cast associated item to TraitImplItem.

	* ast/rust-ast.cc
	(SingleASTNode::SingleASTNode):
	Unify handling of associated items.
	(SingleASTNode::operator=): Likewise.
	(SingleASTNode::accept_vis): Likewise.
	(SingleASTNode::is_error): Likewise.
	(SingleASTNode::as_string): Likewise.

	* ast/rust-item.h
	(class Function): Remove direct inheritence from AssociatedItem.
	(class ConstantItem): Likewise.
	* ast/rust-macro.h
	(class MacroInvocation):
	Remove direct inheritence from AssociatedItem and TraitImplItem.
2024-01-18 16:30:39 +00:00
Robert Goss
972a4f0205 Add improved error when a field is redefined in a struct constructor
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>
2024-01-18 14:53:11 +00:00
Arthur Cohen
5b40b9c7af rust_debug: Cast size_t values to unsigned long before printing.
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.
2024-01-18 08:47:25 +00:00
Kushal Pal
0cd26bd700 Handle async keyword for regular implementations
Fixes #2788

gcc/rust/ChangeLog:

	* parse/rust-parse-impl.h (Parser::parse_inherent_impl_item):
	Added switch-case for ASYNC token.

gcc/testsuite/ChangeLog:

	* rust/compile/issue-2788.rs: New test.

Signed-off-by: Kushal Pal <kushalpal109@gmail.com>
2024-01-17 13:24:04 +00:00
Kushal Pal
6d85a80bcf Fix inconsistent formatting
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>
2024-01-16 14:43:32 +00:00
Kushal Pal
f54df95296 Handle async functions in traits
Fixes #2785

gcc/rust/ChangeLog:

	* checks/errors/rust-ast-validation.cc (ASTValidation::visit):
	Added check for `async` functions inside trait.
	* parse/rust-parse-impl.h (Parser::parse_trait_item):
	Added switch-case for ASYNC token.

gcc/testsuite/ChangeLog:

	* rust/compile/issue-2785.rs: New test.

Signed-off-by: Kushal Pal <kushalpal109@gmail.com>
2024-01-16 14:43:32 +00:00
Arthur Cohen
3fcd86e404 expand: C++ify proc macro decls generation
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>.
2024-01-15 10:09:01 +00:00
Nirmal Patel
b864866f52 Handle newlines during string parsing while lexing
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>
2024-01-04 09:06:04 +00:00
Jakub Dupak
a12143b962 TyTy: Refactor FnType deprecated API
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>
2023-12-27 19:03:20 +00:00
Jakub Dupak
b9fccabd7b ast: Lower 'for' lifetimes
gcc/rust/ChangeLog:

	* hir/rust-ast-lower-type.cc (ASTLoweringType::visit): For lifetimes.

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2023-12-27 19:03:10 +00:00
Jakub Dupak
205151adeb ast: Infer static lifetime for const and static items
(probably incomplete propagation)

gcc/rust/ChangeLog:

	* hir/rust-ast-lower-base.cc (ASTLoweringBase::lower_lifetime): Propagate static
	requirement.
	* hir/rust-ast-lower-base.h: Propagate static requirement.
	* hir/rust-ast-lower-implitem.h: Propagate static requirement.
	* hir/rust-ast-lower-item.cc (ASTLoweringItem::visit): Propagate static requirement.
	* hir/rust-ast-lower-type.cc (ASTLoweringType::translate): Propagate static requirement.
	(ASTLoweringType::visit): Propagate static requirement.
	* hir/rust-ast-lower-type.h: Propagate static requirement.

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2023-12-27 19:03:10 +00:00
Jakub Dupak
4261ac4d8c ast: Full lifetime elision handling
gcc/rust/ChangeLog:

	* parse/rust-parse-impl.h (Parser::parse_generic_param): Lifetime elision control.
	(Parser::parse_lifetime_where_clause_item): Lifetime elision control.
	(Parser::parse_type_param_bound): Lifetime elision control.
	(Parser::parse_lifetime_bounds): Lifetime elision control.
	(Parser::parse_lifetime): Lifetime elision control.
	(Parser::parse_path_generic_args): Lifetime elision control.
	(Parser::parse_self_param): Lifetime elision control.
	(Parser::parse_break_expr): Lifetime elision control.
	(Parser::parse_continue_expr): Lifetime elision control.
	(Parser::parse_reference_type_inner): Lifetime elision control.
	* parse/rust-parse.h: Lifetime elision control.

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2023-12-27 19:03:10 +00:00
Jakub Dupak
77db7e8fb9 ast: Unify explicitly and implicitly elided lifettimes
gcc/rust/ChangeLog:

	* ast/rust-ast.h: Elided lifetime static constructor
	* ast/rust-type.h: Default lifetime to elided.
	* parse/rust-parse-impl.h (Parser::parse_lifetime_param): Use elided lifetime.
	(Parser::parse_lifetime): Use elided lifetime/
	(Parser::lifetime_from_token): Use elided lifetime.
	(Parser::parse_self_param): Use elided lifetime.
	(Parser::parse_reference_type_inner): Use elided lifetime.

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2023-12-27 19:03:10 +00:00
Jakub Dupak
e557052930 ast: Fix lifetime type parsing
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>
2023-12-27 19:03:10 +00:00
Kushal Pal
7bb5d5c9b2 Generate error for async trait fucntions
Fixes #2767

gcc/rust/ChangeLog:

	* checks/errors/rust-ast-validation.cc (ASTValidation::visit):
	Added check for `async` function inside trait.

gcc/testsuite/ChangeLog:

	* rust/compile/issue-2767.rs: New test.

Signed-off-by: Kushal Pal <kushalpal109@gmail.com>
2023-12-27 13:03:38 +00:00
Kushal Pal
b2e1131b48 Handle async qualifier inside trait
Fixes #2778

gcc/rust/ChangeLog:

	* parse/rust-parse-impl.h (Parser::parse_trait_impl_item):
	Handled `async` items

Signed-off-by: Kushal Pal <kushalpal109@gmail.com>
2023-12-27 13:03:38 +00:00
Raiki Tamura
d8c5cf1b1d gccrs: split rust-mangle.cc into two files
gcc/rust/ChangeLog:

	* Make-lang.in: Add .o files
	* backend/rust-mangle.cc (struct V0Path): moved to splitted files
	(v0_path): Likewise.
	(legacy_mangle_name): Likewise.
	(legacy_mangle_canonical_path): Likewise.
	(legacy_hash): Likewise.
	(v0_tuple_prefix): Likewise.
	(v0_numeric_prefix): Likewise.
	(v0_simple_type_prefix): Likewise.
	(v0_complex_type_prefix): Likewise.
	(v0_integer_62): Likewise.
	(v0_opt_integer_62): Likewise.
	(v0_disambiguator): Likewise.
	(v0_type_prefix): Likewise.
	(v0_generic_args): Likewise.
	(v0_identifier): Likewise.
	(v0_type_path): Likewise.
	(v0_function_path): Likewise.
	(v0_scope_path): Likewise.
	(v0_crate_path): Likewise.
	(v0_inherent_or_trait_impl_path): Likewise.
	(v0_closure): Likewise.
	(legacy_mangle_item): Likewise.
	(v0_mangle_item): Likewise.
	* backend/rust-mangle.h (legacy_mangle_item): Likewise.
	(v0_mangle_item): Likewise.
	* backend/rust-mangle-legacy.cc: New file.
	* backend/rust-mangle-v0.cc: New file.

Signed-off-by: Raiki Tamura <tamaron1203@gmail.com>
2023-12-26 22:17:38 +00:00
Jakub Dupak
03a38a4ff2 BIR: Cleanup
gcc/rust/ChangeLog:

	* checks/errors/borrowck/rust-bir-place.h: Cleanup.
	* checks/errors/borrowck/rust-borrow-checker.h: Cleanup.

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2023-12-19 17:23:09 +00:00
Jakub Dupak
eb7dffae86 TyTy: SubstitutionRef cast specialization
Allows skipping parent check when casting.

gcc/rust/ChangeLog:

	* typecheck/rust-tyty.h (BaseType::is): Cast API.
	(SubstitutionRef>): Cast API.
	(BaseType::as): Cast API.
	(BaseType::try_as): Cast API.

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2023-12-19 17:23:09 +00:00
Jakub Dupak
19a422d8b8 TyTy: Common interface for fucntion-like types
gcc/rust/ChangeLog:

	* typecheck/rust-tyty.h (class ClosureType): Inherit interface.
	(class FnPtr): Inherit interface.
	(class FnType): Inherit interface.
	(class CallableTypeInterface): New interface.
	(BaseType::is): Detect interface members API.

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2023-12-19 17:23:09 +00:00
Jakub Dupak
b05434dec8 TyTy: refactor to new API
gcc/rust/ChangeLog:

	* typecheck/rust-hir-type-check-type.cc (TypeCheckType::resolve_root_path): Refactor.

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2023-12-19 17:23:09 +00:00
Jakub Dupak
30b2e9c84d BIR: Fix missed nodiscard
gcc/rust/ChangeLog:

	* checks/errors/borrowck/rust-bir-builder-internal.h: Replace nodiscard.
	* checks/errors/borrowck/rust-bir-place.h: Replace nodiscard.

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2023-12-19 17:23:09 +00:00
Jakub Dupak
79a4ae0548 TyTy: Fix missed nodiscard
gcc/rust/ChangeLog:

	* typecheck/rust-tyty.h: Fix nodiscard to warn unused.

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2023-12-19 17:23:09 +00:00
Jakub Dupak
d2f33c584f HIR: add missing getters
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>
2023-12-19 17:23:09 +00:00
Arthur Cohen
f7127fc4a2 gccrs: refactor builtins initialization and attributes
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.

Also add attributes support through LANG_HOOKS_COMMON_ATTRIBUTE_TABLE
lang hook.

Most of these changes are based on D frontend.

gcc/rust/ChangeLog:

	* Make-lang.in (GRS_OBJS): Add rust-attribs.o.
	* backend/rust-builtins.cc (builtin_const, builtin_noreturn)
	(builtin_novops): Remove.
	(BuiltinsContext::lookup_simple_builtin): Adjust.
	(BuiltinsContext::setup_overflow_fns): Remove.
	(BuiltinsContext::define_function_type): Set builtin type to
	errormark so the builtin is considered unavailable.
	(BuiltinsContext::setup_math_fns): Remove.
	(BuiltinsContext::setup_atomic_fns): Remove.
	(build_c_type_nodes): Refactor based on D frontend.
	(BuiltinsContext::define_builtin_types): Likewise.
	(DEF_PRIMITIVE_TYPE): New.
	(DEF_FUNCTION_TYPE_0): New.
	(DEF_FUNCTION_TYPE_1): New.
	(DEF_FUNCTION_TYPE_2): New.
	(DEF_FUNCTION_TYPE_3): New.
	(DEF_FUNCTION_TYPE_4): New.
	(DEF_FUNCTION_TYPE_5): New.
	(DEF_FUNCTION_TYPE_6): New.
	(DEF_FUNCTION_TYPE_7): New.
	(DEF_FUNCTION_TYPE_8): New.
	(DEF_FUNCTION_TYPE_9): New.
	(DEF_FUNCTION_TYPE_10): New.
	(DEF_FUNCTION_TYPE_11): New.
	(DEF_FUNCTION_TYPE_VAR_0): New.
	(DEF_FUNCTION_TYPE_VAR_1): New.
	(DEF_FUNCTION_TYPE_VAR_2): New.
	(DEF_FUNCTION_TYPE_VAR_3): New.
	(DEF_FUNCTION_TYPE_VAR_4): New.
	(DEF_FUNCTION_TYPE_VAR_5): New.
	(DEF_FUNCTION_TYPE_VAR_6): New.
	(DEF_FUNCTION_TYPE_VAR_7): New.
	(DEF_FUNCTION_TYPE_VAR_11): New.
	(DEF_POINTER_TYPE): New.
	(BuiltinsContext::setup): Adjust.
	(BuiltinsContext::define_builtin_attributes): New.
	(DEF_ATTR_NULL_TREE): New.
	(DEF_ATTR_INT): New.
	(DEF_ATTR_STRING): New.
	(DEF_ATTR_IDENT): New.
	(DEF_ATTR_TREE_LIST): New.
	(handle_flags): Remove.
	(BuiltinsContext::define_builtins): New.
	(DEF_BUILTIN): New.
	(BuiltinsContext::define_builtin): Remove.
	(BuiltinsContext::register_rust_mappings): New. Add all missing
	builtins.
	(BuiltinsContext::lookup_gcc_builtin): Adjust.
	* backend/rust-builtins.h (DEF_PRIMITIVE_TYPE): New.
	(DEF_FUNCTION_TYPE_0): New.
	(DEF_FUNCTION_TYPE_1): New.
	(DEF_FUNCTION_TYPE_2): New.
	(DEF_FUNCTION_TYPE_3): New.
	(DEF_FUNCTION_TYPE_4): New.
	(DEF_FUNCTION_TYPE_5): New.
	(DEF_FUNCTION_TYPE_6): New.
	(DEF_FUNCTION_TYPE_7): New.
	(DEF_FUNCTION_TYPE_8): New.
	(DEF_FUNCTION_TYPE_9): New.
	(DEF_FUNCTION_TYPE_10): New.
	(DEF_FUNCTION_TYPE_11): New.
	(DEF_FUNCTION_TYPE_VAR_0): New.
	(DEF_FUNCTION_TYPE_VAR_1): New.
	(DEF_FUNCTION_TYPE_VAR_2): New.
	(DEF_FUNCTION_TYPE_VAR_3): New.
	(DEF_FUNCTION_TYPE_VAR_4): New.
	(DEF_FUNCTION_TYPE_VAR_5): New.
	(DEF_FUNCTION_TYPE_VAR_6): New.
	(DEF_FUNCTION_TYPE_VAR_7): New.
	(DEF_FUNCTION_TYPE_VAR_11): New.
	(DEF_POINTER_TYPE): New.
	(DEF_ATTR_NULL_TREE): New.
	(DEF_ATTR_INT): New.
	(DEF_ATTR_STRING): New.
	(DEF_ATTR_IDENT): New.
	(DEF_ATTR_TREE_LIST): New.
	* backend/rust-compile-intrinsic.cc (Intrinsics::compile): Add
	comment.
	(op_with_overflow_inner): Adjust.
	(copy_handler_inner): Adjust.
	(prefetch_data_handler): Adjust.
	(build_atomic_builtin_name): Adjust.
	(atomic_load_handler_inner): Adjust.
	(uninit_handler): Adjust.
	(move_val_init_handler): Adjust.
	(expect_handler_inner): Adjust.
	* rust-gcc.cc (fetch_overflow_builtins): Adjust.
	* rust-lang.cc (rust_localize_identifier): Adjust.
	(LANG_HOOKS_COMMON_ATTRIBUTE_TABLE): New.
	* rust-attribs.cc: New file.

gcc/testsuite/ChangeLog:

	* rust/compile/torture/intrinsics-4.rs: Adjust.
	* rust/compile/torture/intrinsics-math.rs: Adjust.
	* rust/execute/torture/atomic_load.rs: Adjust.
	* rust/execute/torture/atomic_store.rs: Adjust.
	* rust/compile/torture/intrinsics-1.rs: Removed.
	* rust/compile/torture/builtin_abort.rs: New test.
	* rust/execute/torture/builtin_abort.rs: New test.

Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
2023-12-18 10:21:50 +00:00
Pierre-Emmanuel Patry
6c8074688b Change cfg stripper to use default visitor
Cfg visitor used it's own visit patterns, this made the code longer than
required.

gcc/rust/ChangeLog:

	* expand/rust-cfg-strip.cc (CfgStrip::visit): Change calls from visitor
	to default visitor.
	(CfgStrip::go): Add call to visit crate.
	* expand/rust-cfg-strip.h (class CfgStrip): Update prototypes and
	remove empty ones.
	* ast/rust-ast-visitor.cc: add WhereClause condition check.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-12-14 15:39:07 +00:00
Pierre-Emmanuel Patry
61d4955bb7 Make expand visitor inherit from default visitor
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>
2023-12-11 12:27:32 +00:00
Pierre-Emmanuel Patry
1748242340 Make default resolver inherit from default visitor
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>
2023-12-11 10:57:43 +00:00
Owen Avery
1b6adb1a09 Allow enabling lang_items and no_core features
gcc/rust/ChangeLog:

	* checks/errors/rust-feature.cc
	(Feature::name_hash_map):
	Add entries for Name::LANG_ITEMS and Name::NO_CORE.
	* checks/errors/rust-feature.h
	(Feature::Name::LANG_ITEMS): New.
	(Feature::Name::NO_CORE): New.

gcc/testsuite/ChangeLog:

	* rust/compile/sized-stub.rs: New test.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-12-11 10:47:45 +00:00
Kushal Pal
358932954b Renamed WIN64 to WIN_64
Fixes issue #2768

gcc/rust/ChangeLog:

	* backend/rust-compile-base.cc (HIRCompileBase::setup_abi_options):
	Renamed `WIN64` to `WIN_64`
	* util/rust-abi.cc (get_abi_from_string): Likewise
	(get_string_from_abi): Likewise
	* util/rust-abi.h (enum ABI): Likewise

Signed-off-by: Kushal Pal <kushalpal109@gmail.com>
2023-12-11 10:47:07 +00:00
Nobel Singh
5e3a8751f2 Generate error for const trait functions
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>
2023-12-06 09:36:23 +00:00
Pierre-Emmanuel Patry
a48b4f860d Add a regression test for function body check
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>
2023-12-06 09:35:56 +00:00
Pierre-Emmanuel Patry
bc596aafbe Add validation for functions without body
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>
2023-12-06 09:35:56 +00:00
Pierre-Emmanuel Patry
6d179035cd Make function bodies truly optional
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>
2023-12-06 09:35:56 +00:00
Pierre-Emmanuel Patry
e876ff57d8 Add execution test for name resolution 2.0
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>
2023-12-01 13:10:14 +00:00
Pierre-Emmanuel Patry
dc962fa75f Add multiple regression test in name resolution
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>
2023-12-01 13:10:14 +00:00
Pierre-Emmanuel Patry
b831e5bf7b Make early name resolver inherit from default one
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>
2023-12-01 13:08:32 +00:00
Pierre-Emmanuel Patry
fba0a7b945 Change the attribute checker visitor to default one
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>
2023-12-01 10:24:45 +00:00
Pierre-Emmanuel Patry
48942f64d5 Make feature gate visitor inherit from default one
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>
2023-12-01 10:12:57 +00:00
Pierre-Emmanuel Patry
0d6d39457d Add regression test for const fn in trait
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>
2023-12-01 09:26:43 +00:00
Pierre-Emmanuel Patry
0ff1dcb343 Add AST validation check for const in trait
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>
2023-12-01 09:26:43 +00:00
Pierre-Emmanuel Patry
5210b2b07c Add a regression test for async const functions
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>
2023-12-01 09:14:09 +00:00
Pierre-Emmanuel Patry
af079a89f6 Add async const function ast validation pass
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>
2023-12-01 09:14:09 +00:00
Pierre-Emmanuel Patry
804830a025 Allow const and async specifiers in functions
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>
2023-12-01 09:14:09 +00:00
Pierre-Emmanuel Patry
6b9657a645 Split async and const function qualifiers
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>
2023-12-01 09:14:09 +00:00
Owen Avery
51f7bfcd86 Remove class AST::InherentImplItem
gcc/rust/ChangeLog:

	* ast/rust-ast-full-decls.h
	(class InherentImplItem): Remove.
	* ast/rust-ast.h
	(class InherentImplItem): Remove.
	(class SingleASTNode):
	Store pointer to AssociatedItem instead of InherentImplItem.

	* ast/rust-ast.cc
	(SingleASTNode::SingleASTNode):
	Use clone_associated_item instead of clone_inherent_impl_item.
	(SingleASTNode::operator=): Likewise.

	* ast/rust-item.h
	(class InherentImpl):
	Use AssociatedItem rather than InherentImplItem.
	(class Function): Likewise.
	(class ConstantItem): Likewise.
	* ast/rust-macro.h
	(class MacroInvocation): Likewise.
	* expand/rust-expand-visitor.cc
	(ExpandVisitor::visit): Likewise.
	* parse/rust-parse-impl.h
	(Parser::parse_impl): Likewise.
	(Parser::parse_inherent_impl_item): Likewise.
	(Parser::parse_inherent_impl_function_or_method): Likewise.
	* parse/rust-parse.h
	(Parser::parse_inherent_impl_item): Likewise.
	(Parser::parse_inherent_impl_function_or_method): Likewise.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-11-30 12:11:33 +00:00
Philip Herron
0ddb160c35 gccrs: Remove backend dependancy on resolution rib information
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>
2023-11-30 10:14:28 +00:00
Pierre-Emmanuel Patry
16d0a2d058 Add a regression test for unsafe module validation
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>
2023-11-29 23:37:08 +00:00
Pierre-Emmanuel Patry
26ac74e2a8 Emit an error on unsafe modules
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>
2023-11-29 23:37:08 +00:00
Pierre-Emmanuel Patry
3eb942857d Parse module safety
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>
2023-11-29 23:37:08 +00:00
Pierre-Emmanuel Patry
2ab87ee89a Add unsafety member to modules
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>
2023-11-29 23:37:08 +00:00
Owen Avery
2b75494008 Create base class for TupleStructItems and TuplePatternItems
gcc/rust/ChangeLog:

	* hir/tree/rust-hir-pattern.h
	(class TupleItems): New.
	(class TupleStructItems): Inherit from TupleItems.
	(class TuplePatternItems): Likewise.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-11-29 16:51:34 +00:00
Arthur Cohen
708920065e toplevel: Resolve use declarations
gcc/rust/ChangeLog:

	* resolve/rust-toplevel-name-resolver-2.0.cc
	(TopLevel::insert_or_error_out): New functions.
	(TopLevel::handle_use_dec): New function.
	(flatten_rebind): Likewise.
	(flatten_list): Likewise.
	(flatten_glob): Likewise.
	(flatten): Likewise.
	(TopLevel::visit): Visit various `use` declaration nodes.
	* resolve/rust-toplevel-name-resolver-2.0.h: Declare functions and
	visitors.
2023-11-28 15:33:11 +00:00
Arthur Cohen
c5c2cfffca early: Move use declaration resolving to TopLevel
gcc/rust/ChangeLog:

	* resolve/rust-early-name-resolver-2.0.cc
	(Early::visit): Remove visitors.
	* resolve/rust-early-name-resolver-2.0.h: Likewise.
2023-11-28 15:33:11 +00:00
Arthur Cohen
a1baaee2e9 ast: Add NodeId to UseTree base class
gcc/rust/ChangeLog:

	* ast/rust-item.h (class UseTree): Add `node_id` member.
2023-11-28 15:33:11 +00:00
Arthur Cohen
b7615465e0 toplevel: Add comment about running the collector twice
gcc/rust/ChangeLog:

	* resolve/rust-toplevel-name-resolver-2.0.cc
	(TopLevel::insert_or_error_out): Add documentation comment.
	(TopLevel::go): Likewise.
2023-11-28 15:33:11 +00:00
Arthur Cohen
435620aecf early: Resolve paths properly
gcc/rust/ChangeLog:

	* resolve/rust-early-name-resolver-2.0.cc
	(Early::insert_once): New function.
	(Early::visit): Likewise.
	* resolve/rust-early-name-resolver-2.0.h: Likewise.
2023-11-28 15:33:11 +00:00
Arthur Cohen
f9a5838435 late: Start storing mappings properly in the resolver
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.
2023-11-22 13:29:41 +00:00
Arthur Cohen
436d473f0c late: Start setting up builtin types
gcc/rust/ChangeLog:

	* resolve/rust-late-name-resolver-2.0.cc
	(Late::setup_builtin_types): New function.
	(Late::go): Setup builtin types.
	* resolve/rust-late-name-resolver-2.0.h:
	* resolve/rust-name-resolution-context.cc
	(NameResolutionContext::map_usage): New function.
	* resolve/rust-name-resolution-context.h: Likewise.
2023-11-22 13:29:41 +00:00
Arthur Cohen
4023eb2397 nr2.0: Store mappings in NameResolutionContext
gcc/rust/ChangeLog:

	* resolve/rust-name-resolution-context.h: Store a reference to the
	mappings.
	* resolve/rust-name-resolution-context.cc
	(NameResolutionContext::NameResolutionContext): Likewise.
2023-11-22 13:29:41 +00:00
Arthur Cohen
f9aa600dc0 toplevel: Use DefaultResolver for Function
gcc/rust/ChangeLog:

	* resolve/rust-toplevel-name-resolver-2.0.cc (TopLevel::visit): Use
	the DefaultResolver in the toplevel visitor.
2023-11-22 13:29:41 +00:00
Arthur Cohen
2bbff6da82 nr2.0: Add base for late name resolution
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.
2023-11-22 13:29:41 +00:00
Arthur Cohen
589d50bb4c ctx: Add Labels ForeverStack to the resolver.
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.
2023-11-22 13:29:41 +00:00
M V V S Manoj Kumar
50fe556cc3 Added support to Parse ASYNC function
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>
2023-11-21 17:49:55 +00:00
Pierre-Emmanuel Patry
34479e5427 Introduce a proper keyword list
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>
2023-11-21 12:45:32 +00:00
Pierre-Emmanuel Patry
897532ac16 Replace some weak keyword raw value with constexpr
Raw values may have typos or contain error, replacing those will
improve the codebase.

gcc/rust/ChangeLog:

	* ast/rust-ast-collector.cc (TokenCollector::visit): Replace raw value.
	* parse/rust-parse-impl.h (Parser::is_macro_rules_def): Likewise.
	(Parser::parse_item): Likewise.
	(Parser::parse_vis_item): Likewise.
	(Parser::parse_macro_rules_def): Likewise.
	(Parser::parse_union): Likewise.
	(Parser::parse_trait_impl_item): Likewise.
	(Parser::parse_stmt): Likewise.
	(Parser::parse_stmt_or_expr): Likewise.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-11-21 12:45:32 +00:00
Pierre-Emmanuel Patry
0f379bd8c9 Add a list of weak keyword
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>
2023-11-21 12:45:32 +00:00
Pierre-Emmanuel Patry
f4f42391af Replace some keyword raw values
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>
2023-11-21 12:45:32 +00:00
Pierre-Emmanuel Patry
27da3bb4a9 Add await keyword
The 2018 edition await keyword was missing from the keyword list.

gcc/rust/ChangeLog:

	* lex/rust-token.h (enum PrimitiveCoreType): Add await keyword
	definition.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-11-21 12:45:32 +00:00
Pierre-Emmanuel Patry
52a5b5d535 Treat underscore as a keyword
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>
2023-11-21 12:45:32 +00:00
Pierre-Emmanuel Patry
8433e828c0 Add edition separation for keywords
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>
2023-11-21 12:45:32 +00:00
Pierre-Emmanuel Patry
f211a42458 Replace TOK suffix with KW
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>
2023-11-21 12:45:32 +00:00
Pierre-Emmanuel Patry
546e25139b Add ast validation check on union variant number
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>
2023-11-21 12:27:21 +00:00
Pierre-Emmanuel Patry
0f9752e4b2 Add a test regular variadic functions errors
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>
2023-11-21 11:16:34 +00:00
Pierre-Emmanuel Patry
33965b86fe Emit an error on variadic non extern functions
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>
2023-11-21 11:16:34 +00:00
Pierre-Emmanuel Patry
b1b0de60cd Add check for associated items on auto traits
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>
2023-11-21 11:15:44 +00:00
Pierre-Emmanuel Patry
1786c4fcb1 Add a regression test for super trait on auto trait
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>
2023-11-21 11:15:44 +00:00
Pierre-Emmanuel Patry
e361eceb9d Reject auto traits with super trait
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>
2023-11-21 11:15:44 +00:00
Pierre-Emmanuel Patry
c500e77a52 Add regression test for generic auto traits
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>
2023-11-21 11:15:44 +00:00
Pierre-Emmanuel Patry
0437eb7efe Reject auto traits with generic parameters
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>
2023-11-21 11:15:44 +00:00
Pierre-Emmanuel Patry
5f0e77ad46 fixup: Ensure buffer allocation for bootstrap
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>
2023-11-21 10:17:09 +00:00
Arthur Cohen
1a758c3a9b forever stack: Remove development debug info
gcc/rust/ChangeLog:

	* resolve/rust-forever-stack.hxx: Remove debug log.
2023-11-21 10:10:42 +00:00
Arthur Cohen
b2a23e51a6 resolve: Format if properly
gcc/rust/ChangeLog:

	* resolve/rust-ast-resolve-path.cc (ResolvePath::resolve_path): Format.
2023-11-21 10:10:42 +00:00
Arthur Cohen
7bdcac804a foreverstack: Add to_rib method
gcc/rust/ChangeLog:

	* resolve/rust-forever-stack.h: New method.
	* resolve/rust-forever-stack.hxx: Likewise.
2023-11-21 10:10:42 +00:00
Arthur Cohen
8ef0e88fa4 foreverstack: Add to_canonical_path method
gcc/rust/ChangeLog:

	* resolve/rust-forever-stack.h: New method.
	* resolve/rust-forever-stack.hxx: Likewise.
2023-11-21 10:10:42 +00:00
Arthur Cohen
b075f3a210 forever stack: Improve resolve_path implementation
gcc/rust/ChangeLog:

	* resolve/rust-forever-stack.hxx: Do not copy segment when
	dereferencing iterator in `find_starting_point`.
2023-11-21 10:10:42 +00:00
Arthur Cohen
f6be8b0b56 forever stack: Fix resolve_path signature
gcc/rust/ChangeLog:

	* resolve/rust-forever-stack.h: Fix `ForeverStack::resolve_path`
	signature.
	* resolve/rust-forever-stack.hxx: Likewise.
	* resolve/rust-early-name-resolver-2.0.cc (Early::visit): Use new API.
	(Early::visit_attributes): Likewise.
2023-11-21 10:10:42 +00:00
Arthur Cohen
c996fa2f35 foreverstack: Specialize get for Namespace::Labels
gcc/rust/ChangeLog:

	* resolve/rust-forever-stack.hxx: Add specific behavior for
	`ForeverStack::get` when dealing with labels.
2023-11-21 10:10:42 +00:00
Arthur Cohen
4dc684ca80 forever-stack: Fix basic get logic
gcc/rust/ChangeLog:

	* resolve/rust-forever-stack.h: Improve resolve_path API.
	* resolve/rust-forever-stack.hxx: Likewise and fix implementation.
2023-11-21 10:10:42 +00:00
Arthur Cohen
2ff12aff4c rib: Add Namespace enum
gcc/rust/ChangeLog:

	* resolve/rust-rib.h: Add Namespace enum.
2023-11-21 10:10:42 +00:00
Arthur Cohen
1505bfb7ba ast: Change *Path nodes API
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.
2023-11-21 10:10:42 +00:00
Pierre-Emmanuel Patry
9735aca65a Add new test for parsing errors on self pointers
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>
2023-11-21 09:19:08 +00:00
Pierre-Emmanuel Patry
d2f2f68a8d Report self parameter parsing error kind
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>
2023-11-21 09:19:08 +00:00
Pierre-Emmanuel Patry
6f8b0ffd76 Fix error emission for self pointers
Self pointer checking loop condition was inverted, the latter was
therefore never executed.

gcc/rust/ChangeLog:

	* parse/rust-parse-impl.h (Parser::parse_self_param): Fix the loop
	exit condition.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-11-21 09:19:08 +00:00
Pierre-Emmanuel Patry
03c6549b2d Add a test to highlight public trait type parsing
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>
2023-11-21 09:11:38 +00:00
Pierre-Emmanuel Patry
889dec2e6a Add visibility to trait item
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>
2023-11-21 09:11:38 +00:00
Owen Avery
005d5e1f03 Adjust item kind enums for TupleStructItems and TuplePatternItems
gcc/rust/ChangeLog:

	* hir/tree/rust-hir-pattern.h
	(TupleStructItems::ItemType::RANGE): Rename to...
	(TupleStructItems::ItemType::RANGED): ...here.
	(TupleStructItems::ItemType::NO_RANGE): Rename to...
	(TupleStructItems::ItemType::MULTIPLE): ...here.

	(TuplePatternItems::TuplePatternItemType): Rename to...
	(TuplePatternItems::ItemType): ...here.

	: Handle renames.

	* backend/rust-compile-pattern.cc: Likewise.
	* typecheck/rust-hir-type-check-pattern.cc: Likewise.
	* checks/errors/borrowck/rust-bir-builder-pattern.h: Likewise.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-11-15 15:00:06 +00:00
Pierre-Emmanuel Patry
fd7d577a3e Add a new test for float disambiguation
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>
2023-11-15 14:32:30 +00:00
Pierre-Emmanuel Patry
e79301c4be Fix float lexing and tuple index disambiguation
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>
2023-11-15 14:32:30 +00:00
Raiki Tamura
31c5637378 gccrs: v0-mangle closures
gcc/rust/ChangeLog:

	* backend/rust-compile-expr.cc (CompileExpr::generate_closure_function):
	Fix reference to node.
	* backend/rust-mangle.cc (struct V0Path): Modified to accept closures.
	(v0_crate_path): Modified to accept closures.
	(v0_closure): New function to mangle closures.
	(v0_path): Modified to accept closures
	* util/rust-mapping-common.h (UNKNOWN_NODEID): Change to UINT32_MAX.
	(UNKNOWN_HIRID): Change to UINT32_MAX.

gcc/testsuite/ChangeLog:

	* rust/compile/v0-mangle2.rs: New test.

Signed-off-by: Raiki Tamura <tamaron1203@gmail.com>
2023-11-15 09:44:25 +00:00
Pierre-Emmanuel Patry
facd325f9e Move default visitor templates to header
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>
2023-11-15 09:18:47 +00:00
Pierre-Emmanuel Patry
20262dae7f Move templated functions to header file
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>
2023-11-15 09:18:47 +00:00
Owen Avery
9a5e6fa2d4 Bump actions/upload-artifact from v2 to v3
ChangeLog:

	* .github/workflows/ccpp.yml:
	Bump actions/upload-artifact from v2 to v3.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-11-15 09:17:31 +00:00
Pierre-Emmanuel Patry
fe0d34c277 Rework function special parameters
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>
2023-11-14 18:27:16 +00:00
Pierre-Emmanuel Patry
ca5ccfc43c Add new test for invalid variadics
Highlight invalid variadic filtering through the ast validation checker.

gcc/testsuite/ChangeLog:

	* rust/compile/invalid_variadics.rs: New test.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-11-14 18:27:16 +00:00
Pierre-Emmanuel Patry
5cf0fc3d59 Add multiple check on variadics position
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>
2023-11-14 18:27:16 +00:00
Pierre-Emmanuel Patry
87a1800aca Add trait context to ContextualASTVisitor
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>
2023-11-14 18:27:16 +00:00
Pierre-Emmanuel Patry
5f6c254c21 Add regression test for invalid label name
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>
2023-11-14 18:27:16 +00:00
Pierre-Emmanuel Patry
1596bbb282 Change error location for LoopLabel
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>
2023-11-14 18:27:16 +00:00
Pierre-Emmanuel Patry
f39de4f9e6 Add validation pass for label name
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>
2023-11-14 18:27:16 +00:00
Pierre-Emmanuel Patry
7d9052b36f Use a loop label in break expression
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>
2023-11-14 18:27:16 +00:00
Pierre-Emmanuel Patry
f46fd40194 Use keyword const values instead of raw values
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>
2023-11-14 18:27:16 +00:00
Pierre-Emmanuel Patry
8ec6996a74 Change keyword set to a map
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>
2023-11-14 18:27:16 +00:00
Pierre-Emmanuel Patry
fdb87a41ad Replace local keyword set with the utils
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>
2023-11-14 18:27:16 +00:00
Pierre-Emmanuel Patry
47662833de Add new keyword utility class
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>
2023-11-14 18:27:16 +00:00
Pierre-Emmanuel Patry
7582c73ba8 Add licence text and change header guard name
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>
2023-11-14 18:27:16 +00:00
Pierre-Emmanuel Patry
0789030ed4 Add regression test for lifetime name validation
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>
2023-11-14 18:27:16 +00:00
Pierre-Emmanuel Patry
afbc038914 Add lifetime name validation pass
Add lifetime name check in ast validation visitor.

gcc/rust/ChangeLog:

	* checks/errors/rust-ast-validation.cc (RS_TOKEN): Add keyword set.
	(RS_TOKEN_KEYWORD): Likewise.
	(ASTValidation::visit): Add validation on lifetime visit.
	* checks/errors/rust-ast-validation.h: Add function prototype.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-11-14 18:27:16 +00:00
Owen Avery
9864d7fe8a Replace AST::Method with existing AST::Function
gcc/rust/ChangeLog:

	* ast/rust-item.h
	(class Method): Remove.
	(Function::self_param): New.
	(Function::has_self_param): New.
	(Function::Function): Initialize self_param.
	(Function::operator=): Likewise.
	(Function::get_self_param): New.
	* ast/rust-ast.cc
	(Method::as_string): Remove.
	(Method::accept_vis): Remove.

	* ast/rust-ast-collector.cc
	(TokenCollector::visit):
	Remove AST::Method visitor, handle self_param in AST::Function visitor.
	* ast/rust-ast-collector.h
	(TokenCollector::visit): Remove AST::Method visitor.
	* ast/rust-ast-full-decls.h (class Method): Remove.

	* ast/rust-ast-visitor.h
	(ASTVisitor::visit): Remove AST::Method visitor.
	(DefaultASTVisitor::visit): Likewise.
	* ast/rust-ast-visitor.cc
	(DefaultASTVisitor::visit):
	Remove AST::Method visitor, handle self_param in AST::Function visitor.

	* checks/errors/rust-feature-gate.cc
	(FeatureGate::visit): Remove AST::Method visitor.
	* checks/errors/rust-feature-gate.h
	(FeatureGate::visit): Likewise..

	* expand/rust-cfg-strip.cc
	(CfgStrip::visit):
	Remove AST::Method visitor, handle self_param in AST::Function visitor.
	* expand/rust-cfg-strip.h
	(CfgStrip::visit): Remove AST::Method visitor.

	* expand/rust-derive-clone.cc
	(DeriveClone::clone_fn): Return AST::Function instead of AST::Method.
	* expand/rust-derive.h (DeriveVisitor::visit): Remove AST::Method visitor.

	* expand/rust-expand-visitor.cc
	(ExpandVisitor::visit):
	Remove AST::Method visitor, handle self_param in AST::Function visitor.
	* expand/rust-expand-visitor.h:
	(ExpandVisitor::visit): Remove AST::Method visitor.

	* hir/rust-ast-lower-base.cc (ASTLoweringBase::visit): Likewise.
	* hir/rust-ast-lower-base.h (ASTLoweringBase::visit): Likewise.

	* hir/rust-ast-lower-implitem.h
	(ASTLowerImplItem::visit):
	Remove AST::Method visitor, handle self_param in AST::Function visitor.

	* parse/rust-parse-impl.h: Include optional.h.
	(Parser::parse_function): Adjust AST::Function construction.
	(Parser::parse_inherent_impl_function_or_method):
	Construct AST::Function instead of AST::Method,
	adjust AST::Function construction.
	(Parser::parse_trait_impl_function_or_method): Likewise.
	(Parser::parse_method):
	Return std::unique_ptr<AST::Function> instead of AST::Method.

	* parse/rust-parse.h
	(Parser::parse_method): Likewise.

	* resolve/rust-ast-resolve-base.cc
	(ResolverBase::visit): Remove AST::Method visitor.
	* resolve/rust-ast-resolve-base.h
	(ResolverBase::visit): Likewise.

	* resolve/rust-ast-resolve-implitem.h
	(ResolveToplevelImplItem::visit): Likewise.

	* resolve/rust-ast-resolve-item.cc
	(ResolveItem::visit): Remove AST::Method visitor,
	handle self_param in AST::Function visitor.
	* resolve/rust-ast-resolve-item.h
	(ResolveItem::visit): Remove AST::Method visitor.

	* resolve/rust-default-resolver.cc
	(DefaultResolver::visit): Remove AST::Method visitor.
	* resolve/rust-default-resolver.h
	(DefaultResolver::visit): Likewise.

	* resolve/rust-early-name-resolver.cc
	(EarlyNameResolver::visit): Remove AST::Method visitor,
	handle self_param in AST::Function visitor.
	* resolve/rust-early-name-resolver.h
	(EarlyNameResolver::visit): Remove AST::Method visitor.

	* resolve/rust-toplevel-name-resolver-2.0.cc
	(TopLevel::visit): Likewise.
	* resolve/rust-toplevel-name-resolver-2.0.h
	(TopLevel::visit): Likewise.

	* util/rust-attributes.cc
	(AttributeChecker::visit): Likewise.
	* util/rust-attributes.h
	(AttributeChecker::visit): Likewise.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-11-09 21:02:22 +00:00
Pierre-Emmanuel Patry
25652e25b5 Add named variadic argument test
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>
2023-11-09 15:39:45 +00:00
Pierre-Emmanuel Patry
5b017d205a Add a new regression test for named variadics
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>
2023-11-09 15:39:45 +00:00
Pierre-Emmanuel Patry
6b500406a1 Parse named variadic parameters
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>
2023-11-09 15:39:45 +00:00
Pierre-Emmanuel Patry
a5edbe7783 Add a new regression test
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>
2023-11-09 15:39:45 +00:00
Pierre-Emmanuel Patry
44518d975c Fix multiple issues with variadic representation
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>
2023-11-09 15:39:45 +00:00
Pierre-Emmanuel Patry
b47dee55b1 Allow variadic NamedFunctionParam
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>
2023-11-09 15:39:45 +00:00
Pierre-Emmanuel Patry
56d6246dbb Add a function to check if a function is variadic
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>
2023-11-09 15:39:45 +00:00
Pierre-Emmanuel Patry
afb8e75e08 Parse variadic functions
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>
2023-11-09 15:39:45 +00:00
Pierre-Emmanuel Patry
203f192707 Change FunctionParam to represent variadic params
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>
2023-11-09 15:39:45 +00:00
Pierre-Emmanuel Patry
2c862b96f1 Add a new test for const without body
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>
2023-11-06 17:13:22 +00:00
Pierre-Emmanuel Patry
068753493f Make use of the Contextual visitor in validation
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>
2023-11-06 17:13:22 +00:00
Pierre-Emmanuel Patry
95325d7864 Add a new visitor that gathers context information
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>
2023-11-06 17:13:22 +00:00
Pierre-Emmanuel Patry
4068593c22 Add a default AST visitor
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>
2023-11-06 17:13:22 +00:00
Pierre-Emmanuel Patry
ebe2f98aa5 Add some reference getter
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>
2023-11-06 17:13:22 +00:00
Pierre-Emmanuel Patry
e7caf68fe0 Small fix to the ast collector visitor
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>
2023-11-06 17:13:22 +00:00
Pierre-Emmanuel Patry
fb346fab74 Emit an error on associated const without values
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>
2023-11-06 17:13:22 +00:00
Pierre-Emmanuel Patry
230cd6df82 Add call to ast validation checker
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>
2023-11-06 17:13:22 +00:00
Pierre-Emmanuel Patry
d8286cfb1f Add two new steps to compile process
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>
2023-11-06 17:13:22 +00:00
Pierre-Emmanuel Patry
b70b3d6110 Add ast validation checker
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>
2023-11-06 17:13:22 +00:00
Pierre-Emmanuel Patry
2c5d1113e3 Add more checks for expr value in early visitors
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>
2023-11-06 17:13:22 +00:00
Pierre-Emmanuel Patry
1f8a1bbff6 Move SingleASTNode implementation out of header
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>
2023-11-06 11:46:54 +00:00
Pierre-Emmanuel Patry
78ba5b74fb Add missing override specifier
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>
2023-11-06 11:46:54 +00:00
Pierre-Emmanuel Patry
e009d3df6a Add regression test for float literal tuple indices
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>
2023-11-06 10:08:09 +00:00
Pierre-Emmanuel Patry
7de72c6684 Fix token lexed as a float literal
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>
2023-11-06 10:08:09 +00:00
Jakub Dupak
0a2f8fc8f2 HIR: remove obsole double borrow member
gcc/rust/ChangeLog:

	* hir/rust-hir-dump.cc (Dump::visit): Remove obsolete member.
	* hir/tree/rust-hir-expr.h (class BorrowExpr): Remove obsolete member.
	* hir/tree/rust-hir.cc (BorrowExpr::as_string): Remove obsolete member.

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2023-11-02 13:41:31 +00:00
Jakub Dupak
16182dc050 HIR: fix typo
gcc/rust/ChangeLog:

	* hir/rust-ast-lower-expr.cc (ASTLoweringExpr::visit): Fix typo.

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2023-11-02 13:41:31 +00:00
Owen Avery
e489a694c7 Compile pattern match statements into conditional statements
gcc/rust/ChangeLog:

	* backend/rust-compile-expr.cc
	(patterns_mergeable): Remove.
	(struct PatternMerge): Remove.
	(sort_tuple_patterns): Remove.
	(simplify_tuple_match): Remove.
	(CompileExpr::visit): Modify compilation of MatchExpr.

	* backend/rust-compile-pattern.cc
	(CompilePatternCaseLabelExpr::visit): Replace with...
	(CompilePatternCheckExpr::visit): ...this.
	* backend/rust-compile-pattern.h
	(class CompilePatternCaseLabelExpr): Replace with...
	(class CompilePatternCheckExpr): ...this.

	* backend/rust-compile-type.cc
	(TyTyResolveCompile::get_implicit_enumeral_node_type):
	Make enumeral type equivalent to isize.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-11-01 16:46:52 +00:00
Pierre-Emmanuel Patry
5d622b6a6d Document proc macro token tree indices
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>
2023-10-31 11:39:08 +00:00
Pierre-Emmanuel Patry
4ac19a0501 Move proc macro builders to their own file
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>
2023-10-31 11:39:08 +00:00
Pierre-Emmanuel Patry
3c6aca6cc1 Add array length to the proc macro buffer
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>
2023-10-31 11:39:08 +00:00
Pierre-Emmanuel Patry
a1ed0756c0 Put common functions in their own namespace
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>
2023-10-31 11:39:08 +00:00
Pierre-Emmanuel Patry
aee54e56a9 Add macro buffer global variable export
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>
2023-10-31 11:39:08 +00:00
Pierre-Emmanuel Patry
5afa8b58b7 Add an explicit value to proc macro enum kind
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>
2023-10-31 11:39:08 +00:00
Pierre-Emmanuel Patry
b71fd2afa8 Change proc macro entrypoint
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>
2023-10-31 11:39:08 +00:00
Pierre-Emmanuel Patry
16c0f9c7fb Add utility function to build proc macro types
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>
2023-10-31 11:39:08 +00:00
Pierre-Emmanuel Patry
c5dc4b0a5f Add getters for proc macro mappings
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>
2023-10-31 11:39:08 +00:00
Pierre-Emmanuel Patry
573ca06d2a Collect procedural macros in the crate
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>
2023-10-31 11:39:08 +00:00
Pierre-Emmanuel Patry
80fe1c7b6f Reformat comments
gcc/rust/ChangeLog:

	* backend/rust-compile-base.cc (HIRCompileBase::setup_abi_options):
	Reformat uncorrectly formatted comments.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-10-31 11:39:08 +00:00
Pierre-Emmanuel Patry
e76f9223ed Add containers for proc macro collection mappings
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>
2023-10-31 11:39:08 +00:00
Pierre-Emmanuel Patry
b5118d1a6a Add const getter for tokentrees
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>
2023-10-31 11:39:08 +00:00
Pierre-Emmanuel Patry
327a285500 Change ABI setup and add gccrs_proc_macro attr
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>
2023-10-31 11:39:08 +00:00
Pierre-Emmanuel Patry
ff32f8fdce Make proc macro definition cdecl
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>
2023-10-31 11:39:08 +00:00
Jakub Dupak
2a1a37344f borrowck: Refactor and BIR improvements
gcc/rust/ChangeLog:

	* checks/errors/borrowck/rust-bir-builder-expr-stmt.cc (ExprStmtBuilder::setup_loop): Move.
	(ExprStmtBuilder::get_label_ctx): Move.
	(ExprStmtBuilder::get_unnamed_loop_ctx): Moved.
	(ExprStmtBuilder::visit): BIR improvements.
	* checks/errors/borrowck/rust-bir-builder-expr-stmt.h: Refactor.
	* checks/errors/borrowck/rust-bir-builder-internal.h (class LifetimeResolver):
	Refactor.
	(struct BuilderContext): Move.Refactor.
	(optional_from_ptr): Map on null ptr.
	* checks/errors/borrowck/rust-bir-builder-lazyboolexpr.h (class LazyBooleanExprBuilder):
	Refactor.
	* checks/errors/borrowck/rust-bir-builder-pattern.h: Refactor.
	* checks/errors/borrowck/rust-bir-builder-struct.h (class StructBuilder): Refactor.
	* checks/errors/borrowck/rust-bir-builder.h: Refactor.
	* checks/errors/borrowck/rust-bir-dump.cc (Dump::go): Refactor.
	(Dump::visit): Refactor.
	(Dump::visit_place): Refactor.
	(Dump::visit_move_place): Refactor.
	(Dump::visit_lifetime): Refactor.
	* checks/errors/borrowck/rust-bir-dump.h: Refactor.
	* checks/errors/borrowck/rust-bir-place.h: Refactor.

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2023-10-26 15:05:49 +00:00
Jakub Dupak
325dd9ed04 borrowck: Dev notes
gcc/rust/ChangeLog:

	* checks/errors/borrowck/dev-notes.md: New file.

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2023-10-26 15:05:49 +00:00
Jakub Dupak
df5b6a371d borrowck: Docs
gcc/rust/ChangeLog:

	* checks/errors/borrowck/bir-design-notes.md: New file.

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2023-10-26 15:05:49 +00:00
Jakub Dupak
449a375541 borrowck: Make goto explicit.
gcc/rust/ChangeLog:

	* checks/errors/borrowck/rust-bir-builder-expr-stmt.cc (ExprStmtBuilder::visit): Use goto.
	* checks/errors/borrowck/rust-bir-builder-internal.h: Explicit goto.
	* checks/errors/borrowck/rust-bir-builder-lazyboolexpr.h: Explicit goto.

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2023-10-26 15:05:49 +00:00
Jakub Dupak
587c3b2b91 borrowck: BIR continue
gcc/rust/ChangeLog:

	* checks/errors/borrowck/rust-bir-builder-expr-stmt.cc (ExprStmtBuilder::visit): Continue.
	(ExprStmtBuilder::setup_loop): Continue.

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2023-10-26 15:05:49 +00:00
Jakub Dupak
8aac66b06e borrowck: Dump: handle infinite loops
gcc/rust/ChangeLog:

	* checks/errors/borrowck/rust-bir-dump.cc (simplify_cfg): Detech infinite loops.

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2023-10-26 15:05:49 +00:00
Jakub Dupak
85f924f470 borrowck: BIR: handle break
gcc/rust/ChangeLog:

	* checks/errors/borrowck/rust-bir-builder-expr-stmt.cc (ExprStmtBuilder::visit): Push ctx.
	(ExprStmtBuilder::setup_loop): Common loop infractructure setup.
	* checks/errors/borrowck/rust-bir-builder-expr-stmt.h: Loop ctx.
	* checks/errors/borrowck/rust-bir-builder-internal.h (struct BuilderContext): Loop ctx.

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2023-10-26 15:05:49 +00:00
Jakub Dupak
97a0d40594 borrowck: Dump improve jumps
gcc/rust/ChangeLog:

	* checks/errors/borrowck/rust-bir-dump.cc (Dump::go): Improve jumps dump.
	(Dump::visit): Improve jumps dump.
	* checks/errors/borrowck/rust-bir-dump.h (class Dump): Improve jumps dump.

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2023-10-26 15:05:49 +00:00
Jakub Dupak
c92e110f06 borrowck: Dump: simplify cfg
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>
2023-10-26 15:05:49 +00:00
Jakub Dupak
8eb8474add borrowck: Dump: proper comma separation
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>
2023-10-26 15:05:49 +00:00
Jakub Dupak
f5b9bab688 borrowck: BIR dump
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>
2023-10-26 15:05:49 +00:00
Jakub Dupak
9a45588f39 borrowck: Create BIR builders (visitors)
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>
2023-10-26 15:05:49 +00:00
Jakub Dupak
dfafead7c2 borrowck: Create Borrow-checker IR (BIR)
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>
2023-10-26 15:05:49 +00:00
Jakub Dupak
dd23e4f8b9 borrowck: Execute only with CLI flag
gcc/rust/ChangeLog:

	* lang.opt: CLI flag.
	* rust-session-manager.cc (Session::compile_crate): Guard execution.

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2023-10-26 15:05:49 +00:00
Jakub Dupak
7ac6f9b4c7 borrowck: Add CLI option for borrowck
gcc/rust/ChangeLog:

	* checks/errors/borrowck/rust-borrow-checker.cc (BorrowChecker::BorrowChecker): Opt dump.
	(BorrowChecker::go): Opt dump.
	* checks/errors/borrowck/rust-borrow-checker.h (class BorrowChecker): Opt dump.
	* lang.opt: Add compile until borrowcheck.
	* rust-session-manager.cc (Session::enable_dump): Add BIR.
	(Session::compile_crate): Handle new options.
	* rust-session-manager.h (struct CompileOptions): Add BIR.

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2023-10-26 15:05:49 +00:00
Jakub Dupak
2bb559cea9 borrowck: Add initial structure for borrowchecking
gcc/rust/ChangeLog:

	* Make-lang.in: Build borrowck.
	* checks/errors/borrowck/rust-borrow-checker.cc: New file.
	* checks/errors/borrowck/rust-borrow-checker.h: New file.
	* checks/errors/borrowck/rust-function-collector.h: New file.

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2023-10-26 15:05:49 +00:00
Pierre-Emmanuel Patry
9a8b3eaedd Fix warning with overridden virtual methods
Overridden virtual methods were not marked as such.

gcc/rust/ChangeLog:

	* ast/rust-pattern.h: Add override modifier to overriding methods.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-10-24 07:33:57 +00:00
Pierre-Emmanuel Patry
eb393ac7a9 Add a new regression test for issue 2665
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>
2023-10-23 16:35:23 +00:00
Pierre-Emmanuel Patry
4f0da0ec6e Parse const with no value expression
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>
2023-10-23 16:35:23 +00:00
Jakub Dupak
af3071fc34 hir: Avoid copy in getter (PathPattern)
gcc/rust/ChangeLog:

	* hir/tree/rust-hir-path.h: Avoid copy in getter.

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2023-10-23 11:37:37 +00:00
Jakub Dupak
2e3e600360 hir: Rename ComoundAssignment getters
Use more a consistent name.

gcc/rust/ChangeLog:

	* backend/rust-compile-expr.cc (CompileExpr::visit): Rename method.
	* checks/errors/privacy/rust-privacy-reporter.cc (PrivacyReporter::visit): Rename method.
	* checks/errors/rust-const-checker.cc (ConstChecker::visit): Rename method.
	* checks/errors/rust-unsafe-checker.cc (UnsafeChecker::visit): Rename method.
	* hir/rust-hir-dump.cc (Dump::visit): Rename method.
	* hir/tree/rust-hir-expr.h: Rename method.
	* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit): Rename method.
	* typecheck/rust-tyty.h: Rename method.
2023-10-23 11:37:37 +00:00
Jakub Dupak
ba10e40be3 hir: Rename get_pattern_mappings method
Unify with the name used in Expr to allow convenient template over
everything that has mappings.

gcc/rust/ChangeLog:

	* backend/rust-compile-base.cc: Rename method.
	* backend/rust-compile-expr.cc (sort_tuple_patterns): Rename method.
	* backend/rust-compile-pattern.cc (CompilePatternCaseLabelExpr::visit): Rename method.
	(CompilePatternBindings::visit): Rename method.
	(CompilePatternLet::visit): Rename method.
	* backend/rust-compile-stmt.cc (CompileStmt::visit): Rename method.
	* backend/rust-compile-var-decl.h: Rename method.
	* hir/rust-ast-lower-pattern.cc (ASTLoweringPattern::translate): Rename method.
	* hir/rust-hir-dump.cc (Dump::visit): Rename method.
	* hir/tree/rust-hir-path.h: Rename method.
	* hir/tree/rust-hir-pattern.h: Rename method.
	* hir/tree/rust-hir.h: Rename method.
	* typecheck/rust-hir-type-check-pattern.cc (TypeCheckPattern::Resolve): Rename method.
	(TypeCheckPattern::visit): Rename method.
	(ClosureParamInfer::visit): Rename method.
	* typecheck/rust-hir-type-check-stmt.cc (TypeCheckStmt::visit): Rename method.
	* util/rust-hir-map.cc (Mappings::insert_hir_pattern): Rename method.

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2023-10-23 11:37:37 +00:00
Jakub Dupak
a6c535de75 hir: Add missing getter
gcc/rust/ChangeLog:

	* hir/tree/rust-hir-expr.h: Add getter for name.

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2023-10-23 11:37:37 +00:00
Jakub Dupak
ef4d1a8e16 ast: Handle tuplestruct pattern with indices
gcc/rust/ChangeLog:

	* hir/rust-ast-lower-pattern.cc (ASTLoweringPattern::visit): Implement for tuple pat.
	* resolve/rust-ast-resolve-pattern.cc (PatternDeclaration::visit): Implement for tupple pat.

gcc/testsuite/ChangeLog:

	* rust/compile/tupple_struct_pattern_tuple.rs: New test.

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2023-10-23 11:37:37 +00:00
Jakub Dupak
8c7bc537ef hir: Refactor - avoid copy in getter
gcc/rust/ChangeLog:

	* hir/tree/rust-hir-path.h: Avoid copy in getter.
	* hir/tree/rust-hir-pattern.h: Avoid copy in getter.
	* hir/tree/rust-hir.h: Avoid copy in getter.

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2023-10-23 11:37:37 +00:00
Owen Avery
4931eb8339 Make resolution of AssociatedItem instances polymorphic
gcc/rust/ChangeLog:

	* resolve/rust-ast-resolve-implitem.h
	(ResolveToplevelImplItem::go): Take AssociatedItem as parameter.
	(ResolveTopLevelTraitItems::go): Likewise.
	* resolve/rust-ast-resolve-item.cc
	(ResolveTraitItems::go): Likewise.
	(ResolveItem::resolve_impl_item): Likewise.
	(ResolveImplItems::go): Likewise.
	* resolve/rust-ast-resolve-item.h
	(ResolveTraitItems::go): Likewise.
	(ResolveItem::resolve_impl_item): Likewise.
	(ResolveImplItems::go): Likewise.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-10-20 12:24:38 +00:00
Owen Avery
2ef9814c6e Make lowering of AssociatedItem instances polymorphic
gcc/rust/ChangeLog:

	* hir/rust-ast-lower-implitem.h
	(ASTLoweringImplItem::translate): Take AssociatedItem as parameter.
	(ASTLoweringTraitItem::translate): Likewise.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-10-20 12:23:55 +00:00
Jakub Dupak
9a53cb5c38 compile: bail on labelled block
gcc/rust/ChangeLog:

	* backend/rust-compile-expr.cc (CompileExpr::visit): Bail on labelled block.

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2023-10-20 08:35:27 +00:00
Jakub Dupak
8ad583020b typecheck: add loop ctx for labelled block
gcc/rust/ChangeLog:

	* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit): Add loop ctx.

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2023-10-20 08:35:27 +00:00
Jakub Dupak
155458a125 resolve: Resolve labelled block
gcc/rust/ChangeLog:

	* resolve/rust-ast-resolve-expr.cc (ResolveExpr::visit): Resolve using loop logic.

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2023-10-20 08:35:27 +00:00
Jakub Dupak
483cb84277 hir: Lower labelled block
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.
2023-10-20 08:35:27 +00:00
Jakub Dupak
ee60ec5429 ast: Parse labelled block
gcc/rust/ChangeLog:

	* ast/rust-ast-builder.cc (AstBuilder::block): Add label arg to constructor call.
	* ast/rust-expr.h (class LoopLabel): Move before BlockExpr.
	(class BlockExpr): Add LoopLabel member.
	* expand/rust-derive-clone.cc (DeriveClone::clone_fn): Add label arg to constructor call.
	* parse/rust-parse-impl.h (Parser::parse_block_expr): Add label parameter.
	(Parser::parse_labelled_loop_expr): Add label arg to constructor call.
	* parse/rust-parse.h: Add label arg to constructor call.

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2023-10-20 08:35:27 +00:00
Owen Avery
cdd548b649 Create base class AssociatedItem
gcc/rust/ChangeLog:

	* ast/rust-ast.h
	(class AssociatedItem):
	New, based on TraitItem, InherentImplItem, and TraitImplItem classes.
	(class TraitItem): Inherit from AssociatedItem.
	(class InherentImplItem): Likewise.
	(class TraitImplItem): Likewise.
	* ast/rust-item.h
	(class Method): Update cloning functions.
	(class Function): Likewise.
	(class TypeAlias): Likewise.
	(class ConstantItem): Likewise.
	(class TraitItemFunc): Likewise.
	(class TraitItemMethod): Likewise.
	(class TraitItemConst): Likewise.
	(class TraitItemType): Likewise.
	* ast/rust-macro.h
	(class MacroInvocation): Likewise.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-10-18 09:42:39 +00:00
Raiki Tamura
b3f02d9c8c gccrs: Add tests for v0 mangling
gcc/rust/ChangeLog:

	* backend/rust-mangle.cc (v0_identifier): Fix broken encoding.
	(v0_scope_path): Modify paramter.
	(v0_path): Fix namespace for modules.

gcc/testsuite/ChangeLog:

	* rust/compile/v0-mangle1.rs: New test.

Signed-off-by: Raiki Tamura <tamaron1203@gmail.com>
2023-10-17 22:21:15 +00:00
Pierre-Emmanuel Patry
25eb53ddb8 Add new test for closure in closure parsing
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>
2023-10-17 22:19:46 +00:00
Pierre-Emmanuel Patry
0af6a9f106 Break OR tokens in closure parameter list context
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>
2023-10-17 22:19:46 +00:00
Pierre-Emmanuel Patry
813d0b956f Add new regression test for macro matcher behavior
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>
2023-10-17 22:18:41 +00:00
Pierre-Emmanuel Patry
94b1ff75bb Add path to macro fragment follow restrictions
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>
2023-10-17 22:18:41 +00:00
Pierre-Emmanuel Patry
c3b68b53f2 Add a new test for mbe named macro_rules
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>
2023-10-17 14:07:33 +00:00
Pierre-Emmanuel Patry
9762e0915b Add new regression test
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>
2023-10-17 14:07:33 +00:00
Pierre-Emmanuel Patry
3e3180abd5 Allow macro named macro_rules
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>
2023-10-17 14:07:33 +00:00
Pierre-Emmanuel Patry
0abe96a7d4 Add new regression test
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>
2023-10-17 13:19:47 +00:00
Pierre-Emmanuel Patry
442008fb55 Add a new regression test
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>
2023-10-17 13:19:47 +00:00
Pierre-Emmanuel Patry
66aa1799f5 Fix RangeFromExpr parsing in for loops
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>
2023-10-17 13:19:47 +00:00
Pierre-Emmanuel Patry
6658219e9b Add a new regression test for macro call "default"
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>
2023-10-17 11:47:29 +00:00
Pierre-Emmanuel Patry
948523ad7e Allow call to macro named "default" at item level
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>
2023-10-17 11:47:29 +00:00
Pierre-Emmanuel Patry
ba0fb415bf Add a new regression test
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>
2023-10-17 11:43:13 +00:00
Pierre-Emmanuel Patry
0ad1096952 Fix path expr segment parsing with generic path
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>
2023-10-17 11:43:13 +00:00
Owen Avery
c82bbb09b0 Replace get_pattern_node_id with get_node_id
gcc/rust/ChangeLog:

	* ast/rust-ast.h
	(Pattern::get_pattern_node_id): Rename to...
	(Pattern::get_node_id): ...here.
	* ast/rust-macro.h
	(MacroInvocation::get_pattern_node_id): Rename to...
	(MacroInvocation::get_node_id): ...here.
	* ast/rust-path.h
	(PathInExpression::get_pattern_node_id): Remove.
	(QualifiedPathInExpression::get_pattern_node_id): Remove.
	* ast/rust-pattern.h
	(LiteralPattern::get_pattern_node_id): Remove.
	(IdentifierPattern::get_pattern_node_id): Remove.
	(WildcardPattern::get_pattern_node_id): Remove.
	(RestPattern::get_pattern_node_id): Rename to...
	(RestPattern::get_node_id): ...here.
	(RangePattern::get_pattern_node_id): Remove.
	(ReferencePattern::get_pattern_node_id): Remove.
	(StructPattern::get_pattern_node_id): Remove.
	(TupleStructPattern::get_pattern_node_id): Remove.
	(TuplePattern::get_pattern_node_id): Remove.
	(GroupedPattern::get_pattern_node_id): Remove.
	(SlicePattern::get_pattern_node_id): Remove.
	(AltPattern::get_pattern_node_id): Remove.
	* resolve/rust-early-name-resolver.cc
	(EarlyNameResolver::visit):
	Use get_node_id instead of get_pattern_node_id.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-10-16 15:31:10 +00:00
Pierre-Emmanuel Patry
9ddb362bc0 Add regression test
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>
2023-10-16 15:30:23 +00:00
Pierre-Emmanuel Patry
abb2703e8f Add comma for expr delimiter to fix match arms
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>
2023-10-16 15:30:23 +00:00
Pierre-Emmanuel Patry
9d0a073583 Add regression test
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>
2023-10-16 15:29:50 +00:00
Pierre-Emmanuel Patry
1815409677 Fix pub unit type parsing
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>
2023-10-16 15:29:50 +00:00
Jakub Dupak
2b4eb390ec TyTy: use new subclass API
gcc/rust/ChangeLog:

	* typecheck/rust-tyty.cc (BaseType::is_unit): Refactor.
	(BaseType::satisfies_bound): Refactor.
	(BaseType::get_root): Refactor.
	(BaseType::destructure): Refactor.
	(BaseType::monomorphized_clone): Refactor.
	(BaseType::is_concrete): Refactor.
	(InferType::InferType): Refactor.
	(InferType::clone): Refactor.
	(InferType::apply_primitive_type_hint): Refactor.
	(StructFieldType::is_equal): Refactor.
	(ADTType::is_equal): Refactor.
	(handle_substitions): Refactor.
	(ADTType::handle_substitions): Refactor.
	(TupleType::TupleType): Refactor.
	(TupleType::is_equal): Refactor.
	(TupleType::handle_substitions): Refactor.

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2023-10-16 15:26:00 +00:00
Jakub Dupak
e3fcc884cf TyTy: TyTy improved subclass casting and checking
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>
2023-10-16 15:26:00 +00:00
Pierre-Emmanuel Patry
522528bce9 Add a regression test for global path parsing
Add a new test to highlight fix for #2649.

gcc/testsuite/ChangeLog:

	* rust/compile/parse_global_path_generic.rs: New test.
2023-10-16 14:40:06 +00:00
Pierre-Emmanuel Patry
a87e147ed5 Fix type param bound parsing with opening scope
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>
2023-10-16 14:40:06 +00:00
Pierre-Emmanuel Patry
08396ed5c2 Change debug log call to as_string function
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>
2023-10-16 14:40:06 +00:00
Raiki Tamura
b6a420f645 gccrs: Initial implementation of v0 mangling
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>
2023-10-16 13:57:24 +00:00
Owen Avery
288536f73b Rename cloning methods in TupleStructItems and TuplePatternItems
gcc/rust/ChangeLog:

	* hir/tree/rust-hir-pattern.h
	(TupleStructItems::clone_tuple_struct_items_impl): Rename to...
	(TupleStructItems::clone_tuple_items_impl): ...here.
	(TupleStructItemsNoRange::clone_tuple_struct_items_impl): Rename to...
	(TupleStructItemsNoRange::clone_tuple_items_impl): ...here.
	(TupleStructItemsRange::clone_tuple_struct_items_impl): Rename to...
	(TupleStructItemsRange::clone_tuple_items_impl): ...here.

	(TuplePatternItems::clone_tuple_pattern_items_impl): Rename to...
	(TuplePatternItems::clone_tuple_items_impl): ...here.
	(TuplePatternItemsMultiple::clone_tuple_pattern_items_impl): Rename to...
	(TuplePatternItemsMultiple::clone_tuple_items_impl): ...here.
	(TuplePatternItemsRanged::clone_tuple_pattern_items_impl): Rename to...
	(TuplePatternItemsRanged::clone_tuple_items_impl): ...here.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-10-16 13:28:36 +00:00
Owen Avery
464cfa56f3 Adjust methods for TuplePatternItems to match TupleStructItems
gcc/rust/ChangeLog:

	* hir/tree/rust-hir-pattern.h
	(TuplePatternItems::get_pattern_type): Rename to...
	(TuplePatternItems::get_item_type): ...here.
	(TuplePatternItemsMultiple::get_pattern_type): Rename to...
	(TuplePatternItemsMultiple::get_item_type): ...here.
	(TuplePatternItemsRanged::get_pattern_type): Rename to...
	(TuplePatternItemsRanged::get_item_type): ...here.

	* backend/rust-compile-expr.cc: Adjust calls to renamed methods.
	* backend/rust-compile-pattern.cc: Likewise.
	* typecheck/rust-hir-type-check-pattern.cc: Likewise.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-10-16 13:27:55 +00:00
Marc Poulhiès
7292e71b61 gccrs: minor changes (typo and minor refactor)
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>
2023-10-16 12:19:17 +00:00
Jakub Dupak
007166ca6c Add test for parser bug
gcc/testsuite/ChangeLog:

	* rust/compile/issue-2645.rs: New test.

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2023-10-05 14:02:18 +00:00
Jakub Dupak
10fd060d61 Fix parser bug on tupplestruct pattern
gcc/rust/ChangeLog:

	* parse/rust-parse-impl.h: Add missing token consumption

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2023-10-05 14:02:18 +00:00
Mohammed Rizan Farooqui
c7728c8020 Removed unnecessary comments
gcc/rust/ChangeLog:

	* expand/rust-macro-builtins.cc (MacroBuiltin::include_str_handler): Comment removed
	(MacroBuiltin::env_handler): Comment removed
	(MacroBuiltin::cfg_handler): Comment removed
	(MacroBuiltin::line_handler): Comment removed

Signed-off-by: Mohammed Rizan Farooqui <rizanfarooqui@gmail.com>
2023-10-05 07:03:48 +00:00
Jakub Dupak
1908504f62 Fix type confusion in coercion
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>
2023-10-03 07:02:40 +00:00
Pierre-Emmanuel Patry
289722166e Fix ICE when emitting an error during cfg strip
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>
2023-09-27 08:17:45 +00:00
Raiki Tamura
d0742b3695 Fix CanonicalPath for inherent impl
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>
2023-09-26 12:16:04 +00:00
Owen Avery
4d6a0094e9 Fix spelling
gcc/rust/ChangeLog:

	* ast/rust-expr.h: Fix spelling of "doesn't".
	* backend/rust-compile-expr.cc: Fix spelling of "accessors".
	* backend/rust-compile-implitem.h: Fix spelling of "normal".
	* backend/rust-constexpr.cc: Fix spelling of "actual".

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-09-19 17:10:06 +00:00
Marc Poulhiès
612a48a889 gccrs: Add debug helper to dump HIR
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>
2023-09-18 22:11:00 +00:00
Philip Herron
f9455fb91b gccrs: port over readonly_error from c-family for lvalue assignment checks
Fixes #2391

gcc/rust/ChangeLog:

	* Make-lang.in: fixup formatting
	* resolve/rust-ast-resolve-expr.cc (ResolveExpr::visit): remove old check
	* rust-session-manager.cc (Session::compile_crate): call new lint
	* resolve/rust-ast-verify-assignee.h: Removed.
	* checks/errors/rust-readonly-check.cc: New file.
	* checks/errors/rust-readonly-check.h: New file.

gcc/testsuite/ChangeLog:

	* rust/compile/wrong_lhs_assignment.rs: update error message
	* rust/compile/issue-2391.rs: New test.

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2023-09-17 20:05:46 +00:00
Muhammad Mahad
a2d5250162 gccrs: [E0617] attempt for invalid type variable in variadic function
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>
2023-09-17 15:57:23 +00:00
Philip Herron
e6b2c1aea4 gccrs: Remove HIR::ForLoopExpr
This will end up getting desugared into a LoopExpr with a MatchExpr body.

gcc/rust/ChangeLog:

	* backend/rust-compile-block.h: remove HIR::ForLoopExpr
	* backend/rust-compile-expr.h: likewise
	* checks/errors/privacy/rust-privacy-reporter.cc (PrivacyReporter::visit): likewise
	* checks/errors/privacy/rust-privacy-reporter.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
	* checks/lints/rust-lint-marklive.h: likewise
	* hir/rust-ast-lower.cc (ASTLoweringExprWithBlock::visit): likewise
	* hir/rust-hir-dump.cc (Dump::visit): likewise
	* hir/rust-hir-dump.h: likewise
	* hir/tree/rust-hir-expr.h (class ForLoopExpr): likewise
	* hir/tree/rust-hir-full-decls.h (class ForLoopExpr): likewise
	* hir/tree/rust-hir-visitor.h: likewise
	* hir/tree/rust-hir.cc (ForLoopExpr::as_string): likewise
	(ForLoopExpr::accept_vis): likewise
	* typecheck/rust-hir-type-check-expr.h: likewise

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2023-09-17 15:07:57 +00:00
Marc Poulhiès
4bf84ba154 gccrs: Minor typo fix
Fix varadic -> variadic

gcc/rust/ChangeLog:

	* backend/rust-compile-expr.cc (CompileExpr::visit): Fix typo in varIadic.
	* backend/rust-compile-type.cc (TyTyResolveCompile::visit): Likewise.
	* rust-backend.h (function_type_varadic): Rename into ...
	(function_type_variadic): ... this.
	* rust-gcc.cc (function_type_varadic): Rename into ...
	(function_type_variadic): ... this.
	* typecheck/rust-tyty-call.cc (TypeCheckCallExpr::visit): Likewise.
	* typecheck/rust-tyty.h (is_varadic): Renamed into ...
	(is_variadic): ... this.

Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
2023-09-17 14:12:07 +00:00
Pierre-Emmanuel Patry
2322c30f8c Add license text to libproc_macro rust interface
The license text was missing in rust files producing the libproc_macro
interface to the libproc_macro_internal library.

ChangeLog:

	* libgrust/libproc_macro/bridge.rs: Add license text.
	* libgrust/libproc_macro/bridge/ffistring.rs: Likewise.
	* libgrust/libproc_macro/bridge/group.rs: Likewise.
	* libgrust/libproc_macro/bridge/ident.rs: Likewise.
	* libgrust/libproc_macro/bridge/literal.rs: Likewise.
	* libgrust/libproc_macro/bridge/punct.rs: Likewise.
	* libgrust/libproc_macro/bridge/span.rs: Likewise.
	* libgrust/libproc_macro/bridge/token_stream.rs: Likewise.
	* libgrust/libproc_macro/group.rs: Likewise.
	* libgrust/libproc_macro/ident.rs: Likewise.
	* libgrust/libproc_macro/lib.rs: Likewise.
	* libgrust/libproc_macro/literal.rs: Likewise.
	* libgrust/libproc_macro/punct.rs: Likewise.
	* libgrust/libproc_macro/span.rs: Likewise.
	* libgrust/libproc_macro/token_stream.rs: Likewise.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-09-15 09:26:39 +00:00
Marc Poulhiès
70ef832659 gccrs: trivial typo fix.
Fix subsititions -> substitutions

gcc/rust/ChangeLog:

	* backend/rust-compile-base.cc (HIRCompileBase::compile_function):
	Fix typo in substitutions.
	(HIRCompileBase::resolve_method_address): Likewise.
	* backend/rust-compile-extern.h (CompileExternItem::visit):
	Likewise.
	* backend/rust-compile-implitem.cc (CompileTraitItem::visit):
	Likewise.
	* backend/rust-compile-intrinsic.cc (maybe_override_ctx):
	Likewise.
	* backend/rust-compile-item.cc (CompileItem::visit): Likewise.
	* backend/rust-compile-resolve-path.cc
	(HIRCompileBase::query_compile): Likewise.
	* typecheck/rust-coercion.cc (TypeCoercionRules::do_coercion):
	Likewise.
	* typecheck/rust-hir-type-check-item.cc
	(TypeCheckItem::ResolveImplBlockSelfWithInference): Likewise.
	* typecheck/rust-hir-type-check-path.cc (TypeCheckExpr::visit):
	Likewise.
	* typecheck/rust-hir-type-check-type.cc (TypeCheckType::visit):
	Likewise.
	* typecheck/rust-tyty.cc (BaseType::has_subsititions_defined):
	Renamed into ...
	(BaseType::has_substitutions_defined): ... this.
	(ADTType::is_equal): Fix typo in substitutions.
	(handle_substitions): Likewise.
	(FnType::is_equal): Likewise.
	(FnType::handle_substitions): Likewise.
	* typecheck/rust-tyty.h (has_subsititions_defined): Renamed into
	...
	(has_substitutions_defined): ... this.

Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
2023-09-14 22:36:22 +00:00
Owen Avery
c5c4897e8d Add intrinsics::assume
gcc/rust/ChangeLog:

	* backend/rust-compile-intrinsic.cc
	(get_identifier): Add declaration.
	(assume_handler): New.
	(generic_intrinsics): Add assume_handler entry.

gcc/testsuite/ChangeLog:

	* rust/compile/assume.rs: New test.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-09-14 21:26:27 +00:00
Owen Avery
bdc7b1fa35 Memoize Backend::wchar_type
gcc/rust/ChangeLog:

	* rust-gcc.cc
	(Backend::wchar_type): Store static wchar tree.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-09-14 21:12:42 +00:00
Owen Avery
a7ac7228e3 Remove unused complex number support
gcc/rust/ChangeLog:

	* rust-backend.h
	(complex_type): Remove.
	(complex_constant_expression): Remove.
	(real_part_expression): Remove.
	(imag_part_expression): Remove.
	(complex_expression): Remove.
	* rust-gcc.cc
	(complex_type): Remove.
	(complex_constant_expression): Remove.
	(real_part_expression): Remove.
	(imag_part_expression): Remove.
	(complex_expression): Remove.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-09-14 21:11:50 +00:00
Owen Avery
3f886d81b2 Use namespace definition to simplify function declarations
gcc/rust/ChangeLog:

	* rust-gcc.cc
	(namespace Backend):
	Use namespace definition instead of qualified names.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-09-13 10:59:53 +00:00
liushuyu
92efa02359 rust-compile-intrinsic: add copy intrinsics ...
... 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>
2023-09-13 10:21:09 +00:00
liushuyu
710e6f03b6 rust-builtins: add likely and unlikey intrinsics
gcc/rust/ChangeLog:
	* backend/rust-builtins.cc: add `expect` builtin definition.
	* backend/rust-compile-intrinsic.cc: add `likely` and `unlikely`
	intrinsics handler.

Signed-off-by: Zixing Liu <liushuyu011@gmail.com>
2023-09-13 10:21:09 +00:00
Owen Avery
c86181cf8c Rename "rust_error_codes.def" to "rust-error-codes.def"
gcc/rust/ChangeLog:

	* rust_error_codes.def: Moved to...
	* rust-error-codes.def: ...here...
	* rust-diagnostics.h: ...and update references.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-09-13 10:19:10 +00:00
Guillaume Gomez
a6e33926b1 Shorten make_unsigned_long_tree code and remove Backend::integer_constant_expression
gcc/rust/ChangeLog:

	* backend/rust-compile-intrinsic.cc: Simplify `make_unsigned_long_tree`
	* rust-backend.h: Remove `integer_constant_expression`
	* rust-gcc.cc: Remove `integer_constant_expression`
2023-09-12 10:21:55 +00:00
Dave Evans
d574b41ea1 Fix typechecking (and compilation) error for alt patterns in match expressions.
gcc/rust/ChangeLog:

	* backend/rust-compile-pattern.cc (CompilePatternCaseLabelExpr::visit):
	Add AltPattern visitor function
	* backend/rust-compile-pattern.h:
	Update CompilePatternCaseLabelExpr::visit(AltPattern&).
	* typecheck/rust-hir-type-check-pattern.cc (TypeCheckPattern::visit):
	Update AltPattern visitor

gcc/testsuite/ChangeLog:

	* rust/compile/issue-2431.rs: New test.

Signed-off-by: Dave Evans <dave@dmetwo.org>
2023-09-12 10:20:21 +00:00
Guillaume Gomez
1ee78b3892 Remove unused ctx argument in make_unsigned_long_tree function
gcc/rust/ChangeLog:

	* backend/rust-compile-intrinsic.cc: Remove unused argument
2023-09-12 08:21:37 +00:00
Arthur Cohen
da2203ca3f privacy: Uncomment test relying on #1257
gcc/testsuite/ChangeLog:

	* rust/compile/privacy6.rs: Uncomment commented out functions.
	* rust/compile/privacy9.rs: Fix unused variables.
2023-09-11 13:44:53 +00:00
Arthur Cohen
a804f98195 privacy: Add testcase for #1260
gcc/testsuite/ChangeLog:

	* rust/compile/privacy9.rs: New test.
2023-09-11 13:44:53 +00:00
Pierre-Emmanuel Patry
6a8b207b9e libgrust: Add dependency to libstdc++
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>
2023-09-11 12:53:53 +00:00
Muhammad Mahad
139f6c3875 gccrs: [E0599] Failed to resovle method implementation
gcc/rust/ChangeLog:

	* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit):
	Added new error message, rich location and error code.

gcc/testsuite/ChangeLog:

	* rust/compile/cfg2.rs: Updated according to new message.
	* rust/compile/issue-2139.rs: likewise.
	* rust/compile/issue-2190-1.rs: likewise.
	* rust/compile/method1.rs: likewise.

Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
2023-09-08 12:59:37 +00:00
Owen Avery
8da5a49a0e Convert class Backend into namespace
gcc/rust/ChangeLog:

	* rust-backend.h
	(class Backend): Convert to ...
	(namespace Backend): ... namespace.
	* rust-gcc.cc
	(Backend::Backend): Rename to ...
	(Backend::init): ... here.
	(rust_get_backend): Remove.

	* rust-session-manager.cc
	(rust_get_backend): Remove.
	(Session::init): Use Backend::init instead of rust_get_backend.
	(Session::compile_crate):
	Initialize Context without pointer to Backend.
	* rust-session-manager.h
	(Session::backend): Remove.
	* backend/rust-compile-context.cc
	(Context::Context): Remove pointer to Backend.
	* backend/rust-compile-context.h
	(class Context): Remove pointer to Backend, update function calls.

	* backend/rust-compile-base.cc: Update function calls.
	* backend/rust-compile-block.cc: Likewise.
	* backend/rust-compile-expr.cc: Likewise.
	* backend/rust-compile-extern.h: Likewise.
	* backend/rust-compile-fnparam.cc: Likewise.
	* backend/rust-compile-intrinsic.cc: Likewise.
	* backend/rust-compile-item.cc: Likewise.
	* backend/rust-compile-pattern.cc: Likewise.
	* backend/rust-compile-resolve-path.cc: Likewise.
	* backend/rust-compile-type.cc: Likewise.
	* backend/rust-compile-var-decl.h: Likewise.
	* backend/rust-compile.cc: Likewise.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-09-07 20:48:58 +00:00
Pierre-Emmanuel Patry
b6284bd9ff Unify raw attribute values
Attribute values were used as raw string, this is error prone and
makes renaming harder. Using a constexpr instead will leverage the power
of the compiler and emit an error when an incorrect builtin attribute
value is used.

gcc/rust/ChangeLog:

	* ast/rust-ast.cc (Attribute::check_cfg_predicate): Change raw
	string to constexpr call.
	(Attribute::separate_cfg_attrs): Likewise.
	* backend/rust-compile-base.cc (should_mangle_item): Likewise.
	(HIRCompileBase::setup_fndecl): Likewise.
	(HIRCompileBase::handle_cold_attribute_on_fndecl): Likewise.
	* checks/errors/privacy/rust-privacy-reporter.cc (find_proc_macro_attribute):
	Likewise.
	* checks/errors/rust-unsafe-checker.cc (check_target_attr):
	Likewise.
	* expand/rust-cfg-strip.cc (fails_cfg): Likewise.
	(fails_cfg_with_expand): Likewise.
	(expand_cfg_attrs): Likewise.
	* expand/rust-macro-builtins.cc: Likewise.
	* hir/rust-ast-lower-base.cc (ASTLoweringBase::handle_outer_attributes): Likewise.
	(ASTLoweringBase::lower_macro_definition): Likewise.
	* hir/rust-hir-dump.cc (Dump::visit): Likewise.
	* parse/rust-parse-impl.h (Parser::parse_doc_comment): Likewise.
	* parse/rust-parse.cc (extract_module_path): Likewise.
	* resolve/rust-early-name-resolver.cc (is_macro_use_module):
	Likewise.
	(EarlyNameResolver::visit): Likewise.
	* resolve/rust-toplevel-name-resolver-2.0.cc (is_macro_export):
	Likwise.
	* rust-session-manager.cc (Session::injection): Likewise.
	* typecheck/rust-hir-type-check-base.cc (TypeCheckBase::parse_repr_options): Likewise.
	* util/rust-attributes.cc (is_proc_macro_type): Likewise.
	(AttributeChecker::check_attribute): Likewise.
	(AttributeChecker::visit): Likewise.
	* util/rust-hir-map.cc (Mappings::insert_macro_def): Likewise.
	* util/rust-attribute-values.h: New file.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-09-07 14:08:53 +00:00
Owen Avery
e1d0b3cc02 Remove Gcc_backend
gcc/rust/ChangeLog:

	* rust-backend.h
	(Backend::Backend): New.
	(Backend::~Backend): Remove.
	(class Gcc_backend): Remove.
	* rust-gcc.cc
	(Gcc_backend::Gcc_backend): Rename to ...
	(Backend::Backend): ... here.
	(rust_get_backend): Construct Backend instead of Gcc_backend.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-09-07 06:33:01 +00:00
Pierre-Emmanuel Patry
4e7ae3938b Add missing linemap to lexer
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>
2023-09-06 11:50:30 +00:00
Pierre-Emmanuel Patry
241e53bc42 Add proc macro definition insertion
Insert proc macro definition from extern crates.

gcc/rust/ChangeLog:

	* resolve/rust-toplevel-name-resolver-2.0.cc (TopLevel::visit):
	Add proc macro definition insertion.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-09-06 11:50:30 +00:00
Pierre-Emmanuel Patry
9f7a9dfb26 Change proc macro mapping definition insertion
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>
2023-09-06 11:50:30 +00:00
Pierre-Emmanuel Patry
32fea09d30 Retrieve def for derive & attribute proc macros
Add definition retrieval for derive and attribute proc macro types.

gcc/rust/ChangeLog:

	* resolve/rust-early-name-resolver-2.0.cc (Early::visit_attributes):
	Add proc macro handle retrieval for attribute and derive proc macros.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-09-06 11:50:30 +00:00
Pierre-Emmanuel Patry
99276280aa Change proc macro definition lookup to optionals
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>
2023-09-06 11:50:30 +00:00
Pierre-Emmanuel Patry
53ad5220c4 Use optional for proc macro invocation lookup
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>
2023-09-06 11:50:30 +00:00
Owen Avery
97bd31cdaf Remove Backend::write_export_data
gcc/rust/ChangeLog:

	* rust-backend.h
	(Backend::write_export_data): Remove.
	* rust-gcc.cc
	(Backend::write_export_data): Remove.
2023-09-06 11:29:16 +00:00
Owen Avery
850e118c61 Move remaining expression-related methods into base class Backend
gcc/rust/ChangeLog:

	* rust-backend.h
	(Backend::real_part_expression): Make non-virtual.
	(Backend::imag_part_expression): Likewise.
	(Backend::complex_expression): Likewise.
	(Backend::convert_expression): Likewise.
	(Backend::struct_field_expression): Likewise.
	(Backend::compound_expression): Likewise.
	(Backend::conditional_expression): Likewise.
	(Backend::negation_expression): Likewise.
	(Backend::arithmetic_or_logical_expression): Likewise.
	(Backend::arithmetic_or_logical_expression_checked): Likewise.
	(Backend::comparison_expression): Likewise.
	(Backend::lazy_boolean_expression): Likewise.
	(Backend::constructor_expression): Likewise.
	(Backend::array_constructor_expression): Likewise.
	(Backend::array_initializer): Likewise.
	(Backend::array_index_expression): Likewise.
	(Backend::call_expression): Likewise.

	(Gcc_backend::real_part_expression): Remove.
	(Gcc_backend::imag_part_expression): Remove.
	(Gcc_backend::complex_expression): Remove.
	(Gcc_backend::convert_expression): Remove.
	(Gcc_backend::struct_field_expression): Remove.
	(Gcc_backend::compound_expression): Remove.
	(Gcc_backend::conditional_expression): Remove.
	(Gcc_backend::negation_expression): Remove.
	(Gcc_backend::arithmetic_or_logical_expression): Remove.
	(Gcc_backend::arithmetic_or_logical_expression_checked): Remove.
	(Gcc_backend::comparison_expression): Remove.
	(Gcc_backend::lazy_boolean_expression): Remove.
	(Gcc_backend::constructor_expression): Remove.
	(Gcc_backend::array_constructor_expression): Remove.
	(Gcc_backend::array_initializer): Remove.
	(Gcc_backend::array_index_expression): Remove.
	(Gcc_backend::call_expression): Remove.
	* rust-gcc.cc
	(Gcc_backend::real_part_expression): Rename to ...
	(Backend::real_part_expression): ... here.
	(Gcc_backend::imag_part_expression): Rename to ...
	(Backend::imag_part_expression): ... here.
	(Gcc_backend::complex_expression): Rename to ...
	(Backend::complex_expression): ... here.
	(Gcc_backend::convert_expression): Rename to ...
	(Backend::convert_expression): ... here.
	(Gcc_backend::struct_field_expression): Rename to ...
	(Backend::struct_field_expression): ... here.
	(Gcc_backend::compound_expression): Rename to ...
	(Backend::compound_expression): ... here.
	(Gcc_backend::conditional_expression): Rename to ...
	(Backend::conditional_expression): ... here.
	(Gcc_backend::negation_expression): Rename to ...
	(Backend::negation_expression): ... here.
	(Gcc_backend::arithmetic_or_logical_expression): Rename to ...
	(Backend::arithmetic_or_logical_expression): ... here.
	(Gcc_backend::arithmetic_or_logical_expression_checked): Rename to ...
	(Backend::arithmetic_or_logical_expression_checked): ... here.
	(Gcc_backend::comparison_expression): Rename to ...
	(Backend::comparison_expression): ... here.
	(Gcc_backend::lazy_boolean_expression): Rename to ...
	(Backend::lazy_boolean_expression): ... here.
	(Gcc_backend::constructor_expression): Rename to ...
	(Backend::constructor_expression): ... here.
	(Gcc_backend::array_constructor_expression): Rename to ...
	(Backend::array_constructor_expression): ... here.
	(Gcc_backend::array_initializer): Rename to ...
	(Backend::array_initializer): ... here.
	(Gcc_backend::array_index_expression): Rename to ...
	(Backend::array_index_expression): ... here.
	(Gcc_backend::call_expression): Rename to ...
	(Backend::call_expression): ... here.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-09-06 07:18:37 +00:00
Pierre-Emmanuel Patry
1588263d88 Clarify package import procedure
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>
2023-09-05 14:05:36 +00:00
Pierre-Emmanuel Patry
b2af85c218 resolver: Refactor macro insertion
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>
2023-09-05 14:05:36 +00:00
Pierre-Emmanuel Patry
f1527eff1e resolver: Refactor assertion
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>
2023-09-05 14:05:36 +00:00
Pierre-Emmanuel Patry
63af481671 Move extern crate resolving
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>
2023-09-05 14:05:36 +00:00
Pierre-Emmanuel Patry
774de7cc86 Supress error with proc macro crates
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>
2023-09-05 14:05:36 +00:00
Pierre-Emmanuel Patry
3742a491c8 Move proc macro definition to mappings
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>
2023-09-05 14:05:36 +00:00
Pierre-Emmanuel Patry
441309ca1f Add proc macro top level discovery
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>
2023-09-05 14:05:36 +00:00
Pierre-Emmanuel Patry
a3284ac1ba Change early resolver visit_attributes arguments
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>
2023-09-05 14:05:36 +00:00
Pierre-Emmanuel Patry
aa712861f4 Add getters for different types of proc macros
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>
2023-09-05 14:05:36 +00:00
Pierre-Emmanuel Patry
3c77182243 Add proc macros abstractions to crate structure
Add multiple setters for a crate object in order to add macro
abstractions previously introduced.

gcc/rust/ChangeLog:

	* ast/rust-ast.h (struct Crate): Add proc macro members.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-09-05 14:05:36 +00:00
Pierre-Emmanuel Patry
76263ca000 Add proc macro ast representation
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>
2023-09-05 14:05:36 +00:00
Pierre-Emmanuel Patry
32e861f100 Visit function and structure attributes
Add a simple attribute visit function and override StructStruct &
Function visit functions.

gcc/rust/ChangeLog:

	* resolve/rust-early-name-resolver-2.0.cc (Early::visit_attributes):
	Add function to handle attributes.
	(Early::visit): Override visitor functions.
	* resolve/rust-early-name-resolver-2.0.h: Add prototype.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-09-05 14:05:36 +00:00
Pierre-Emmanuel Patry
439508893b Parse unparsed derive tokenstreams
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>
2023-09-05 14:05:36 +00:00
Pierre-Emmanuel Patry
655da655c1 Ease some constraints on derive definition
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>
2023-09-05 14:05:36 +00:00
Pierre-Emmanuel Patry
7cfad27662 Change trait getter to return references
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>
2023-09-05 14:05:36 +00:00
Pierre-Emmanuel Patry
133d96c375 Set traits getter as member function
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>
2023-09-05 14:05:36 +00:00
Pierre-Emmanuel Patry
6eaf1b2878 Make is_builtin a member function
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>
2023-09-05 14:05:36 +00:00
Philip Herron
fe9e3efdc0 gccrs: Fix match-expression code-gen
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>
2023-09-04 16:56:29 +00:00
Owen Avery
997fc94e10 Move block-related methods into base class Backend
gcc/rust/ChangeLog:

	* rust-backend.h
	(Backend::block): Make non-virtual.
	(Backend::block_add_statements): Likewise.

	(Gcc_backend::block): Remove.
	(Gcc_backend::block_add_statements): Remove.
	* rust-gcc.cc
	(Gcc_backend::block): Rename to ...
	(Backend::block): ... here.
	(Gcc_backend::block_add_statements): Rename to ...
	(Backend::block_add_statements): ... here.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-09-04 16:55:06 +00:00
Pierre-Emmanuel Patry
52144478c6 libproc_macro: Split c++ and rust
Move the rust interface to the libproc_macro directory.

ChangeLog:

	* libgrust/libproc_macro_internal/rust/bridge.rs: Moved to...
	* libgrust/libproc_macro/bridge.rs: ...here.
	* libgrust/libproc_macro_internal/rust/bridge/ffistring.rs: Moved to...
	* libgrust/libproc_macro/bridge/ffistring.rs: ...here.
	* libgrust/libproc_macro_internal/rust/bridge/group.rs: Moved to...
	* libgrust/libproc_macro/bridge/group.rs: ...here.
	* libgrust/libproc_macro_internal/rust/bridge/ident.rs: Moved to...
	* libgrust/libproc_macro/bridge/ident.rs: ...here.
	* libgrust/libproc_macro_internal/rust/bridge/literal.rs: Moved to...
	* libgrust/libproc_macro/bridge/literal.rs: ...here.
	* libgrust/libproc_macro_internal/rust/bridge/punct.rs: Moved to...
	* libgrust/libproc_macro/bridge/punct.rs: ...here.
	* libgrust/libproc_macro_internal/rust/bridge/span.rs: Moved to...
	* libgrust/libproc_macro/bridge/span.rs: ...here.
	* libgrust/libproc_macro_internal/rust/bridge/token_stream.rs: Moved to...
	* libgrust/libproc_macro/bridge/token_stream.rs: ...here.
	* libgrust/libproc_macro_internal/rust/group.rs: Moved to...
	* libgrust/libproc_macro/group.rs: ...here.
	* libgrust/libproc_macro_internal/rust/ident.rs: Moved to...
	* libgrust/libproc_macro/ident.rs: ...here.
	* libgrust/libproc_macro_internal/rust/lib.rs: Moved to...
	* libgrust/libproc_macro/lib.rs: ...here.
	* libgrust/libproc_macro_internal/rust/literal.rs: Moved to...
	* libgrust/libproc_macro/literal.rs: ...here.
	* libgrust/libproc_macro_internal/rust/punct.rs: Moved to...
	* libgrust/libproc_macro/punct.rs: ...here.
	* libgrust/libproc_macro_internal/rust/span.rs: Moved to...
	* libgrust/libproc_macro/span.rs: ...here.
	* libgrust/libproc_macro_internal/rust/token_stream.rs: Moved to...
	* libgrust/libproc_macro/token_stream.rs: ...here.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-09-04 12:37:01 +00:00
Pierre-Emmanuel Patry
879915d4a5 Rename libproc_macro to libproc_macro_internal
The name was a bit misleading since libproc_macro is a rust library that
should we should be able to link against some rust code. This cpp
library was the layer below the libproc_macro library, the "real" gcc
libproc_macro act as a translation layer for the internal library.

gcc/rust/ChangeLog:

	* expand/rust-macro-expand.h: Change include directive with the
	new name.
	* expand/rust-proc-macro.h (RUST_PROC_MACRO_H): Likewise.
	* util/rust-hir-map.h: Likewise.
	* util/rust-token-converter.h: Likewise.
	* util/rust-token-converter.cc: Remove useless include
	directive.
	* Make-lang.in: Rename library.

ChangeLog:

	* libgrust/Makefile.am: Change library name.
	* libgrust/Makefile.in: Likewise.
	* libgrust/configure.ac: Likewise.
	* libgrust/configure: Regenerate.
	* libgrust/libproc_macro/Makefile.am: Moved to...
	* libgrust/libproc_macro_internal/Makefile.am: ...here.
	* libgrust/libproc_macro/Makefile.in: Moved to...
	* libgrust/libproc_macro_internal/Makefile.in: ...here.
	* libgrust/libproc_macro/bridge.h: Moved to...
	* libgrust/libproc_macro_internal/bridge.h: ...here.
	* libgrust/libproc_macro/ffistring.cc: Moved to...
	* libgrust/libproc_macro_internal/ffistring.cc: ...here.
	* libgrust/libproc_macro/ffistring.h: Moved to...
	* libgrust/libproc_macro_internal/ffistring.h: ...here.
	* libgrust/libproc_macro/group.cc: Moved to...
	* libgrust/libproc_macro_internal/group.cc: ...here.
	* libgrust/libproc_macro/group.h: Moved to...
	* libgrust/libproc_macro_internal/group.h: ...here.
	* libgrust/libproc_macro/ident.cc: Moved to...
	* libgrust/libproc_macro_internal/ident.cc: ...here.
	* libgrust/libproc_macro/ident.h: Moved to...
	* libgrust/libproc_macro_internal/ident.h: ...here.
	* libgrust/libproc_macro/literal.cc: Moved to...
	* libgrust/libproc_macro_internal/literal.cc: ...here.
	* libgrust/libproc_macro/literal.h: Moved to...
	* libgrust/libproc_macro_internal/literal.h: ...here.
	* libgrust/libproc_macro/proc_macro.cc: Moved to...
	* libgrust/libproc_macro_internal/proc_macro.cc: ...here.
	* libgrust/libproc_macro/proc_macro.h: Moved to...
	* libgrust/libproc_macro_internal/proc_macro.h: ...here.
	* libgrust/libproc_macro/punct.cc: Moved to...
	* libgrust/libproc_macro_internal/punct.cc: ...here.
	* libgrust/libproc_macro/punct.h: Moved to...
	* libgrust/libproc_macro_internal/punct.h: ...here.
	* libgrust/libproc_macro/registration.h: Moved to...
	* libgrust/libproc_macro_internal/registration.h: ...here.
	* libgrust/libproc_macro/rust/bridge.rs: Moved to...
	* libgrust/libproc_macro_internal/rust/bridge.rs: ...here.
	* libgrust/libproc_macro/rust/bridge/ffistring.rs: Moved to...
	* libgrust/libproc_macro_internal/rust/bridge/ffistring.rs: ...here.
	* libgrust/libproc_macro/rust/bridge/group.rs: Moved to...
	* libgrust/libproc_macro_internal/rust/bridge/group.rs: ...here.
	* libgrust/libproc_macro/rust/bridge/ident.rs: Moved to...
	* libgrust/libproc_macro_internal/rust/bridge/ident.rs: ...here.
	* libgrust/libproc_macro/rust/bridge/literal.rs: Moved to...
	* libgrust/libproc_macro_internal/rust/bridge/literal.rs: ...here.
	* libgrust/libproc_macro/rust/bridge/punct.rs: Moved to...
	* libgrust/libproc_macro_internal/rust/bridge/punct.rs: ...here.
	* libgrust/libproc_macro/rust/bridge/span.rs: Moved to...
	* libgrust/libproc_macro_internal/rust/bridge/span.rs: ...here.
	* libgrust/libproc_macro/rust/bridge/token_stream.rs: Moved to...
	* libgrust/libproc_macro_internal/rust/bridge/token_stream.rs: ...here.
	* libgrust/libproc_macro/rust/group.rs: Moved to...
	* libgrust/libproc_macro_internal/rust/group.rs: ...here.
	* libgrust/libproc_macro/rust/ident.rs: Moved to...
	* libgrust/libproc_macro_internal/rust/ident.rs: ...here.
	* libgrust/libproc_macro/rust/lib.rs: Moved to...
	* libgrust/libproc_macro_internal/rust/lib.rs: ...here.
	* libgrust/libproc_macro/rust/literal.rs: Moved to...
	* libgrust/libproc_macro_internal/rust/literal.rs: ...here.
	* libgrust/libproc_macro/rust/punct.rs: Moved to...
	* libgrust/libproc_macro_internal/rust/punct.rs: ...here.
	* libgrust/libproc_macro/rust/span.rs: Moved to...
	* libgrust/libproc_macro_internal/rust/span.rs: ...here.
	* libgrust/libproc_macro/rust/token_stream.rs: Moved to...
	* libgrust/libproc_macro_internal/rust/token_stream.rs: ...here.
	* libgrust/libproc_macro/span.cc: Moved to...
	* libgrust/libproc_macro_internal/span.cc: ...here.
	* libgrust/libproc_macro/span.h: Moved to...
	* libgrust/libproc_macro_internal/span.h: ...here.
	* libgrust/libproc_macro/tokenstream.cc: Moved to...
	* libgrust/libproc_macro_internal/tokenstream.cc: ...here.
	* libgrust/libproc_macro/tokenstream.h: Moved to...
	* libgrust/libproc_macro_internal/tokenstream.h: ...here.
	* libgrust/libproc_macro/tokentree.cc: Moved to...
	* libgrust/libproc_macro_internal/tokentree.cc: ...here.
	* libgrust/libproc_macro/tokentree.h: Moved to...
	* libgrust/libproc_macro_internal/tokentree.h: ...here.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-09-04 12:37:01 +00:00
Owen Avery
22a045be3c Move statement-related methods into base class Backend
gcc/rust/ChangeLog:

	* rust-backend.h
	(Backend::init_statement): Make non-virtual.
	(Backend::assignment_statement): Likewise.
	(Backend::return_statement): Likewise.
	(Backend::if_statement): Likewise.
	(Backend::loop_expression): Likewise.
	(Backend::exit_expression): Likewise.
	(Backend::compound_statement): Likewise.
	(Backend::statement_list): Likewise.
	(Backend::exception_handler_statement): Likewise.

	(Gcc_backend::init_statement): Remove.
	(Gcc_backend::assignment_statement): Remove.
	(Gcc_backend::return_statement): Remove.
	(Gcc_backend::if_statement): Remove.
	(Gcc_backend::compound_statement): Remove.
	(Gcc_backend::statement_list): Remove.
	(Gcc_backend::exception_handler_statement): Remove.
	(Gcc_backend::loop_expression): Remove.
	(Gcc_backend::exit_expression): Remove.
	* rust-gcc.cc
	(Gcc_backend::init_statement): Rename to ...
	(Backend::init_statement): ... here.
	(Gcc_backend::assignment_statement): Rename to ...
	(Backend::assignment_statement): ... here.
	(Gcc_backend::return_statement): Rename to ...
	(Backend::return_statement): ... here.
	(Gcc_backend::exception_handler_statement): Rename to ...
	(Backend::exception_handler_statement): ... here.
	(Gcc_backend::if_statement): Rename to ...
	(Backend::if_statement): ... here.
	(Gcc_backend::loop_expression): Rename to ...
	(Backend::loop_expression): ... here.
	(Gcc_backend::exit_expression): Rename to ...
	(Backend::exit_expression): ... here.
	(Gcc_backend::compound_statement): Rename to ...
	(Backend::compound_statement): ... here.
	(Gcc_backend::statement_list): Rename to ...
	(Backend::statement_list): ... here.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-09-04 08:32:18 +00:00
Owen Avery
d6caab05c7 Move function-related methods into base class Backend
gcc/rust/ChangeLog:

	* rust-backend.h
	(Backend::function): Make non-virtual.
	(Backend::function_defer_statement): Likewise.
	(Backend::function_set_parameters): Likewise.
	(Backend::write_global_definitions): Likewise.
	(Backend::write_export_data): Likewise.

	(Gcc_backend::function): Remove.
	(Gcc_backend::function_defer_statement): Remove.
	(Gcc_backend::function_set_parameters): Remove.
	(Gcc_backend::write_global_definitions): Remove.
	(Gcc_backend::write_export_data): Remove.
	* rust-gcc.cc
	(Gcc_backend::function): Rename to ...
	(Backend::function): ... here.
	(Gcc_backend::function_defer_statement):
	Fix a qualified lookup of Backend::label and rename to ...
	(Backend::function_defer_statement): ... here.
	(Gcc_backend::function_set_parameters) Rename to ...
	(Backend::function_set_parameters): ... here.
	(Gcc_backend::write_global_definitions): Rename to ...
	(Backend::write_global_definitions): ... here.
	(Gcc_backend::write_export_data): Rename to ...
	(Backend::write_export_data): ... here.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-09-04 08:31:39 +00:00
Muhammad Mahad
e5b5938b5a gccrs:[E0592] methods or associated functions with same name already defined
gcc/rust/ChangeLog:

	* typecheck/rust-hir-inherent-impl-overlap.h:
	Added rich location and errorcode.
	* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit):
	likewise.

gcc/testsuite/ChangeLog:

	* rust/compile/generics7.rs: Added Errorcode hint.
	* rust/compile/generics8.rs: Updated dejagnu comment.
	* rust/compile/issue-925.rs: Added Errorcode hint.

Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
2023-09-04 08:31:39 +00:00
Muhammad Mahad
699f525719 gccrs: [E0532] Pattern arm did not match expected kind
gcc/rust/ChangeLog:

	* typecheck/rust-hir-type-check-pattern.cc (TypeCheckPattern::visit):
	Added error code.

gcc/testsuite/ChangeLog:

	* rust/compile/issue-2029.rs:
	Updated for dejagnu testcase.

Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
2023-09-03 18:06:30 +00:00
Owen Avery
1f2dc6402d Move some simple expression-related methods into base class Backend
gcc/rust/ChangeLog:

	* rust-backend.h
	(Backend::zero_expression): Make non-virtual.
	(Backend::var_expression): Likewise.
	(Backend::integer_constant_expression): Likewise.
	(Backend::float_constant_expression): Likewise.
	(Backend::complex_constant_expression): Likewise.
	(Backend::string_constant_expression): Likewise.
	(Backend::char_constant_literal): Likewise.
	(Backend::wchar_constant_literal): Likewise.
	(Backend::boolean_constant_expression): Likewise.

	(Gcc_backend::zero_expression): Remove.
	(Gcc_backend::var_expression): Remove.
	(Gcc_backend::integer_constant_expression): Remove.
	(Gcc_backend::float_constant_expression): Remove.
	(Gcc_backend::complex_constant_expression): Remove.
	(Gcc_backend::string_constant_expression): Remove.
	(Gcc_backend::wchar_constant_expression): Remove.
	(Gcc_backend::char_constant_expression): Remove.
	(Gcc_backend::boolean_constant_expression): Remove.
	* rust-gcc.cc
	(Gcc_backend::zero_expression): Rename to ...
	(Backend::zero_expression): ... here.
	(Gcc_backend::var_expression): Rename to ...
	(Backend::var_expression): ... here.
	(Gcc_backend::integer_constant_expression): Rename to ...
	(Backend::integer_constant_expression): ... here.
	(Gcc_backend::float_constant_expression): Rename to ...
	(Backend::float_constant_expression): ... here.
	(Gcc_backend::complex_constant_expression): Rename to ...
	(Backend::complex_constant_expression): ... here.
	(Gcc_backend::string_constant_expression): Rename to ...
	(Backend::string_constant_expression): ... here.
	(Gcc_backend::wchar_constant_expression): Rename to ...
	(Backend::wchar_constant_expression): ... here.
	(Gcc_backend::char_constant_expression): Rename to ...
	(Backend::char_constant_expression): ... here.
	(Gcc_backend::boolean_constant_expression): Rename to ...
	(Backend::boolean_constant_expression): ... here.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-09-03 18:05:51 +00:00
Owen Avery
87037d678c Move variable-related methods into base class Backend
gcc/rust/ChangeLog:

	* rust-backend.h
	(Backend::global_variable): Make non-virtual.
	(Backend::global_variable_set_init): Likewise.
	(Backend::local_variable): Likewise.
	(Backend::parameter_variable): Likewise.
	(Backend::static_chain_variable): Likewise.
	(Backend::temporary_variable): Likewise.

	(Gcc_backend::global_variable): Remove.
	(Gcc_backend::global_variable_set_init): Remove.
	(Gcc_backend::local_variable): Remove.
	(Gcc_backend::parameter_variable): Remove.
	(Gcc_backend::static_chain_variable): Remove.
	(Gcc_backend::temporary_variable): Remove.

	(Gcc_backend::non_zero_size_type): Move to ...
	(Backend::non_zero_size_type): ... here.
	(Gcc_backend::convert_tree): Move to ...
	(Backend::convert_tree): ... here.

	* rust-gcc.cc
	(Gcc_backend::non_zero_size_type): Rename to ...
	(Backend::non_zero_size_type): ... here.
	(Gcc_backend::convert_tree): Rename to ...
	(Backend::convert_tree): ... here.
	(Gcc_backend::global_variable): Rename to ...
	(Backend::global_variable): ... here.
	(Gcc_backend::global_variable_set_init): Rename to ...
	(Backend::global_variable_set_init): ... here.
	(Gcc_backend::local_variable): Rename to ...
	(Backend::local_variable): ... here.
	(Gcc_backend::parameter_variable): Rename to ...
	(Backend::parameter_variable): ... here.
	(Gcc_backend::static_chain_variable): Rename to ...
	(Backend::static_chain_variable): ... here.
	(Gcc_backend::temporary_variable): Rename to ...
	(Backend::temporary_variable): ... here.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-09-03 18:05:16 +00:00
Muhammad Mahad
45d892b542 gccrs: [E0603] Use of private item outside scope
gcc/rust/ChangeLog:

	* checks/errors/privacy/rust-privacy-reporter.cc
	(PrivacyReporter::check_for_privacy_violation):
	Added errorcode & richlocation.

gcc/testsuite/ChangeLog:

	* rust/compile/privacy1.rs: Added errorcode.
	* rust/compile/privacy3.rs: likewise.
	* rust/compile/privacy4.rs: likewise.
	* rust/compile/privacy5.rs: likewise.

Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
2023-09-03 18:04:55 +00:00
Owen Avery
b1956a4f70 Move debug-related functions into base class Backend
gcc/rust/ChangeLog:

	* rust-backend.h
	(Backend::debug): Make non-virtual.
	(Backend::get_identifier_node): Likewise.

	(Gcc_backend::debug): Remove.
	(Gcc_backend::get_identifier_node): Remove.
	* rust-gcc.cc
	(Gcc_backend::debug): Rename to ...
	(Backend::debug): ... here.
	(Gcc_backend::get_identifier_node): Rename to ...
	(Backend::get_identifier_node): ... here.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-09-02 22:37:32 +00:00
Owen Avery
cc42db3e7f Improve type checking for if expressions
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>
2023-09-02 22:35:03 +00:00
Owen Avery
abf727d29e Move label-related functions into base class Backend
gcc/rust/ChangeLog:

	* rust-backend.h
	(Backend::label): Make non-virtual.
	(Backend::label_definition_statement): Likewise.
	(Backend::goto_statement): Likewise.
	(Backend::label_address): Likewise.

	(Gcc_backend::label): Remove.
	(Gcc_backend::label_definition_statement): Remove.
	(Gcc_backend::goto_statement): Remove.
	(Gcc_backend::label_address): Remove.
	* rust-gcc.cc
	(Gcc_backend::label): Rename to ...
	(Backend::label): ... here.
	(Gcc_backend::label_definition_statement): Rename to ...
	(Backend::label_definition_statement): ... here.
	(Gcc_backend::goto_statement): Rename to ...
	(Backend::goto_statement): ... here.
	(Gcc_backend::label_address): Rename to ...
	(Backend::label_address): ... here.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-09-02 22:31:54 +00:00
Owen Avery
20f83726d4 Bump our docker build's debian base image version to match rust:latest's
ChangeLog:

	* Dockerfile: Bump debian base image version from 11 to 12

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-09-02 22:31:36 +00:00
Owen Avery
2382da192c Fix ODR violations
gcc/rust/ChangeLog:

	* backend/rust-constexpr.cc
	(struct constexpr_fundef): Rename to ...
	(struct rust_constexpr_fundef): ... here.
	(struct constexpr_call): Rename to ...
	(struct rust_constexpr_call): ... here.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-09-02 22:31:04 +00:00
Raiki Tamura
6479fbfb22 gccrs: Add check for no_mangle attribute
gcc/rust/ChangeLog:

	* lex/rust-input-source.h: Move constants from here...
	* util/rust-codepoint.h (struct Codepoint): ... to here
	* util/rust-attributes.cc (check_no_mangle_function): New function.
	(AttributeChecker::visit): Use it.
	* util/rust-unicode.cc (is_ascii_only): New function.
	* util/rust-unicode.h (is_ascii_only): Likewise.
	* backend/rust-mangle.cc (legacy_mangle_name): Use it.
	* util/rust-punycode.cc (extract_basic_string): Likewise.
	* lex/rust-lex.cc (Lexer::parse_byte_char): Likewise.

Signed-off-by: Raiki Tamura <tamaron1203@gmail.com>
2023-09-01 12:03:36 +00:00
Muhammad Mahad
47d8541712 gccrs: [E0658] top level or-patterns are not allowed let binding
gcc/rust/ChangeLog:

	* hir/rust-ast-lower-pattern.cc (ASTLoweringPattern::visit):
	Added richlocation & error code.

gcc/testsuite/ChangeLog:

	* rust/compile/let_alt.rs: Updated comment.

Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
2023-09-01 12:02:56 +00:00
Owen Avery
acb4810bf0 Fix invalid call to vector::front in TypeBoundPredicate constructors
gcc/rust/ChangeLog:

	* typecheck/rust-hir-type-check-expr.cc
	(TypeCheckExpr::resolve_fn_trait_call): Add TODO comment.
	* typecheck/rust-tyty-bounds.cc
	(TypeBoundPredicate::TypeBoundPredicate):
	Add assertions, new error constructor.
	(TypeBoundPredicate::error): Use new error constructor.
	* typecheck/rust-tyty.h
	(struct TypeBoundPredicate::mark_is_error): New.
	(TypeBoundPredicate::TypeBoundPredicate):
	Add new error constructor.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-09-01 10:46:58 +00:00
Owen Avery
b3933cc6ea Bump docker/build-push-action to v4
ChangeLog:

	* .github/workflows/docker.yml:
	Bump docker/build-push-action from v2 to v4.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-09-01 10:46:42 +00:00
Owen Avery
5b2055d104 Move type-related functions into base class Backend
gcc/rust/ChangeLog:

	* rust-backend.h:
	(Backend::wchar_type): Make non-virtual.
	(Backend::get_pointer_size): Likewise.
	(Backend::raw_str_type): Likewise.
	(Backend::integer_type): Likewise.
	(Backend::float_type): Likewise.
	(Backend::complex_type): Likewise.
	(Backend::pointer_type): Likewise.
	(Backend::reference_type): Likewise.
	(Backend::immutable_type): Likewise.
	(Backend::function_type): Likewise.
	(Backend::function_type_varadic): Likewise.
	(Backend::function_ptr_type): Likewise.
	(Backend::struct_type): Likewise.
	(Backend::union_type): Likewise.
	(Backend::array_type): Likewise.
	(Backend::named_type): Likewise.
	(Backend::type_size): Likewise.
	(Backend::type_alignment): Likewise.
	(Backend::type_field_alignment): Likewise.
	(Backend::type_field_offset): Likewise.

	(Gcc_backend::wchar_type): Remove.
	(Gcc_backend::get_pointer_size): Remove.
	(Gcc_backend::raw_str_type): Remove.
	(Gcc_backend::integer_type): Remove.
	(Gcc_backend::float_type): Remove.
	(Gcc_backend::complex_type): Remove.
	(Gcc_backend::pointer_type): Remove.
	(Gcc_backend::reference_type): Remove.
	(Gcc_backend::immutable_type): Remove.
	(Gcc_backend::function_type): Remove.
	(Gcc_backend::function_type_varadic): Remove.
	(Gcc_backend::function_ptr_type): Remove.
	(Gcc_backend::struct_type): Remove.
	(Gcc_backend::union_type): Remove.
	(Gcc_backend::array_type): Remove.
	(Gcc_backend::named_type): Remove.
	(Gcc_backend::type_size): Remove.
	(Gcc_backend::type_alignment): Remove.
	(Gcc_backend::type_field_alignment): Remove.
	(Gcc_backend::type_field_offset): Remove.

	(Gcc_backend::fill_in_fields): Move to ...
	(Backend::fill_in_fields): ... here.
	(Gcc_backend::fill_in_array): Move to ...
	(Backend::fill_in_array): ... here.

	* rust-gcc.cc
	(Gcc_backend::wchar_type): Rename to ...
	(Backend::wchar_type): ... here.
	(Gcc_backend::get_pointer_size): Rename to ...
	(Backend::get_pointer_size): ... here.
	(Gcc_backend::raw_str_type): Rename to ...
	(Backend::raw_str_type): ... here.
	(Gcc_backend::integer_type): Rename to ...
	(Backend::integer_type): ... here.
	(Gcc_backend::float_type): Rename to ...
	(Backend::float_type): ... here.
	(Gcc_backend::complex_type): Rename to ...
	(Backend::complex_type): ... here.
	(Gcc_backend::pointer_type): Rename to ...
	(Backend::pointer_type): ... here.
	(Gcc_backend::reference_type): Rename to ...
	(Backend::reference_type): ... here.
	(Gcc_backend::immutable_type): Rename to ...
	(Backend::immutable_type): ... here.
	(Gcc_backend::function_type): Rename to ...
	(Backend::function_type): ... here.
	(Gcc_backend::function_type_varadic): Rename to ...
	(Backend::function_type_varadic): ... here.
	(Gcc_backend::function_ptr_type): Rename to ...
	(Backend::function_ptr_type): ... here.
	(Gcc_backend::struct_type): Rename to ...
	(Backend::struct_type): ... here.
	(Gcc_backend::union_type): Rename to ...
	(Backend::union_type): ... here.
	(Gcc_backend::fill_in_fields): Rename to ...
	(Backend::fill_in_fields): ... here.
	(Gcc_backend::array_type): Rename to ...
	(Backend::array_type): ... here.
	(Gcc_backend::fill_in_array): Rename to ...
	(Backend::fill_in_array): ... here.
	(Gcc_backend::named_type): Rename to ...
	(Backend::named_type): ... here.
	(Gcc_backend::type_size): Rename to ...
	(Backend::type_size): ... here.
	(Gcc_backend::type_alignment): Rename to ...
	(Backend::type_alignment): ... here.
	(Gcc_backend::type_field_alignment): Rename to ...
	(Backend::type_field_alignment): ... here.
	(Gcc_backend::type_field_offset): Rename to ...
	(Backend::type_field_offset): ... here.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-09-01 10:46:18 +00:00
Philip Herron
52cf9a9a33 gccrs: fix bug in the iterator testcase
gcc/testsuite/ChangeLog:

	* rust/compile/iterators1.rs: this should be casting to the $ty

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2023-08-31 21:25:00 +00:00
Philip Herron
ba792413ae gccrs: Fix move_val_init
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>
2023-08-31 21:25:00 +00:00
Philip Herron
113fe163a4 gccrs: Mark uninit-intrinsic as side-effects
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>
2023-08-31 21:25:00 +00:00
Philip Herron
fabb8b050e gccrs: Fix overflow intrinsic use before init
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>
2023-08-31 21:25:00 +00:00
Philip Herron
53e6e5be47 gccrs: Fix bad uninit intrinsic
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>
2023-08-31 21:25:00 +00:00
Pierre-Emmanuel Patry
4d49db696b Collect error instance instead of lambda functions
Use error object instead of lambda for error collection.

gcc/rust/ChangeLog:

	* resolve/rust-early-name-resolver-2.0.cc (Early::visit):
	Collect error instead of lambda.
	* resolve/rust-early-name-resolver-2.0.h (std::function<void):
	Remove type alias.
	* rust-diagnostics.h: Change collection type.
	* rust-session-manager.cc (Session::expansion): Change
	collection container.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-08-31 14:27:34 +00:00
Pierre-Emmanuel Patry
764a6c2703 Add regression test for nested macros
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>
2023-08-31 14:27:34 +00:00
Pierre-Emmanuel Patry
9ff9f4ec32 Resolve nested macro definition
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>
2023-08-31 14:27:34 +00:00
Owen Avery
a8876144d7 Handle gengtype annotations in backend/rust-tree.{cc,h}
gcc/rust/ChangeLog:

	* config-lang.in:
	Add "backend/rust-tree.h" and "backend/rust-tree.h" to gtfiles.
	* backend/rust-tree.cc: Include new header generated by gengtype.

	* backend/rust-tree.h
	(struct language_function): Add TODO.
	* rust-lang.cc:
	Include "rust-tree.h".
	(struct lang_type): Remove duplicate definition.
	(struct lang_decl): Likewise.
	(struct lang_identifier): Likewise.
	(struct language_function): Likewise.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-08-31 10:35:29 +00:00
Owen Avery
16939cc645 Bump docker workflow dependencies
ChangeLog:

	* .github/workflows/docker.yml: Bump docker action versions.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-08-31 10:35:13 +00:00
Owen Avery
83fd38dfe0 Use checkout@v3 in workflows
ChangeLog:

	* .github/workflows/bootstrap.yml: Bump checkout action version.
	* .github/workflows/ccpp.yml: Likewise.
	* .github/workflows/clang-format.yml: Likewise.
	* .github/workflows/docker.yml: Likewise.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-08-31 10:35:13 +00:00
Muhammad Mahad
1c4f312e49 gccrs: [E0769] Use of tuple struct/variant in struct variant
gcc/rust/ChangeLog:

	* typecheck/rust-hir-type-check-pattern.cc (TypeCheckPattern::visit):
	Added error code and rich location.

gcc/testsuite/ChangeLog:

	* rust/compile/match4.rs:
	Updated new error commment.

Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
2023-08-30 21:55:31 +00:00
Owen Avery
aea10051a6 Add missing gengtype related structs
gcc/rust/ChangeLog:

	* backend/rust-tree.h
	(struct rust_cp_class_binding): Fork from gcc/cp/name_lookup.h.
	(struct rust_cp_binding_level): Likewise.
	(struct named_label_entry): Remove declaration...
	(struct rust_named_label_entry): ... and fork definition from gcc/cp/decl.cc.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-08-29 09:44:27 +00:00
Muhammad Mahad
f2fc29d456 diagnostics: Added non-const rich_location * function
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>
2023-08-29 08:29:30 +00:00
Muhammad Mahad
e493d7e0db gccrs: [E0271] Type mismatch between associated type trait.
Added rich location and error code.

gcc/rust/ChangeLog:

	* typecheck/rust-tyty.cc (BaseType::satisfies_bound):
	Added errorcode and user-friendly error message.

gcc/testsuite/ChangeLog:

	* rust/compile/issue-1725-2.rs:
	Updated dejagnu message.

Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
2023-08-28 17:32:19 +00:00
Owen Avery
1b158384d6 Fork c++ resorting methods
gcc/rust/ChangeLog:

	* backend/rust-tree.cc
	(resort_data): Fork from c++ frontend.
	(resort_member_name_cmp): Likewise.
	(resort_type_member_vec): Likewise.
	* backend/rust-tree.h
	(resort_type_member_vec): Likewise.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-08-28 17:30:39 +00:00
Owen Avery
8e2e7fa021 Rename some structs to avoid ODR issues
gcc/rust/ChangeLog:

	* backend/rust-tree.cc
	(struct conv_type_hasher): Rename to ...
	(struct rust_conv_type_hasher): ... here.
	(struct cplus_array_hasher): Rename to ...
	(struct rust_cplus_array_hasher): ... here.
	(struct source_location_table_entry_hash): Rename to ...
	(struct rust_source_location_table_entry_hash): ... here.
	* backend/rust-tree.h
	(struct named_decl_hash): Rename to ...
	(struct rust_named_decl_hash): ... here.
	(struct cxx_saved_binding): Rename to ...
	(struct rust_cxx_saved_binding): ... here.
	(struct named_label_hash): Rename to ...
	(struct rust_named_label_hash): ... here.
	(struct tree_pair_s): Rename to ...
	(struct rust_tree_pair_s): ... here.
	(struct tree_pair_p): Rename to ...
	(struct rust_tree_pair_p): ... here.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-08-28 13:31:40 +00:00
Owen Avery
c727e23596 Namespace related tweaks
gcc/rust/ChangeLog:

	* backend/rust-tree.cc
	(Rust::gt_pch_nx): Move external function declaration ...
	(gt_pch_nx): ... out of Rust namespace.
	* backend/rust-tree.h
	(OVL_FIRST): Qualify function name.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-08-23 13:24:24 +00:00
Philip Herron
4baf8ab8f2 gccrs: Fix compilation of types which hold onto dangling infer vars
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>
2023-08-23 13:23:09 +00:00
Muhammad Mahad
a6134331c8 gccrs: Invalid order of generic parameters
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>
2023-08-23 10:02:15 +00:00
Owen Avery
ba4db84d49 Improve byte vector to string conversion
gcc/rust/ChangeLog:

	* expand/rust-macro-builtins.cc
	(MacroBuiltin::include_str_handler): Use vector::data.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-08-22 12:43:11 +00:00
Muhammad Mahad
8fcbb07fa7 gccrs: [E0573] Something other than type was used
gcc/rust/ChangeLog:

	* typecheck/rust-hir-type-check-type.cc:
	Added last variant name, errorcode & rich location. for enum candidates.

gcc/testsuite/ChangeLog:

	* rust/compile/issue-2479.rs: Updated comment.

Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
2023-08-22 12:42:59 +00:00
Owen Avery
3196ca3526 Remove stmt_tree and dependency on cp_token_cache
gcc/rust/ChangeLog:

	* backend/rust-tree.h
	(struct stmt_tree_s): Remove.
	(typedef stmt_tree): Remove.
	(c_language_function::x_stmt_tree): Remove.
	(saved_scope::x_stmt_tree): Remove.
	(lang_decl_fn::pending_inline_p): Remove.
	(lang_decl_fn::spare): Adjust size.
	(lang_decl_fn::pending_inline_info): Remove.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-08-21 11:45:45 +00:00
Owen Avery
79a7f07ff6 Handle gengtype annotations in rust-constexpr.cc
gcc/rust/ChangeLog:

	* backend/rust-constexpr.cc:
	Include gt-rust-rust-constexpr.h.
	(struct constexpr_call_hasher): Rename to ...
	(struct rust_constexpr_call_hasher): ... here.
	(struct constexpr_fundef_hasher): Rename to ...
	(struct rust_constexpr_fundef_hasher): ... here.
	* config-lang.in: Add rust-constexpr.cc to gtfiles.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-08-18 14:43:59 +00:00
Raiki Tamura
b1dd53faa1 gccrs: Add punycode encoding to v0 mangling
gcc/rust/ChangeLog:

	* backend/rust-mangle.cc (v0_add_identifier): Added punycode encoding
	(v0_mangle_item): Likewise.
	* lex/rust-lex.cc (assert_source_content): Change type
	(test_buffer_input_source): Change type
	(test_file_input_source): Change type
	* resolve/rust-ast-resolve-toplevel.h: fix typo
	* rust-session-manager.cc (Session::load_extern_crate): fix typo
	* util/rust-canonical-path.h: fix typo
	* util/rust-hir-map.cc (NodeMapping::get_error): fix typo
	(Mappings::Mappings): fix typo
	* util/rust-mapping-common.h (UNKNOWN_CREATENUM): fix typo
	(UNKNOWN_CRATENUM): Change 0 to UINT32_MAX

Signed-off-by: Raiki Tamura <tamaron1203@gmail.com>
2023-08-18 10:52:24 +00:00
Muhammad Mahad
879a62f50d gccrs: [E0391] Detected type dependency cycle
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>
2023-08-18 10:49:02 +00:00
Muhammad Mahad
8ac2e43fb2 gccrs: Non-allowed default type paramters
gcc/rust/ChangeLog:

	* hir/rust-ast-lower-item.cc (ASTLoweringItem::visit):
	Added more helpful error message.

gcc/testsuite/ChangeLog:

	* rust/compile/generics10.rs: for dejagnu.

Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
2023-08-17 13:33:38 +00:00
Muhammad Mahad
d4bf5e3f23 gccrs: [E0034] found more than one items for method
Multiple items found with same prototype.
Fixes: https://github.com/Rust-GCC/gccrs/issues/2366

gcc/rust/ChangeLog:

	* typecheck/rust-hir-path-probe.h:
	Fixes issue & added rich location message.
	* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit):
	Added rich location and error code.

gcc/testsuite/ChangeLog:

	* rust/compile/generics6.rs: Updated dejagnu comment.
	* rust/compile/generics7.rs: likewise.
	* rust/compile/issue-925.rs: likewise.

Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
2023-08-17 13:33:23 +00:00
Pierre-Emmanuel Patry
9ef8689c7f Add a regression test for decimal lexing
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>
2023-08-17 10:01:43 +00:00
Pierre-Emmanuel Patry
c5326821d3 fix lexer exponent output on tuple indices
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>
2023-08-17 10:01:43 +00:00
Muhammad Mahad
294c5906d7 gccrs: [E0164] Neither tuple struct nor tuple variant used as a pattern
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>
2023-08-17 10:00:47 +00:00
Muhammad Mahad
b9ae3541a1 gccrs: [E0535] Unknown argument given to inline attribute
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>
2023-08-17 09:55:39 +00:00
Muhammad Mahad
3ef836fb09 gccrs: [E0380] Use of auto trait with method or associated item
gcc/rust/ChangeLog:

	* parse/rust-parse-impl.h (Parser::parse_trait):
	added errorcode & updated error message.

gcc/testsuite/ChangeLog:

	* rust/compile/auto_trait_invalid.rs:
	Updated comment.

Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
2023-08-17 09:53:37 +00:00
Muhammad Mahad
0110145c1d gccrs: [E0753] Use of inner doc comment in invalid context
gcc/rust/ChangeLog:

	* parse/rust-parse-impl.h (Parser::parse_outer_attribute):
	Added errorcode & updated error function.

gcc/testsuite/ChangeLog:

	* rust/compile/bad_inner_doc.rs:
	Updated comment to pass testcase.

Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
2023-08-17 09:53:20 +00:00
Muhammad Mahad
efa3041b4b gccrs: Support for rich-loc & errorcode in parser error
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>
2023-08-16 11:03:52 +00:00
Muhammad Mahad
5545c75fa5 gccrs: [E0534] inline attribute was malformed
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>
2023-08-16 09:28:41 +00:00
Arthur Cohen
74b27ac68d diagnostics: Fix mismatch between new[] and free
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
2023-08-14 00:30:37 +00:00
Raiki Tamura
87c5cc1516 gccrs: Type annotation for make-unicode-data.py
gcc/rust/ChangeLog:

	* util/make-rust-unicode.py: Add type annotation

Signed-off-by: Raiki Tamura <tamaron1203@gmail.com>
2023-08-12 19:26:35 +00:00
Philip Herron
b1dd4236cf gccrs: improve name mangling hash
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>
2023-08-12 19:25:52 +00:00
Philip Herron
1d52917eb8 gccrs: simplify matching possible candidates
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>
2023-08-12 19:25:45 +00:00
Marc Poulhiès
086b7f9c9a gccrs: Cleanup HIR dump
visit_field() correctly handles empty unique_ptr<> and displays "none".

gcc/rust/ChangeLog:

	* hir/rust-hir-dump.cc (Dump::visit): Remove useless if/else
	already handled by visit_field.

Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
2023-08-12 17:22:19 +00:00
Owen Avery
c10d668b50 Add missing CHECKING_P guard to rust-punycode.cc
gcc/rust/ChangeLog:

	* util/rust-punycode.cc: Add CHECKING_P guard.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-08-12 17:15:29 +00:00
Raiki Tamura
56680955c4 gccrs: Fix legacy mangling to use Unicode escape
gcc/rust/ChangeLog:

	* backend/rust-mangle.cc (legacy_mangle_name): Use Unicode escape

Signed-off-by: Raiki Tamura <tamaron1203@gmail.com>
2023-08-12 17:15:17 +00:00
Philip Herron
9ae3c203f7 gccrs: remove horrible hack in solving complex generics on impl blocks
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>
2023-08-12 17:14:52 +00:00
Owen Avery
2691b54498 Use MacroInvocLexerBase in ProcMacroInvocLexer
gcc/rust/ChangeLog:

	* expand/rust-proc-macro-invoc-lexer.cc
	(ProcMacroInvocLexer::skip_token): Remove.
	* expand/rust-proc-macro-invoc-lexer.h:
	Include "rust-macro-invoc-lexer.h".
	(class ProcMacroInvocLexer):
	Extend MacroInvocLexerBase.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-08-11 13:41:52 +00:00
Raiki Tamura
2b1d37ced3 gccrs: clean up Codepoint and InputSource
gcc/rust/ChangeLog:

	* lex/rust-codepoint.h: Moved to...
	* util/rust-codepoint.h: ...here.
	* lex/rust-input-source.h: Add missing license
	* util/rust-unicode.cc: Add missing license
	* util/rust-punycode.cc (extract_basic_string): Remove constant

Signed-off-by: Raiki Tamura <tamaron1203@gmail.com>
2023-08-11 13:38:25 +00:00
Arthur Cohen
969439fa8e macro-expand: Keep optional references to last_{def, invoc}
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.
2023-08-11 13:32:52 +00:00
Marc Poulhiès
5712d7d383 gccrs: Adjust HIR dump for IfExpr and IfExprConseqElse
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>
2023-08-11 10:46:39 +00:00
Muhammad Mahad
e55113ea2b gccrs: [E0054/E0604/E0620/E0606] TypeCasting ErrorCodes
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>
2023-08-10 09:37:44 +00:00
Muhammad Mahad
152eb85264 gccrs: [E0541] Use of unknown meta item
gcc/rust/ChangeLog:

	* backend/rust-compile-base.cc:
	Added ErrorCode.

gcc/testsuite/ChangeLog:

	* rust/compile/attr_deprecated_2.rs:
	Updated comment to pass the testcase.

Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
2023-08-10 09:35:22 +00:00
Muhammad Mahad
2da2efa10f gccrs: [E0703] Use of Invalid ABI
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>
2023-08-10 09:35:08 +00:00
Owen Avery
e4da7e5d6b Basic formatting/comment fixes
gcc/rust/ChangeLog:

	* ast/rust-ast-collector.cc: Adjust formatting.
	* checks/errors/rust-feature-gate.cc: Add trailing newline.
	* rust-diagnostics.h: Remove old comment.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-08-10 09:34:35 +00:00
Owen Avery
cd9a6e3bb5 Remove unneeded references to "this" in backend methods
gcc/rust/ChangeLog:

	* rust-gcc.cc
	(Gcc_backend::struct_type): Remove references to "this".
	(Gcc_backend::union_type): Likewise.
	(Gcc_backend::array_type): Likewise.
	(Gcc_backend::wchar_constant_expression): Likewise.
	(Gcc_backend::convert_expression): Likewise.
	(Gcc_backend::constructor_expression): Likewise.
	(Gcc_backend::array_initializer): Likewise.
	(Gcc_backend::assignment_statement): Likewise.
	(Gcc_backend::global_variable): Likewise.
	(Gcc_backend::temporary_variable): Likewise.
	(Gcc_backend::function_defer_statement): Likewise.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-08-10 09:33:06 +00:00
Raiki Tamura
ebd449ca97 gccrs: Add function Rust::encode_punycode
gcc/rust/ChangeLog:

	* Make-lang.in: Add rust-punycode.o.
	* rust-lang.cc (run_rust_tests): Add selftest.
	* util/rust-punycode.cc: New file.
	* util/rust-punycode.h: New file.

Signed-off-by: Raiki Tamura <tamaron1203@gmail.com>
2023-08-09 12:41:01 +00:00
Muhammad Mahad
67d1f4a53e gccrs: [E0308] array misamatch types
gcc/rust/ChangeLog:

	* backend/rust-compile.cc (HIRCompileBase::verify_array_capacities):
	Added ErrorCode.

gcc/testsuite/ChangeLog:

	* rust/compile/arrays2.rs: changed comment to pass
	testcase.

Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
2023-08-09 12:05:21 +00:00
Muhammad Mahad
a58485620d gccrs: [E0282] type annotations needed
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>
2023-08-09 11:49:06 +00:00
Owen Avery
0d678b209d Move Backend::error_variable to Bvariable::error_variable
gcc/rust/ChangeLog:

	* rust-backend.h
	(Backend::error_variable): Remove.
	(Gcc_backend::error_variable): Move to ...
	* rust-gcc.cc
	(Bvariable::error_variable): ... here ...
	* rust-gcc.h
	(Bvariable::error_variable): ... and declare here.
	(Gcc_backend::global_variable): Update error_variable call.
	(Gcc_backend::local_variable): Likewise.
	(Gcc_backend::parameter_variable): Likewise.
	(Gcc_backend::static_chain_variable): Likewise.
	(Gcc_backend::temporary_variable): Likewise.
	* backend/rust-compile-extern.h
	(CompileExternItem::visit): Likewise.
	* backend/rust-compile-fnparam.cc
	(CompileFnParam::CompileFnParam): Likewise.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-08-09 09:23:34 +00:00
Owen Avery
09e23335a2 Remove Backend::bool_type and Backend::char_type
gcc/rust/ChangeLog:

	* backend/rust-compile-type.cc
	(TyTyResolveCompile::visit): Inline Backend::bool_type call.
	* rust-backend.h
	(Backend::bool_type): Remove.
	(Backend::char_type): Remove.
	(Gcc_backend::bool_type): Remove.
	(Gcc_backend::char_type): Remove.
	* rust-gcc.cc
	(Gcc_backend::char_constant_expression): Inline Backend::char_type call.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-08-09 09:23:16 +00:00
Raiki Tamura
a4b7e7375f gccrs: Normalize all identifier tokens
gcc/rust/ChangeLog:

	* lex/rust-lex.cc (assert_source_content): Fix namespace specifier
	(test_buffer_input_source): Likewise.
	(test_file_input_source): Likewise.
	* lex/rust-lex.h: Move InputSource ...
	* lex/rust-input-source.h: ... to here. (New file)
	* lex/rust-token.cc (nfc_normalize_token_string): New function
	* lex/rust-token.h (nfc_normalize_token_string): New function
	* rust-lang.cc (run_rust_tests): Modify order of selftests.
	* rust-session-manager.cc (validate_crate_name): Modify interface of Utf8String.
	* util/rust-unicode.cc (lookup_cc): Modify codepoint_t typedef.
	(lookup_recomp): Likewise.
	(recursive_decomp_cano): Likewise.
	(decomp_cano): Likewise.
	(sort_cano): Likewise.
	(compose_hangul): Likewise.
	(assert_normalize): Likewise.
	(Utf8String::nfc_normalize): New function.
	* util/rust-unicode.h: Modify interface of Utf8String.

gcc/testsuite/ChangeLog:

	* rust/compile/unicode_norm1.rs: New test.

Signed-off-by: Raiki Tamura <tamaron1203@gmail.com>
2023-08-09 09:23:03 +00:00
Muhammad Mahad
74b83511e4 gccrs: [E0412] used type name not in scope
gcc/rust/ChangeLog:

	* resolve/rust-ast-resolve-type.cc (ResolveRelativeTypePath::go):
	Added ErrorCode.

Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
2023-08-09 09:19:46 +00:00
Pierre-Emmanuel Patry
07046b16e9 Fix a warning about extra semicolon
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>
2023-08-09 09:19:26 +00:00
Muhammad Mahad
be04efc9ce gccrs: [E0658] Unstable langauge feature
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>
2023-08-09 09:19:01 +00:00
Muhammad Mahad
87172a8bf9 gccrs: [E0015] Use of non-const inside const
gcc/rust/ChangeLog:

	* checks/errors/rust-const-checker.cc (ConstChecker::check_function_call):
	Added errorcode.

Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
2023-08-09 09:18:19 +00:00
Muhammad Mahad
2fcf448238 gccrs: [E0107] Wrong number of generic argument
gcc/rust/ChangeLog:

	* typecheck/rust-tyty-subst.cc (SubstitutionRef::get_mappings_from_generic_args):
	Added errorcode.

Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
2023-08-09 09:17:43 +00:00
Arthur Cohen
f7d937321b nr2.0: Add macros 2.0 resolution testcase.
gcc/testsuite/ChangeLog:

	* rust/compile/name_resolution10.rs: New test.
2023-08-03 17:36:42 +00:00
Arthur Cohen
88d258483f nr2.0: Add macros 2.0 in Ribs in TopLevel visitor
gcc/rust/ChangeLog:

	* resolve/rust-toplevel-name-resolver-2.0.cc (TopLevel::visit): Declare
	macros in the current rib if they are macros 2.0.
2023-08-03 17:36:42 +00:00
Arthur Cohen
6993fe43fc ast: Add get_kind method to MacroRulesDefinition
gcc/rust/ChangeLog:

	* ast/rust-macro.h: Add new method to `MacroRulesDefinition` to allow
	getting the `MacroKind` contained.
2023-08-03 17:36:42 +00:00
Arthur Cohen
d77abf259d nr2.0: Add complex macro name resolution test cases
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.
2023-08-03 17:36:42 +00:00
Arthur Cohen
980ef03bc5 session-manager: Run name resolution 2.0 if the option is present
gcc/rust/ChangeLog:

	* rust-session-manager.cc
	(Session::expansion): Use new `Early` name resolution 2.0 pass
2023-08-03 17:36:42 +00:00
Arthur Cohen
f868ca89b0 nr2.0: Add Early name resolution visitor
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.
2023-08-03 17:36:42 +00:00
Arthur Cohen
d270a516e1 nr2.0: Visit receiver/call expression and arguments in calls/methods
gcc/rust/ChangeLog:

	* resolve/rust-default-resolver.cc
	(DefaultResolver::visit): Visit CallExpr and MethodCallExpr properly.
	* resolve/rust-default-resolver.h: Switch "node" to plural in documentation.
2023-08-03 17:36:42 +00:00
Arthur Cohen
c9aeb8f914 toplevel: Handle macro definitions properly
gcc/rust/ChangeLog:

	* resolve/rust-toplevel-name-resolver-2.0.cc
	(TopLevel::insert_or_error_out): Fix format string.
	(is_macro_export): New method.
	(TopLevel::visit): Handle macro definitions.
2023-08-03 17:36:42 +00:00
Arthur Cohen
02d0d97229 resolver: Resolve macros too.
gcc/rust/ChangeLog:

	* resolve/rust-name-resolution-context.cc
	(Resolver::insert): Do not call into `rust_unreachable` when resolving
	macros anymore.
2023-08-03 17:36:42 +00:00
Arthur Cohen
be4dcaf1b8 forever stack: Add path resolution
gcc/rust/ChangeLog:

	* resolve/rust-forever-stack.h
	(insert_at_root): New method.
	(resolve_path): New method.
	(reverse_iter): Iterate on `Node`s instead of `Rib`s
	* resolve/rust-forever-stack.hxx: Add path resolution.
2023-08-03 17:36:42 +00:00
Arthur Cohen
a29abdd22b rib2.0: Add shadowing
gcc/rust/ChangeLog:

	* resolve/rust-rib.h: Add shadowing parameter. Make kind field public.
	* resolve/rust-rib.cc (Rib::insert): Likewise.
2023-08-03 17:36:42 +00:00
Muhammad Mahad
0fe8a6b44d gccrs: [E0426] Use of undeclared label
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>
2023-08-03 13:40:31 +00:00
Muhammad Mahad
5eac656912 gccrs: [E0635] Use of Unknown feature.
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>
2023-08-03 13:37:15 +00:00
Marc Poulhiès
95dcbb25a1 mklog: handle Signed-Off-By, minor cleanup
fixup for:

commit 1531c69922
Author:     Marc Poulhiès <dkm@kataplop.net>
AuthorDate: Thu Jul 6 22:40:57 2023 +0200
Commit:     CohenArthur <arthur.cohen@embecosm.com>
CommitDate: Wed Jul 12 11:41:31 2023 +0000

    mklog: handle Signed-Off-By, minor cleanup

The regex was not matching the # comments.

contrib/ChangeLog:

	* mklog.py (FIRST_LINE_OF_END_RE): Correctly match comments.

Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
2023-08-02 18:33:30 +00:00
Muhammad Mahad
6c63150705 gccrs: [E0308] mismatch types on assignment
This errorcode emits when there are
mismatch types between lhs & rhs of
assignment operator & refactored
message. This error code was used
in many test cases, so updated the
error comments.

gcc/rust/ChangeLog:

	* typecheck/rust-unify.cc (UnifyRules::emit_type_mismatch):
	refactored & called error function.

gcc/testsuite/ChangeLog:

	* rust/compile/arrays1.rs: changed comment to pass testcase.
	* rust/compile/bad_type1.rs: likewise.
	* rust/compile/bad_type2.rs: likewise.
	* rust/compile/const_generics_6.rs: likewise.
	* rust/compile/deadcode_err1.rs: likewise.
	* rust/compile/deadcode_err2.rs: likewise.
	* rust/compile/func1.rs: likewise.
	* rust/compile/func3.rs: likewise.
	* rust/compile/func4.rs: likewise.
	* rust/compile/func5.rs: likewise.
	* rust/compile/generics1.rs: likewise.
	* rust/compile/generics2.rs: likewise.
	* rust/compile/generics3.rs: likewise.
	* rust/compile/implicit_returns_err1.rs: likewise.
	* rust/compile/implicit_returns_err2.rs: likewise.
	* rust/compile/implicit_returns_err3.rs: likewise.
	* rust/compile/implicit_returns_err4.rs: likewise.
	* rust/compile/issue-1152.rs: likewise.
	* rust/compile/issue-2477.rs: likewise.
	* rust/compile/reference1.rs: likewise.
	* rust/compile/stmt_with_block_err1.rs: likewise.
	* rust/compile/traits1.rs: likewise.
	* rust/compile/traits2.rs: likewise.
	* rust/compile/tuple_mismatch.rs: likewise.
	* rust/compile/tuple_struct3.rs: likewise.
	* rust/compile/mismatched-types.rs: New test from rustc.

Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
2023-08-02 12:42:31 +00:00
Marc Poulhiès
36db4d9539 gccrs: better handling of incorrect file loading in include_* builtin macros
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>
2023-08-02 10:04:20 +00:00
Arthur Cohen
b7c5b50a4e nr2.0: Use DefaultResolver for TopLevel
gcc/rust/ChangeLog:

	* resolve/rust-toplevel-name-resolver-2.0.h
	(class TopLevel): Inherit from DefaultResolver
	* resolve/rust-toplevel-name-resolver-2.0.cc
	(TopLevel::TopLevel): Remove unecessary methods
2023-08-02 08:26:27 +00:00
Arthur Cohen
bbeaf4b29c nr2.0: Add DefaultResolver visitor
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.
2023-08-02 08:26:27 +00:00
Raiki Tamura
f78dd97b87 gccrs: Normalize Hangul to NFC
gcc/rust/ChangeLog:

	* util/rust-unicode.cc (decomp_cano): Decompose Hangul.
	(sort_cano): Fix bounds check.
	(recomp): use `compose_hangul`.
	(compose_hangul): Compose Hangul.
	(rust_utf8_normalize_test): Add tests.

Signed-off-by: Raiki Tamura <tamaron1203@gmail.com>
2023-08-02 07:34:38 +00:00
Arthur Cohen
4f1838b880 forever-stack: Use rust_assert instead of assert
This causes complaints by our GCC 4.8 builder.

gcc/rust/ChangeLog:

	* resolve/rust-forever-stack.hxx: assert() -> rust_assert()
2023-08-01 15:37:57 +00:00
Arthur Cohen
d9e87e719f top-level: Add base TopLevel visitor
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.
2023-08-01 15:37:57 +00:00
Arthur Cohen
7515e1f72c name resolution 2.0: Add base for our context data structure
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.
2023-08-01 15:37:57 +00:00
Muhammad Mahad
d20a2c270b gccrs: [E0572] return is outside of function context
gcc/rust/ChangeLog:

	* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit):
	called error function.

Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
2023-08-01 15:12:33 +00:00
Owen Avery
cc167a9cc0 Use MacroInvocLexerBase in MacroInvocLexer
gcc/rust/ChangeLog:

	* expand/rust-macro-invoc-lexer.cc
	(MacroInvocLexer::skip_token): Remove.
	* expand/rust-macro-invoc-lexer.h
	(class MacroInvocLexer): Extend MacroInvocLexerBase.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-08-01 15:00:54 +00:00
Raiki Tamura
dba8bc5bf8 fix bootstrap build failure
gcc/rust/ChangeLog:

	* util/rust-unicode.cc (binary_search_sorted_array): Fix type.

Signed-off-by: Raiki Tamura <tamaron1203@gmail.com>
2023-07-31 12:56:05 +00:00
Marc Poulhiès
c55ca4ed1f gccrs: use tl::optional for macro transcribers
refs #2421.

gcc/rust/ChangeLog:

	* ast/rust-ast-fragment.cc (Fragment::create_empty): New.
	* ast/rust-ast-fragment.h (MacroTranscriberFunc): New.
	* ast/rust-macro.h (MacroRulesDefinition): Use MacroTranscriberFunc.
	* expand/rust-macro-builtins.cc
	(MacroBuiltin::builtin_transcribers): likewise.
	(MacroBuiltin::assert_handler): Return optional.
	(MacroBuiltin::file_handler): Likewise.
	(MacroBuiltin::column_handler): Likewise.
	(MacroBuiltin::include_bytes_handler): Likewise.
	(MacroBuiltin::include_str_handler): Likewise.
	(MacroBuiltin::compile_error_handler): Likewise.
	(MacroBuiltin::concat_handler): Likewise.
	(MacroBuiltin::env_handler): Likewise.
	(MacroBuiltin::cfg_handler): Likewise.
	(MacroBuiltin::include_handler): Likewise.
	(MacroBuiltin::line_handler): Likewise.
	(MacroBuiltin::stringify_handler): Likewise.
	(MacroBuiltin::sorry): Likewise.
	* expand/rust-macro-builtins.h (builtin_transcribers): Use
	MacroTranscriberFunc.
	(assert_handler): Return optional.
	(file_handler): Likewise.
	(column_handler): Likewise.
	(include_bytes_handler): Likewise.
	(include_str_handler): Likewise.
	(compile_error_handler): Likewise.
	(concat_handler): Likewise.
	(env_handler): Likewise.
	(cfg_handler): Likewise.
	(include_handler): Likewise.
	(line_handler): Likewise.
	(stringify_handler): Likewise.
	(sorry): Likewise.
	* expand/rust-macro-expand.cc (MacroExpander::expand_invoc):
	Adjust to transcribers returning optional.

Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
2023-07-31 09:04:40 +00:00
Philip Herron
22f4c74767 gccrs: Fix ICE by adding check for enum candidate's in TypePath resolution
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>
2023-07-30 19:12:06 +00:00
Raiki Tamura
a3fc40c674 gccrs: Add Unicode check for crate_name attributes
gcc/rust/ChangeLog:

	* lex/rust-codepoint.h: Add comment
	* lex/rust-lex.h: New method to get decoded characters
	* rust-session-manager.cc (validate_crate_name): Modify unicode check
	(rust_crate_name_validation_test): Add testcases
	* util/rust-unicode.h (RUST_UNICODE_H): New class Utf8String.
	(class Utf8String): New class.
	* util/rust-unicode.cc (binary_search_sorted_array): Add comment.
	(recursive_decomp_cano): Add comment.
	(recomp): Remove dead code.
	(dump_string): Removed.

gcc/testsuite/ChangeLog:

	* rust/compile/bad-crate-name.rs: Moved to...
	* rust/compile/bad-crate-name1.rs: ...here.
	* rust/compile/bad-crate-name2.rs: New test.

Signed-off-by: Raiki Tamura <tamaron1203@gmail.com>
2023-07-30 17:20:51 +00:00
Owen Avery
4553f58e19 Add missing CHECKING_P guard to rust-unicode.cc
gcc/rust/ChangeLog:

	* util/rust-unicode.cc: Add CHECKING_P guard.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-07-30 17:19:41 +00:00
Philip Herron
5ad0febb77 gccrs: fix ice when function is outside of context
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>
2023-07-30 00:08:48 +00:00
Philip Herron
5785d329b1 gccrs: Begin enforcing Sized properly and support anti traits like ?Sized
Sized is implicitly applied to every generic type parameter apart from the
implicit Self type parameter on traits, as that would cause a recursive
bound and would make Traits unable to be appied to unsized types.

In order to keep everything happy this means we also need to support the
anti trait bound '?' so that Sized can be removed properly. The full Sized
rules are not completely implemented here. Slice's and Str's are currently
marked as Sized but there is a small regression here that looks like a more
general bug which should be fixed on its own as part of #2443. There is
a big testsuite update here to pull in the Sized lang item.

Note this lays the bound's ground work so we can start supporting Drop
trait properly which needs tackled very soon.

Fixes: #2375
Addresses: #2443

gcc/rust/ChangeLog:

	* expand/rust-proc-macro.cc (literal_from_string): update Lexer constructor
	(tokenstream_from_string): likewise
	* lex/rust-lex.cc (Lexer::Lexer): likewise
	* lex/rust-lex.h: pass through Linemap
	* parse/rust-cfg-parser.cc (parse_cfg_option): likewise
	* rust-session-manager.cc (Session::load_extern_crate): likewise
	* typecheck/rust-hir-trait-resolve.cc (TraitResolver::resolve_trait):
	dont apply Sized on self
	* typecheck/rust-hir-type-check-base.cc (TypeCheckBase::get_marker_predicate): new
	* typecheck/rust-hir-type-check-base.h: add prototype
	* typecheck/rust-hir-type-check-type.cc (TypeResolveGenericParam::Resolve): apply Sized
	(TypeResolveGenericParam::visit): likewise
	* typecheck/rust-hir-type-check-type.h: update prototypes
	* typecheck/rust-typecheck-context.cc: remove bad assertions
	* typecheck/rust-tyty-bounds.cc (TypeBoundsProbe::assemble_sized_builtin): cleanup
	(TypeCheckBase::get_predicate_from_bound): apply sized rules properly
	* util/rust-hir-map.cc (Mappings::lookup_trait_item_lang_item): helpers
	(Mappings::get_lang_item): likewise
	* util/rust-hir-map.h: likewise
	* util/rust-token-converter.cc (from_ident): update lexer ctor
	(from_punct): likewise

gcc/testsuite/ChangeLog:

	* rust/compile/bounds1.rs: Apply sized trait
	* rust/compile/canonical_paths1.rs: likewise
	* rust/compile/cast_generics.rs: likewise
	* rust/compile/closure_no_type_anno.rs: likewise
	* rust/compile/complex_qualified_path_in_expr.rs: likewise
	* rust/compile/const-issue1440.rs: likewise
	* rust/compile/const_generics_1.rs: likewise
	* rust/compile/const_generics_8.rs: likewise
	* rust/compile/derive_macro1.rs: likewise
	* rust/compile/derive_macro3.rs: likewise
	* rust/compile/derive_macro4.rs: likewise
	* rust/compile/derive_macro6.rs: likewise
	* rust/compile/expected_type_args2.rs: likewise
	* rust/compile/expected_type_args3.rs: likewise
	* rust/compile/generics1.rs: likewise
	* rust/compile/generics11.rs: likewise
	* rust/compile/generics12.rs: likewise
	* rust/compile/generics2.rs: likewise
	* rust/compile/generics3.rs: likewise
	* rust/compile/generics4.rs: likewise
	* rust/compile/generics6.rs: likewise
	* rust/compile/generics7.rs: likewise
	* rust/compile/generics8.rs: likewise
	* rust/compile/if_let_expr.rs: likewise
	* rust/compile/issue-1005.rs: likewise
	* rust/compile/issue-1019.rs: likewise
	* rust/compile/issue-1031.rs: likewise
	* rust/compile/issue-1034.rs: likewise
	* rust/compile/issue-1128.rs: likewise
	* rust/compile/issue-1129-2.rs: likewise
	* rust/compile/issue-1130.rs: likewise
	* rust/compile/issue-1131.rs: likewise
	* rust/compile/issue-1165.rs: likewise
	* rust/compile/issue-1173.rs: likewise
	* rust/compile/issue-1235.rs: likewise
	* rust/compile/issue-1237.rs: likewise
	* rust/compile/issue-1289.rs: likewise
	* rust/compile/issue-1383.rs: likewise
	* rust/compile/issue-1447.rs: likewise
	* rust/compile/issue-1589.rs: likewise
	* rust/compile/issue-1725-1.rs: likewise
	* rust/compile/issue-1725-2.rs: likewise
	* rust/compile/issue-1773.rs: likewise
	* rust/compile/issue-1786.rs: likewise
	* rust/compile/issue-1893.rs: likewise
	* rust/compile/issue-1901.rs: likewise
	* rust/compile/issue-1930.rs: likewise
	* rust/compile/issue-1981.rs: likewise
	* rust/compile/issue-2019-1.rs: likewise
	* rust/compile/issue-2019-2.rs: likewise
	* rust/compile/issue-2019-3.rs: likewise
	* rust/compile/issue-2036.rs: likewise
	* rust/compile/issue-2037.rs: likewise
	* rust/compile/issue-2070.rs: likewise
	* rust/compile/issue-2105.rs: likewise
	* rust/compile/issue-2106.rs: likewise
	* rust/compile/issue-2135.rs: likewise
	* rust/compile/issue-2136-1.rs: likewise
	* rust/compile/issue-2136-2.rs: likewise
	* rust/compile/issue-2139.rs: likewise
	* rust/compile/issue-2142.rs: likewise
	* rust/compile/issue-2165.rs: likewise
	* rust/compile/issue-2166.rs: likewise
	* rust/compile/issue-2190-1.rs: likewise
	* rust/compile/issue-2190-2.rs: likewise
	* rust/compile/issue-2195.rs: likewise
	* rust/compile/issue-2238.rs: likewise
	* rust/compile/issue-2304.rs: likewise
	* rust/compile/issue-850.rs: likewise
	* rust/compile/issue-855.rs: likewise
	* rust/compile/issue-925.rs: likewise
	* rust/compile/macro-issue1400.rs: likewise
	* rust/compile/macro20.rs: likewise
	* rust/compile/macro23.rs: likewise
	* rust/compile/macro40.rs: likewise
	* rust/compile/macro54.rs: likewise
	* rust/compile/name_resolution2.rs: likewise
	* rust/compile/name_resolution4.rs: likewise
	* rust/compile/nested_generic.rs: likewise
	* rust/compile/parse_associated_type_as_generic_arg.rs: likewise
	* rust/compile/parse_associated_type_as_generic_arg2.rs: likewise
	* rust/compile/parse_associated_type_as_generic_arg3.rs: likewise
	* rust/compile/parse_complex_generic_application.rs: likewise
	* rust/compile/parse_complex_generic_application2.rs: likewise
	* rust/compile/path_as_generic_arg.rs: likewise
	* rust/compile/privacy4.rs: likewise
	* rust/compile/privacy6.rs: likewise
	* rust/compile/sizeof-stray-infer-var-bug.rs: likewise
	* rust/compile/stmt_with_block_dot.rs: likewise
	* rust/compile/torture/associated_types1.rs: likewise
	* rust/compile/torture/forward_decl_5.rs: likewise
	* rust/compile/torture/generics1.rs: likewise
	* rust/compile/torture/generics10.rs: likewise
	* rust/compile/torture/generics11.rs: likewise
	* rust/compile/torture/generics12.rs: likewise
	* rust/compile/torture/generics13.rs: likewise
	* rust/compile/torture/generics14.rs: likewise
	* rust/compile/torture/generics15.rs: likewise
	* rust/compile/torture/generics16.rs: likewise
	* rust/compile/torture/generics17.rs: likewise
	* rust/compile/torture/generics18.rs: likewise
	* rust/compile/torture/generics19.rs: likewise
	* rust/compile/torture/generics2.rs: likewise
	* rust/compile/torture/generics20.rs: likewise
	* rust/compile/torture/generics21.rs: likewise
	* rust/compile/torture/generics22.rs: likewise
	* rust/compile/torture/generics23.rs: likewise
	* rust/compile/torture/generics24.rs: likewise
	* rust/compile/torture/generics25.rs: likewise
	* rust/compile/torture/generics26.rs: likewise
	* rust/compile/torture/generics27.rs: likewise
	* rust/compile/torture/generics28.rs: likewise
	* rust/compile/torture/generics29.rs: likewise
	* rust/compile/torture/generics3.rs: likewise
	* rust/compile/torture/generics30.rs: likewise
	* rust/compile/torture/generics31.rs: likewise
	* rust/compile/torture/generics32.rs: likewise
	* rust/compile/torture/generics4.rs: likewise
	* rust/compile/torture/generics5.rs: likewise
	* rust/compile/torture/generics6.rs: likewise
	* rust/compile/torture/generics7.rs: likewise
	* rust/compile/torture/generics8.rs: likewise
	* rust/compile/torture/generics9.rs: likewise
	* rust/compile/torture/intrinsics-2.rs: likewise
	* rust/compile/torture/intrinsics-6.rs: likewise
	* rust/compile/torture/intrinsics-7.rs: likewise
	* rust/compile/torture/intrinsics-8.rs: likewise
	* rust/compile/torture/issue-1024.rs: likewise
	* rust/compile/torture/issue-1075.rs: likewise
	* rust/compile/torture/issue-1432.rs: likewise
	* rust/compile/torture/issue-1555.rs: likewise
	* rust/compile/torture/issue-368.rs: likewise
	* rust/compile/torture/issue-808.rs: likewise
	* rust/compile/torture/issue-862.rs: likewise
	* rust/compile/torture/issue-893-2.rs: likewise
	* rust/compile/torture/issue-893.rs: likewise
	* rust/compile/torture/must_use2.rs: likewise
	* rust/compile/torture/nested_fn2.rs: likewise
	* rust/compile/torture/phantom_data.rs: likewise
	* rust/compile/torture/range-lang-item1.rs: likewise
	* rust/compile/torture/traits1.rs: likewise
	* rust/compile/torture/traits11.rs: likewise
	* rust/compile/torture/traits12.rs: likewise
	* rust/compile/torture/traits13.rs: likewise
	* rust/compile/torture/traits14.rs: likewise
	* rust/compile/torture/traits15.rs: likewise
	* rust/compile/torture/traits16.rs: likewise
	* rust/compile/torture/traits17.rs: likewise
	* rust/compile/torture/traits18.rs: likewise
	* rust/compile/torture/traits19.rs: likewise
	* rust/compile/torture/traits2.rs: likewise
	* rust/compile/torture/traits3.rs: likewise
	* rust/compile/torture/traits4.rs: likewise
	* rust/compile/torture/traits5.rs: likewise
	* rust/compile/torture/traits6.rs: likewise
	* rust/compile/torture/traits7.rs: likewise
	* rust/compile/torture/traits8.rs: likewise
	* rust/compile/torture/traits9.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/compile/torture/utf8_identifiers.rs: likewise
	* rust/compile/traits1.rs: likewise
	* rust/compile/traits10.rs: likewise
	* rust/compile/traits11.rs: likewise
	* rust/compile/traits12.rs: likewise
	* rust/compile/traits2.rs: likewise
	* rust/compile/traits3.rs: likewise
	* rust/compile/traits4.rs: likewise
	* rust/compile/traits5.rs: likewise
	* rust/compile/traits6.rs: likewise
	* rust/compile/traits7.rs: likewise
	* rust/compile/traits8.rs: likewise
	* rust/compile/traits9.rs: likewise
	* rust/compile/type-bindings1.rs: likewise
	* rust/compile/unconstrained_type_param.rs: likewise
	* rust/compile/unsafe10.rs: likewise
	* rust/execute/torture/closure1.rs: likewise
	* rust/execute/torture/closure2.rs: likewise
	* rust/execute/torture/closure3.rs: likewise
	* rust/execute/torture/closure4.rs: likewise
	* rust/execute/torture/coercion1.rs: likewise
	* rust/execute/torture/coercion2.rs: likewise
	* rust/execute/torture/coercion3.rs: likewise
	* rust/execute/torture/copy_nonoverlapping1.rs: likewise
	* rust/execute/torture/derive_macro1.rs: likewise
	* rust/execute/torture/derive_macro3.rs: likewise
	* rust/execute/torture/derive_macro4.rs: likewise
	* rust/execute/torture/index1.rs: likewise
	* rust/execute/torture/issue-1120.rs: likewise
	* rust/execute/torture/issue-1133.rs: likewise
	* rust/execute/torture/issue-1198.rs: likewise
	* rust/execute/torture/issue-1232.rs: likewise
	* rust/execute/torture/issue-1249.rs: likewise
	* rust/execute/torture/issue-1436.rs: likewise
	* rust/execute/torture/issue-1496.rs: likewise
	* rust/execute/torture/issue-1720-2.rs: likewise
	* rust/execute/torture/issue-1720.rs: likewise
	* rust/execute/torture/issue-2052.rs: likewise
	* rust/execute/torture/issue-2179.rs: likewise
	* rust/execute/torture/issue-2180.rs: likewise
	* rust/execute/torture/issue-2236.rs: likewise
	* rust/execute/torture/issue-647.rs: likewise
	* rust/execute/torture/issue-845.rs: likewise
	* rust/execute/torture/issue-851.rs: likewise
	* rust/execute/torture/issue-858.rs: likewise
	* rust/execute/torture/macros23.rs: likewise
	* rust/execute/torture/macros28.rs: likewise
	* rust/execute/torture/method2.rs: likewise
	* rust/execute/torture/method3.rs: likewise
	* rust/execute/torture/method4.rs: likewise
	* rust/execute/torture/operator_overload_1.rs: likewise
	* rust/execute/torture/operator_overload_10.rs: likewise
	* rust/execute/torture/operator_overload_11.rs: likewise
	* rust/execute/torture/operator_overload_12.rs: likewise
	* rust/execute/torture/operator_overload_2.rs: likewise
	* rust/execute/torture/operator_overload_3.rs: likewise
	* rust/execute/torture/operator_overload_4.rs: likewise
	* rust/execute/torture/operator_overload_5.rs: likewise
	* rust/execute/torture/operator_overload_6.rs: likewise
	* rust/execute/torture/operator_overload_7.rs: likewise
	* rust/execute/torture/operator_overload_8.rs: likewise
	* rust/execute/torture/operator_overload_9.rs: likewise
	* rust/execute/torture/prefetch_data.rs: likewise
	* rust/execute/torture/ref-pattern2.rs: likewise
	* rust/execute/torture/slice-magic.rs: likewise
	* rust/execute/torture/slice-magic2.rs: likewise
	* rust/execute/torture/slice1.rs: likewise
	* rust/execute/torture/str-layout1.rs: likewise
	* rust/execute/torture/trait1.rs: likewise
	* rust/execute/torture/trait10.rs: likewise
	* rust/execute/torture/trait11.rs: likewise
	* rust/execute/torture/trait12.rs: likewise
	* rust/execute/torture/trait13.rs: likewise
	* rust/execute/torture/trait2.rs: likewise
	* rust/execute/torture/trait3.rs: likewise
	* rust/execute/torture/trait4.rs: likewise
	* rust/execute/torture/trait5.rs: likewise
	* rust/execute/torture/trait6.rs: likewise
	* rust/execute/torture/trait7.rs: likewise
	* rust/execute/torture/trait8.rs: likewise
	* rust/execute/torture/trait9.rs: likewise
	* rust/execute/torture/transmute1.rs: likewise
	* rust/execute/torture/wrapping_op1.rs: likewise
	* rust/execute/torture/wrapping_op2.rs: likewise
	* rust/link/generic_function_0.rs: likewise
	* rust/link/generic_function_1.rs: likewise
	* rust/compile/issue-2375.rs: New test.

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2023-07-29 23:51:27 +00:00
Philip Herron
eefebdb3a1 gccrs: Track polarity in type bound predicate
Addresses #2443

gcc/rust/ChangeLog:

	* typecheck/rust-hir-path-probe.cc: track regular polarity
	* typecheck/rust-hir-trait-resolve.cc (TraitResolver::resolve_trait): likewise
	* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit): likewise
	* typecheck/rust-hir-type-check-item.cc (TypeCheckItem::visit): likewise
	* typecheck/rust-tyty-bounds.cc (TypeCheckBase::get_predicate_from_bound): likewise
	(TypeBoundPredicate::TypeBoundPredicate): update ctor
	(TypeBoundPredicate::operator=): update copy assignment ctor
	(TypeBoundPredicate::error): update error node
	* typecheck/rust-tyty.h: add polarity field to predicate

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2023-07-29 23:51:27 +00:00
Philip Herron
f284cff3ff gccrs: Track trait bound polarity properly
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>
2023-07-29 23:51:27 +00:00
Owen Avery
7bb4d1b750 Move Gcc_backend declaration to header file
gcc/rust/ChangeLog:

	* rust-backend.h: Include "rust-gcc.h".
	(class Gcc_backend): Move to ...
	* rust-gcc.cc (class Gcc_backend): ... here.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-07-29 22:58:14 +00:00
Philip Herron
5a378edb75 gccrs: fix ICE when we have unimplemented/invalid trait items
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>
2023-07-29 17:27:20 +00:00
Raiki Tamura
7ce263e17a Add function for Unicode NFC normalization
gcc/rust/ChangeLog:

	* Make-lang.in: Add rust-unicode.o
	* rust-lang.cc (run_rust_tests): Add test.
	* rust-system.h: Include <array>
	* util/make-rust-unicode.py: Generater of rust-unicode-data.h.
	* util/rust-unicode-data.h: Auto-generated file.
	* util/rust-unicode.cc: New file.
	* util/rust-unicode.h: New file.

Signed-off-by: Raiki Tamura <tamaron1203@gmail.com>
2023-07-29 16:05:39 +00:00
Arthur Cohen
42bd81f8df error codes: Add rust_error_codes.def, refactor ErrorCode enum
gcc/rust/ChangeLog:

	* rust-diagnostics.cc: Rework `make_description` and `make_url` functions.
	* rust-diagnostics.h: Specify ErrorCode's underlying type,
	remove error_codes_strings table.
	* rust_error_codes.def: New file.
2023-07-29 16:03:47 +00:00
Owen Avery
611457431b Remove Location typedef
gcc/rust/ChangeLog:

	* rust-location.h (typedef Location): Remove.

	* expand/rust-proc-macro.cc
	(register_callback): Replace Location constructor with UNDEF_LOCATION.

	* ast/rust-ast-collector.h: Replace Location with location_t.
	* checks/errors/privacy/rust-privacy-reporter.cc: Likewise.
	* checks/errors/privacy/rust-privacy-reporter.h: Likewise.
	* checks/errors/privacy/rust-pub-restricted-visitor.cc: Likewise.
	* checks/errors/privacy/rust-pub-restricted-visitor.h: Likewise.
	* checks/errors/rust-feature-gate.cc: Likewise.
	* checks/errors/rust-feature-gate.h: Likewise.
	* metadata/rust-imports.h: Likewise.
	* resolve/rust-ast-resolve-path.h: Likewise.
	* resolve/rust-name-resolver.h: Likewise.
	* rust-backend.h: Likewise.
	* rust-diagnostics.h: Likewise.
	* rust-gcc.cc: Likewise.
	* rust-linemap.h: Likewise.
	* util/rust-attributes.cc: Likewise.
	* util/rust-hir-map.cc: Likewise.
	* util/rust-hir-map.h: Likewise.
	* util/rust-token-converter.cc: Likewise.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-07-29 16:03:44 +00:00
Owen Avery
69f6bc9c91 Replace usages of Location with location_t in typechecking
gcc/rust/ChangeLog:

	* typecheck/rust-autoderef.cc: Replace Location with location_t.
	* typecheck/rust-coercion.cc: Likewise.
	* typecheck/rust-coercion.h: Likewise.
	* typecheck/rust-hir-path-probe.h: Likewise.
	* typecheck/rust-hir-trait-reference.cc: Likewise.
	* typecheck/rust-hir-trait-resolve.cc: Likewise.
	* typecheck/rust-hir-type-check-base.cc: Likewise.
	* typecheck/rust-hir-type-check-expr.cc: Likewise.
	* typecheck/rust-hir-type-check-expr.h: Likewise.
	* typecheck/rust-hir-type-check-implitem.cc: Likewise.
	* typecheck/rust-hir-type-check-item.cc: Likewise.
	* typecheck/rust-hir-type-check-path.cc: Likewise.
	* typecheck/rust-hir-type-check-pattern.cc: Likewise.
	* typecheck/rust-hir-type-check-stmt.cc: Likewise.
	* typecheck/rust-hir-type-check-struct.cc: Likewise.
	* typecheck/rust-hir-type-check-type.cc: Likewise.
	* typecheck/rust-hir-type-check-type.h: Likewise.
	* typecheck/rust-type-util.cc: Likewise.
	* typecheck/rust-type-util.h: Likewise.
	* typecheck/rust-tyty-bounds.cc: Likewise.
	* typecheck/rust-tyty-call.cc: Likewise.
	* typecheck/rust-tyty-call.h: Likewise.
	* typecheck/rust-tyty-cmp.h: Likewise.
	* typecheck/rust-tyty-subst.cc: Likewise.
	* typecheck/rust-tyty-subst.h: Likewise.
	* typecheck/rust-tyty.cc: Likewise.
2023-07-28 13:20:21 +00:00
Muhammad Mahad
f201ef93a5 gccrs: [E0571] break with argument in non-loop loop
Refactored error message similiar to rustc
& called error function.

gcc/rust/ChangeLog:

	* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit):
	refactored error message & called error function.

gcc/testsuite/ChangeLog:

	* rust/compile/break2.rs: Modified file to pass test case.
	* rust/compile/break_with_value_inside_loop.rs: New test.

Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
2023-07-28 13:19:28 +00:00
Pierre-Emmanuel Patry
fe6ad2e676 proc_macro: Add literal_from_string callback
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>
2023-07-28 09:15:21 +00:00
Pierre-Emmanuel Patry
69454e5304 converter: Move literal conversion out
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>
2023-07-28 09:15:21 +00:00
Pierre-Emmanuel Patry
9b62bc32f5 Move callbacked function in a new namespace
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>
2023-07-28 09:15:21 +00:00
Muhammad Mahad
b4d1406d6d gccrs: New Error Code Framework
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>
2023-07-28 08:21:56 +00:00
Pierre-Emmanuel Patry
1bc8f08453 Add multiple tests for non root proc macro
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>
2023-07-27 14:20:52 +00:00
Pierre-Emmanuel Patry
67b2057b7a Check proc_macro attributes on non root functions
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>
2023-07-27 14:20:52 +00:00
Owen Avery
d62a388625 Replace Location with location_t in unnamed function parameters
gcc/rust/ChangeLog:

	* backend/rust-compile-base.h: Replace Location with location_t.
	* metadata/rust-imports.h: Likewise.
	* resolve/rust-name-resolver.cc: Likewise.
	* resolve/rust-name-resolver.h: Likewise.
	* rust-backend.h: Likewise.
	* rust-gcc.cc: Likewise.
	* rust-gcc.h: Likewise.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-07-27 14:18:45 +00:00
Owen Avery
d76d64cb06 Run bootstrap builds on a schedule
ChangeLog:

	* .github/workflows/bootstrap.yml:
	Run a bootstrap build nightly.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-07-27 14:18:02 +00:00
Pierre-Emmanuel Patry
27f5146d48 proc_macro: Remove useless typedef
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>
2023-07-27 12:25:20 +00:00
Pierre-Emmanuel Patry
851d83e346 proc_macro: Delete unused prototype
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>
2023-07-27 12:25:20 +00:00
Pierre-Emmanuel Patry
614f081a5e proc_macro: Remode function indirection
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>
2023-07-27 12:25:20 +00:00
Pierre-Emmanuel Patry
4321126f05 proc_macro: Add is_available function
Add is_available function to the C++ library.

ChangeLog:

	* libgrust/libproc_macro/proc_macro.cc (bridge_is_available):
	Add bridge function.
	* libgrust/libproc_macro/proc_macro.h (bridge_is_available):
	Likewise.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-07-27 12:25:20 +00:00
Pierre-Emmanuel Patry
5b36e8993a proc_macro: Add is_available callback
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>
2023-07-27 12:25:20 +00:00
Pierre-Emmanuel Patry
1074c90c80 proc_macro: Rename from_string callback symbol
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>
2023-07-27 12:25:20 +00:00
Pierre-Emmanuel Patry
ddce1d9e9e proc_macro: Refactor attribute search
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>
2023-07-27 12:24:54 +00:00
Pierre-Emmanuel Patry
f925f2f094 privacy: Refactor proc macro privacy check
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>
2023-07-27 12:24:54 +00:00
Pierre-Emmanuel Patry
72e6a1e85d testsuite: Add tests for pub items in proc_macros
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>
2023-07-27 12:24:54 +00:00
Pierre-Emmanuel Patry
5e48542f93 testsuite: Replace dg-excess-errors with dg-error
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>
2023-07-27 12:24:54 +00:00
Pierre-Emmanuel Patry
890f8db3d1 privacy: Add tests for private proc macro error
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>
2023-07-27 12:24:54 +00:00
Pierre-Emmanuel Patry
ac850d186a proc macro: Add privacy check
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>
2023-07-27 12:24:54 +00:00
Pierre-Emmanuel Patry
9a906fea9e Add tests for non function proc_macro_derive
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>
2023-07-27 09:40:30 +00:00
Pierre-Emmanuel Patry
456d1f0a04 Add tests for non function proc_macro_attribute
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>
2023-07-27 09:40:30 +00:00
Pierre-Emmanuel Patry
d6eb8f3841 Add tests for non function proc_macro attributes
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>
2023-07-27 09:40:30 +00:00
Pierre-Emmanuel Patry
dc9eaa15e9 Emit error with proc macro on non functions
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>
2023-07-27 09:40:30 +00:00
Pierre-Emmanuel Patry
18837b84b5 Remove NodeId member from Identifier
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>
2023-07-27 09:39:23 +00:00
Muhammad Mahad
7cfba279da gccrs: [E0045] Variadic Parameters Used on Non-C ABI Function
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>
2023-07-27 09:08:13 +00:00
Muhammad Mahad
245867e999 gccrs: [E0323] Implemented associated const, expected another trait
Refactored Error message similiar to rustc.

gcc/rust/ChangeLog:

	* typecheck/rust-hir-type-check-implitem.cc (TypeCheckImplItemWithTrait::visit):
	called error function.

gcc/testsuite/ChangeLog:

	* rust/compile/non_member_const.rs: New test.

Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
2023-07-27 09:07:54 +00:00
Pierre-Emmanuel Patry
cd38fecd8f proc_macro: Mirror FFIString changes in C++library
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>
2023-07-27 09:03:08 +00:00
Pierre-Emmanuel Patry
3e98458f7e proc_macro: Increase FFIString usage
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>
2023-07-27 09:03:08 +00:00
Owen Avery
ccac7ed46c Continue to replace usages of Location with location_t
gcc/rust/ChangeLog:

	* backend/rust-compile-base.cc: Replace Location with location_t.
	* backend/rust-compile-base.h: Likewise.
	* backend/rust-compile-expr.cc: Likewise.
	* lex/rust-token.h: Likewise.
	* metadata/rust-import-archive.cc: Likewise.
	* metadata/rust-imports.cc: Likewise.
	* metadata/rust-imports.h: Likewise.
	* rust-backend.h: Likewise.
	* rust-diagnostics.cc: Likewise.
	* rust-diagnostics.h: Likewise.
	* rust-gcc.cc: Likewise.
	* rust-linemap.cc: Likewise.
	* util/rust-token-converter.cc: Likewise.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-07-21 14:11:58 +00:00
Owen Avery
19983e80d9 Replace usages of Location with location_t in the lexer, AST, and HIR
gcc/rust/ChangeLog:

	* ast/rust-ast-builder.h: Replace Location with location_t.
	* ast/rust-ast.h: Likewise.
	* ast/rust-expr.h: Likewise.
	* ast/rust-item.h: Likewise.
	* ast/rust-macro.h: Likewise.
	* ast/rust-path.h: Likewise.
	* hir/tree/rust-hir-expr.h: Likewise.
	* hir/tree/rust-hir-item.h: Likewise.
	* hir/tree/rust-hir-path.h: Likewise.
	* hir/tree/rust-hir.h: Likewise.
	* lex/rust-lex.cc: Likewise.
	* lex/rust-lex.h: Likewise.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-07-21 11:51:06 +00:00
Owen Avery
9b971d3af0 Replace Location with location_t in parsing and macro expansion
gcc/rust/ChangeLog:

	* expand/rust-derive-clone.cc: Replace Location with location_t.
	* expand/rust-derive-clone.h: Likewise.
	* expand/rust-derive-copy.cc: Likewise.
	* expand/rust-derive-copy.h: Likewise.
	* expand/rust-derive.cc: Likewise.
	* expand/rust-derive.h: Likewise.
	* expand/rust-macro-builtins.cc: Likewise.
	* expand/rust-macro-builtins.h: Likewise.
	* expand/rust-macro-expand.cc: Likewise.
	* parse/rust-parse-impl.h: Likewise.
	* parse/rust-parse.cc: Likewise.
	* parse/rust-parse.h: Likewise.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-07-21 11:50:38 +00:00
Owen Avery
79fc30c714 Improve keyword check while parsing a macro match
gcc/rust/ChangeLog:

	* parse/rust-parse-impl.h
	(Parser::parse_macro_match): Use token_id_is_keyword.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-07-21 11:49:35 +00:00
Pierre-Emmanuel Patry
66975b3e72 resolve: Remove ProcMacroInvocable interface
Since all identifiers in attributes are converted to SimplePath, this
common interface is no longer required.

gcc/rust/ChangeLog:

	* ast/rust-ast.h (class Identifier): Remove interface
	inheritance.
	(class SimplePath): Likewise.
	* expand/rust-expand-visitor.cc (get_traits_to_derive): Change
	return type.
	(derive_item): Update according to get_traits_to_derive return
	type.
	(expand_item_attribute): Likewise.
	(ExpandVisitor::expand_inner_stmts): Likewise.
	* expand/rust-macro-expand.h (struct MacroExpander): Likewise.
	* util/rust-hir-map.cc (Mappings::insert_derive_proc_macro_invocation):
	Change input type to SimplePath.
	(Mappings::lookup_derive_proc_macro_invocation): Likewise.
	(Mappings::insert_attribute_proc_macro_invocation): Likewise.
	(Mappings::lookup_attribute_proc_macro_invocation): Likewise.
	* util/rust-hir-map.h: Likewise with function prototypes.
	* util/rust-proc-macro-invocation.h: Removed.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-07-21 09:06:09 +00:00
Pierre-Emmanuel Patry
d597883ade resolve: Convert identifier to a SimplePath
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>
2023-07-21 09:06:09 +00:00
Pierre-Emmanuel Patry
361fd8fea7 resolve: Add mappings for proc macros and resolving
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>
2023-07-21 09:06:09 +00:00
Pierre-Emmanuel Patry
224409f746 attribute: Add missing header guard
Missing header guard may cause infinitie include recursion.

gcc/rust/ChangeLog:

	* util/rust-attributes.h (RUST_ATTRIBUTES_H): Add missing header
	guard.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-07-21 09:06:09 +00:00
Pierre-Emmanuel Patry
dd4c38042c ast: Add manual dispatch for meta item downcasting
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>
2023-07-21 09:06:09 +00:00
Pierre-Emmanuel Patry
01c316bc2b resolve: Add extern crate proc macro collection
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>
2023-07-21 09:06:09 +00:00
Pierre-Emmanuel Patry
5539f28018 import: Load procedural macros into external crate
Load the procedural macro array into the external crate structure.

gcc/rust/ChangeLog:

	* metadata/rust-imports.cc (Import::try_package_in_directory):
	Add call to load macros before loading metadatas.
	* expand/rust-proc-macro.cc: Return empty vector instead of
	panicking on error.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-07-21 09:06:09 +00:00
Pierre-Emmanuel Patry
071e02ed91 import: Change raw pointer to unique_ptr
Replace Stream raw pointer with a smart pointer.

gcc/rust/ChangeLog:

	* metadata/rust-import-archive.cc (Stream_concatenate::do_peek):
	Remove deletion.
	(Stream_concatenate::do_advance): Likewise.
	(Import::find_archive_export_data): Replace with a smart
	pointer.
	* metadata/rust-imports.cc (add_search_path): Change return type
	to smart pointer.
	(Import::open_package): Likewise.
	(Import::try_package_in_directory): Likewise.
	(Import::find_export_data): Likewise.
	(Import::find_object_export_data): Likewise.
	(Import::Import): Change constructor to accept unique_ptr.
	* metadata/rust-imports.h: Change constructor prototype.
	* rust-session-manager.cc (Session::load_extern_crate): Change
	pointer to smart pointer.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-07-21 09:06:09 +00:00
Pierre-Emmanuel Patry
6b4f24c1ca import: Store procedural macros in extern crate
Store procedural macro data in extern crate node.

gcc/rust/ChangeLog:

	* metadata/rust-extern-crate.cc (ExternCrate::ExternCrate):
	Change constructor to accept procedural macro vector.
	* metadata/rust-extern-crate.h: Add vector of procecural macro
	in extern crate.
	* rust-session-manager.cc (Session::load_extern_crate): Add
	argument to new constructor call.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-07-21 09:06:09 +00:00
Pierre-Emmanuel Patry
d2e3536378 import: Change package opening prototypes
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>
2023-07-21 09:06:09 +00:00
Pierre-Emmanuel Patry
3dab250b5e import: Add cli extern crate resolution
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>
2023-07-21 09:06:09 +00:00
Owen Avery
6df293b14a Replace default argument with UNDEF_LOCATION
gcc/rust/ChangeLog:

	* ast/rust-ast-collector.h
	(TokenCollector::visit):
	Replace default argument with UNDEF_LOCATION.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-07-20 09:10:00 +00:00
Owen Avery
97cbd459f4 Replace Location with location_t in gccrs backend
gcc/rust/ChangeLog:

	* backend/rust-compile-base.cc: Replace Location with location_t.
	* backend/rust-compile-base.h: Likewise.
	* backend/rust-compile-block.cc: Likewise.
	* backend/rust-compile-expr.cc: Likewise.
	* backend/rust-compile-expr.h: Likewise.
	* backend/rust-compile-extern.h: Likewise.
	* backend/rust-compile-implitem.h: Likewise.
	* backend/rust-compile-intrinsic.cc: Likewise.
	* backend/rust-compile-item.h: Likewise.
	* backend/rust-compile-pattern.h: Likewise.
	* backend/rust-compile-resolve-path.cc: Likewise.
	* backend/rust-compile-stmt.cc: Likewise.
	* backend/rust-compile-type.cc: Likewise.
	* backend/rust-compile.cc: Likewise.
	* backend/rust-constexpr.cc: Likewise.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-07-20 09:09:33 +00:00
Muhammad Mahad
41e7dee103 gccrs: [E0268] break or continue used outside of loop
Refactored error description similiar to rustc.

gcc/rust/ChangeLog:

	* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit):
	refactored and call error function.

gcc/testsuite/ChangeLog:

	* rust/compile/break1.rs: Modified to pass test case.
	* rust/compile/continue1.rs: likewise.
	* rust/compile/break_continue_outside_loop.rs: New test.

Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
2023-07-20 09:06:44 +00:00
Pierre-Emmanuel Patry
aaeeaa2f77 Add a test for malformed derive declaration input
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>
2023-07-20 08:21:00 +00:00
Pierre-Emmanuel Patry
242f7a9267 proc macro: Add crate type regression tests
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>
2023-07-20 08:21:00 +00:00
Pierre-Emmanuel Patry
61fc7f1cb5 proc macro: Add help message to malformed derive
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>
2023-07-20 08:21:00 +00:00
Pierre-Emmanuel Patry
d6912fb38b proc macro: Detect malformed proc_macro_derive
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>
2023-07-20 08:21:00 +00:00
Pierre-Emmanuel Patry
f715169a6e proc macros: Add crate type attribute check
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>
2023-07-20 08:21:00 +00:00
Pierre-Emmanuel Patry
b8268b6b7b libproc_macro: Change rust Ident definition
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>
2023-07-19 15:03:42 +00:00
Pierre-Emmanuel Patry
4332fbfaec libproc_macro: Change Ident structure
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>
2023-07-19 15:03:42 +00:00
Pierre-Emmanuel Patry
04c9af6d0f proc_macro: Add from string implementation
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>
2023-07-19 14:31:42 +00:00
Pierre-Emmanuel Patry
9378b26777 cli: Add frust-type option
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>
2023-07-19 12:39:44 +00:00
Arthur Cohen
011c867c0a nr2.0: Add ForeverStack data structure.
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.
2023-07-19 09:52:38 +00:00
Marc Poulhiès
235dbf0b57 gccrs: rework the HIR dump pass
Nearly complete rewrite of the HIR dump pass.

fixes #693

gcc/rust/ChangeLog:

	* hir/rust-hir-dump.cc (convert_param_kind_to_str): New.
	(convert_new_bind_type_to_str): New.
	(convert_mut_to_str): New.
	(Dump::go): New.
	(Dump::put): New.
	(Dump::begin): New.
	(Dump::end): New.
	(Dump::begin_field): New.
	(Dump::end_field): New.
	(Dump::put_field): New.
	(Dump::visit_field): New.
	(Dump::visit): Refactor.
	(Dump::visit_collection): New.
	(Dump::do_traititem): New.
	(Dump::do_vis_item): New.
	(Dump::do_functionparam): New.
	(Dump::do_pathpattern): New.
	(Dump::do_structexprstruct): New.
	(Dump::do_expr): New.
	(Dump::do_pathexpr): New.
	(Dump::do_typepathsegment): New.
	(Dump::do_typepathfunction): New.
	(Dump::do_qualifiedpathtype): New.
	(Dump::do_operatorexpr): New.
	(Dump::do_mappings): New.
	(Dump::do_inner_attrs): New.
	(Dump::do_outer_attrs): New.
	(Dump::do_baseloopexpr): New.
	(Dump::do_ifletexpr): New.
	(Dump::do_struct): New.
	(Dump::do_enumitem): New.
	(Dump::do_traitfunctiondecl): New.
	(Dump::do_externalitem): New.
	(Dump::do_namefunctionparam): New.
	(Dump::do_stmt): New.
	(Dump::do_type): New.
	(Dump::do_item): New.
	(Dump::do_tuplefield): New.
	(Dump::do_structfield): New.
	(Dump::do_genericargs): New.
	(Dump::do_maybenamedparam): New.
	* hir/rust-hir-dump.h: Refactor.
	* hir/tree/rust-hir-item.h (enum_to_str): New.
	* hir/tree/rust-hir-type.h (enum_to_str): New.
	* hir/tree/rust-hir.cc (enum_to_str): New.
	* util/rust-common.h (enum_to_str): New.

Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
2023-07-18 20:34:44 +00:00
Arthur Cohen
3e4fe9978f nr2.0: Add basic Rib class
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>
2023-07-18 14:06:32 +00:00
Owen Avery
0e7f04ad26 Replace some more usages of Location with location_t
gcc/rust/ChangeLog:

	* ast/rust-ast.h: Replace Location with location_t.
	* ast/rust-expr.h: Likewise.
	* ast/rust-item.h: Likewise.
	* ast/rust-macro.h: Likewise.
	* ast/rust-path.h: Likewise.
	* ast/rust-pattern.h: Likewise.
	* ast/rust-stmt.h: Likewise.
	* ast/rust-type.h: Likewise.
	* hir/rust-ast-lower-base.h: Likewise.
	* hir/tree/rust-hir-expr.h: Likewise.
	* hir/tree/rust-hir-item.h: Likewise.
	* 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.h: Likewise.
	* lex/rust-token.h: Likewise.
	* resolve/rust-ast-resolve-pattern.h: Likewise.
	* typecheck/rust-hir-trait-reference.h: Likewise.
	* typecheck/rust-tyty-bounds.h: Likewise.
	* typecheck/rust-tyty-call.h: Likewise.
	* typecheck/rust-tyty-subst.h: Likewise.
	* typecheck/rust-tyty-util.h: Likewise.
	* typecheck/rust-tyty.h: Likewise.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-07-18 09:08:16 +00:00
Owen Avery
9cf8b77a3e Replace some usages of Location with location_t
gcc/rust/ChangeLog:

	* ast/rust-ast-collector.cc: Replace Location with location_t.
	* ast/rust-ast.cc: Likewise.
	* ast/rust-ast.h: Likewise.
	* ast/rust-expr.h: Likewise.
	* ast/rust-item.h: Likewise.
	* ast/rust-macro.h: Likewise.
	* ast/rust-path.cc: Likewise.
	* ast/rust-path.h: Likewise.
	* ast/rust-pattern.h: Likewise.
	* ast/rust-stmt.h: Likewise.
	* ast/rust-type.h: Likewise.
	* backend/rust-compile-base.cc: Likewise.
	* backend/rust-compile-base.h: Likewise.
	* backend/rust-compile-block.cc: Likewise.
	* backend/rust-compile-expr.cc: Likewise.
	* backend/rust-compile-expr.h: Likewise.
	* backend/rust-compile-fnparam.cc: Likewise.
	* backend/rust-compile-fnparam.h: Likewise.
	* backend/rust-compile-intrinsic.cc: Likewise.
	* backend/rust-compile-pattern.cc: Likewise.
	* backend/rust-compile-resolve-path.h: Likewise.
	* backend/rust-compile.cc: Likewise.
	* checks/errors/rust-const-checker.cc: Likewise.
	* checks/errors/rust-const-checker.h: Likewise.
	* checks/errors/rust-unsafe-checker.cc: Likewise.
	* checks/errors/rust-unsafe-checker.h: Likewise.
	* expand/rust-macro-builtins.cc: Likewise.
	* expand/rust-macro-expand.h: Likewise.
	* hir/rust-ast-lower-base.h: Likewise.
	* hir/rust-ast-lower-implitem.h: Likewise.
	* hir/rust-ast-lower-item.cc: Likewise.
	* hir/tree/rust-hir-expr.h: Likewise.
	* hir/tree/rust-hir-item.h: Likewise.
	* 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.cc: Likewise.
	* hir/tree/rust-hir.h: Likewise.
	* lex/rust-token.h: Likewise.
	* metadata/rust-extern-crate.cc: Likewise.
	* metadata/rust-extern-crate.h: Likewise.
	* parse/rust-parse-impl.h: Likewise.
	* parse/rust-parse.h: Likewise.
	* resolve/rust-ast-resolve-expr.cc: Likewise.
	* resolve/rust-ast-resolve-implitem.h: Likewise.
	* resolve/rust-ast-resolve-pattern.h: Likewise.
	* resolve/rust-ast-resolve-stmt.h: Likewise.
	* resolve/rust-ast-resolve-toplevel.h: Likewise.
	* resolve/rust-ast-resolve-type.h: Likewise.
	* resolve/rust-name-resolver.cc: Likewise.
	* resolve/rust-name-resolver.h: Likewise.
	* rust-diagnostics.cc: Likewise.
	* rust-diagnostics.h: Likewise.
	* rust-gcc.cc: Likewise.
	* rust-session-manager.cc: Likewise.
	* rust-session-manager.h: Likewise.
	* typecheck/rust-casts.cc: Likewise.
	* typecheck/rust-casts.h: Likewise.
	* typecheck/rust-coercion.cc: Likewise.
	* typecheck/rust-coercion.h: Likewise.
	* typecheck/rust-hir-path-probe.cc: Likewise.
	* typecheck/rust-hir-path-probe.h: Likewise.
	* typecheck/rust-hir-trait-reference.cc: Likewise.
	* typecheck/rust-hir-trait-reference.h: Likewise.
	* typecheck/rust-hir-trait-resolve.cc: Likewise.
	* typecheck/rust-hir-type-check-base.cc: Likewise.
	* typecheck/rust-hir-type-check-base.h: Likewise.
	* typecheck/rust-hir-type-check-item.cc: Likewise.
	* typecheck/rust-hir-type-check-item.h: Likewise.
	* typecheck/rust-hir-type-check-path.cc: Likewise.
	* typecheck/rust-hir-type-check-pattern.cc: Likewise.
	* typecheck/rust-hir-type-check-pattern.h: Likewise.
	* typecheck/rust-hir-type-check-type.cc: Likewise.
	* typecheck/rust-hir-type-check-type.h: Likewise.
	* typecheck/rust-hir-type-check.cc: Likewise.
	* typecheck/rust-hir-type-check.h: Likewise.
	* typecheck/rust-substitution-mapper.cc: Likewise.
	* typecheck/rust-substitution-mapper.h: Likewise.
	* typecheck/rust-type-util.cc: Likewise.
	* typecheck/rust-typecheck-context.cc: Likewise.
	* typecheck/rust-tyty-bounds.cc: Likewise.
	* typecheck/rust-tyty-call.h: Likewise.
	* typecheck/rust-tyty-subst.cc: Likewise.
	* typecheck/rust-tyty-subst.h: Likewise.
	* typecheck/rust-tyty-util.cc: Likewise.
	* typecheck/rust-tyty-util.h: Likewise.
	* typecheck/rust-tyty.cc: Likewise.
	* typecheck/rust-tyty.h: Likewise.
	* typecheck/rust-unify.cc: Likewise.
	* typecheck/rust-unify.h: Likewise.
	* util/rust-hir-map.cc: Likewise.
	* util/rust-hir-map.h: Likewise.
	* util/rust-identifier.h: Likewise.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-07-17 11:17:14 +00:00
Owen Avery
b7c8f5a33b Move some Gcc_backend method definitions out of class declaration
gcc/rust/ChangeLog:

	* rust-gcc.cc
	(Gcc_backend::debug): Move out of class declaration.
	(Gcc_backend::get_identifier_node): Likewise.
	(Gcc_backend::wchar_type): Likewise.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-07-17 09:40:41 +00:00
Muhammad Mahad
d7651385b6 gccrs: [E0423] expected function, tuple struct or tuple variant, found struct
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>
2023-07-17 09:40:02 +00:00
Owen Avery
95e8c2d54f Remove Linemap::predeclared_location
gcc/rust/ChangeLog:

	* rust-linemap.h (Linemap::predeclared_location): Remove.
	* backend/rust-compile-type.cc:
	Replace Linemap::predeclared_location with BUILTINS_LOCATION.
	* resolve/rust-name-resolver.cc: Likewise.
	* typecheck/rust-hir-type-check-type.cc: Likewise.
	* typecheck/rust-tyty.cc: Likewise.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-07-17 09:39:11 +00:00
Owen Avery
ea69361b34 Add include guard for rust-gcc.h
gcc/rust/ChangeLog:

	* rust-gcc.h: Add include guard.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-07-17 09:38:29 +00:00
Arthur Cohen
866512cbc0 rust-unreachable: Add specific behavior for rust_unreachable
As discussed during the community call, rust_unreachable() should
always trigger an internal compiler error and should not offer
the behavior of __builtin_unreachable when asserts are disabled, unlike
gcc_unreachable().

gcc/rust/ChangeLog:

	* rust-system.h (rust_unreachable): Change definition to fancy_abort
	* ast/rust-ast-collector.cc (TokenCollector::visit): Use rust_unreachable
	instead of gcc_unreachable.
	(get_delimiters): Likewise.
	* ast/rust-ast-dump.h: Likewise.
	* ast/rust-ast-formatting.cc (get_string_in_delims): Likewise.
	(get_mode_dump_desc): Likewise.
	* ast/rust-ast.cc (Visibility::as_string): Likewise.
	(UseTreeGlob::as_string): Likewise.
	* ast/rust-ast.h: Likewise.
	* ast/rust-macro.h: Likewise.
	* ast/rust-path.h: Likewise.
	* backend/rust-compile-expr.cc (sort_tuple_patterns): Likewise.
	(CompileExpr::visit): Likewise.
	(CompileExpr::generate_closure_fntype): Likewise.
	* backend/rust-compile-intrinsic.cc (op_with_overflow_inner): Likewise.
	* backend/rust-compile-pattern.cc (CompilePatternBindings::visit): Likewise.
	(CompilePatternLet::visit): Likewise.
	* backend/rust-constexpr.cc (base_field_constructor_elt): Likewise.
	(eval_array_reference): Likewise.
	(label_matches): Likewise.
	(eval_store_expression): Likewise.
	(eval_call_expression): Likewise.
	(build_data_member_initialization): Likewise.
	(array_index_cmp): Likewise.
	(get_array_or_vector_nelts): Likewise.
	(eval_bit_field_ref): Likewise.
	(eval_loop_expr): Likewise.
	(potential_constant_expression_1): Likewise.
	* backend/rust-mangle.cc (v0_simple_type_prefix): Likewise.
	(v0_type_prefix): Likewise.
	(v0_mangle_item): Likewise.
	(Mangler::mangle_item): Likewise.
	* backend/rust-tree.cc (convert_to_void): Likewise.
	(type_memfn_quals): Likewise.
	(rs_tree_equal): Likewise.
	(fold_offsetof): Likewise.
	(fold_builtin_source_location): Likewise.
	(lvalue_error): Likewise.
	* backend/rust-tree.h (struct named_decl_hash): Likewise.
	(struct named_label_hash): Likewise.
	* checks/errors/privacy/rust-visibility-resolver.cc
	(VisibilityResolver::resolve_visibility): Likewise.
	(VisibilityResolver::visit): Likewise.
	* checks/errors/rust-const-checker.cc (ConstChecker::ctx_to_str): Likewise.
	* checks/errors/rust-feature.cc (Feature::create): Likewise.
	* expand/rust-expand-visitor.cc (get_traits_to_derive): Likewise.
	(derive_item): Likewise.
	(expand_item_attribute): Likewise.
	(expand_stmt_attribute): Likewise.
	* expand/rust-macro-expand.cc (MacroExpander::match_matcher): Likewise.
	(MacroExpander::match_repetition): Likewise.
	(transcribe_context): Likewise.
	(MacroExpander::import_proc_macros): Likewise.
	(MacroExpander::parse_proc_macro_output): Likewise.
	* expand/rust-macro-expand.h: Likewise.
	* expand/rust-macro-invoc-lexer.h: Likewise.
	* expand/rust-macro-substitute-ctx.cc (SubstituteCtx::substitute_token): Likewise.
	* expand/rust-proc-macro-invoc-lexer.h: Likewise.
	* expand/rust-proc-macro.cc (load_macros): Likewise.
	* hir/rust-ast-lower-base.cc (ASTLoweringBase::lower_generic_args): Likewise.
	(ASTLoweringBase::lower_literal): Likewise.
	* hir/rust-ast-lower-expr.cc (ASTLoweringExpr::visit): Likewise.
	* hir/rust-ast-lower-pattern.cc (ASTLoweringPattern::visit): Likewise.
	* hir/rust-ast-lower-type.cc (ASTLoweringType::visit): Likewise.
	* hir/rust-hir-dump.cc (Dump::visit): Likewise.
	* hir/tree/rust-hir.cc (get_string_in_delims): Likewise.
	(Visibility::as_string): Likewise.
	(UseTreeGlob::as_string): Likewise.
	(CompoundAssignmentExpr::as_string): Likewise.
	(ArithmeticOrLogicalExpr::as_string): Likewise.
	* lex/rust-lex.cc (Lexer::parse_byte_string): Likewise.
	(Lexer::parse_string): Likewise.
	* lex/rust-token.cc (RS_TOKEN): Likewise.
	* parse/rust-parse-impl.h (Parser::parse_simple_path_segment): Likewise.
	(Parser::parse_path_ident_segment): Likewise.
	(Parser::parse_attr_input): Likewise.
	(Parser::parse_inherent_impl_item): Likewise.
	(Parser::parse_trait_impl_item): Likewise.
	(Parser::parse_type_path_segment): Likewise.
	(Parser::parse_reference_type): Likewise.
	(get_lbp_for_comparison_expr): Likewise.
	* parse/rust-parse.cc (peculiar_fragment_match_compatible): Likewise.
	* resolve/rust-ast-resolve-path.cc (ResolvePath::resolve_path): Likewise.
	* resolve/rust-ast-resolve-pattern.cc (PatternDeclaration::visit): Likewise.
	* resolve/rust-ast-resolve-type.cc (ResolveRelativeTypePath::go): Likewise.
	(ResolveTypeToCanonicalPath::visit): Likewise.
	(ResolveGenericArgs::resolve_disambiguated_generic): Likewise.
	* rust-gcc.cc (operator_to_tree_code): Likewise.
	(fetch_overflow_builtins): Likewise.
	(Gcc_backend::non_zero_size_type): Likewise.
	(Gcc_backend::convert_tree): Likewise.
	* rust-lang.cc (grs_langhook_type_for_mode): Likewise.
	(grs_langhook_global_bindings_p): Likewise.
	(grs_langhook_pushdecl): Likewise.
	(grs_langhook_getdecls): Likewise.
	(convert): Likewise.
	* typecheck/rust-autoderef.h: Likewise.
	* typecheck/rust-hir-path-probe.cc: Likewise.
	* typecheck/rust-hir-trait-reference.cc (TraitItemReference::get_tyty): Likewise.
	* typecheck/rust-hir-type-check-base.cc (TypeCheckBase::resolve_literal): Likewise.
	* typecheck/rust-hir-type-check-expr.cc: Likewise.
	* typecheck/rust-hir-type-check-expr.h: Likewise.
	* typecheck/rust-hir-type-check-implitem.cc (TypeCheckImplItem::visit): Likewise.
	* typecheck/rust-hir-type-check-pattern.cc (TypeCheckPattern::visit): Likewise.
	* typecheck/rust-hir-type-check-stmt.h: Likewise.
	* typecheck/rust-hir-type-check.cc (TraitItemReference::get_type_from_fn): Likewise.
	* typecheck/rust-substitution-mapper.h: Likewise.
	* typecheck/rust-typecheck-context.cc (TypeCheckContextItem::get_context_type): Likewise.
	* typecheck/rust-tyty-call.h: Likewise.
	* typecheck/rust-tyty.cc (TypeKindFormat::to_string): Likewise.
	(BaseType::monomorphized_clone): Likewise.
	(VariantDef::variant_type_string): Likewise.
	(ClosureType::handle_substitions): Likewise.
	(IntType::as_string): Likewise.
	(UintType::as_string): Likewise.
	(FloatType::as_string): Likewise.
	* typecheck/rust-unify.cc (UnifyRules::expect_projection): Likewise.
	* util/rust-token-converter.cc (convert): Likewise.
	(from_literal): Likewise.
	(from_group): Likewise.
	(from_tokentree): Likewise.
2023-07-14 17:03:20 +00:00
Muhammad Mahad
a34d667572 gccrs: [E0658] Use of unstable feature
gcc/rust/ChangeLog:

	* checks/errors/rust-feature-gate.cc (FeatureGate::gate):
	called error function.

gcc/testsuite/ChangeLog:

	* rust/compile/changed_intrinsics.rs: New test.

Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
2023-07-14 17:02:18 +00:00
Muhammad Mahad
04353fb887 gccrs: [E0093] Declaration of unknown intrinsic function
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>
2023-07-14 17:02:09 +00:00
Muhammad Mahad
601c2893aa gccrs: [E0133] Use of unsafe code outside of unsafe function or block
gcc/rust/ChangeLog:

	* checks/errors/rust-unsafe-checker.cc (check_unsafe_call):
	called error function.

Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
2023-07-13 12:13:37 +00:00
Owen Avery
446ef149eb Remove RichLocation typedef
gcc/rust/ChangeLog:

	* rust-location.h
	(typedef RichLocation): Remove.
	* expand/rust-macro-expand.cc: Replace RichLocation with rich_location.
	* hir/rust-ast-lower-base.cc: Likewise.
	* resolve/rust-ast-resolve-implitem.h: Likewise.
	* resolve/rust-ast-resolve-stmt.h: Likewise.
	* resolve/rust-ast-resolve-toplevel.h: Likewise.
	* rust-diagnostics.cc: Likewise.
	* rust-diagnostics.h: Likewise.
	* rust-session-manager.cc: Likewise.
	* typecheck/rust-casts.cc: Likewise.
	* typecheck/rust-coercion.cc: Likewise.
	* typecheck/rust-hir-inherent-impl-overlap.h: Likewise.
	* typecheck/rust-hir-path-probe.h: Likewise.
	* typecheck/rust-hir-trait-reference.cc: Likewise.
	* typecheck/rust-hir-type-check-expr.cc: Likewise.
	* typecheck/rust-hir-type-check-implitem.cc: Likewise.
	* typecheck/rust-hir-type-check-item.cc: Likewise.
	* typecheck/rust-hir-type-check-pattern.cc: Likewise.
	* typecheck/rust-tyty-cmp.h: Likewise.
	* typecheck/rust-tyty-subst.cc: Likewise.
	* typecheck/rust-tyty.cc: Likewise.
	* typecheck/rust-unify.cc: Likewise.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-07-13 12:07:26 +00:00
Owen Avery
d7f5c14279 Remove Linemap::start_line
gcc/rust/ChangeLog:

	* lex/rust-lex.cc
	(Lexer::start_line): Use linemap_line_start.
	* rust-linemap.cc
	(Linemap::start_line): Remove.
	* rust-linemap.h
	(Linemap::start_line): Remove.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-07-13 12:06:57 +00:00
Owen Avery
b75357f4a1 Change class RichLocation into typedef
gcc/rust/ChangeLog:

	* rust-linemap.cc
	(RichLocation::RichLocation): Remove.
	(RichLocation::~RichLocation): Remove.
	(RichLocation::add_range): Remove.
	(RichLocation::add_fixit_insert_before): Remove.
	(RichLocation::add_fixit_insert_after): Remove.
	* rust-location.h
	(class RichLocation): Remove.
	* rust-diagnostics.cc
	(rust_be_error_at): Remove RichLocation::get invocation.
	* expand/rust-macro-expand.cc: Fix RichLocation constructor.
	* hir/rust-ast-lower-base.cc: Likewise.
	* resolve/rust-ast-resolve-implitem.h: Likewise.
	* resolve/rust-ast-resolve-stmt.h: Likewise.
	* resolve/rust-ast-resolve-toplevel.h: Likewise.
	* rust-session-manager.cc: Likewise.
	* typecheck/rust-casts.cc: Likewise.
	* typecheck/rust-coercion.cc: Likewise.
	* typecheck/rust-hir-inherent-impl-overlap.h: Likewise.
	* typecheck/rust-hir-path-probe.h: Likewise.
	* typecheck/rust-hir-trait-reference.cc: Likewise.
	* typecheck/rust-hir-type-check-expr.cc: Likewise.
	* typecheck/rust-hir-type-check-implitem.cc: Likewise.
	* typecheck/rust-hir-type-check-item.cc: Likewise.
	* typecheck/rust-hir-type-check-pattern.cc: Likewise.
	* typecheck/rust-tyty-cmp.h: Likewise.
	* typecheck/rust-tyty-subst.cc: Likewise.
	* typecheck/rust-tyty.cc: Likewise.
	* typecheck/rust-unify.cc: Likewise.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-07-12 14:43:18 +00:00
Owen Avery
486c8b87e4 Remove Linemap::get_location
gcc/rust/ChangeLog:

	* lex/rust-lex.cc
	(Lexer::get_current_location): Use linemap_position_for_column.
	* rust-session-manager.cc
	(Session::handle_crate_name): Likewise.
	* rust-linemap.cc
	(Linemap::get_location): Remove.
	* rust-linemap.h
	(Linemap::get_location): Likewise.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-07-12 14:40:54 +00:00
Marc Poulhiès
1531c69922 mklog: handle Signed-Off-By, minor cleanup
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>
2023-07-12 11:41:31 +00:00
Pierre-Emmanuel Patry
0bcba57962 dump: Output escaped character values
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>
2023-07-12 11:40:07 +00:00
Marc Poulhiès
4bbf156f33 gccrs: minor HIR cleanup
Remove more rust_assert in accessors.

gcc/rust/ChangeLog:

	* hir/tree/rust-hir-type.h (MaybeNamedParam::get_type): Remove
	rust_assert.
	(BareFunctionType::get_return_type): Likewise.

Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
2023-07-12 09:07:30 +00:00
Pierre-Emmanuel Patry
a8d9f91114 remove braces around scalar initializers
Remove useless braces around scalar initializers. This will also remove
some warning emitted by the compiler and avoid cluttering it's output.

gcc/rust/ChangeLog:

	* backend/rust-compile-intrinsic.cc (offset_handler): Remove
	braces.
	(sizeof_handler): Likewise.
	(transmute_handler): Likewise.
	(rotate_handler): Likewise.
	(wrapping_op_handler_inner): Likewise.
	(op_with_overflow_inner): Likewise.
	(atomic_load_handler_inner): Likewise.
	(unchecked_op_inner): Likewise.
	(uninit_handler): Likewise.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-07-12 09:06:54 +00:00
Pierre-Emmanuel Patry
2377e5b2da Add missing virtual destructor to interfaces
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>
2023-07-12 09:06:54 +00:00
Pierre-Emmanuel Patry
010e701e5f Change specifier of some forward declaration
Change storage specifier of some forward declaration to satisfy compiler
warning.

gcc/rust/ChangeLog:

	* hir/tree/rust-hir-full-decls.h (struct Crate): Change to
	class.
	(class Crate): Likewise.
	(struct StructField): Likewise.
	(class StructField): Likewise.
	(struct TupleField): Likewise.
	(class TupleField): Likewise.
	(struct TraitFunctionDecl): Likewise.
	(class TraitFunctionDecl): Likewise.
	* rust-session-manager.h (struct Crate): Likewise.
	(class Crate): Likewise.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-07-12 09:06:54 +00:00
Owen Avery
d8b86f0d25 Remove unnecessary usage of Location copy constructor
gcc/rust/ChangeLog:

	* ast/rust-expr.h
	(MetaItemPathLit::get_locus): Remove copy construction.
	* backend/rust-constexpr.cc
	(eval_constant_expression): Likewise.
	(is_valid_constexpr_fn): Likewise.
	* util/rust-token-converter.cc
	(convert): Likewise.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-07-12 08:11:15 +00:00
Owen Avery
b68dd7e641 Merge Linemap::to_string into Linemap::location_to_string
gcc/rust/ChangeLog:

	* lex/rust-lex.cc
	(Lexer::dump_and_skip): Use location_to_string.
	* rust-linemap.cc
	(Linemap::to_string): Move to...
	(Linemap::location_to_string): ... here.
	* rust-linemap.h
	(Linemap::to_string): Remove.
	(Linemap::location_to_string): Remove definition.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-07-12 08:10:38 +00:00
Marc Poulhiès
ff2d1b7cea gccrs: minor HIR cleanup
Add one more accessor and remove some rust_assert() in accessors for unique_ptr&.

gcc/rust/ChangeLog:

	* hir/tree/rust-hir-expr.h (TypeCastExpr::get_casted_expr): Remove
	assert in accessor.
	(TypeCastExpr::get_type_to_convert_to): Likewise.
	(CompoundAssignmentExpr::get_left_expr): Likewise.
	(CompoundAssignmentExpr::get_right_expr): Likewise.
	(GroupedExpr::get_expr_in_parens): Likewise.
	(TupleIndexExpr::get_tuple_expr): Likewise.
	(FieldAccessExpr::get_receiver_expr): Likewise.
	(ClosureParam::get_pattern): Likewise.
	(ClosureParam::get_type): Likewise.
	(ExprType::get_return_type): Likewise.
	(IfLetExpr::get_scrutinee_expr): Likewise.
	(MatchArm::get_guard_expr): Likewise.
	(MatchExpr::get_scrutinee_expr): Likewise.
	* hir/tree/rust-hir-item.h (TypeParam::get_type): Likewise.
	(SelfParam::get_type): Likewise.
	(Function::get_return_type): Likewise.
	(TypeAlias::get_type_aliased): Likewise.
	(StructField::get_field_type): Likewise.
	(TraitFunctionDecl::get_block_expr): Likewise.
	(ImplBlock::get_trait_ref): Likewise.
	* hir/tree/rust-hir-path.h (ConstGenericArg::get_expression): New.
	(TypePathFunction::get_return_type): Remove assert in accessor.
	(QualifiedPathType::get_trait): Likewise.
	* hir/tree/rust-hir-pattern.h (PatternType::get_lower_bound): Likewise.
	(PatternType::get_upper_bound): Likewise.
	(ReferencePattern::get_referenced_pattern): Likewise.
	* hir/tree/rust-hir.h (ConstGenericParam::get_default_expression): Likewise.

Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
2023-07-11 19:13:01 +00:00
Muhammad Mahad
1827610473 gccrs: [E0124] field x is already declared in struct
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>
2023-07-11 10:26:26 +00:00
Owen Avery
5d124d1512 Add rust_error_at accepting location_t and ErrorCode
gcc/rust/ChangeLog:

	* rust-diagnostics.cc
	(rust_be_error_at): Add function accepting location_t and ErrorCode.
	(rust_error_at): Likewise.
	* rust-diagnostics.h
	(rust_error_at): Likewise.
	(rust_be_error_at): Likewise.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-07-11 10:25:37 +00:00
Owen Avery
6ba9a11eae Merge Gcc_linemap into Linemap
gcc/rust/ChangeLog:

	* rust-linemap.cc
	(class Gcc_linemap): Remove.
	(Gcc_linemap::start_file): Move to...
	(Linemap::start_file): ... here.
	(Gcc_linemap::to_string): Move to...
	(Linemap::to_string): ... here.
	(Gcc_linemap::stop): Move to...
	(Linemap::stop): ... here.
	(Gcc_linemap::start_line): Move to...
	(Linemap::start_line): ... here.
	(Gcc_linemap::get_location): Move to...
	(Linemap::get_location): ... here.
	(rust_get_linemap): Use Linemap.
	* rust-linemap.h
	(Linemap::in_file_): New field from Gcc_linemap.
	(Linemap::Linemap): Initialize in_file_.
	(Linemap::~Linemap): Make non-virtual.
	(Linemap::start_file): Likewise.
	(Linemap::start_line): Likewise.
	(Linemap::get_location): Likewise.
	(Linemap::stop): Likewise.
	(Linemap::to_string): Likewise.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-07-11 10:24:34 +00:00
Arthur Cohen
3016c44e53 gccrs: Remove Rust::Optional in favor of tl::optional
gcc/rust/ChangeLog:

	* Make-lang.in: Remove rust-optional-test.cc's object file
	* ast/rust-macro.h: Remove use of Rust::Optional
	* backend/rust-compile-base.cc
	(HIRCompileBase::resolve_method_address): Likewise.
	* checks/errors/privacy/rust-privacy-reporter.cc
	(PrivacyReporter::check_for_privacy_violation): Likewise.
	(PrivacyReporter::visit): Likewise.
	* checks/errors/privacy/rust-privacy-reporter.h: Likewise.
	* checks/errors/rust-feature-gate.cc (FeatureGate::check): Likewise.
	* checks/errors/rust-feature.cc (Feature::create): Likewise.
	(Feature::as_name): Likewise.
	* checks/errors/rust-feature.h: Likewise.
	* expand/rust-macro-builtins.cc: Likewise.
	* lex/rust-lex.cc (Lexer::Lexer): Likewise.
	(Lexer::skip_token): Likewise.
	(Lexer::dump_and_skip): Likewise.
	* lex/rust-lex.h: Likewise.
	* resolve/rust-ast-resolve-path.cc (ResolvePath::resolve_path): Likewise.
	* resolve/rust-ast-resolve-type.cc (ResolveRelativeTypePath::go): Likewise.
	* rust-lang.cc (run_rust_tests): Likewise.
	* rust-session-manager.cc (Session::compile_crate): Likewise.
	(TargetOptions::dump_target_options): Likewise.
	* rust-session-manager.h (struct TargetOptions): Likewise.
	* util/rust-hir-map.cc (Mappings::lookup_module_children): Likewise.
	(Mappings::lookup_module_chidren_items): Likewise.
	(Mappings::lookup_module_child): Likewise.
	(Mappings::lookup_parent_module): Likewise.
	* util/rust-hir-map.h (RUST_HIR_MAP_H): Likewise.
	* util/rust-optional-test.cc: Removed.
	* util/rust-optional.h: Removed.
2023-07-10 15:54:56 +00:00
Owen Avery
1fe255e492 Replace Linemap::unknown_location with UNKNOWN_LOCATION
gcc/rust/ChangeLog:

	* rust-linemap.h (Linemap::unknown_location): Remove.
	* ast/rust-ast.cc:
	Replace Linemap::unknown_location with UNKNOWN_LOCATION.
	* ast/rust-path.cc: Likewise.
	* hir/tree/rust-hir.cc: Likewise.
	* metadata/rust-imports.cc: Likewise.
	* parse/rust-parse-impl.h: Likewise.
	* parse/rust-parse.h: Likewise.
	* rust-backend.h: Likewise.
	* rust-diagnostics.cc: Likewise.
	* rust-session-manager.cc: Likewise.
	* typecheck/rust-tyty.cc: Likewise.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-07-10 08:31:35 +00:00
Muhammad Mahad
a06cec181d gccrs: [E0070] invalid left-hand side of assignment
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>
2023-07-09 13:06:33 +00:00
Muhammad Mahad
f7a29f5653 gccrs: [E0061] Refactored argument mismatch error function
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>
2023-07-09 13:03:04 +00:00
Arthur Cohen
3ebcb20e71 nr2.0: Add complex testcases
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>
2023-07-09 11:54:21 +00:00
Arthur Cohen
44ffe11932 expected: Adapt type to GCC's requirements.
Disable exceptions and remove inclusion of poisoned headers.

gcc/rust/ChangeLog:

	* util/expected.h: Adapt class to GCC requirements.
2023-07-09 11:53:11 +00:00
Arthur Cohen
ba8453aeb7 util: Add tl::expected type
Directly taken from https://github.com/TartanLlama/expected.

gcc/rust/ChangeLog:

	* util/expected.h: New file.
2023-07-09 11:53:11 +00:00
Arthur Cohen
e74cb8201f optional: Adapt class to GCC's standards.
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.
2023-07-09 11:52:26 +00:00
Arthur Cohen
49a6c70d60 optional: Import tl's optional type
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.
2023-07-09 11:52:26 +00:00
Owen Avery
763dd38a49 Replace value initialization of Location with UNDEF_LOCATION
gcc/rust/ChangeLog:

	* rust-location.h (UNDEF_LOCATION): New.
	* ast/rust-ast-collector.cc: Replace Location () with UNDEF_LOCATION.
	* ast/rust-ast-fragment.cc: Likewise.
	* ast/rust-ast.h: Likewise.
	* ast/rust-expr.h: Likewise.
	* ast/rust-item.h: Likewise.
	* ast/rust-macro.h: Likewise.
	* ast/rust-path.h: Likewise.
	* ast/rust-type.h: Likewise.
	* backend/rust-compile-expr.cc: Likewise.
	* backend/rust-compile-extern.h: Likewise.
	* backend/rust-compile-implitem.h: Likewise.
	* backend/rust-compile-intrinsic.cc: Likewise.
	* backend/rust-compile-item.h: Likewise.
	* backend/rust-compile.cc: Likewise.
	* backend/rust-constexpr.cc: Likewise.
	* expand/rust-expand-visitor.cc: Likewise.
	* expand/rust-macro-expand.cc: Likewise.
	* expand/rust-macro-expand.h: Likewise.
	* expand/rust-macro-invoc-lexer.cc: Likewise.
	* expand/rust-proc-macro-invoc-lexer.cc: Likewise.
	* expand/rust-proc-macro.cc: Likewise.
	* hir/tree/rust-hir-expr.h: Likewise.
	* hir/tree/rust-hir-item.h: Likewise.
	* hir/tree/rust-hir-path.h: Likewise.
	* hir/tree/rust-hir-type.h: Likewise.
	* hir/tree/rust-hir.h: Likewise.
	* lex/rust-lex.cc: Likewise.
	* metadata/rust-export-metadata.cc: Likewise.
	* parse/rust-parse-impl.h: Likewise.
	* resolve/rust-ast-resolve-item.cc: Likewise.
	* resolve/rust-ast-resolve.cc: Likewise.
	* rust-diagnostics.h: Likewise.
	* rust-session-manager.cc: Likewise.
	* typecheck/rust-autoderef.cc: Likewise.
	* typecheck/rust-coercion.cc: Likewise.
	* typecheck/rust-hir-dot-operator.cc: Likewise.
	* typecheck/rust-hir-path-probe.cc: Likewise.
	* typecheck/rust-hir-trait-reference.cc: Likewise.
	* typecheck/rust-hir-trait-reference.h: Likewise.
	* typecheck/rust-hir-type-check-expr.cc: Likewise.
	* typecheck/rust-hir-type-check-implitem.cc: Likewise.
	* typecheck/rust-hir-type-check-type.cc: Likewise.
	* typecheck/rust-hir-type-check.cc: Likewise.
	* typecheck/rust-tyty-bounds.cc: Likewise.
	* typecheck/rust-tyty-subst.cc: Likewise.
	* typecheck/rust-tyty.cc: Likewise.
	* util/rust-hir-map.cc: Likewise.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-07-09 08:29:07 +00:00
Pierre-Emmanuel Patry
e4647c3f34 collector: Fix abi output
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>
2023-07-07 13:46:54 +00:00
Pierre-Emmanuel Patry
241fcaeb55 collector: Fix remaining trait & extern issues
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>
2023-07-07 13:46:54 +00:00
Pierre-Emmanuel Patry
925310c10f collector: Output extern function attributes
Outer attributes on external functions did not output correctly.

gcc/rust/ChangeLog:

	* ast/rust-ast-collector.cc (TokenCollector::visit): Output
	outer attributes on external functions.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-07-07 13:46:54 +00:00
Pierre-Emmanuel Patry
835f9300bd collector: Fix method qualifier output
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>
2023-07-07 13:46:54 +00:00
Pierre-Emmanuel Patry
eb8f51036a collector: Add where clause to trait impl block
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>
2023-07-07 13:46:54 +00:00
Pierre-Emmanuel Patry
8b28b320d3 collector: Output outer attributes on blockexpr
Outer attributes on block expr did not output properly.

gcc/rust/ChangeLog:

	* ast/rust-ast-collector.cc (TokenCollector::visit): Add outer
	attributes to collector output.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-07-07 13:46:54 +00:00
Pierre-Emmanuel Patry
257d6ce56f collector: Add variadics to collector output
Variadics were missing from collector output for external functions.

gcc/rust/ChangeLog:

	* ast/rust-ast-collector.cc (TokenCollector::visit): Add
	variadics in collector output.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-07-07 13:46:54 +00:00
Pierre-Emmanuel Patry
ac9003b440 collector: Add generics to external functions
Add generic to external functiond declaration collector output.

gcc/rust/ChangeLog:

	* ast/rust-ast-collector.cc (TokenCollector::visit): Add
	generics.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-07-07 13:46:54 +00:00
Pierre-Emmanuel Patry
ee95b41c07 collector: Fix missing trait generics
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>
2023-07-07 13:46:54 +00:00
Pierre-Emmanuel Patry
dc6fb87fcf collector: Reformat trait impl
Trait impl were not readable, hence the reformat.

gcc/rust/ChangeLog:

	* ast/rust-ast-collector.cc (TokenCollector::visit): Reformat
	trait impl block.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-07-07 13:46:54 +00:00
Pierre-Emmanuel Patry
7743aeabab collector: Add generic to inherent impl block
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>
2023-07-07 13:46:54 +00:00
Pierre-Emmanuel Patry
0081ef0dad dump: Fix dollar spacing rule
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>
2023-07-07 13:46:54 +00:00
Pierre-Emmanuel Patry
af4407fdf6 collector: Change match arm format
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>
2023-07-07 13:46:54 +00:00
Pierre-Emmanuel Patry
23d13cbcb3 collector: Fix trait impl block
Trait impl block did not output any generic declaration nor the trait
excalamation mark.

gcc/rust/ChangeLog:

	* ast/rust-ast-collector.cc (TokenCollector::visit): Fix trait
	impl block output.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-07-07 13:46:54 +00:00
Pierre-Emmanuel Patry
1d184037a3 collector: Fix doubled generics
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>
2023-07-07 13:46:54 +00:00
Pierre-Emmanuel Patry
90160c17bb collector: Fix output for function qualifiers
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>
2023-07-07 13:46:54 +00:00
Pierre-Emmanuel Patry
b0da1695a8 collector: Fix method self parameter
Fix visitor for self parameter in methods.

gcc/rust/ChangeLog:

	* ast/rust-ast-collector.cc (TokenCollector::visit): Fix self
	param output.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-07-07 13:46:54 +00:00
Pierre-Emmanuel Patry
ff0e18be3f dump: Fix spacing with dots and references
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>
2023-07-07 13:46:54 +00:00
Pierre-Emmanuel Patry
8785f55655 collector: Fix some token collector
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>
2023-07-07 13:46:54 +00:00
Owen Avery
bfea515f42 Create MacroInvocLexerBase
gcc/rust/ChangeLog:

	* expand/rust-macro-invoc-lexer.h
	(class MacroInvocLexerBase): New.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-07-07 13:05:01 +00:00
Owen Avery
5ca1ed0397 Reduce Linemap/Gcc_linemap abstraction further
gcc/rust/ChangeLog:

	* expand/rust-macro-builtins.cc
	(source_relative_path): Use LOCATION_FILE.
	(MacroBuiltin::file_handler): Likewise.
	(MacroBuiltin::column_handler): Use LOCATION_COLUMN.
	(MacroBuiltin::line_handler): Use LOCATION_LINE.
	* rust-linemap.cc
	(Gcc_linemap::location_file): Remove.
	(Gcc_linemap::location_line): Remove.
	(Gcc_linemap::location_column): Remove.
	* rust-linemap.h
	(Linemap::location_file): Remove.
	(Linemap::location_line): Remove.
	(Linemap::location_column): Remove.
	(Linemap::location_to_file): Remove.
	(Linemap::location_to_line): Remove.
	(Linemap::location_to_column): Remove.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-07-07 12:10:52 +00:00
Muhammad Mahad
65553ce9a9 gccrs: [E0425] Use of unresolved name
Refactored error message similiar to
rustc.

gcc/rust/ChangeLog:

	* resolve/rust-ast-resolve-expr.cc (ResolveExpr::visit):
	called error function and changed error message
	similiar to rustc.

gcc/testsuite/ChangeLog:

	* rust/compile/break-rust2.rs: Updated comment to pass testcase.
	* rust/compile/const_generics_3.rs: likewise.
	* rust/compile/const_generics_4.rs: likewise.
	* rust/compile/not_find_value_in_scope.rs: New test.

Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
2023-07-07 10:53:25 +00:00
Owen Avery
a5abd7d778 Reduce Linemap/Gcc_linemap abstraction
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>
2023-07-07 10:37:44 +00:00
Muhammad Mahad
b9566fddf2 gccrs: [E0053] method 'x' has an incompatible type for trait 'y'
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>
2023-07-06 16:12:43 +00:00
Muhammad Mahad
0aa7ed791b gccrs: [E0063] constructor is missing fields
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>
2023-07-06 16:12:24 +00:00
Raiki Tamura
46a61f02f1 gccrs: add utf-8 validation for input source
gcc/rust/ChangeLog:

	* lex/rust-lex.cc (Lexer::input_source_is_valid_utf8): New method of `Lexer`.
	* lex/rust-lex.h: Likewise.
	* rust-session-manager.cc (Session::compile_crate): Add error.

gcc/testsuite/ChangeLog:

	* rust/compile/broken_utf8.rs: New test.

Signed-off-by: Raiki Tamura <tamaron1203@gmail.com>
2023-07-06 16:12:19 +00:00
Owen Avery
5e735e9aaa Ignore semicolon following a macro expansion in expression context
gcc/rust/ChangeLog:

	* expand/rust-macro-expand.cc
	(transcribe_expression): Skip trailing semicolon.

gcc/testsuite/ChangeLog:

	* rust/compile/macro-issue2273.rs: New test.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-07-06 10:58:37 +00:00
Muhammad Mahad
c8679a6d88 gccrs:[E0046] Missing Items in Trait Implementation
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>
2023-07-06 10:53:48 +00:00
Raiki Tamura
5d8f78c9d2 gccrs: Add location info to Rust::Identifier
gcc/rust/ChangeLog:

	* ast/rust-ast.h: Modify constructors of `Rust::Identifier`
	* ast/rust-pattern.h: Likewise.
	* hir/tree/rust-hir-item.h: Likewise.
	* parse/rust-parse-impl.h (Parser::parse_macro_rules_def): Likewise.
	(Parser::parse_decl_macro_def): Likewise.
	(Parser::parse_macro_match_fragment): Likewise.
	(Parser::parse_module): Likewise.
	(Parser::parse_use_tree): Likewise.
	(Parser::parse_function): Likewise.
	(Parser::parse_type_param): Likewise.
	(Parser::parse_type_alias): Likewise.
	(Parser::parse_struct): Likewise.
	(Parser::parse_struct_field): Likewise.
	(Parser::parse_enum): Likewise.
	(Parser::parse_enum_item): Likewise.
	(Parser::parse_union): Likewise.
	(Parser::parse_static_item): Likewise.
	(Parser::parse_trait): Likewise.
	(Parser::parse_trait_item): Likewise.
	(Parser::parse_trait_type): Likewise.
	(Parser::parse_trait_const): Likewise.
	(Parser::parse_external_item): Likewise.
	(Parser::parse_generic_args_binding): Likewise.
	(Parser::parse_method): Likewise.
	(Parser::parse_maybe_named_param): Likewise.
	(Parser::parse_identifier_pattern): Likewise.
	(Parser::parse_struct_expr_field): Likewise.
	(ResolveItem::visit): Likewise.
	* typecheck/rust-hir-type-check-implitem.cc (TypeCheckImplItem::visit):Add comments
	* resolve/rust-ast-resolve-item.cc (ResolveTraitItems::visit): Likewise.
	* checks/lints/rust-lint-scan-deadcode.h: Fix error location

Signed-off-by: Raiki Tamura <tamaron1203@gmail.com>
2023-07-06 10:50:58 +00:00
Owen Avery
0f898a4014 Change class Location into typedef
gcc/rust/ChangeLog:

	* backend/rust-compile-base.cc
	(HIRCompileBase::address_expression): Remove gcc_location method call.
	(HIRCompileBase::indirect_expression): Likewise.
	(HIRCompileBase::compile_constant_item): Likewise.
	(HIRCompileBase::named_constant_expression): Likewise.
	* backend/rust-compile-expr.cc
	(CompileExpr::visit): Remove gcc_location method call, use UNKNOWN_LOCATION to initialize.
	(CompileExpr::get_fn_addr_from_dyn): Remove gcc_location method call.
	(CompileExpr::type_cast_expression): Likewise.
	* backend/rust-compile-intrinsic.cc
	(transmute_handler): Replace "Location ().gcc_location ()" with UNKNOWN_LOCATION.
	(copy_nonoverlapping_handler): Likewise.
	(prefetch_data_handler): Likewise.
	(atomic_store_handler_inner): Likewise.
	(atomic_load_handler_inner): Likewise.
	* resolve/rust-ast-resolve-expr.cc
	(ResolveExpr::visit): Remove gcc_location method call.
	* rust-diagnostics.cc
	(rust_be_error_at): Likewise.
	(rust_be_warning_at): Likewise.
	(rust_be_fatal_error): Likewise.
	(rust_be_inform): Likewise.
	* rust-diagnostics.h
	(rust_sorry_at): Likewise.
	* rust-gcc.cc
	(Bvariable::get_tree): Likewise.
	(Gcc_backend::fill_in_fields): Likewise.
	(Gcc_backend::named_type): Likewise.
	(Gcc_backend::real_part_expression): Likewise.
	(Gcc_backend::imag_part_expression): Likewise.
	(Gcc_backend::complex_expression): Likewise.
	(Gcc_backend::convert_expression): Likewise.
	(Gcc_backend::struct_field_expression): Likewise.
	(Gcc_backend::compound_expression): Likewise.
	(Gcc_backend::conditional_expression): Likewise.
	(Gcc_backend::negation_expression): Likewise.
	(Gcc_backend::arithmetic_or_logical_expression): Likewise.
	(Gcc_backend::arithmetic_or_logical_expression_checked): Likewise.
	(Gcc_backend::comparison_expression): Likewise.
	(Gcc_backend::lazy_boolean_expression): Likewise.
	(Gcc_backend::constructor_expression): Likewise.
	(Gcc_backend::array_constructor_expression): Likewise.
	(Gcc_backend::array_initializer): Likewise.
	(Gcc_backend::array_index_expression): Likewise.
	(Gcc_backend::call_expression): Likewise.
	(Gcc_backend::assignment_statement): Likewise.
	(Gcc_backend::return_statement): Likewise.
	(Gcc_backend::exception_handler_statement): Likewise.
	(Gcc_backend::if_statement): Likewise.
	(Gcc_backend::loop_expression): Likewise.
	(Gcc_backend::exit_expression): Likewise.
	(Gcc_backend::block): Likewise.
	(Gcc_backend::convert_tree): Likewise.
	(Gcc_backend::global_variable): Likewise.
	(Gcc_backend::local_variable): Likewise.
	(Gcc_backend::parameter_variable): Likewise.
	(Gcc_backend::static_chain_variable): Likewise.
	(Gcc_backend::temporary_variable): Likewise.
	(Gcc_backend::label): Likewise.
	(Gcc_backend::goto_statement): Likewise.
	(Gcc_backend::label_address): Likewise.
	(Gcc_backend::function): Likewise.
	* rust-linemap.cc
	(Gcc_linemap::to_string): Likewise.
	(Gcc_linemap::location_file): Likewise.
	(Gcc_linemap::location_line): Likewise.
	(Gcc_linemap::location_column): Likewise.
	(Gcc_linemap::is_predeclared): Likewise.
	(Gcc_linemap::is_unknown): Likewise.
	(RichLocation::RichLocation): Likewise.
	(RichLocation::add_range): Likewise.
	(RichLocation::add_fixit_insert_before): Likewise.
	(RichLocation::add_fixit_insert_after): Likewise.
	* rust-location.h
	(class Location): Replace with typedef.
	(operator<): Remove.
	(operator==): Remove.
	(operator+): Remove.
	(operator-): Remove.
	* typecheck/rust-hir-trait-resolve.cc
	(AssociatedImplTrait::setup_associated_types): Initialize Location with UNKNOWN_LOCATION.
	* typecheck/rust-hir-type-check-stmt.cc
	(TypeCheckStmt::visit): Likewise.
	* util/rust-token-converter.cc
	(convert): Remove gcc_location method call.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-07-06 10:50:36 +00:00
Marc Poulhiès
f2617325f8 gccrs: HIR cleanup
Some more HIR cleanup.

gcc/rust/ChangeLog:

	* hir/tree/rust-hir-expr.h (BorrowExpr::is_double_borrow): New.
	(ArrayElemsCopied::get_elem_to_copy)
	(ArrayElemsCopied::get_num_copies_expr): Return unique_ptr.
	(CallExpr::get_fnexpr): Likewise.
	(ReturnExpr::get_expr): Likewise.
	(StructExprStructFields::get_struct_base): New.
	(MethodCallExpr::has_params): New.
	(ClosureExpr::has_params): New.
	(BlockExpr::get_inner_attrs): New.
	(WhileLoopExpr::get_patterns): New.
	(ForLoopExpr::get_pattern): New.
	(IfLetExpr::get_if_block): Return ref to unique_ptr.
	(IfLetExprConseqElse::get_else_block): Likewise.
	(MatchExpr::get_inner_attrs): New.
	* hir/tree/rust-hir-item.h (Module::get_module_name): New.
	(ExternCrate::get_referenced_crate)
	(ExternCrate::get_as_clause_name): New.
	(UseTreeGlob::get_glob_type, UseTreeGlob::get_path): New.
	(UseTreeList::get_path_type, UseTreeList::get_path)
	(UseTreeList::get_trees): New.
	(TraitItemKind::get_expr): Remove assert. unique_ptr can
	be "empty". Must be checked in caller.
	* hir/tree/rust-hir-pattern.h (IdentifierPattern::get_is_ref)
	(IdentifierPattern::get_to_bind): New.
	(RangePatternBoundType::get_has_minus): New.
	(RangePattern::get_has_ellipsis_syntax): New.
	(StructPatternField::get_outer_attrs): New.
	(StructPatternFieldTuplePat::get_index)
	(StructPatternFieldTuplePat::get_tuple_pattern): New.
	(StructPatternFieldIdent::get_has_ref): New.
	* hir/tree/rust-hir-stmt.h (LetStmt::get_outer_attrs): New.
	(LetStmt::get_type)
	(LetStmt::get_init_expr, LetStmt::get_pattern): Return unique_ptr.
	(ExprStmt::get_expr): Likewise.
	* hir/tree/rust-hir-type.h (TraitBound::get_for_lifetimes): New.
	(TraitBound::get_in_params): New.
	(TraitBound::get_opening_question_mark): New.
	(ImplTraitType::get_type_param_bounds): New.
	(TraitObjectType::get_has_dyn): New.
	(TraitBound::get_type_in_parens): New.
	(ImplTraitTypeOneBound::get_trait_bound): New.
	(BareFunctionType::get_for_lifetimes)
	(BareFunctionType::get_is_variadic)
	(BareFunctionType::get_function_qualifiers): New.
	* hir/tree/rust-hir.h (class Expr): Virtual inherit from FullVisitable.
	(class Pattern): Likewise.
	(ConstGenericParam::get_name): New.
	* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit): Adjust call.
	(TypeCheckExpr::resolve_fn_trait_call): Likewise.
	* backend/rust-compile-expr.cc (CompileExpr::visit): Adjust call.
	(CompileExpr::array_copied_expr): Likewise.
	(CompileExpr::generate_possible_fn_trait_call): Likewise.
	* backend/rust-compile-stmt.cc (CompileStmt::visit): Likewise.
	* checks/errors/privacy/rust-privacy-reporter.cc (PrivacyReporter::visit): Likewise.
	* checks/errors/rust-const-checker.cc (ConstChecker::visit): Likewise.
	* checks/errors/rust-unsafe-checker.cc (UnsafeChecker::visit): Likewise.
	* hir/rust-hir-dump.cc (Dump::visit): Likewise.
	* typecheck/rust-hir-type-check-stmt.cc (TypeCheckStmt::visit): Likewise.

Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
2023-07-06 10:50:15 +00:00
Muhammad Mahad
5406b633a1 gccrs: [E0034] Ambiguous Method Call Error
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>
2023-07-04 05:06:51 +00:00
Muhammad Mahad
28be497dc3 gccrs: [E0229] associated type bindings error
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>
2023-07-04 05:06:47 +00:00
Marc Poulhiès
2f91d51120 gccrs: minor HIR interface cleanup
Minor changes in HIR interface: add missing getters, make some classes
inherit from FullVisitable.

gcc/rust/ChangeLog:

	* hir/tree/rust-hir-expr.h (class ArrayElems): Inherit from FullVisitable.
	(class StructExprField): Likewise.
	* hir/tree/rust-hir-item.h (class WhereClauseItem): Likewise.
	(class UseTree): Likewise.
	(UseTreeRebind::get_path, UseTreeRebind::get_identifier)
	(UseTreeRebind::get_bind_type): New.
	(UseDeclaration::get_use_tree): New.
	(struct TraitFunctionDecl): Change struct to ...
	(class TraitFunctionDecl): ... class.
	(TraitFunctionDecl::get_where_clause): New.
	(StructField::get_outer_attrs): New.
	(struct TupleField): Change struct to ...
	(class TupleField): ... class.
	(TupleField::get_visibility, TupleField::get_outer_attrs): New.
	* hir/tree/rust-hir-pattern.h (class TupleStructItems): Inherit
	from FullVisitable.

Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
2023-07-03 19:54:15 +00:00
Raiki Tamura
5d33b88c81 gccrs: Remove unnecessary methods of Rust::Lexer
gcc/rust/ChangeLog:

	* lex/rust-lex.cc (Lexer::build_token): Replace function call.
	(Lexer::parse_string): Likewise.
	(Lexer::parse_identifier_or_keyword): Likewise.
	(Lexer::parse_raw_string): Likewise.
	(Lexer::parse_char_or_lifetime): Likewise.
	(Lexer::get_input_codepoint_length): Deleted.
	(Lexer::peek_codepoint_input): Deleted.
	(Lexer::skip_codepoint_input): Deleted.
	* lex/rust-lex.h: Remove some methods and fields

Signed-off-by: Raiki Tamura <tamaron1203@gmail.com>
2023-07-03 08:48:51 +00:00
Philip Herron
b49a9581d5 gccrs: Track fn_once output lang item properly
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>
2023-07-02 22:13:45 +00:00
Philip Herron
cfc51d46fc gccrs: fix ICE with inserting autoderef mappings
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>
2023-06-30 22:02:15 +00:00
Muhammad Mahad
251348f3c8 gccrs: [E0027] struct pattern fails to specify struct's fields
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>
2023-06-30 17:34:41 +00:00
Marc Poulhiès
ec0c3ad30d gccrs: refactor: make crate.items private
Introduce Crate::get_items () and fixup all callers.

gcc/rust/ChangeLog:

	* hir/tree/rust-hir.h (struct Crate): Rename struct into ...
	(class Crate): ... class, and add get_items.
	* backend/rust-compile.cc (CompileCrate::go): Adapt to visibility change of items.
	* checks/errors/privacy/rust-privacy-check.cc (Resolver::resolve): Likewise.
	* checks/errors/privacy/rust-privacy-reporter.cc (PrivacyReporter::go): Likewise.
	* checks/errors/privacy/rust-pub-restricted-visitor.cc (PubRestrictedVisitor::go): Likewise.
	* checks/errors/privacy/rust-visibility-resolver.cc (VisibilityResolver::go): Likewise.
	* checks/errors/rust-const-checker.cc (ConstChecker::go): Likewise.
	* checks/errors/rust-unsafe-checker.cc (UnsafeChecker::go): Likewise.
	* checks/lints/rust-lint-marklive.cc (FindEntryPoint::find): Likewise.
	* checks/lints/rust-lint-scan-deadcode.h (ScanDeadCode::Scan): Likewise.
	* metadata/rust-export-metadata.cc (PublicInterface::gather_export_data): Likewise.
	* typecheck/rust-hir-type-check.cc (TypeResolution::Resolve): Likewise.
	* hir/rust-hir-dump.cc (CompileCrate::go): Likewise.

Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
2023-06-30 17:15:14 +00:00
Marc Poulhiès
f044da1073 gccrs: Add new getters
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>
2023-06-30 17:15:14 +00:00
Marc Poulhiès
dc59fc36db gccrs: FullVisitable abstract class
Introduce FullVisitable class. HIR nodes implementing the FullVisitor
interface should inherit from this class.

gcc/rust/ChangeLog:

	* hir/tree/rust-hir.h (class FullVisitable): New.
	(class Stmt): Adjust with new class.
	(class Expr): Likewise.
	(class Pattern): Likewise.
	(class Type): Likewise.
	(class TypeParamBound): Likewise.
	(class GenericParam): Likewise.
	(class TraitItem): Likewise.
	(class ImplItem): Likewise.

Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
2023-06-30 17:15:14 +00:00
Marc Poulhiès
539e4bcd98 gccrs: factor out inner attributes in a class
Introduce WithInnerAttrs class that can be inherited instead of
duplicating the same data/method in all HIR classes.

gcc/rust/ChangeLog:

	* hir/tree/rust-hir.h (class WithInnerAttrs): New.
	(class Item): Adjust to new WithInnerAttrs class.
	(struct Crate): Likewise.
	* hir/rust-hir-dump.cc (Dump::go): Likewise.
	(Dump::visit): Likewise.
	* hir/tree/rust-hir-expr.h (class GroupedExpr): Likewise.
	(class ArrayExpr): Likewise.
	(class TupleExpr): Likewise.
	(class StructExprStruct): Likewise.
	(class BlockExpr): Likewise.
	(class MatchExpr): Likewise.
	* hir/tree/rust-hir-item.h (TypeParam::get_outer_attribute): New.
	(class Module): Adjust to new  WithInnerAttrs class.
	(struct StructField): change struct to...
	(class StructField): ... a class.
	(class ImplBlock): Adjust to new  WithInnerAttrs class.
	(class ExternBlock): Likewise.

Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
2023-06-30 17:15:14 +00:00
Marc Poulhiès
d96093d97b gccrs: cleanup getters to return &unique_ptr instead of pointer
Make all getter methods in HIR classes return a unique_ptr reference
instead of a pointer and adjust all callers.

gcc/rust/ChangeLog:

	* hir/tree/rust-hir-type.h (ArrayType::get_element_type): Returns
	unique_ptr.
	* hir/tree/rust-hir-expr.h (ArithmeticOrLogicalExpr::get_lhs)
	(ArithmeticOrLogicalExpr::get_rhs): Likewise.
	(ComparisonExpr::get_lhs, ComparisonExpr::get_rhs): Likewise.
	(LazyBooleanExpr::get_lhs, LazyBooleanExpr::get_rhs): Likewise.
	(AssignmentExpr::get_lhs, AssignmentExpr::get_rhs): Likewise.
	(ArrayExpr::get_internal_elements): Likewise.
	(ArrayIndexExpr::get_index_expr, ArrayIndexExpr::get_array_expr):
	Likewise.
	(StructExprFieldWithVal::get_value): Likewise.
	(IfExpr::get_if_condition, IfExpr::get_if_block): Likewise.
	(ExprWithBlock::get_else_block): Likewise.
	* hir/tree/rust-hir-item.h (FunctionParam::get_param_name)
	(FunctionParam::get_type): Likewise.
	(ConstantItem::get_type, ConstantItem::get_expr): Likewise.
	(StaticItem::get_expr, StaticItem::get_type): Likewise.
	* typecheck/rust-hir-type-check-type.cc (TypeCheckType::visit):
	Adjust for previous change.
	* backend/rust-compile-block.cc (CompileConditionalBlocks::visit):
	Likewise.
	* backend/rust-compile-expr.cc (CompileExpr::visit): Likewise.
	* backend/rust-compile-item.cc (CompileItem::visit): Likewise.
	* backend/rust-compile-struct-field-expr.cc
	(CompileStructExprField::visit): Likewise.
	* checks/errors/privacy/rust-privacy-reporter.cc
	(PrivacyReporter::visit): Likewise.
	* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::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-stmt.cc (TypeCheckStmt::visit):
	Likewise.
	* typecheck/rust-hir-type-check-struct.cc
	(TypeCheckStructExpr::visit): Likewise.
	* typecheck/rust-hir-type-check.cc
	(TraitItemReference::get_type_from_fn): Likewise.

Signed-off-by: Marc Poulhiès <dkm@kataplop.net>
2023-06-30 17:15:14 +00:00
Arthur Cohen
9d3f198572 abi: Add testcase for using "Rust" as ABI string
gcc/testsuite/ChangeLog:

	* rust/compile/rust_abi.rs: New test.
2023-06-30 17:12:24 +00:00
Pierre-Emmanuel Patry
1db82e8886 parser: Propagate type hint value
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>
2023-06-30 14:24:44 +00:00
Raiki Tamura
abfb39e2c6 gccrs: fix lexing byte literal
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>
2023-06-30 14:19:32 +00:00
Muhammad Mahad
2e1f190573 gccrs: refactored field error function
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>
2023-06-30 09:05:46 +00:00
Owen Avery
40b4f94e95 Improve macro repetition handling
gcc/rust/ChangeLog:

	* expand/rust-macro-expand.cc
	(MacroExpander::match_matcher): Remove append_fragment inside repetitions.
	(MacroExpander::match_n_matches): Use sub_stack push/pop to handle repetitions.
	(MatchedFragmentContainer::add_fragment): Add MatchedFragmentContainer accepting version.
	* expand/rust-macro-expand.h
	(MatchedFragmentContainer::add_fragment): Likewise.
	(MatchedFragmentContainerRepetition::add_fragment): Likewise.
	(SubstititionScope::append_fragment): Likewise.

gcc/testsuite/ChangeLog:

	* rust/compile/macro56.rs: New test.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-06-30 08:01:24 +00:00
Philip Herron
7af86eaaff gccrs: fix how we handle coercions and casts of unsafe pointers
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>
2023-06-29 15:38:44 +00:00
Philip Herron
eb88e324cd gccrs: Track associated type generics
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>
2023-06-29 15:38:44 +00:00
Pierre-Emmanuel Patry
2ddf542ed6 dump: Add formatting to dump
Add formatting character output to ast dump.

gcc/rust/ChangeLog:

	* ast/rust-ast-collector.cc (TokenCollector::visit): Add comment
	after tail expressions.
	* ast/rust-ast-dump.cc (Dump::require_spacing): Check for
	missing previous token.
	* ast/rust-ast-dump.h: Output formatting characters.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-06-29 12:30:17 +00:00
Pierre-Emmanuel Patry
18a67ff6bf collector: Implement formatting options
The collector did only output the tokens without any formatting.

gcc/rust/ChangeLog:

	* ast/rust-ast-collector.cc (TokenCollector::collect): Collect
	CollectItems once done.
	(TokenCollector::newline): Add newline formatting
	implementation.
	(TokenCollector::indentation): Add indentation implementation.
	(TokenCollector::increment_indentation): Add indentation
	increment.
	(TokenCollector::comment): Add new comment formatting option.
	* ast/rust-ast-collector.h: Update prototypes.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-06-29 12:30:17 +00:00
Pierre-Emmanuel Patry
299edc484b collector: Store CollectItem instead of TokenPtr
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>
2023-06-29 12:30:17 +00:00
Pierre-Emmanuel Patry
409d29c991 collector: Remove external container
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>
2023-06-29 12:30:17 +00:00
Pierre-Emmanuel Patry
feddab8c7d dump: Output separating space under condition
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>
2023-06-29 12:30:17 +00:00
Pierre-Emmanuel Patry
bfc620f80a dump: Replace ast dump internals
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>
2023-06-29 12:30:17 +00:00
Pierre-Emmanuel Patry
31d13f10b6 collector: Fix missing semicolon output
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>
2023-06-29 12:30:17 +00:00
Pierre-Emmanuel Patry
cf7095b0c6 dump: Remove tokenstream dump
This dump will soon replace ast-pretty print and is hence no longer
required.

gcc/rust/ChangeLog:

	* rust-session-manager.cc (Session::enable_dump): Remove
	tokenstream dump.
	(Session::compile_crate): Likewise.
	(Session::dump_tokenstream): Likewise.
	* rust-session-manager.h (struct CompileOptions): Likewise.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-06-29 12:30:17 +00:00
Raiki Tamura
bc5b1b7b5c gccrs: Add tests for Unicode identifiers
gcc/testsuite/ChangeLog:

	* rust/compile/torture/raw_identifiers.rs: New test.
	* rust/compile/torture/utf8_identifiers.rs: New test.

Signed-off-by: Raiki Tamura <tamaron1203@gmail.com>
2023-06-29 12:29:50 +00:00
Raiki Tamura
9e4c3ed357 gccrs: fix tokenizing utf-8 whitespaces
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>
2023-06-29 12:25:26 +00:00
Pierre-Emmanuel Patry
09512e6135 ast: Add explicit default copy constructor
Add explicit default copy/move constructor to identifiers.

gcc/rust/ChangeLog:

	* ast/rust-ast.h: Add default constructors.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-06-29 09:26:34 +00:00
Pierre-Emmanuel Patry
d5723ccebb ast: Change Identifier definition
Change Identifier type definition from a simple typedef to a whole class
with it's own node id.

gcc/rust/ChangeLog:

	* ast/rust-ast-collector.cc (TokenCollector::visit): Change with
	call to getter.
	* ast/rust-ast.cc (Module::as_string): Likewise.
	(StaticItem::as_string): Likewise.
	(TupleStruct::as_string): Likewise.
	(Method::as_string): Likewise.
	(StructStruct::as_string): Likewise.
	(UseTreeRebind::as_string): Likewise.
	(Enum::as_string): Likewise.
	(Trait::as_string): Likewise.
	(Union::as_string): Likewise.
	(Function::as_string): Likewise.
	(TypeAlias::as_string): Likewise.
	(MacroRulesDefinition::as_string): Likewise.
	(FieldAccessExpr::as_string): Likewise.
	(MacroMatchFragment::as_string): Likewise.
	(TypeParam::as_string): Likewise.
	(StructExprFieldIdentifierValue::as_string): Likewise.
	(EnumItem::as_string): Likewise.
	(StructField::as_string): Likewise.
	(ExternalTypeItem::as_string): Likewise.
	(ExternalStaticItem::as_string): Likewise.
	(ExternalFunctionItem::as_string): Likewise.
	(TraitFunctionDecl::as_string): Likewise.
	(TraitMethodDecl::as_string): Likewise.
	(TraitItemConst::as_string): Likewise.
	(TraitItemType::as_string): Likewise.
	(MaybeNamedParam::as_string): Likewise.
	(MetaListPaths::as_string): Likewise.
	(MetaListNameValueStr::as_string): Likewise.
	(Module::process_file_path): Likewise.
	(MetaListNameValueStr::check_cfg_predicate): Likewise.
	(MetaListPaths::check_cfg_predicate): Likewise.
	(MetaWord::check_cfg_predicate): Likewise.
	(MetaNameValueStr::check_cfg_predicate): Likewise.
	(MetaNameValueStr::to_attribute): Likewise.
	(MetaWord::to_attribute): Likewise.
	(MetaListPaths::to_attribute): Likewise.
	(MetaListNameValueStr::to_attribute): Likewise.
	(operator<<): Change Identifier class <<
	operator overload for standard output stream.
	* ast/rust-ast.h (class Identifier): Change typedef to proper
	class definition.
	(operator<<): Add prototype for operator overload.
	(class Token): Change getter identifier.
	(class MetaListNameValueStr): Likewise.
	(class PathExpr): Likewise.
	* ast/rust-expr.h: Likewise.
	* ast/rust-item.h: Likewise.
	* ast/rust-macro.h: Likewise.
	* ast/rust-path.cc (GenericArg::disambiguate_to_type): Likewise.
	(GenericArgsBinding::as_string): Likewise.
	(ConstGenericParam::as_string): Likewise.
	* ast/rust-path.h: Likewise.
	* ast/rust-pattern.cc (IdentifierPattern::as_string): Likewise.
	(StructPatternFieldIdentPat::as_string): Likewise.
	(StructPatternFieldIdent::as_string): Likewise.
	* ast/rust-type.h: Likewise.
	* backend/rust-compile-base.cc: Likewise.
	* backend/rust-compile-expr.cc (CompileExpr::visit): Likewise.
	* backend/rust-compile-extern.h: Likewise.
	* backend/rust-compile-fnparam.cc (CompileFnParam::visit):
	Likewise.
	* backend/rust-compile-implitem.cc (CompileTraitItem::visit):
	Likewise.
	* backend/rust-compile-item.cc (CompileItem::visit): Likewise.
	* backend/rust-compile-pattern.cc (CompilePatternBindings::visit): Likewise.
	* backend/rust-compile-struct-field-expr.cc (CompileStructExprField::visit):
	Likewise.
	* backend/rust-compile-var-decl.h: Likewise.
	* backend/rust-compile.cc: Likewise.
	* checks/errors/rust-unsafe-checker.cc (check_extern_call):
	Likewise.
	* checks/lints/rust-lint-marklive.cc (MarkLive::visit):
	Likewise.
	* checks/lints/rust-lint-scan-deadcode.h: Likewise.
	* expand/rust-derive-clone.cc (DeriveClone::clone_fn): Likewise.
	(DeriveClone::visit_tuple): Likewise.
	(DeriveClone::visit_struct): Likewise.
	(DeriveClone::visit_union): Likewise.
	* expand/rust-derive-copy.cc (DeriveCopy::visit_struct):
	Likewise.
	(DeriveCopy::visit_tuple): Likewise.
	(DeriveCopy::visit_enum): Likewise.
	(DeriveCopy::visit_union): Likewise.
	* expand/rust-macro-expand.cc (MacroExpander::match_matcher):
	Likewise.
	(MacroExpander::match_n_matches): Likewise.
	(MacroExpander::match_repetition): Likewise.
	(MacroExpander::match_repetition_skipped_metavars): Likewise.
	* hir/rust-ast-lower-base.cc (struct_field_name_exists):
	Likewise.
	* hir/rust-ast-lower-expr.cc (ASTLoweringExpr::visit): Likewise.
	* hir/rust-ast-lower-type.cc (ASTLowerGenericParam::visit):
	Likewise.
	* hir/rust-hir-dump.cc (Dump::visit): Likewise.
	* hir/tree/rust-hir-expr.h: Likewise.
	* hir/tree/rust-hir-item.h: Likewise.
	* hir/tree/rust-hir-path.h: Likewise.
	* hir/tree/rust-hir-type.h: Likewise.
	* hir/tree/rust-hir.cc (Module::as_string): Likewise.
	(StaticItem::as_string): Likewise.
	(TupleStruct::as_string): Likewise.
	(ConstantItem::as_string): Likewise.
	(StructStruct::as_string): Likewise.
	(UseTreeRebind::as_string): Likewise.
	(Enum::as_string): Likewise.
	(Trait::as_string): Likewise.
	(Union::as_string): Likewise.
	(Function::as_string): Likewise.
	(TypeAlias::as_string): Likewise.
	(FieldAccessExpr::as_string): Likewise.
	(TypeParam::as_string): Likewise.
	(GenericArgsBinding::as_string): Likewise.
	(StructPatternFieldIdent::as_string): Likewise.
	(StructPatternFieldIdentPat::as_string): Likewise.
	(IdentifierPattern::as_string): Likewise.
	(StructExprFieldIdentifierValue::as_string): Likewise.
	(EnumItem::as_string): Likewise.
	(StructField::as_string): Likewise.
	(ExternalStaticItem::as_string): Likewise.
	(ExternalFunctionItem::as_string): Likewise.
	(NamedFunctionParam::as_string): Likewise.
	(TraitFunctionDecl::as_string): Likewise.
	(TraitItemConst::as_string): Likewise.
	(TraitItemType::as_string): Likewise.
	(MaybeNamedParam::as_string): Likewise.
	* hir/tree/rust-hir.h: Likewise.
	* parse/rust-parse-impl.h (Parser::parse_macro_match_fragment):
	Likewise.
	(Parser::parse_module): Likewise.
	(Parser::parse_use_tree): Likewise.
	(Parser::parse_maybe_named_param): Likewise.
	* resolve/rust-ast-resolve-implitem.h: Likewise.
	* resolve/rust-ast-resolve-item.cc (ResolveTraitItems::visit):
	Likewise.
	(ResolveItem::visit): Likewise.
	(flatten_rebind): Likewise.
	(ResolveExternItem::visit): Likewise.
	(rust_flatten_rebind): Likewise.
	(rust_flatten_rebind_nested): Likewise.
	* resolve/rust-ast-resolve-pattern.cc (PatternDeclaration::go):
	Likewise.
	(PatternDeclaration::visit): Likewise.
	(PatternDeclaration::add_new_binding): Likewise.
	* resolve/rust-ast-resolve-stmt.h: Likewise.
	* resolve/rust-ast-resolve-toplevel.h: Likewise.
	* resolve/rust-ast-resolve-type.h: Likewise.
	* resolve/rust-early-name-resolver.cc (EarlyNameResolver::visit): Likewise.
	* typecheck/rust-autoderef.cc: Likewise.
	* typecheck/rust-hir-dot-operator.cc (MethodResolver::select):
	Likewise.
	* typecheck/rust-hir-path-probe.cc (PathProbeType::visit):
	Likewise.
	* typecheck/rust-hir-trait-reference.cc (TraitReference::get_name): Likewise.
	* typecheck/rust-hir-trait-resolve.cc (ResolveTraitItemToRef::visit): Likewise.
	(TraitResolver::resolve_trait): Likewise.
	(TraitItemReference::resolve_item): Likewise.
	(AssociatedImplTrait::setup_raw_associated_types): Likewise.
	* typecheck/rust-hir-type-check-enumitem.cc (TypeCheckEnumItem::visit): Likewise.
	* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit):
	Likewise.
	* typecheck/rust-hir-type-check-implitem.cc (TypeCheckTopLevelExternItem::visit): Likewise.
	(TypeCheckImplItem::visit): Likewise.
	(TypeCheckImplItemWithTrait::visit): Likewise.
	* typecheck/rust-hir-type-check-item.cc (TypeCheckItem::visit):
	Likewise.
	* typecheck/rust-hir-type-check-pattern.cc (TypeCheckPattern::visit): Likewise.
	* typecheck/rust-hir-type-check-struct.cc (TypeCheckStructExpr::visit): Likewise.
	* typecheck/rust-hir-type-check-type.cc (TypeResolveGenericParam::visit): Likewise.
	* typecheck/rust-hir-type-check.cc (TraitItemReference::get_type_from_fn): Likewise.
	* typecheck/rust-tyty-subst.cc (SubstitutionRef::get_mappings_from_generic_args): Likewise.
	* util/rust-attributes.cc (check_doc_attribute): Likewise.
	* util/rust-hir-map.cc (Mappings::insert_macro_def): Likewise.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-06-29 09:26:34 +00:00
Raiki Tamura
3d2a0c0445 gccrs: Refactor lexer to handle UTF-8
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>
2023-06-28 15:43:33 +00:00
Owen Avery
2983beb0d9 Insert empty repeated metavars for nested repetitions
gcc/rust/ChangeLog:

	* expand/rust-macro-expand.cc
	(MacroExpander::match_repetition_skipped_metavars): New.
	(MacroExpander::match_repetition): Use new method.
	* expand/rust-macro-expand.h
	(MacroExpander::match_repetition_skipped_metavars): New.

gcc/testsuite/ChangeLog:

	* rust/compile/macro-issue2268.rs: New test.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-06-27 15:20:30 +00:00
Muhammad Mahad
5711a2ad93 gccrs: [E0023] Incorrect Number of Fields in Pattern Extraction
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>
2023-06-27 09:28:56 +00:00
Muhammad Mahad
f56fd7edc1 gccrs:[E0026] Non-Existent Field Extraction in Struct Pattern
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>
2023-06-27 09:27:22 +00:00
Owen Avery
96ba341e0f Match tokens in macros more closely
gcc/rust/ChangeLog:

	* expand/rust-macro-expand.cc
	(MacroExpander::match_token): Match token instead of token id.
	* parse/rust-parse-impl.h
	(Parser::skip_token): Add token-skipping variant.
	(Parser::expect_token): Likewise.
	* parse/rust-parse.h
	(Parser::skip_token): Likewise.
	(Parser::expect_token): Likewise.

gcc/testsuite/ChangeLog:

	* rust/compile/macro-issue2264.rs: New test.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-06-27 07:50:44 +00:00
Arthur Cohen
4c07c94212 rust: Add -frust-name-resolution-2.0 option
This option enables an experimental name resolution algorithm. Disabled
by default.

gcc/rust/ChangeLog:

	* lang.opt: Add -frust-name-resolution-2.0 option
2023-06-26 15:36:01 +00:00
Philip Herron
ac43e5899c gccrs: Stop autoderef of raw pointer types
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>
2023-06-25 21:18:56 +00:00
Philip Herron
337ed0fd1b gccrs: Add method selection to operator overloading
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>
2023-06-25 21:07:02 +00:00
Muhammad Mahad
04eb580efa ErrorCode[E0277] Type Does Not Implement Expected Trait
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>
2023-06-25 20:41:35 +00:00
Matthew Jasper
210557d8a4 gccrs: Expand expressions/types correctly in more contexts.
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>
2023-06-25 20:40:29 +00:00
Pierre-Emmanuel Patry
3ccf008b14 expand: Change names and document behavior
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>
2023-06-22 08:49:35 +00:00
Pierre-Emmanuel Patry
be6d7343a5 expand: Merge arguments into one
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>
2023-06-22 08:49:35 +00:00
Pierre-Emmanuel Patry
d37a1d5470 expand: Convert last statement to tail expr
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>
2023-06-22 08:49:35 +00:00
Pierre-Emmanuel Patry
650ae19d14 expand: Add tail expr expansion
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>
2023-06-22 08:49:35 +00:00
Arthur Cohen
5ab2f1b3aa expand: Derive statements
Expand procedural macros on statements properly.

gcc/rust/ChangeLog:

	* expand/rust-expand-visitor.cc : Change type from pointer to
	reference and expand statements from statements.
	* ast/rust-macro.h: Return macro kind.
	* ast/rust-ast.h: Add Statement kind.
	* ast/rust-item.h: Change module.
	* ast/rust-stmt.h: Return kind.

Co-authored-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-06-22 08:49:35 +00:00
Owen Avery
d3b247e733 Make MatchedFragmentContainer a tree-like structure
gcc/rust/ChangeLog:

	* expand/rust-macro-expand.cc
	(MacroExpander::expand_decl_macro):
	Use pointers/smart pointers to refer to MatchedFragmentContainer instances.
	(MacroExpander::transcribe_rule): Likewise.
	(MatchedFragmentContainer::get_single_fragment): New implementation.
	(MatchedFragmentContainer::get_fragments): Likewise.
	(MatchedFragmentContainer::add_fragment): Likewise.
	(MatchedFragmentContainer::zero): Likewise.
	(MatchedFragmentContainer::metavar): Likewise.
	* expand/rust-macro-expand.h
	(class MatchedFragmentContainer): Make abstract.
	(class MatchedFragmentContainerMetaVar): New.
	(class MatchedFragmentContainerRepetition): New.
	(class SubstitutionScope):
	Use pointers/smart pointers to refer to MatchedFragmentContainer instances.
	(MacroExpander::transcribe_rule): Likewise.
	* expand/rust-macro-substitute-ctx.cc
	(SubstituteCtx::substitute_metavar): Likewise.
	(SubstituteCtx::check_repetition_amount): Likewise.
	(SubstituteCtx::substitute_repetition): Likewise.
	* expand/rust-macro-substitute-ctx.h
	(class SubstituteCtx): Likewise.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-06-22 08:38:34 +00:00
Muhammad Mahad
c93eb308c5 ErrorCode[E0433] Use of Undeclared Crate, Module, or Type
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>
2023-06-21 12:51:40 +00:00
Philip Herron
065d8c4d79 gccrs: Apply generic arguments to the respective trait bounds
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>
2023-06-21 09:00:30 +00:00
Philip Herron
8e2619254f gccrs: Fix generic argument tracking
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>
2023-06-21 09:00:30 +00:00
Philip Herron
7bb7c2a44e gccrs: add new method to infer impl block type
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>
2023-06-21 09:00:30 +00:00
Philip Herron
3a27f1e905 gccrs: fix unsafe lookup at zero index
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>
2023-06-21 09:00:30 +00:00
Matthew Jasper
dbf982cbd8 gccrs: Parse statement macros as statements.
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>
2023-06-20 08:10:23 +00:00
Matthew Jasper
33544f7984 gccrs: Parse semicolons in more cases for statement macros
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>
2023-06-20 08:10:23 +00:00
Matthew Jasper
cbca7bdde2 gccrs: Handle tail expression normalization right before lowering to HIR.
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>
2023-06-20 08:10:23 +00:00
Matthew Jasper
3a0f10e798 gccrs: Print macro invocations in AST dump
gcc/rust/ChangeLog:

	* ast/rust-ast-dump.cc (Dump::visit): Print macro invocations.

Signed-off-by: Matthew Jasper <mjjasper1@gmail.com>
2023-06-20 08:10:23 +00:00
Raiki Tamura
1931d49c42 gccrs: tokenize Unicode identifiers
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>
2023-06-20 08:10:20 +00:00
Raiki Tamura
c05b7f2238 libcpp: add function to check XID properties
libcpp/ChangeLog:

	* charset.cc (check_xid_property):new function to check XID_Start and XID_Continue
	* include/cpplib.h (check_xid_property):add enum representing XID properties

Signed-off-by: Raiki Tamura <tamaron1203@gmail.com>
2023-06-20 08:10:20 +00:00
Owen Avery
b533df3643 Prevent invalid iterator dereference
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>
2023-06-19 07:34:19 +00:00
Owen Avery
7671253eda Remove direct error on macro rule count-related match failure
gcc/rust/ChangeLog:

	* expand/rust-macro-expand.cc
	(MacroExpander::match_repetition): Remove redundant rust_error_at call.

gcc/testsuite/ChangeLog:

	* rust/compile/macro6.rs: Remove check for direct error.
	* rust/compile/macro7.rs: Likewise.
	* rust/compile/macro-issue2229.rs: New test.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-06-15 15:44:59 +00:00
Philip Herron
b028c7ece2 gccrs: we can't check the bounds involving empty placeholder types
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>
2023-06-14 15:30:31 +00:00
tieway59
d1e10de001 fixup: Remove old typecheck dump
fixes https://github.com/Rust-GCC/gccrs/issues/2020

gcc/rust/ChangeLog:

	* typecheck/rust-tycheck-dump.h: Delete this file
	* rust-session-manager.cc: Remove `Session::dump_type_resolution`
	and `TYPE_RESOLUTION_DUMP`
	* rust-session-manager.h: Likewise

Signed-off-by: Taiwei Wu tieway59@foxmail.com
2023-06-14 11:10:20 +00:00
Pierre-Emmanuel Patry
706341acbd build: Do not build libgrust when rust is disabled
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>
2023-06-14 11:09:46 +00:00
Pierre-Emmanuel Patry
61cbe20102 fixup: Fix missing build dependency
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>
2023-06-14 11:09:46 +00:00
Philip Herron
c84e7d9db2 gccrs: fortify resolve_method_address to match the types
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>
2023-06-14 08:26:31 +00:00
Arthur Cohen
c021eef8aa derive: Factor common fields inside the base visitor
gcc/rust/ChangeLog:

	* expand/rust-derive.h: Store AstBuilder and location.
	* expand/rust-derive.cc (DeriveVisitor::DeriveVisitor): Update constructor.
	* expand/rust-derive-clone.h: Remove members now stored in `DeriveVisitor`.
	* expand/rust-derive-copy.h: Likewise.
	* expand/rust-derive-clone.cc (DeriveClone::DeriveClone): Update constructor.
	* expand/rust-derive-copy.cc (DeriveCopy::DeriveCopy): Likewise.
2023-06-13 11:52:56 +00:00
Philip Herron
e43261892f gccrs: ensure assoicated types are setup for concrete trait impl blocks
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>
2023-06-13 08:46:22 +00:00
Dave Evans
e3e945f055 Fix ICE for reference patterns in match statements
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>
2023-06-13 08:16:21 +00:00
TieWay59
533e1ef3ca Remove obsolete error diagnostic
fixes https://github.com/Rust-GCC/gccrs/issues/2064

Remove every `{ dg-error "failed to type resolve expression" }`
annotation that causes a failure when running the testsuite.

gcc/rust/ChangeLog:

	* typecheck/rust-hir-type-check-expr.cc: Remove obsolete error diagnostic

gcc/testsuite/ChangeLog:

	* rust/compile/break1.rs: remove dg-error "failed to type resolve expression"
	* rust/compile/break2.rs: Likewise
	* rust/compile/cfg2.rs: Likewise
	* rust/compile/continue1.rs: Likewise
	* rust/compile/generics4.rs: Likewise
	* rust/compile/generics6.rs: Likewise
	* rust/compile/generics7.rs: Likewise
	* rust/compile/issue-2029.rs: Likewise
	* rust/compile/issue-2139.rs: Likewise
	* rust/compile/issue-2190-1.rs: Likewise
	* rust/compile/issue-925.rs: Likewise
	* rust/compile/method1.rs: Likewise
	* rust/compile/shadow1.rs: Likewise
	* rust/compile/type-bindings1.rs: Likewise
	* rust/compile/unary_negation.rs: Likewise
	* rust/compile/unary_not.rs: Likewise
	* rust/compile/unconstrained_type_param.rs: Likewise
	* rust/compile/usize1.rs: Likewise

Signed-off-by: Taiwei Wu <tieway59@foxmail.com>
2023-06-13 08:12:29 +00:00
Philip Herron
eedab85e02 gccrs: introduce new types_compatable
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>
2023-06-11 18:13:29 +00:00
Pierre-Emmanuel Patry
edff04f5dd expand: Make to_derive argument const
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>
2023-06-08 14:32:36 +02:00
Pierre-Emmanuel Patry
b94c7a9748 expand: Allow empty derive attribute
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>
2023-06-08 14:32:35 +02:00
Pierre-Emmanuel Patry
588b130c7c expand: Expand item level attribute proc macros
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>
2023-06-08 14:32:35 +02:00
Pierre-Emmanuel Patry
b21aa448a4 expand: Add in order trait expansion
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>
2023-06-08 14:32:35 +02:00
Pierre-Emmanuel Patry
9829370cfb expand: Remove proc macro fragment from expander
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>
2023-06-08 14:32:35 +02:00
Pierre-Emmanuel Patry
855a62d130 expand: Move derive system to new one
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>
2023-06-08 14:32:35 +02:00
Pierre-Emmanuel Patry
3fcec13b13 expand: Add derive proc macro draft
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>
2023-06-08 14:32:35 +02:00
Pierre-Emmanuel Patry
12131c106f expand: Add prc macro expander and registration
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>
2023-06-08 14:32:35 +02:00
Pierre-Emmanuel Patry
562a0860f1 ast: Fix attribute collection
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>
2023-06-08 14:32:35 +02:00
Pierre-Emmanuel Patry
c60b36b977 libproc_macro: Fix Tokenstream growth
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>
2023-06-08 14:32:35 +02:00
Pierre-Emmanuel Patry
f13da289f1 libproc_macro: Fix capacity update in tokenstream
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>
2023-06-08 14:32:35 +02:00
Pierre-Emmanuel Patry
118518e2ba collector: Make visitors public
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>
2023-06-08 14:32:35 +02:00
Pierre-Emmanuel Patry
7c0c0cb69b libproc_macro: Rename Procmacro subtypes
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>
2023-06-08 14:32:34 +02:00
Pierre-Emmanuel Patry
cba5e7468d expand: Add procmacro loading function
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>
2023-06-08 14:32:34 +02:00
Pierre-Emmanuel Patry
eace2796dd libproc_macro: Add procmacro array definition
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>
2023-06-08 14:32:34 +02:00
Pierre-Emmanuel Patry
b966194fa3 attributes: Add allow_internal_unstable attribute
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.
2023-06-08 14:32:34 +02:00
Pierre-Emmanuel Patry
69b2420743 collector: Move implementation to header
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>
2023-06-08 14:32:34 +02:00
Owen Avery
ab44003c26 Fix non-mod-rs files' external module loading paths
gcc/rust/ChangeLog:

	* Make-lang.in: Add "rust-dir-owner.o".
	* ast/rust-ast.cc: Include "rust-dir-owner.h".
	(Module::process_file_path):
	Handle non-mod-rs external file modules properly.
	* parse/rust-parse-impl.h: Include "rust-dir-owner.h".
	(Parser::parse_module):
	Handle non-mod-rs external file modules properly.
	* util/rust-dir-owner.cc: New file.
	* util/rust-dir-owner.h: New file.

gcc/testsuite/ChangeLog:

	* rust/compile/test_mod.rs: Moved to...
	* rust/compile/issue-1089/test_mod.rs: ...here.
	* rust/compile/mod_missing_middle.rs: Fix paths.
	* rust/compile/missing_middle/both_path.rs: Moved to...
	* rust/compile/mod_missing_middle/missing_middle/both_path.rs: ...here.
	* rust/compile/missing_middle/explicit.not.rs: Moved to...
	* rust/compile/mod_missing_middle/missing_middle/explicit.not.rs: ...here.
	* rust/compile/missing_middle/other.rs: Moved to...
	* rust/compile/mod_missing_middle/missing_middle/explicit.not/other.rs: ...here.
	* rust/compile/missing_middle/inner_path.rs: Moved to...
	* rust/compile/mod_missing_middle/missing_middle/inner_path.rs: ...here.
	* rust/compile/missing_middle/outer_path.rs: Moved to...
	* rust/compile/mod_missing_middle/missing_middle/outer_path.rs: ...here.
	* rust/compile/missing_middle/sub/mod.rs: Moved to...
	* rust/compile/mod_missing_middle/missing_middle/sub/mod.rs: ...here.
	* rust/compile/torture/modules/mod.rs: Moved to...
	* rust/compile/torture/extern_mod1/modules/mod.rs: ...here.
	* rust/execute/torture/modules/mod.rs: Moved to...
	* rust/execute/torture/extern_mod4/modules/mod.rs: ...here.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-06-07 11:23:48 +00:00
Owen Avery
25b40ba2e0 Add error message when derive macro is invoked
gcc/rust/ChangeLog:

	* expand/rust-macro-builtins.cc: Fix comments.
	(MacroBuiltin::proc_macro_builtin): Add error message.
	* expand/rust-macro-builtins.h: Fix comments.

gcc/testsuite/ChangeLog:

	* rust/compile/derive_macro8.rs: New test.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-06-07 08:31:28 +00:00
Philip Herron
12d79b13fc gccrs: Respect the concrete type when resolving qualifed path types
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>
2023-06-06 23:36:56 +00:00
Owen Avery
1b322540fa Prevent initialization related warnings/errors for Optional
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=80635#c53

gcc/rust/ChangeLog:

	* util/rust-optional.h
	(class Optional): Add volatile field to union.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-06-06 14:59:42 +00:00
Owen Avery
d5fddb55d3 Handle crate metavariable
gcc/rust/ChangeLog:

	* expand/rust-macro-substitute-ctx.cc
	(SubstituteCtx::substitute_metavar): Substitute crate metavar.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-06-06 14:13:19 +00:00
Owen Avery
333e7a2b04 Allow parsing a borrow from struct expression
gcc/rust/ChangeLog:

	* parse/rust-parse-impl.h
	(Parser::null_denotation): Allow struct expression referencing.

gcc/testsuite/ChangeLog:

	* rust/compile/struct-expr-parse.rs: New test.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-06-06 14:09:45 +00:00
Charalampos Mitrodimas
e11efa45bf ast: dump literals correctly
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>
2023-06-06 12:46:02 +00:00
Arthur Cohen
cc09d0bf04 derive: Add dummy builtin transcriber for builtin derive macros.
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.
2023-06-05 13:23:05 +00:00
Pierre-Emmanuel Patry
171ea4e2b3 fixup: Fix bootstrap build
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>
2023-06-05 13:19:52 +00:00
Arthur Cohen
d9c676cbfc derive: Add proper derive(Clone) for unions
gcc/rust/ChangeLog:

	* ast/rust-ast-builder.cc (AstBuilder::struct_expr_struct): New function.
	(AstBuilder::let): Likewise.
	(AstBuilder::struct_expr): Likewise.
	(AstBuilder::struct_expr_field): Likewise.
	(AstBuilder::field_access): Likewise.
	(AstBuilder::wildcard): Likewise.
	* ast/rust-ast-builder.h: Likewise.
	* expand/rust-derive-clone.cc (DeriveClone::visit_union): Implement
	properly.

gcc/testsuite/ChangeLog:

	* rust/compile/derive_macro4.rs: New test.
	* rust/compile/derive_macro6.rs: New test.
2023-06-02 14:32:58 +00:00
Arthur Cohen
2946327ff9 derive: Add #[derive(Copy)] builtin
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.
2023-06-02 13:32:29 +00:00
Arthur Cohen
2e49323c75 derive: Add #[derive(Clone)] for regular structs
gcc/rust/ChangeLog:

	* expand/rust-derive-clone.cc (DeriveClone::visit_struct): Implement proper
	cloning for structs with fields.
	* ast/rust-ast-builder.cc (AstBuilder::struct_expr): New function.
	(AstBuilder::struct_expr_field): Likewise.
	(AstBuilder::field_access): Likewise.
	(AstBuilder::let): Likewise.
	* ast/rust-ast-builder.h: Declare new functions.

gcc/testsuite/ChangeLog:

	* rust/execute/torture/derive_macro4.rs: New test.
2023-06-01 15:32:23 +00:00
Pierre-Emmanuel Patry
7ffe13507f converter: Refactor locations
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>
2023-06-01 15:23:35 +00:00
Pierre-Emmanuel Patry
430b26a329 converter: Convert back Locations from spans
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>
2023-06-01 15:23:35 +00:00
Pierre-Emmanuel Patry
f35d52ce69 converter: Add conversion from locations to spans
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>
2023-06-01 15:23:35 +00:00
Pierre-Emmanuel Patry
e26fea0f49 libproc_macro: Add cpp Span representation
Add Span representation in libproc_macro cpp part of the library.
Integrate spans to existing types.

gcc/rust/ChangeLog:

	* util/rust-token-converter.cc (convert): Update call to
	constructors with location information.
	(handle_suffix): Convert token locus to a Span and use it in the
	literal.

ChangeLog:

	* libgrust/libproc_macro/Makefile.am: Add span.cc
	* libgrust/libproc_macro/Makefile.in: Regenerate.
	* libgrust/libproc_macro/span.cc: New file.
	* libgrust/libproc_macro/span.h: New file.
	* libgrust/libproc_macro/group.cc (Group::make_group): Add span
	argument.
	* libgrust/libproc_macro/group.h (GROUP_H): Add include
	directive for spans.
	* libgrust/libproc_macro/ident.cc (Ident__new): Add span
	argument.
	(Ident__new_raw): Likewise.
	(Ident::make_ident): Likewise.
	* libgrust/libproc_macro/ident.h (Ident__new): Likewise.
	(Ident__new_raw): Likewise.
	* libgrust/libproc_macro/literal.cc (Literal::clone): Clone the
	span.
	(Literal::make_literal): Add span argument.
	(Literal::make_u8): Likewise.
	(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.
	* libgrust/libproc_macro/literal.h (struct Literal): Add span to
	Literal structure.
	* libgrust/libproc_macro/punct.cc (Punct::make_punct): Add span
	argument to punct constructor.
	* libgrust/libproc_macro/punct.h (struct Punct): Add span to
	Punct structure.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-06-01 15:23:35 +00:00
Pierre-Emmanuel Patry
3f60f6104a libproc_macro: Add Span definition
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>
2023-06-01 15:23:35 +00:00
Owen Avery
d0e9f47b08 Properly match delimiters
gcc/rust/ChangeLog:

	* expand/rust-macro-expand.cc
	(MacroExpander::try_match_rule): Don't match delimiters for root matcher.
	(MacroExpander::match_matcher): Add option to match delimiters.
	* expand/rust-macro-expand.h
	(MacroExpander::match_matcher): Likewise.
	* parse/rust-parse-impl.h
	(Parser::skip_token): Add zero argument method.
	* parse/rust-parse.h:
	(Parser::skip_token): Likewise.

gcc/testsuite/ChangeLog:

	* rust/compile/macro-delim.rs: New test.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-06-01 15:21:53 +00:00
Philip Herron
18c00a4c0c gccrs: get rid of useless helper class and fix header usage
gcc/rust/ChangeLog:

	* Make-lang.in: remove files
	* backend/rust-compile-block.h: fix headers
	* backend/rust-compile-expr.h: likewise
	* backend/rust-compile-fnparam.h: likewise
	* backend/rust-compile-item.h: likewise
	* backend/rust-compile-pattern.h: likewise
	* backend/rust-compile-resolve-path.h: likewise
	* backend/rust-compile-stmt.h: likewise
	* typecheck/rust-autoderef.cc: likewise
	* typecheck/rust-hir-path-probe.cc: likewise
	* typecheck/rust-hir-path-probe.h: likewise
	* typecheck/rust-hir-trait-reference.h: likewise
	* typecheck/rust-hir-trait-resolve.cc: use a for loop instead
	* typecheck/rust-hir-trait-resolve.h: fix headers
	* typecheck/rust-hir-type-check-expr.h: likewise
	* typecheck/rust-hir-type-check-implitem.h: likewise
	* typecheck/rust-hir-type-check-item.h: likewise
	* typecheck/rust-hir-type-check-path.cc: likewise
	* typecheck/rust-hir-type-check-pattern.h: likewise
	* typecheck/rust-hir-type-check-stmt.h: likewise
	* typecheck/rust-hir-type-check-type.h: likewise
	* typecheck/rust-hir-type-check-util.cc: Removed.
	* typecheck/rust-hir-type-check-util.h: Removed.

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2023-06-01 15:09:29 +00:00
Arthur Cohen
1eef15537f expansion: Add base for deriving builtin macros (Clone, Copy...)
gcc/rust/ChangeLog:

	* Make-lang.in: Add new object files to Makefile.
	* expand/rust-expand-visitor.cc (is_derive): Move function.
	(is_builtin): Likewise.
	(get_traits_to_derive): New function.
	(derive_item): Likewise.
	(ExpandVisitor::visit): Visit item/statements containers.
	(ExpandVisitor::visit_outer_attrs): Take a reference on the attribute
	instead of a copy.
	(ExpandVisitor::is_derive): Deleted function.
	(ExpandVisitor::is_builtin): Likewise.
	* expand/rust-expand-visitor.h (RUST_EXPAND_VISITOR_H): Add missing #ifdef
	guards.
	(is_derive): Declare function.
	(is_builtin): Likewise.
	* expand/rust-macro-builtins.cc (builtin_macro_from_string): Use new
	MacroBuiltin::builtins map.
	(make_macro_path_str): Likewise.
	* expand/rust-macro-builtins.h (enum class): Add builtin derive macros.
	* expand/rust-derive-clone.cc: New file.
	* expand/rust-derive-clone.h: New file.
	* expand/rust-derive.cc: New file.
	* expand/rust-derive.h: New file.
	* util/rust-hir-map.cc (Mappings::insert_macro_def): Fix logic for
	setting builtin macro transcribers.

gcc/testsuite/ChangeLog:

	* rust/compile/macro43.rs: Fix test with new derive macros.
	* rust/compile/derive_macro1.rs: New test.
	* rust/compile/derive_macro3.rs: New test.
	* rust/execute/torture/derive_macro1.rs: New test.
	* rust/execute/torture/derive_macro3.rs: New test.
2023-06-01 08:45:11 +00:00
Arthur Cohen
a0e39c36e2 ast: Add AstBuilder class.
gcc/rust/ChangeLog:

	* ast/rust-ast-builder.cc: New file.
	* ast/rust-ast-builder.h: New file.
2023-06-01 08:45:11 +00:00
Arthur Cohen
e4359c4726 expand: Add missing copyright headers
Fixes #2250

gcc/rust/ChangeLog:

	* expand/rust-macro-invoc-lexer.cc: Add missing copyright header.
	* expand/rust-macro-substitute-ctx.cc: Likewise.
2023-06-01 08:25:26 +00:00
Owen Avery
aa823eafca Make key and key/value config options seperate
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>
2023-05-31 13:51:44 +00:00
Philip Herron
fb1259001c gccrs: Fix cast site to not miss type-unifications
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>
2023-05-30 17:03:48 +00:00
Philip Herron
bc2cac1413 gccrs: Add missing name resolution to item statements
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>
2023-05-30 16:32:08 +00:00
Philip Herron
d3412f6cdc gccrs: remove unused header
gcc/rust/ChangeLog:

	* resolve/rust-ast-resolve-pattern.cc: remove unused

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2023-05-30 16:32:08 +00:00
Philip Herron
85d2d5f0f8 gccrs: Fix missing pop of name scope at the end of Trait Impl
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>
2023-05-30 16:32:08 +00:00
Philip Herron
82d9bd0b03 gccrs: remove useless lookup to NodeId
gcc/rust/ChangeLog:

	* backend/rust-compile-expr.cc (CompileExpr::visit): remove unused

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2023-05-30 16:32:08 +00:00
Philip Herron
2747ea19ce gccrs: Add missing HIR lowering to item statements
Addresses #2238

gcc/rust/ChangeLog:

	* hir/rust-ast-lower-stmt.cc (ASTLoweringStmt::translate): hir lowering
	(ASTLoweringStmt::visit): likewise
	* hir/rust-ast-lower-stmt.h: likewise

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2023-05-30 16:32:08 +00:00
Owen Avery
019dd7b55f Avoid invalid metavariable substitutions
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>
2023-05-30 08:36:00 +00:00
Owen Avery
0162ff3900 Fix handling of single fragments in repetitions
gcc/rust/ChangeLog:

	* expand/rust-macro-substitute-ctx.cc
	(SubstituteCtx::check_repetition_amount):
	Ignore single fragments while checking repetition amount.

gcc/testsuite/ChangeLog:

	* rust/compile/issue-2207.rs: New test.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-05-30 08:33:50 +00:00
Philip Herron
2d80680140 gccrs: Fix bounds checking to check both sides
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>
2023-05-26 16:28:04 +00:00
Philip Herron
d47f52a583 gccrs: support deref cycles to resolve to trait items
Fixes #2190

gcc/rust/ChangeLog:

	* backend/rust-compile-expr.cc (HIRCompileBase::resolve_deref_adjustment):
	reuse op overload code
	* typecheck/rust-autoderef.cc (Adjuster::try_deref_type): update
	(Adjuster::try_raw_deref_type): likewise
	* typecheck/rust-autoderef.h: likewise
	* typecheck/rust-hir-dot-operator.cc (MethodResolver::select):
	improve debug loging

gcc/testsuite/ChangeLog:

	* rust/compile/issue-2190-1.rs: New test.
	* rust/compile/issue-2190-2.rs: New test.

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2023-05-26 16:28:04 +00:00
Philip Herron
e656f08b6f gccrs: refactor resolve_method_address to be more generic
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>
2023-05-26 16:28:04 +00:00
David Malcolm
9e2ecdf3b9 hir: remove stray semicolon
Fix for this warning:

../../src/gcc/rust/typecheck/rust-hir-trait-reference.cc:40:2: warning: extra ‘;’ [-Wpedantic]
   40 | };
      |  ^

gcc/rust/ChangeLog:

	* typecheck/rust-hir-trait-reference.cc (TraitItemReference::is_optional): Remove
	stray semicolon.
2023-05-25 09:00:33 +00:00
Arthur Cohen
058682f736 enr: Cleanup #[macro_use] accumulation
gcc/rust/ChangeLog:

	* resolve/rust-early-name-resolver.cc (EarlyNameResolver::go): Cleanup
	order of calls when accumulating #[macro_use] macros.
	(EarlyNameResolver::visit): Likewise.
2023-05-24 09:33:42 +00:00
Matthew Jasper
6521333e40 gccrs: Fix macro resolutions in middle of multiple nested macro_use modules
gcc/rust/ChangeLog:

	* resolve/rust-early-name-resolver.cc (EarlyNameResolver::accumulate_escaped_macros):
	Remove unnecessary visit.

gcc/testsuite/ChangeLog:

	* rust/compile/nested_macro_use3.rs: New test.

Signed-off-by: Matthew Jasper <mjjasper1@gmail.com>
2023-05-22 10:10:38 +00:00
Matthew Jasper
1666b77ead gccrs: Only check first item of cfg_attr attribute as predicate
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>
2023-05-22 08:08:20 +00:00
Owen Avery
003ac98771 Add operator== for Optional.
gcc/rust/ChangeLog:

	* util/rust-optional.h
	(operator==): New for Optional<T> == Optional<U>.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-05-22 07:59:49 +00:00
Owen Avery
c7b7e297ea Parse AttrInputMacro
gcc/rust/ChangeLog:

	* parse/rust-parse-impl.h
	(Parser::parse_attr_input): Parse AttrInputMacro.

gcc/testsuite/ChangeLog:

	* rust/compile/doc_macro.rs: New test.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-05-18 20:44:20 +00:00
Pierre-Emmanuel Patry
4ddb7d143b ast: Propagate type suffix
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>
2023-05-18 20:39:00 +00:00
Owen Avery
cc661d8a33 Improve Optional<T> implementation
gcc/rust/ChangeLog:

	* util/rust-optional.h
	(class Optional<T>): Improve inner state.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-05-18 20:38:32 +00:00
Owen Avery
ee5b5905de Handle keyword metavariables
gcc/rust/ChangeLog:

	* expand/rust-macro-substitute-ctx.cc
	(SubstituteCtx::check_repetition_amount): Handle keywords.
	(SubstituteCtx::substitute_token): Likewise.
	* lex/rust-token.cc
	(Token::get_str): Likewise.
	* parse/rust-parse-impl.h
	(Parser::parse_macro_match_fragment): Likewise.

gcc/testsuite/ChangeLog:

	* rust/compile/macro-issue2194.rs: New test.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-05-18 20:29:52 +00:00
Arthur Cohen
5c78ef9854 ast: Add outer_attrs to all Items
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.
2023-05-18 16:40:08 +00:00
Pierre-Emmanuel Patry
ad7c998b21 libproc_macro: Change constructor in ffistring
The "new" constructor wasn't fitting it's usage well.

ChangeLog:

	* libgrust/libproc_macro/rust/bridge/ffistring.rs: Implement
	From trait for FFIString.
	* libgrust/libproc_macro/rust/bridge/literal.rs: Change
	constructor call.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-05-17 16:13:45 +00:00
Pierre-Emmanuel Patry
70c245e4e3 libproc_macro: Copy ffistring data from source
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>
2023-05-17 16:13:45 +00:00
Pierre-Emmanuel Patry
668c220024 libproc_macro: Remove has_suffix attribute
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>
2023-05-17 16:13:45 +00:00
Pierre-Emmanuel Patry
d8202b68bc converter: Merge dispatch into one function
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>
2023-05-17 16:13:45 +00:00
Pierre-Emmanuel Patry
4c34885a5a libproc_macro: Change cpp literal representation
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>
2023-05-17 16:13:45 +00:00
Pierre-Emmanuel Patry
37a893441e libproc_macro: Change rust literal internals
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>
2023-05-17 16:13:45 +00:00
Owen Avery
9cbcb74d71 Add AST::AttrInputMacro
gcc/rust/ChangeLog:

	* ast/rust-ast-dump.cc
	(Dump::visit): Add AttrInputMacro visitor.
	* ast/rust-ast-dump.h:
	(Dump::visit): Likewise.
	* ast/rust-ast-full-decls.h
	(class AttrInputMacro): New.
	* ast/rust-ast-collector.cc
	(TokenCollector::visit):
	Add and call out to AttrInputMacro visitor.
	* ast/rust-ast-collector.h:
	(TokenCollector::visit): Add AttrInputMacro visitor.
	* ast/rust-ast-visitor.h:
	(ASTVisitor::visit): Likewise.
	* ast/rust-ast.cc
	(AttrInputMacro::accept_vis): New.
	(AttrInputMacro::as_string): New.
	(AttrInputMacro::AttrInputMacro): New.
	(AttrInputMacro::operator=): New.
	* ast/rust-ast.h:
	(AttrInput::AttrInputType::MACRO): New.
	* ast/rust-expr.h
	(class AttrInputMacro): New.
	* checks/errors/rust-feature-gate.h:
	(FeatureGate::visit): Add AttrInputMacro visitor.
	* expand/rust-cfg-strip.cc
	(CfgStrip::visit): Likewise.
	* expand/rust-cfg-strip.h:
	(CfgStrip::visit): Likewise.
	* expand/rust-expand-visitor.cc
	(ExpandVisitor::visit): Likewise.
	* expand/rust-expand-visitor.h:
	(ExpandVisitor::visit): Likewise.
	* hir/rust-ast-lower-base.cc
	(ASTLoweringBase::visit): Likewise.
	* hir/rust-ast-lower-base.h:
	(ASTLoweringBase::visit): Likewise.
	* resolve/rust-ast-resolve-base.cc
	(ResolverBase::visit): Likewise.
	* resolve/rust-ast-resolve-base.h:
	(ResolverBase::visit): Likewise.
	* resolve/rust-early-name-resolver.cc
	(EarlyNameResolver::visit): Likewise.
	* resolve/rust-early-name-resolver.h:
	(EarlyNameResolver::visit): Likewise.
	* util/rust-attributes.cc
	(AttributeChecker::visit): Likewise.
	(check_doc_attribute): Handle AttrInputType::MACRO.
	* util/rust-attributes.h:
	(AttributeChecker::visit): Add AttrInputMacro visitor.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-05-17 16:12:25 +00:00
Owen Avery
d98e5aaa62 Make MacroInvocation cloning public
gcc/rust/ChangeLog:

	* ast/rust-macro.h
	(MacroInvocation::clone_macro_invocation_impl): Make public.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-05-17 16:12:25 +00:00
Owen Avery
6dd946dc11 Allow hashing Optional<T>
gcc/rust/ChangeLog:

	* util/rust-optional.h
	(struct std::hash<Optional<T>>): New.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-05-17 16:08:00 +00:00
Owen Avery
86dc0a1a1f Improve Optional<T&> implementation
gcc/rust/ChangeLog:

	* util/rust-optional.h
	(class Optional<T&>): Use pointers internally.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-05-17 16:07:51 +00:00
Arthur Cohen
7c03c7d73c dump: Dump TupleIndexExprs
gcc/rust/ChangeLog:

	* ast/rust-ast-dump.cc (Dump::visit): Implement dump for
	`TupleIndexExpr`.
2023-05-16 13:20:49 +00:00
Owen Avery
e02b4427f8 Change return type of token_id_keyword_string
gcc/rust/ChangeLog:

	* lex/rust-token.cc
	(token_id_keyword_string): Return std::string reference.
	* lex/rust-token.h
	(token_id_keyword_string): Return std::string reference.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-05-16 08:22:35 +00:00
Matthew Jasper
136ef0912e gccrs: Fix parsing of block expressions followed by .
`{ ... }.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>
2023-05-15 14:48:41 +00:00
Matthew Jasper
4cd88c4cd6 ast: Remove ExprStmtWithBlock / ExprStmtWithoutBlock distinction
This distinction isn't very helpful and makes correct parsing harder.

gcc/rust/ChangeLog:

	* ast/rust-ast-full-decls.h (class ExprStmtWithoutBlock): Remove.
	(class ExprStmtWithBlock): Remove.
	* ast/rust-stmt.h (class ExprStmtWithoutBlock): Remove.
	(class ExprStmtWithBlock): Remove.
	(class ExprStmt):
	Make non-abstract, add common functionality from removed base classes.
	* ast/rust-ast.h: Move to_stmt to base class.
	* ast/rust-ast.cc (ExprStmtWithBlock::as_string): Remove.
	* ast/rust-macro.h: Use new signature for to_stmt.
	(ExprStmt::as_string): New method.
	(ExprStmtWithoutBlock::as_string): Remove.
	(BlockExpr::strip_tail_expr): Update for removed classes.
	(ExprStmtWithoutBlock::accept_vis): Remove.
	(ExprStmtWithBlock::accept_vis): Remove.
	(ExprStmt::accept_vis): New method.
	* ast/rust-ast-dump.cc (Dump::visit): Update for removed classes.
	* ast/rust-ast-dump.h: Likewise.
	* ast/rust-ast-collector.h: Likewise.
	* ast/rust-ast-collector.cc (TokenStream::visit): Likewise.
	* ast/rust-ast-visitor.h: Likewise.
	* checks/errors/rust-feature-gate.h: Likewise.
	* expand/rust-expand-visitor.cc (ExpandVisitor::visit): Likewise.
	* expand/rust-expand-visitor.h: Likewise.
	* expand/rust-cfg-strip.cc (CfgStrip::visit): Likewise.
	* expand/rust-cfg-strip.h: Likewise.
	* hir/rust-ast-lower-base.cc (ASTLoweringBase::visit): Likewise.
	* hir/rust-ast-lower-base.h: Likewise.
	* hir/rust-ast-lower-stmt.cc (ASTLoweringStmt::visit): Likewise.
	* hir/rust-ast-lower-stmt.h: Likewise.
	* util/rust-attributes.cc (AttributeChecker::visit): Likewise.
	* util/rust-attributes.h: Likewise.
	* resolve/rust-ast-resolve-base.cc (ResolverBase::visit): Likewise.
	* resolve/rust-ast-resolve-base.h: Likewise.
	* resolve/rust-ast-resolve-stmt.h: Likewise.
	* resolve/rust-early-name-resolver.cc (EarlyNameResolver::visit):
	Likewise.
	* resolve/rust-early-name-resolver.h: Likewise.
	* parse/rust-parse-impl.h (Parser::parse_match_expr): Likewise.
	(Parser::parse_stmt_or_expr_without_block): Likewise.
	* parse/rust-parse.h: Likewise.

Signed-off-by: Matthew Jasper <mjjasper1@gmail.com>
2023-05-15 14:48:41 +00:00
Owen Avery
142b84e3c5 Handle keywords in macro fragments
gcc/rust/ChangeLog:

	* lex/rust-token.cc
	(token_id_is_keyword): New.
	(token_id_keyword_string): New.
	* lex/rust-token.h
	(token_id_is_keyword): New.
	(token_id_keyword_string): New.
	* expand/rust-macro-expand.cc
	(MacroExpander::match_fragment): Match keywords for ident fragment.
	* parse/rust-parse-impl.h
	(Parser::parse_identifier_or_keyword_token): Add.
	* parse/rust-parse.h
	(Parser::parse_identifier_or_keyword_token): Add.

gcc/testsuite/ChangeLog:

	* rust/compile/macro-issue2192.rs: New test.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-05-12 11:28:13 +00:00
Arthur Cohen
dc80964529 Address invalid little-endian-only testcases
gcc/testsuite/ChangeLog:

	* rust/compile/const-issue1440.rs: Remove LE conditional compilation.
	* rust/compile/torture/issue-1432.rs: Likewise.
2023-05-12 11:25:39 +00:00
Pierre-Emmanuel Patry
12d52ac021 converter: Fix suffix condition
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>
2023-05-11 09:38:22 +02:00
Pierre-Emmanuel Patry
39817cc6c9 converter: Fix some styling issues
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>
2023-05-11 09:38:22 +02:00
Pierre-Emmanuel Patry
983b113224 converter: Make converter input immutable
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>
2023-05-11 09:38:22 +02:00
Pierre-Emmanuel Patry
b61549737c converter: Add Ident conversions
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>
2023-05-11 09:38:22 +02:00
Pierre-Emmanuel Patry
f616a5db5c converter: Convert literals back to tokens
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>
2023-05-11 09:38:22 +02:00
Pierre-Emmanuel Patry
58c10eb4fb converter: Add punct conversion function
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>
2023-05-11 09:38:22 +02:00
Pierre-Emmanuel Patry
47eed0650b converter: Const conversion to tokenstream
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>
2023-05-11 09:38:21 +02:00
Pierre-Emmanuel Patry
c032b7c103 converter: Return a vector to const pointers
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>
2023-05-11 09:38:21 +02:00
Pierre-Emmanuel Patry
c24227d377 converter: Add from_tokentree function
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>
2023-05-11 09:38:21 +02:00
Pierre-Emmanuel Patry
87dfca85c9 converter: Add group conversion implementation
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>
2023-05-11 09:38:21 +02:00
Pierre-Emmanuel Patry
15225362fe converter: Add TokenStream conversion function
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>
2023-05-11 09:38:21 +02:00
Pierre-Emmanuel Patry
b12481cf8c converter: Remove redundant variable
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>
2023-05-11 09:38:21 +02:00
Pierre-Emmanuel Patry
8f6b745955 ast: Move token converter out of ast module
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>
2023-05-11 09:38:21 +02:00
Pierre-Emmanuel Patry
2dc0dab7e8 ast: Rename header guard
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>
2023-05-11 09:38:21 +02:00
Pierre-Emmanuel Patry
a442837352 ast: Rename rust-ast-tokenstream file
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>
2023-05-11 09:38:21 +02:00
Pierre-Emmanuel Patry
c4e20409d7 ast: Rename TokenStream in the AST module
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>
2023-05-11 09:38:21 +02:00
Pierre-Emmanuel Patry
a841180b02 tokenstream: Add conversion for float literals
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>
2023-05-11 09:38:21 +02:00
Pierre-Emmanuel Patry
96ed2e8e19 tokenstream: Add literal int draft conversion
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>
2023-05-11 09:38:20 +02:00
Pierre-Emmanuel Patry
7358d90bb6 tokenstream: Add string and byte string literals
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>
2023-05-11 09:38:20 +02:00
Pierre-Emmanuel Patry
f087501e33 tokenstream: Add tokens to Ident conversion
Add conversion from a rust token to tokenstream Idents.

gcc/rust/ChangeLog:

	* ast/rust-ast-tokenstream.cc (TokenStream::collect): Add Ident
	conversion.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-05-11 09:38:20 +02:00
Pierre-Emmanuel Patry
75eb15164a tokenstream: Add joint punct token conversion
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>
2023-05-11 09:38:20 +02:00
Pierre-Emmanuel Patry
fb2a8509d7 tokenstream: Convert single punctuation tokens
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>
2023-05-11 09:38:20 +02:00
Pierre-Emmanuel Patry
b49c70be23 tokenstream: Convert group markers
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>
2023-05-11 09:38:20 +02:00
M V V S Manoj Kumar
5ee23f588d Added HIR::InlineAsm node
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>
2023-05-10 14:38:20 +00:00
Philip Herron
875cd5ee9c gccrs: Add missing coercion site logic to return expressions
gcc/rust/ChangeLog:

	* backend/rust-compile-base.cc: track return type in fncontext
	* backend/rust-compile-context.h (struct fncontext): likewise
	* backend/rust-compile-expr.cc (CompileExpr::visit): apply coercion site
	(CompileExpr::generate_closure_function): update push_context
	* typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit): likewise

gcc/testsuite/ChangeLog:

	* rust/execute/torture/coercion3.rs: New test.

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2023-05-09 16:22:28 +00:00
Philip Herron
eb60cd1f6d gccrs: add missing coercion site code generation for block tail
Fixes #2179

gcc/rust/ChangeLog:

	* backend/rust-compile-base.cc (HIRCompileBase::compile_function_body):
	add missing coercion_site codegen

gcc/testsuite/ChangeLog:

	* rust/execute/torture/issue-2179.rs: New test.

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2023-05-09 16:22:28 +00:00
Philip Herron
6ff31ac29d gccrs: unify how we handle DST's
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>
2023-05-09 16:22:28 +00:00
Philip Herron
af58bf3dd2 gccrs: we can only return unit-type when the ABI is non C
gcc/rust/ChangeLog:

	* backend/rust-compile-type.cc (TyTyResolveCompile::visit): add filter

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2023-05-08 14:53:18 +00:00
Philip Herron
ea597e73da gccrs: Redo how we handle unit types for the final time
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>
2023-05-08 14:53:18 +00:00
Philip Herron
a252a9c12d gccrs: Fix ICE in check for unused global variables
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>
2023-05-08 14:53:18 +00:00
Owen Avery
85ca0ba820 Fix "default unsafe fn ..." parsing
gcc/rust/ChangeLog:

	* parse/rust-parse-impl.h
	(Parser::parse_trait_impl_function_or_method):
	Parse function/method qualifiers after "default".

gcc/testsuite/ChangeLog:

	* rust/compile/parse_specialization.rs:
	Add "default unsafe" coverage.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-05-08 13:57:14 +00:00
Philip Herron
cae5140e9b gccrs: Add missing compile locals for constants and statics
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>
2023-05-05 18:15:06 +00:00
Arthur Cohen
bd91c5696e ast: Format AST code properly.
gcc/rust/ChangeLog:

	* ast/rust-ast.h (class AttrInputMetaItemContainer): Run clang-format.
	(class DelimTokenTree): Likewise.
2023-05-05 11:56:07 +00:00
Arthur Cohen
9d1e7f2cb0 enr: Accumulate nested escaped macros properly.
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.
2023-05-05 11:56:07 +00:00
Arthur Cohen
0f9a757b73 ast: Add take_items() and set_items() methods for Item containers
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.
2023-05-05 11:56:07 +00:00
Arthur Cohen
8ff1e54d97 ast: Add Kind::MODULE
gcc/rust/ChangeLog:

	* ast/rust-ast.h (enum Kind): Add MODULE variant.
	* ast/rust-item.h: Return Kind::MODULE in AST::Module::get_kind().
2023-05-05 11:56:07 +00:00
Arthur Cohen
58f866ba45 builtin: Cleanup handling of builtin macros
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.
2023-05-05 11:48:37 +00:00
Arthur Cohen
0a0114f528 utils: Add bidirectional hashmap class
gcc/rust/ChangeLog:

	* expand/rust-macro-builtins.cc: Include bidirectional map.
	* util/bi-map.h: New file.
2023-05-05 11:48:37 +00:00
Pierre-Emmanuel Patry
f04cbc3f17 libproc_macro: Add helpers to construct Procmacro
Add some helper functions to create Procmacro tagged unions.

ChangeLog:

	* libgrust/libproc_macro/proc_macro.cc (Procmacro::make_derive):
	Add custom derive macro constructor.
	(Procmacro::make_attribute): Add attribute macro constructor.
	(Procmacro::make_bang): Add bang macro constructor.
	* libgrust/libproc_macro/proc_macro.h (struct Procmacro):
	Add helper function prototypes.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-05-05 07:41:24 +00:00
Pierre-Emmanuel Patry
1e14898108 libproc_macro: Add proc_macro interface structures
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>
2023-05-05 07:41:24 +00:00
Owen Avery
bb1e40da86 Add test from issue 1446
gcc/testsuite/ChangeLog:

	* rust/compile/issue-1446.rs: New test.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-05-04 09:07:52 +00:00
Owen Avery
2e91a0bf65 Handle replacing stripped tail expressions
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>
2023-05-04 09:07:52 +00:00
Owen Avery
d294dde0d2 Add is_expr method to AST::Stmt
gcc/rust/ChangeLog:

	* ast/rust-ast.h
	(Stmt::is_expr): New.
	* ast/rust-stmt.h
	(ExprStmt::is_expr): New.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-05-04 09:07:52 +00:00
Owen Avery
7c7fa5f999 Fix out of bounds indexing while expanding macros with repetition
gcc/rust/ChangeLog:

	* expand/rust-macro-substitute-ctx.cc
	(SubstituteCtx::substitute_repetition): Fix out-of-bounds.

gcc/testsuite/ChangeLog:

	* rust/compile/macro52.rs: New test.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-05-03 09:58:59 +00:00
Pierre-Emmanuel Patry
6266d344d3 libproc_macro: Change proc_macro.h to main header
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>
2023-05-03 08:41:48 +00:00
Pierre-Emmanuel Patry
afcde5f817 libproc_macro: Build statically
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>
2023-05-03 08:41:48 +00:00
Pierre-Emmanuel Patry
b0141f5adc libproc_macro: Remove internal named namespaces
Either move the elements from their namespace up to the procmacro
namespace or make the namespace anonymous.

ChangeLog:

	* libgrust/libproc_macro/group.cc (Group::make_group): Remove
	internal namespace.
	(Group::drop): Likewise.
	* libgrust/libproc_macro/group.h (enum Delimiter): Make members
	upercase.
	(struct Group):
	* libgrust/libproc_macro/ident.cc (Ident::drop): Remove internal
	namespace.
	* libgrust/libproc_macro/ident.h (Ident__clone): Likewise.
	* libgrust/libproc_macro/literal.cc (Literal::make_isize):
	Likewise.
	* libgrust/libproc_macro/literal.h (union LiteralPayload):
	Likewise.
	(Literal__from_string): Likewise.
	* libgrust/libproc_macro/punct.cc (Punct::make_punct): Likewise.
	* libgrust/libproc_macro/punct.h (enum Spacing): Make members
	uppercase.
	* libgrust/libproc_macro/tokenstream.cc (TokenStream::make_tokenstream):
	Remove internal namespace.
	(TokenStream::grow): Likewise.
	(TokenStream::push): Likewise.
	(TokenSream__push): Likewise.
	(TokenStream__clone): Likewise.
	(TokenStream__drop): Likewise.
	* libgrust/libproc_macro/tokenstream.h (struct TokenStream):
	Likewise.
	(TokenSream__push): Likewise.
	(TokenStream__drop): Likewise.
	* libgrust/libproc_macro/tokentree.cc (TokenTree::make_tokentree):
	Likewise.
	(TokenTree::drop): Likewise.
	* libgrust/libproc_macro/tokentree.h (union TokenTreePayload):
	Likewise.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-05-03 08:41:48 +00:00
Pierre-Emmanuel Patry
87abaedf5a libproc_macro: Put all structures in a namespace
Put all functions and structures in a Procmacro namespace to avoid
spilling names in any other namespace.

ChangeLog:

	* libgrust/libproc_macro/group.cc (Group::drop): Add Procmacro
	namespace.
	* libgrust/libproc_macro/group.h: Likewise.
	* libgrust/libproc_macro/ident.cc (Ident::drop): Likewise.
	* libgrust/libproc_macro/ident.h (Ident__clone): Likewise.
	* libgrust/libproc_macro/literal.cc (Literal::make_isize):
	Likewise.
	* libgrust/libproc_macro/literal.h (Literal__from_string):
	Likewise.
	* libgrust/libproc_macro/punct.cc (Punct::make_punct): Likewise.
	* libgrust/libproc_macro/punct.h: Likewise.
	* libgrust/libproc_macro/tokenstream.cc (TokenStream__drop):
	Likewise.
	* libgrust/libproc_macro/tokenstream.h (TokenStream__drop):
	Likewise.
	* libgrust/libproc_macro/tokentree.cc (TokenTree::drop):
	Likewise.
	* libgrust/libproc_macro/tokentree.h: Likewise.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-05-03 08:41:48 +00:00
Pierre-Emmanuel Patry
ad3f88286e libproc_macro: Remove unused gm2 variable
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>
2023-05-03 08:41:48 +00:00
Pierre-Emmanuel Patry
1fb32d7293 cli: Add frust-extern option
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>
2023-04-28 16:26:38 +00:00
Owen Avery
fef6c56001 Fix infinite loop with parsing invalid generic parameters
gcc/rust/ChangeLog:

	* parse/rust-parse-impl.h
	(Parser::parse_generic_params):
	Handle parameter parsing error.

gcc/testsuite/ChangeLog:

	* rust/compile/issue-2125.rs: New test.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-04-28 11:09:16 +00:00
Philip Herron
aaf7336dfa gccrs: Improve operator overload check for recursive overload
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>
2023-04-28 10:52:24 +00:00
Philip Herron
187f4b9eb8 gccrs: qualified path syntax is used to disambiguate predicates
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>
2023-04-28 10:16:43 +00:00
Philip Herron
c13032e55c gccrs: Extract helper lookup_associated_impl_block
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>
2023-04-28 10:16:43 +00:00
Owen Avery
48510f443f Type check StructPatternFieldIdentPat
gcc/rust/ChangeLog:

	* typecheck/rust-hir-type-check-pattern.cc
	(TypeCheckPattern::visit): Type check StructPatternFieldIdentPat.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-04-28 09:18:06 +00:00
Owen Avery
4051d11a7d Lower StructPatternFieldIdentPat
gcc/rust/ChangeLog:

	* hir/rust-ast-lower-pattern.cc
	(ASTLoweringPattern::visit): Lower StructPatternFieldIdentPat.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-04-28 09:18:01 +00:00
Philip Herron
ca1f50ba61 gccrs: resolve the associated_predicate when mapping Fn traits
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>
2023-04-27 22:18:22 +00:00
Philip Herron
5dfcde3b49 gccrs: Add missing where clause lowering for Impl functions
Fixes #2106

gcc/rust/ChangeLog:

	* hir/rust-ast-lower-implitem.h: add missing where clause lowering

gcc/testsuite/ChangeLog:

	* rust/compile/issue-2106.rs: New test.
	* rust/compile/issue-1524.rs: regression (placeholder generic)

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2023-04-27 22:18:08 +00:00
Philip Herron
b5a7e8d10b gccrs: Add missing TypeBoundWhereClauseItem::get_locus
gcc/rust/ChangeLog:

	* hir/tree/rust-hir-item.h: add get_locus() const

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2023-04-27 22:18:08 +00:00
Owen Avery
8b6d44ad42 Add accessors to HIR::StructPatternFieldIdentPat
gcc/rust/ChangeLog:

	* hir/tree/rust-hir-pattern.h
	(StructPatternFieldIdentPat::get_identifier): New.
	(StructPatternFieldIdentPat::get_pattern): New.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-04-27 22:17:51 +00:00
Marc Poulhiès
d2df050bd4 gccrs: Minor tuning in AST dump
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>
2023-04-26 22:05:54 +00:00
Owen Avery
e68922cb64 Fix -frust-dump-* error messages
gcc/rust/ChangeLog:

	* rust-session-manager.cc
	(Session::enable_dump): Fix error messages.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-04-26 21:55:20 +00:00
Philip Herron
9b3028c01e gccrs: Add missing ABI checking on function types
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>
2023-04-26 21:53:39 +00:00
Philip Herron
f26be61bf0 gccrs: Add missing ABI mapping
gcc/rust/ChangeLog:

	* util/rust-abi.cc (get_abi_from_string): add ABI mapping

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2023-04-26 21:53:39 +00:00
Philip Herron
a14731ddb6 gccrs: Add mechanism use pattern information to improve type info
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>
2023-04-26 15:28:06 +00:00
Philip Herron
419e1cff11 gccrs: remove unused header
gcc/rust/ChangeLog:

	* typecheck/rust-hir-type-check-pattern.h: cleanup

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2023-04-26 15:28:06 +00:00
Philip Herron
dd0677cf09 gccrs: Fix ICE when we dont get a reference type
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>
2023-04-26 15:28:06 +00:00
Philip Herron
83e971d908 gccrs: remove unused includes
gcc/rust/ChangeLog:

	* backend/rust-compile-implitem.h: remove includes

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2023-04-26 15:12:22 +00:00
Philip Herron
727056301b gccrs: fix ICE with recursive function calls
Fixes #2136

gcc/rust/ChangeLog:

	* backend/rust-compile-item.cc (CompileItem::visit): remove bad checks

gcc/testsuite/ChangeLog:

	* rust/compile/issue-2136-1.rs: New test.
	* rust/compile/issue-2136-2.rs: New test.

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2023-04-26 15:12:22 +00:00
Philip Herron
8f66804585 gccrs: enable -Winfinite-recursion warnings by default
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>
2023-04-26 15:12:22 +00:00
Philip Herron
028a5bb8ed gccrs: Fix ICE in assignment of error type bound predicates
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>
2023-04-26 15:02:47 +00:00
Philip Herron
ddcd571a67 gccrs: Fix ICE during method resolution
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>
2023-04-26 15:02:44 +00:00
Philip Herron
34a5eebc1b gccrs: Track Self properly with TypePredicateBounds
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>
2023-04-26 15:02:40 +00:00
Philip Herron
198f98ec04 gccrs: add error state to TypeCheckContextItem and missing copy ctor's
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>
2023-04-26 15:02:40 +00:00
Philip Herron
c630493edc gccrs: add helper to check for a const or static context
gcc/rust/ChangeLog:

	* typecheck/rust-hir-type-check.h: new helper
	* typecheck/rust-typecheck-context.cc (TypeCheckContext::have_function_context):
	implementation

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2023-04-26 15:02:40 +00:00
Philip Herron
aa67a856e7 gccrs: Add get_defid helper to TypeCheckContextItem
gcc/rust/ChangeLog:

	* typecheck/rust-hir-type-check.h: Add prototype
	* typecheck/rust-typecheck-context.cc (TypeCheckContextItem::get_defid): implementation

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2023-04-26 15:02:40 +00:00
Philip Herron
b0f0ed0097 gccrs: minor refactor to reuse a variable instead of recreating it later
gcc/rust/ChangeLog:

	* typecheck/rust-hir-type-check-expr.cc: refactor

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2023-04-26 15:02:40 +00:00
Philip Herron
04fad308c6 gccrs: Fix memory corruption at peek_context
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>
2023-04-26 15:02:40 +00:00
Arthur Cohen
e70fbab606 patterns: Add execution testcases to verify proper pattern matching
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.
2023-04-25 20:58:16 +00:00
Pierre-Emmanuel Patry
68df05cf10 ci: Add libgrust to clang-format checker
Add the libgrust directory to the clang-format github action.

ChangeLog:

	* .github/workflows/clang-format.yml: Add libgrust directory.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-04-25 20:57:18 +00:00
Owen Avery
125c236e2a Resolve identifier-pattern struct pattern fields
gcc/rust/ChangeLog:

	* resolve/rust-ast-resolve-pattern.cc
	(PatternDeclaration::visit): Handle StructPatternFieldIdentPat.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-04-25 20:56:14 +00:00
Pierre-Emmanuel Patry
aa108c2164 libproc_macro: Fix literal drop function
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>
2023-04-21 14:51:32 +00:00
Pierre-Emmanuel Patry
bfc2f58e1e libproc_macro: Implement Drop for TokenStream
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>
2023-04-21 13:15:47 +00:00
Pierre-Emmanuel Patry
dc89a98af0 libproc_macro: Add remaining drop functions
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>
2023-04-21 13:15:47 +00:00
Pierre-Emmanuel Patry
ca50a4f3a6 libproc_macro: Add drop function to Literal struct
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>
2023-04-21 13:15:47 +00:00
Pierre-Emmanuel Patry
bf75c15d40 libproc_macro: Add drop function on Ident struct
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>
2023-04-21 13:15:47 +00:00
Pierre-Emmanuel Patry
4984dd59b6 libproc_macro: Add remaining tokenstream structs.
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>
2023-04-21 13:15:47 +00:00
TieWay59
67905463cb Fix translation mistakes 2023 in GCC/Rust [PR108890]
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>
2023-04-21 13:09:46 +00:00
Pierre-Emmanuel Patry
a6d4d0bbea libproc_macro: Add Punct struct
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>
2023-04-21 11:25:06 +00:00
Pierre-Emmanuel Patry
52e4af4f39 libproc_macro: Add namespace to Ident
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>
2023-04-21 09:31:24 +00:00
Pierre-Emmanuel Patry
3fb63250ea libproc_macro: Add named constructor
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>
2023-04-21 09:31:24 +00:00
Pierre-Emmanuel Patry
a3978a7591 libproc_macro: Change drop rust interface
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>
2023-04-21 09:31:24 +00:00
Pierre-Emmanuel Patry
81544c2378 libproc_macro: Add ident implementation
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>
2023-04-21 09:31:24 +00:00
M V V S Manoj Kumar
2078d8dd83 Deleted the as_string ASR and HIR dumps
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>
2023-04-21 09:26:13 +00:00
Arthur Cohen
82e26f8362 parser: Parse reference patterns correctly
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.
2023-04-21 08:47:11 +00:00
Owen Avery
428a31804b Add error message for AltPattern in let statements
gcc/rust/ChangeLog:

	* hir/rust-ast-lower-pattern.cc
	(ASTLoweringPattern::translate): Add is_let_top_level parameter.
	(ASTLoweringPattern::visit): Handle is_let_top_level.
	* hir/rust-ast-lower-pattern.h
	(class ASTLoweringPattern): Add is_let_top_level.
	* hir/rust-ast-lower-stmt.cc
	(ASTLoweringStmt::visit): Set is_let_top_level.

gcc/testsuite/ChangeLog:

	* rust/compile/let_alt.rs: New test.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-04-21 07:38:21 +00:00
Zheyuan Chen
3013c408b0 Implement Dump:visit() function for QualifiedPathInType argument.
gcc/rust/ChangeLog:

	* ast/rust-ast-dump.cc: fix bad formatting for associated type.

Signed-off-by: Zheyuan Chen <sephirotheca17@gmail.com>
2023-04-20 07:51:02 +00:00
Philip Herron
ab4931bf81 gccrs: Add testcase to show matching of enum variants
Fixes #852

gcc/testsuite/ChangeLog:

	* rust/compile/issue-852.rs: New test.

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2023-04-19 21:12:08 +00:00
Sergey Bugaev
74b4d6ddf6 gccrs: Lower ErrorPropagationExpr from AST to HIR
gcc/rust/ChangeLog:
	* hir/rust-ast-lower-expr.h, hir/rust-ast-lower-expr.cc:
	Lower AST::ErrorPropagationExpr to HIR::ErrorPropagationExpr

Signed-off-by: Sergey Bugaev <bugaevc@gmail.com>
2023-04-19 09:40:10 +00:00
Pierre-Emmanuel Patry
4f7461b1fd libproc_macro: Add member functions to Literal
Add some member functions to the Literal structure as well as named
constructors.

ChangeLog:

	* libgrust/libproc_macro/literal.cc (Literal__string): Add call
	to named constructor.
	(Literal__byte_string): Likewise.
	(Literal::make_unsigned): Add function.
	(Literal::make_signed): Add function.
	(Literal::clone): Likewise.
	(Literal::make_u8): Likewise.
	(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.
	(make_char): Likewise.
	(Literal::make_char): Likewise.
	(make_usize): Likewise.
	(Literal::make_usize): Likewise.
	(make_isize): Likewise.
	(Literal::make_isize): Likewise.
	* libgrust/libproc_macro/literal.h: Add prototypes.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-04-19 08:48:33 +00:00
Pierre-Emmanuel Patry
9b5f58352b libproc_macro: Put literal members in namespace
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>
2023-04-19 08:48:33 +00:00
Pierre-Emmanuel Patry
4d1bb3df10 libproc_macro: Drop function shall take a mutable
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>
2023-04-19 08:48:33 +00:00
Pierre-Emmanuel Patry
da0553bcbf libproc_macro: Add literal ffi implementations
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>
2023-04-19 08:48:33 +00:00
Pierre-Emmanuel Patry
50583d4283 libproc_macro: Add Literal type
Add the Literal type matching rust ffi definitions.

ChangeLog:

	* libgrust/libproc_macro/proc_macro.h (PROC_MACRO_H): Add
	literal header include directive.
	* libgrust/libproc_macro/literal.h: New file.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-04-19 08:48:33 +00:00
Pierre-Emmanuel Patry
4fc72ffbba libproc_macro: Add license headers
Add license headers to existing files.

ChangeLog:

	* libgrust/libproc_macro/proc_macro.cc (test): Remove dummy
	function.
	* libgrust/libproc_macro/proc_macro.h (test): Likewise.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-04-19 08:48:33 +00:00
Thomas Schwinge
ddde0cfaaa Merge commit 'cbe93dfa4d41d5a131b53bd3f97c973939f98ae6' into HEAD [#2130] 2023-04-18 18:42:59 +02:00
Thomas Schwinge
cbe93dfa4d Merge commit '8e08c7886eed5824bebd0e011526ec302d622844' into HEAD 2023-04-18 12:45:52 +02:00
Pierre-Emmanuel Patry
b2c44f0066 ast: Fix scope separator in tokenstreams
Qualified types had a simple colon output instead of full scope
resolution tokens in QualifiedPathInTypes.

gcc/rust/ChangeLog:

	* ast/rust-ast-tokenstream.cc (TokenStream::visit): Fix scope
	resolution token output.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-04-17 17:25:51 +00:00
Pierre-Emmanuel Patry
4f2f07943d ast: Fix tokenstream QualifiedPathInExpression
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>
2023-04-17 17:25:51 +00:00
Pierre-Emmanuel Patry
2d478a4c3e ast: Fix tokenstream function body
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>
2023-04-17 17:25:51 +00:00
Pierre-Emmanuel Patry
002bb55a10 parser: Fix attribute differentation
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>
2023-04-17 17:25:51 +00:00
Pierre-Emmanuel Patry
58a83dcdab lex: Fix lifetime string representation
Lifetime string representation used two single quotes instead of one.

gcc/rust/ChangeLog:

	* lex/rust-token.cc (Token::as_string): Fix lifetime string
	representation.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-04-17 17:25:51 +00:00
Sergey Bugaev
e7ea5fb640 resolve: Add "break rust" Easter egg
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>
2023-04-17 08:46:19 +00:00
Sergey Bugaev
3bd09533b3 resolve: Add ResolveExpr::funny_error
...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>
2023-04-17 08:46:19 +00:00
Sergey Bugaev
bfd8e24c2a ast: Add AST::Kind::IDENTIFIER
...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>
2023-04-17 08:46:19 +00:00
Sergey Bugaev
8129f20c81 ast: Make AST::Kind an enum class
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>
2023-04-17 08:46:19 +00:00
Owen Avery
8664ba4cf2 Add lowering for if-let expressions
gcc/rust/ChangeLog:

	* typecheck/rust-hir-type-check-expr.cc
	(TypeCheckExpr::visit): Add implementation for IfLetExprConseqElse.
	* typecheck/rust-hir-type-check-expr.h:
	(TypeCheckExpr::visit): Remove stub implementation for IfLetExprConseqElse.
	* hir/rust-ast-lower-expr.cc
	(ASTLoweringExpr::visit): Lower IfLetExpr{,ConseqElse}.
	* hir/rust-ast-lower-expr.h:
	(ASTLoweringExpr::visit): Likewise.
	* hir/rust-ast-lower-block.h
	(ASTLoweringIfLetBlock::visit): Lower IfLetExprConseqElse.
	(ASTLoweringExprWithBlock::visit): Likewise.
	* hir/rust-ast-lower.cc
	(ASTLoweringIfLetBlock::visit): Lower IfLetExprConseqElse.
	* hir/tree/rust-hir-expr.h
	(IfLetExprConseqElse::IfLetExprConseqElse): Make constructor more general.
	(IfLetExprConseqElse::vis_else_block): Add.
	(IfLetExprConseqElse::get_else_block): Add.
	* resolve/rust-ast-resolve-expr.cc
	(ResolveExpr::visit): Add IfLetExprConseqElse visitor.
	* resolve/rust-ast-resolve-expr.h
	(ResolveExpr::visit): Add IfLetExprConseqElse visitor.

gcc/testsuite/ChangeLog:

	* rust/compile/if_let_expr.rs: Increase test coverage.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-04-17 08:36:36 +00:00
Sebastian Kirmayer
cde6f8d9b5 parser: macro: reject separator in ? repetition
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>
2023-04-14 12:53:54 +00:00
Owen Avery
2608859a39 Unify AST::IfLetExprConseqIf{,Let} into AST::IfLetExprConseqElse
This simplifies the AST's representation of if-let-statements
to match the HIR.

gcc/rust/ChangeLog:

	* ast/rust-expr.h
	(class IfLetExprConseqElse): Make else_block ExprWithBlock.
	(class IfLetExprConseqIf): Remove.
	(class IfLetExprConseqIfLet): Remove.
	* ast/rust-ast-full-decls.h
	(class IfLetExprConseqIf): Remove.
	(class IfLetExprConseqIfLet): Remove.
	* ast/rust-ast.cc
	(IfLetExprConseqElse::as_string): Adjust output.
	(IfLetExprConseqIf::as_string): Remove.
	(IfLetExprConseqIfLet::as_string): Remove.
	(IfLetExprConseqIf::accept_vis): Remove.
	(IfLetExprConseqIfLet::accept_vis): Remove.
	* ast/rust-ast-visitor.h
	(ASTVisitor::visit): Remove IfLetExprConseqIf{,Let} visitors.
	* ast/rust-ast-dump.cc
	(Dump::visit): Likewise.
	* ast/rust-ast-dump.h:
	(Dump::visit): Likewise.
	* ast/rust-ast-tokenstream.cc
	(TokenStream::visit): Likewise.
	* ast/rust-ast-tokenstream.h
	(TokenStream::visit): Likewise.
	* util/rust-attributes.cc
	(AttributeChecker::visit): Likewise.
	* util/rust-attributes.h:
	(AttributeChecker::visit): Likewise.
	* resolve/rust-early-name-resolver.cc
	(EarlyNameResolver::visit): Likewise.
	* resolve/rust-early-name-resolver.h
	(EarlyNameResolver::visit): Likewise.
	* resolve/rust-ast-resolve-base.h
	(ResolverBase::visit): Likewise.
	* resolve/rust-ast-resolve-base.cc
	(ResolverBase::visit): Likewise.
	* checks/errors/rust-feature-gate.h
	(FeatureGate::visit): Likewise.
	* expand/rust-cfg-strip.cc
	(CfgStrip::visit): Likewise.
	* expand/rust-cfg-strip.h:
	(CfgStrip::visit): Likewise.
	* expand/rust-expand-visitor.cc
	(ExpandVisitor::visit): Likewise.
	* expand/rust-expand-visitor.h
	(ExpandVisitor::visit): Likewise.
	* hir/rust-ast-lower-base.cc
	(ASTLoweringBase::visit): Likewise.
	* hir/rust-ast-lower-base.h:
	(ASTLoweringBase::visit): Likewise.
	* parse/rust-parse-impl.h
	(Parser::parse_if_let_expr): Replace IfLetExprConseqIf{,Let} with IfLetExprConseqElse.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-04-14 12:35:57 +00:00
Pierre-Emmanuel Patry
ac79c65365 ast: Fix StructExprStruct tokenstream
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>
2023-04-14 12:34:44 +00:00
Thomas Schwinge
705de6d54c Rust: Make 'tree'-level 'MAIN_NAME_P' work
'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'.
2023-04-14 11:57:27 +02:00
Thomas Schwinge
4e95a91174 Revert "Rust: Make 'tree'-level 'MAIN_NAME_P' work"
This reverts commit 41c7e1d0a7.
2023-04-14 11:57:21 +02:00
Thomas Schwinge
41c7e1d0a7 Rust: Make 'tree'-level 'MAIN_NAME_P' work
'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'.
2023-04-14 11:57:11 +02:00
Owen Avery
37d4fa770f Handle underscore in MacroMatch.
gcc/rust/ChangeLog:

	* parse/rust-parse-impl.h
	(Parser::parse_macro_match): Handle underscore.

gcc/testsuite/ChangeLog:

	* rust/compile/macro51.rs: New test.
2023-04-14 07:35:37 +00:00
Owen Avery
47b92ff183 Fully unify deriving classes into HIR::ExprStmt
gcc/rust/ChangeLog:

	* hir/tree/rust-hir-full-decls.h
	(class ExprStmtWithoutBlock): Remove.
	(class ExprStmtWithBlock): Remove.
	* hir/tree/rust-hir-stmt.h
	(class ExprStmt):
	Add remaining ExprStmtWith{,out}Block functionality.
	(class ExprStmtWithoutBlock): Remove.
	(class ExprStmtWithBlock): Remove.
	* hir/rust-ast-lower-stmt.cc
	(ASTLoweringStmt::visit):
	Lower to HIR::ExprStmt instead of deriving class.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-04-13 11:50:47 +00:00
Owen Avery
862ec75eaf Unify HIR::ExprStmt derived class visiting
gcc/rust/ChangeLog:

	* backend/rust-compile-stmt.cc
	(CompileStmt::visit): Unify ExprStmtWith{,out}Block visitors.
	* backend/rust-compile-stmt.h
	(CompileStmt::visit): Likewise.
	* backend/rust-compile-item.h
	(CompileItem::visit): Likewise.
	* hir/rust-hir-dump.cc
	(Dump::visit): Likewise.
	* hir/rust-hir-dump.h
	(Dump::visit): Likewise.
	* hir/tree/rust-hir-stmt.h
	(ExprStmt::accept_vis): Add.
	(ExprStmtWithoutBlock::accept_vis): Remove.
	(ExprStmtWithBlock::accept_vis): Remove.
	* hir/tree/rust-hir.cc
	(ExprStmt::accept_vis): Add.
	(ExprStmtWithoutBlock::accept_vis): Remove.
	(ExprStmtWithBlock::accept_vis): Remove.
	* hir/tree/rust-hir-visitor.h
	(HIRFullVisitor::visit): Likewise.
	(HIRFullVisitorBase::visit): Likewise.
	(HIRStmtVisitor::visit): Likewise.
	* checks/errors/rust-const-checker.cc
	(ConstChecker::visit): Likewise.
	* checks/errors/rust-const-checker.h
	(ConstChecker::visit): Likewise.
	* checks/errors/rust-unsafe-checker.cc
	(UnsafeChecker::visit): Likewise.
	* checks/errors/rust-unsafe-checker.h
	(UnsafeChecker::visit): Likewise.
	* checks/errors/privacy/rust-privacy-reporter.cc
	(PrivacyReporter::visit): Likewise.
	* checks/errors/privacy/rust-privacy-reporter.h
	(PrivacyReporter::visit): Likewise.
	* checks/lints/rust-lint-marklive.h
	(MarkLive::visit): Likewise.
	* typecheck/rust-hir-type-check-stmt.cc
	(TypeCheckStmt::visit): Likewise.
	* typecheck/rust-hir-type-check-stmt.h
	(TypeCheckStmt::visit): Likewise.
	* typecheck/rust-tycheck-dump.h
	(TypeResolverDump::visit): Likewise.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-04-13 11:50:47 +00:00
Owen Avery
b0487d6731 Move method as_string into HIR::ExprStmt from deriving classes
gcc/rust/ChangeLog:

	* hir/tree/rust-hir.cc
	(ExprStmt::as_string): Add method.
	(ExprStmtWithBlock::as_string): Remove method.
	(ExprStmtWithoutBlock::as_string): Remove method.
	* hir/tree/rust-hir-stmt.h
	(ExprStmt::as_string): Add method.
	(ExprStmtWithBlock::as_string): Remove method.
	(ExprStmtWithoutBlock::as_string): Remove method.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-04-13 11:50:47 +00:00
Owen Avery
0a00ea70db Move functionality into HIR::ExprStmt from deriving classes
gcc/rust/ChangeLog:

	* hir/tree/rust-hir-stmt.h
	(ExprStmt::expr): Add field.
	(ExprStmt::get_expr): Add method.
	(ExprStmt::ExprStmt): Add copy/move constructors, modify existing constructor.
	(ExprStmt::operator=): Add assignment operator.
	(ExprStmtWithoutBlock::expr): Remove field.
	(ExprStmtWithoutBlock::get_expr): Remove method.
	(ExprStmtWithoutBlock::ExprStmt):
	Remove copy/move constructors, modify existing constructor.
	(ExprStmtWithoutBlock::operator=): Remove assignment operator.
	(ExprStmtWithBlock::expr): Remove field.
	(ExprStmtWithBlock::get_expr): Remove method.
	(ExprStmtWithBlock::ExprStmt): Remove copy/move constructors, modify existing constructor.
	(ExprStmtWithBlock::operator=): Remove assignment operator.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-04-13 11:50:47 +00:00
Owen Avery
132a5011e3 Unify AST::IfExprConseqIf{,Let} into AST::IfExprConseqElse
This simplifies the AST's representation of if-statements
to match the HIR.

gcc/rust/ChangeLog:

	* ast/rust-expr.h
	(class IfExprConseqElse): Make else_block ExprWithBlock.
	(class IfExprConseqIf): Remove.
	(class IfExprConseqIfLet): Remove.
	* ast/rust-ast-full-decls.h
	(class IfExprConseqIf): Remove.
	(class IfExprConseqIfLet): Remove.
	* ast/rust-ast.cc
	(IfExprConseqElse::as_string): Adjust output.
	(IfExprConseqIf::as_string): Remove.
	(IfExprConseqIfLet::as_string): Remove.
	(IfExprConseqIf::accept_vis): Remove.
	(IfExprConseqIfLet::accept_vis): Remove.
	* ast/rust-ast-visitor.h
	(ASTVisitor::visit): Remove IfExprConseqIf{,Let} visitors.
	* ast/rust-ast-tokenstream.cc
	(TokenStream::visit): Likewise.
	* ast/rust-ast-tokenstream.h
	(TokenStream::visit): Likewise.
	* ast/rust-ast-dump.cc
	(Dump::visit): Likewise.
	* ast/rust-ast-dump.h
	(Dump::visit): Likewise.
	* checks/errors/rust-feature-gate.h
	(FeatureGate::visit): Likewise.
	* util/rust-attributes.cc
	(AttributeChecker::visit): Likewise.
	* util/rust-attributes.h
	(AttributeChecker::visit): Likewise.
	* resolve/rust-early-name-resolver.cc
	(EarlyNameResolver::visit): Likewise.
	* resolve/rust-early-name-resolver.h
	(EarlyNameResolver::visit): Likewise.
	* resolve/rust-ast-resolve-base.h
	(ResolverBase::visit): Likewise.
	* resolve/rust-ast-resolve-base.cc
	(ResolverBase::visit): Likewise.
	* resolve/rust-ast-resolve-expr.h
	(ResolveExpr::visit): Remove IfExprConseqIf visitor.
	* resolve/rust-ast-resolve-expr.cc
	(ResolveExpr::visit): Likewise.
	* expand/rust-cfg-strip.cc
	(CfgStrip::visit): Remove IfExprConseqIf{,Let} visitors.
	* expand/rust-cfg-strip.h
	(CfgStrip::visit): Likewise.
	* expand/rust-expand-visitor.cc
	(ExpandVisitor::visit): Likewise.
	* expand/rust-expand-visitor.h
	(ExpandVisitor::visit): Likewise.
	* hir/rust-ast-lower-base.cc
	(ASTLoweringBase::visit): Likewise.
	* hir/rust-ast-lower-base.h
	(ASTLoweringBase::visit): Likewise.
	* hir/rust-ast-lower-block.h
	(ASTLoweringIfBlock::visit): Remove IfExprConseqIf visitor.
	(ASTLoweringExprWithBlock::visit): Likewise.
	* hir/rust-ast-lower.cc
	(ASTLoweringIfBlock::visit):
	Remove IfExprConseqIf visitor, adjust IfExprConseqElse lowering.
	* hir/rust-ast-lower-expr.h
	(ASTLoweringExpr::visit): Remove IfExprConseqIf visitor.
	* hir/rust-ast-lower-expr.cc
	(ASTLoweringExpr::visit): Likewise.
	* parse/rust-parse-impl.h
	(Parser::parse_if_expr): Replace IfExprConseqIf{,Let} with IfExprConseqElse.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-04-12 13:17:19 +00:00
Pierre-Emmanuel Patry
dc5f674759 ast: Fix inner attribute tokenstream
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>
2023-04-11 17:03:32 +00:00
Thomas Schwinge
626dabb43d Merge commit 'df3a80d97fe58eafcd880448b3768ca302c743f6' into HEAD [#2115] 2023-04-11 10:43:08 +02:00
Marc Poulhiès
62d48d5e4a gccrs: Introduce AST::Visitable class for AST
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>
2023-04-11 07:42:45 +00:00
Thomas Schwinge
2bc9f60374 Placate clang-format, 'gcc/rust/rust-lang.cc:grs_langhook_type_for_mode'
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.
2023-04-11 07:36:25 +00:00
Thomas Schwinge
df3a80d97f Merge upstream (dummy), "Rust front-end update 2023-04-05"
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.
2023-04-10 11:09:15 +02:00
Thomas Schwinge
3757e8d717 Merge commit '6baa95c9c5b3fea96fd22d03d961db4e4cf48d88' into HEAD [#2112] 2023-04-10 10:59:48 +02:00
Thomas Schwinge
6baa95c9c5 Adjust '.github/bors_log_expected_warnings' 2023-04-08 23:02:06 +02:00
Thomas Schwinge
b1d131f894 Merge commit '939fb3fffebf7be2638ddef25dbe1c15f2aaa9d6' into HEAD 2023-04-07 22:04:54 +02:00
Thomas Schwinge
353f5e8f00 Merge commit 'aee5ee35602e0098c2ae16fa2fc9c8845caf92ed' into HEAD
Addresses: #1713
Fixes: #1973
2023-04-07 21:56:15 +02:00
Thomas Schwinge
6ee85b3255 Merge commit 'aee5ee35602e0098c2ae16fa2fc9c8845caf92ed~1' into HEAD 2023-04-07 21:56:06 +02:00
Thomas Schwinge
3ccb746bbe Merge commit '334f23d83261997ca89d8919b94b97aa22003a65' into HEAD 2023-04-07 21:53:02 +02:00
Thomas Schwinge
58b047a8de Merge commit '320dc51c2d9969f644885cc1afa0d8a924f0ab87' into HEAD [#1540] 2023-04-07 21:50:40 +02:00
Thomas Schwinge
1dcdf61f9e Merge commit '7411eca498beb13729cc2acec77e68250940aa81' into HEAD 2023-04-07 21:44:55 +02:00
Thomas Schwinge
ec914345e9 Merge commit '7411eca498beb13729cc2acec77e68250940aa81~1' into HEAD 2023-04-07 21:43:06 +02:00
Pierre-Emmanuel Patry
e44f127cdb ast: Add difference between attributes
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>
2023-04-07 11:36:58 +00:00
Philip Herron
92b1370485 gccrs: Support fully qualified calls to trait items from CallExpr's
Fixes #2070

gcc/rust/ChangeLog:

	* backend/rust-compile-resolve-path.cc (HIRCompileBase::query_compile):
	reuse resolve_method_address to monomorphize the call if required
	* typecheck/rust-hir-type-check-path.cc (TypeCheckExpr::resolve_segments):
	allow matching against unimplemented trait item bounds

gcc/testsuite/ChangeLog:

	* rust/compile/issue-2070.rs: New test.

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2023-04-05 09:24:55 +00:00
Philip Herron
4d663acdb6 gccrs: never re-setup trait item bound with a dyn object
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>
2023-04-05 09:24:55 +00:00
Philip Herron
f83e63a89a gccrs: refactor resolve_method_address to be inside base class
gcc/rust/ChangeLog:

	* backend/rust-compile-base.cc (HIRCompileBase::resolve_method_address): moved here
	* backend/rust-compile-base.h: refactored prototype
	* backend/rust-compile-expr.cc (CompileExpr::resolve_method_address): refactor
	* backend/rust-compile-expr.h: likewise

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2023-04-05 09:24:55 +00:00
Philip Herron
4713107dff gccrs: remove unused code in query_compile
gcc/rust/ChangeLog:

	* backend/rust-compile-resolve-path.cc (HIRCompileBase::query_compile): remove unused

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2023-04-05 09:24:55 +00:00
Philip Herron
de9adfef3d gccrs: cleanup query_compile to reuse destructure call
gcc/rust/ChangeLog:

	* backend/rust-compile-resolve-path.cc (HIRCompileBase::query_compile): call destructure

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2023-04-05 09:24:55 +00:00
Philip Herron
b9fc7b51a4 gccrs: cleanup resolve method address
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>
2023-04-05 09:24:55 +00:00
Pierre-Emmanuel Patry
da41f6d8a4 expand: Add outer attribute expansion on expr
Add additional outer attribute expansion on some expressions.

gcc/rust/ChangeLog:

	* expand/rust-expand-visitor.cc (ExpandVisitor::visit): Add call
	to attribute expansion function.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-04-05 08:20:48 +00:00
Pierre-Emmanuel Patry
865f3b05ad expand: Add builtin attribute identification
Add a function to identify builtin attributes and skip those on proc
macro expansion phase.

gcc/rust/ChangeLog:

	* expand/rust-expand-visitor.cc (ExpandVisitor::visit_outer_attrs):
	Change condition order.
	(ExpandVisitor::visit_inner_using_attrs): Likewise.
	(ExpandVisitor::visit_attrs_with_derive): Likewise.
	(ExpandVisitor::is_builtin): Add builtin identification
	function.
	* expand/rust-expand-visitor.h: Add function prototype.
	* util/rust-attributes.cc: Add missing rustc_builtin_macro
	attribute.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-04-05 08:20:48 +00:00
Pierre-Emmanuel Patry
a7302b77e3 expand: Add call to outer attributes stubs
Add call to outer attribute expansion stub on required types.

gcc/rust/ChangeLog:

	* expand/rust-expand-visitor.cc (ExpandVisitor::expand_struct_fields):
	Add call to expand structu fields.
	(ExpandVisitor::expand_function_params): Add call to expand
	function parameters.
	(ExpandVisitor::expand_closure_params): Add call to expand
	closure parameters.
	(ExpandVisitor::visit): Add calls for item outer attribute
	expansions.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-04-05 08:20:48 +00:00
Pierre-Emmanuel Patry
11d6828d74 expand: Add stub function for attribute expansion
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>
2023-04-05 08:20:48 +00:00
Pierre-Emmanuel Patry
6ad6a78a4a ast: Add outer attribute getter to Expr class
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>
2023-04-05 08:20:48 +00:00
Pierre-Emmanuel Patry
fe11b51bd3 expand: Add inner attribute expansion stubs
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>
2023-04-05 08:20:48 +00:00
Pierre-Emmanuel Patry
b109e685aa expand: Add derive expansion stubs
Add derive macros expansion stub functions.

gcc/rust/ChangeLog:

	* expand/rust-expand-visitor.cc (ExpandVisitor::visit): Add call
	to derive expander.
	(ExpandVisitor::expand_derive): Expand a single derive.
	(ExpandVisitor::visit_attrs_with_derive): Visit an item with
	derive attributes.
	(ExpandVisitor::is_derive): Identify a derive attribute.
	* expand/rust-expand-visitor.h: Add function prototypes.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-04-05 08:20:48 +00:00
Pierre-Emmanuel Patry
7035cd6ba1 ast: Fix ICE on generic args path
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>
2023-04-05 08:09:09 +00:00
Pierre-Emmanuel Patry
f499a356a8 ast: Fix macros in tokenstreams
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>
2023-04-05 08:09:09 +00:00
Pierre-Emmanuel Patry
1d501ab142 ast: Visit crate inner attributes for tokenstreams
Crate level inner attributes were not visited.

gcc/rust/ChangeLog:

	* ast/rust-ast-tokenstream.cc (TokenStream::visit): Visit inner
	attributes.
2023-04-05 08:09:09 +00:00
Pierre-Emmanuel Patry
d94116ad6a ast: Change visibility in token type
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>
2023-04-05 08:09:09 +00:00
Pierre-Emmanuel Patry
4331f52f62 ast: Fix attribute tokenstreams
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>
2023-04-05 08:09:09 +00:00
Pierre-Emmanuel Patry
0b7b488405 ast: Output union's outer attributes
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>
2023-04-05 08:09:09 +00:00
Pierre-Emmanuel Patry
1a7f62cd03 ast: Output inner attributes in tokenstreams
Inner attributes were not correctly visited.

gcc/rust/ChangeLog:

	* ast/rust-ast-tokenstream.cc (TokenStream::visit): Add call to
	inner attribute visitor.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-04-05 08:09:09 +00:00
Pierre-Emmanuel Patry
68ee667852 ast: Fix char literal ICE
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>
2023-04-05 08:09:09 +00:00
Pierre-Emmanuel Patry
28f445767e ast: Fix match case comma output
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>
2023-04-05 08:09:09 +00:00
Pierre-Emmanuel Patry
75ec5f4f48 ast: Fix tokenstream extern block statements
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>
2023-04-05 08:09:09 +00:00
Pierre-Emmanuel Patry
f749a7fa0b ast: Move pattern implementation out of rust-ast
Move rust-pattern implementation out of rust-ast.cc in their own file.

gcc/rust/ChangeLog:

	* Make-lang.in: Add two new files to the list of sources.
	* ast/rust-ast-full.h: Add new ast formatting header.
	* ast/rust-ast.cc (enum indent_mode): Move formatting function
	to it's own file.
	(indent_spaces): Likewise.
	(get_string_in_delims): Likewise.
	(enum AttrMode): Likewise.
	(get_mode_dump_desc): Likewise.
	(append_attributes): Likewise.
	(unquote_string): Likewise.
	(GroupedExpr::as_string): Move pattern implementation to it's
	own file.
	(RangePattern::as_string): Likewise.
	(RangePatternBoundLiteral::as_string): Likewise.
	(SlicePattern::as_string): Likewise.
	(AltPattern::as_string): Likewise.
	(TuplePatternItemsMultiple::as_string): Likewise.
	(TuplePatternItemsRanged::as_string): Likewise.
	(TuplePattern::as_string): Likewise.
	(StructPatternField::as_string): Likewise.
	(StructPatternFieldIdent::as_string): Likewise.
	(StructPatternFieldTuplePat::as_string): Likewise.
	(StructPatternFieldIdentPat::as_string): Likewise.
	(StructPatternElements::as_string): Likewise.
	(StructPattern::as_string): Likewise.
	(LiteralPattern::as_string): Likewise.
	(ReferencePattern::as_string): Likewise.
	(IdentifierPattern::as_string): Likewise.
	(TupleStructItemsNoRange::as_string): Likewise.
	(TupleStructItemsRange::as_string): Likewise.
	(TupleStructPattern::as_string): Likewise.
	(GroupedExpr::accept_vis): Likewise.
	(LiteralPattern::accept_vis): Likewise.
	(IdentifierPattern::accept_vis): Likewise.
	(WildcardPattern::accept_vis): Likewise.
	(RestPattern::accept_vis): Likewise.
	(RangePatternBoundLiteral::accept_vis): Likewise.
	(RangePatternBoundPath::accept_vis): Likewise.
	(RangePatternBoundQualPath::accept_vis): Likewise.
	(RangePattern::accept_vis): Likewise.
	(ReferencePattern::accept_vis): Likewise.
	(StructPatternFieldTuplePat::accept_vis): Likewise.
	(StructPatternFieldIdentPat::accept_vis): Likewise.
	(StructPatternFieldIdent::accept_vis): Likewise.
	(StructPattern::accept_vis): Likewise.
	(TupleStructItemsNoRange::accept_vis): Likewise.
	(TupleStructItemsRange::accept_vis): Likewise.
	(TupleStructPattern::accept_vis): Likewise.
	(TuplePatternItemsMultiple::accept_vis): Likewise.
	(TuplePatternItemsRanged::accept_vis): Likewise.
	(TuplePattern::accept_vis): Likewise.
	(GroupedPattern::accept_vis): Likewise.
	(SlicePattern::accept_vis): Likewise.
	(AltPattern::accept_vis): Likewise.
	* ast/rust-ast-formatting.cc: New file.
	* ast/rust-ast-formatting.h: New file.
	* ast/rust-pattern.cc: New file.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-04-04 12:05:02 +00:00
Pierre-Emmanuel Patry
8b017829f1 ast: Move rust-path implementation out of rust-ast
Move rust-path implementation details out of rust-ast.cc file. This will
hopefully decrease compile time and make things clearer.

gcc/rust/ChangeLog:

	* Make-lang.in: Add new file for rust-path implementation.
	* ast/rust-ast.cc (PathInExpression::as_string): Move function
	to the new file.
	(PathPattern::as_string): Likewise.
	(QualifiedPathInExpression::as_string): Likewise.
	(ConstGenericParam::as_string): Likewise.
	(QualifiedPathInType::as_string): Likewise.
	(TypePath::as_string): Likewise.
	(PathPattern::convert_to_simple_path): Likewise.
	(TypePath::as_simple_path): Likewise.
	(PathExprSegment::as_string): Likewise.
	(GenericArgs::as_string): Likewise.
	(GenericArgsBinding::as_string): Likewise.
	(TypePath::to_trait_bound): Likewise.
	(TypePathSegmentGeneric::as_string): Likewise.
	(TypePathFunction::as_string): Likewise.
	(TypePathSegmentFunction::as_string): Likewise.
	(ConstGenericParam::accept_vis): Likewise.
	(PathInExpression::accept_vis): Likewise.
	(TypePathSegment::accept_vis): Likewise.
	(TypePathSegmentGeneric::accept_vis): Likewise.
	(TypePathSegmentFunction::accept_vis): Likewise.
	(TypePath::accept_vis): Likewise.
	(QualifiedPathInExpression::accept_vis): Likewise.
	(QualifiedPathInType::accept_vis): Likewise.
	(GenericArg::disambiguate_to_const): Likewise.
	(GenericArg::disambiguate_to_type): Likewise.
	* ast/rust-path.cc: New file.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-04-04 12:05:02 +00:00
Philip Herron
b99448f4b0 gccrs: Fix ICE using constructors for intilizers in statics
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>
2023-04-04 11:54:57 +00:00
Owen Avery
011eb78b35 Handle "fn" and "fn_mut" lang items
gcc/rust/ChangeLog:

	* util/rust-lang-item.h
	(RustLangItem::ItemType::FN): Add.
	(RustLangItem::ItemType::FN_MUT): Add.
	(RustLangItem::Parse): Handle FN and FN_MUT.
	(RustLangItem::ToString): Handle FN and FN_MUT.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-04-04 09:43:48 +00:00
Emanuele Micheletti
f990f89e90 gccrs: Fix bad cast as a char
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>
2023-04-02 21:08:56 +00:00
Philip Herron
1ef3947943 gccrs: Fix handling of generic arguments for lifetimes only
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>
2023-03-30 16:52:24 +00:00
Philip Herron
3cc5c9360c gccrs: add missing name resolution to self params with specified types
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>
2023-03-30 16:52:24 +00:00
Philip Herron
efc3154162 gccrs: make distinction between error and empty for substution args
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>
2023-03-30 16:52:24 +00:00
Philip Herron
441c1d06b9 gccrs: privacy reporter should be permissive of error types
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
2023-03-30 16:52:24 +00:00
Pierre-Emmanuel Patry
832812bb9c ast: Fix various TokenStream visitors
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>
2023-03-30 16:48:28 +02:00
Pierre-Emmanuel Patry
816ed80ab7 token: Add type hints to string dump
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>
2023-03-30 16:48:28 +02:00
Pierre-Emmanuel Patry
848bd4dfeb session: Add tokenstream dump option
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>
2023-03-30 16:48:28 +02:00
Pierre-Emmanuel Patry
c3a62ea7d7 lex: Add source code token string representation
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>
2023-03-30 16:48:28 +02:00
Pierre-Emmanuel Patry
a05f114acf ast: Add missing constructor implementation
Add a missing constructor implementation for TokenStream objects.

gcc/rust/ChangeLog:

	* ast/rust-ast-tokenstream.cc (TokenStream::TokenStream): Add
	constructor.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-03-30 16:48:27 +02:00
Pierre-Emmanuel Patry
1bc503fe37 ast: Add TokenStream collect function
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>
2023-03-30 16:48:27 +02:00
Pierre-Emmanuel Patry
ea248799f7 ast: Refactor SimplePath attribute name
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>
2023-03-30 16:48:27 +02:00
Pierre-Emmanuel Patry
f580c1f44c ast: Add multiple formatting stub functions
Add multiple stub functions depending on the context. This will allow an
easier unification of ast dump.

gcc/rust/ChangeLog:

	* ast/rust-ast-tokenstream.cc (TokenStream::visit_as_line): Add
	formatting calls.
	(TokenStream::visit_items_as_block): Likewise.
	(TokenStream::newline): Add stub.
	(TokenStream::indentation): Add stub.
	(TokenStream::increment_indentation): Add stub.
	(TokenStream::decrement_indentation): Add stub.
	(TokenStream::visit): Add formatting calls.
	(TokenStream::visit_function_common): Likewise.
	* ast/rust-ast-tokenstream.h: Add stub prototypes.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-03-30 16:48:27 +02:00
Pierre-Emmanuel Patry
08c2c0e02b ast: Add AltPattern TokenStream visitor
Add TokenStream visitor implementation for AltPattern.

gcc/rust/ChangeLog:

	* ast/rust-ast-tokenstream.cc (TokenStream::visit): Add visitor.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-03-30 16:48:27 +02:00
Pierre-Emmanuel Patry
cc5d198e6c ast: Add Meta items TokenStream visitor
Add visitor implementation for all remaining meta items.

gcc/rust/ChangeLog:

	* ast/rust-ast-tokenstream.cc (TokenStream::visit): Add visitor
	implementation.
	* ast/rust-ast-tokenstream.h: Add additional function prototype.
	* ast/rust-item.h: Add some getters.
	* ast/rust-macro.h: Likewise.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-03-30 16:48:27 +02:00
Pierre-Emmanuel Patry
3d9dbf5c00 ast: Add use declarations TokenStream visitors
Add UseDeclaration (and it's childrens) visitor implementation.

gcc/rust/ChangeLog:

	* ast/rust-ast-tokenstream.cc (TokenStream::visit): Add visitor.
	* ast/rust-item.h: Add missing getters.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-03-30 16:48:27 +02:00
Pierre-Emmanuel Patry
c34e05d01c ast: Add ExternCrate TokenStream visitor
Add a visitor implementation for ExternCrate declarations.

gcc/rust/ChangeLog:

	* ast/rust-ast-tokenstream.cc (TokenStream::visit): Add visitor.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-03-30 16:48:27 +02:00
Pierre-Emmanuel Patry
2ca2aaeae0 ast: Implement remaining expr TokenStream visitor
Implement the missing expression functions visitors for TokenStream.

gcc/rust/ChangeLog:

	* ast/rust-ast-tokenstream.cc (TokenStream::visit): Add
	visitors.
	(TokenStream::visit_closure_common): Merge common code for
	closure visitors.
	* ast/rust-ast-tokenstream.h: Add function prototype.
	* ast/rust-expr.h: Add missing move attribute getter.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-03-30 16:48:27 +02:00
Pierre-Emmanuel Patry
bea0c13139 ast: Add Tokenstream visitors for loop expressions
Add the implementation of tokenstream dump for multiple loop
expressions.

gcc/rust/ChangeLog:

	* ast/rust-ast-tokenstream.cc (TokenStream::visit): Add
	visitors.
	(TokenStream::visit_loop_common): Merge common loop code.
	* ast/rust-ast-tokenstream.h: Add function prototypes.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-03-30 16:48:26 +02:00
Pierre-Emmanuel Patry
f9fcd37d05 ast: Add some expr TokenStream visitors
Implement some TokenStream expression visitor functions.

gcc/rust/ChangeLog:

	* ast/rust-ast-tokenstream.cc (TokenStream::visit): Implement
	visitor.
	* ast/rust-ast-tokenstream.h: Add function prototype for missing
	component.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-03-30 16:48:26 +02:00
Pierre-Emmanuel Patry
439c05ae3a ast: Add trailing comma formatting option
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>
2023-03-30 16:48:26 +02:00
Pierre-Emmanuel Patry
f0ed95a8b9 ast: Implement TokenStream visitor for meta nodes
Implement TokenStream visitor on some Meta container nodes.

gcc/rust/ChangeLog:

	* ast/rust-ast-tokenstream.cc (TokenStream::visit): Implement
	visitors.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-03-30 16:48:26 +02:00
Pierre-Emmanuel Patry
028f85abf7 ast: Refactor and add some Path node visitors
Implement some functions for Path nodes and refactor existing ones by
merging some common code.

gcc/rust/ChangeLog:

	* ast/rust-ast-tokenstream.cc (TokenStream::visit): Implement
	visitors.
	* ast/rust-ast-tokenstream.h: Add function prototypes.
	* ast/rust-ast.h: Add missing getters.
	* ast/rust-expr.h: Likewise.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-03-30 16:48:26 +02:00
Pierre-Emmanuel Patry
cf6c77494c ast: Add conversion to token stream
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>
2023-03-30 16:48:26 +02:00
Philip Herron
98735d4fe7 gccrs: handle bare function types with no specified return type
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>
2023-03-30 15:17:53 +01:00
Philip Herron
ea9ae40440 gccrs: Add test to show multiple candidates for methods is working
Fixes #925

gcc/testsuite/ChangeLog:

	* rust/compile/issue-925.rs: New test.

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2023-03-30 14:44:06 +01:00
Philip Herron
7851d38445 gccrs: Add missing known attribute stable
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>
2023-03-30 14:43:48 +01:00
Philip Herron
5055bd8939 gccrs: move missed testcase
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>
2023-03-30 14:43:24 +01:00
Philip Herron
bb035c384a gccrs: fix ICE with bad match arm type
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>
2023-03-30 14:43:04 +01:00
Pierre-Emmanuel Patry
649833b71a libproc_macro: Move rust interface directory
Move libproc_macro's interface to it's final directory.

ChangeLog:

	* librust/proc_macro/rust/bridge.rs: Moved to...
	* libgrust/libproc_macro/rust/bridge.rs: ...here.
	* librust/proc_macro/rust/bridge/group.rs: Moved to...
	* libgrust/libproc_macro/rust/bridge/group.rs: ...here.
	* librust/proc_macro/rust/bridge/ident.rs: Moved to...
	* libgrust/libproc_macro/rust/bridge/ident.rs: ...here.
	* librust/proc_macro/rust/bridge/literal.rs: Moved to...
	* libgrust/libproc_macro/rust/bridge/literal.rs: ...here.
	* librust/proc_macro/rust/bridge/punct.rs: Moved to...
	* libgrust/libproc_macro/rust/bridge/punct.rs: ...here.
	* librust/proc_macro/rust/bridge/span.rs: Moved to...
	* libgrust/libproc_macro/rust/bridge/span.rs: ...here.
	* librust/proc_macro/rust/bridge/token_stream.rs: Moved to...
	* libgrust/libproc_macro/rust/bridge/token_stream.rs: ...here.
	* librust/proc_macro/rust/group.rs: Moved to...
	* libgrust/libproc_macro/rust/group.rs: ...here.
	* librust/proc_macro/rust/ident.rs: Moved to...
	* libgrust/libproc_macro/rust/ident.rs: ...here.
	* librust/proc_macro/rust/lib.rs: Moved to...
	* libgrust/libproc_macro/rust/lib.rs: ...here.
	* librust/proc_macro/rust/literal.rs: Moved to...
	* libgrust/libproc_macro/rust/literal.rs: ...here.
	* librust/proc_macro/rust/punct.rs: Moved to...
	* libgrust/libproc_macro/rust/punct.rs: ...here.
	* librust/proc_macro/rust/span.rs: Moved to...
	* libgrust/libproc_macro/rust/span.rs: ...here.
	* librust/proc_macro/rust/token_stream.rs: Moved to...
	* libgrust/libproc_macro/rust/token_stream.rs: ...here.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-03-30 13:52:32 +02:00
Pierre-Emmanuel Patry
36ead3c1b5 libproc_macro: Change string format
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>
2023-03-30 13:52:32 +02:00
Pierre-Emmanuel Patry
09b2be2439 libproc_macro: Minor refactor
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>
2023-03-30 13:52:32 +02:00
Pierre-Emmanuel Patry
77216f03f2 libproc_macro: Custom Clone on TokenStream
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>
2023-03-30 13:52:32 +02:00
Pierre-Emmanuel Patry
da81fa1f08 libproc_macro: Manual Clone for Literal
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>
2023-03-30 13:52:32 +02:00
Pierre-Emmanuel Patry
acf5db7152 libproc_macro: Custom Clone for Ident
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>
2023-03-30 13:52:32 +02:00
Pierre-Emmanuel Patry
0f1723455c libproc_macro: Add string length to ffi
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>
2023-03-30 13:52:32 +02:00
Pierre-Emmanuel Patry
3954270ee7 libproc_macro: Implement FromStr for TokenStream
Implement FromStr for TokenStream rust interface type.

ChangeLog:

	* librust/proc_macro/rust/bridge/token_stream.rs: Add FromStr
	implementation on internal type.
	* librust/proc_macro/rust/lib.rs: Implement FromStr.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-03-30 13:52:32 +02:00
Pierre-Emmanuel Patry
eeda932733 libproc_macro: Implement FromStr on Literal
Implement FromStr trait on external Literal rust type.

ChangeLog:

	* librust/proc_macro/rust/literal.rs: Implement FromStr.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-03-30 13:52:32 +02:00
Pierre-Emmanuel Patry
252f019e6c libproc_macro: Implement FromStr on bridge Literal
Implement the trait FromStr on the internal rust Literal type.

ChangeLog:

	* librust/proc_macro/rust/bridge/literal.rs: Implement FromStr.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-03-30 13:52:32 +02:00
Pierre-Emmanuel Patry
834f942532 libproc_macro: Add ffi safe i128 & u128
Add ffi safe representation for i128 and u128 types in Literal rust
interface type.

ChangeLog:

	* librust/proc_macro/rust/bridge/literal.rs: Add i128 and u128.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-03-30 13:52:32 +02:00
Pierre-Emmanuel Patry
9eaf139ee7 libproc_macro: Add Group implementation
Add Group rust structure implementation in libproc_macro.

ChangeLog:

	* librust/proc_macro/rust/bridge/group.rs: Add internal Group
	implementation.
	* librust/proc_macro/rust/group.rs: Add Group implementation.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-03-30 13:52:31 +02:00
Pierre-Emmanuel Patry
1364b17a02 libproc_macro: Implement Debug for Group
Implement the Debug trait for the rust Group external structure.

ChangeLog:

	* librust/proc_macro/rust/bridge/group.rs: Derive Debug.
	* librust/proc_macro/rust/group.rs: Implement Debug.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-03-30 13:52:31 +02:00
Pierre-Emmanuel Patry
8901323c39 libproc_macro: Implement Display for Group
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>
2023-03-30 13:52:31 +02:00
Pierre-Emmanuel Patry
048f24069e libproc_macro: Add Display impl for Punct
Add Display trait implementation for external rust structure Punct.
ChangeLog:

	* librust/proc_macro/rust/punct.rs: Add Display implementation.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-03-30 13:52:31 +02:00
Pierre-Emmanuel Patry
82c0c5c5d9 libproc_macro: Implement Display on Literal
Implement the Display trait on external rust structure Literal.

ChangeLog:

	* librust/proc_macro/rust/literal.rs: Implement Display trait.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-03-30 13:52:31 +02:00
Pierre-Emmanuel Patry
30fc7d9cf5 libproc_macro: Implement Debug on Literal
Implement the Debug trait on Literal external rust structure.

ChangeLog:

	* librust/proc_macro/rust/bridge/literal.rs: Derive Debug on
	inner types.
	* librust/proc_macro/rust/literal.rs: Implement Debug.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-03-30 13:52:31 +02:00
Pierre-Emmanuel Patry
ae2da395d3 libproc_macro: Add Debug impl for TokenStream
Add the Debug trait implementation for the TokenStream external rust
structure.

ChangeLog:

	* librust/proc_macro/rust/bridge/token_stream.rs: Add derive.
	* librust/proc_macro/rust/lib.rs: Add TokenStream debug
	implementation.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-03-30 13:52:31 +02:00
Pierre-Emmanuel Patry
3762177c58 libproc_macro: Implement Display for TokenStream
Implement the Display trait for the external rust structure TokenStream.

ChangeLog:

	* librust/proc_macro/rust/bridge/token_stream.rs: Add internal
	TokenStream Display implementation.
	* librust/proc_macro/rust/lib.rs: Add external Display
	implementation for TokenStream.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-03-30 13:52:31 +02:00
Pierre-Emmanuel Patry
453a246bb4 libproc_macro: Implement Display for Literal
Implement the Display trait on rust internal Literal structure.

ChangeLog:

	* librust/proc_macro/rust/bridge/literal.rs: Implement Display.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-03-30 13:52:31 +02:00
Pierre-Emmanuel Patry
541c0f009c libproc_macro: Implement Display for Punct
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>
2023-03-30 13:52:31 +02:00
Pierre-Emmanuel Patry
fa88446bd5 libproc_macro: Implement Display for Group
Implement the Display trait on internal rust Group structure.

ChangeLog:

	* librust/proc_macro/rust/bridge/group.rs: Implement Display.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-03-30 13:52:31 +02:00
Pierre-Emmanuel Patry
b74ef5aca0 libproc_macro: Implement Display for LexError
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>
2023-03-30 13:52:30 +02:00
Pierre-Emmanuel Patry
09c75e3750 libproc_macro: Implement Extend for TokenStream
Implement extension from TokenTree and TokenStream iterators on
TokenStream rust type.

ChangeLog:

	* librust/proc_macro/rust/bridge/token_stream.rs: Add internal
	implementation for TokenStream extension.
	* librust/proc_macro/rust/lib.rs: Add call to internal.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-03-30 13:52:30 +02:00
Pierre-Emmanuel Patry
f84d6127fe libproc_macro: Implement FromIterator
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>
2023-03-30 13:52:30 +02:00
Pierre-Emmanuel Patry
e4cd0d726e libproc_macro: Add TokenStream implementation
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>
2023-03-30 13:52:30 +02:00
Pierre-Emmanuel Patry
eedfefb49d libproc_macro: Add is_available ffi
Add ffi call for is_available function.

ChangeLog:

	* librust/proc_macro/rust/bridge.rs: Add internal
	implementation.
	* librust/proc_macro/rust/lib.rs: Add call to internal
	implementation.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-03-30 13:52:30 +02:00
Pierre-Emmanuel Patry
dc4f537942 libproc_macro: Add TokenTree implementation
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>
2023-03-30 13:52:30 +02:00
Pierre-Emmanuel Patry
896533bfff libproc_macro: Change Punct internal size type
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>
2023-03-30 13:52:30 +02:00
Pierre-Emmanuel Patry
20578ae774 libproc_macro: Add literal internal implementation
Add internal implementation for the rust Literal type in libproc_macro
rust interface.

ChangeLog:

	* librust/proc_macro/rust/bridge.rs: Add internal literal
	module.
	* librust/proc_macro/rust/literal.rs: Add link to internal
	implementation.
	* librust/proc_macro/rust/bridge/literal.rs: Add internal
	implementation.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-03-30 13:52:30 +02:00
Pierre-Emmanuel Patry
6a12e6ea0e libproc_macro: Make internal Punct type ffi safe
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>
2023-03-30 13:52:30 +02:00
Pierre-Emmanuel Patry
e41c961955 libproc_macro: Make Ident ffi-safe
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>
2023-03-30 13:52:30 +02:00
Pierre-Emmanuel Patry
905cf7298d libproc_macro: Add Punct rust type implementation
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>
2023-03-30 13:52:30 +02:00
Pierre-Emmanuel Patry
95016480c6 libproc_macro: Add Ident type implementation
Add the Ident rust type internal implementation.
ChangeLog:

	* librust/proc_macro/rust/bridge.rs: Add ident internal module.
	* librust/proc_macro/rust/ident.rs: Add ident internals.
	* librust/proc_macro/rust/span.rs: Make internal field public.
	* librust/proc_macro/rust/bridge/ident.rs: Add internal Ident
	type.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-03-30 13:52:30 +02:00
Pierre-Emmanuel Patry
ddd0c450bc libproc_macro: Add Span rust implementation
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>
2023-03-30 13:52:29 +02:00
Pierre-Emmanuel Patry
2e39012125 libproc_macro: Add iterator impl to TokenStream
Add iterator impl functions to the TokenStream rust interface in
libproc_macro.

ChangeLog:

	* librust/proc_macro/rust/lib.rs: Add iterators.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-03-30 13:52:29 +02:00
Pierre-Emmanuel Patry
553ffc7464 libproc_macro: Add token_stream module interface
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>
2023-03-30 13:52:29 +02:00
Pierre-Emmanuel Patry
f9ff02ad6f libproc_macro: Add is_available interface
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>
2023-03-30 13:52:29 +02:00
Pierre-Emmanuel Patry
fc8a92c487 libproc_macro: Add TokenTree type interface
Add TokenTree rust type interface to libproc_macro.

ChangeLog:

	* librust/proc_macro/rust/lib.rs: Add TokenTree type.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-03-30 13:52:29 +02:00
Pierre-Emmanuel Patry
e59c6f19aa libproc_macro: Move Delimiter type to group module
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>
2023-03-30 13:52:29 +02:00
Pierre-Emmanuel Patry
44a0fd574f libproc_macro: Add Group type interface
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>
2023-03-30 13:52:29 +02:00
Pierre-Emmanuel Patry
5640374631 libproc_macro: Add TokenStream type interface
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>
2023-03-30 13:52:29 +02:00
Pierre-Emmanuel Patry
a4b7fca1ec libproc_macro: Add documentation to interface
Add some string documentation to existing rust type interface.

ChangeLog:

	* librust/proc_macro/rust/ident.rs: Add documentation.
	* librust/proc_macro/rust/lib.rs: Add documentation.
	* librust/proc_macro/rust/literal.rs: Add documentation.
	* librust/proc_macro/rust/span.rs: Add documentation.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-03-30 13:52:29 +02:00
Pierre-Emmanuel Patry
08ccfe9c65 libproc_macro: Move Spacing type to punct module
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>
2023-03-30 13:52:29 +02:00
Pierre-Emmanuel Patry
f7152d606c libproc_macro: Add punct type interface
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>
2023-03-30 13:52:28 +02:00
Pierre-Emmanuel Patry
570094e524 libproc_macro: Move some types to their own module
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>
2023-03-30 13:52:28 +02:00
Pierre-Emmanuel Patry
b42b30da3e libproc_macro: Add Spacing type interface.
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>
2023-03-30 13:52:28 +02:00
Pierre-Emmanuel Patry
0b6b3851de libproc_macro: Add Literal type interface
Add Literal type rust interface to libproc_macro.

ChangeLog:

	* librust/proc_macro/rust/lib.rs: Add Literal.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-03-30 13:52:28 +02:00
Pierre-Emmanuel Patry
4f6d36157d libproc_macro: Add LexError type interface
Add LexError type rust interface in libproc_macro.

ChangeLog:

	* librust/proc_macro/rust/lib.rs: Add LexError.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-03-30 13:52:28 +02:00
Pierre-Emmanuel Patry
400e08b2da libproc_macro: Add Ident type interface
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>
2023-03-30 13:52:28 +02:00
Pierre-Emmanuel Patry
4f16aff137 libproc_macro: Add Span type rust interface
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>
2023-03-30 13:52:28 +02:00
Pierre-Emmanuel Patry
df33f7b5bb libproc_macro: Add Delimiter type interface
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>
2023-03-30 13:52:28 +02:00
Philip Herron
89d83fd0e8 gccrs: fix ICE when closure body is not a block
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>
2023-03-30 08:40:17 +00:00
Owen Avery
0ddec9f44d Fix parsing of array expressions.
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>
2023-03-29 21:17:35 +00:00
Arthur Cohen
87a0a8f84f docker: Do not run update-alternatives on invalid path
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>
2023-03-29 21:16:30 +00:00
Arthur Cohen
70b889b90a privacy: Check for pub(crate) when resolving visibility path.
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.
2023-03-29 21:14:15 +00:00
Arthur Cohen
ff4d4570b4 resolver: Allow SimplePath to resolve to their root segment
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.
2023-03-29 21:14:15 +00:00
Arthur Cohen
9af9a69367 ast: Fix location for pub(crate)
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
2023-03-29 21:14:15 +00:00
Arthur Cohen
649af3ed28 ast: Refactor rust-ast-lower-type.h to source file
gcc/rust/ChangeLog:

	* hir/rust-ast-lower-type.h: Move all remaining definitions to source file.
	* hir/rust-ast-lower-type.cc (ASTLoweringType::translate): Moved to source file.
	(ASTLoweringType::visit): Likewise.
	(ASTLowerGenericParam::translate): Likewise.
	(ASTLowerGenericParam::visit): Likewise.
	(ASTLoweringTypeBounds::translate): Likewise.
	(ASTLoweringTypeBounds::visit): Likewise.
	(ASTLowerWhereClauseItem::translate): Likewise.
	(ASTLowerWhereClauseItem::visit): Likewise.
2023-03-29 21:13:53 +00:00
Owen Avery
5148f044c6 Remove commented out TuplePatternItemsSingle
gcc/rust/ChangeLog:

	* ast/rust-pattern.h: Remove commented out code.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-03-29 21:13:35 +00:00
emanuele-em
c5427467ab gccrs: Fix bad cast error to bool
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>
2023-03-29 21:11:43 +00:00
Arthur Cohen
3eb5dcb67c expand: Rename AttrVisitor -> CfgStrip
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.
2023-03-25 08:47:56 +00:00
Arthur Cohen
267d80f146 expand: Add new ExpandVisitor class
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.
2023-03-25 08:47:56 +00:00
Arthur Cohen
e10e882ddf expand: Move cfg-attrs related functions out of MacroExpander
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.
2023-03-25 08:47:56 +00:00
Arthur Cohen
2b52571e8a lowering: Add lowering of exported macros
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.
2023-03-25 08:47:34 +00:00
Arthur Cohen
a3e7bde5b0 mappings: Keep exported macro IDs
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.
2023-03-25 08:47:34 +00:00
Arthur Cohen
7b14e6eecb Revert "hir: Add ExportedMacro node and handling."
This reverts commit a1f940d193. It is easier
and cleaner to store exported macros' NodeIds into our mappings rather than
create a new HIR kind of node.

gcc/rust/ChangeLog:

	* backend/rust-compile-item.h: Revert 1c946687239b86a92839d57dfbc928ad7ce35eae.
	* 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-full-decls.h (class ExportedMacro): Likewise.
	* hir/tree/rust-hir-item.h (class ExportedMacro): Likewise.
	* hir/tree/rust-hir-visitor.h: Likewise.
	* hir/tree/rust-hir.cc (ExportedMacro::accept_vis): Likewise.
	(ExportedMacro::get_locus): Likewise.
	(ExportedMacro::get_item_kind): Likewise.
	(ExportedMacro::clone_item_impl): Likewise.
	* hir/tree/rust-hir.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.
	* util/rust-attributes.cc: Likewise.
2023-03-25 08:47:34 +00:00
Philip Herron
03bce1d084 gccrs: Fix ICE on parsing trait object missing dyn keyword
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>
2023-03-24 23:23:18 +00:00
Philip Herron
c6c02b9135 gccrs: Fix bad type inference
gcc/rust/ChangeLog:

	* typecheck/rust-hir-trait-resolve.cc: don't inject extra inference variables

gcc/testsuite/ChangeLog:

	* rust/compile/issue-1893.rs: New test.

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2023-03-24 15:31:03 +00:00
Marc Poulhiès
7d38d01886 ci: check Signed-off-by lines (and others) are at the end
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>
2023-03-23 07:55:37 +00:00
Arthur Cohen
b623cb99ac ast: Dump each MacroRule properly without the extra semicolon
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.
2023-03-21 21:57:33 +00:00
Arthur Cohen
43d1fc6c8f rust-imports: Fix last few mentions of Go.
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.
2023-03-21 21:57:02 +00:00
Owen Avery
9024d99f5b Lower AltPattern
gcc/rust/ChangeLog:

	* hir/rust-ast-lower-pattern.cc
	(ASTLoweringPattern::visit): Lower AltPattern.
	* hir/rust-ast-lower-pattern.h:
	(ASTLoweringPattern::visit): Add AltPattern visitor.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-03-21 09:10:37 +00:00
Xiao Ma
4f76aad18b Fix FeatureGate::gate will crash on 32-bit x86.
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>
2023-03-20 22:16:00 +00:00
Philip Herron
a8662e89f8 gccrs: support use declaration to write the type into the correct namespace
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>
2023-03-20 21:47:57 +00:00
Philip Herron
70b83a23f5 gccrs: Return resolved_node_id when possible
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>
2023-03-20 21:47:57 +00:00
Mahmoud Mohamed
1eba43033b Add name resolution and ast lowering for slice pattern
gcc/rust/ChangeLog:

	* hir/rust-ast-lower-pattern.cc (ASTLoweringPattern::visit):
	Add lowering for SlicePattern.
	* hir/rust-ast-lower-pattern.h: Likewise.
	* resolve/rust-ast-resolve-pattern.cc (PatternDeclaration::visit):
	Add name resolution visit for SlicePattern.
	* resolve/rust-ast-resolve-pattern.h: Likewise.

Signed-off-by: Mahmoud Mohamed <mahadelr19@gmail.com>
2023-03-20 21:07:17 +00:00
Philip Herron
a505e2913b gccrs: Cleanup unused headers
gcc/rust/ChangeLog:

	* hir/rust-ast-lower-implitem.h (RUST_AST_LOWER_IMPLITEM_H): cleanup header usage
	* hir/rust-ast-lower-item.cc: likewise
	* hir/rust-ast-lower-item.h (RUST_AST_LOWER_ITEM): likewise
	* hir/rust-ast-lower-stmt.cc: likewise
	* hir/rust-ast-lower-stmt.h (RUST_AST_LOWER_STMT): likewise
	* hir/rust-ast-lower-type.h: likewise
	* hir/rust-ast-lower.cc: likewise
	* hir/rust-ast-lower.h: likewise
	* resolve/rust-ast-resolve-expr.h: likewise
	* resolve/rust-ast-resolve-item.cc: likewise
	* resolve/rust-ast-resolve-item.h: likewise
	* resolve/rust-ast-resolve-stmt.cc: likewise
	* resolve/rust-ast-resolve-stmt.h: likewise
	* resolve/rust-ast-resolve-struct-expr-field.h: likewise
	* resolve/rust-ast-resolve-toplevel.h: likewise
	* resolve/rust-ast-resolve-type.h: likewise
	* resolve/rust-ast-resolve.h: likewise

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2023-03-20 19:58:19 +00:00
Arthur Cohen
99d89fda0b ci: Do not run check-gccrs-prefix on PRs to master
ChangeLog:

	* .github/workflows/commit-format.yml: Skip job on PRs to master.
2023-03-20 14:06:22 +00:00
Mahmoud Mohamed
09bdaafaf2 Remove unused ResolvePattern visitor
gcc/rust/ChangeLog:

	* resolve/rust-ast-resolve-pattern.h (class ResolvePattern): Removed.
2023-03-20 11:07:05 +00:00
Philip Herron
6b77eb316c gccrs: Add move_val_init intrinsic
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>
2023-03-18 00:15:08 +00:00
Philip Herron
858fd17fcf gccrs: Fix bad method resolution
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>
2023-03-18 00:15:08 +00:00
Philip Herron
5751556c9e gccrs: add new apply_primtiive_type_hint to inference variables
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>
2023-03-18 00:15:08 +00:00
Jiakun Fan
be27571c11 Feat: add visit (AST::Attribute &)
gcc/rust/ChangeLog:

	* hir/rust-hir-dump.cc (Dump::go): fix format
	(Dump::visit):impl `visit (AST::Attribute &)`
	and `visit (Lifetime &)`
	* hir/rust-hir-dump.h:add `visit (AST::Attribute &)`

Signed-off-by: Jiakun Fan <120090316@link.cuhk.edu.cn>
2023-03-17 16:38:54 +00:00
Jiakun Fan
04b04f7a03 Dump inner attrs for Dump::visit(BlockExpr &)
Refer to `BlockExpr::as_string ()`, dump inner attrs for `Dump::vist`

gcc/rust/ChangeLog:

	* hir/rust-hir-dump.cc (Dump::visit):
	dump inner attrs

Signed-off-by: Jiakun Fan <120090316@link.cuhk.edu.cn>
2023-03-17 16:38:54 +00:00
Mahmoud Mohamed
47a7a4d646 resolve: Add name resolution for AltPattern
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>
2023-03-17 16:37:37 +00:00
Owen Avery
428bd07637 Unify HIR::IfLetExprConseqIf{,Let} into HIR::IfLetExprConseqElse
This should allow for 'if let' expressions to be lowered more easily.

gcc/rust/ChangeLog:

	* backend/rust-compile-block.h
	(CompileConditionalBlocks::visit): Remove IfLetExprConseqIf{,Let} visitors.
	(CompileExprWithBlock::visit): Remove IfLetExprConseqIf{,Let} visitors.
	* backend/rust-compile-expr.h
	(CompileExpr::visit): Remove IfLetExprConseqIf{,Let} visitors.
	* checks/errors/rust-unsafe-checker.cc
	(UnsafeChecker::visit): Remove IfLetExprConseqIf{,Let} visitors.
	* checks/errors/rust-unsafe-checker.h
	(UnsafeChecker::visit): Remove IfLetExprConseqIf{,Let} visitors.
	* checks/errors/rust-const-checker.cc
	(ConstChecker::visit): Remove IfLetExprConseqIf{,Let} visitors.
	* checks/errors/rust-const-checker.h
	(ConstChecker::visit): Remove IfLetExprConseqIf{,Let} visitors.
	* checks/errors/privacy/rust-privacy-reporter.cc
	(PrivacyReporter::visit): Remove IfLetExprConseqIf{,Let} visitors.
	* checks/errors/privacy/rust-privacy-reporter.h
	(PrivacyReporter::visit): Remove IfLetExprConseqIf{,Let} visitors.
	* hir/tree/rust-hir-expr.h
	(class IfLetExprConseqElse): Make else_block ExprWithBlock.
	(class IfLetExprConseqIf): Remove.
	(class IfLetExprConseqIfLet): Remove.
	* hir/tree/rust-hir-full-decls.h
	(class IfLetExprConseqIf): Remove.
	(class IfLetExprConseqIfLet): Remove.
	* hir/tree/rust-hir.cc
	(IfLetExprConseqElse::as_string): Adjust output.
	(IfLetExprConseqIf::as_string): Remove.
	(IfLetExprConseqIfLet::as_string): Remove.
	(IfLetExprConseqIf::accept_vis): Remove.
	(IfLetExprConseqIfLet::accept_vis): Remove.
	* hir/tree/rust-hir-visitor.h
	(HIRFullVisitor::visit): Remove IfLetExprConseqIf{,Let} visitors.
	(HIRFullVisitorBase::visit): Remove IfLetExprConseqIf{,Let} visitors.
	(HIRExpressionVisitor::visit): Remove IfLetExprConseqIf{,Let} visitors.
	* hir/rust-hir-dump.cc
	(Dump::visit): Remove IfLetExprConseqIf{,Let} visitors.
	* hir/rust-hir-dump.h
	(Dump::visit): Remove IfLetExprConseqIf{,Let} visitors.
	* typecheck/rust-hir-type-check-expr.h
	(TypeCheckExpr::visit): Remove IfLetExprConseqIf{,Let} visitors.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-03-17 16:33:49 +00:00
Owen Avery
3d4b187191 Unify HIR::IfExprConseqIf{,Let} into HIR::IfExprConseqElse
This should simplify 'if' expression handling to match
future simplifications to 'if let' expression handling.

gcc/rust/ChangeLog:

	* typecheck/rust-hir-type-check-expr.cc
	(TypeCheckExpr::visit): Remove IfExprConseqIf visitor.
	* typecheck/rust-hir-type-check-expr.h
	(TypeCheckExpr::visit): Remove IfExprConseqIf{,Let} visitor.
	* backend/rust-compile-block.cc
	(CompileConditionalBlocks::visit): Remove IfExprConseqIf visitor.
	* backend/rust-compile-block.h
	(CompileConditionalBlocks::visit): Remove IfExprConseqIf{,Let} visitors.
	(CompileExprWithBlock::visit):
	Remove IfExprConseqIf{,Let} visitors, implement BlockExpr visitor.
	* backend/rust-compile-expr.cc
	(CompileExpr::visit): Remove IfExprConseqIf visitor.
	* backend/rust-compile-expr.h
	(CompileExpr::visit): Remove IfExprConseqIf{,Let} visitors.
	* checks/lints/rust-lint-marklive.h
	(MarkLive::visit): Remove IfExprConseqIf visitor.
	* checks/errors/rust-const-checker.cc
	(ConstChecker::visit): Remove IfExprConseqIf{,Let} visitors.
	* checks/errors/rust-const-checker.h
	(ConstChecker::visit): Remove IfExprConseqIf{,Let} visitors.
	* checks/errors/rust-unsafe-checker.cc
	(UnsafeChecker::visit): Remove IfExprConseqIf{,Let} visitors.
	* checks/errors/rust-unsafe-checker.h
	(UnsafeChecker::visit): Remove IfExprConseqIf{,Let} visitors.
	* checks/errors/privacy/rust-privacy-reporter.cc
	(PrivacyReporter::visit): Remove IfExprConseqIf{,Let} visitors.
	* checks/errors/privacy/rust-privacy-reporter.h
	(PrivacyReporter::visit): Remove IfExprConseqIf{,Let} visitors.
	* hir/tree/rust-hir-expr.h
	(class IfExprConseqElse): Make else_block ExprWithBlock.
	(class IfExprConseqIf): Remove.
	(class IfExprConseqIfLet): Remove.
	* hir/tree/rust-hir-full-decls.h
	(class IfExprConseqIf): Remove.
	(class IfExprConseqIfLet): Remove.
	* hir/tree/rust-hir.cc
	(IfExprConseqElse::as_string): Adjust output.
	(IfExprConseqIf::as_string): Remove.
	(IfExprConseqIfLet::as_string): Remove.
	(IfExprConseqIf::accept_vis): Remove.
	(IfExprConseqIfLet::accept_vis): Remove.
	* hir/tree/rust-hir-visitor.h
	(HIRFullVisitor::visit): Remove IfExprConseqIf{,Let} visitors.
	(HIRFullVisitorBase::visit): Remove IfExprConseqIf{,Let} visitors.
	(HIRExpressionVisitor::visit): Remove IfExprConseqIf{,Let} visitors.
	* hir/rust-hir-dump.cc
	(Dump::visit): Remove IfExprConseqIf{,Let} visitors.
	* hir/rust-hir-dump.h
	(Dump::visit): Remove IfExprConseqIf{,Let} visitors.
	* hir/rust-ast-lower.cc
	(ASTLoweringIfBlock::visit): Replace HIR::IfExprConseqIf with HIR::IfExprConseqElse.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-03-17 16:31:54 +00:00
Mahmoud Mohamed
dd4038083e resolve: Fix multiple bindings handling in match
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>
2023-03-17 16:30:46 +00:00
Philip Herron
7334fb00e9 gccrs: remove proxy class to use virtual method to get impl_item name
gcc/rust/ChangeLog:

	* typecheck/rust-hir-inherent-impl-overlap.h (class ImplItemToName): remove

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2023-03-17 10:34:36 +00:00
Philip Herron
90a53011cb gccrs: cleanup resolve method address code generation
gcc/rust/ChangeLog:

	* backend/rust-compile-expr.cc (CompileExpr::resolve_method_address): remove unused code

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2023-03-17 10:34:36 +00:00
Philip Herron
75b6a14c46 gccrs: Only infer when no generic arguments have been specified
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>
2023-03-17 10:34:36 +00:00
Philip Herron
dab27f737e gccrs: add extra debug line for method resolve select
gcc/rust/ChangeLog:

	* typecheck/rust-hir-dot-operator.cc (MethodResolver::select): add debug

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2023-03-17 10:34:36 +00:00
Philip Herron
9ace79ff7e gccrs: Remove solve_missing_mappings_from_this to handle covariants
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>
2023-03-17 10:34:36 +00:00
Philip Herron
85a5abeb37 gccrs: get rid of can_eq in CoerceionRules selection
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>
2023-03-17 10:34:36 +00:00
Philip Herron
6bbf7202c6 gccrs: cleanup header usage to decouple includes
gcc/rust/ChangeLog:

	* backend/rust-compile-base.cc: fix headers
	* backend/rust-compile-base.h: likewise
	* backend/rust-compile-expr.cc: likewise
	* backend/rust-compile-extern.h: likewise
	* backend/rust-compile-pattern.cc: likewise
	* backend/rust-compile.cc: likewise
	* typecheck/rust-autoderef.cc: likewise
	* typecheck/rust-hir-dot-operator.cc: likewise
	* typecheck/rust-hir-inherent-impl-overlap.h: likewise
	* typecheck/rust-hir-path-probe.cc: likewise
	* typecheck/rust-hir-trait-resolve.cc: likewise
	* typecheck/rust-hir-type-check-base.cc: likewise
	* typecheck/rust-hir-type-check-base.h (RUST_HIR_TYPE_CHECK_BASE): likewise
	* typecheck/rust-hir-type-check-enumitem.cc: likewise
	* typecheck/rust-hir-type-check-expr.cc: likewise
	* typecheck/rust-hir-type-check-implitem.cc: likewise
	* typecheck/rust-hir-type-check-item.cc: likewise
	* typecheck/rust-hir-type-check-path.cc: likewise
	* typecheck/rust-hir-type-check-pattern.cc: likewise
	* typecheck/rust-hir-type-check-stmt.cc: likewise
	* typecheck/rust-hir-type-check-struct.cc: likewise
	* typecheck/rust-hir-type-check-type.cc: likewise
	* typecheck/rust-hir-type-check-type.h: likewise
	* typecheck/rust-hir-type-check.h (RUST_HIR_TYPE_CHECK): likewise
	* typecheck/rust-tyty-bounds.cc: likewise
	* typecheck/rust-tyty-call.cc: likewise
	* typecheck/rust-tyty-subst.cc: likewise
	* typecheck/rust-tyty.cc: likewise

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2023-03-17 10:34:36 +00:00
Philip Herron
35da2edceb gccrs: get rid of virtual dispatch for substitution proxys
gcc/rust/ChangeLog:

	* typecheck/rust-tyty.cc (BaseType::has_subsititions_defined): new implementation
	(BaseType::needs_generic_substitutions): likewise
	(ProjectionType::needs_generic_substitutions): remove
	(ProjectionType::has_subsititions_defined): remove
	* typecheck/rust-tyty.h: update header

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2023-03-17 10:34:36 +00:00
Philip Herron
01c741adc2 gccrs: tyty get rid of useless virtuals
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>
2023-03-17 10:34:36 +00:00
Philip Herron
bab5649037 gccrs: group basetype virtuals together and remove unused virtual
gcc/rust/ChangeLog:

	* typecheck/rust-tyty.h: cleanup ordering of header

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2023-03-17 10:34:36 +00:00
Philip Herron
d6e39f781e gccrs: refactor monomoprhized_clone to not use virtual dispatch
gcc/rust/ChangeLog:

	* typecheck/rust-tyty.cc (BaseType::monomorphized_clone): new impl
	(InferType::monomorphized_clone): remove
	(ErrorType::monomorphized_clone): likewise
	(ADTType::monomorphized_clone): likewise
	(TupleType::monomorphized_clone): likewise
	(FnType::monomorphized_clone): likewise
	(FnPtr::monomorphized_clone): likewise
	(ClosureType::monomorphized_clone): likewise
	(ArrayType::clone): likewise
	(ArrayType::get_var_element_type): likewise
	(ArrayType::monomorphized_clone): likewise
	(SliceType::clone): likewise
	(SliceType::get_var_element_type): likewise
	(SliceType::monomorphized_clone): likewise
	(BoolType::monomorphized_clone): likewise
	(IntType::monomorphized_clone): likewise
	(UintType::monomorphized_clone): likewise
	(FloatType::monomorphized_clone): likewise
	(USizeType::monomorphized_clone): likewise
	(ISizeType::monomorphized_clone): likewise
	(CharType::monomorphized_clone): likewise
	(ReferenceType::clone): likewise
	(ReferenceType::get_var_element_type): likewise
	(ReferenceType::monomorphized_clone): likewise
	(PointerType::clone): likewise
	(PointerType::get_var_element_type): likewise
	(PointerType::monomorphized_clone): likewise
	(ParamType::monomorphized_clone): likewise
	(StrType::monomorphized_clone): likewise
	(NeverType::monomorphized_clone): likewise
	(PlaceholderType::monomorphized_clone): likewise
	(ProjectionType::monomorphized_clone): likewise
	(DynamicObjectType::monomorphized_clone): likewise
	* typecheck/rust-tyty.h: update header

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2023-03-17 10:34:36 +00:00
Philip Herron
712aa0027c gccrs: refactor TyTy::BaseType::is_unit to not use virtual dispatch
gcc/rust/ChangeLog:

	* typecheck/rust-tyty.cc (BaseType::is_unit): new implementation
	(ErrorType::is_unit): remove
	(TupleType::is_unit): likewise
	(NeverType::is_unit): likewise
	(PlaceholderType::is_unit): likewise
	(ProjectionType::is_unit): likewise
	* typecheck/rust-tyty.h: update header

Signed-off-by: Philip Herron <herron.philip@googlemail.com>
2023-03-17 10:34:36 +00:00
Philip Herron
75ad892c42 gccrs: refactor is_concrete to not just virtual dispatch
Its easier to debug and maintain one base function for this than relying
on virtual dispatch

Signed-off-by: Philip Herron <herron.philip@googlemail.com>

gcc/rust/ChangeLog:

	* typecheck/rust-tyty.cc (BaseType::is_concrete): new implementation
	(InferType::is_concrete): remove
	(ErrorType::is_concrete): likewise
	(StructFieldType::is_concrete): likewise
	(ADTType::is_concrete): likewise
	(TupleType::is_concrete): likewise
	(BoolType::is_concrete): likewise
	(IntType::is_concrete): likewise
	(UintType::is_concrete): likewise
	(FloatType::is_concrete): likewise
	(USizeType::is_concrete): likewise
	(ISizeType::is_concrete): likewise
	(CharType::is_concrete): likewise
	(ReferenceType::is_concrete): likewise
	(PointerType::is_concrete): likewise
	(ParamType::is_concrete): likewise
	(StrType::is_concrete): likewise
	(NeverType::is_concrete): likewise
	(PlaceholderType::is_concrete): likewise
	(ProjectionType::is_concrete): likewise
	(DynamicObjectType::is_concrete): likewise
	* typecheck/rust-tyty.h: update header
2023-03-17 10:34:36 +00:00
Philip Herron
254208dc7a gccrs: reuse destructure code in compilation of types
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>
2023-03-17 10:34:36 +00:00
Tage Johansson
0e010fc08b gccrs: Add all rust keywords (except priv) to the follow-set of :vis when parsing macro rules
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>
2023-03-16 10:19:16 +00:00
Pierre-Emmanuel Patry
ae80bcdd9b build: Regenerate build files
Regenerate all build files.

ChangeLog:

	* Makefile.in:
	* configure: Regenerate.
	* libgrust/Makefile.in: New file.
	* libgrust/aclocal.m4: New file.
	* libgrust/configure: New file.
	* libgrust/libproc_macro/Makefile.in: New file.

libgm2/ChangeLog:

	* Makefile.in: Regenerate.
	* aclocal.m4: Regenerate.
	* libm2cor/Makefile.in: Regenerate.
	* libm2iso/Makefile.in: Regenerate.
	* libm2log/Makefile.in: Regenerate.
	* libm2min/Makefile.in: Regenerate.
	* libm2pim/Makefile.in: Regenerate.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-03-15 16:27:27 +00:00
Pierre-Emmanuel Patry
92d2d5a608 build: Add libgrust as compilation modules
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>
2023-03-15 16:27:27 +00:00
Pierre-Emmanuel Patry
cc10d5ed59 librust: Add libproc_macro and build system
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>
2023-03-15 16:27:27 +00:00
Mahmoud Mohamed
bed6308e5e resolve: Handle multiple bindings to the same identifier
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>
2023-03-15 11:14:06 +00:00
Mahmoud Mohamed
fc0addd1ff hir: Improve pattern bindings handling in closure parameters
gcc/rust/ChangeLog:

	* backend/rust-compile-expr.cc (CompileExpr::generate_closure_function):
	handle closure parameters pattern bindings using CompilePatternBindings visitor

gcc/testsuite/ChangeLog:

	* rust/execute/torture/closure4.rs: New test.
	* rust/execute/torture/ref-pattern2.rs: New test.

Signed-off-by: Mahmoud Mohamed <mahadelr19@gmail.com>
2023-03-15 11:04:50 +00:00
Arthur Cohen
7cd4f74e3d gccrs: Rename compiler proper
ChangeLog:

	* README.md (process): Rename `rust1` to `crab1` in examples.

gcc/rust/ChangeLog:

	* Make-lang.in: Rename `rust1` to `crab1`.
	* config-lang.in: Likewise.
	* lang-specs.h: Likewise.
	* rustspec.cc (lang_specific_driver): Likewise.
2023-03-15 10:34:27 +00:00
Owen Avery
1ff171adfd Add method to access SlicePattern items
gcc/rust/ChangeLog:

	* hir/tree/rust-hir-pattern.h
	(SlicePattern::get_items): Add.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-03-15 10:23:29 +00:00
Owen Avery
7ef3277cb2 Convert structs to classes
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>
2023-03-15 10:23:29 +00:00
Owen Avery
26e4aa3cd5 HIR::AltPattern fixes
gcc/rust/ChangeLog:

	* hir/tree/rust-hir-pattern.h
	(class AltPattern): Remove duplicate access specifier.
	(AltPattern::get_alts): Add.
	* hir/tree/rust-hir.cc
	(AltPattern::as_string): Add.
	(AltPattern::accept_vis): Add.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-03-15 10:23:29 +00:00
Arthur Cohen
a1f940d193 hir: Add ExportedMacro node and handling.
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.
2023-03-14 16:15:50 +00:00
Mahmoud Mohamed
43590461e0 hir: Provide basic handling for ReferencePattern in function parameter
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>
2023-03-14 10:24:48 +00:00
Arthur Cohen
362c6d7f14 enr: Fetch module items during early name resolution
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.
2023-03-13 18:11:30 +00:00
Jakub Dupak
98363db007 hir: Simplify indentation to single line
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>
2023-03-13 18:09:47 +00:00
Jakub Dupak
048971cf42 hir: Unify indentation approach with ast
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>
2023-03-13 18:09:47 +00:00
Mahmoud Mohamed
f31fc7b0f6 hir: Fix ReferencePattern typechecking
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>
2023-03-13 18:09:26 +00:00
Marc Poulhiès
2c1e7b55da gccrs: fix some clang warnings
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>
2023-03-10 12:45:46 +00:00
vincent
6f9938c712 hir: add a helper function for visit
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>
2023-03-09 13:54:25 +00:00
goar5670
5bd4b19068 typecheck: Add basic typechecking for ReferenceType
gcc/rust/ChangeLog:
	* hir/tree/rust-hir-pattern.h (HIR::ReferencePattern):
	added get_referenced_pattern function.
	* resolve/rust-ast-resolve-pattern.h
	(Resolve::PatternDeclaration): add visit function for
	AST::ReferencePattern
	* typecheck/rust-hir-type-check-pattern.cc
	(Resolver::TypeCheckPattern): add visit function for
	HIR::ReferencePattern

gcc/testsuite/ChangeLog:
	* rust/compile/ref_pattern_fn_param.rs: New test.

Signed-off-by: Mahmoud Mohamed <mahadelr19@gmail.com>
2023-03-08 10:26:22 +00:00
Owen Avery
1a33a5cf6b Add coherence related lang_items
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.
2023-03-08 10:23:54 +00:00
Owen Avery
94cbaa29a8 Add AltPattern HIR node
Example:
	match x {
	    0 | 1 => true,
	    _ => false
	}

gcc/rust/ChangeLog:

	* backend/rust-compile-fnparam.h:
	(CompileFnParam::visit): Add AltPattern visitor.
	* backend/rust-compile-pattern.h:
	(CompilePatternCaseLabelExpr::visit): Add AltPattern visitor.
	(CompilePatternBindings::visit): Add AltPattern visitor.
	(CompilePatternLet::visit): Add AltPattern visitor.
	* backend/rust-compile-resolve-path.h:
	(ResolvePathRef::visit): Add AltPattern visitor.
	* backend/rust-compile-var-decl.h:
	(CompileVarDecl::visit): Add AltPattern visitor.
	* checks/errors/rust-const-checker.cc
	(ConstChecker::visit): Add AltPattern visitor.
	* checks/errors/rust-const-checker.h:
	(ConstChecker::visit): Add AltPattern visitor.
	* checks/errors/rust-unsafe-checker.cc
	(UnsafeChecker::visit): Add AltPattern visitor.
	* checks/errors/rust-unsafe-checker.h:
	(UnsafeChecker::visit): Add AltPattern visitor.
	* hir/rust-hir-dump.cc
	(Dump::visit): Add AltPattern visitor.
	* hir/rust-hir-dump.h:
	(Dump::visit): Add AltPattern visitor.
	* hir/tree/rust-hir-full-decls.h
	(class AltPattern): Add forward declaration.
	* hir/tree/rust-hir-pattern.h
	(class AltPattern): New class.
	* hir/tree/rust-hir-visitor.h:
	(HIRFullVisitor::visit): Add AltPattern visitor.
	(HIRFullVisitorBase::visit): Add AltPattern visitor.
	(HIRPatternVisitor::visit): Add AltPattern visitor.
	* hir/tree/rust-hir.h:
	(Pattern::PatternType::ALT): New enumerator.
	* typecheck/rust-hir-type-check-pattern.cc
	(TypeCheckPattern::visit): Add AltPattern visitor.
	* typecheck/rust-hir-type-check-pattern.h:
	(TypeCheckPattern::visit): Add AltPattern visitor.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-03-07 10:11:10 +00:00
Pierre-Emmanuel Patry
f6e926a689 expand: Add stringify macro
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>
2023-03-07 10:07:31 +00:00
Nikos Alexandris
914b938884 Add length checking for tuple patterns
gcc/rust/ChangeLog:

	* typecheck/rust-hir-type-check-pattern.cc (TypeCheckPattern::visit):
		Add length checking for tuple patterns.
	(TypeCheckPattern::emit_pattern_size_error): New function.
	* typecheck/rust-hir-type-check-pattern.h: New function
		emit_pattern_size_error.

gcc/testsuite/ChangeLog:

	* rust/compile/tuple_mismatch.rs: New test.

Signed-off-by: Nikos Alexandris <nikos-alexandris@protonmail.com>
2023-03-06 13:29:34 +00:00
goar5670
bdd36f1de0 parser: Fix handling of multiple left angles in null denotation
gcc/rust/ChangeLog:

	* parse/rust-parse-impl.h (Parser::parse_expr):
	split LEFT_SHIFT before null_denotation.

gcc/testsuite/ChangeLog:

	* rust/compile/complex_qualified_path_in_expr.rs : New test.

Signed-off-by: Mahmoud Mohamed <mahadelr19@gmail.com>
2023-03-06 13:25:08 +00:00
Parthib
136c765c74 Cleanup and Assertion
gcc/rust/ChangLog:

	* rust-object-export.cc: Modified
	* hir/rust-ast-lower-type.cc (rust_fatal_error): Removed
		(rust_assert): Added

Signed-off-by: Parthib <parthibdutta02@gmail.com>
2023-03-06 12:36:16 +00:00
Owen Avery
ae91a0a3f2 Resolve closure parameters without given type
gcc/rust/ChangeLog:

	* resolve/rust-early-name-resolver.cc
	(EarlyNameResolver::visit):
	Check for closure parameter without given type.

gcc/testsuite/ChangeLog:

	* rust/compile/closure_no_type_anno.rs: Extend test.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-03-04 21:26:59 +00:00
Philip Herron
a4aeea9a90 gccrs: make predicate bounds overwrite-able
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.
2023-03-03 19:27:24 +00:00
Philip Herron
06e1d43c2f gccrs: Fix name-resolution to be permissive and carry on
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
2023-03-03 19:27:24 +00:00
Philip Herron
f71f25af74 gccrs: Add missing node_id copys in the copy constructors
Signed-off-by: Philip Herron <herron.philip@googlemail.com>

gcc/rust/ChangeLog:

	* ast/rust-path.h: add missing copy for node_id
2023-03-03 19:27:24 +00:00
Philip Herron
99b3cfe5cd gccrs: cleanup headers
Signed-off-by: Philip Herron <herron.philip@googlemail.com>

gcc/rust/ChangeLog:

	* rust-gcc.h: remove unused headers
2023-03-03 19:27:24 +00:00
Philip Herron
4ab9d9ce33 gccrs: Fix missing move and copy constructors missing the associated-path
Addresses #1524

Signed-off-by: Philip Herron <herron.philip@googlemail.com>

gcc/rust/ChangeLog:

	* ast/rust-ast.cc (QualifiedPathInType::as_string): add missing to string
	* ast/rust-path.h: add missing copy+move constructors and assignment overloads
	* hir/tree/rust-hir-path.h: likewise
	* hir/tree/rust-hir.cc (QualifiedPathInType::as_string): add missing to string

gcc/testsuite/ChangeLog:

	* rust/compile/parse_associated_type_as_generic_arg.rs: it now works without -fsyntax-only
	* rust/compile/parse_associated_type_as_generic_arg2.rs: likewise
2023-03-03 19:27:24 +00:00
Philip Herron
22465fbc8c gccrs: destructure parameter names.
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
2023-03-03 19:27:24 +00:00
Philip Herron
6540653bc2 gccrs: Take advantage of our new unify_and to inject inference
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
2023-03-03 19:21:12 +00:00
goar5670
a4c851df03 parser: Fix parsing closure parameter
gcc/rust/ChangeLog:

	* parse/rust-parse-impl.h (Parser::parse_closure_param):
	Replace parse_pattern with parse_pattern_no_alt.

gcc/testsuite/ChangeLog:

	* rust/compile/closure_no_type_anno.rs: New test.

Signed-off-by: Mahmoud Mohamed <mahadelr19@gmail.com>
2023-03-03 15:17:49 +00:00
Pierre-Emmanuel Patry
26b19976c8 parser: Fix while let expr parsing
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>
2023-03-02 16:36:57 +00:00
Philip Herron
32a9736ef6 gccrs: add uninit intrinsic
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.
2023-03-02 16:35:59 +00:00
Pierre-Emmanuel Patry
baf5c546b5 parser: Add 0 sized slice pattern parsing
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>
2023-03-02 14:22:21 +00:00
Pierre-Emmanuel Patry
35ab5e3dff fixup: parser: Fix bootstrap compile error
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>
2023-03-02 13:51:12 +00:00
Abdul Rafey
724d3e824d added support for printing HIR dump of functions, statements, arithematic/logical expressions and literals.
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>
2023-03-02 10:11:56 +00:00
Nikos Alexandris
6d25dac737 Add location info when opening a file fails in include_str and include_bytes. Resolves issue #1872
gcc/rust/ChangeLog:

	* expand/rust-macro-builtins.cc (load_file_bytes): Add location parameter.
	(MacroBuiltin::include_bytes_handler): Pass location to load_file_bytes.
	(MacroBuiltin::include_str_handler): Pass location to load_file_bytes.

gcc/testsuite/ChangeLog:

	* rust/compile/builtin_macro_include_bytes_location_info.rs: New test.
	* rust/compile/builtin_macro_include_str_location_info.rs: New test.

Signed-off-by: Nikos Alexandris <nikos-alexandris@protonmail.com>
2023-03-02 09:19:00 +00:00
Pierre-Emmanuel Patry
9ec974b93e testsuite: Add a test for .. in slice patterns
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>
2023-03-01 21:31:47 +00:00
Pierre-Emmanuel Patry
0e41289aa5 parser: Add RestPattern parsing
Add simple RestPattern parsing to the pattern parsing function.

gcc/rust/ChangeLog:

	* parse/rust-parse-impl.h (Parser::parse_pattern_no_alt): Handle
	RestPattern correctly.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-03-01 21:31:47 +00:00
Pierre-Emmanuel Patry
a2ef9ad25a ast: Add NodeId and clone to RestPattern
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>
2023-03-01 21:31:47 +00:00
Pierre-Emmanuel Patry
ac375e4983 testsuite: Add a test for if let syntax
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>
2023-03-01 21:29:26 +00:00
Pierre-Emmanuel Patry
1f24ea4b3c parser: Fix if let parsing
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>
2023-03-01 21:29:26 +00:00
Philip Herron
23befb042f gccrs: add {add,sub,mul}_with_overflow intrinsics
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.
2023-03-01 21:23:44 +00:00
Arthur Cohen
7394a6893d hir: Refactor ASTLoweringStmt to source file.
gcc/rust/ChangeLog:

	* Make-lang.in: Add rust-ast-lower-stmt.o
	* hir/rust-ast-lower-stmt.h: Move definitions to...
	* hir/rust-ast-lower-stmt.cc: ...here.
2023-03-01 16:22:16 +00:00
mxlol233
9c46a853be Add feature gate definition for extern_types.
This commit add a basic implementation to gating `ExternalTypeItem` AST node.

gcc/rust/ChangeLog:

	* checks/errors/rust-feature-gate.cc: Add definition
	for `extern_types`.
	* checks/errors/rust-feature-gate.h: Likewise.
	* checks/errors/rust-feature.cc: Likewise.
	* checks/errors/rust-feature.h: Likewise.

gcc/testsuite/ChangeLog:
	* rust/compile/feature_extern_types.rs:New file.

Signed-off-by: Xiao Ma <mxlol233@outlook.com>
2023-03-01 15:02:21 +00:00
Owen Avery
9dce6f995c Fix assignment operator overloads for AST and HIR patterns
gcc/rust/ChangeLog:

	* ast/rust-pattern.h
	(StructPatternElements::operator=): Clear vector before inserting.
	(TupleStructItemsNoRange::operator=): Clear vector before inserting.
	(TupleStructItemsRange::operator=): Clear vectors before inserting.
	(TuplePatternItemsMultiple::operator=): Clear vector before inserting.
	(TuplePatternItemsRanged::operator=): Clear vectors before inserting.
	(SlicePattern::operator=): Clear vector before inserting.
	(AltPattern::operator=): Clear vector before inserting.
	* hir/tree/rust-hir-pattern.h
	(StructPatternElements::operator=): Clear vector before inserting.
	(TupleStructItemsNoRange::operator=): Clear vector before inserting.
	(TupleStructItemsRange::operator=): Clear vectors before inserting.
	(TuplePatternItemsMultiple::operator=): Clear vector before inserting.
	(TuplePatternItemsRanged::operator=): Clear vectors before inserting.
	(SlicePattern::operator=): Clear vector before inserting.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-03-01 09:26:45 +00:00
bl7awy
193c21c85b typecheck: Fix casting error behind generics
gcc/rust/ChangeLog:
	* typecheck/rust-casts.cc (TypeCastRules::cast_rules): Perform destructure on `from` type.

gcc/testsuite/ChangeLog:
	* rust/compile/cast_generics.rs: New test.

Signed-off-by: Mahmoud Mohamed  <mahadelr19@gmail.com>
2023-03-01 00:16:04 +00:00
Owen Avery
9284e20b65 Change struct StructPatternElements into class
gcc/rust/ChangeLog:

	* ast/rust-pattern.h
	(struct StructPatternElements): Change to class.
	(class StructPatternElements): Change from struct.
	* hir/tree/rust-hir-pattern.h
	(struct StructPatternElements): Change to class.
	(class StructPatternElements): Change from struct.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-02-28 22:46:19 +00:00
Owen Avery
588b5f19dc Replace gcc_unreachable with rust_sorry_at
gcc/rust/ChangeLog:

	* typecheck/rust-hir-type-check-pattern.cc
	(TypeCheckPattern::visit): Improve error messages.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-02-28 22:46:19 +00:00
Owen Avery
0cf0a7b8fc Fix formatting
gcc/rust/ChangeLog:

	* hir/tree/rust-hir-pattern.h
	(class TupleStructItemsNoRange): Fix formatting.
	(class TupleStructItemsRange): Fix formatting.
	(class TuplePatternItemsMultiple): Fix formatting.
	(class TuplePatternItemsRanged): Fix formatting.
	(class SlicePattern): Fix formatting.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-02-28 22:46:19 +00:00
Pierre-Emmanuel Patry
c2a3b370a9 ast: Add RestPattern AST node
Add the RestPattern AST node representing ".." code in some rust
context. This commit also provides the different visitors for this node.

gcc/rust/ChangeLog:

	* ast/rust-ast-dump.cc (Dump::visit): Add visitor.
	* ast/rust-ast-dump.h: Add visitor prototype.
	* ast/rust-ast-full-decls.h (class RestPattern): Add forward
	declaration for class RestPattern.
	* ast/rust-ast-visitor.h: Add visitor prototype.
	* ast/rust-ast.cc (RestPattern::accept_vis): Add function to
	accept a foreign visitor.
	* ast/rust-pattern.h (class RestPattern): Add class RestPattern.
	* checks/errors/rust-feature-gate.h: Add visitor prototype.
	* expand/rust-attribute-visitor.cc (AttrVisitor::visit): Add
	visitor implementation.
	* expand/rust-attribute-visitor.h: Add visitor prototype.
	* hir/rust-ast-lower-base.cc (ASTLoweringBase::visit): Add
	visitor implementation.
	* hir/rust-ast-lower-base.h: Add visitor prototype.
	* resolve/rust-ast-resolve-base.cc (ResolverBase::visit): Add
	visitor implementation.
	* resolve/rust-ast-resolve-base.h: Add visitor prototype.
	* resolve/rust-early-name-resolver.cc (EarlyNameResolver::visit):
	Add visitor implementation.
	* resolve/rust-early-name-resolver.h: Add visitor prototype.
	* util/rust-attributes.cc (AttributeChecker::visit): Add visitor
	implementation.
	* util/rust-attributes.h: Add visitor prototype.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-02-28 22:37:17 +00:00
Philip Herron
41890d20e2 gccrs: Remove cmp_autoderef_mode hack from old autoderef
Signed-off-by: Philip Herron <herron.philip@googlemail.com>

gcc/rust/ChangeLog:

	* typecheck/rust-tyty-cmp.h: remove
	* typecheck/rust-tyty.cc (set_cmp_autoderef_mode): likewise
	(reset_cmp_autoderef_mode): likewise
	* typecheck/rust-tyty.h (set_cmp_autoderef_mode): likewise
	(reset_cmp_autoderef_mode): likewise
2023-02-28 20:38:35 +00:00
Philip Herron
43a92787e3 gccrs: Fix method resolution to use TryCoerce
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.
2023-02-28 20:38:35 +00:00
Philip Herron
a20426036a gccrs: bug-fix implicit inference checks
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
2023-02-28 20:38:35 +00:00
Philip Herron
0632bfbf63 gccrs: autoderef unconstify so we can use in non const contexts
Signed-off-by: Philip Herron <herron.philip@googlemail.com>

gcc/rust/ChangeLog:

	* backend/rust-compile-base.h: unconsify
	* backend/rust-compile.cc (HIRCompileBase::coercion_site): likewise
	(HIRCompileBase::coercion_site1): likewise
	* typecheck/rust-autoderef.cc (Adjuster::try_deref_type): likewise
	(Adjuster::try_raw_deref_type): likewise
	(Adjuster::try_unsize_type): likewise
	(AutoderefCycle::cycle): likewise
	(AutoderefCycle::try_autoderefed): likewise
	* typecheck/rust-autoderef.h: likewise
	* typecheck/rust-coercion.cc (TypeCoercionRules::select): likewise
	* typecheck/rust-coercion.h: likewise
	* typecheck/rust-hir-dot-operator.cc (MethodResolver::Probe): likewise
	(MethodResolver::select): likewise
	* typecheck/rust-hir-dot-operator.h: likewise
2023-02-28 20:38:35 +00:00
Philip Herron
ea139aa381 gccrs: Only emit errors during type-bounds checking when required
Signed-off-by: Philip Herron <herron.philip@googlemail.com>

gcc/rust/ChangeLog:

	* typecheck/rust-unify.cc (UnifyRules::go): respect the emit_errors flag
2023-02-28 20:38:35 +00:00
Philip Herron
e164f32df2 gccrs: Make coercion sites autoderef cycle optional
Signed-off-by: Philip Herron <herron.philip@googlemail.com>

gcc/rust/ChangeLog:

	* typecheck/rust-casts.cc (TypeCastRules::check): update to new interface
	* typecheck/rust-coercion.cc (TypeCoercionRules::Coerce): likewise
	(TypeCoercionRules::TryCoerce): likewise
	(TypeCoercionRules::TypeCoercionRules): likewise
	* typecheck/rust-coercion.h: likewise
	* typecheck/rust-type-util.cc (coercion_site): likewise
2023-02-28 20:38:35 +00:00
Philip Herron
bd4556fb65 gccrs: Allow infer vars on the lhs too
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
2023-02-28 20:38:35 +00:00
Philip Herron
4b43f026aa gccrs: Generic pointers are coerceable
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.
2023-02-28 20:38:35 +00:00
Philip Herron
83863c6919 gccrs: refactor unify commit as a static function from unify code
Signed-off-by: Philip Herron <herron.philip@googlemail.com>

gcc/rust/ChangeLog:

	* typecheck/rust-unify.cc (UnifyRules::Resolve): refactor
	(UnifyRules::commit): refactor
	* typecheck/rust-unify.h: likewise
2023-02-28 20:38:35 +00:00
Philip Herron
fd849953da gccrs: Fix ICE in ADTType::is_concrete
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
2023-02-28 20:38:35 +00:00
Pierre-Emmanuel Patry
b50b73e392 testsuite: Add test with missing semicolon
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>
2023-02-28 17:00:02 +00:00
Pierre-Emmanuel Patry
f2d18bdabc testsuite: Add extern type item test
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>
2023-02-28 17:00:02 +00:00
Pierre-Emmanuel Patry
689c421dd7 parser: Parse external type item
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>
2023-02-28 17:00:02 +00:00
omkar-mohanty
5c2ed969a2 Implement and test include_str eager expansion
builtins: Implement eager expansion for include_str!()

gcc/rust/ChangeLog:

	* expand/rust-macro-builtins.cc
	(MacroBuiltin::include_str_handler): eager expansion
	(make_macro_path_str): macto to string
	(parse_single_string_literal): check for eager invocation
	(MacroBuiltin::assert_handler): eager expansion
	(MacroBuiltin::include_bytes_handler): eager expansion
	(MacroBuiltin::include_str_handler): eager expansion
	(MacroBuiltin::compile_error_handler): eager expansion
	(MacroBuiltin::include_handler): eager expansion

gcc/testsuite/ChangeLog:

	* rust/compile/builtin_macro_eager3.rs: New test.

Signed-off-by: omkar-mohanty <franzohouser@gmail.com>
2023-02-28 12:45:10 +00:00
Arthur Cohen
ce43f55e99 parser: Parse default impl Functions and Methods
gcc/rust/ChangeLog:

	* ast/rust-item.h (class Method): Add `is_default` field.
	(class Function): Likewise.
	* parse/rust-parse-impl.h (Parser::parse_item): Add nice error when
	parsing `default` outside of an `impl` block
	(Parser::parse_trait_impl_item): Allow parsing functions
	or methods when seeing `default`.

gcc/testsuite/ChangeLog:

	* rust/compile/parse_invalid_specialization.rs: New test.
	* rust/compile/parse_specialization.rs: New test.
	* rust/compile/default_not_a_kw.rs: New test.
2023-02-27 09:52:33 +00:00
Pierre-Emmanuel Patry
0d4a4475e9 typecheck: Refactor cast_site
Refactor cast_site to be a simple function in rust-type-util.h.

gcc/rust/ChangeLog:

	* typecheck/rust-hir-type-check-base.cc (TypeCheckBase::cast_site):
	Remove cast_site.
	* typecheck/rust-hir-type-check-base.h: Remove cast_site
	prototype.
	* typecheck/rust-type-util.cc (cast_site): Add cast_site.
	* typecheck/rust-type-util.h (cast_site): Add cast_site
	prototype.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-02-24 14:59:12 +00:00
Arthur Cohen
9a0f9fb8ba ast: Add proper visitors for ExternalTypeItem
gcc/rust/ChangeLog:

	* ast/rust-item.h: Add non-const `get_visibility` to ExternalTypeItem.
	* ast/rust-ast-dump.cc (Dump::visit): Add implementation for ExternalTypeItem.
	* expand/rust-attribute-visitor.cc (AttrVisitor::visit): Likewise.
2023-02-24 14:43:01 +00:00
Arthur Cohen
782d6d062d ast: Add ExternalTypeItem node
gcc/rust/ChangeLog:

	* ast/rust-item.h (class ExternalTypeItem): New class.
	* ast/rust-ast.cc (ExternalTypeItem::as_string): New function.
	(ExternalTypeItem::accept_vis): Likewise.
	* ast/rust-ast-full-decls.h (class ExternalTypeItem): Declare class.
	* ast/rust-ast-dump.cc (Dump::visit): Add base visitor for ExternalTypeItem.
	* ast/rust-ast-dump.h: Likewise.
	* ast/rust-ast-visitor.h: Likewise.
	* checks/errors/rust-feature-gate.h: Likewise.
	* expand/rust-attribute-visitor.cc (AttrVisitor::visit): Likewise.
	* expand/rust-attribute-visitor.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.
	* resolve/rust-early-name-resolver.cc (EarlyNameResolver::visit): Likewise.
	* resolve/rust-early-name-resolver.h: Likewise.
	* util/rust-attributes.cc (AttributeChecker::visit): Likewise.
	* util/rust-attributes.h: Likewise.
2023-02-24 14:43:01 +00:00
Arthur Cohen
cda1d7852d macro_invoc_lexer: Add split_current_token implementation
gcc/rust/ChangeLog:

	* expand/rust-macro-invoc-lexer.cc (MacroInvocLexer::split_current_token):
	Add proper implementation.

gcc/testsuite/ChangeLog:

	* rust/compile/expand_macro_qual_path_in_type.rs: New test.
2023-02-24 11:01:27 +00:00
Arthur Cohen
53059c7e10 Merge remote-tracking branch 'upstream/tschwinge/merge-upstream' 2023-02-23 16:02:43 +01:00
Arthur Cohen
f60c15f509 parser: Add parsing of auto traits
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.
2023-02-23 13:54:18 +00:00
Pierre-Emmanuel Patry
918851ad2c typecheck: Refactor coercion_site
Refactor coercion_site to be a simple function in rust-type-util.h
instead of a static function in TypeCheckBase.
gcc/rust/ChangeLog:

	* typecheck/rust-hir-trait-resolve.cc (TraitItemReference::resolve_item):
	Remove TypeCheckBase namespace qualifier.
	* typecheck/rust-hir-type-check-base.cc (TypeCheckBase::coercion_site):
	Remove coercion_site function.
	* typecheck/rust-hir-type-check-base.h: Remove coercion_site
	prototype.
	* typecheck/rust-type-util.cc (coercion_site): Add coercion_site
	function.
	* typecheck/rust-type-util.h (coercion_site): Add coercion_site
	prototype.
	* typecheck/rust-tyty-call.cc (TypeCheckCallExpr::visit):
	Remove TypeCheckBase namespace qualifier.
	(TypeCheckMethodCallExpr::check): Remove TypeCheckBase namespace
	qualifier.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-02-23 09:58:25 +00:00
Thomas Schwinge
a04fb4ed9e Merge upstream (dummy), 2023-02-21 "Rust front-end update"
In #1908 'Merge upstream, last commit before 2023-02-21 "Rust front-end update"'
we merged commit ecc863e85e from upstream GCC
master branch.

This one now merges the 2023-02-21 "Rust front-end update", commits
ecc863e85efe259c799515de0c38c2297b0e3bd7..ecb409b23b86363fa085ec32e89e1aeda002cb70:

      - 7e7a958804 gccrs: Fix missing dead code analysis ICE on local enum definition
      - 7080854461 gccrs: visibility: Rename get_public_vis_type -> get_vis_type
      - 1e8eb10220 gccrs: dump: Emit visibility when dumping items
      - 543ba35905 gccrs: Add catch for recusive type queries
      - d072b4a516 gccrs: testing: try loop in const function
      - 980bd25e25 gccrs: ast: dump assignment and compound assignment expr
      - aeed747093 gccrs: ast: dump If expressions
      - 00e0684a78 gccrs: builtins: Move implementation into source file
      - 79434fabf7 gccrs: Track DefId on ADT variants
      - 31b77593ed gccrs: Ensure uniqueness on Path probe's
      - a5d3586a9b gccrs: Support looking up super traits for trait items
      - 8d02ef57a6 gccrs: ast: dump: add emit_generic_params helper
      - 4c807ef70d gccrs: ast: dump: add format_{tuple,struct}_field helpers
      - 0a762d2049 gccrs: ast: dump structs, enums and unions
      - ab6d8ad3f5 gccrs: intrinsics: Add data prefetching intrinsics
      - 570415e75c gccrs: fix ICE on missing closing paren
      - a08f265625 gccrs: mappings: Add MacroInvocation -> MacroRulesDef mappings
      - 295cd26508 gccrs: rust-ast-resolve-item: Add note about resolving glob uses
      - 2f1035fc91 gccrs: ast: Add accept_vis() method to `GenericArg`
      - 5221974691 gccrs: early-name-resolver: Add simple macro name resolution
      - 13556413e3 gccrs: Support type resolution on super traits on dyn objects
      - f49e252824 gccrs: Add mappings for fn_once lang item
      - 2d7661e76e gccrs: Add ABI mappings for rust-call to map to ABI::RUST
      - 59bee4d466 gccrs: Method resolution must support multiple candidates
      - b1510ce0fc gccrs: ast: dump: fix extra newline in block without tail
      - 0a9114c151 gccrs: ast: dump: minor fixups to IfExpr formatting
      - c091fd5f4a gccrs: ast: dump: ComparisonExpr and LazyBooleanExpr
      - f26e9ca3e9 gccrs: ast: dump: ArrayExpr
      - d1db46191e gccrs: ast: dump: various simple Exprs
      - 173f98ae49 gccrs: ast: dump: RangeExprs
      - 74065c000e gccrs: Refactor TraitResolver to not require a visitor
      - acbaadfa46 gccrs: ast: dump TypeAlias
      - 8f0b1526e0 gccrs: Support outer attribute handling on trait items just like normal items
      - 421494b592 gccrs: dump: Emit visibility when dumping items
      - 31150a6366 gccrs: dump: Dump items within modules
      - 2f16df1b44 gccrs: dump: Fix module dumping
      - e535b7b3e3 gccrs: ast: Module: unloaded module and inner attributes
      - ec28fdb6aa gccrs: dump: Dump macro rules definition
      - 643ec1c253 gccrs: Add check for recursive trait cycles
      - e2647e5e5a gccrs: ast: Refactor ASTFragment -> Fragment class
      - 68e743090d gccrs: rust: Replace uses of ASTFragment -> Fragment
      - b326cced19 gccrs: ast: Improve Fragment API
      - ed75e142a7 gccrs: Add missing fn_once_output langitem
      - 870dd9d5d3 gccrs: Refactor expression hir lowering into cc file
      - 9e19f329e5 gccrs: Formatting cleanup in HIR lowering pattern
      - 977e0e5227 gccrs: Add name resolution for closures
      - 4d021d9e01 gccrs: Refactor method call type checking
      - 898240946c gccrs: Add closures to lints and error checking
      - 740a199722 gccrs: Initial Type resolution for closures
      - 699e7e8627 gccrs: Closure support at CallExpr
      - 12e94515f8 gccrs: Add missing name resolution to Function type-path segments
      - 875f722de5 gccrs: Add missing hir lowering to function type-path segments
      - 51d180fcd7 gccrs: Add missing type resolution for function type segments
      - 21d19d2cf6 gccrs: Support Closure calls as generic trait bounds
      - a8531cd9a8 gccrs: Implement the inline visitor
      - 6ef1089ec2 gccrs: rust: Allow gccrs to build on x86_64-apple-darwin with clang/libc++
      - 4d39d3912f gccrs: builtins: Rename all bang macro handlers
      - 782e070374 gccrs: intrinsics: Add `sorry_handler` intrinsic handler
      - 514284ecd9 gccrs: constexpr: Add `rust_sorry_at` in places relying on init values
      - a7c8f7ee34 gccrs: intrinsics: Add early implementation for atomic_store_{seqcst, relaxed, release}
      - 1c586a1d1c gccrs: intrinsics: Add unchecked operation intrinsics
      - cb2cf21cf3 gccrs: intrinsics: Use lambdas for wrapping_<op> intrinsics
      - f4c818c623 gccrs: intrinsics: Cleanup error handling around atomic_store_*
      - 5b5a0ca771 gccrs: intrinsics: Implement atomic_load intrinsics
      - aedd97a537 gccrs: ast: visitor pattern -> overload syntax compatibility layer
      - 3b5fb3f89b gccrs: ast: transform helper methods to visits and add methods to simplify repeated patterns
      - a56faba963 gccrs: ast: refer correctly to arguments in docs-strings
      - 04a16c58e3 gccrs: ast: Dump unit struct
      - 2fc0130360 gccrs: add lang item "phantom_data"
      - b84222899c gccrs: add Location to AST::Visibility
      - 85f69a9b6a gccrs: typecheck: Fix overzealous `delete` call
      - 907d11194e gccrs: ast: add visit overload for references
      - bd2240d30f gccrs: ast: Dump where clause and recursively needed nodes
      - 59fb0747cc gccrs: ast: Dump slice type
      - 140a2aed7e gccrs: ast: Dump array type
      - 971d16cbfa gccrs: ast: Dump raw pointer type
      - c4c859bff8 gccrs: ast: Dump never type
      - 91409d27d5 gccrs: ast: Dump tuple type
      - ee0166fa1b gccrs: ast: Dump inferred type
      - ae1f6b3a96 gccrs: ast: Dump bare function type
      - ca06115eac gccrs: ast: Dump impl trait type one bound
      - 638f65b208 gccrs: ast: Dump impl trait type
      - 7ed4a0ebc1 gccrs: ast: Dump trait object type
      - e311e9b7c5 gccrs: ast: Dump parenthesised type
      - 0bb33cb574 gccrs: ast: Dump trait object type one bound
      - 1acb7e02ed gccrs: ast: Dump type param type
      - b8863414ed gccrs: ast: Dump generic parameters
      - ce13edd879 gccrs: ast: Remove unused include in rust-ast-dump.cc
      - 0e44abb1b5 gccrs: ast: Dump remove /* stmp */ comment to not clutter the dump
      - 567494f703 gccrs: ast: Dump no comma after self in fn params if it is the last one
      - 78c70a50f7 gccrs: Remove default location. Add visibility location to create_* functions
      - 0ef795c327 gccrs: Improve lexer dump
      - 01af669357 gccrs: Get rid of make builtin macro
      - 32a4659c5e gccrs: Refactor name resolver to take a Rib::ItemType
      - f7c258b291 gccrs: Add closure binding's tracking to name resolution
      - eb1202224f gccrs: Add capture tracking to the type info for closures
      - 92389b46a9 gccrs: Add initial support for argument capture of closures
      - e7a69d4533 gccrs: Fix undefined behaviour issues on macos
      - 03df9a040c gccrs: Skip this debug test case which is failing on the latest mac-os devtools and its only for debug info
      - 9f455ed820 gccrs: Cleanup unused parameters to fix the bootstrap build
      - b9203d82ad gccrs: Repair 'gcc/rust/lang.opt' comment
      - 064bbd0fe1 gccrs: const evaluator: Remove get_nth_callarg
      - ecb409b23b gccrs: add math intrinsics

..., and:

      - e28c5b33b9 Update copyright years.

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.
2023-02-22 08:49:44 +01:00
Pierre-Emmanuel Patry
1145917c6b typecheck: Refactor unify_site
Refactor unify_site to be a simple function in rust-type-util.h.

gcc/rust/ChangeLog:

	* typecheck/rust-autoderef.cc: Remove TypeCheckBase qualifier.
	* typecheck/rust-hir-trait-resolve.cc: Remove TypeCheckBase
	qualifier.
	* typecheck/rust-hir-type-check-base.cc (TypeCheckBase::unify_site):
	Remove unify_site.
	* typecheck/rust-hir-type-check-base.h: Remove unify_site
	header.
	* typecheck/rust-hir-type-check.cc (TypeResolution::Resolve):
	Remove TypeCheckBase qualifier.
	* typecheck/rust-type-util.cc (unify_site): Add unify_site
	function.
	* typecheck/rust-type-util.h (unify_site): Add unify_site
	prototype.
	* typecheck/rust-tyty-call.cc (TypeCheckMethodCallExpr::check):
	Remove TypeCheckBase qualifier.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
2023-02-22 07:14:56 +00:00
Arthur Cohen
429e258dbe ci: Run GCC 4.8 job in Ubuntu 18.04 container
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
2023-02-22 06:24:10 +00:00
Thomas Schwinge
0d5fe7b9ae Adjust '.github/bors_log_expected_warnings' 2023-02-21 22:37:04 +01:00
Thomas Schwinge
4a4e0b20ad Merge commit 'ecc863e85efe259c799515de0c38c2297b0e3bd7' into HEAD 2023-02-21 21:13:49 +01:00
Thomas Schwinge
017e88785a Merge commit '7b8916a6fd098546e4e53e53b37a5153664ba17f' into HEAD [#1819, #1864, #1885] 2023-02-21 20:48:38 +01:00
Thomas Schwinge
bc644ac377 Merge commit 'ae113080a9f98e807db239f3ad2157c64324542f' into HEAD 2023-02-21 20:47:19 +01:00
Arthur Cohen
87e7c9deda parser: Allow LEFT_SHIFT to start parse_type
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.
2023-02-20 12:52:12 +00:00
Arthur Cohen
57b64a6426 parser: Allow parsing of qualified type path as nested generic argument
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 #1815
Fixed #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.
2023-02-20 12:52:12 +00:00
mxlol233
773d3c6477 Add feature gate for "rustc_attri".
This commit implemented a basic feature gate to check some attributes
for `rustc_attri`.

gcc/rust/ChangeLog:

	* checks/errors/rust-feature-gate.cc: Add implementations
	for `rustc_attri`.
	* checks/errors/rust-feature-gate.h: Likewise.

gcc/testsuite/ChangeLog:

	* rust/compile/builtin_macro_compile_error.rs: Add
	crate feature `rustc_attri`.
	* rust/compile/builtin_macro_concat.rs: Likewise.
	* rust/compile/builtin_macro_eager1.rs: Likewise.
	* rust/compile/builtin_macro_eager2.rs: Likewise.
	* rust/compile/builtin_macro_env.rs: Likewise.
	* rust/compile/builtin_macro_include_bytes.rs:
	Likewise.
	* rust/compile/builtin_macro_include_str.rs:
	Likewise.
	* rust/compile/builtin_macro_not_found.rs:
	Likewise.
	* rust/compile/builtin_macro_recurse2.rs:
	Likewise.
	* rust/compile/feature_rust_attri0.rs:New file.
	* rust/compile/feature_rust_attri1.rs:New file.
	* rust/compile/include_empty.rs:Add crate feature
	`rustc_attri`.
	* rust/compile/issue-1830_bytes.rs:Likewise.
	* rust/compile/issue-1830_str.rs:Likewise.
	* rust/compile/macro42.rs:Likewise.
	* rust/execute/torture/builtin_macro_cfg.rs:
	Likewise.
	* rust/execute/torture/builtin_macro_concat.rs:
	Likewise.
	* rust/execute/torture/builtin_macro_env.rs:
	Likewise.
	* rust/execute/torture/builtin_macro_include_bytes.rs:
	Likewise.
	* rust/execute/torture/builtin_macro_include_str.rs:
	Likewise.
	* rust/execute/torture/builtin_macro_line.rs:
	Likewise.
	* rust/execute/torture/builtin_macros1.rs:
	Likewise.
	* rust/execute/torture/builtin_macros3.rs:
	Likewise.
	* rust/execute/torture/macros29.rs:Likewise.
	* rust/execute/torture/macros30.rs:Likewise.
	* rust/execute/torture/macros31.rs:Likewise.

Signed-off-by: Xiao Ma <mxlol233@outlook.com>
2023-02-20 12:51:18 +00:00
Owen Avery
15ca76ea86 Parse AltPattern
Renamed Parser::parse_pattern to Parser::parse_pattern_no_alt and created
new method Parser::parse_pattern to handle alternate patterns.

gcc/rust/ChangeLog:

	* parse/rust-parse-impl.h
	(Parser::parse_pattern): Add.
	(Parser::parse_pattern_no_alt): Rename.
	* parse/rust-parse.h:
	(Parser::parse_pattern): Add.
	(Parser::parse_pattern_no_alt): Rename.

gcc/testsuite/ChangeLog:

	* rust/compile/pattern-or.rs: New test.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-02-20 10:32:44 +00:00
Arthur Cohen
e23e7f14a5 Merge remote-tracking branch 'upstream/tschwinge/merge-upstream' 2023-02-20 11:24:38 +01:00
Owen Avery
3448f0fa23 Fix issue with parsing unsafe block expression statements
gcc/rust/ChangeLog:

	* parse/rust-parse-impl.h
	(Parser::parse_stmt): Handle unsafe expression statements.

gcc/testsuite/ChangeLog:

	* rust/compile/issue-1422.rs: New test.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-02-20 09:29:04 +00:00
Owen Avery
0f736eb625 Address unsafe with/without block handling ambiguity
gcc/rust/ChangeLog:

	* parse/rust-parse-impl.h
	(Parser::parse_expr_stmt): Remove hypothetical unsafe + expr_stmt_without_block handling.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-02-20 09:29:04 +00:00
M V V S Manoj Kumar
1774ff486a Added AST Node AST::InlineAsm
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.
2023-02-20 09:22:40 +00:00
Thomas Schwinge
24a3d7353f Adjust '.github/bors_log_expected_warnings' 2023-02-18 08:27:59 +01:00
Thomas Schwinge
99469c4aca Merge commit '27a89f84c458ae938bc3eb92ad0d594c06fc3b42' into HEAD
Fixes: #1819
Fixes: #1864
2023-02-18 07:36:17 +01:00
Thomas Schwinge
cf4670ff8f Merge commit '9dcfee4ef1a165b7fe525d71fc090a1bcae550cd' into HEAD 2023-02-18 07:35:28 +01:00
Arthur Cohen
5752164328 diagnostic: Refactor Error class
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.
2023-02-17 13:12:46 +00:00
Arthur Cohen
e995781440 ast: Refactor TraitItem to keep Location info
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.
2023-02-17 13:12:26 +00:00
Philip Herron
332b8abe75 gccrs: add test case to show our query-type system is working
Fixes #1361

Signed-off-by: Philip Herron <herron.philip@googlemail.com>

gcc/testsuite/ChangeLog:

	* rust/compile/issue-1361.rs: New test.
2023-02-16 23:17:34 +00:00
SainiAditya1
1bd1e46645 rename rust-hir-full-tests.cc
gcc/rust/Changelog:

	* hir/tree/rust-hir-full-test.cc: Moved to...
	* hir/tree/rust-hir.cc: ...here.
	* Make-lang.in: Rename rust-hir-full-test.

Signed-off-by: SainiAditya1 <Adityasaini10012001@outlook.com>
2023-02-16 12:52:55 +00:00
Thomas Schwinge
74913f718b Fix up DejaGnu directives in 'rust/compile/issue-1830_{bytes,str}.rs' test cases [#1838]
'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.
2023-02-16 10:47:59 +00:00
Owen Avery
b4d7468658 Add AST::AltPattern class
gcc/rust/ChangeLog:

	* ast/rust-ast-dump.cc
	(Dump::visit): Add AltPattern visitor.
	* ast/rust-ast-dump.h:
	(Dump::visit): Add AltPattern visitor.
	* ast/rust-ast-full-decls.h
	(class AltPattern): Add declaration.
	* ast/rust-ast-visitor.h:
	(ASTVisitor::visit): Add AltPattern visitor.
	* ast/rust-ast.cc
	(AltPattern::as_string): Add definition.
	(AltPattern::accept_vis): Add definition.
	* ast/rust-pattern.h
	(class AltPattern): Add declaration.
	* checks/errors/rust-feature-gate.h:
	(FeatureGate::visit) Add AltPattern visitor
	* expand/rust-attribute-visitor.cc
	(AttrVisitor::visit): Add AltPattern visitor.
	* expand/rust-attribute-visitor.h:
	(AttrVisitor::visit): Add AltPattern visitor.
	* hir/rust-ast-lower-base.cc
	(ASTLoweringBase::visit): Add AltPattern visitor.
	* hir/rust-ast-lower-base.h:
	(ASTLoweringBase::visit): Add AltPattern visitor.
	* resolve/rust-ast-resolve-base.cc
	(ResolverBase::visit): Add AltPattern visitor.
	* resolve/rust-ast-resolve-base.h:
	(ResolverBase::visit): Add AltPattern visitor.
	* resolve/rust-early-name-resolver.cc
	(EarlyNameResolver::visit): Add AltPattern visitor.
	* resolve/rust-early-name-resolver.h:
	(EarlyNameResolver::visit): Add AltPattern visitor.
	* util/rust-attributes.cc
	(AttributeChecker::visit): Add AltPattern visitor.
	* util/rust-attributes.h:
	(AttributeChecker::visit): Add AltPattern visitor.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-02-16 09:16:47 +00:00
Owen Avery
d4863de507 Fix formatting
gcc/rust/ChangeLog:

	* ast/rust-pattern.h: Fix formatting.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-02-16 09:16:47 +00:00
Arthur Cohen
d6e33adc71 builtins: Return empty list of tokens instead of nullptr
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.
2023-02-15 13:56:17 +00:00
Owen Avery
64ea37670a Add trailing newline
gcc/rust/ChangeLog:

	* checks/errors/rust-feature-gate.h: Add trailing newline before EOF.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-02-15 08:02:07 +00:00
Philip Herron
dac6d99a87 gccrs: Fix regression in testcase
Fixes #776

Signed-off-by: Philip Herron <herron.philip@googlemail.com>

gcc/testsuite/ChangeLog:

	* rust/compile/torture/traits10.rs: Fix test-case
2023-02-14 22:55:07 +00:00
Philip Herron
84eb2e24d9 gccrs: Support for Sized builtin marker trait
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.
2023-02-14 22:55:07 +00:00
Philip Herron
226e5736c0 gccrs: Add new virtual function HIR::ImplItem::get_impl_item_name
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
2023-02-14 22:55:07 +00:00
Philip Herron
a10df8a219 gccrs: Extract query_type from TypeCheckBase to be a simple extern
Signed-off-by: Philip Herron <herron.philip@googlemail.com>

gcc/rust/ChangeLog:

	* Make-lang.in: add new dependancy
	* typecheck/rust-hir-type-check-base.cc (TypeCheckBase::query_type): refactor
	* typecheck/rust-hir-type-check-base.h: refactor
	* typecheck/rust-hir-type-check.h (RUST_HIR_TYPE_CHECK): refactor
	* typecheck/rust-type-util.cc: New file.
	* typecheck/rust-type-util.h: New file.
2023-02-14 22:55:07 +00:00
Owen Avery
92d6dc8443 Implemented UTF-8 checking for include_str!()
gcc/rust/ChangeLog:

	* expand/rust-macro-builtins.cc
	(MacroBuiltin::include_str_handler): Add check for valid UTF-8.

gcc/testsuite/ChangeLog:

	* rust/compile/builtin_macro_include_str.rs:
	Include test of invalid UTF-8.
	* rust/compile/invalid_utf8: File with invalid UTF-8.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-02-14 22:00:59 +00:00
Owen Avery
665e53cc3e Add support for parsing empty tuple patterns.
gcc/rust/ChangeLog:

	* parse/rust-parse-impl.h
	(Parser::parse_grouped_or_tuple_pattern): Add support for empty tuple patterns.

gcc/testsuite/ChangeLog:

	* rust/compile/parse_empty_tuple_pattern.rs: New test.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-02-14 19:44:07 +00:00
Pierre-Emmanuel Patry
cf9ed4001e testsuite: Add empty string macro test
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>
2023-02-14 19:43:16 +00:00
Pierre-Emmanuel Patry
3c22361370 lex: Prevent directories in RAIIFile
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>
2023-02-14 19:43:16 +00:00
Owen Avery
df00fb8f5b Simplify WildcardPattern let statement handling
gcc/rust/ChangeLog:

	* backend/rust-compile-pattern.cc
	(CompilePatternLet::visit): Simplify WildcardPattern compilation for let statements.
	* backend/rust-compile-var-decl.h:
	(CompileVarDecl::visit): Remove variable declaration for WildcardPattern.
	* resolve/rust-ast-resolve-pattern.h:
	(PatternDeclaration::visit): Remove name resolution for WildcardPattern.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-02-14 19:42:47 +00:00
Owen Avery
444023411c Add test
gcc/testsuite/ChangeLog:

	* rust/compile/variadic.rs: New test.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-02-14 19:42:29 +00:00
Owen Avery
ca071f897c Add variadic argument type checking
gcc/rust/ChangeLog:

	* typecheck/rust-tyty-call.cc
	(TypeCheckCallExpr::visit): Add variadic argument type checking.
	(TypeCheckCallExpr::visit): Fix comment spelling ("varadic").

gcc/testsuite/ChangeLog:

	* rust/execute/torture/overflow1.rs: Fix test.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-02-14 19:42:29 +00:00
Arthur Cohen
e07ef30852 ci: Add missing merge_group trigger for workflow
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.
2023-02-14 18:52:09 +00:00
bors[bot]
2006ca18fe Merge #1825
1825: Add feature gate for "rust-intrinsic". r=CohenArthur a=TuringKi

This commit implemented a feature gate to check `intrinsics`.

gcc/rust/ChangeLog:

	* checks/errors/rust-feature-gate.cc: Add implementation for `void FeatureGate::visit (AST::ExternBlock &block)`. Add `valid_feature` construction process in `FeatureGate::check`.
	* checks/errors/rust-feature-gate.h: Add declaration for `void FeatureGate::visit (AST::ExternBlock &block)`. Add private variable `valid_feature`.
	* checks/errors/rust-feature.h: Change `issue` to `m_issue`.

gcc/testsuite/ChangeLog:

	* rust/compile/const-issue1440.rs: Add crate feature: `intrinsics`.
	* rust/compile/feature_intrinsics.rs: New file.
	* rust/compile/issue-1031.rs: Add crate feature: `intrinsics`.
	* rust/compile/issue-1130.rs: Add crate feature: `intrinsics`.
	* rust/compile/issue-1131.rs: Add crate feature: `intrinsics`.
	* rust/compile/issue-1237.rs: Add crate feature: `intrinsics`.
	* rust/compile/issue-1289.rs: Add crate feature: `intrinsics`.
	* rust/compile/rust-const-blog-issue.rs: Add crate feature: `intrinsics`.
	* rust/compile/torture/intrinsics-3.rs: Add crate feature: `intrinsics`.
	* rust/compile/torture/intrinsics-4.rs: Add crate feature: `intrinsics`.
	* rust/compile/torture/intrinsics-5.rs: Add crate feature: `intrinsics`.
	* rust/compile/torture/intrinsics-6.rs: Add crate feature: `intrinsics`.
	* rust/compile/torture/intrinsics-7.rs: Add crate feature: `intrinsics`.
	* rust/compile/torture/issue-1024.rs: Add crate feature: `intrinsics`.
	* rust/compile/torture/issue-1075.rs: Add crate feature: `intrinsics`.
	* rust/compile/torture/issue-1432.rs: Add crate feature: `intrinsics`.
	* rust/compile/unsafe10.rs: Add crate feature: `intrinsics`.
	* rust/execute/torture/atomic_load.rs: Add crate feature: `intrinsics`.
	* rust/execute/torture/atomic_store.rs: Add crate feature: `intrinsics`.
	* rust/execute/torture/copy_nonoverlapping1.rs: Add crate feature: `intrinsics`.
	* rust/execute/torture/issue-1120.rs: Add crate feature: `intrinsics`.
	* rust/execute/torture/issue-1133.rs: Add crate feature: `intrinsics`.
	* rust/execute/torture/issue-1232.rs: Add crate feature: `intrinsics`.
	* rust/execute/torture/slice-magic.rs: Add crate feature: `intrinsics`.
	* rust/execute/torture/slice-magic2.rs: Add crate feature: `intrinsics`.
	* rust/execute/torture/str-layout1.rs: Add crate feature: `intrinsics`.
	* rust/execute/torture/transmute1.rs: Add crate feature: `intrinsics`.
	* rust/execute/torture/wrapping_op1.rs: Add crate feature: `intrinsics`.
	* rust/execute/torture/wrapping_op2.rs: Add crate feature: `intrinsics`.

Signed-off-by: Xiao Ma <mxlol233@outlook.com>



Co-authored-by: mxlol233 <mxlol233@outlook.com>
2023-02-14 10:23:32 +00:00
mxlol233
debb72b0e9 Add feature gate for "rust-intrinsic".
This commit implemented a feature gate to check `intrinsics`.

gcc/rust/ChangeLog:

	* checks/errors/rust-feature-gate.cc: Add implementation for
	`void FeatureGate::visit (AST::ExternBlock &block)`. Add `valid_feature`
	construction process in `FeatureGate::check`.
	* checks/errors/rust-feature-gate.h: Add declaration for
	`void FeatureGate::visit (AST::ExternBlock &block)`. Add private
	variable `valid_feature`.
	* checks/errors/rust-feature.h: Change `issue` to `m_issue`.

gcc/testsuite/ChangeLog:

	* rust/compile/const-issue1440.rs: Add crate feature: `intrinsics`.
	* rust/compile/feature_intrinsics.rs: New file.
	* rust/compile/issue-1031.rs: Add crate feature: `intrinsics`.
	* rust/compile/issue-1130.rs: Add crate feature: `intrinsics`.
	* rust/compile/issue-1131.rs: Add crate feature: `intrinsics`.
	* rust/compile/issue-1237.rs: Add crate feature: `intrinsics`.
	* rust/compile/issue-1289.rs: Add crate feature: `intrinsics`.
	* rust/compile/rust-const-blog-issue.rs: Add crate feature: `intrinsics`.
	* rust/compile/torture/intrinsics-3.rs: Add crate feature: `intrinsics`.
	* rust/compile/torture/intrinsics-4.rs: Add crate feature: `intrinsics`.
	* rust/compile/torture/intrinsics-5.rs: Add crate feature: `intrinsics`.
	* rust/compile/torture/intrinsics-6.rs: Add crate feature: `intrinsics`.
	* rust/compile/torture/intrinsics-7.rs: Add crate feature: `intrinsics`.
	* rust/compile/torture/issue-1024.rs: Add crate feature: `intrinsics`.
	* rust/compile/torture/issue-1075.rs: Add crate feature: `intrinsics`.
	* rust/compile/torture/issue-1432.rs: Add crate feature: `intrinsics`.
	* rust/compile/unsafe10.rs: Add crate feature: `intrinsics`.
	* rust/execute/torture/atomic_load.rs: Add crate feature: `intrinsics`.
	* rust/execute/torture/atomic_store.rs: Add crate feature: `intrinsics`.
	* rust/execute/torture/copy_nonoverlapping1.rs: Add crate feature:
	`intrinsics`.
	* rust/execute/torture/issue-1120.rs: Add crate feature: `intrinsics`.
	* rust/execute/torture/issue-1133.rs: Add crate feature: `intrinsics`.
	* rust/execute/torture/issue-1232.rs: Add crate feature: `intrinsics`.
	* rust/execute/torture/slice-magic.rs: Add crate feature: `intrinsics`.
	* rust/execute/torture/slice-magic2.rs: Add crate feature: `intrinsics`.
	* rust/execute/torture/str-layout1.rs: Add crate feature: `intrinsics`.
	* rust/execute/torture/transmute1.rs: Add crate feature: `intrinsics`.
	* rust/execute/torture/wrapping_op1.rs: Add crate feature: `intrinsics`.
	* rust/execute/torture/wrapping_op2.rs: Add crate feature: `intrinsics`.

Signed-off-by: Xiao Ma <mxlol233@outlook.com>
2023-02-14 11:20:23 +08:00
bors[bot]
cc23831ec6 Merge #1850 #1851
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>
2023-02-13 15:32:22 +00:00
Thomas Schwinge
2166e589d8 Update copyright years.
Update GCC/Rust files per 'contrib/update-copyright.py --this-year'.

Fixes: #1831
2023-02-13 16:22:28 +01:00
Thomas Schwinge
4ae5d1ec60 Merge commit '50335ddd301404e9053786b26a23a924471b4d09' into HEAD
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.
2023-02-13 14:47:05 +01:00
bors[bot]
73e6dac17f Merge #1847
1847: Merge upstream, last commit before 2023-01-31 GCC/Rust upstreaming r=tschwinge a=tschwinge



Co-authored-by: Andrea Corallo <andrea.corallo@arm.com>
Co-authored-by: Richard Biener <rguenther@suse.de>
Co-authored-by: Srinath Parvathaneni <srinath.parvathaneni@arm.com>
Co-authored-by: Iain Sandoe <iain@sandoe.co.uk>
Co-authored-by: François Dumont <fdumont@gcc.gnu.org>
Co-authored-by: Jason Merrill <jason@redhat.com>
Co-authored-by: Harald Anlauf <anlauf@gmx.de>
Co-authored-by: Marek Polacek <polacek@redhat.com>
Co-authored-by: GCC Administrator <gccadmin@gcc.gnu.org>
Co-authored-by: Lulu Cheng <chenglulu@loongson.cn>
Co-authored-by: Rainer Orth <ro@CeBiTec.Uni-Bielefeld.DE>
Co-authored-by: Jakub Jelinek <jakub@redhat.com>
Co-authored-by: Eric Biggers <ebiggers@google.com>
Co-authored-by: Xianmiao Qu <cooper.qu@linux.alibaba.com>
Co-authored-by: Andre Vieira <andre.simoesdiasvieira@arm.com>
2023-02-13 12:27:06 +00:00
bors[bot]
59d4ee6cc1 Merge #1750
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>
2023-02-13 11:15:24 +00:00
Thomas Schwinge
a7bd5c91f8 Adjust '.github/bors_log_expected_warnings' 2023-02-12 22:51:41 +01:00
Thomas Schwinge
d0a30acf3e Merge commit '9e56306f4d7c15e7667d8ac0b62ae6efb93ba756' into HEAD 2023-02-12 16:43:57 +01:00
Thomas Schwinge
ebecfbd351 Merge commit '83ffe9cde7fe0b4deb0d1b54175fd9b19c38179c' into HEAD
Conflicts:
	gcc/rust/rust-gcc-diagnostics.cc
	gcc/rust/typecheck/rust-hir-trait-ref.h
	gcc/rust/typecheck/rust-hir-type-check-toplevel.cc
	gcc/rust/typecheck/rust-hir-type-check-toplevel.h
	gcc/rust/typecheck/rust-tyctx.cc
	gcc/rust/typecheck/rust-tyty-rules.h

Upstream GCC commit r13-5197-g83ffe9cde7fe0b4deb0d1b54175fd9b19c38179c
"Update copyright years" did updated those files that don't exist in
GCC/Rust master branch anymore.
2023-02-12 16:37:19 +01:00
Thomas Schwinge
d4d6d573b4 Merge commit '83ffe9cde7fe0b4deb0d1b54175fd9b19c38179c^' into HEAD 2023-02-12 16:35:44 +01:00
Thomas Schwinge
2c454254ce Merge commit 'efce0caf2d75dff5a83812b8da2dd3725197ac7c' into HEAD 2023-02-12 16:34:59 +01:00
Thomas Schwinge
fb6b70e8bd Merge commit 'b0edfa0ef02c0f4820cec0601a4fd85aba516428' into HEAD 2023-02-12 16:34:43 +01:00
Thomas Schwinge
6144cf290f Merge commit 'b0edfa0ef02c0f4820cec0601a4fd85aba516428^' into HEAD 2023-02-12 16:34:35 +01:00
Thomas Schwinge
15c3184e88 Merge commit '02c031088ac0bbf716aec52e027d615b7a5a572b' into HEAD [#1704]
"Empty" merge: GCC/Rust #1704 commit 404cdd1eeb
"rust: fix link serialization [PR108113]"
and upstream GCC commit r13-4804-g02c031088ac0bbf716aec52e027d615b7a5a572b
"rust: fix link serialization [PR108113]" are identical.
2023-02-12 16:33:26 +01:00
Thomas Schwinge
6863cc3a23 Merge commit '02c031088ac0bbf716aec52e027d615b7a5a572b^' into HEAD 2023-02-12 16:29:21 +01:00
Thomas Schwinge
7d39b61800 Merge commit 'f80f540e394e87ac70349bad109bfc4b465c7c98' into HEAD [#1512]
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".
2023-02-12 16:28:14 +01:00
Thomas Schwinge
e9b5dc738b Merge commit 'f80f540e394e87ac70349bad109bfc4b465c7c98^' into HEAD 2023-02-12 16:27:19 +01:00
Thomas Schwinge
6d4f8ef1a1 Merge commit '4a1648084137f515eddd5dc087d5dfbf360a5bfa' into HEAD 2023-02-12 16:26:52 +01:00
Thomas Schwinge
b93418944e Merge commit '9cf9f3c7629d768d940d9f87cddcd616bb0449e0' into HEAD 2023-02-12 16:26:43 +01:00
Thomas Schwinge
ab1305234f Merge commit '9cf9f3c7629d768d940d9f87cddcd616bb0449e0^' into HEAD 2023-02-12 16:26:22 +01:00
Thomas Schwinge
09e9d996b0 Merge commit '95dc11475dac06b5eecd904079de8aa94827a36a' into HEAD [#1619]
Conflicts:
	gcc/rust/parse/rust-parse-impl.h

This overrides GCC/Rust #1619 commit db4b399c25
"parser: Fix ICE in closure parsing"
with upstream GCC commit r13-4697-g95dc11475dac06b5eecd904079de8aa94827a36a
"rust: Fix up aarch64-linux bootstrap [PR106072]".
2023-02-12 16:22:35 +01:00
Thomas Schwinge
81007c5254 Merge commit '95dc11475dac06b5eecd904079de8aa94827a36a^' into HEAD 2023-02-12 16:20:58 +01:00
bors[bot]
3a8c8d0d41 Merge #1820
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>
2023-02-10 11:40:27 +00:00
bors[bot]
0d5d7a66ac Merge #1810 #1823 #1824 #1837 #1839
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>
2023-02-10 10:17:07 +00:00
bors[bot]
bceb118bc2 Merge #1789
1789: Run workflow r=CohenArthur a=Parthib314

Fixes #1767 

Co-authored-by: Parthib <94271200+Parthib314@users.noreply.github.com>
2023-02-10 09:47:36 +00:00
bors[bot]
d4cce98350 Merge #1832
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>
2023-02-10 09:05:28 +00:00
Arthur Cohen
373a25382c ci: Revert bors running of commit checkers
ChangeLog:

	* .github/bors.toml: Remove checks for commit formats.
2023-02-10 10:07:03 +01:00
Abdul Rafey
c02a518fab fixed indentations in AST pretty expanded dump of trait gcc/rust/ChangeLog:
* ast/rust-ast-dump.cc (Dump::visit): removed extra indentations in trait ast dump

Signed-off-by: Abdul Rafey <abdulrafeyq@gmail.com>
2023-02-09 20:42:20 +05:30
Pierre-Emmanuel Patry
9762350b8c cli: Update safety warning message
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>
2023-02-09 11:55:12 +01:00
Pierre-Emmanuel Patry
7179562ff2 typecheck: Refactor rust-hir-trait-reference.h
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>
2023-02-08 16:28:04 +01:00
Arthur Cohen
f67f5409d2 expander: Add documentation for expand_eager_invocations
gcc/rust/ChangeLog:

	* expand/rust-macro-expand.cc (MacroExpander::expand_eager_invocations):
	Add documentation explaining the algorithm.
2023-02-08 12:23:06 +01:00
Arthur Cohen
c6db68ee15 macros: Perform macro expansion in a fixed-point fashion.
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.
2023-02-08 12:02:54 +01:00
Arthur Cohen
b9501cbe26 macro: Allow builtin MacroInvocations within the AST
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
2023-02-08 12:02:41 +01:00
Arthur Cohen
b1de4bb869 expansion: Add get_token_slice to MacroInvocLexer class
gcc/rust/ChangeLog:

	* expand/rust-macro-invoc-lexer.cc (MacroInvocLexer::get_token_slice):
	Add API to retrieve token slices when lexing macro expansions.
	* expand/rust-macro-invoc-lexer.h: Declare `get_token_slice`.
2023-02-08 12:02:40 +01:00
Arthur Cohen
51533ca765 parser: Expose parse_macro_invocation as public API
gcc/rust/ChangeLog:

	* parse/rust-parse.h: Move `parse_macro_invocation` to public API.
2023-02-08 12:02:40 +01:00
Arthur Cohen
d555ef1800 rust-item: include rust-expr.h
gcc/rust/ChangeLog:

	* ast/rust-item.h (class BlockExpr): Remove forward declaration of
	class `BlockExpr`.
2023-02-08 12:02:40 +01:00
Owen Avery
d9eb2eb73c Add support for TuplePattern in let statements
gcc/rust/ChangeLog:

	* hir/tree/rust-hir-pattern.h
	(TuplePatternItemsRanged::get_lower_patterns): Add method.
	(TuplePatternItemsRanged::get_upper_patterns): Add method.
	* backend/rust-compile-pattern.cc
	(CompilePatternLet::visit): Implement TuplePattern visitor.
	* backend/rust-compile-pattern.h
	(CompilePatternLet::visit): Move TuplePattern visitor out of header file.

gcc/testsuite/ChangeLog:

	* rust/execute/torture/let-pattern-1.rs: New test.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-02-06 00:24:31 -05:00
Arthur Cohen
7f66312db4 ci: Require commits check to pass for bors to merge and fix CI names
ChangeLog:

	* .github/bors.toml: Add commit checkers.
	* .github/workflows/commit-format.yml: Rename commit checker jobs.
2023-02-05 09:12:09 +01:00
bors[bot]
8f1fce4916 Merge #1739
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>
2023-02-05 00:56:44 +00:00
Philip Herron
6d7a7b2288 gccrs: Add general TypeBounds checks
Existing tests are updated to use libcore copy and clone implementation.

Addresses #1725

Signed-off-by: Philip Herron <herron.philip@googlemail.com>

gcc/rust/ChangeLog:

	* typecheck/rust-unify.cc (UnifyRules::go): ensure the bounds are checked

gcc/testsuite/ChangeLog:

	* rust/compile/torture/intrinsics-4.rs: implement Copy trait
	* rust/compile/torture/intrinsics-5.rs: likewise
	* rust/execute/torture/atomic_load.rs: likewise
	* rust/execute/torture/atomic_store.rs: likewise
	* rust/bounds1.rs: New test.
2023-02-05 00:10:49 +00:00
Philip Herron
1b0794c172 gccrs: Remove bad error message on checking function arguments
Signed-off-by: Philip Herron <herron.philip@googlemail.com>

gcc/rust/ChangeLog:

	* typecheck/rust-tyty-call.cc (TypeCheckCallExpr::visit): remove error message

gcc/testsuite/ChangeLog:

	* rust/compile/func3.rs: update test case
2023-02-05 00:10:49 +00:00
Philip Herron
aff069dfb1 gccrs: Fix higher ranked trait bounds computation of self
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
2023-02-05 00:10:48 +00:00
Philip Herron
d4e6b64e7f gccrs: Add missing Sized, Copy and Clone lang item mappings
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.
2023-02-05 00:10:48 +00:00
Philip Herron
e612713029 gccrs: Fix nullptr dereference
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
2023-02-05 00:10:48 +00:00
Philip Herron
95fa967f5c gccrs: Refactor the type unification code
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
2023-02-05 00:10:48 +00:00
Philip Herron
edcf5b63bf gccrs: Remove monomorphization hack to setup possible associated types
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.
2023-02-05 00:10:48 +00:00
Philip Herron
b5719d74b3 gccrs: Add missing param subst callback
Signed-off-by: Philip Herron <herron.philip@googlemail.com>

gcc/rust/ChangeLog:

	* typecheck/rust-tyty-subst.cc: add missing callback
2023-02-05 00:10:48 +00:00
Philip Herron
fc6c5f7dc2 gccrs: Clear the substitution callbacks when copying ArgumentMappings
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
2023-02-05 00:10:48 +00:00
Philip Herron
50856ddba4 gccrs: Refactor handle_substitutions to take a reference
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
2023-02-05 00:10:48 +00:00
Philip Herron
82d0550253 gccrs: Rename header rust-hir-trait-ref.h to rust-hir-trait-reference.h
Signed-off-by: Philip Herron <herron.philip@googlemail.com>

gcc/rust/ChangeLog:

	* typecheck/rust-hir-trait-ref.h: Moved to...
	* typecheck/rust-hir-trait-reference.h: ...here.
	* typecheck/rust-hir-trait-resolve.cc: refactor
	* typecheck/rust-hir-trait-resolve.h (RUST_HIR_TRAIT_RESOLVE_H): likewise
	* typecheck/rust-hir-type-check.h: likewise
	* typecheck/rust-tyty.cc: likewise
2023-02-05 00:10:48 +00:00
Philip Herron
56a21f487f gccrs: Rename rust-tyctx.cc to rust-typecheck-context.cc
Signed-off-by: Philip Herron <herron.philip@googlemail.com>

gcc/rust/ChangeLog:

	* Make-lang.in: update name
	* typecheck/rust-tyctx.cc: Moved to...
	* typecheck/rust-typecheck-context.cc: ...here.
2023-02-05 00:10:47 +00:00
Philip Herron
5ea0f26bab gccrs: Refactor all code out of the rust-tyty.h header
Signed-off-by: Philip Herron <herron.philip@googlemail.com>

gcc/rust/ChangeLog:

	* typecheck/rust-hir-type-check.h: refactor
	* typecheck/rust-tyctx.cc (TypeCheckContext::iterate): refactor
	(TypeCheckContext::have_loop_context): likewise
	(TypeCheckContext::push_new_loop_context): likewise
	(TypeCheckContext::push_new_while_loop_context): likewise
	(TypeCheckContext::peek_loop_context): likewise
	(TypeCheckContext::pop_loop_context): likewise
	(TypeCheckContext::swap_head_loop_context): likewise
	(TypeCheckContext::insert_trait_reference): likewise
	(TypeCheckContext::lookup_trait_reference): likewise
	(TypeCheckContext::insert_receiver): likewise
	(TypeCheckContext::lookup_receiver): likewise
	(TypeCheckContext::insert_associated_type_mapping): likewise
	(TypeCheckContext::clear_associated_type_mapping): likewise
	(TypeCheckContext::lookup_associated_type_mapping): likewise
	(TypeCheckContext::insert_variant_definition): likewise
	(TypeCheckContext::lookup_variant_definition): likewise
	(TypeCheckContext::insert_operator_overload): likewise
	(TypeCheckContext::lookup_operator_overload): likewise
	(TypeCheckContext::insert_unconstrained_check_marker): likewise
	(TypeCheckContext::have_checked_for_unconstrained): likewise
	(TypeCheckContext::insert_resolved_predicate): likewise
	(TypeCheckContext::lookup_predicate): likewise
	(TypeCheckContext::insert_query): likewise
	(TypeCheckContext::query_completed): likewise
	(TypeCheckContext::query_in_progress): likewise
	(TypeCheckContext::insert_trait_query): likewise
	(TypeCheckContext::trait_query_completed): likewise
	(TypeCheckContext::trait_query_in_progress): likewise
	(TypeCheckContextItem::Item::Item): likewise
	(TypeCheckContextItem::TypeCheckContextItem): likewise
	(TypeCheckContextItem::get_item): likewise
	(TypeCheckContextItem::get_impl_item): likewise
	(TypeCheckContextItem::get_trait_item): likewise
	(TypeCheckContextItem::get_type): likewise
	* typecheck/rust-tyty.cc (StructFieldType::StructFieldType): likewise
	(StructFieldType::get_ref): likewise
	(StructFieldType::get_name): likewise
	(StructFieldType::get_field_type): likewise
	(StructFieldType::set_field_type): likewise
	(StructFieldType::is_concrete): likewise
	(StructFieldType::debug): likewise
	(StructFieldType::get_locus): likewise
	(VariantDef::variant_type_string): likewise
	(VariantDef::VariantDef): likewise
	(VariantDef::operator=): likewise
	(VariantDef::get_error_node): likewise
	(VariantDef::is_error): likewise
	(VariantDef::get_id): likewise
	(VariantDef::get_defid): likewise
	(VariantDef::get_variant_type): likewise
	(VariantDef::is_data_variant): likewise
	(VariantDef::is_dataless_variant): likewise
	(VariantDef::get_identifier): likewise
	(VariantDef::num_fields): likewise
	(VariantDef::get_field_at_index): likewise
	(VariantDef::get_fields): likewise
	(VariantDef::lookup_field): likewise
	(VariantDef::get_discriminant): likewise
	(VariantDef::as_string): likewise
	(VariantDef::is_equal): likewise
	(VariantDef::clone): likewise
	(VariantDef::monomorphized_clone): likewise
	(VariantDef::get_ident): likewise
	(TupleType::TupleType): likewise
	(TupleType::get_unit_type): likewise
	(TupleType::is_unit): likewise
	(TupleType::num_fields): likewise
	(TupleType::is_concrete): likewise
	(TupleType::get_fields): likewise
	(BoolType::BoolType): likewise
	(BoolType::get_name): likewise
	(BoolType::is_concrete): likewise
	(IntType::IntType): likewise
	(IntType::get_name): likewise
	(IntType::get_int_kind): likewise
	(IntType::is_concrete): likewise
	(UintType::UintType): likewise
	(UintType::get_name): likewise
	(UintType::get_uint_kind): likewise
	(UintType::is_concrete): likewise
	(FloatType::FloatType): likewise
	(FloatType::get_name): likewise
	(FloatType::get_float_kind): likewise
	(FloatType::is_concrete): likewise
	(USizeType::USizeType): likewise
	(USizeType::get_name): likewise
	(USizeType::is_concrete): likewise
	(ISizeType::ISizeType): likewise
	(ISizeType::get_name): likewise
	(ISizeType::is_concrete): likewise
	(CharType::CharType): likewise
	(CharType::is_concrete): likewise
	(CharType::get_name): likewise
	(ReferenceType::ReferenceType): likewise
	(ReferenceType::is_concrete): likewise
	(ReferenceType::mutability): likewise
	(ReferenceType::is_mutable): likewise
	(ReferenceType::is_dyn_object): likewise
	(ReferenceType::is_dyn_slice_type): likewise
	(ReferenceType::is_dyn_str_type): likewise
	(PointerType::PointerType): likewise
	(PointerType::is_concrete): likewise
	(PointerType::mutability): likewise
	(PointerType::is_mutable): likewise
	(PointerType::is_const): likewise
	(PointerType::is_dyn_object): likewise
	(PointerType::is_dyn_slice_type): likewise
	(PointerType::is_dyn_str_type): likewise
	(ParamType::ParamType): likewise
	(ParamType::get_generic_param): likewise
	(ParamType::can_resolve): likewise
	(ParamType::is_concrete): likewise
	(StrType::StrType): likewise
	(StrType::get_name): likewise
	(StrType::is_concrete): likewise
	(NeverType::NeverType): likewise
	(NeverType::get_name): likewise
	(NeverType::is_unit): likewise
	(NeverType::is_concrete): likewise
	(PlaceholderType::PlaceholderType): likewise
	(PlaceholderType::get_name): likewise
	(PlaceholderType::is_unit): likewise
	(PlaceholderType::get_symbol): likewise
	(PlaceholderType::is_concrete): likewise
	(ProjectionType::is_unit): likewise
	(ProjectionType::get_name): likewise
	(ProjectionType::needs_generic_substitutions): likewise
	(ProjectionType::supports_substitutions): likewise
	(ProjectionType::has_subsititions_defined): likewise
	(ProjectionType::get): likewise
	(ProjectionType::is_concrete): likewise
	(DynamicObjectType::is_concrete): likewise
	* typecheck/rust-tyty.h: likewise
2023-02-05 00:10:47 +00:00
Philip Herron
d5d70e3fa6 gccrs: Refactor PathProbeType code into CC file
Signed-off-by: Philip Herron <herron.philip@googlemail.com>

gcc/rust/ChangeLog:

	* typecheck/rust-hir-path-probe.cc (PathProbeCandidate::Candidate::Candidate): refactor
	(PathProbeCandidate::PathProbeCandidate): likewise
	(PathProbeCandidate::as_string): likewise
	(PathProbeCandidate::is_enum_candidate): likewise
	(PathProbeCandidate::is_impl_candidate): likewise
	(PathProbeCandidate::is_trait_candidate): likewise
	(PathProbeCandidate::is_full_trait_item_candidate): likewise
	(PathProbeCandidate::get_error): likewise
	(PathProbeCandidate::is_error): likewise
	(PathProbeCandidate::get_defid): likewise
	(PathProbeCandidate::operator<): likewise
	* typecheck/rust-hir-path-probe.h (struct PathProbeCandidate): likewise
2023-02-05 00:10:47 +00:00
Philip Herron
3e044eb0d5 gccrs: Refactor PathProbe into cc file
Signed-off-by: Philip Herron <herron.philip@googlemail.com>

gcc/rust/ChangeLog:

	* typecheck/rust-hir-path-probe.cc (PathProbeType::PathProbeType): refactor
	(PathProbeType::Probe): likewise
	(PathProbeType::visit): likewise
	(PathProbeType::process_enum_item_for_candiates): likewise
	(PathProbeType::process_impl_items_for_candidates): likewise
	(PathProbeType::is_reciever_generic): likewise
	(PathProbeImplTrait::PathProbeImplTrait): likewise
	(PathProbeImplTrait::Probe): likewise
	(PathProbeImplTrait::process_trait_impl_items_for_candidates): likewise
	* typecheck/rust-hir-path-probe.h (struct PathProbeCandidate): likewise
	* typecheck/rust-hir-trait-resolve.cc
	(PathProbeImplTrait::process_trait_impl_items_for_candidates): likewise
2023-02-05 00:10:47 +00:00
Philip Herron
725a25a197 gccrs: Refactor BaseType, InferType and ErrorType impl into cc file
Signed-off-by: Philip Herron <herron.philip@googlemail.com>

gcc/rust/ChangeLog:

	* typecheck/rust-tyty.cc (BaseType::BaseType): refactor
	(BaseType::~BaseType): likewise
	(BaseType::get_ref): likewise
	(BaseType::set_ref): likewise
	(BaseType::get_ty_ref): likewise
	(BaseType::set_ty_ref): likewise
	(BaseType::is_equal): likewise
	(BaseType::is_unit): likewise
	(BaseType::get_kind): likewise
	(BaseType::get_combined_refs): likewise
	(BaseType::append_reference): likewise
	(BaseType::supports_substitutions): likewise
	(BaseType::has_subsititions_defined): likewise
	(BaseType::can_substitute): likewise
	(BaseType::needs_generic_substitutions): likewise
	(BaseType::contains_type_parameters): likewise
	(BaseType::get_ident): likewise
	(BaseType::get_locus): likewise
	(InferType::InferType): likewise
	(InferType::get_infer_kind): likewise
	(InferType::get_name): likewise
	(InferType::is_concrete): likewise
	(ErrorType::ErrorType): likewise
	(ErrorType::is_unit): likewise
	(ErrorType::is_concrete): likewise
	(ErrorType::get_name): likewise
	(ErrorType::monomorphized_clone): likewise
	* typecheck/rust-tyty.h (class SubstitutionArgumentMappings): likewise
2023-02-05 00:10:47 +00:00
Philip Herron
1cd74211cc gccrs: Refactor all substitution mapper code implementation into its own CC file
Signed-off-by: Philip Herron <herron.philip@googlemail.com>

gcc/rust/ChangeLog:

	* typecheck/rust-substitution-mapper.cc (SubstMapper::SubstMapper): refactor
	(SubstMapper::Resolve): likewise
	(SubstMapper::InferSubst): likewise
	(SubstMapper::have_generic_args): likewise
	(SubstMapper::visit): likewise
	(SubstMapperInternal::visit): likewise
	(SubstMapperFromExisting::SubstMapperFromExisting): likewise
	(SubstMapperFromExisting::Resolve): likewise
	(SubstMapperFromExisting::visit): likewise
	(GetUsedSubstArgs::GetUsedSubstArgs): likewise
	(GetUsedSubstArgs::From): likewise
	(GetUsedSubstArgs::visit): likewise
	* typecheck/rust-substitution-mapper.h: refactor
	* typecheck/rust-tyty-subst.cc (SubstitutionParamMapping::get_generic_param): likewise
2023-02-05 00:09:57 +00:00
Philip Herron
fba98d61c3 gccrs: Refactor SubstitutionRef base class into its own CC file
Signed-off-by: Philip Herron <herron.philip@googlemail.com>

gcc/rust/ChangeLog:

	* Make-lang.in: update the makefile
	* typecheck/rust-tyty.cc (SubstitutionParamMapping::need_substitution): likewise
	(SubstitutionParamMapping::override_context): likewise
	(SubstitutionRef::get_mappings_from_generic_args): likewise
	(SubstitutionRef::infer_substitions): likewise
	(SubstitutionRef::are_mappings_bound): likewise
	(SubstitutionRef::solve_missing_mappings_from_this): likewise
	(SubstitutionRef::monomorphize): likewise
	* typecheck/rust-tyty.h (class SubstitutionParamMapping): likewise
	(class SubstitutionArg): likewise
	(std::function<void): likewise
	(class SubstitutionArgumentMappings): likewise
	(class SubstitutionRef): likewise
	* typecheck/rust-tyty-subst.cc: New file.
	* typecheck/rust-tyty-subst.h: New file.
2023-02-05 00:06:43 +00:00
Philip Herron
1fbf184bb9 gccrs: Refactor TyVar and TypeBoundPredicates
This extract these helpers into seperate files

Signed-off-by: Philip Herron <herron.philip@googlemail.com>

gcc/rust/ChangeLog:

	* Make-lang.in: update makefile
	* typecheck/rust-tyty.cc (TyVar::TyVar): move to new file
	(TyVar::get_tyty): likewise
	(TyVar::get_implicit_infer_var): likewise
	(TyVar::subst_covariant_var): likewise
	(TyVar::clone): likewise
	(TyVar::monomorphized_clone): likewise
	(TyWithLocation::TyWithLocation): likewise
	* typecheck/rust-tyty.h (class BaseType): cleanup
	(class TypeBoundPredicate): move to its own file
	(class TypeBoundPredicateItem): likewise
	(class TypeBoundsMappings): likewise
	(class TyVar): likewise
	(class TyWithLocation): likewise
	* typecheck/rust-tyty-bounds.h: New file.
	* typecheck/rust-tyty-util.cc: New file.
	* typecheck/rust-tyty-util.h: New file.
2023-02-05 00:06:43 +00:00
Philip Herron
8e9f9807f3 gccrs: Move TypePredicateItem impl out of the header
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
2023-02-05 00:06:43 +00:00
Philip Herron
bf724a30cc gccrs: Add another test case for passing associated type-bounds
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>
2023-02-05 00:06:36 +00:00
bors[bot]
47a9a9e949 Merge #1826
1826: Removed comment copy-pasted from gcc/tree.def r=philberty a=powerboat9

Addresses #1640.

Co-authored-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-02-04 23:42:46 +00:00
Owen Avery
7ffdfcbd24 Removed comment copy-pasted from gcc/tree.def
gcc/rust/ChangeLog:

	* backend/rust-compile-expr.cc (CompileExpr::visit): Removed copy-pasted comment.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-02-04 12:07:38 -05:00
bors[bot]
8d96698ffc Merge #1818
1818: Implement lowering ReferencePattern from AST to HIR r=CohenArthur a=powerboat9

gcc/rust/ChangeLog:

	* ast/rust-pattern.h (ReferencePattern::get_has_two_amps): Add method. (ReferencePattern::get_is_mut): Add method.
	* hir/rust-ast-lower-pattern.cc (ASTLoweringPattern::visit): Add ReferencePattern visitor.
	* hir/rust-ast-lower-pattern.h (ASTLoweringPattern::visit): Add ReferencePattern visitor.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>

Partially addresses #1813

Co-authored-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-02-03 20:17:06 +00:00
bors[bot]
868b0626e5 Merge #1737
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>
2023-02-03 17:04:01 +00:00
bors[bot]
278f7616ef Merge #1698
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>
2023-02-03 13:28:26 +00:00
mxlol233
c255fb2ca2 Add support for feature check.
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>
2023-02-03 21:28:04 +08:00
Parthib
0d6b11551b Moving Functions from rust-gcc-diagnostics to rust-diagnostics.cc
gcc/rust/ChangeLog:

	* Make-lang.in: Modified
	* rust-diagnostics.cc (rust_be_get_quotechars): Added
		(rust_be_internal_error_at): Added
		(rust_be_error_at): Added
		(class rust_error_code_rule): Added
		(rust_be_warning_at): Added
		(rust_be_fatal_error): Added
		(rust_be_inform): Added
		(rust_be_debug_p): Added

	* rust-gcc-diagnostics.cc: Removed
2023-02-03 18:21:42 +05:30
bors[bot]
1f96413438 Merge #1812
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>
2023-02-03 12:45:58 +00:00
bors[bot]
71bd5b2272 Merge #1816
1816: Move rust-buffered-queue.h to util folder #1766 r=CohenArthur a=drmahad

### gcc/rust/ChangeLog:

- 	rust-buffered-queue.h
- 	Moved to util/rust-buffered-queue.h.

Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>


Co-authored-by: MAHAD <mahadtxt@gmail.com>
2023-02-03 11:03:52 +00:00
Arthur Cohen
38bad2bf21 parser: Fix parsing of closure param list
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.
2023-02-03 11:50:00 +01:00
Arthur Cohen
d600227704 parser: Improve parsing of complex generic arguments
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.
2023-02-03 11:49:11 +01:00
bors[bot]
776c4247de Merge #1783
1783: Remove HIR::GroupedPattern r=philberty a=powerboat9

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>

Removes HIR::GroupedPattern and lowers AST::GroupedPattern to its inner pattern directly. Addresses https://github.com/Rust-GCC/gccrs/pull/1771#pullrequestreview-1271272084

Co-authored-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-02-02 18:29:46 +00:00
Owen Avery
1b46cfb35a Implement lowering ReferencePattern from AST to HIR
gcc/rust/ChangeLog:

	* ast/rust-pattern.h:
	(ReferencePattern::is_double_reference): Add method.
	(ReferencePattern::get_is_mut): Add method.
	* hir/rust-ast-lower-pattern.cc
	(ASTLoweringPattern::visit): Add ReferencePattern visitor.
	* hir/rust-ast-lower-pattern.h:
	(ASTLoweringPattern::visit): Add ReferencePattern visitor.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-02-02 12:35:10 -05:00
Owen Avery
595eacc993 Optimize HIR::ReferencePattern
gcc/rust/ChangeLog:

	* hir/tree/rust-hir-pattern.h
	(class ReferencePattern): Remove has_two_amps field.
	* hir/tree/rust-hir-full-test.cc
	(ReferencePattern::as_string): Remove usage of ReferencePattern::has_two_amps.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-02-02 12:34:22 -05:00
Owen Avery
8437757f77 Remove HIR::GroupedPattern
gcc/rust/ChangeLog:

	* backend/rust-compile-fnparam.h
	(CompileFnParam::visit): Remove HIR::GroupedPattern visitor.
	* backend/rust-compile-pattern.cc
	(CompilePatternCaseLabelExpr::visit): Remove HIR::GroupedPattern visitor.
	(CompilePatternBindings::visit): Remove HIR::GroupedPattern visitor.
	* backend/rust-compile-pattern.h
	(CompilePatternCaseLabelExpr::visit): Remove HIR::GroupedPattern visitor.
	(CompilePatternBindings::visit): Remove HIR::GroupedPattern visitor.
	(CompilePatternLet::visit): Remove HIR::GroupedPattern visitor.
	* backend/rust-compile-resolve-path.h
	(ResolvePathRef::visit): Remove HIR::GroupedPattern visitor.
	* backend/rust-compile-var-decl.h
	(CompileVarDecl::visit): Remove HIR::GroupedPattern visitor.
	* checks/errors/rust-const-checker.cc
	(ConstChecker::visit): Remove HIR::GroupedPattern visitor.
	* checks/errors/rust-const-checker.h
	(ConstChecker::visit): Remove HIR::GroupedPattern visitor.
	* checks/errors/rust-unsafe-checker.cc
	(UnsafeChecker::visit): Remove HIR::GroupedPattern visitor.
	* checks/errors/rust-unsafe-checker.h
	(UnsafeChecker::visit): Remove HIR::GroupedPattern visitor.
	* hir/rust-hir-dump.cc (Dump::visit): Remove HIR::GroupedPattern visitor.
	* hir/rust-hir-dump.h (Dump::visit): Remove HIR::GroupedPattern visitor.
	* hir/tree/rust-hir-full-decls.h (class GroupedPattern): Remove class.
	* hir/tree/rust-hir-full-test.cc (GroupedPattern::accept_vis): Remove method.
	* hir/tree/rust-hir-pattern.h (class GroupedPattern): Remove class.
	* hir/tree/rust-hir-visitor.h
	(HIRFullVisitor::visit): Remove HIR::GroupedPattern visitor.
	(HIRFullVisitorBase::visit): Remove HIR::GroupedPattern visitor.
	(HIRPatternVisitor::visit): Remove HIR::GroupedPattern visitor.
	* typecheck/rust-hir-type-check-pattern.cc
	(TypeCheckPattern::visit): Remove HIR::GroupedPattern visitor.
	* typecheck/rust-hir-type-check-pattern.h
	(TypeCheckPattern::visit): Remove HIR::GroupedPattern visitor.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-02-01 23:38:08 -05:00
Owen Avery
a26b897b44 Improve GroupedPattern lowering
gcc/rust/ChangeLog:

	* hir/rust-ast-lower-pattern.cc
	(ASTLoweringPattern::visit): Lower AST::GroupedPattern to its inner pattern.

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-02-01 23:38:07 -05:00
MAHAD
30e80e860a Move rust-buffered-queue.h to util folder #1766
gcc/rust/ChangeLog:

	* rust-buffered-queue.h: Moved to...
	* util/rust-buffered-queue.h: ...here.

Signed-off-by: Muhammad Mahad <mahadtxt@gmail.com>
2023-02-02 07:21:49 +05:00
ArshErgon
d10d3dc997 ci: update ubuntu version
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.
2023-02-01 18:58:36 +01:00
bors[bot]
a9422b51c1 Merge #1811
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>
2023-02-01 14:24:35 +00:00
Arthur Cohen
cddb1f2d9f parser: Allow parsing multiple reference types
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.
2023-02-01 11:47:28 +01:00
Thomas Schwinge
9b7fe56826 Merge commit 'edc676cfe8988c62c81b0df224c7fe82583012b1' into HEAD
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.
2023-02-01 10:34:30 +01:00
bors[bot]
7f222689dc Merge #1788
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>
2023-01-31 21:46:24 +00:00
Arthur Cohen
c146eb7d99 ci: Add commit format checker 2023-01-31 15:49:35 +01:00
bors[bot]
d0dad09f5d Merge #1775
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>
2023-01-30 23:46:48 +00:00
Owen Avery
a731476b50 Create and use CompilePatternLet visitor for compiling let statments
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-01-30 15:18:15 -05:00
bors[bot]
026e20b1dc Merge #1776
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>
2023-01-30 13:27:16 +00:00
bors[bot]
d7c321da9f Merge #1735
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>
2023-01-30 12:44:25 +00:00
Arthur Cohen
3630e0e2bf macro: Allow builtin MacroInvocations within the AST
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): Likewise.
	(Parser::parse_type_no_bounds): Likewise.
2023-01-30 13:47:35 +01:00
bors[bot]
0ae13efb5a Merge #1778
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>
2023-01-30 11:41:57 +00:00
Abdul Rafey
d17212591a fixed compiler error message on wildcard pattern within expression
Signed-off-by: Abdul Rafey <abdulrafeyq@gmail.com>
2023-01-30 16:15:50 +05:30
Abdul Rafey
e66cb001dc moved operator.h to util/rust-operators.h
Signed-off-by: Abdul Rafey <abdulrafeyq@gmail.com>
2023-01-30 16:06:00 +05:30
bors[bot]
d12a38da68 Merge #1777
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>
2023-01-30 09:06:03 +00:00
Parthib
2ad7c1ca0e Rename file rust-ast-full-test.cc to rust-ast.cc 2023-01-28 22:07:45 +05:30
bors[bot]
21ec24265b Merge #1759
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>
2023-01-27 16:10:43 +00:00
bors[bot]
d4f6a97c62 Merge #1772
1772: Added missing GroupedPattern visitors for code generation r=philberty a=powerboat9

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>

Implements some missing visitor methods for GroupedPattern compilation.

Co-authored-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-01-27 15:25:48 +00:00
Owen Avery
2ba4506b67 Added missing GroupedPattern visitors for code generation
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-01-26 12:04:15 -05:00
bors[bot]
fe828b4f93 Merge #1771
1771: Add type resolution for grouped patterns r=philberty a=powerboat9

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>

Adds type resolution for GroupedPattern.

Co-authored-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-01-26 15:28:46 +00:00
Owen Avery
01a07f7d39 Add type resolution for grouped patterns
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-01-25 13:12:28 -05:00
Owen Avery
248316afc3 Add get_item method for HIR::GroupedPattern
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-01-25 13:12:27 -05:00
bors[bot]
a91b12e2c4 Merge #1769
1769: Add HIR lowering for GroupedPattern r=philberty a=powerboat9

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>

Implements HIR lowering for grouped patterns.

Co-authored-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-01-25 09:49:08 +00:00
Owen Avery
ea7893625e Add HIR lowering for GroupedPattern
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-01-24 13:38:27 -05:00
bors[bot]
6a320bca7b Merge #1763
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>
2023-01-24 16:39:54 +00:00
bors[bot]
7558c183a1 Merge #1760
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>
2023-01-24 15:52:01 +00:00
Lyra
fc0c03dcf7 Do not crash on empty macros expand. Fixes #1712
This commit fixes a compiler crash when expanding an empty macro into an existing AST.

Signed-off-by: Lyra Karenai <teromene@teromene.fr>
2023-01-24 15:05:09 +01:00
Owen Avery
a194ee1dcb Support GroupedPattern during name resolution
Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-01-23 16:25:40 -05:00
vagrant
53c0231c78 Revert 10-second timeout for each test 2023-01-21 18:33:07 +00:00
bors[bot]
01c232573e Merge #1732
1732: testsuite: Handle Windows carriage returns properly r=CohenArthur a=CohenArthur

In dg-output, check for \r* carriage returns to make sure execution tests pass on windows platforms

gcc/testsuite/ChangeLog:

	* rust/execute/torture/builtin_macro_cfg.rs: Handle carriage returns properly
	* rust/execute/torture/builtin_macro_concat.rs: Handle carriage returns properly
	* rust/execute/torture/builtin_macro_env.rs: Handle carriage returns properly
	* rust/execute/torture/builtin_macro_include_bytes.rs: Handle carriage returns properly
	* rust/execute/torture/builtin_macro_include_str.rs: Handle carriage returns properly
	* rust/execute/torture/builtin_macro_line.rs: Handle carriage returns properly
	* rust/execute/torture/builtin_macros1.rs: Handle carriage returns properly
	* rust/execute/torture/builtin_macros3.rs: Handle carriage returns properly
	* rust/execute/torture/cfg1.rs: Handle carriage returns properly
	* rust/execute/torture/cfg2.rs: Handle carriage returns properly
	* rust/execute/torture/cfg3.rs: Handle carriage returns properly
	* rust/execute/torture/cfg4.rs: Handle carriage returns properly
	* rust/execute/torture/coercion1.rs: Handle carriage returns properly
	* rust/execute/torture/coercion2.rs: Handle carriage returns properly
	* rust/execute/torture/extern_mod4.rs: Handle carriage returns properly
	* rust/execute/torture/helloworld1.rs: Handle carriage returns properly
	* rust/execute/torture/helloworld2.rs: Handle carriage returns properly
	* rust/execute/torture/issue-1198.rs: Handle carriage returns properly
	* rust/execute/torture/issue-1231.rs: Handle carriage returns properly
	* rust/execute/torture/issue-1232.rs: Handle carriage returns properly
	* rust/execute/torture/issue-1249.rs: Handle carriage returns properly
	* rust/execute/torture/issue-1436.rs: Handle carriage returns properly
	* rust/execute/torture/issue-1496.rs: Handle carriage returns properly
	* rust/execute/torture/issue-647.rs: Handle carriage returns properly
	* rust/execute/torture/issue-845.rs: Handle carriage returns properly
	* rust/execute/torture/issue-851.rs: Handle carriage returns properly
	* rust/execute/torture/issue-858.rs: Handle carriage returns properly
	* rust/execute/torture/issue-976.rs: Handle carriage returns properly
	* rust/execute/torture/macros10.rs: Handle carriage returns properly
	* rust/execute/torture/macros11.rs: Handle carriage returns properly
	* rust/execute/torture/macros12.rs: Handle carriage returns properly
	* rust/execute/torture/macros13.rs: Handle carriage returns properly
	* rust/execute/torture/macros14.rs: Handle carriage returns properly
	* rust/execute/torture/macros2.rs: Handle carriage returns properly
	* rust/execute/torture/macros22.rs: Handle carriage returns properly
	* rust/execute/torture/macros29.rs: Handle carriage returns properly
	* rust/execute/torture/macros3.rs: Handle carriage returns properly
	* rust/execute/torture/macros30.rs: Handle carriage returns properly
	* rust/execute/torture/macros31.rs: Handle carriage returns properly
	* rust/execute/torture/macros7.rs: Handle carriage returns properly
	* rust/execute/torture/macros8.rs: Handle carriage returns properly
	* rust/execute/torture/macros9.rs: Handle carriage returns properly
	* rust/execute/torture/match1.rs: Handle carriage returns properly
	* rust/execute/torture/match2.rs: Handle carriage returns properly
	* rust/execute/torture/match3.rs: Handle carriage returns properly
	* rust/execute/torture/match_bool1.rs: Handle carriage returns properly
	* rust/execute/torture/match_byte1.rs: Handle carriage returns properly
	* rust/execute/torture/match_char1.rs: Handle carriage returns properly
	* rust/execute/torture/match_int1.rs: Handle carriage returns properly
	* rust/execute/torture/match_loop1.rs: Handle carriage returns properly
	* rust/execute/torture/match_range1.rs: Handle carriage returns properly
	* rust/execute/torture/match_range2.rs: Handle carriage returns properly
	* rust/execute/torture/match_tuple1.rs: Handle carriage returns properly
	* rust/execute/torture/method1.rs: Handle carriage returns properly
	* rust/execute/torture/method2.rs: Handle carriage returns properly
	* rust/execute/torture/method3.rs: Handle carriage returns properly
	* rust/execute/torture/method4.rs: Handle carriage returns properly
	* rust/execute/torture/operator_overload_1.rs: Handle carriage returns properly
	* rust/execute/torture/operator_overload_10.rs: Handle carriage returns properly
	* rust/execute/torture/operator_overload_11.rs: Handle carriage returns properly
	* rust/execute/torture/operator_overload_12.rs: Handle carriage returns properly
	* rust/execute/torture/operator_overload_2.rs: Handle carriage returns properly
	* rust/execute/torture/operator_overload_4.rs: Handle carriage returns properly
	* rust/execute/torture/operator_overload_5.rs: Handle carriage returns properly
	* rust/execute/torture/operator_overload_6.rs: Handle carriage returns properly
	* rust/execute/torture/operator_overload_7.rs: Handle carriage returns properly
	* rust/execute/torture/operator_overload_8.rs: Handle carriage returns properly
	* rust/execute/torture/operator_overload_9.rs: Handle carriage returns properly
	* rust/execute/torture/str-layout1.rs: Handle carriage returns properly
	* rust/execute/torture/str-zero.rs: Handle carriage returns properly
	* rust/execute/torture/trait1.rs: Handle carriage returns properly
	* rust/execute/torture/trait10.rs: Handle carriage returns properly
	* rust/execute/torture/trait11.rs: Handle carriage returns properly
	* rust/execute/torture/trait12.rs: Handle carriage returns properly
	* rust/execute/torture/trait13.rs: Handle carriage returns properly
	* rust/execute/torture/trait2.rs: Handle carriage returns properly
	* rust/execute/torture/trait3.rs: Handle carriage returns properly
	* rust/execute/torture/trait4.rs: Handle carriage returns properly
	* rust/execute/torture/trait5.rs: Handle carriage returns properly
	* rust/execute/torture/trait6.rs: Handle carriage returns properly
	* rust/execute/torture/trait7.rs: Handle carriage returns properly
	* rust/execute/torture/trait8.rs: Handle carriage returns properly
	* rust/execute/torture/trait9.rs: Handle carriage returns properly

Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
2023-01-20 08:36:23 +00:00
Arthur Cohen
22343f79c0 testsuite: Handle Windows carriage returns properly
In dg-output, check for \r* carriage returns to make sure execution
tests pass on windows platforms

gcc/testsuite/ChangeLog:

	* rust/execute/torture/builtin_macro_cfg.rs: Handle carriage returns
		properly.
	* rust/execute/torture/builtin_macro_concat.rs: Likewise.
	* rust/execute/torture/builtin_macro_env.rs: Likewise.
	* rust/execute/torture/builtin_macro_include_bytes.rs: Likewise.
	* rust/execute/torture/builtin_macro_include_str.rs: Likewise.
	* rust/execute/torture/builtin_macro_line.rs: Likewise.
	* rust/execute/torture/builtin_macros1.rs: Likewise.
	* rust/execute/torture/builtin_macros3.rs: Likewise.
	* rust/execute/torture/cfg1.rs: Likewise.
	* rust/execute/torture/cfg2.rs: Likewise.
	* rust/execute/torture/cfg3.rs: Likewise.
	* rust/execute/torture/cfg4.rs: Likewise.
	* rust/execute/torture/coercion1.rs: Likewise.
	* rust/execute/torture/coercion2.rs: Likewise.
	* rust/execute/torture/extern_mod4.rs: Likewise.
	* rust/execute/torture/helloworld1.rs: Likewise.
	* rust/execute/torture/helloworld2.rs: Likewise.
	* rust/execute/torture/issue-1198.rs: Likewise.
	* rust/execute/torture/issue-1231.rs: Likewise.
	* rust/execute/torture/issue-1232.rs: Likewise.
	* rust/execute/torture/issue-1249.rs: Likewise.
	* rust/execute/torture/issue-1436.rs: Likewise.
	* rust/execute/torture/issue-1496.rs: Likewise.
	* rust/execute/torture/issue-647.rs: Likewise.
	* rust/execute/torture/issue-845.rs: Likewise.
	* rust/execute/torture/issue-851.rs: Likewise.
	* rust/execute/torture/issue-858.rs: Likewise.
	* rust/execute/torture/issue-976.rs: Likewise.
	* rust/execute/torture/macros10.rs: Likewise.
	* rust/execute/torture/macros11.rs: Likewise.
	* rust/execute/torture/macros12.rs: Likewise.
	* rust/execute/torture/macros13.rs: Likewise.
	* rust/execute/torture/macros14.rs: Likewise.
	* rust/execute/torture/macros2.rs: Likewise.
	* rust/execute/torture/macros22.rs: Likewise.
	* rust/execute/torture/macros29.rs: Likewise.
	* rust/execute/torture/macros3.rs: Likewise.
	* rust/execute/torture/macros30.rs: Likewise.
	* rust/execute/torture/macros31.rs: Likewise.
	* rust/execute/torture/macros7.rs: Likewise.
	* rust/execute/torture/macros8.rs: Likewise.
	* rust/execute/torture/macros9.rs: Likewise.
	* rust/execute/torture/match1.rs: Likewise.
	* rust/execute/torture/match2.rs: Likewise.
	* rust/execute/torture/match3.rs: Likewise.
	* rust/execute/torture/match_bool1.rs: Likewise.
	* rust/execute/torture/match_byte1.rs: Likewise.
	* rust/execute/torture/match_char1.rs: Likewise.
	* rust/execute/torture/match_int1.rs: Likewise.
	* rust/execute/torture/match_loop1.rs: Likewise.
	* rust/execute/torture/match_range1.rs: Likewise.
	* rust/execute/torture/match_range2.rs: Likewise.
	* rust/execute/torture/match_tuple1.rs: Likewise.
	* rust/execute/torture/method1.rs: Likewise.
	* rust/execute/torture/method2.rs: Likewise.
	* rust/execute/torture/method3.rs: Likewise.
	* rust/execute/torture/method4.rs: Likewise.
	* rust/execute/torture/operator_overload_1.rs: Likewise.
	* rust/execute/torture/operator_overload_10.rs: Likewise.
	* rust/execute/torture/operator_overload_11.rs: Likewise.
	* rust/execute/torture/operator_overload_12.rs: Likewise.
	* rust/execute/torture/operator_overload_2.rs: Likewise.
	* rust/execute/torture/operator_overload_4.rs: Likewise.
	* rust/execute/torture/operator_overload_5.rs: Likewise.
	* rust/execute/torture/operator_overload_6.rs: Likewise.
	* rust/execute/torture/operator_overload_7.rs: Likewise.
	* rust/execute/torture/operator_overload_8.rs: Likewise.
	* rust/execute/torture/operator_overload_9.rs: Likewise.
	* rust/execute/torture/str-layout1.rs: Likewise.
	* rust/execute/torture/str-zero.rs: Likewise.
	* rust/execute/torture/trait1.rs: Likewise.
	* rust/execute/torture/trait10.rs: Likewise.
	* rust/execute/torture/trait11.rs: Likewise.
	* rust/execute/torture/trait12.rs: Likewise.
	* rust/execute/torture/trait13.rs: Likewise.
	* rust/execute/torture/trait2.rs: Likewise.
	* rust/execute/torture/trait3.rs: Likewise.
	* rust/execute/torture/trait4.rs: Likewise.
	* rust/execute/torture/trait5.rs: Likewise.
	* rust/execute/torture/trait6.rs: Likewise.
	* rust/execute/torture/trait7.rs: Likewise.
	* rust/execute/torture/trait8.rs: Likewise.
	* rust/execute/torture/trait9.rs: Likewise.
	* rust/execute/torture/closure2.rs: Likewise.
	* rust/execute/torture/closure3.rs: Likewise.
	* rust/execute/torture/loop-condition-eval.rs: Likewise.
	* rust/execute/torture/operator_overload_3.rs: Likewise.
2023-01-19 17:28:50 +01:00
bors[bot]
7c84b3c02a Merge #1751
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>
2023-01-17 16:32:09 +00:00
MAHAD
78e96b15a5 README.md: Added experimental flag & updated gccrs path
(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>
2023-01-17 20:54:11 +05:00
bors[bot]
9e6c79054f Merge #1736
1736: Change how CompileVarDecl outputs Bvariable's r=philberty a=powerboat9

This allows patterns to declare multiple/no variables

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
---

Co-authored-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-01-14 22:35:55 +00:00
Owen Avery
dc31146d63 Change how CompileVarDecl outputs Bvariable's
This allows patterns to declare multiple/no variables

Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>
2023-01-12 21:36:11 -05:00
bors[bot]
2f9f77f9dd Merge #1733
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>
2023-01-12 13:54:04 +00:00
mxlol233
68839a57ea diagnostics: Add underline for tokens in diagnostics.
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>
2023-01-12 20:36:23 +08:00
bors[bot]
0030bead12 Merge #1734
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>
2023-01-11 16:45:18 +00:00
mxlol233
8400990952 Add get_locus function for abstract class MetaItemInner.
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>
2023-01-11 23:24:07 +08:00
bors[bot]
59cbecb75d Merge #1730
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>
2023-01-11 11:39:37 +00:00
Owen Avery
97c1308bec Reuse TypeCheckPattern on LetStmt's
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>
2023-01-10 18:27:45 -05:00
bors[bot]
b6fcee808f Merge #1724
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 #1726



Fixes #1720 

Co-authored-by: Philip Herron <herron.philip@googlemail.com>
2023-01-10 22:39:41 +00:00
Philip Herron
ed6718d979 Support associated type bound arguments
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.
2023-01-10 22:12:16 +00:00
Philip Herron
2359320427 Add name resolution to generic argument associated item bindings
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):
2023-01-10 22:12:16 +00:00
bors[bot]
3290293e16 Merge #1708
1708: Parse declarative macro (decl_macro 2.0) r=CohenArthur a=tamaroning

This PR is currentry wip.
Opinions and advices are welcome!

Co-authored-by: Raiki Tamura <tamaron1203@gmail.com>
2023-01-09 15:48:12 +00:00
Raiki Tamura
9e5769cf45 Implement declarative macro 2.0 parser
Signed-off-by: Raiki Tamura <tamaron1203@gmail.com>
2023-01-10 00:38:52 +09:00
bors[bot]
48d32bc9cb Merge #1707 #1717
1707: Fix frust very long typo r=CohenArthur a=CohenArthur

Missing space character

1717: format: Fix git whitespace errors r=CohenArthur a=CohenArthur

Addresses #1680 
Fixes #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>
2023-01-05 15:59:10 +00:00
bors[bot]
68b0212c81 Merge #1711
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>
2023-01-05 15:17:27 +00:00
bors[bot]
fc72441e83 Merge #1709
1709: Check const functions for mutable references r=CohenArthur a=dme2

Fixes #1552

Co-authored-by: Dave <dme2223@gmail.com>
2023-01-05 08:36:42 +00:00
bors[bot]
8742e54052 Merge #1716
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>
2023-01-04 20:12:07 +00:00
Arthur Cohen
fd25c4fa72 format: Fix git whitespace errors 2023-01-04 16:37:55 +01:00
mxlol233
2f36f38054 rust: add bound parsing in parse_generic_arg.
Signed-off-by: Xiao Ma <mxlol233@outlook.com>
2023-01-04 22:18:18 +08:00
Dave
5918059fd3 Check for mutable references in const functions
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>
2023-01-02 17:56:59 -06:00
Prajwal S N
aa7698dca9 unsafe: check use of target_feature attribute
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>
2023-01-02 16:52:21 +05:30
bors[bot]
0152926ab3 Merge #1706
1706: Add math intrinsics r=CohenArthur a=tamaroning

Addresses https://github.com/Rust-GCC/gccrs/issues/658
Added math intrinsic functions.

Co-authored-by: Raiki Tamura <tamaron1203@gmail.com>
2022-12-16 12:46:03 +00:00
Arthur Cohen
5bbbe70df9 fatal_error_flag: Fix typo in error message 2022-12-16 13:40:03 +01:00
Raiki Tamura
54e2c74a5b add math intrinsics 2022-12-16 02:27:59 +09:00
bors[bot]
84a85305de Merge #1700
1700: Merge upstream, last commit before GCC/Rust upstreaming r=CohenArthur a=tschwinge



Co-authored-by: Eric Botcazou <ebotcazou@adacore.com>
Co-authored-by: Richard Biener <rguenther@suse.de>
Co-authored-by: Patrick Palka <ppalka@redhat.com>
Co-authored-by: Jonathan Wakely <jwakely@redhat.com>
Co-authored-by: Harald Anlauf <anlauf@gmx.de>
Co-authored-by: Ian Lance Taylor <iant@golang.org>
Co-authored-by: GCC Administrator <gccadmin@gcc.gnu.org>
Co-authored-by: David Malcolm <dmalcolm@redhat.com>
Co-authored-by: Lulu Cheng <chenglulu@loongson.cn>
Co-authored-by: Alexandre Oliva <oliva@adacore.com>
Co-authored-by: Paul-Antoine Arras <pa@codesourcery.com>
Co-authored-by: Tobias Burnus <tobias@codesourcery.com>
Co-authored-by: Jakub Jelinek <jakub@redhat.com>
Co-authored-by: Martin Liska <mliska@suse.cz>
Co-authored-by: Iskander Shakirzyanov <iskander@ispras.ru>
Co-authored-by: Iain Buclaw <ibuclaw@gdcproject.org>
Co-authored-by: Kyrylo Tkachov <kyrylo.tkachov@arm.com>
Co-authored-by: John David Anglin <danglin@gcc.gnu.org>
2022-12-15 14:13:33 +00:00
Thomas Schwinge
782daee399 Adjust '.github/bors_log_expected_warnings' 2022-12-15 14:52:24 +01:00
bors[bot]
9c21f45e45 Merge #1704
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>
2022-12-15 09:06:54 +00:00
Marc Poulhiès
404cdd1eeb rust: fix link serialization [PR108113]
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>
2022-12-14 21:57:04 +01:00
Thomas Schwinge
fe648fb91c Adjust for "Make Warray-bounds alias to Warray-bounds= [PR107787]"
See GCC upstream commit 7c01d029fc
"Make Warray-bounds alias to Warray-bounds= [PR107787]".
2022-12-14 17:32:48 +01:00
Thomas Schwinge
5bfaeebb0d Merge commit '3b89428c0d5710c8093055b3d92c543888759f93' into HEAD 2022-12-14 17:30:30 +01:00
Thomas Schwinge
0d0de2c6c5 Merge commit '3d6dbb6fc5d1d14bf36a879b6f4a00ae91090a63' into HEAD 2022-12-14 17:29:17 +01:00
bors[bot]
3b89428c0d Merge #1703
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>
2022-12-14 14:46:30 +00:00
Marek Polacek
5c2e6c93d9 c++: Quash -Wdangling-reference for member operator* [PR107488]
-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)
2022-12-14 14:29:44 +01:00
bors[bot]
3d6dbb6fc5 Merge #1701
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>
2022-12-14 11:51:46 +00:00
Thomas Schwinge
2384a03456 Really fix up '.github/bors_log_expected_warnings' 2022-12-14 11:25:45 +01:00
Thomas Schwinge
a42212a630 Revert "bors: Fix warning list"
This reverts #1585 commit 94d11161c1.

Conflicts:
	.github/bors_log_expected_warnings
... manually resolved and adjusted; let's see...
2022-12-14 10:26:06 +01:00
Thomas Schwinge
1664a73088 Revert "ci: Apply warnings in CI"
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.
2022-12-14 10:25:31 +01:00
Thomas Schwinge
529a6980f3 Revert "ci: Use same CXXFLAGS in bootstrap workflow"
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'.

> '-Wno-unused-parameter' [did] move into
> 'rust-warn'

This reverts #1623 commit b3222881f4.
2022-12-14 10:20:16 +01:00
Thomas Schwinge
caca467268 'rust-warn += -Wno-unused-parameter'
(cherry picked from #1670 commit 7ceb5e29c80c1fc91e208ae6955a22b0b73a2e6b)
2022-12-14 10:20:15 +01:00
Thomas Schwinge
74e1638596 Merge commit 'b4fddbe9592e9feb37ce567d90af822b75995531' into HEAD 2022-12-13 22:44:33 +01:00
bors[bot]
62d1620c91 Merge #1678 #1682 #1687
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>
2022-12-09 10:08:22 +00:00
Arthur Cohen
88e509b1b1 const evaluator: Remove get_nth_callarg
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
2022-12-09 10:44:48 +01:00
bors[bot]
e91b6e5339 Merge #1681
1681: Backport #1653 r=CohenArthur a=CohenArthur



Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
2022-12-09 09:31:27 +00:00
Arthur Cohen
d77d5be069 var_expression: document that the memory of the val argument isn't freed 2022-12-09 10:33:18 +01:00
bors[bot]
d0cb3248ce Merge #1683
1683: backend: Replace double_int_to_tree -> wide_int_to_tree r=CohenArthur a=CohenArthur



Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
2022-12-09 08:06:06 +00:00
bors[bot]
db4970e9db Merge #1684
1684: backend: Use build_int_cstu for size expressions r=CohenArthur a=CohenArthur



Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
2022-12-09 07:31:23 +00:00
bors[bot]
b36e8cac9f Merge #1685
1685: Backport 1656 r=CohenArthur a=CohenArthur



Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
2022-12-08 18:46:53 +00:00
bors[bot]
038e11c3ee Merge #1540
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>
2022-12-07 14:19:12 +00:00
bors[bot]
8c0f4e48ff Merge #1686
1686: bors: Expect ubuntu32bit and gcc48 jobs to succeed r=CohenArthur a=CohenArthur



Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
2022-12-07 13:46:35 +00:00
bors[bot]
3f50151666 Merge #1688
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>
2022-12-07 12:11:33 +00:00
Arthur Cohen
19d5f921d0 ci: gcc-4.8 package is only available in Ubuntu 18.04 2022-12-07 10:32:21 +01:00
Arthur Cohen
f7172bc289 ci: Lock Ubuntu version to 20.04 2022-12-07 10:22:13 +01:00
Thomas Schwinge
ca0a935cdc Repair 'gcc/rust/lang.opt' comment
... lost in #1527 commit 138a626012
"rust: Add -frust-compile-until option".
2022-12-07 09:23:32 +01:00
Thomas Schwinge
d9d9ca0b9e Move '-frust-incomplete-and-experimental-compiler-do-not-use' out of the middle of '-frust-mangling=[...]' 2022-12-07 09:15:39 +01:00
Arthur Cohen
09a9382eea bors: Expect ubuntu32bit and gcc48 jobs to succeed 2022-12-06 16:16:01 +01:00
Arthur Cohen
a2ae23a9f2 rust-lang: Don't fold convert_to expressions 2022-12-06 16:13:21 +01:00
Arthur Cohen
a6285cf219 backend: Don't fold convert_to expressions 2022-12-06 16:13:21 +01:00
Arthur Cohen
50cd4d91e3 backend: Use build_int_cstu for size expressions 2022-12-06 16:08:07 +01:00
Arthur Cohen
277497f77c backend: Replace double_int_to_tree -> wide_int_to_tree 2022-12-06 16:07:12 +01:00
Arthur Cohen
b2d445c2bb long_flag: Add env variable, remove bootstrap guards 2022-12-05 14:52:09 +01:00
Arthur Cohen
3df7703a62 fix makefile syntax error 2022-12-05 14:52:09 +01:00
Arthur Cohen
9b6cd2601d rename variable which holds bootstrap flag 2022-12-05 14:52:09 +01:00
Arthur Cohen
ef97884710 make: Use RUST_CXXFLAGS for session-manager specifically 2022-12-05 14:52:09 +01:00
Arthur Cohen
be9740eaa6 rust1: Use RUST_CXXFLAGS 2022-12-05 14:52:09 +01:00
Arthur Cohen
ddd1b481a0 session-manager: Add fatal_error when flag is not present 2022-12-05 14:52:09 +01:00
Arthur Cohen
f3cb834600 wip: Add long flag and enable it on release builds 2022-12-05 14:52:09 +01:00
Philip Herron
a3a755838f Cleanup unused parameters to fix the bootstrap build 2022-12-05 02:20:55 +00:00
bors[bot]
9666f2b169 Merge #1632
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>
2022-12-05 01:22:10 +00:00
Philip Herron
31dd14e197 Skip this debug test case which is failing on the latest mac-os devtools and its only for debug info 2022-12-05 00:31:18 +00:00
Philip Herron
48b11d3bb8 Fix undefined behaviour issues on macos
This adds missing copy constructors to HIR::PathExprSegment which were
wrongly defaulting to empty vectors when apply specified generic arguments
to method calls.
2022-12-05 00:17:26 +00:00
bors[bot]
e39fadcd0a Merge #1611
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>
2022-12-04 22:02:22 +00:00
Philip Herron
3053ec3660 Add initial support for argument capture of closures
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
2022-12-04 21:00:45 +00:00
Philip Herron
3573ec082f Add capture tracking to the type info for closures 2022-12-04 21:00:45 +00:00
Philip Herron
b5c354de73 Add closure binding's tracking to name resolution
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
2022-12-04 21:00:45 +00:00
Philip Herron
6c5dc8aa1a Refactor name resolver to take a Rib::ItemType
This allows us to track the type of declaration that is stored within a
Rib.
2022-12-04 21:00:44 +00:00
Philip Herron
d07cae9e4b Get rid of make builtin macro
This macro is a mess and a helper method is much better for this case.
2022-12-04 21:00:44 +00:00
bors[bot]
22329b03a6 Merge #1676
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>
2022-12-04 19:14:59 +00:00
Philip Herron
071e8b001c Revert "builtins: Cleanup initialization of builtins"
This reverts commit fc59d13749.
2022-12-04 16:17:29 +00:00
Philip Herron
9da783d1b7 Revert "rust: Remove unused variables and fix dangling references"
This reverts commit 9657c328d0.
2022-12-04 15:27:26 +00:00
bors[bot]
402118688f Merge #1672
1672: just for fun r=philberty a=philberty

I love https://justforfunnoreally.dev/

Co-authored-by: Philip Herron <philip.herron@embecosm.com>
2022-12-04 14:58:48 +00:00
bors[bot]
0bf68cf5e6 Merge #1668
1668: builtins: Remove unused parameter r=CohenArthur a=CohenArthur

Merging #1630 broke the bootstrap build

Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
2022-12-02 09:20:06 +00:00
Philip Herron
01fbbffcca Join justforfun.dev 2022-12-01 22:37:47 +00:00
Arthur Cohen
4c66e0f3c1 builtins: Remove unused parameter 2022-11-30 12:13:40 +01:00
bors[bot]
738df996e0 Merge #1630
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>
2022-11-30 09:46:51 +00:00
Arthur Cohen
fc59d13749 builtins: Cleanup initialization of builtins
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.
2022-11-30 09:47:11 +01:00
bors[bot]
71b8beb150 Merge #1651
1651: Improve dump lex r=CohenArthur a=tamaroning

Fixes #1650 


Co-authored-by: Raiki Tamura <tamaron1203@gmail.com>
2022-11-28 11:45:44 +00:00
Raiki Tamura
b43c5d4fd8 Improve lexer dump 2022-11-19 07:58:38 +09:00
bors[bot]
9ef8144e39 Merge #1636
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>
2022-11-18 08:48:08 +00:00
bors[bot]
d8e9850b7f Merge #1652
1652: AST dump types r=CohenArthur a=jdupak


- \[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`
- N\A - Added any relevant test cases to `gcc/testsuite/rust/`

---

Add/fix AST dump of types incl. generic parameters.


Co-authored-by: Jakub Dupak <dev@jakubdupak.com>
2022-11-17 10:12:19 +00:00
Dave
bea720bef7 Remove default location. Add visibility location to create_* functions 2022-11-16 17:06:44 -06:00
Jakub Dupak
9527e99858 ast: Dump no comma after self in fn params if it is the last one
Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2022-11-16 17:59:39 +01:00
Jakub Dupak
b0ec92f7d4 ast: Dump remove /* stmp */ comment to not clutter the dump
Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2022-11-16 17:59:39 +01:00
Jakub Dupak
fc944a0241 ast: Remove unused include in rust-ast-dump.cc
Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2022-11-16 17:59:38 +01:00
Jakub Dupak
78df522226 ast: Dump generic parameters
Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2022-11-16 17:59:38 +01:00
Jakub Dupak
a3dfe962eb ast: Dump type param type
Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2022-11-16 17:59:37 +01:00
Jakub Dupak
5c943bf438 ast: Dump trait object type one bound
Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2022-11-16 17:59:37 +01:00
Jakub Dupak
4c69451b3d ast: Dump parenthesised type
Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2022-11-16 17:59:36 +01:00
Jakub Dupak
0e026b6c33 ast: Dump trait object type
Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2022-11-16 17:59:35 +01:00
Jakub Dupak
9147e08003 ast: Dump impl trait type
Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2022-11-16 17:59:35 +01:00
Jakub Dupak
6c432d6ca2 ast: Dump impl trait type one bound
Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2022-11-16 17:59:34 +01:00
Jakub Dupak
0ebbd2a451 ast: Dump bare function type
+ Return FunctionQualifiers as ref to work in ast dump

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2022-11-16 17:59:33 +01:00
Jakub Dupak
8c239b1428 ast: Dump inferred type
Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2022-11-16 16:26:48 +01:00
Jakub Dupak
9b6d820612 ast: Dump tuple type
Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2022-11-16 16:26:47 +01:00
Jakub Dupak
496ed46e0a ast: Dump never type
Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2022-11-16 16:26:47 +01:00
Jakub Dupak
20bf6802ba ast: Dump raw pointer type
Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2022-11-16 16:26:46 +01:00
Jakub Dupak
0eaaeb4b35 ast: Dump array type
Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2022-11-16 16:26:45 +01:00
Jakub Dupak
f4d7813336 ast: Dump slice type
Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2022-11-16 16:26:44 +01:00
bors[bot]
27136db8fd Merge #1633
1633: Implement PhantomData r=CohenArthur a=tamaroning

Fixes #1127 

Added `phantom_data` lang item


Co-authored-by: Raiki Tamura <tamaron1203@gmail.com>
2022-11-16 09:27:49 +00:00
bors[bot]
716ae8d024 Merge #1649
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>
2022-11-15 20:46:40 +00:00
bors[bot]
4c56599954 Merge #1635
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>
2022-11-15 16:16:01 +00:00
Arthur Cohen
9657c328d0 rust: Remove unused variables and fix dangling references 2022-11-15 17:17:15 +01:00
bors[bot]
815a57351a Merge #1631
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>
2022-11-15 11:01:12 +00:00
Jakub Dupak
22977337fa ast: Dump where clause and recursively needed nodes
This is currently needed for lifetimes to use the existing infrastructure.

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2022-11-15 11:52:05 +01:00
Jakub Dupak
7264aac826 ast: add visit overload for references
This is currently needed for lifetimes to use the existing infrastructure.

Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2022-11-15 11:51:47 +01:00
bors[bot]
009337f593 Merge #1628
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>
2022-11-14 09:11:53 +00:00
Arthur Cohen
28ae1589e1 typecheck: Fix overzealous delete call 2022-11-14 10:14:25 +01:00
Dave
ec62fce8e8 clang-format 2022-11-10 19:28:57 -06:00
Dave
1531256aa6 add Location to AST::Visibility 2022-11-09 23:17:50 -06:00
Raiki Tamura
f726b12ca1 clang-format 2022-11-09 19:58:31 +09:00
Raiki Tamura
d8d81d818d add lang item "phantom_data" 2022-11-09 18:49:12 +09:00
bors[bot]
9606dc92b9 Merge #1625
1625: Ast dump unit struct r=CohenArthur a=jdupak

Adds dump for unit struct

Depends on #1624 

Co-authored-by: Jakub Dupak <dev@jakubdupak.com>
2022-11-08 08:48:20 +00:00
Jakub Dupak
b6ce6882fb ast: Dump unit struct
Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2022-11-07 22:09:18 +01:00
bors[bot]
4a514b7a92 Merge #1624
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>
2022-11-07 12:56:39 +00:00
bors[bot]
0a59abbfc7 Merge #1627
1627: Merge GCC mainline/master into gccrs/master r=CohenArthur a=ibuclaw

`@doko42` was asking, so here's another merge sync.

Co-authored-by: GCC Administrator <gccadmin@gcc.gnu.org>
Co-authored-by: Andrew MacLeod <amacleod@redhat.com>
Co-authored-by: Liwei Xu <liwei.xu@intel.com>
Co-authored-by: Richard Biener <rguenther@suse.de>
Co-authored-by: Jakub Jelinek <jakub@redhat.com>
Co-authored-by: Andre Vieira <andre.simoesdiasvieira@arm.com>
Co-authored-by: Jonathan Wakely <jwakely@redhat.com>
Co-authored-by: Martin Jambor <mjambor@suse.cz>
Co-authored-by: Joseph Myers <joseph@codesourcery.com>
Co-authored-by: Patrick Palka <ppalka@redhat.com>
Co-authored-by: Florian Weimer <fweimer@redhat.com>
Co-authored-by: Marek Polacek <polacek@redhat.com>
Co-authored-by: liuhongt <hongtao.liu@intel.com>
Co-authored-by: Martin Liska <mliska@suse.cz>
Co-authored-by: Robin Dapp <rdapp@linux.ibm.com>
Co-authored-by: Takayuki 'January June' Suwa <jjsuwa_sys3175@yahoo.co.jp>
Co-authored-by: Stefan Schulze Frielinghaus <stefansf@linux.ibm.com>
2022-11-04 13:22:10 +00:00
Jakub Dupak
dd6296cffe ast: Dump add proper line_trailing argument to visit_items_as_block
Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2022-11-04 13:48:48 +01:00
Jakub Dupak
7486d6cda4 ast: refer correctly to arguments in docs-strings
Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2022-11-04 13:48:42 +01:00
Jakub Dupak
77cba0083a ast: transform helper methods to visits and add methods to simplify repeated patterns
Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2022-11-04 13:48:06 +01:00
Arthur Cohen
a7b70c7041 ci: Update expected warnings 2022-11-03 14:33:10 +01:00
bors[bot]
f8c2fab0c6 Merge #1622
1622: intrinsics: Add atomic_load_* r=CohenArthur a=CohenArthur



Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
2022-11-01 17:29:07 +00:00
bors[bot]
d8de1df884 Merge #1623
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>
2022-11-01 16:59:43 +00:00
Iain Buclaw
762066ae83 Merge remote-tracking branch 'mainline/trunk' into ibuclaw/merge_trunk 2022-11-01 17:46:37 +01:00
Mark Wielaard
cdcfe27cfb dwarf2out.c: Don't emit DW_LANG_Rust_old
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.
2022-10-30 16:03:16 +01:00
Jakub Dupak
56a227a63b ast: visitor pattern -> overload syntax compatibility layer
Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2022-10-28 17:14:53 +02:00
Arthur Cohen
b3222881f4 ci: Use same CXXFLAGS in bootstrap workflow 2022-10-28 14:32:45 +02:00
Arthur Cohen
b0bde7e2b5 intrinsics: Implement atomic_load intrinsics
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>
2022-10-28 10:37:28 +02:00
Arthur Cohen
0e08acbf2c intrinsics: Cleanup error handling around atomic_store_* 2022-10-28 10:37:28 +02:00
bors[bot]
2d1c287af3 Merge #1620
1620: Intrinsics unchecked ops r=CohenArthur a=CohenArthur

Addresses #658 


Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
2022-10-27 16:30:02 +00:00
bors[bot]
353ed6ce8a Merge #1616 #1617
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>
2022-10-27 10:49:47 +00:00
bors[bot]
4dbff3d055 Merge #1621
1621: intrinsics: Use lambdas for wrapping_<op> intrinsics r=CohenArthur a=CohenArthur



Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
2022-10-27 10:19:47 +00:00
Arthur Cohen
2357b5d513 intrinsics: Use lambdas for wrapping_<op> intrinsics 2022-10-27 12:22:14 +02:00
Arthur Cohen
259c384a97 rust-object-export: Remove system includes 2022-10-27 12:15:11 +02:00
Arthur Cohen
e9e3ca5ca6 parser: Remove system includes 2022-10-27 12:15:11 +02:00
Arthur Cohen
5206aede53 lex: Remove system includes 2022-10-27 12:15:11 +02:00
Arthur Cohen
c5454530ec attribute checker: Remove system includes 2022-10-27 12:15:11 +02:00
Arthur Cohen
0b7cd54d63 optional: Remove system includes 2022-10-27 12:15:11 +02:00
Arthur Cohen
639341e5b7 make_unique: Remove system includes 2022-10-27 12:15:11 +02:00
Arthur Cohen
c1ff8a96f6 lexer: Remove system includes 2022-10-27 12:15:11 +02:00
Arthur Cohen
8d3ed91565 ast: Remove system include 2022-10-27 12:15:11 +02:00
Arthur Cohen
3f3b4a45eb lang-specs: Rename language spec @rs -> @rust
Co-authored-by: ibuclaw <ibuclaw@gdcproject.org>
2022-10-27 12:00:01 +02:00
bors[bot]
d8a8061f2e Merge #1618
1618: Add missing copyright headers r=CohenArthur a=CohenArthur

Closes #1601
Closes #1600  

Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
2022-10-26 15:32:36 +00:00
bors[bot]
19461b9e9c Merge #1619
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>
2022-10-26 14:53:18 +00:00
Arthur Cohen
fc2aa3cd38 intrinsics: Add unchecked operation intrinsics 2022-10-26 16:03:37 +02:00
Arthur Cohen
db4b399c25 parser: Fix ICE in closure parsing
`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.
2022-10-26 11:25:42 +02:00
Arthur Cohen
dcb38a3e45 rust-privacy-reporter: Add copyright header 2022-10-26 10:57:06 +02:00
Arthur Cohen
1e11f00ca1 rust-cfg-parser: Add copyright header 2022-10-26 10:56:58 +02:00
bors[bot]
2bc1c53092 Merge #1615
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>
2022-10-26 08:56:37 +00:00
bors[bot]
14c942c3eb Merge #1585
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>
2022-10-26 08:27:39 +00:00
Arthur Cohen
4d42744aa5 intrinsics: Add early implementation for atomic_store_{seqcst, relaxed, release}
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>
2022-10-26 09:58:05 +02:00
bors[bot]
0cf743d57f Merge #1614
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>
2022-10-25 17:24:06 +00:00
Arthur Cohen
94d11161c1 bors: Fix warning list 2022-10-25 14:32:28 +02:00
Arthur Cohen
b664c8bfd0 constexpr: Add rust_sorry_at in places relying on init values
This also comments out a now unused function
2022-10-25 14:32:28 +02:00
bors[bot]
6c7841a3ac Merge #1613
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>
2022-10-25 12:08:10 +00:00
Arthur Cohen
83e5265d6a intrinsics: Add sorry_handler intrinsic handler
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
2022-10-25 11:10:19 +02:00
Arthur Cohen
6304177c2b builtins: Rename all bang macro handlers
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
2022-10-24 17:28:32 +02:00
Arthur Cohen
a32ef7aa18 ci: Apply warnings in CI 2022-10-24 15:28:08 +02:00
Arthur Cohen
da13bf4bbc make: Inherit CXXFLAGS, remove compiler-specific warnings 2022-10-24 15:28:08 +02:00
bors[bot]
490aa25d55 Merge #1608
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>
2022-10-21 14:13:47 +00:00
bors[bot]
60b21d2f58 Merge #1607
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>
2022-10-21 13:05:18 +00:00
Philip Herron
05bd0555fa Support Closure calls as generic trait bounds
Addresses #195
2022-10-20 18:31:24 +01:00
Philip Herron
f6f87dead4 Add missing type resolution for function type segments 2022-10-20 18:05:43 +01:00
Philip Herron
d396692534 Add missing hir lowering to function type-path segments 2022-10-20 17:59:27 +01:00
Philip Herron
8e09dfb538 Add missing name resolution to Function type-path segments 2022-10-20 17:59:03 +01:00
Philip Herron
678bf85243 Closure support at CallExpr
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
2022-10-20 16:10:15 +01:00
Philip Herron
feaa40602b Initial Type resolution for closures
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
2022-10-20 16:10:08 +01:00
Philip Herron
e637c0445b Add closures to lints and error checking 2022-10-20 16:06:09 +01:00
Philip Herron
662a7a9030 Refactor method call type checking
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.
2022-10-20 16:03:33 +01:00
bors[bot]
dfb5921b76 Merge #1549
1549: Dump macro declarations properly r=CohenArthur a=CohenArthur

Dump `MacroRulesDef` properly

Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
2022-10-20 11:54:07 +00:00
Philip Herron
8c4cf085d9 Add name resolution for closures
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.
2022-10-19 19:32:47 +01:00
Philip Herron
8e2d13922f Formatting cleanup in HIR lowering pattern
Move implementation into cc file from the header and remove unnessecary
new lines in the expr lowering header.
2022-10-19 19:32:47 +01:00
Philip Herron
5f25f457ec Add hir lowering of closure expressions
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
2022-10-19 19:32:47 +01:00
Philip Herron
851b9e1458 Refactor expression hir lowering into cc file 2022-10-19 19:32:47 +01:00
Philip Herron
a28e7dcb46 Add missing fn_once_output langitem 2022-10-19 19:32:47 +01:00
bors[bot]
3cedc655c2 Merge #1596
1596: Add more implementations for TARGET_RUST_OS_INFO r=philberty a=ibuclaw

Pretty much all follow the same template as how darwin was added in the first commit, so mostly uninteresting.

The only slight deviation is with `*-*-linux*`, where rather than putting it in a common `glibc-rust.cc` file, I've instead opted to force each platform have their own source file. So Linux gets a `linux-rust.cc` file, and anyone who wants to add Hurd, kFreeBSD, or kOpenSolaris later can do so by adding a case to this switch with the appropriately named file (i.e: `gnu-rust.cc` for Hurd).

The same can also be said for MinGW targets - `winnt-rust.cc` is explicitly _not_ set for Cygwin, and I'd prefer that whoever does add Cygwin support will create a separate file for it - otherwise you've either got to modify the target headers to add whatever defines you need in order to abstract the two away, or start adding some defines to `tm_rust.h` to expose hints about the target known at configure time.

Linux is also the only implementation that has an `#ifndef` condition, as not all Linux targets include `linux-android.{h,opt}`.

Checked dumps of target_options on a plethora of target configurations, though this list is by no means exhaustive.

---

<details>
  <summary>i686-dragonflybsd</summary>

```
target_pointer_width: "32"
target_env: ""
target_vendor: "unknown"
target_endian: "little"
target_os: "dragonfly"
target_family: "unix"
target_arch: "x86"
```
</details>
<details>
  <summary>x86_64-dragonflybsd</summary>

```
target_pointer_width: "64"
target_env: ""
target_vendor: "unknown"
target_endian: "little"
target_os: "dragonfly"
target_family: "unix"
target_feature: "fxsr"
target_feature: "sse"
target_feature: "sse2"
target_feature: "mmx"
target_arch: "x86_64"
```
</details>
<details>
  <summary>aarch64-freebsd12, ia64-freebsd6, riscv64-freebsd12</summary>

```
target_pointer_width: "64"
target_env: ""
target_vendor: "unknown"
target_endian: "little"
target_os: "freebsd"
target_family: "unix"
```
</details>
<details>
  <summary>arm-freebsd12</summary>

```
target_pointer_width: "32"
target_env: ""
target_vendor: "unknown"
target_endian: "little"
target_os: "freebsd"
target_family: "unix"
```
</details>
<details>
  <summary>i486-freebsd4, i686-freebsd6</summary>

```
target_pointer_width: "32"
target_env: ""
target_vendor: "unknown"
target_endian: "little"
target_os: "freebsd"
target_family: "unix"
target_arch: "x86"
```
</details>
<details>
  <summary>powerpc-freebsd6</summary>

```
target_pointer_width: "32"
target_env: ""
target_vendor: "unknown"
target_endian: "big"
target_os: "freebsd"
target_family: "unix"
```
</details>
<details>
  <summary>sparc64-freebsd6</summary>

```
target_pointer_width: "64"
target_env: ""
target_vendor: "unknown"
target_endian: "big"
target_os: "freebsd"
target_family: "unix"
```
</details>
<details>
  <summary>x86_64-freebsd6</summary>

```
target_pointer_width: "64"
target_env: ""
target_vendor: "unknown"
target_endian: "little"
target_os: "freebsd"
target_family: "unix"
target_feature: "fxsr"
target_feature: "sse"
target_feature: "sse2"
target_feature: "mmx"
target_arch: "x86_64"
```
</details>
<details>
  <summary>aarch64-fuchsia</summary>

```
target_pointer_width: "64"
target_env: ""
target_vendor: "unknown"
target_endian: "little"
target_os: "fushsia"
target_family: "unix"
```
</details>
<details>
  <summary>x86_64-fuchsia</summary>

```
target_pointer_width: "64"
target_env: ""
target_vendor: "unknown"
target_endian: "little"
target_os: "fushsia"
target_family: "unix"
target_feature: "fxsr"
target_feature: "sse"
target_feature: "sse2"
target_feature: "mmx"
target_arch: "x86_64"
```
</details>
<details>
  <summary>i686-kfreebsd-gnu</summary>

```
target_endian: "little"
target_pointer_width: "32"
target_arch: "x86"
```
</details> 
<details>
  <summary>arm-linux-androideabi</summary>

```
target_pointer_width: "32"
target_env: ""
target_endian: "little"
target_os: "android"
target_vendor: "unknown"
target_family: "unix"
```
</details>
<details>
  <summary>aarch64-linux-gnu, alpha-linux-gnu, ia64-linux, riscv64-unknown-linux-gnu</summary>

```
target_pointer_width: "64"
target_env: "gnu"
target_endian: "little"
target_os: "linux"
target_vendor: "unknown"
target_family: "unix"
```
</details>
<details>
  <summary>am33_2.0-linux-gnu, csky-linux-gnu, mips64el-st-linux-gnu, nios2-linux-gnu, powerpcle-linux, riscv32-unknown-linux-gnu, rx-linux, shle-linux, vax-linux-gnu</summary>

```
target_pointer_width: "32"
target_env: "gnu"
target_endian: "little"
target_os: "linux"
target_vendor: "unknown"
target_family: "unix"
```
</details>
<details>
  <summary>arc-linux-uclibc, bfin-linux-uclibc</summary>

```
target_pointer_width: "32"
target_env: "uclibc"
target_endian: "little"
target_os: "linux"
target_vendor: "unknown"
target_family: "unix"
```
</details>
<details>
  <summary>arceb-linux-uclibc, or1k-linux-uclibc</summary>

```
target_pointer_width: "32"
target_env: "uclibc"
target_endian: "big"
target_os: "linux"
target_vendor: "unknown"
target_family: "unix"
```
</details>
<details>
  <summary>frv-linux, h8300-linux, hppa-linux-gnu, m68k-linux, microblaze-linux, mips64octeon-linux, mipsisa32r2-linux-gnu, mipsisa64r2-linux, mips-linux, mips-mti-linux, powerpc64-linux_altivec, powerpc-linux, s390-linux-gnu, sparc-leon3-linux-gnu, sparc-linux-gnu, xtensa-linux</summary>

```
target_pointer_width: "32"
target_env: "gnu"
target_endian: "big"
target_os: "linux"
target_vendor: "unknown"
target_family: "unix"
```
</details>
<details>
  <summary>hppa64-linux-gnu, s390x-linux-gnu, sparc64-linux</summary>

```
target_pointer_width: "64"
target_env: "gnu"
target_endian: "big"
target_os: "linux"
target_vendor: "unknown"
target_family: "unix"
```
</details>
<details>
  <summary>i686-pc-linux-gnu, i686-pc-linux</summary>

```
target_pointer_width: "32"
target_env: "gnu"
target_endian: "little"
target_os: "linux"
target_vendor: "unknown"
target_family: "unix"
target_arch: "x86"
```
</details>
<details>
  <summary>or1k-linux-musl</summary>

```
target_pointer_width: "32"
target_env: "musl"
target_endian: "big"
target_os: "linux"
target_vendor: "unknown"
target_family: "unix"
```
</details>
<details>
  <summary>i686-mingw32crt</summary>

```
target_pointer_width: "32"
target_env: "gnu"
target_vendor: "pc"
target_endian: "little"
target_os: "windows"
target_family: "windows"
target_arch: "x86"
```
</details>
<details>
  <summary>x86_64-mingw32, x86_64-w64-mingw32</summary>

```
target_pointer_width: "64"
target_env: "gnu"
target_vendor: "pc"
target_endian: "little"
target_os: "windows"
target_family: "windows"
target_feature: "fxsr"
target_feature: "sse"
target_feature: "sse2"
target_feature: "mmx"
target_arch: "x86_64"
```
</details>
<details>
  <summary>aarch64-netbsd, alpha-netbsd</summary>

```
target_pointer_width: "64"
target_env: ""
target_vendor: "unknown"
target_endian: "little"
target_os: "netbsd"
target_family: "unix"
```
</details>
<details>
  <summary>arm-netbsdelf, vax-netbsdelf</summary>

```
target_pointer_width: "32"
target_env: ""
target_vendor: "unknown"
target_endian: "little"
target_os: "netbsd"
target_family: "unix"
```
</details>
<details>
  <summary>hppa-netbsd, m68k-netbsdelf, mips-netbsd, powerpc-netbsd, sh-netbsdelf, sparc-netbsdelf</summary>

```
target_pointer_width: "32"
target_env: ""
target_vendor: "unknown"
target_endian: "big"
target_os: "netbsd"
target_family: "unix"
```
</details>
<details>
  <summary>i686-netbsdelf9</summary>

```
target_pointer_width: "32"
target_env: ""
target_vendor: "unknown"
target_endian: "little"
target_os: "netbsd"
target_family: "unix"
target_arch: "x86"
```
</details>
<details>
  <summary>sparc64-netbsd</summary>

```
target_pointer_width: "64"
target_env: ""
target_vendor: "unknown"
target_endian: "big"
target_os: "netbsd"
target_family: "unix"
```
</details> 
<details>
  <summary>x86_64-netbsd</summary>

```
target_pointer_width: "64"
target_env: ""
target_vendor: "unknown"
target_endian: "little"
target_os: "netbsd"
target_family: "unix"
target_feature: "fxsr"
target_feature: "sse"
target_feature: "sse2"
target_feature: "mmx"
target_arch: "x86_64"
```
</details>
<details>
  <summary>alpha-openbsd</summary>

```
target_pointer_width: "64"
target_env: ""
target_vendor: "unknown"
target_endian: "little"
target_os: "openbsd"
target_family: "unix"
```
</details>
<details>
  <summary>bfin-openbsd</summary>

```
target_pointer_width: "32"
target_env: ""
target_vendor: "unknown"
target_endian: "little"
target_os: "openbsd"
target_family: "unix"
```
</details>
<details>
  <summary>i686-openbsd</summary>

```
target_pointer_width: "32"
target_env: ""
target_vendor: "unknown"
target_endian: "little"
target_os: "openbsd"
target_family: "unix"
target_arch: "x86"
```
</details>
<details>
  <summary>sparc64-openbsd</summary>

```
target_pointer_width: "64"
target_env: ""
target_vendor: "unknown"
target_endian: "big"
target_os: "openbsd"
target_family: "unix"
```
</details>
<details>
  <summary>x86_64-openbsd</summary>

```
target_pointer_width: "64"
target_env: ""
target_vendor: "unknown"
target_endian: "little"
target_os: "openbsd"
target_family: "unix"
target_feature: "fxsr"
target_feature: "sse"
target_feature: "sse2"
target_feature: "mmx"
target_arch: "x86_64"
```
</details>
<details>
  <summary>aarch64-wrs-vxworks</summary>

```
target_pointer_width: "64"
target_env: "gnu"
target_vendor: "wrs"
target_endian: "little"
target_os: "vxworks"
target_family: "unix"
```
</details>
<details>
  <summary>arm-wrs-vxworks7</summary>

```
target_pointer_width: "32"
target_env: "gnu"
target_vendor: "wrs"
target_endian: "little"
target_os: "vxworks"
target_family: "unix"
```
</details>

<details>
  <summary>i686-wrs-vxworks, i686-wrs-vxworksae</summary>

```
target_pointer_width: "32"
target_env: "gnu"
target_vendor: "wrs"
target_endian: "little"
target_os: "vxworks"
target_family: "unix"
target_arch: "x86"
```
</details>
<details>
  <summary>mips-wrs-vxworks, powerpc-wrs-vxworksae, powerpc-wrs-vxworks, powerpc-wrs-vxworksmils, sh-wrs-vxworks, sparc-wrs-vxworks</summary>

```
target_pointer_width: "32"
target_env: "gnu"
target_vendor: "wrs"
target_endian: "big"
target_os: "vxworks"
target_family: "unix"
```
</details>
<details>
  <summary>arm-uclinux_eabi, bfin-uclinux, c6x-uclinux</summary>

```
target_endian: "little"
target_pointer_width: "32"
```
</details>

<details>
  <summary>lm32-uclinux, m68k-uclinux, moxie-uclinux, xtensa-uclinux</summary>

```
target_endian: "big"
target_pointer_width: "32"
```
</details>

Co-authored-by: Iain Buclaw <ibuclaw@gdcproject.org>
2022-10-19 17:45:47 +00:00
bors[bot]
9ecbc90087 Merge #1602
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>
2022-10-19 17:04:07 +00:00
Arthur Cohen
8949098072 ast: Improve Fragment API 2022-10-19 15:01:53 +02:00
Arthur Cohen
540d896c3f rust: Replace uses of ASTFragment -> Fragment 2022-10-19 15:01:53 +02:00
Arthur Cohen
4f2c1499fe ast: Refactor ASTFragment -> Fragment class 2022-10-19 14:54:47 +02:00
Philip Herron
0a52177612 Add check for recursive trait cycles
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
2022-10-17 11:37:23 +01:00
bors[bot]
381e061438 Merge #1597
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>
2022-10-17 10:04:40 +00:00
Arthur Cohen
15229ea41f dump: Dump macro rules definition
Co-authored-by: jdupak <dev@jakubdupak.com>
2022-10-17 11:35:09 +02:00
bors[bot]
a14da50ebe Merge #1594 #1595
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>
2022-10-17 09:33:26 +00:00
Jakub Dupak
b2add32145 ast: Module: unloaded module and inner attributes
Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2022-10-15 21:30:40 +02:00
bors[bot]
3922772f5f Merge #1548 #1593
1548: Dump module items r=CohenArthur a=CohenArthur



1593: ast: dump TypeAlias r=CohenArthur a=jdupak

Implements ast dump for TypeAlias

Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
Co-authored-by: Jakub Dupak <dev@jakubdupak.com>
2022-10-14 16:19:29 +00:00
Arthur Cohen
25d243dd18 dump: Fix module dumping
Co-authored-by: jdupak <dev@jakubdupak.com>
2022-10-14 18:01:03 +02:00
bors[bot]
cba464b9e0 Merge #1590
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>
2022-10-14 15:42:47 +00:00
Arthur Cohen
b6d4c62a84 dump: Dump items within modules 2022-10-14 17:22:20 +02:00
Arthur Cohen
85651630ad dump: Emit visibility when dumping items 2022-10-14 17:22:18 +02:00
Philip Herron
68af6007a9 Support outer attribute handling on trait items just like normal items
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
2022-10-14 16:06:33 +01:00
Jakub Dupak
95be10245b ast: dump TypeAlias
Signed-off-by: Jakub Dupak <dev@jakubdupak.com>
2022-10-14 16:41:25 +02:00
bors[bot]
fa0bd80192 Merge #1580
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>
2022-10-14 14:41:18 +00:00
Philip Herron
e8c82076bc Refactor TraitResolver to not require a visitor
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.
2022-10-14 14:00:16 +01:00
bors[bot]
c85492954d Merge #1587
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>
2022-10-14 09:31:25 +00:00
bors[bot]
84ca2f9123 Merge #1583
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>
2022-10-14 08:52:42 +00:00
David Faust
d27cb6e128 ast: dump: RangeExprs 2022-10-13 13:35:56 -07:00
David Faust
53e2df36a2 ast: dump: various simple Exprs
Adds dump for:
- BorrowExpr
- DereferenceExpr
- ErrorPropagationExpr
- NegationExpr
- TypeCastExpr
- GroupedExpr
2022-10-13 13:35:56 -07:00
David Faust
6927e3ee00 ast: dump: ArrayExpr 2022-10-13 13:35:56 -07:00
David Faust
191907df1f ast: dump: ComparisonExpr and LazyBooleanExpr 2022-10-13 13:31:40 -07:00
David Faust
45326391da ast: dump: minor fixups to IfExpr formatting 2022-10-13 13:31:40 -07:00
David Faust
a5a8628230 ast: dump: fix extra newline in block without tail 2022-10-13 13:31:40 -07:00
bors[bot]
8cbcff46d3 Merge #1584
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>
2022-10-13 15:09:01 +00:00
Philip Herron
9bac2dbfe9 Method resolution must support multiple candidates
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
2022-10-13 15:45:16 +01:00
Iain Buclaw
a02750e8dd rust: Implement TARGET_RUST_OS_INFO for *-*-*linux*.
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.
2022-10-13 16:42:23 +02:00
Iain Buclaw
89babdf791 rust: Implement TARGET_RUST_OS_INFO for i[34567]86-*-mingw* and x86_64-*-mingw*.
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.
2022-10-13 16:41:14 +02:00
Iain Buclaw
ff87a2fbd0 rust: Implement TARGET_RUST_OS_INFO for *-*-fuchsia*.
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.
2022-10-13 16:40:26 +02:00
Iain Buclaw
cbea188073 rust: Implement TARGET_RUST_OS_INFO for *-*-vxworks*
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.
2022-10-13 14:40:34 +02:00
Iain Buclaw
1fc003cb99 rust: Implement TARGET_RUST_OS_INFO for *-*-dragonfly*
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.
2022-10-13 14:34:45 +02:00
Iain Buclaw
587d78dbfe rust: Implement TARGET_RUST_OS_INFO for *-*-solaris2*.
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.
2022-10-13 10:06:42 +02:00
Iain Buclaw
47ad158d21 rust: Implement TARGET_RUST_OS_INFO for *-*-openbsd*
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.
2022-10-13 10:04:30 +02:00
Iain Buclaw
320d13e50f rust: Implement TARGET_RUST_OS_INFO for *-*-netbsd*
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.
2022-10-13 10:03:12 +02:00
Iain Buclaw
41eb78512b rust: Implement TARGET_RUST_OS_INFO for *-*-freebsd*
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.
2022-10-13 10:03:12 +02:00
bors[bot]
1a871569f6 Merge #1570
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>
2022-10-12 13:11:15 +00:00
Philip Herron
0a9a3e826f Add ABI mappings for rust-call to map to ABI::RUST 2022-10-12 12:34:55 +01:00
Philip Herron
63d901e48f Add mappings for fn_once lang item 2022-10-12 12:34:39 +01:00
Philip Herron
32e45c4076 Support type resolution on super traits on dyn objects
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
2022-10-12 12:27:45 +01:00
Arthur Cohen
6dca194d4b early-name-resolver: Add simple macro name resolution
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.
2022-10-11 16:13:30 +02:00
Arthur Cohen
113f73f368 ast: Add accept_vis() method to GenericArg 2022-10-11 15:58:06 +02:00
Arthur Cohen
3dc104bc8a rust-ast-resolve-item: Add note about resolving glob uses 2022-10-11 15:55:41 +02:00
Arthur Cohen
5346330e86 mappings: Add MacroInvocation -> MacroRulesDef mappings 2022-10-11 15:55:41 +02:00
bors[bot]
3e7320510e Merge #1574
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>
2022-10-10 16:46:57 +00:00
Marc Poulhiès
d4c07a9b47 fix ICE on missing closing paren
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>
2022-10-08 10:08:20 +02:00
bors[bot]
06fe912b70 Merge #1572
1572: AST: dump structs, unions and enums r=dafaust a=dafaust



Co-authored-by: David Faust <david.faust@oracle.com>
2022-10-07 18:17:39 +00:00
bors[bot]
bef31ea273 Merge #1543
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>
2022-10-07 11:03:59 +00:00
bors[bot]
e623ee314f Merge #1565
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>
2022-10-07 08:00:32 +00:00
Arthur Cohen
71397abfbe intrinsics: Add data prefetching intrinsics 2022-10-07 10:00:20 +02:00
David Faust
93937bd658 ast: dump structs, enums and unions 2022-10-06 14:00:36 -07:00
David Faust
1f9d7ec437 ast: dump: add format_{tuple,struct}_field helpers 2022-10-06 13:49:44 -07:00
David Faust
b64b889e15 ast: dump: add emit_generic_params helper 2022-10-06 13:47:32 -07:00
Arthur Cohen
4134055f18 lang.opt: Remove overzealous warning initialisation
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
2022-10-06 16:14:30 +02:00
bors[bot]
b4096017e3 Merge #1562
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>
2022-10-06 13:07:50 +00:00
Philip Herron
a7d2643d9b Support looking up super traits for trait items
When supporting calls to super traits we need to allow lookups based on
the super traits as specified on the TraitReferences.

Fixes #1555
2022-10-06 14:07:17 +01:00
Philip Herron
e033f1705d Ensure uniqueness on Path probe's
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
2022-10-06 14:07:16 +01:00
Philip Herron
fc746fd620 Track DefId on ADT variants
We must track the DefID on variants for algebraic data types as this will
allow us to enforce unique'ness on path queries relating to this.
2022-10-06 14:07:16 +01:00
bors[bot]
adaf4561d6 Merge #1564
1564: builtins: Move implementation into source file r=CohenArthur a=CohenArthur



Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
2022-10-06 11:09:18 +00:00
bors[bot]
6e0ba5f8a5 Merge #1547
1547: Dump item visibility r=CohenArthur a=CohenArthur



Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
2022-10-06 10:38:39 +00:00
bors[bot]
40f8c333fe Merge #1554
1554: testing: try loop in const function r=philberty a=abbasfaisal



Co-authored-by: Faisal Abbas <faisal.abbas@elastica.co>
2022-10-06 10:06:57 +00:00
bors[bot]
82971d968b Merge #1563
1563: ast: dump assignment and if expressions r=CohenArthur a=dafaust



Co-authored-by: David Faust <david.faust@oracle.com>
2022-10-06 09:11:43 +00:00
Arthur Cohen
a8b1f98f83 builtins: Move implementation into source file 2022-10-06 10:56:42 +02:00
David Faust
e9e5288a30 ast: dump If expressions 2022-10-05 10:11:38 -07:00
David Faust
d55f22d046 ast: dump assignment and compound assignment expr 2022-10-05 10:10:18 -07:00
Faisal Abbas
5a87f5f469 testing: try loop in const function
Signed-off-by: Faisal Abbas <90.abbasfaisal@gmail.com>
2022-10-03 19:32:30 +01:00
Iain Buclaw
bb5efc657a rust: Implement TARGET_RUST_OS_INFO for *-*-darwin*
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.
2022-09-30 23:54:19 +02:00
Iain Buclaw
f334e18a1f rust: Implement TARGET_RUST_CPU_INFO for i[34567]86-*-* and x86_64-*-*
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.
2022-09-30 23:54:07 +02:00
Iain Buclaw
b220923f96 rust: Reintroduce TARGET_RUST_OS_INFO hook
gcc/ChangeLog:

	* doc/tm.texi: Regenerate.
	* doc/tm.texi.in: Document TARGET_RUST_OS_INFO.

gcc/rust/ChangeLog:

	* rust/rust-session-manager.cc (Session::init): Call
	targetrustm.rust_os_info.
	* rust/rust-target.def (rust_os_info): New hook.
2022-09-30 23:53:26 +02:00
Iain Buclaw
f97e0ca6e4 rust: Reintroduce TARGET_RUST_CPU_INFO hook
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.
2022-09-30 23:53:26 +02:00
Iain Buclaw
066b6b8df9 rust: Add skeleton support and documentation for targetrustm hooks.
gcc/ChangeLog:

	* Makefile.in (tm_rust_file_list, tm_rust_include_list, TM_RUST_H,
	RUST_TARGET_DEF, RUST_TARGET_H, RUST_TARGET_OBJS): New variables.
	(tm_rust.h, cs-tm_rust.h, default-rust.o,
	rust/rust-target-hooks-def.h, s-rust-target-hooks-def-h): New rules.
	(s-tm-texi): Also check timestamp on rust-target.def.
	(generated_files): Add TM_RUST_H and rust-target-hooks-def.h.
	(build/genhooks.o): Also depend on RUST_TARGET_DEF.
	* config.gcc (tm_rust_file, rust_target_objs, target_has_targetrustm):
	New variables.
	* configure: Regenerate.
	* configure.ac (tm_rust_file_list, tm_rust_include_list,
	rust_target_objs): Add substitutes.
	* doc/tm.texi: Regenerate.
	* doc/tm.texi.in (targetrustm): Document.
	(target_has_targetrustm): Document.
	* genhooks.cc: Include rust/rust-target.def.
	* config/default-rust.cc: New file.

gcc/rust/ChangeLog:

	* rust/rust-target-def.h: New file.
	* rust/rust-target.def: New file.
	* rust/rust-target.h: New file.
2022-09-30 23:53:26 +02:00
bors[bot]
8ff035ddc5 Merge #1551
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>
2022-09-30 15:02:32 +00:00
Philip Herron
d1069815fa Add catch for recusive type queries
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
2022-09-30 13:41:09 +01:00
Arthur Cohen
040c5f8933 dump: Emit visibility when dumping items 2022-09-28 11:54:59 +02:00
Arthur Cohen
960d9d289e visibility: Rename get_public_vis_type -> get_vis_type 2022-09-28 11:54:59 +02:00
bors[bot]
9b1ba11b0b Merge #1546
1546: Merge remote-tracking branch 'mainline/master' into ibuclaw/merge_mainline r=philberty a=ibuclaw

Fixes: #1544

Co-authored-by: Jonathan Wakely <jwakely@redhat.com>
Co-authored-by: GCC Administrator <gccadmin@gcc.gnu.org>
Co-authored-by: Torbjörn SVENSSON <torbjorn.svensson@foss.st.com>
Co-authored-by: Mikael Morin <mikael@gcc.gnu.org>
Co-authored-by: Harald Anlauf <anlauf@gmx.de>
Co-authored-by: liuhongt <hongtao.liu@intel.com>
Co-authored-by: Kewen Lin <linkw@linux.ibm.com>
Co-authored-by: Hu, Lin1 <lin1.hu@intel.com>
Co-authored-by: Martin Liska <mliska@suse.cz>
Co-authored-by: Eric Botcazou <ebotcazou@adacore.com>
Co-authored-by: Piotr Trojanek <trojanek@adacore.com>
Co-authored-by: Boris Yakobowski <yakobowski@adacore.com>
Co-authored-by: Justin Squirek <squirek@adacore.com>
Co-authored-by: Tucker Taft <taft@adacore.com>
Co-authored-by: Kévin Le Gouguec <legouguec@adacore.com>
2022-09-27 15:56:30 +00:00
Iain Buclaw
875cb50f9f Update expected warnings post merge 2022-09-27 16:32:46 +02:00
bors[bot]
b71e3dc02a Merge #1545
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 #1455
Fixes #1006
Fixes #1073
Fixes #1272


Co-authored-by: Philip Herron <philip.herron@embecosm.com>
2022-09-27 14:06:08 +00:00
Iain Buclaw
76425e1924 Merge remote-tracking branch 'mainline/master' into ibuclaw/merge_mainline
Fixes: #1544
2022-09-27 13:40:33 +02:00
Philip Herron
b17e69852e Fix missing dead code analysis ICE on local enum definition
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
2022-09-27 12:24:37 +01:00
Philip Herron
b37c71dd77 Add testcase to show forward declared items work via TypeAlias
Fixes #1073
2022-09-27 12:24:37 +01:00
Philip Herron
6cae31a09e Add testcase to show forward declared items work
Fixes #1006
2022-09-27 12:24:37 +01:00
Philip Herron
96c8baa8a7 Refactor TypeResolution to be a simple query based system
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
2022-09-27 12:24:37 +01:00
Philip Herron
770a2449e8 Fix duplicated function generation on higher ranked trait bounds
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.
2022-09-27 12:24:37 +01:00
Philip Herron
3a24dde2e7 Make constexpr constructors type-checking more permissive 2022-09-27 11:37:29 +01:00
Philip Herron
af3b5be6c9 Cleanup formatting of backend expression visitor 2022-09-27 11:34:21 +01:00
bors[bot]
cecd314884 Merge #1521
1521: expand: eager evaluate macros inside builtin macros r=CohenArthur a=liushuyu

- expand: eagerly evaluate the macros inside some of the builtin macros

Co-authored-by: liushuyu <liushuyu011@gmail.com>
2022-09-27 05:26:17 +00:00
liushuyu
1c19256b70 testsuite/rust: add a testcase for testing ...
... builtin macro and decl macro mixed expansion
2022-09-26 22:30:33 -06:00
liushuyu
ca3a03dd74 testsuite: adapt existing testcases 2022-09-26 22:12:42 -06:00
liushuyu
a16c35340c expand: eager evaluate macros inside builtin macros 2022-09-26 22:12:08 -06:00
bors[bot]
8ed1bbaa40 Merge #1542
1542: Merge GCC mainline/master into gccrs/master r=philberty a=ibuclaw

As per title, pull in the latest and greatest from gcc development.

Co-authored-by: Tim Lange <mail@tim-lange.me>
Co-authored-by: GCC Administrator <gccadmin@gcc.gnu.org>
Co-authored-by: Martin Liska <mliska@suse.cz>
Co-authored-by: Javier Miranda <miranda@adacore.com>
Co-authored-by: Bob Duff <duff@adacore.com>
Co-authored-by: Patrick Bernardi <bernardi@adacore.com>
Co-authored-by: Steve Baird <baird@adacore.com>
Co-authored-by: Gary Dismukes <dismukes@adacore.com>
Co-authored-by: Eric Botcazou <ebotcazou@adacore.com>
Co-authored-by: Justin Squirek <squirek@adacore.com>
Co-authored-by: Piotr Trojanek <trojanek@adacore.com>
Co-authored-by: Joffrey Huguet <huguet@adacore.com>
Co-authored-by: Yannick Moy <moy@adacore.com>
2022-09-26 09:30:08 +00:00
bors[bot]
6d98713a7b Merge #1527 #1529 #1530 #1534
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>
2022-09-26 07:36:56 +00:00
Arthur Cohen
138a626012 rust: Add -frust-compile-until option
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.
2022-09-26 09:32:34 +02:00
bors[bot]
cfd2938f06 Merge #1532
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>
2022-09-26 06:58:57 +00:00
Iain Buclaw
033a459935 Update expected warnings post merge 2022-09-24 20:32:49 +02:00
Iain Buclaw
13de60fb8e Merge remote-tracking branch 'mainline/master' into ibuclaw/targetrustm 2022-09-24 16:23:43 +02:00
bors[bot]
6da3cab7b0 Merge #1541
1541: Static const eval safety r=philberty a=philberty

This adds a test case for the rust issue: https://blog.rust-lang.org/2022/09/15/const-eval-safety-rule-revision.html

Co-authored-by: Philip Herron <philip.herron@embecosm.com>
2022-09-22 12:20:49 +00:00
Philip Herron
5f01d6c537 Add testcase for const-eval issue from rust-blog
see:
https://blog.rust-lang.org/2022/09/15/const-eval-safety-rule-revision.html
2022-09-18 10:37:35 +01:00
Philip Herron
a6bb21fca5 remove bad assertion 2022-09-17 10:06:48 +01:00
Philip Herron
6b6a1c70f4 Statics are a coercion site
Statics can be assigned to a block expression meaning they need to behave
similarly to constant items.
2022-09-17 10:05:59 +01:00
Philip Herron
53f4a8601c Static Items must be const evaluated
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.
2022-09-17 10:04:49 +01:00
Arthur Cohen
d4da06f721 module lowering: Do not append null pointers as items
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
2022-09-14 10:27:51 +02:00
Arthur Cohen
c71b174a29 attributes: Add #[macro_use] as builtin 2022-09-13 16:33:21 +02:00
Arthur Cohen
7ebe669336 const generics: Forbid default values in Functions, Traits and Impls 2022-09-13 09:37:40 +02:00
Arthur Cohen
5a019b1e71 const generics: Make sure const generic types are visited properly in
all contexts
2022-09-12 15:53:01 +02:00
bors[bot]
f252b40936 Merge #1528
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>
2022-09-08 00:39:35 +00:00
bors[bot]
f03760b98b Merge #1526
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>
2022-09-08 00:08:07 +00:00
liushuyu
6839ad40ee testsuite: add loop condition execution test 2022-09-06 22:41:17 -06:00
Faisal Abbas
908f1e2022 add testcase with struct to test component_ref and constructor codes in
eval_constant_expression()
2022-09-06 22:27:59 +01:00
liushuyu
bed01725c1 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.
2022-09-05 17:57:43 -06:00
bors[bot]
8c6b017310 Merge #1522
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>
2022-09-05 11:45:24 +00:00
Faisal Abbas
a876e9e8f0 add testcase to test component_ref and constructor codes in eval_constant_expression() 2022-09-04 17:49:44 +01:00
Faisal Abbas
a4f07c8391 bugfix: initialize slice from array in const context 2022-09-04 16:45:41 +01:00
bors[bot]
4f0a2729d7 Merge #1519
1519: Fix generic substitution on unit structs r=philberty a=philberty

Fixes #1518

Co-authored-by: Philip Herron <philip.herron@embecosm.com>
2022-08-31 21:38:32 +00:00
Philip Herron
63403f0af7 Unit structs are not concrete when they need substitutions
Fixes #1518
2022-08-31 17:17:04 +01:00
Philip Herron
126c7c9d7a Add new check for contains_associated_types
We don't need to setup associated types when a trait does not contain any
associated types.
2022-08-31 17:17:03 +01:00
Philip Herron
721c7a472c Add extra debugging for method call expressions 2022-08-31 17:17:03 +01:00
bors[bot]
ceb43210f8 Merge #1505
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>
2022-08-31 13:21:19 +00:00
Philip Herron
5acb1375c9 Create canonical process of compiling constant items
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.
2022-08-31 14:08:59 +01:00
Philip Herron
b1cf3a384d Remove param_use_canonical_types checks ported from c++ front-end
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.
2022-08-31 14:08:43 +01:00
bors[bot]
9b210f1c54 Merge #1517
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>
2022-08-31 12:50:21 +00:00
Philip Herron
5a0c27cb79 Refactor unify to hit a unify_site
This allows us to enforce better error handling on unify sites
2022-08-31 13:49:27 +01:00
Philip Herron
119b4c0982 Add missing location info to coercions 2022-08-31 11:36:52 +01:00
Philip Herron
5175404928 Add guards against getting data from an empty vector 2022-08-31 11:36:52 +01:00
bors[bot]
ebb127f2ae Merge #1408 #1503 #1511
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>
2022-08-31 09:47:45 +00:00
bors[bot]
45f80a2d86 Merge #1514
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>
2022-08-31 09:15:27 +00:00
Arthur Cohen
fcf6fea382 ast: Add better assertion on AST fragments
Co-authored-by: philberty <philip.herron@embecosm.com>
2022-08-31 11:16:59 +02:00
Arthur Cohen
842829a591 ast: Only expand expressions and types if the kind is right 2022-08-31 11:16:59 +02:00
Arthur Cohen
2bf4f17d1f dump: Add AST debugging using the AST::Dump class 2022-08-31 11:16:59 +02:00
bors[bot]
017be6aeb8 Merge #1515 #1516
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>
2022-08-30 09:41:27 +00:00
Arthur Cohen
8dfa9676db transcriber: Do not infinite loop if the current parsed node is an error
Co-authored-by: philberty <philip.herron@embecosm.com>
2022-08-30 11:07:25 +02:00
bors[bot]
be5e11036e Merge #1513
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>
2022-08-30 09:04:11 +00:00
Arthur Cohen
32be5443e3 macros: Handle matchers properly in repetitions 2022-08-30 11:04:16 +02:00
Arthur Cohen
b376c0cb37 parser: Parse RangeFullExpr without erroring out 2022-08-29 16:42:31 +02:00
Arthur Cohen
2a607410e5 bors: Fix expected warning list 2022-08-29 11:28:10 +02:00
Arthur Cohen
a8403dd7fa fmt: Fix formatting in rust-diagnostics 2022-08-29 10:46:28 +02:00
David Malcolm
bc2fe97fad Experiment with adding an error code to an error 2022-08-29 10:39:36 +02:00
David Malcolm
05f1f87274 diagnostics: add error_meta 2022-08-29 10:28:13 +02:00
bors[bot]
64c7a90934 Merge #1510
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>
2022-08-27 09:02:41 +00:00
bors[bot]
76f89f0fc5 Merge #1512
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>
2022-08-26 20:04:01 +00:00
Philip Herron
8e9dcd47d3 Add missing language selection for rs6000 2022-08-26 21:02:19 +01:00
Arthur Cohen
702bb4bb01 lint: Do not emit unused warnings for public items 2022-08-26 14:34:18 +02:00
Arthur Cohen
c6a7ab78ff rustc_attrs: Allow rustc_inherit_overflow_checks as a builtin
attribute

We cannot yet handle this attribute, but we should not reject it either
2022-08-26 14:06:23 +02:00
bors[bot]
732997e93f Merge #1509
1509: constexpr: Fix warning in sorry fmt string r=philberty a=CohenArthur

Closes #1508 

Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
2022-08-26 09:37:51 +00:00
Arthur Cohen
bcab5d906c constexpr: Fix warning in sorry fmt string 2022-08-26 11:06:54 +02:00
Arthur Cohen
fc82b68cc1 backend: Add overflow checks to every arithmetic operation 2022-08-26 08:44:02 +02:00
bors[bot]
595cbafdf3 Merge #1507
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>
2022-08-25 15:24:50 +00:00
Arthur Cohen
ff7d6bfed2 builtins: Add add_overflow builtin and refactor class 2022-08-25 17:16:13 +02:00
Arthur Cohen
3e79563a65 backend: Expose Bvariable class through rust-gcc header 2022-08-25 17:15:31 +02:00
bors[bot]
1416b85322 Merge #1499
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>
2022-08-25 14:35:59 +00:00
Philip Herron
727afe64d6 Desugar double borrows into two HIR:BorrowExpr's
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
2022-08-25 15:33:02 +01:00
bors[bot]
5b3c4be73f Merge #1473
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>
2022-08-25 14:03:30 +00:00
Philip Herron
43b7dd91fb Fix warnings on diagnostics 2022-08-25 14:51:26 +01:00
Philip Herron
c52268c6d2 Add testcase for const array index expressions 2022-08-25 13:46:39 +01:00
Philip Herron
49cddf6e58 Fix up missing jump_target handling
This adds in missed ported code for handling VAR_DECLS and jump's within
statement lists.
2022-08-25 13:20:09 +01:00
Philip Herron
a3e1361d1a Fix port of NOP_EXPR
NOP_EXPR should fall through into convert and view_convert_exprs.
2022-08-25 12:40:28 +01:00
Faisal Abbas
5a8f2fd653 rust-constexpr.cc: fixes
- 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>
2022-08-25 12:40:28 +01:00
Faisal Abbas
f83e254c29 rust-constexpr.cc: fix warnings for unused variables for unsupported bits
Signed-off-by: Faisal Abbas <90.abbasfaisal@gmail.com>
2022-08-25 12:40:28 +01:00
Faisal Abbas
2f7fbbaad1 rust-constexpr.cc: fix build error 2022-08-25 12:40:28 +01:00
Faisal Abbas
0f8e2c1e2f rust-tree.cc: comment some important code instead of removing it. 2022-08-25 12:40:28 +01:00
Faisal Abbas
4ca228d2f3 rust-constexpr.cc: port over cxx_eval_array_reference and
cxx_eval_component_reference.

Some important parts are commented out and marked such. These will
need revisiting.
2022-08-25 12:40:28 +01:00
Faisal Abbas
debe4aedc7 rust-constexpr.cc: port over potential_constant_expression_1() 2022-08-25 12:40:28 +01:00
Faisal Abbas
533effe0f3 rust constexpr: port over cxx_eval_builtin_function_call().
It still needs potential_constant_expression_1() which will be continued
to be ported over.

Signed-off-by: Faisal Abbas <90.abbasfaisal@gmail.com>
2022-08-25 12:40:27 +01:00
Faisal Abbas
8c2da345e0 rust constexpr: porting cxx_eval_builtin_function_call
Signed-off-by: Faisal Abbas <90.abbasfaisal@gmail.com>
2022-08-25 12:40:27 +01:00
Faisal Abbas
9350b3733a rust constexpr: conttinue porting cxx_eval_builtin_function_call
Signed-off-by: Faisal Abbas <90.abbasfaisal@gmail.com>
2022-08-25 12:40:27 +01:00
Faisal Abbas
1c53bc4fc8 rust constexpr: conttinue porting cxx_eval_builtin_function_call
Signed-off-by: Faisal Abbas <90.abbasfaisal@gmail.com>
2022-08-25 12:40:27 +01:00
Faisal Abbas
e1170b0abe rust constexprC: start porting cxx_eval_builtin_function_call
Signed-off-by: Faisal Abbas <90.abbasfaisal@gmail.com>
2022-08-25 12:40:27 +01:00
Faisal Abbas
bd31c63fe1 rust-constexpr.cc: port over more cases to eval_constant_expression 2022-08-25 12:40:27 +01:00
Faisal Abbas
a38ad0b614 rust-constexpr.cc: port over more cases to eval_constant_expression 2022-08-25 12:40:27 +01:00
Faisal Abbas
d780f02a54 rust-constexpr.cc: port over cxx_eval_outermost_constant_expr 2022-08-25 12:40:27 +01:00
Faisal Abbas
6b440d46f1 rust-constexpr.cc: add few more cases to eval_constant_expression() 2022-08-25 12:40:27 +01:00
Faisal Abbas
3e6dfca316 rust-constexpr.cc: port over cxx_eval_vector_conditional_expression 2022-08-25 12:40:26 +01:00
Faisal Abbas
bbc514d024 rust-constexpr.cc: port over cxx_eval_bare_aggregate. Comments out build_ctor_subob_ref
inside init_subob_ctx.
2022-08-25 12:40:26 +01:00
Faisal Abbas
c628a66a92 rust-constexpr.cc: port over more cases to eval_constant_expression().
Its possible many of them are not useful for Rust so we can remove them
in the clean up expected later.
2022-08-25 12:40:26 +01:00
Faisal Abbas
e8e58d54db rust-constexpr.cc: port over cxx_eval_logical_expression 2022-08-25 12:40:26 +01:00
Faisal Abbas
30b2f58b54 rust-constexpr.cc: port MEF_REF and INDIRECT_REF cases to eval_constant_expression(). 2022-08-25 12:40:26 +01:00
Faisal Abbas
266891d17c rust-constexpr.cc: port VIEW_CONVERT_EXPR and CONVERT_EXPR cases to
eval_constant_expression(). Throws away code under UNARY_PLUS_EXPR
and PTRMEM_CST as those tree codes come from cp-tree.def.
2022-08-25 12:40:26 +01:00
Faisal Abbas
fdbe92d898 rust-constexpr.cc: port over NOP_EXPR case and fold_indrect_ref_1() 2022-08-25 12:40:25 +01:00
Faisal Abbas
23bde7d7c6 rust-constexpr.cc: port over cxx_eval_unary_expression 2022-08-25 12:40:25 +01:00
Faisal Abbas
e991065fdb rust-constexpr.cc: port over cxx_eval_switch_expr 2022-08-25 12:40:25 +01:00
Faisal Abbas
f21f475fec rust-constexpr.cc: add more cases to eval_constant_expression()
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
2022-08-25 12:40:25 +01:00
Faisal Abbas
a360c28cb6 rust-constexpr.cc: port over cxx_eval_bit_field_ref
Signed-off-by: Faisal Abbas <90.abbasfaisal@gmail.com>
2022-08-25 12:40:25 +01:00
Faisal Abbas
17663caca4 gccrs constant folding port: ports over
- 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>
2022-08-25 12:40:25 +01:00
Philip Herron
d4e80fd645 Each intrinsic needs marked as const
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.
2022-08-25 12:40:25 +01:00
Philip Herron
4fe7b96c27 Const functions need to be marked as DECL_DECLARED_CONSTEXPR_P
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.
2022-08-25 12:40:25 +01:00
Philip Herron
8a9b94d8c3 Port over:
- 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.
2022-08-25 12:40:24 +01:00
Philip Herron
44b80bf024 Port over context structures 2022-08-25 12:40:24 +01:00
Faisal Abbas
bb4dd8fbc8 gccrs const folding port: continue porting potential_constant_expression_1()
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>
2022-08-25 12:40:24 +01:00
Faisal Abbas
121c8dd00d gccrs const folding port: continue porting potential_constant_expression_1()
Following functions are ported in this changeset:
 - resolve_nondeduced_context
 - instantiate_non_dependent_or_null
 - resolve_nondeduced_context_or_error
 - really_overloaded_fn
 - invalid_nonstatic_memfn_p
 - strip_top_quals
 - cxx_incomplete_type_inform
 - cxx_incomplete_type_diagnostic
 - cxx_incomplete_type_error

Following structs, classes and enums are ported in this changeset:
 - stmt_tree_s
 - c_language_function
 - omp_declare_target_attr
 - cxx_binding
 - cxx_saved_binding
 - saved_scope
 - named_label_hash
 - language_function
 - ref_operator

Signed-off-by: Faisal Abbas <90.abbasfaisal@gmail.com>
2022-08-25 12:40:24 +01:00
Faisal Abbas
a00b61e6bf gccrs const folding port: continue porting potential_constant_expression_1()
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>
2022-08-25 12:40:24 +01:00
Faisal Abbas
7c13a2e587 gccrs const folding port: start porting cxx_eval_array_reference()
Following functions are ported in this changeset:
 - array_index_cmp
 - unshare_constructor
 - find_array_ctor_elt
 - reduced_constant_expression_p
 - verify_constant
 - diag_array_subscript
 - get_array_or_vector_nelts
 - eval_and_check_array_index
 - extract_string_elt
 - free_constructor
 - cv_unqualified
 - make_tree_vector
 - release_tree_vector
 - vec_safe_push

Following structs, classes and enums are ported in this changeset:
 - releasing_vec

Signed-off-by: Faisal Abbas <90.abbasfaisal@gmail.com>
2022-08-25 12:40:24 +01:00
Faisal Abbas
a5b583d021 gccrs const folding port: continue porting potential_constant_expression_1()
Following functions are ported in this changeset:
 - next_initializable_field
 - sufficient_parms_p
 - default_ctor_p
 - user_provided_p
 - type_has_non_user_provided_default_constructor
 - default_init_uninitialized_part
 - extract_conversion_operator
 - get_class_binding_direct
 - lang_check_failed
 - skip_artificial_parms_for
 - in_class_defaulted_default_constructor
 - is_instantiation_of_constexpr
 - check_for_uninitialized_const_var

Signed-off-by: Faisal Abbas <90.abbasfaisal@gmail.com>
2022-08-25 12:40:24 +01:00
Faisal Abbas
3343535fdb gccrs const folding port: continue porting potential_constant_expression_1()
Following functions are ported in this changeset:
 - fields_linear_search
 - nothrow_spec_p
 - maybe_get_fns
 - get_fns
 - get_first_fn
 - dependent_name
 - called_fns_equal
 - canonical_eh_spec
 - rs_tree_code_length
 - rs_tree_operand_length
 - rs_tree_equal
 - publicly_uniquely_derived_p
 - comp_except_types
 - comp_except_specs
 - compparms
 - rs_build_qualified_type_real
 - vector_targets_convertible_p
 - comp_array_types
 - same_type_ignoring_top_level_qualifiers_p
 - comp_ptr_ttypes_const
 - similar_type_p
 - structural_comptypes
 - comptypes
 - gnu_vector_type_p
 - set_array_type_canon
 - is_byte_access_type
 - build_cplus_array_type

Following structs, classes and enums are ported in this changeset:
 - named_decl_hash
 - lang_decl_selector
 - lang_decl_base
 - lang_decl_min
 - lang_decl_fn
 - lang_decl_ns
 - lang_decl_parm
 - lang_decl_decomp
 - lang_decl
 - lkp_iterator
 - compare_bounds_t
 - cplus_array_info
 - cplus_array_hasher

Signed-off-by: Faisal Abbas <90.abbasfaisal@gmail.com>
2022-08-25 12:40:24 +01:00
Faisal Abbas
b394fe4571 gccrs const folding port: continue porting potential_constant_expression_1()
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>
2022-08-25 12:40:24 +01:00
Faisal Abbas
b9c08d705e gccrs const folding port: continue porting potential_constant_expression_1()
Following functions are ported in this changeset:
 - type_memfn_quals
 - find_parameter_pack_data
 - conv_type_hasher
 - make_conv_op_name
 - builtin_pack_fn_p
 - builtin_pack_call_p
 - has_extra_args_mechanism_p
 - find_parameter_packs_r
 - type_memfn_rqual
 - maybe_add_lang_type_raw
 - type_of_this_parm
 - class_of_this_parm

Following structs, classes and enums are ported in this changeset:
 - cxx_binding
 - c_common_identifier
 - lang_identifier
 - cp_ref_qualifier
 - find_parameter_pack_data
 - conv_type_hasher

Signed-off-by: Faisal Abbas <90.abbasfaisal@gmail.com>
2022-08-25 12:40:23 +01:00
Faisal Abbas
f6f1984c3e gccrs const folding port: continue porting potential_constant_expression_1()
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
2022-08-25 12:40:23 +01:00
Faisal Abbas
4bae115bfd gccrs const folding port: continue porting potential_constant_expression_1()
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>
2022-08-25 12:40:23 +01:00
Arthur Cohen
a9055d8294 session-manager: Add ast-pretty-expanded dump 2022-08-25 12:00:45 +02:00
Arthur Cohen
b1ddbf1851 dump: Handle more visitors in AST dump 2022-08-25 12:00:44 +02:00
bors[bot]
d3cf195ab4 Merge #1498
1498: Merge from GCC upstream r=philberty a=philberty

Lets see if it builds.

Co-authored-by: GCC Administrator <gccadmin@gcc.gnu.org>
Co-authored-by: Dimitrije Milošević <dimitrije.milosevic@syrmia.com>
Co-authored-by: Aldy Hernandez <aldyh@redhat.com>
Co-authored-by: Jakub Jelinek <jakub@redhat.com>
Co-authored-by: Martin Liska <mliska@suse.cz>
Co-authored-by: Roger Sayle <roger@nextmovesoftware.com>
Co-authored-by: Sam Feifer <sfeifer@redhat.com>
Co-authored-by: Andrew Stubbs <ams@codesourcery.com>
Co-authored-by: Jose E. Marchesi <jose.marchesi@oracle.com>
Co-authored-by: H.J. Lu <hjl.tools@gmail.com>
Co-authored-by: David Malcolm <dmalcolm@redhat.com>
Co-authored-by: Richard Biener <rguenther@suse.de>
Co-authored-by: Immad Mir <mirimmad@outlook.com>
2022-08-24 16:50:14 +00:00
Arthur Cohen
2e77960b14 merge: Update bors' expected warnings 2022-08-24 17:10:43 +02:00
bors[bot]
825a44b40c Merge #1497
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>
2022-08-23 19:16:47 +00:00
bors[bot]
241fcaacf6 Merge #1500
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>
2022-08-23 14:29:21 +00:00
Philip Herron
a15ee6c3e5 Remove missed target hooks code 2022-08-23 14:48:25 +01:00
Philip Herron
57f0c9d646 Merge remote-tracking branch 'gcc/master' into phil/gcc-upstream-merge
This merges GCC as of baa3ffb19c into gccrs
2022-08-23 14:31:03 +01:00
Philip Herron
36a9255b1b Refactor our casts to follow the Rustc implemention
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
2022-08-23 14:06:40 +01:00
bors[bot]
8d1a6deb4e Merge #1493
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>
2022-08-22 14:37:10 +00:00
Philip Herron
56f503b88a Qualified paths can have an optional as clause
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
2022-08-22 12:55:34 +01:00
Philip Herron
6dea70e1da Cleanup canonical path usage on impl blocks 2022-08-22 12:27:31 +01:00
bors[bot]
0f4ec11e8c Merge #1492
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>
2022-08-19 21:06:50 +00:00
Philip Herron
fdbf789c2b Redo coercion site code
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.
2022-08-19 21:59:00 +01:00
bors[bot]
abfd358d75 Merge #1491
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>
2022-08-19 14:12:15 +00:00
David Faust
6758b6c5b0 typecheck: resolve tuple elt against parent elt
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.
2022-08-18 09:18:47 -07:00
bors[bot]
5391805604 Merge #1477
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>
2022-08-17 14:34:14 +00:00
Philip Herron
73e7917948 Refactor backend to use finegrained visitors
This also moves more code out of the headers to their associated impl files
to improve compilation times and code navigation.
2022-08-17 13:01:13 +01:00
bors[bot]
36f52d2a90 Merge #1471
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>
2022-08-17 11:34:00 +00:00
bors[bot]
4f039ff9f6 Merge #1474
1474: unsafe: Allow calls to safe intrinsics r=CohenArthur a=CohenArthur

Fixes #1461 

Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
2022-08-17 10:30:28 +00:00
Philip Herron
42a105c55f Update expected warnings post cleanup 2022-08-17 10:55:01 +01:00
Arthur Cohen
3b8642ed96 unsafe: Allow calls to safe intrinsics 2022-08-16 14:21:24 +02:00
bors[bot]
4665766d3c Merge #1459
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>
2022-08-16 10:39:44 +00:00
Arthur Cohen
f68ecc7e59 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>())`

Finally, unlike most intrinsics, copy_nonoverlapping must be marked as impure

Co-authored-by: philbert <philip.herron@embecosm.com>
2022-08-16 11:29:00 +02:00
Thomas Schwinge
3cd9342634 Disable 'TARGET_RUST_CPU_INFO', 'TARGET_RUST_OS_INFO'
This finishes the revert of all the target hook info work.

Co-authored-by: Philip Herron <philip.herron@embecosm.com>
2022-08-12 16:04:34 +01:00
Philip Herron
1c8ebf6696 Revert GCC changes to ff7aeceb6b 2022-08-12 16:04:17 +01:00
bors[bot]
021e495339 Merge #1465 #1467
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>
2022-08-12 12:11:26 +00:00
bors[bot]
fadc704751 Merge #1466
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>
2022-08-12 11:40:14 +00:00
bors[bot]
3399688a1b Merge #1468
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>
2022-08-12 06:31:13 +00:00
Philip Herron
2f15ae7493 Revert "Ensure we set TREE_SIDE_EFFECTS on call expressions"
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.
2022-08-11 16:15:35 +01:00
Philip Herron
d4ddd73b0b Desugar HIR::IdentifierExpr into HIR::PathInExpression
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
2022-08-11 15:55:28 +01:00
Philip Herron
9caea7bcf8 Dont return error_mark_node on bad CallExpr arguments
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.
2022-08-11 15:50:12 +01:00
bors[bot]
70a0039b82 Merge #1464
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>
2022-08-11 13:33:48 +00:00
bors[bot]
e57bbcb241 Merge #1458 #1463
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>
2022-08-11 12:59:01 +00:00
Arthur Cohen
8899dc9bf7 intrinsics: Add wrapping_{add, sub, mul}
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.
2022-08-11 14:52:40 +02:00
Philip Herron
46ef912923 Remove unused include in HIR 2022-08-11 13:17:45 +01:00
bors[bot]
b28f138483 Merge #1462
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>
2022-08-11 12:00:27 +00:00
Philip Herron
d91796f90d Remove unused prototypes 2022-08-11 12:55:44 +01:00
Philip Herron
113b830ca0 Remove unused switch statement wrapper 2022-08-11 12:54:42 +01:00
Philip Herron
f891a13aa2 Ensure we set TREE_SIDE_EFFECTS on call expressions
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
2022-08-11 12:34:13 +01:00
Philip Herron
2ad0cde0a5 Refactor the TypeResolution pass to use fine grained visitors
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
2022-08-11 09:52:13 +01:00
Philip Herron
630ef83dfc Refactor helper from TypeCheckResolveToplevel
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
2022-08-11 09:52:13 +01:00
bors[bot]
eca2ac2c23 Merge #1453
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>
2022-08-10 11:06:18 +00:00
bors[bot]
7027e5c21a Merge #1452
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>
2022-08-10 10:35:07 +00:00
Arthur Cohen
71b5bc8705 transmute: Fix behavior by always performing the raw copy
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>
2022-08-10 12:36:26 +02:00
bors[bot]
7c3766ccfc Merge #1454
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>
2022-08-10 10:03:11 +00:00
Philip Herron
50bb06ce3b Seperate 64 and 32 bit testing combos into seperate jobs
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.
2022-08-10 10:51:26 +01:00
Arthur Cohen
fc8d5dfe93 intrinsics: Refactor compilation of intrinsics
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
2022-08-10 10:32:44 +02:00
bors[bot]
349b0f8ed4 Merge #1445
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>
2022-08-10 06:29:06 +00:00
Arthur Cohen
45095d73f1 compile: Move and rename SimpleIntrinsics -> BuiltinsContext
This will allow us to use the class for more than just math builtins
2022-08-10 08:28:42 +02:00
Philip Herron
6496291f34 Enforce win64 abi test to always run on -m64 mode
Fixes #1439
2022-08-09 16:35:37 +01:00
Philip Herron
fefd8633dc Remove 128bit code generation from test case
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
2022-08-09 16:18:33 +01:00
Philip Herron
4db24e3f2b Add in -m32,-m64 configuration to make check-rust
This is to gate PR's which might break builds on 32bit systems.

Addresses #1439
2022-08-09 15:33:31 +01:00
bors[bot]
5865fb27a7 Merge #1425 #1451
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>
2022-08-09 14:25:07 +00:00
bors[bot]
17b625cbd6 Merge #1444
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>
2022-08-09 13:48:52 +00:00
Arthur Cohen
4ffd884a69 const-checker: Add is_const_extern_fn helper function
Co-authored-by: philberty <philip.herron@embecosm.com>
2022-08-09 09:37:41 +02:00
Philip Herron
92eef6c33d Fix type inference on unit-structs
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
2022-08-08 17:24:48 +01:00
Philip Herron
b9840366b6 Unify generic substitutions on unit-structs
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
2022-08-08 17:23:27 +01:00
Philip Herron
e0a14f4839 ADT's and tuples are valid to be unified with inference variables
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
2022-08-08 17:08:01 +01:00
bors[bot]
8749b66879 Merge #1438
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>
2022-08-08 09:28:26 +00:00
Arthur Cohen
084f959076 attr: Handle rustc_const_{un}stable properly
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.
2022-08-08 09:07:54 +02:00
bors[bot]
c8f65b3fc8 Merge #1442
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>
2022-08-08 05:47:41 +00:00
liushuyu
ab9b1e4dea testsuite: test for diagnostics shown ...
... when a built-in macro does not exist
2022-08-07 23:44:08 -06:00
Thomas Schwinge
23702abda4 Enhance #1426 "Invalid recursive :stmt expansion in fragment specifiers" test case
... 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.
2022-08-06 13:16:31 +02:00
bors[bot]
7beea479c5 Merge #1437
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>
2022-08-05 13:38:37 +00:00
Philip Herron
c86ac620c2 Array index access does not need to unsize to a slice for access
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
2022-08-05 14:37:41 +01:00
bors[bot]
8725e324aa Merge #1435
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>
2022-08-05 12:42:24 +00:00
Philip Herron
f70783d063 Update the type hasher to stop duplication of aggregate types
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
2022-08-05 13:03:01 +01:00
bors[bot]
a39108dea1 Merge #1431
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>
2022-08-05 10:09:20 +00:00
bors[bot]
e77bc10ba1 Merge #1433
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>
2022-08-05 09:33:52 +00:00
bors[bot]
bc65cac0e7 Merge #1430
1430: hir: more conformant builtin macro detection r=philberty a=liushuyu

- hir: more conformant builtin macro detection

Fixes #971 

Co-authored-by: liushuyu <liushuyu011@gmail.com>
2022-08-04 19:47:43 +00:00
Philip Herron
7022b9dd10 Fix bad transmute for aggregate types
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
2022-08-04 20:36:46 +01:00
Philip Herron
5d17a8b6b2 Support Autoderef coercions
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
2022-08-04 16:52:52 +01:00
Philip Herron
79d0f29464 Fix ICE in audodref mappings when argument is a method call
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.
2022-08-04 16:52:52 +01:00
Philip Herron
6f88307147 Refactor type resolution of method call expression
This simply moves the implementation of this into a cc file to help with
compilation times.
2022-08-04 16:52:29 +01:00
Philip Herron
da31b651da Update TyTy::can_eq interface for pointers and references
It is valid for pointers and references to unify against inference
variables.
2022-08-04 16:52:29 +01:00
Philip Herron
405d9f1d13 Fix ICE with duplicate hirid on autoderef coercion site mappings
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.
2022-08-04 15:48:37 +01:00
Philip Herron
94e53f8e55 Refactor indirect_expression from the gcc-backend wrapper
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.
2022-08-04 15:48:37 +01:00
Philip Herron
2dc902baa1 Refactor all coercion type calls into a single coercion_site function
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.
2022-08-04 15:48:36 +01:00
Philip Herron
ffb419d6a4 Refactor the autoderef cycle to be a reuseable base class
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.
2022-08-04 15:48:36 +01:00
liushuyu
8141f618bb tree-wide(testsuite): update all the builtin macro tests ...
... now builtin macros need #[rustc_builtin_macro] annotation
2022-08-03 20:22:22 -06:00
liushuyu
df1a201190 hir: more conformant builtin macro detection ...
... 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>
2022-08-03 20:22:11 -06:00
bors[bot]
c788a80619 Merge #1429
1429: expand: correctly handles non-macro nodes r=philberty a=liushuyu

- expand: correctly handles non-macro nodes when expanding macros recursively to avoid improperly stripping them

Fixes #1426

Co-authored-by: liushuyu <liushuyu011@gmail.com>
2022-08-03 09:18:41 +00:00
liushuyu
9fc6a27b5c expand: correctly handles non-macro nodes ...
... when expanding macros recursively to avoid improperly stripping them

Signed-off-by: Zixing Liu <liushuyu011@gmail.com>
2022-08-02 02:19:18 -06:00
bors[bot]
8809ee8c6a Merge #1427
1427: unsafe: Check for unsafe function/method calls r=CohenArthur a=CohenArthur

Addresses #1411 

Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
2022-07-29 16:27:22 +00:00
Arthur Cohen
f742538d13 unsafe: Report errors on calls to unsafe or extern functions and methods 2022-07-29 18:18:54 +02:00
Arthur Cohen
b38dee3d38 mappings: Keep track of extern blocks
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.
2022-07-29 18:18:54 +02:00
Arthur Cohen
e88a55ab69 testsuite: Calls to printf are unsafe 2022-07-29 18:18:54 +02:00
Arthur Cohen
df0dd17b89 testsuite: Calls to transmute are unsafe 2022-07-29 18:18:54 +02:00
bors[bot]
2d824b796c Merge #1421
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>
2022-07-29 12:32:30 +00:00
bors[bot]
7f1685d7f6 Merge #1402
1402: CI Improvements and fixes r=philberty a=liushuyu

- CI: fix Remark check (fix #1340)


Co-authored-by: liushuyu <liushuyu011@gmail.com>
2022-07-29 11:18:16 +00:00
liushuyu
5e63ca064a 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.

Signed-off-by: Zixing Liu <liushuyu011@gmail.com>
2022-07-28 23:29:31 -06:00
bors[bot]
0632b1aa5f Merge #1415
1415: Add generic `StackedContexts<T>` type r=CohenArthur a=CohenArthur



Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
2022-07-28 19:06:19 +00:00
Arthur Cohen
957e6180e1 unsafe: Use StackedContexts class 2022-07-28 21:07:10 +02:00
bors[bot]
6d5eb739f0 Merge #1416
1416: unsafe: Add checks for union field accesses r=CohenArthur a=CohenArthur

Addresses #1411 

Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
2022-07-28 15:37:41 +00:00
Arthur Cohen
0ec8f93827 session-manager: Produce a fatal error if multiple files are specified 2022-07-28 17:29:28 +02:00
Arthur Cohen
237be3f618 rustspec: Remove most unused options from gccgo 2022-07-28 16:51:32 +02:00
bors[bot]
add0846629 Merge #1419
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>
2022-07-28 13:15:44 +00:00
Arthur Cohen
6943066878 unsafe: Take references on mappings and name resolver instead of copies
Co-authored-by: philberty <philp.herron@embecosm.com>
2022-07-28 15:15:36 +02:00
Arthur Cohen
1d86619909 const: Add basic const context checking
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
2022-07-28 15:15:36 +02:00
Arthur Cohen
2160d34c5f hir: Add mappings to ArrayElems 2022-07-28 11:27:31 +02:00
Arthur Cohen
0bf54ff468 util: Add StackedContext class 2022-07-28 11:27:31 +02:00
liushuyu
2a4b58c9b7 CI: fix remark installation pre-condition ...
... update Node.js to the latest LTS branch
2022-07-28 01:50:30 -06:00
Arthur Cohen
f532ae5aa3 unsafe: Add checks for union field accesses
Co-authored-by: philberty <philip.herron@embecosm.com>
2022-07-27 22:24:49 +02:00
bors[bot]
205096066a Merge #1417
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>
2022-07-27 20:19:02 +00:00
Arthur Cohen
f4e4c2444f unsafe: Forbid use of certain static values outside of unsafe contexts
Using a mutable static or an extern static requires an unsafe function
or block
2022-07-27 15:31:42 +02:00
Arthur Cohen
e7b6a9ee16 hir: Add ExternalItem::ExternKind enumeration 2022-07-27 15:30:09 +02:00
Arthur Cohen
53aee096bd hir: Add Item::ItemKind enumeration
This allows us to perform checks and dispatch when getting an HIR::Item*
from Mappings::lookup_hir_item()
2022-07-27 15:30:09 +02:00
bors[bot]
50ca4b2ba0 Merge #1378
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>
2022-07-27 13:17:31 +00:00
bors[bot]
d94d5b1ea2 Merge #1410
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>
2022-07-27 12:32:38 +00:00
Arthur Cohen
961468ed82 unsafe: Handle multi unsafe contexts by using stack
Co-authored-by: philberty <philip.herron@embecosm.com>
2022-07-27 14:29:14 +02:00
Arthur Cohen
6b14b560bc session-manager: Do not go through with compilation on privacy/unsafe
errors
2022-07-26 15:45:49 +02:00
Arthur Cohen
660460f928 unsafe: Add UnsafeCheck visitor
This visitor takes care of checking for unsafe expressions in safe
contexts. This first iteration reports the dereferencing of raw
pointers.
2022-07-26 15:45:49 +02:00
Arthur Cohen
a7f46cc7fb hir: Add get_to_expr to RangeToIncl 2022-07-26 15:45:49 +02:00
andrewnaguib
5556d29f7b hir/dump: simple dumping of crate attrs and adding a few todos 2022-07-25 01:00:24 -07:00
bors[bot]
dec7ee4c5e Merge #1406
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>
2022-07-22 13:40:06 +00:00
bors[bot]
15d4bdd84a Merge #1409
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>
2022-07-22 10:34:21 +00:00
bors[bot]
dc9981eb31 Merge #1405
1405: Allow repeating metavars alongside repetitions r=CohenArthur a=CohenArthur

Fixes #1400 

Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
2022-07-22 09:55:16 +00:00
bors[bot]
4a8c733b47 Merge #1401
1401: macros: properly handles recursive macros r=CohenArthur a=liushuyu

- macros: properly handles recursive macros

Fixes #1084

Co-authored-by: liushuyu <liushuyu011@gmail.com>
2022-07-22 09:22:07 +00:00
Arthur Cohen
1ab1464228 checks: Refactor project architecture for checking passes
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
2022-07-22 10:35:35 +02:00
Arthur Cohen
8dc692afc2 ast: Add new AttributeChecker visitor
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.
2022-07-21 11:16:19 +02:00
Arthur Cohen
d3926e6a87 macros: Rename APIs around metavars and repetitions to improve clarity 2022-07-20 15:08:51 +02:00
Arthur Cohen
09855d5c0e macro: Allow the repetition of metavars when expanding repetitions
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.
2022-07-20 15:08:51 +02:00
bors[bot]
3f5fc214f4 Merge #1404
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>
2022-07-20 11:48:28 +00:00
Thomas Schwinge
51f03d9d69 'gcc/testsuite/rust/link/link.exp': Fix 'runtest_file_p' usage
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.
2022-07-20 12:03:39 +02:00
liushuyu
3ce22036e4 tests: add regression tests for more macro expansions 2022-07-19 15:38:21 -06:00
liushuyu
0340a567fe expand/attr-visitor: recursively expand the macros if needed
Signed-off-by: Zixing Liu <liushuyu011@gmail.com>
2022-07-19 12:44:13 -06:00
liushuyu
903b7de015 rust/expand: merge expand_invoc and expand_invoc_semi functions 2022-07-19 12:44:03 -06:00
bors[bot]
137cd3bbaa Merge #1397
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>
2022-07-19 11:51:22 +00:00
Arthur Cohen
66af31d5bc lexer: Allow specifiying tokens as reserved in certain editions
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.
2022-07-19 13:09:17 +02:00
bors[bot]
1b5676645a Merge #1394
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>
2022-07-19 10:32:55 +00:00
Philip Herron
fb1b2a6bf5 Fix parsing grammer of grouped expressions as the block tail expression
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
2022-07-19 10:52:12 +01:00
bors[bot]
6622ae2cd0 Merge #1392
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>
2022-07-18 16:00:54 +00:00
bors[bot]
265d5e86f2 Merge #1358
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>
2022-07-18 15:23:07 +00:00
Arthur Cohen
d82201be88 resolver: Disambiguate generic args
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.
2022-07-18 17:24:13 +02:00
Philip Herron
3bf3ea8878 Ensure we parse any inner item attributes when expanding a module
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
2022-07-18 16:18:02 +01:00
bors[bot]
6920d2294b Merge #1373
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>
2022-07-18 12:15:20 +00:00
bors[bot]
e4cdb24c46 Merge #1391
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>
2022-07-17 19:52:16 +00:00
Philip Herron
9c7a580aa1 Fix ICE on duplicate compilation of ExternBlock items
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
2022-07-17 20:45:42 +01:00
bors[bot]
fd2bd659e4 Merge #1362
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>
2022-07-15 16:09:43 +00:00
Philip Herron
2d1378f731 Add new metadata interface to write directly to file
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.
2022-07-15 17:02:20 +01:00
Philip Herron
418aef1b00 Support extern crate
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
2022-07-15 17:02:19 +01:00
Philip Herron
ecd1908fc2 Add support for ast with generic traits
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.
2022-07-15 17:01:53 +01:00
Philip Herron
67f9b173b9 Update build farm status 2022-07-15 14:01:23 +01:00
bors[bot]
0a9416fc04 Merge #1385 #1386 #1387 #1388
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>
2022-07-15 11:02:55 +00:00
Philip Herron
e3f135ef0b Add new interface to mappings class crate_num_to_nodeid and node_is_crate
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.
2022-07-15 12:01:38 +01:00
Philip Herron
6bf6241f29 External Items with Rust ABI need to mangle the full path
When compiling external rust abi item requires the fully qualified
canonical path to be mangled in order to link correctly.
2022-07-15 11:59:38 +01:00
Philip Herron
81c4b6989f Fix undefined behaviour using .get on unique_ptr
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.
2022-07-15 11:58:23 +01:00
Philip Herron
8775525b04 Add missing include for intellisense 2022-07-15 11:57:36 +01:00
bors[bot]
f51284b598 Merge #1380 #1381 #1382
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>
2022-07-15 10:03:38 +00:00
bors[bot]
d155a54785 Merge #1384
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>
2022-07-15 09:27:28 +00:00
Philip Herron
95aa351e65 Support generics in check for valid types in arithmetic expressions
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
2022-07-15 10:25:50 +01:00
Philip Herron
2ff776d364 Support ast dump of generic parameters on functions 2022-07-14 15:07:15 +01:00
Philip Herron
1347d23e09 Implement AST dump for ArithmeticOrLogicalExpr to fix unreachable 2022-07-14 14:50:42 +01:00
Philip Herron
4b82481d85 Support aggregate types in transmute
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.
2022-07-14 14:11:21 +01:00
bors[bot]
ab9f7f287e Merge #1379
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>
2022-07-14 10:33:39 +00:00
liushuyu
ee051b3c44 backend: explain why cdecl is treated differently ...
... when setting up the ABIs

Signed-off-by: Zixing Liu <liushuyu011@gmail.com>
2022-07-13 02:20:20 -06:00
bors[bot]
26114120fd Merge #1375
1375: backend: properly handles foreign ABIs r=philberty a=liushuyu

- Properly handles foreign (`extern` functions) ABIs


Co-authored-by: liushuyu <liushuyu011@gmail.com>
2022-07-12 11:22:47 +00:00
liushuyu
a991c30262 backend: properly handles foreign ABIs 2022-07-08 17:01:40 -06:00
bors[bot]
a273dbd971 Merge #1374
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>
2022-07-08 18:19:34 +00:00
Philip Herron
3ccf43082d remove unused go code 2022-07-08 14:47:23 +01:00
bors[bot]
3f32592159 Merge #1372
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>
2022-07-08 13:24:34 +00:00
Arthur Cohen
c3b88e3283 typecheck-resolve-type: Move all remaining definitions 2022-07-08 14:48:27 +02:00
bors[bot]
e1293ae357 Merge #1366
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>
2022-07-08 11:47:17 +00:00
Philip Herron
fb27d1452b Refactor mappings class and HIR lowering to be consistent
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.
2022-07-08 12:46:30 +01:00
Philip Herron
31887c00fb HIR::TypeParam needs to be permissive of nullptr Type 2022-07-08 12:39:26 +01:00
Philip Herron
2128789a38 Fix HIR::LetStmt Dref nullptr
HIR::LetStmts can have optional specifiedtrs or patterns. This patch
updates the copy constructors to respect this properly to avoid nullptr
deref.
2022-07-08 12:39:26 +01:00
Philip Herron
444bb5b818 Fix nullptr deref on HIR::Function
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.
2022-07-08 12:39:26 +01:00
Arthur Cohen
43cd742e34 typecheck: Add base for resolving const generic params and their default
expression
2022-07-08 12:11:19 +02:00
Arthur Cohen
64f69dbca2 hir: Add missing visitor for ConstGenericParam 2022-07-08 12:11:19 +02:00
bors[bot]
33eb5c938a Merge #1371
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>
2022-07-08 09:29:00 +00:00
Arthur Cohen
b941670e38 typecheck: Refactor TypeCheckTopLevel class
This commit moves the TypeCheckTopLevel implementation into its own
source file, and factors generic parameter resolving into a single
function
2022-07-08 10:26:47 +02:00
bors[bot]
b1c9ac14a0 Merge #1367
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>
2022-07-07 20:00:19 +00:00
David Faust
b7c4aa942f backend: initial support for matches on tuples
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.
2022-07-07 11:41:54 -07:00
David Faust
7784232540 backend: factor out check_match_scrutinee
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.
2022-07-07 11:25:52 -07:00
bors[bot]
a5c82a1d2b Merge #1370
1370: ast: Fix use after move in GenericArg r=philberty a=CohenArthur



Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
2022-07-07 14:30:24 +00:00
bors[bot]
d4dda7805f Merge #1363
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 #1203 
Fixes #1000

Co-authored-by: Philip Herron <philip.herron@embecosm.com>
2022-07-07 13:54:53 +00:00
Philip Herron
ec5da37dbf Refactor Lexer to support an abstract InputSource class
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
2022-07-07 12:28:58 +01:00
Arthur Cohen
465c59f260 ast: Fix use after move in GenericArg 2022-07-07 13:28:43 +02:00
bors[bot]
98b3f9bca2 Merge #1364 #1365 #1368
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>
2022-07-07 10:12:11 +00:00
bors[bot]
c8a9218a5b Merge #1355
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>
2022-07-07 09:34:02 +00:00
Arthur Cohen
1f32e5b455 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.
2022-07-07 11:35:06 +02:00
bors[bot]
ad0e01dfbb Merge #1354
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>
2022-07-07 08:53:12 +00:00
Arthur Cohen
0da912fc45 ast: Add ResolveGenericArgs resolver
This resolver replaces the helper function
`ResolveType::type_resolve_generic_args` and will later benefit from
more functionality such as generic disambiguation
2022-07-07 10:53:03 +02:00
Philip Herron
d99b68560c Fix bad ABI from string method causing all rust abi to become C abi 2022-07-06 21:39:38 +01:00
David Faust
fe64842ff9 HIR: add Literal is_equal ()
A small helper for checking when two Literals contain the same value.
2022-07-06 12:21:03 -07:00
bors[bot]
aafb11016d Merge #1359
1359: typecheck: Move TypeCheckItem into source and header file r=CohenArthur a=CohenArthur



Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
2022-07-06 19:15:27 +00:00
Philip Herron
9507bdec30 Support extern-blocks in ast-dumps
This allows us to support really basic expressions and extern blocks. These
are used for the hello world version of importing metadata in crates.
2022-07-06 17:38:37 +01:00
Philip Herron
1432197984 Allow linemap to be optional nullptr 2022-07-06 17:35:55 +01:00
bors[bot]
29d594e263 Merge #1353
1353: session-manager: Add -frust-dump-ast-pretty r=philberty a=CohenArthur



Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
2022-07-06 09:51:39 +00:00
Arthur Cohen
9cc83569d1 typecheck: Move TypeCheckItem into source and header file 2022-07-06 11:26:13 +02:00
bors[bot]
e0844def89 Merge #1346
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>
2022-07-06 09:15:56 +00:00
Arthur Cohen
6eee318c24 session-manager: Add -frust-dump-ast-pretty 2022-07-04 13:57:22 +02:00
bors[bot]
408b7f87b9 Merge #1352
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>
2022-07-04 08:26:36 +00:00
David Faust
fa006a6728 HIR: fixup MatchArm assignment operator
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.
2022-07-01 12:56:34 -07:00
bors[bot]
33912c1a08 Merge #1336
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>
2022-06-30 15:52:01 +00:00
Arthur Cohen
93f63a94d4 resolver: Add base for resolving const generic parameters
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>;
```
2022-06-30 16:57:17 +02:00
Arthur Cohen
49276efb07 ast: Keep ConstGenericArg as default value for ConstGenericParam 2022-06-30 16:48:18 +02:00
Philip Herron
f4a5629fb7 Fix name resolution using self paths and nested functions
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
2022-06-29 16:35:52 +01:00
Philip Herron
18648e7b9f Add support for the self path
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
2022-06-29 16:35:52 +01:00
bors[bot]
81abc8623c Merge #1151 #1343
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>
2022-06-29 14:07:33 +00:00
bors[bot]
9976c571ff Merge #1338
1338: gccrs const folding port: continue porting potential_constant_expression_1() r=philberty a=abbasfaisal

Card: [Link](https://github.com/Rust-GCC/gccrs/projects/16#card-82300805).

Target function: [Link](https://github.com/Rust-GCC/gccrs/blob/master/gcc/cp/constexpr.cc#L8350)

Following functions are ported in this changeset:
 - [maybe_constexpr_fn](https://github.com/Rust-GCC/gccrs/blob/master/gcc/cp/constexpr.cc#L5495)
 - [get_nth_callarg](https://github.com/Rust-GCC/gccrs/blob/master/gcc/cp/constexpr.cc#L1333)
 - [var_in_maybe_constexpr_fn](https://github.com/Rust-GCC/gccrs/blob/master/gcc/cp/constexpr.cc#L5507)
 - [array_type_nelts_top](https://github.com/Rust-GCC/gccrs/blob/master/gcc/cp/tree.cc#L3055)
 - [builtin_valid_in_constant_expr_p](https://github.com/Rust-GCC/gccrs/blob/master/gcc/cp/tree.cc#L445)
 - [decl_maybe_constant_var_p](https://github.com/Rust-GCC/gccrs/blob/master/gcc/cp/decl2.cc#L4623)
 - [cp_type_quals](https://github.com/Rust-GCC/gccrs/blob/master/gcc/cp/typeck.cc#L10946)

Co-authored-by: Faisal Abbas <90.abbasfaisal@gmail.com>
2022-06-29 13:39:05 +00:00
Philip Herron
1282974cf8 Ensure we support generic arguments on mangled type-paths
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$.
2022-06-29 12:10:08 +01:00
bors[bot]
c88cc0aa64 Merge #1342
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>
2022-06-29 09:02:29 +00:00
liushuyu
0c290e7c6f tests: add tests for deprecated attribute scanning 2022-06-28 17:54:26 -06:00
liushuyu
649d3c45af rust/backend: scan for any deprecated function calls ...
... and emit warnings using GCC's own deprecation warning system
2022-06-28 17:54:18 -06:00
liushuyu
04cc46cfe8 backend: handle deprecated attribute
Signed-off-by: Zixing Liu <liushuyu011@gmail.com>
2022-06-28 17:22:56 -06:00
Philip Herron
5b8502d862 Remove default keyword flags in ResolveType interface
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.
2022-06-28 17:00:54 +01:00
Philip Herron
76aeea68f5 Remove unused class ResolveTypeToCanonicalPath and generation of a path from qualified type paths 2022-06-28 14:18:11 +01:00
Philip Herron
c14187cf54 Remove unused code in ResolveTypeToCanonicalPath class 2022-06-28 14:11:32 +01:00
Philip Herron
7f8479378a remove unnessecary useage of ResolveTypeToCanonicalPath when we dont need it here 2022-06-28 14:05:34 +01:00
Philip Herron
700849ffd0 refacor resolution of TypePaths to be a static function 2022-06-28 13:31:24 +01:00
Philip Herron
eb88a919f5 refactor qualified type path resolution from the ResolveRelativeTypePathClass 2022-06-28 13:13:15 +01:00
Philip Herron
964969d4c6 refactor class helper to create trait impl path segments into the CanonicalPath class itself 2022-06-28 11:01:15 +01:00
Philip Herron
64832f0c5d remove unused class 2022-06-28 10:40:21 +01:00
Philip Herron
d5ffe1cdb0 refactor name resolution of generic arguments into ResolveType class 2022-06-28 10:38:09 +01:00
bors[bot]
65a06a8175 Merge #1341
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>
2022-06-28 08:11:16 +00:00
Arthur Cohen
7bb99a5b83 ci: Temporarily disable Remark CI
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
2022-06-28 09:23:24 +02:00
Philip Herron
da2dda7063 refactor away from helper utility methods and just use the constructor directly 2022-06-27 17:48:55 +01:00
Philip Herron
31e63dd6c2 remove decl mutability context which is unused 2022-06-27 16:12:41 +01:00
Philip Herron
2f2c41a3eb remove unused mark assignment to decl 2022-06-27 13:24:26 +01:00
Philip Herron
1ea95c3548 refactor relative type path function into its assoicated file 2022-06-27 13:07:42 +01:00
Philip Herron
c31bffa99b move resolve-item functions into their associated file 2022-06-27 12:54:16 +01:00
Philip Herron
b9fffb1558 Remove unused parent NodeId mappings 2022-06-27 12:40:18 +01:00
Philip Herron
198d0dfbfa Remove unused function 2022-06-27 11:41:37 +01:00
Philip Herron
5cacb0d3cb Remove locus field which can shadow leading to missing location info 2022-06-27 11:40:36 +01:00
bors[bot]
80a14bd813 Merge #1339
1339: Add `line!` macro r=CohenArthur a=graphman65



Co-authored-by: Sebastien Lacoste <dev@graphman.fr>
2022-06-27 08:07:14 +00:00
Faisal Abbas
2a7a0589f6 gccrs const folding port: continue porting potential_constant_expression_1()
Following functions are ported in this changeset:
 - maybe_constexpr_fn
 - get_nth_callarg
 - var_in_maybe_constexpr_fn
 - array_type_nelts_top
 - builtin_valid_in_constant_expr_p
 - decl_maybe_constant_var_p
 - cp_type_quals
2022-06-25 11:56:42 +01:00
Sebastien Lacoste
40ad6b290a Add line builtin macro
Signed-off-by: Sebastien Lacoste <dev@graphman.fr>
2022-06-24 18:50:07 +02:00
Sebastien Lacoste
7c7202c231 Remove unused commented code
Signed-off-by: Sebastien Lacoste <dev@graphman.fr>
2022-06-24 18:49:59 +02:00
bors[bot]
5bab921fc0 Merge #1337
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>
2022-06-24 15:45:38 +00:00
bors[bot]
fa57ab9f13 Merge #1325
1325: Add const generic disambiguation r=CohenArthur a=CohenArthur

Closes #1321 

Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
2022-06-24 13:17:41 +00:00
Arthur Cohen
7f5ea92bbb parser: Disambiguate default expressions for const generics 2022-06-24 15:14:50 +02:00
Arthur Cohen
af7f140f2f ast: Allow disambiguation of ConstGenericArgs to const generic arguments
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.
2022-06-24 15:11:02 +02:00
bors[bot]
991186154c Merge #1335
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>
2022-06-24 12:40:45 +00:00
andrewnaguib
557b8d93be cli: add "hir-pretty" as a "dump" option
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>
2022-06-24 05:38:13 -07:00
bors[bot]
5b90f0b3cd Merge #1332
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>
2022-06-24 10:07:23 +00:00
bors[bot]
f18dae194c Merge #1331
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>
2022-06-24 09:38:43 +00:00
andrewnaguib
7648286322 hir/add: pretty printing visitor skeleton
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>
2022-06-24 02:05:00 -07:00
bors[bot]
23815a535e Merge #1327 #1329 #1330
1327: Lower const generics structures r=CohenArthur a=CohenArthur

This PR adds lowering for both the `ConstGenericParam` type and the `ConstGenericArg` one. Ideally, we should be able to avoid ambiguites (`let a: Foo<N>;` -> what is N? A type? A const?) by going through the name resolver, and resolve either to a different `AST::ConstGenericArg` either to a correct `AST::Type` or equivalent. So I think we can avoid doing the same "Ambiguous/Clear" dance in the `HIR::ConstGenericArg` type.

If that ends up not being possible, we can always add it and disambiguate during typechecking or other.

Closes #1318

1329: gccrs const folding port: start porting potential_constant_expression… r=CohenArthur a=abbasfaisal

Card: [Link](https://github.com/Rust-GCC/gccrs/projects/16#card-82300805).

Since [this](https://github.com/Rust-GCC/gccrs/blob/master/gcc/cp/constexpr.cc#L8350) is a huge function, we will start by porting chunks on which it depends as that would reduce the chance of missing something important and be easier to review.

This changeset ports over the below typedefs, structs and functions in addition to the macros:

Typedefs:
 - [tsubst_flags_t](7eef766dc5/gcc/cp/cp-tree.h (L5533))

Structs:
 - [lang_type](https://github.com/Rust-GCC/gccrs/blob/master/gcc/cp/cp-tree.h#L2300)
 - [tree_pair_s](https://github.com/Rust-GCC/gccrs/blob/master/gcc/cp/cp-tree.h#L2281)

Functions:
 - [cp_expr_loc_or_loc](https://github.com/Rust-GCC/gccrs/blob/master/gcc/cp/cp-tree.h#L8073)
 - [cp_expr_loc_or_input_loc](https://github.com/Rust-GCC/gccrs/blob/master/gcc/cp/cp-tree.h#L8082)
 - [cp_expr_location](https://github.com/Rust-GCC/gccrs/blob/master/gcc/cp/tree.cc#L6056)
 - [is_really_empty_class](https://github.com/Rust-GCC/gccrs/blob/master/gcc/cp/class.cc#L8867)
 - [is_empty_class](https://github.com/Rust-GCC/gccrs/blob/master/gcc/cp/class.cc#L8850)
 - [array_type_nelts_top](https://github.com/Rust-GCC/gccrs/blob/master/gcc/cp/tree.cc#L3055)

I feel we do not need [is_really_empty_class](https://github.com/abbasfaisal/gccrs/blob/port-potential-const-expression-1-part-by-part/gcc/rust/backend/rust-tree.cc#L786) and [is_empty_class](https://github.com/abbasfaisal/gccrs/blob/port-potential-const-expression-1-part-by-part/gcc/rust/backend/rust-tree.cc#L827) as they are concerned with classes, record types and unions. The tree codes they surround come from [tree.def](https://github.com/Rust-GCC/gccrs/blob/master/gcc/tree.def). I think the class and record tree codes are not relevant to Rust. Feel free to say so and I will remove these functions or if you would like me to dig more into them.



1330: Add location to HIR::Type base class and improve privacy error reporting r=CohenArthur a=graphman65

Fix #1256

Adds location to the HIR::Type base class, removes it from all the subclasses and then use it  in the `check_type_privacy` method to improve privacy error reporting.

The privacy error now looks like this (instead of what you can see in the example #1256).

```rust
gcc/testsuite/rust/compile/privacy5.rs:15:20: error: definition is private in this context
   15 |         fn any(a0: green::Foo, a1: green::Bar) {}
      |                    ^
```

Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
Co-authored-by: Faisal Abbas <90.abbasfaisal@gmail.com>
Co-authored-by: Sebastien Lacoste <dev@graphman.fr>
2022-06-24 07:49:54 +00:00
bors[bot]
e6b7d184d0 Merge #1326
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>
2022-06-24 07:21:34 +00:00
Rainer Orth
c8030bb6b1 Fix remaining misuses of format specifiers on 32-bit targets
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
2022-06-24 08:50:27 +02:00
Sebastien Lacoste
5d7841fa23 Use HIR::Type's location when checking privacy
This improves privacy errors reporting location

Signed-off-by: Sebastien Lacoste <dev@graphman.fr>
2022-06-23 15:58:56 +02:00
Sebastien Lacoste
d114e48ce6 Add location to HIR::Type base class and remove from subclasses
Fixes #1256

Signed-off-by: Sebastien Lacoste <dev@graphman.fr>
2022-06-23 13:28:51 +02:00
Faisal Abbas
67470f5d66 gccrs const folding port: start porting potential_constant_expression_1()
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
2022-06-21 17:54:06 +01:00
Arthur Cohen
6e5468e256 hir: Add ConstGenericArg and lower them properly 2022-06-20 16:50:46 +02:00
Arthur Cohen
8f996567e8 hir: Add ConstGenericParam and lower to them properly 2022-06-20 16:11:36 +02:00
Arthur Cohen
48492dc805 ast: Add location to ConstGenericArg 2022-06-20 14:28:59 +02:00
Mark Wielaard
7e6424852e Actually set TYPE_PACKED for type_record
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.
2022-06-19 01:27:19 +02:00
bors[bot]
c0f11672d7 Merge #1317
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>
2022-06-17 16:11:19 +00:00
Arthur Cohen
5f3c8286b2 ast: Add const generic argument application type
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.
2022-06-17 18:11:56 +02:00
bors[bot]
b711799e3e Merge #1322
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>
2022-06-17 14:34:20 +00:00
andrewnaguib
747700e045 continue #94ac628fd20; refactoring codebase to use "rust_sorry_at" 2022-06-17 06:53:18 -07:00
andrewnaguib
94ac628fd2 fix #1263; wrapping gcc's "sorry_at" with "rust_sorry_at" 2022-06-17 06:52:58 -07:00
bors[bot]
76f7e45179 Merge #1316
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>
2022-06-17 07:50:03 +00:00
Arthur Cohen
594854ec08 parser: Build ConstGenericParam properly 2022-06-17 09:43:07 +02:00
Arthur Cohen
d9fb7d06ca ast: Add ConstGenericParam class
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
2022-06-17 09:43:07 +02:00
bors[bot]
848a1a28b9 Merge #1315
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>
2022-06-17 07:12:29 +00:00
bors[bot]
d4a0780073 Merge #1308
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>
2022-06-17 06:39:03 +00:00
Arthur Cohen
0dbfdb5cfc parser: Add base for parsing const generic application
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.
2022-06-15 18:16:39 +02:00
bors[bot]
08e407e977 Merge #1313
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>
2022-06-15 14:20:22 +00:00
Arthur Cohen
112d4212fc parser: Add base for parsing const generic parameters 2022-06-15 09:43:53 +02:00
Marc Poulhiès
29f5749669 Fix formatting error on 32-bits targets
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>
2022-06-14 22:52:36 +02:00
bors[bot]
44f2de02d4 Merge #1312
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>
2022-06-14 18:44:26 +00:00
bors[bot]
61e95a9bf6 Merge #1296
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>
2022-06-14 12:29:33 +00:00
Arthur Cohen
8e22742c9a parser: Error out if the order of lifetimes and generic types is
incorrect
2022-06-14 14:27:31 +02:00
Arthur Cohen
b9013bda08 ast: Add get_kind() virtual function for GenericParam class 2022-06-14 13:27:36 +02:00
Arthur Cohen
2fe0a4da43 parser: Refactor generic parameter parsing
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
2022-06-14 13:27:36 +02:00
bors[bot]
1c679d7f42 Merge #1307
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>
2022-06-14 07:17:11 +00:00
bors[bot]
25974baf19 Merge #1286
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>
2022-06-14 06:35:18 +00:00
bors[bot]
5a62eb2063 Merge #1309
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>
2022-06-13 08:37:41 +00:00
Nirmal Patel
11493cccd7 Fix lexing of empty comments continuing till next line
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>
2022-06-12 19:23:30 -04:00
Faisal Abbas
859b1debbd gccrs const folding: port over cp_walk_subtrees() from cp/tree.cc
Signed-off-by: Faisal Abbas <90.abbasfaisal@gmail.com>
2022-06-12 18:19:08 +01:00
Philip Herron
7ca7362602 This patch implements complex Path resolution
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
2022-06-10 17:09:34 +01:00
Philip Herron
fc3ef6c4b1 Refactor how we track the current module scope id
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
2022-06-10 17:09:34 +01:00
bors[bot]
e6d32d59f1 Merge #1298
1298: rust/intrinsic: add a basic size check for `transmute` r=philberty a=liushuyu

- rust/intrinsic: add a basic size check for `transmute`

partially addresses #1195

Co-authored-by: liushuyu <liushuyu011@gmail.com>
2022-06-08 15:55:54 +00:00
bors[bot]
8f47bc322c Merge #1299 #1300
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>
2022-06-08 15:25:06 +00:00
Arthur Cohen
ab0f9f9e1b docker: Fix GCCRS_BUILD info
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.
2022-06-08 10:57:16 +02:00
Arthur Cohen
88db3982bc ast: Dump TraitImpl items 2022-06-07 12:30:23 +02:00
bors[bot]
9d81164aa0 Merge #1295
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>
2022-06-07 09:19:25 +00:00
liushuyu
46e248fb7f rust/lex: skip broken string expression ...
... when the matching quote is not found on the same line

this could unstuck the string parser when the parser could not advance
the parsing position
2022-06-07 01:17:37 -06:00
liushuyu
188dd73755 rust/intrinsic: add a basic size check for transmute 2022-06-06 20:34:20 -06:00
Arthur Cohen
4d021b8efb ast: Dump Traits properly 2022-06-04 09:37:38 +02:00
Arthur Cohen
2ad8ec6da7 ast: Dump InherentImpl 2022-06-04 09:37:38 +02:00
bors[bot]
957914b428 Merge #1290 #1291 #1294
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>
2022-06-03 09:29:34 +00:00
bors[bot]
664bd46f4c Merge #1292 #1293
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>
2022-06-03 09:00:14 +00:00
Philip Herron
8d1f5f9948 Add new mappings for items within a module
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
2022-06-02 15:50:06 +01:00
bors[bot]
a71fa22c4d Merge #1288
1288: docker: Add commit information to Docker image r=philberty a=CohenArthur

Closes #1262 

Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
2022-06-02 11:18:30 +00:00
Philip Herron
91b16af14c Fixup name canonicalization for impl blocks
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.
2022-06-02 12:13:43 +01:00
Philip Herron
a89eb96d79 Update Reference and Pointer types equality interface
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
2022-06-02 11:18:01 +01:00
Philip Herron
fc6f6a7179 Add mappings for mut_ptr lang item 2022-06-01 16:50:28 +01:00
bors[bot]
0866a4fbc6 Merge #1287
1287: Add AST dump visitor r=CohenArthur a=CohenArthur

This adds a base for pretty printing our AST through a new visitor (Addresses #1261).

This adds enough code to pretty print "functions" without types in the parameters or return type. Looking for feedback on the implementation before we keep going with more code :)

Here's a tiny patch if you want to see the output whenever you're running `-frust-dump-all`:

```diff
diff --git a/gcc/rust/rust-session-manager.cc b/gcc/rust/rust-session-manager.cc
index 0b0e5af915f..3e39c6a6e17 100644
--- a/gcc/rust/rust-session-manager.cc
+++ b/gcc/rust/rust-session-manager.cc
`@@` -31,6 +31,7 `@@`
 #include "rust-cfg-parser.h"
 #include "rust-lint-scan-deadcode.h"
 #include "rust-lint-unused-var.h"
+#include "rust-ast-dump.h"
 
 #include "diagnostic.h"
 #include "input.h"
`@@` -1023,6 +1024,8 `@@` Session::dump_ast (Parser<Lexer> &parser, AST::Crate &crate) const
 
   parser.debug_dump_ast_output (crate, out);
   out.close ();
+
+  AST::Dump (std::cerr).go (crate);
 }
 
 void
```

output:
```rust
arthur@platypus ~/G/r/gccrs (add-ast-dump-visitor) [1]> cat test.rs
fn foo0(a: i32) {
    let a = 15;
    let b: i32 = 15;
}

fn foo1(a: &i32) {}

struct S;

fn foo2(a: S) {}
fn foo3(a: S) -> i32 {}

arthur@platypus ~/G/r/gccrs (add-ast-dump-visitor)> build/gcc/rust1 test.rs -frust-dump-all
fn foo0(a: ) {
	let a = ;
	let b:  = ;

}

fn foo1(a: ) {

}

fn foo2(a: ) {

}

fn foo3(a: ) -> {

}

test.rs:11:1: error: expected [i32] got [()]
   11 | fn foo3(a: S) -> i32 {}
      | ^                ~

Analyzing compilation unit

Time variable                                   usr           sys          wall           GGC
 phase setup                        :   0.00 (  0%)   0.00 (  0%)   0.01 (100%)   129k ( 94%)
 TOTAL                              :   0.00          0.00          0.01          137k
Extra diagnostic checks enabled; compiler may run slowly.
Configure with --enable-checking=release to disable checks.
```

Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
2022-06-01 10:44:16 +00:00
Philip Herron
92f9eb46ec Add hir lowering to ForLoopExpr this will eventually all become a simple HIR::LoopExpr 2022-06-01 10:53:37 +01:00
Philip Herron
f6589ca957 Add name resolution to ForLoopExpr 2022-06-01 10:53:04 +01:00
Philip Herron
fb2fc585fd Reformat copyright header in rust-parse-impl.h 2022-06-01 09:57:21 +01:00
bors[bot]
998f1f73c2 Merge #1284
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>
2022-06-01 08:33:59 +00:00
Arthur Cohen
573b629859 ast: Indent: Improve indent formatting performance
Co-authored-by: ndrwnaguib <ndrwnaguib@gmail.com>
2022-05-31 14:30:11 +02:00
Arthur Cohen
e009a46e22 docker: Add commit information to Docker image 2022-05-30 16:38:31 +02:00
Arthur Cohen
9a1ae92194 ast: Dump: Add pretty printing of functions 2022-05-30 11:05:14 +02:00
Arthur Cohen
c2c26f0499 ast: Dump: Add Indent class usable with streams 2022-05-30 10:38:31 +02:00
Arthur Cohen
79b14bdf16 ast: Dump: Add base for dump visitor 2022-05-30 10:26:19 +02:00
Thomas Young
b2fb51a264 Marklive: support arrayindex 2022-05-29 13:00:00 +08:00
bors[bot]
7a94948e65 Merge #1283
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>
2022-05-26 18:50:14 +00:00
bors[bot]
a4455d8f52 Merge #1280
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>
2022-05-26 08:55:57 +00:00
bors[bot]
5c84a5ca51 Merge #1281 #1282
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>
2022-05-26 08:26:39 +00:00
Faisal Abbas
1a04c501e4 const folding in gccrs: remove ConstCtx class.
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>
2022-05-26 09:10:31 +01:00
Philip Herron
56634945fb Add build badges for marks build-farm
Fixes #1236
2022-05-25 15:44:09 +01:00
Philip Herron
3a95f28788 Add testcase to prove bug is fixed
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
2022-05-25 15:01:52 +01:00
bors[bot]
d5c1531cc4 Merge #1278
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>
2022-05-25 12:49:07 +00:00
Philip Herron
4cfd6942c0 Str's have the same layout as [T]
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
2022-05-25 13:38:17 +01:00
Philip Herron
7f7efa4463 Remove inside_loop parameter from type resolution of stmts and expressions
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.
2022-05-25 13:37:58 +01:00
bors[bot]
36c91efc86 Merge #1275
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>
2022-05-25 12:14:56 +00:00
bors[bot]
79d977e759 Merge #1279
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>
2022-05-25 11:21:26 +00:00
Philip Herron
d01ae2ab56 Remove old hack to handle type inferencing in untyped decalred bindings
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
2022-05-25 11:54:00 +01:00
bors[bot]
d09b135116 Merge #1277
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>
2022-05-25 09:52:15 +00:00
bors[bot]
986e8e75f0 Merge #1276
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>
2022-05-25 09:16:02 +00:00
Philip Herron
a369360b92 Reuse index_expr_ty type instead of type checking the index expression twice 2022-05-24 16:20:55 +01:00
Philip Herron
25ff27b975 Wrapup testing code within CHECKING_P guards 2022-05-24 16:17:11 +01:00
antego
ec9a03a03b type check 2022-05-24 21:32:31 +10:00
bors[bot]
bf6d540b10 Merge #1268
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.html

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=672adac002939a2dab43b8d231adc1dc

Fixes #1232


Co-authored-by: Philip Herron <philip.herron@embecosm.com>
2022-05-23 14:57:55 +00:00
bors[bot]
63762cc243 Merge #1241
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>
2022-05-23 14:28:23 +00:00
Philip Herron
cd39861da5 Fix Slice Type Layout
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.html

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=672adac002939a2dab43b8d231adc1dc

Fixes #1232
2022-05-23 13:49:01 +01:00
bors[bot]
c7008d3e25 Merge #1266
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>
2022-05-23 11:03:46 +00:00
Philip Herron
a647c00590 Make TyTy::BaseType::destructure recursive
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.
2022-05-23 11:27:24 +01:00
bors[bot]
9204e7a1ac Merge #1267
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>
2022-05-23 09:30:59 +00:00
bors[bot]
55ec3454d0 Merge #1265
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>
2022-05-23 08:58:04 +00:00
Thomas Young
dccb3f8121 Marklive: support match expr 2022-05-22 23:31:55 +08:00
Philip Herron
93e5903553 Revert "Marklive: support match expr"
This reverts commit 75c9f9f61c. Which was
accidently pushed to master outside of the PR system. No harm done :).

Happy hacking.
2022-05-21 17:00:51 +01:00
Thomas Young
75c9f9f61c Marklive: support match expr 2022-05-21 21:23:55 +08:00
Philip Herron
39ae84825c Canonicalize types based on hashing than HirIds and TyTy equality
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.
2022-05-20 15:57:22 +01:00
bors[bot]
5ad0ea3e0e Merge #1258
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>
2022-05-20 11:35:25 +00:00
Arthur Cohen
b0527990a1 privacy: PrivacyReporter: Handle builtin and unimplemented types better 2022-05-20 13:35:33 +02:00
Arthur Cohen
3c31c11393 privacy: PrivacyReporter: Add type privacy checking on explicit types
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
2022-05-20 13:35:33 +02:00
Arthur Cohen
64a41cce91 mappings: Add reverse mappings from HirId -> NodeId 2022-05-20 13:35:33 +02:00
bors[bot]
e9d41c4ef9 Merge #1255
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>
2022-05-19 09:49:30 +00:00
bors[bot]
ff37b816e7 Merge #1252 #1254
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>
2022-05-18 15:26:55 +00:00
bors[bot]
9e61c6eb22 Merge #1250
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>
2022-05-18 14:50:31 +00:00
Arthur Cohen
dba78989e5 privacy: PrivacyReporter: Add visitors for all expressions 2022-05-18 10:24:36 +02:00
Arthur Cohen
6c0be48768 issue #1233: Do not rely on the endianness for testing
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.
2022-05-18 09:43:04 +02:00
Arthur Cohen
7ebe376bd6 privacy: Handle calls to functions defined in previous ancestors
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.
2022-05-17 14:04:34 +02:00
Philip Herron
4a4206c017 Support extern-blocks defined within blocks
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
2022-05-17 11:18:31 +01:00
bors[bot]
8cad07cfd2 Merge #1246
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>
2022-05-17 10:11:04 +00:00
bors[bot]
e4213b9568 Merge #1248
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>
2022-05-13 15:45:24 +00:00
David Faust
b1eb3e036c backend: Compile range patterns 2022-05-13 08:39:41 -07:00
David Faust
f9757a898a typecheck: type check range patterns 2022-05-13 08:39:41 -07:00
David Faust
d01867d2f5 HIR: Lower range patterns 2022-05-12 15:47:50 -07:00
David Faust
26c832fcc2 resolve: Resolve range patterns 2022-05-12 15:47:34 -07:00
David Faust
bd90e61b2b HIR: Add RangePatternBoundType and helpers 2022-05-12 15:47:17 -07:00
David Faust
c31d0c5f78 ast: Add RangePatternBoundType and helpers 2022-05-12 15:46:43 -07:00
Arthur Cohen
48fc2df91b privacy: Add base for privacy violation visitor 2022-05-12 17:10:07 +02:00
Arthur Cohen
d374eb47de resolver: TopLevel: Build tree of child modules 2022-05-12 17:10:06 +02:00
Arthur Cohen
172624a7f9 mappings: Store NodeIds for visibility_map 2022-05-12 17:10:06 +02:00
Arthur Cohen
56b4aa48df mappings: Add module->children mappings 2022-05-12 12:10:31 +02:00
Arthur Cohen
effc63b892 optional: Allow the creation of Optional<T&>
Sadly, this requires specializing the class to keep the underlying pointer of
the reference.
2022-05-12 12:05:31 +02:00
bors[bot]
d4434b511a Merge #1244
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>
2022-05-11 17:12:51 +00:00
David Faust
5aa411c537 Allow match on primitive types
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.
2022-05-11 09:29:55 -07:00
David Faust
502c8a8597 typecheck: add is_primitive_type_kind helper 2022-05-11 09:29:55 -07:00
bors[bot]
f2aee09a0b Merge #1240 #1243
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>
2022-05-11 08:34:05 +00:00
bors[bot]
c1ff79996a Merge #1242
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>
2022-05-10 17:17:08 +00:00
Philip Herron
2e65c14bef Allow cast of integers to pointers
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
2022-05-10 18:01:23 +01:00
Philip Herron
d2dcac6a0b Change Artihmetic Operation to be a cast type operation
Arithmetic operations like this need a cast to support the range of integer
types which are allow here.

Fixes #1234
2022-05-10 18:01:09 +01:00
Arthur Cohen
2959ff8e7d macro: Add assertion to avoid undefined behavior
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`
2022-05-10 15:15:21 +02:00
antego
a91b138bbc Implement name resolution for the IfLet expression.
Addresses #1177.
2022-05-10 22:12:41 +10:00
bors[bot]
03c21a08eb Merge #1218
1218: Lower IfLet expressions r=CohenArthur a=antego

This PR addresses https://github.com/Rust-GCC/gccrs/issues/1177. This change implements the "hir-lowering" part of the plan outlined here https://github.com/Rust-GCC/gccrs/issues/1177#issuecomment-1118530135.

Co-authored-by: antego <antego@users.noreply.github.com>
2022-05-10 10:16:06 +00:00
bors[bot]
ba3f981119 Merge #1238
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>
2022-05-10 09:48:38 +00:00
Philip Herron
d1a2508778 Assigning members to structures is a coercion site
Fix missing coercion site call which allows the coecion of a reference to
a pointer type.

Fixes #1235
2022-05-10 01:52:04 +01:00
bors[bot]
8d828e4b30 Merge #1228
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>
2022-05-09 14:32:00 +00:00
Philip Herron
dd213da6a3 Fix match tests on 32bit systems
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.
2022-05-09 12:04:15 +00:00
antego
245215bf8d Lower IfLet expressions.
Addresses #1177.
2022-05-09 21:19:18 +10:00
bors[bot]
140f6a698b Merge #1219
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>
2022-05-09 11:09:47 +00:00
bors[bot]
dd5a7654d3 Merge #1222 #1223 #1225
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>
2022-05-09 10:40:43 +00:00
CohenArthur
16da547c6d macros: Error out when repeating metavars which refer to repetitions
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.
2022-05-09 12:35:39 +02:00
Philip Herron
55346cc59b Destructure our generics, placeholers or projections during coercion
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.
2022-05-09 11:30:48 +01:00
bors[bot]
3b8f3e6139 Merge #1220 #1221
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>
2022-05-09 10:11:28 +00:00
Philip Herron
cb4d935508 Add new monomorphize_clone interface
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
2022-05-06 16:57:11 +01:00
Philip Herron
0d8c298443 Ensure we don't return error_mark_node for loop expressions
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
2022-05-06 16:36:29 +01:00
Philip Herron
224647d24a Ensure the coercion sites are applied correctly on unions
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
2022-05-06 16:34:13 +01:00
bors[bot]
74e836599c Merge #1215
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>
2022-05-06 12:56:12 +00:00
Arthur Cohen
2df8cf57e6 privacy: Add base for pub(restricted) visitor and linter
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.
2022-05-06 14:29:51 +02:00
Arthur Cohen
4393aabd07 hir: Handle RESTRICTED properly when converting a Visibility to a string 2022-05-06 14:29:51 +02:00
Arthur Cohen
e0bbbbb056 vis: Fix issue when lowering AST::Visibility 2022-05-06 14:29:50 +02:00
Arthur Cohen
22966211a8 privacy: Add base for resolving SimplePaths to Modules 2022-05-06 14:29:28 +02:00
bors[bot]
9ea940e4dc Merge #1216
1216: ast: lower: Refactor ASTLowerItem in its own source file r=CohenArthur a=CohenArthur



Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
2022-05-06 09:13:51 +00:00
Arthur Cohen
41abd0fdb2 ast: lower: Refactor ASTLowerItem in its own source file 2022-05-06 11:12:22 +02:00
bors[bot]
c936fd3255 Merge #1217
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>
2022-05-05 15:59:54 +00:00
Arthur Cohen
b088d47cdc util: Add Optional<T> wrapper class
The class provides an easy to use alternative to raw pointers or member
+ bool pairs. It should be easy to extend and improve upon.
2022-05-05 16:25:30 +02:00
Arthur Cohen
a6f5bc6054 util: Add copyright header on make-unique.h 2022-05-05 14:19:59 +02:00
bors[bot]
af031b081f Merge #1202
1202: Resolve module visibility properly r=CohenArthur a=CohenArthur

Closes #1159 

Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
2022-05-05 12:16:22 +00:00
Arthur Cohen
88c20f5e1d privacy: Add base for resolving SimplePaths to Modules
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
2022-05-05 14:07:36 +02:00
Philip Herron
f5bceb6794 Fix size used in unsized adjustments
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
2022-05-05 11:43:40 +01:00
Arthur Cohen
52b5286a69 hir: SimplePath: Add location info 2022-05-04 16:01:44 +02:00
Arthur Cohen
1ea83c404e ast: Lower SimplePaths properly 2022-05-04 16:01:44 +02:00
bors[bot]
285aabdd3b Merge #1205
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>
2022-05-04 12:17:08 +00:00
Philip Herron
74f4ee8d38 Take advantage of OBJ_TYPE_REF'S in dyn calls
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 #996
Fixes #854
2022-05-04 13:13:12 +01:00
bors[bot]
21b9e1226c Merge #1206 #1209 #1211 #1212 #1213
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>
2022-05-04 10:56:47 +00:00
bors[bot]
aa5ab23081 Merge #1214
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>
2022-05-04 10:22:54 +00:00
Zopolis4
0c5a19dd1c Replace SSH cloning with HTTPS cloning in README.md
Signed-off-by: Maximilian Downey Twiss <creatorsmithmdt@gmail.com>
2022-05-04 17:37:05 +10:00
liushuyu
cb22cd9da3 intrinsic: add rotate_left and rotate_right intrinsic 2022-05-04 01:30:38 -06:00
David Faust
0472834ddf Preserve inside_loop context when compiling match 2022-05-03 15:12:24 -07:00
David Faust
aa372462f4 Compile matches on boolean expressions 2022-05-03 12:55:39 -07:00
David Faust
ca75e756e8 Compile literal patterns for match expressions 2022-05-03 12:55:08 -07:00
Philip Herron
48cad9e8ae Use correct format specifiers for unisnged HOST_WIDE_INT
The code here was wrongly assuming the unsigned long interface which is not
correcty for all targets.
2022-05-03 16:16:12 +01:00
liushuyu
884b936686 intrinsic: add breakpoint intrinsic 2022-05-03 00:05:04 -06:00
bors[bot]
ca722fe423 Merge #1197
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>
2022-05-02 21:26:10 +00:00
bors[bot]
5aec7cbfa5 Merge #1199
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>
2022-05-02 20:10:39 +00:00
bors[bot]
694114ea95 Merge #1201
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>
2022-05-02 19:38:51 +00:00
bors[bot]
fb136314f9 Merge #1191
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>
2022-05-02 14:32:12 +00:00
bors[bot]
27e562a2c0 Merge #1200
1200: Remove duplicated code for expansions of types and expressions r=CohenArthur a=antego

Following up on the comment https://github.com/Rust-GCC/gccrs/pull/1161#pullrequestreview-951665285


Co-authored-by: antego <antego@users.noreply.github.com>
2022-05-02 13:35:01 +00:00
antego
01aa0cf278 Update gcc/rust/expand/rust-attribute-visitor.cc
Co-authored-by: CohenArthur <cohenarthur.dev@gmail.com>
2022-05-02 22:36:04 +10:00
Philip Herron
cf9d65a913 Generic functions should not be TREE_PUBLIC
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.
2022-05-02 10:53:14 +01:00
antego
5fe52462aa Code deduplication for expression and type expansions.
Follow-up for #1161
2022-05-01 11:26:24 +10:00
Philip Herron
d6fb624656 Add new as_name interface for Dynamic types
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
2022-04-30 13:46:41 +01:00
Philip Herron
7e576d70b6 Support recursive coercion sites
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
2022-04-30 13:31:12 +01:00
Philip Herron
44c058c30d Fix address expression to respect reference/pointer types 2022-04-30 13:31:12 +01:00
bors[bot]
f38bf60c3a Merge #1188
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>
2022-04-29 15:14:48 +00:00
bors[bot]
f8a137bd93 Merge #1194
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>
2022-04-29 13:09:18 +00:00
Arthur Cohen
98e1de2d8f ast: Resolver: Refactor ResolveRelativeTypePath in its own source file 2022-04-29 09:37:26 +02:00
Arthur Cohen
c0589ea7db ast: Resolver: Flatten use declarations to paths
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!)
2022-04-29 09:29:30 +02:00
Philip Herron
e09a576320 Add support for transmute intrinsic
This adds in the transmute intrisic by utilizing the convert_expression
framework we have in the backend class.

Fixes #1130
Addresses #658
2022-04-28 16:01:56 +01:00
Philip Herron
ca7598514f Add missing type inferencing rules for arrays and slices 2022-04-28 15:53:39 +01:00
bors[bot]
83e13db1fa Merge #1190 #1192 #1193
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>
2022-04-28 14:19:07 +00:00
bors[bot]
9cf744cbd7 Merge #1172
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>
2022-04-28 13:46:02 +00:00
Arthur Cohen
1c56e969a6 ast: resolve: Implement resolve_visibility method 2022-04-28 15:44:34 +02:00
Philip Herron
ae085ac7b1 Remove unused parameter caller from generating Call expressions
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
2022-04-28 14:43:41 +01:00
Philip Herron
7fe6bc1ba1 Add an assertion to avoid peeking when the stack is empty 2022-04-28 14:43:08 +01:00
Arthur Cohen
06c5f54ccc ast: resolve: Add SimplePath path resolver 2022-04-28 15:20:47 +02:00
Arthur Cohen
821c7947bf ast: resolve: Add SimplePathSeg -> CanonicalPath resolver 2022-04-28 15:16:10 +02:00
Arthur Cohen
0b91defe94 ast: resolve: Add source for ResolverBase 2022-04-28 15:15:05 +02:00
Arthur Cohen
d462ec452a privacy: visibility: Do not use SimplePaths this late 2022-04-28 15:15:05 +02:00
Arthur Cohen
ad32692482 ast: resolve: Move ResolveItem into its own source file 2022-04-28 15:15:05 +02:00
Philip Herron
bbf171c9d2 Fix ICE on missing TypeParam within type context
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
2022-04-28 13:44:39 +01:00
Philip Herron
e500a4164f Refactor trait resolution code into cc file from header 2022-04-28 13:19:54 +01:00
Philip Herron
be158fc97f Complete refactor of generic traits handling
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
2022-04-28 13:09:15 +01:00
Philip Herron
712ae2f173 Fix equality interface on TyTy::FnType
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.
2022-04-28 12:25:26 +01:00
bors[bot]
1ada076b93 Merge #1189
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 #1179 
Closes #1180
Closes #1181
Closes #1182

Necessary for #1172 
Addresses #1159 

Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
2022-04-28 09:44:04 +00:00
bors[bot]
af48e2a3a1 Merge #1186
1186: Refactor `ResolvePath` in its own file r=CohenArthur a=CohenArthur



Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
2022-04-28 09:16:03 +00:00
Arthur Cohen
471cff253a ast: Add location info to remaining meta items 2022-04-28 10:23:31 +02:00
Arthur Cohen
ffb38df2eb ast: Add location info to MetaWord 2022-04-28 10:05:55 +02:00
Arthur Cohen
34c73a75cf ast: Add location info to MetaValueStr 2022-04-28 10:02:16 +02:00
Arthur Cohen
b4fa67403f parse: Add correct location to all public visibilities 2022-04-28 09:47:41 +02:00
David Faust
fd51331270 Support align and packed repr on structs 2022-04-27 12:00:18 -07:00
Arthur Cohen
10b01c305f ast: ResolvePath: Move into its own source file 2022-04-27 16:34:37 +02:00
bors[bot]
9a9bb44058 Merge #1184
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 ea38a59ee8

Fixes #1173 

Co-authored-by: Philip Herron <philip.herron@embecosm.com>
2022-04-27 13:38:41 +00:00
bors[bot]
60f7f998a2 Merge #1163
1163: rust-session-manager: handle `crate_name` attribute r=philberty a=liushuyu

- rust-session-manager: handle `crate_name` attribute

Fix #789 properly

Co-authored-by: liushuyu <liushuyu011@gmail.com>
2022-04-27 12:50:32 +00:00
liushuyu
57725b57e5 rust-session-manager: handle crate_name attribute
Signed-off-by: Zixing Liu <liushuyu011@gmail.com>
2022-04-26 16:30:14 -06:00
Philip Herron
ea38a59ee8 Fix regression in fix for #1173
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.
2022-04-26 21:44:00 +01:00
Philip Herron
40f2979b73 Fix bad name resolution of path with generic segments
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
2022-04-26 21:43:59 +01:00
bors[bot]
d69dd65036 Merge #1176
1176: Keep `SimplePath{Segment}`s in mappings r=CohenArthur a=CohenArthur

Addresses #1159 

Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
2022-04-26 18:54:01 +00:00
bors[bot]
8b2e6da739 Merge #1174
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>
2022-04-26 18:24:36 +00:00
bors[bot]
0ce3b067a8 Merge #1171
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>
2022-04-26 14:41:05 +00:00
Arthur Cohen
6f07a76892 mappings: Add mappings for SimplePath{Segment}s 2022-04-26 16:18:43 +02:00
Arthur Cohen
b3d85dc842 ast: SimplePath: Remove default location parameter 2022-04-26 13:44:38 +02:00
liushuyu
10427869f1 dockerfile: change the base image ...
... to match Rust container image's base image

Signed-off-by: Zixing Liu <liushuyu011@gmail.com>
2022-04-26 03:46:39 -06:00
bors[bot]
ab84521788 Merge #1162 #1167 #1168 #1170
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:
![Screen Shot 2022-04-26 at 9 47 29 am](https://user-images.githubusercontent.com/1451467/165258060-6a42f918-2585-4aef-9da5-9d60d69ca248.png)
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>
2022-04-26 09:13:40 +00:00
bors[bot]
d7c5bbe6af Merge #1166
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>
2022-04-26 08:45:21 +00:00
antego
d780b204d8 Implement macro expansion in IfExpr, IfExprConseqElse, IfExprConseqIf, IfExprConseqIfLet.
Addresses #1141
2022-04-26 18:28:30 +10:00
liushuyu
461bf1369f CI: catch malformed test cases
Signed-off-by: Zixing Liu <liushuyu011@gmail.com>
2022-04-25 16:08:24 -06:00
Arthur Cohen
3e01b6b2a8 ast: resolve: Move ResolveItem into its own source file 2022-04-25 22:38:56 +02:00
bors[bot]
b74044fb62 Merge #1164
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>
2022-04-25 19:14:00 +00:00
Philip Herron
1d19dd8a69 Fix nullptr when resolving the root of a path expression
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
2022-04-25 18:00:22 +01:00
Philip Herron
e69e162462 Support inference of generic parameters on paths behind reference's
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
2022-04-25 17:51:26 +01:00
Arthur Cohen
d0c75495dd ast: Visibility: Add has_path method 2022-04-25 16:56:31 +02:00
Arthur Cohen
5536d36307 ast: SimplePath{Segment}: Add NodeId fields 2022-04-25 16:56:24 +02:00
bors[bot]
2b1cb4ba86 Merge #1161
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>
2022-04-25 11:10:22 +00:00
bors[bot]
d54ca71685 Merge #1160
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>
2022-04-25 10:36:08 +00:00
Arthur Cohen
23db789ecb resolver: Move Scope methods into source file 2022-04-25 12:34:13 +02:00
bors[bot]
bbbd15a4a1 Merge #1156
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>
2022-04-25 10:01:03 +00:00
bors[bot]
f562d738ef Merge #1149
1149: backend: handle no_mangle attribute r=philberty a=liushuyu

- handle the `no_mangle` attribute

Co-authored-by: liushuyu <liushuyu011@gmail.com>
2022-04-25 08:51:51 +00:00
antego
e26b95f64a Following up on #1141. Implementing macro expansion or ComparisonExpr, LazyBooleanExpr, AssignmentExpr. 2022-04-23 10:59:44 +10:00
liushuyu
49c0eeb670 tests/attr_cold: fix a typo 2022-04-22 16:29:26 -06:00
liushuyu
a969ab61ad backend: address comments about no_mangle 2022-04-22 16:17:40 -06:00
liushuyu
af7622f219 backend: handle no_mangle attribute 2022-04-22 16:16:37 -06:00
Arthur Cohen
8466c9b162 resolver: Move Resolver methods into own source file 2022-04-22 16:34:55 +02:00
Arthur Cohen
3001bb64cc resolver: Refactor Rib class in a source file 2022-04-22 16:28:26 +02:00
bors[bot]
1286acc34e Merge #1157
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>
2022-04-22 14:00:50 +00:00
Arthur Cohen
159ffebb20 privacy: visibility: Add remaining visitors for simple items 2022-04-22 15:36:44 +02:00
bors[bot]
a936265bb0 Merge #1150
1150: backend: handle link_section attribute r=philberty a=liushuyu

- handle the `link_section` attribute

Co-authored-by: liushuyu <liushuyu011@gmail.com>
2022-04-22 13:32:20 +00:00
bors[bot]
4337aea3be Merge #1155
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>
2022-04-22 12:15:22 +00:00
Arthur Cohen
bdd1b86ccb privacy: ModuleVis: Constify accessor functions
Co-authored-by: philberty <philip.herron@embecosm.com>
2022-04-22 13:46:46 +02:00
bors[bot]
b392376cc5 Merge #1154
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>
2022-04-22 11:45:59 +00:00
Arthur Cohen
c3a81139f7 privacy: visibility: Assert on module stack instead
Co-authored-by: philberty <philip.herron@embecosm.com>
2022-04-22 13:18:30 +02:00
liushuyu
f6194707a6 backend: handle link_section attribute 2022-04-22 05:17:09 -06:00
bors[bot]
d541ded485 Merge #1148
1148: backend: handle cold attribute r=philberty a=liushuyu

- handle the `cold` attribute

Co-authored-by: liushuyu <liushuyu011@gmail.com>
2022-04-22 10:34:59 +00:00
Arthur Cohen
3e3c0660cb privacy: visibility: Insert enum/traits and their subitems properly 2022-04-22 12:31:58 +02:00
Arthur Cohen
cae1e87339 privacy: visibility: Handle modules properly 2022-04-22 12:31:58 +02:00
Arthur Cohen
7be856f7b6 privacy: visibility: Add resolving for "private" items 2022-04-22 12:31:58 +02:00
Arthur Cohen
77afec780a privacy: visibility: Add base for ModuleVisibility resolver 2022-04-22 12:23:21 +02:00
Arthur Cohen
ca59275cc9 privacy: Add base for visibility map of DefIds 2022-04-22 12:23:21 +02:00
Arthur Cohen
e70aa7f262 hir: Fix documentation on previously changed Visibility struct 2022-04-22 12:23:21 +02:00
Arthur Cohen
bfe8ffef86 privacy: Add ModuleVisibility class 2022-04-22 12:23:21 +02:00
bors[bot]
75ac2f6fc0 Merge #1147
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>
2022-04-22 10:04:28 +00:00
bors[bot]
f0b6dca3fc Merge #1145
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>
2022-04-22 09:31:08 +00:00
Philip Herron
7915329a0c Add support for isize and usize type-hints
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
2022-04-22 10:24:46 +01:00
liushuyu
16730054de backend: handle cold attribute 2022-04-21 17:30:52 -06:00
bors[bot]
243ef0dfe7 Merge #1139
1139: hir: improve doc attribute handling r=philberty a=liushuyu

- hir: improve doc attribute handling

Addresses #1140

Co-authored-by: liushuyu <liushuyu011@gmail.com>
2022-04-21 19:25:01 +00:00
Philip Herron
639b3d61ab Add missing coercion rule from array to slice
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
2022-04-21 20:20:24 +01:00
Philip Herron
0d4fc557c7 Fix generic param redefined bug
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
2022-04-21 18:57:24 +01:00
bors[bot]
cb42c3674a Merge #1144
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>
2022-04-21 17:24:27 +00:00
Philip Herron
dd9e4c1e0c Add name and type resolution for TuplePatterns
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
2022-04-21 16:06:18 +01:00
Philip Herron
fe10ca37ab Handle parsing match arms with no comma
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
2022-04-21 12:13:33 +01:00
bors[bot]
fc22f12c9c Merge #1119
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>
2022-04-21 08:13:19 +00:00
antego
9a56a0d10d Add a test for the cfg!() macro
See #1116 and #1039
2022-04-21 09:02:52 +10:00
Philip Herron
c18257c726 Add HIR Lowering for TuplePattern 2022-04-20 18:04:42 +01:00
Philip Herron
53ce1d5ac9 Add ExprStmt::ExprStmtType WITH_BLOCK and WITHOUT_BLOCK to allow switching 2022-04-20 18:03:41 +01:00
Philip Herron
4eaec85303 Add AST::TuplePatternItems::TuplePatternItemType to differentiate between them 2022-04-20 18:03:15 +01:00
Philip Herron
03ec66cf11 Remove bad has-minus flag which should be contained within AST::Literal 2022-04-20 18:02:22 +01:00
liushuyu
a1c34b478f hir: improve doc attribute handling ...
... should fix #1125

Signed-off-by: Zixing Liu <liushuyu011@gmail.com>
2022-04-20 02:56:36 -06:00
bors[bot]
14dbac9a8b Merge #1138
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>
2022-04-20 08:33:46 +00:00
bors[bot]
dc57f4ced0 Merge #1137
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>
2022-04-20 06:51:19 +00:00
bors[bot]
f6e244dc0e Merge #1134
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>
2022-04-19 17:01:25 +00:00
bors[bot]
4152743451 Merge #1121
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>
2022-04-19 16:33:48 +00:00
Philip Herron
c3a3e1053f Support pattern bindings within function signitures
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
2022-04-19 17:00:32 +01:00
Arthur Cohen
038677dd83 ast: lower: Split rust-lower-base in its own source file 2022-04-19 17:53:37 +02:00
Philip Herron
5528001eca Fix ICE during HIR lowering of ExprWithBlock MatchExpr
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
2022-04-19 12:43:21 +01:00
bors[bot]
5b14291b54 Merge #1124
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>
2022-04-19 09:37:52 +00:00
bors[bot]
321be1b3c9 Merge #1096
1096: macros: add include! macro r=CohenArthur a=liushuyu

- add `include!` macro

Co-authored-by: liushuyu <liushuyu011@gmail.com>
2022-04-19 09:08:38 +00:00
liushuyu
f876cba554 macros: save included filename into session manager 2022-04-19 01:46:26 -06:00
liushuyu
82c045ecfe CI: do not push Docker image ...
... when the workflow is ran in a forked repository

Signed-off-by: Zixing Liu <liushuyu011@gmail.com>
2022-04-18 03:41:07 -06:00
liushuyu
e753fa4e36 macros: add include! macro 2022-04-17 17:35:57 -06:00
bors[bot]
27ad3813dc Merge #1122
1122: testsuite/rust: fix test case failure on macOS r=CohenArthur a=liushuyu

- extent `macro_return` xfail targets to three-segment triples

Co-authored-by: liushuyu <liushuyu011@gmail.com>
2022-04-16 10:05:42 +00:00
bors[bot]
e76b639955 Merge #1118
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>
2022-04-16 09:37:42 +00:00
liushuyu
f5f11bef14 testsuite/rust: extent xfail targets 2022-04-15 21:01:23 -06:00
bors[bot]
042c875024 Merge #1107
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>
2022-04-15 21:08:17 +00:00
Philip Herron
ad9e185e15 Fix bad projection substitution
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
2022-04-15 21:23:28 +01:00
bors[bot]
d17e0aa769 Merge #1116
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>
2022-04-15 08:54:55 +00:00
antego
a9c0649503 Move cfg!() macro to builtins
Fixes #1039
2022-04-15 07:31:32 +10:00
Arthur Cohen
c4443ca3b2 privacy: reachability: Visit all variants of an Enum and their fields 2022-04-14 10:50:02 +02:00
Arthur Cohen
126f7aecdc hir: Add EnumItemKind enum for EnumItem classes 2022-04-14 10:49:19 +02:00
Arthur Cohen
71f2cd57c6 privacy: reachability: wip: Update all base reach levels 2022-04-14 10:01:41 +02:00
bors[bot]
d36a3c5752 Merge #1110
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>
2022-04-14 07:27:52 +00:00
bors[bot]
73e017f7cb Merge #1113
1113: macros: Add env! macro r=CohenArthur a=omachota

Added the `env!()` macro and relevant test cases

Fixes: #977 

Signed-off-by: Ondřej Machota <ondrejmachota@gmail.com>

Co-authored-by: Ondřej Machota <ondrejmachota@gmail.com>
2022-04-14 06:56:37 +00:00
Ondřej Machota
1e6e427696 macros: Add env! macro
Signed-off-by: Ondřej Machota <ondrejmachota@gmail.com>
2022-04-13 23:24:53 +02:00
bors[bot]
60324125c3 Merge #1088
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>
2022-04-13 14:17:42 +00:00
Arthur Cohen
ed904fefdd privacy: reachability: Add base visitor for items with generic params
Co-authored-by: philberty <philip.herron@embecosm.com>
2022-04-13 13:15:30 +02:00
Arthur Cohen
cdfb5b34ac privacy: reachability: Cleanup Struct definition visitor 2022-04-13 13:15:10 +02:00
bors[bot]
497ee70b77 Merge #1111
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>
2022-04-13 10:41:12 +00:00
bors[bot]
c1639be8bb Merge #1114
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>
2022-04-13 10:10:21 +00:00
liushuyu
a125901c55 rust-session-manager: address more comments
Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
Signed-off-by: Zixing Liu <liushuyu011@gmail.com>
2022-04-13 02:30:46 -06:00
Arthur Cohen
03cb435c19 visibility: Add create_private() static function
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.
2022-04-13 09:04:26 +02:00
bors[bot]
a196568774 Merge #1112
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>
2022-04-13 06:43:54 +00:00
Simon Cook
addf65ddfa rust: Use -Otarget when building and logging warnings
This will provide some synchronization for output lines, and so will
make comparisons with known warnings as part of CI more reliable.
2022-04-13 08:34:30 +02:00
liushuyu
1a7391d97f rust-session-manager: address comments ...
... also more closely match rustc's behavior

Signed-off-by: Zixing Liu <liushuyu011@gmail.com>
2022-04-12 18:37:09 -06:00
liushuyu
28769ea0ab testsuite/rust: adapt/fix the testcases ...
... so that the tests will still pass after the crate name logic change

Signed-off-by: Zixing Liu <liushuyu011@gmail.com>
2022-04-12 18:34:54 -06:00
liushuyu
f50e9a27b2 rust-session-manager: set and validate crate name properly ...
... should fix #789

Signed-off-by: Zixing Liu <liushuyu011@gmail.com>
2022-04-12 18:34:54 -06:00
Simon Cook
649f6640c6 rust: Clang/macOS Testing
This adds a version of the build-and-check job that runs with clang on
macOS.
2022-04-12 18:03:58 +02:00
bors[bot]
e9ab95c088 Merge #1109
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>
2022-04-12 15:04:30 +00:00
Simon Cook
1a3f38a2b0 rust: Allow gccrs to build on x86_64-apple-darwin with clang/libc++
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.
2022-04-12 16:45:56 +02:00
bors[bot]
7430791e0f Merge #1082
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>
2022-04-12 14:32:53 +00:00
bors[bot]
2076e69bf9 Merge #1108
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>
2022-04-12 14:03:11 +00:00
bors[bot]
c494f30766 Merge #1106
1106: macros: fix an infinite loop in `concat!` macro parser r=CohenArthur a=liushuyu

- Fix concat macro parser issue which caused an infinite loop when invalid token is encountered


Co-authored-by: liushuyu <liushuyu011@gmail.com>
2022-04-12 13:28:28 +00:00
Arthur Cohen
1e5126022d privacy: reachability: Visit all types of a struct's public fields 2022-04-12 15:26:11 +02:00
Arthur Cohen
3058b55328 privacy: reachability: Visit all struct generic predicates 2022-04-12 15:26:11 +02:00
Arthur Cohen
415586f0e2 typectx: Mark lookup_type() method as const 2022-04-12 15:26:11 +02:00
Arthur Cohen
ece3809c50 privacy: Keep DefIds in reachability map instead
This commit also specialized `std::hash<DefId>` to be able to use it as
key in {unordered_}maps
2022-04-12 15:26:11 +02:00
Arthur Cohen
a376e1939e hir: Keep BaseKind enum inside the Node class
Co-authored-by: philberty <philip.herron@embecosm.com>
2022-04-12 15:26:11 +02:00
Arthur Cohen
be8f2ead95 privacy: reachability: Add base for visiting struct definitions 2022-04-12 15:26:11 +02:00
Arthur Cohen
d103151143 hir: StructField: Add get_visibility() method 2022-04-12 15:26:11 +02:00
Arthur Cohen
6db5c9fb19 privacy: reachability: Add better implementation for StructStruct 2022-04-12 15:26:08 +02:00
Arthur Cohen
3bb4d746a0 privacy: reachability: Add maybe_get_vis_item helper static function 2022-04-12 15:25:37 +02:00
Philip Herron
7609dfc63e Add missing unify rules for inference variables
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.
2022-04-12 13:49:30 +01:00
Arthur Cohen
23fc3ff7fe privacy: ctx: Add proper implementations for insert_reachability() and
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
2022-04-12 14:26:23 +02:00
Arthur Cohen
dfb5f548ce hir: Visibility: Add is_public() method 2022-04-12 14:26:23 +02:00
Arthur Cohen
e01a814061 privacy: reach: Rename ReachLevel enum 2022-04-12 14:20:28 +02:00
Arthur Cohen
8bf037fede privacy: Add base for privacy-related visitors 2022-04-12 14:20:21 +02:00
Arthur Cohen
5449587438 hir: Add Kind enum to downcast safely 2022-04-12 14:20:18 +02:00
bors[bot]
a5b38698aa Merge #1103
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>
2022-04-12 10:47:17 +00:00
bors[bot]
c1a022385f Merge #1086
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>
2022-04-12 09:50:56 +00:00
liushuyu
2fe4048f7f macros: fix an infinite loop ...
... introduced in fed5a41fb1, should fix #1102

Signed-off-by: Zixing Liu <liushuyu011@gmail.com>
2022-04-12 02:18:56 -06:00
liushuyu
e909e4fc7b testsuite/rust: add a xfail test case ...
... to show case the timeout system is working
2022-04-11 17:11:50 -06:00
liushuyu
997894f637 testsuite/rust: add a 10-second timeout for each compile test 2022-04-11 17:11:13 -06:00
Philip Herron
0e686c0fe0 Support Slices from rustc libcore 1.49.0
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
2022-04-11 16:37:28 +01:00
Arthur Cohen
9f5d8a8973 ast: Translate visibilities properly when lowering AST nodes
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
2022-04-11 17:18:02 +02:00
Arthur Cohen
7d806eba2b ast: lowering: Add translate_visibility() static function
This function desugars `AST::Visibility`s into `HIR::Visibility`s,
performing all the necessary checks and conversions
2022-04-11 17:18:02 +02:00
Arthur Cohen
2a264a3693 hir: Cleanup Visibility struct
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.
2022-04-11 17:18:02 +02:00
Philip Herron
69d6fddcbb Allow substitutions to be handled on primitive types without causing unreachable 2022-04-11 11:44:59 +01:00
Philip Herron
0e7eef6556 Make the can equal interface more permissive with associated types 2022-04-11 11:44:59 +01:00
Philip Herron
e7e6527975 Add missing const for get_locus and helper to get used arguments 2022-04-11 11:44:59 +01:00
Philip Herron
68458036c8 Disable failing testcase
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
2022-04-11 11:31:14 +01:00
bors[bot]
1b8d4521db Merge #1091
1091: Add -frust-edition flag and possible values r=CohenArthur a=CohenArthur

Closes #1072 

Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
2022-04-11 09:41:23 +00:00
bors[bot]
2669e80c17 Merge #1090 #1097 #1098 #1099 #1101
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>
2022-04-11 09:10:22 +00:00
Philip Herron
3513fa38f2 Update gcc/rust/util/rust-mapping-common.h
Co-authored-by: CohenArthur <arthur.cohen@embecosm.com>
2022-04-11 09:56:14 +01:00
Philip Herron
4413bc0cf8 Fix bad inherent overlap error
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
2022-04-11 09:47:22 +01:00
bors[bot]
e5281ee490 Merge #1100
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>
2022-04-11 08:43:48 +00:00
liushuyu
fed5a41fb1 macros: add concat! macro
Signed-off-by: Zixing Liu <liushuyu011@gmail.com>
2022-04-11 02:31:17 -06:00
Philip Herron
b1f42c38f5 Add helper as_string for DefIds 2022-04-09 22:26:42 +01:00
Philip Herron
595eb9c411 Add known lang item const_slice_ptr mappings
This will allow us to define the const_slice_ptr lang item attribute
without erroring out as an unknown lang item.
2022-04-09 22:17:39 +01:00
Philip Herron
8d3184e822 Ensure unsize method resolutions actually unsize
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
2022-04-09 21:56:46 +01:00
Philip Herron
6fb118f3e2 Support mangling *const ptr and slices like *const [T]
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
2022-04-09 21:53:06 +01:00
bors[bot]
e43a5c5373 Merge #1092
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>
2022-04-08 09:11:01 +00:00
Arthur Cohen
46e0068fc0 options: Add -frust-edition flag and possible values
Co-authored-by: liushuyu <liushuyu011@gmail.com>
2022-04-08 11:09:13 +02:00
bors[bot]
da3d59db1f Merge #1087
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>
2022-04-08 08:30:30 +00:00
Romain Naour
83681c3990 gcc/rust/Make-lang.in: add missing rust compiler driver
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.
2022-04-08 09:28:23 +02:00
David Faust
5559bdc866 Emit loop initializer for repeat arrays
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.
2022-04-07 09:57:46 -07:00
bors[bot]
b829e7c0a2 Merge #1080
1080: macros: add compile_error! macro r=CohenArthur a=liushuyu

- Added `compile_error` macro


Co-authored-by: liushuyu <liushuyu011@gmail.com>
2022-04-07 08:16:07 +00:00
bors[bot]
779de323f3 Merge #1083
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>
2022-04-06 11:00:42 +00:00
liushuyu
af14ad6056 rust-ast-full-test: fix a minor typo
Signed-off-by: Zixing Liu <liushuyu011@gmail.com>
2022-04-05 17:46:29 -06:00
liushuyu
6d42548da9 rust-session-manager: fix an issue where ...
... the -frust-crate= option got incorrectly overridden by a default
value

Signed-off-by: Zixing Liu <liushuyu011@gmail.com>
2022-04-05 17:46:19 -06:00
liushuyu
35570ae410 macros: add compile_error! macro
addresses #927

Signed-off-by: Zixing Liu <liushuyu011@gmail.com>
2022-04-03 17:17:33 -06:00
bors[bot]
9011184f38 Merge #1071
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>
2022-03-31 09:56:35 +00:00
Arthur Cohen
73532817fd macros: Allow transcribing of zero items
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>
2022-03-31 11:32:26 +02:00
bors[bot]
f9c1a14dab Merge #1069
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>
2022-03-31 08:28:42 +00:00
Arthur Cohen
6bf428379d macros: Expand macro invocation properly in type contexts
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
2022-03-31 09:42:26 +02:00
Arthur Cohen
3413f632ec ast_fragment: Add take_type_fragment() method
Co-authored-by: philberty <philip.herron@embecosm.com>
2022-03-31 09:42:26 +02:00
Arthur Cohen
b6bbf1fa72 macro_transcriber: Add TYPE context and associated transcriber 2022-03-31 09:42:08 +02:00
Arthur Cohen
229512d662 single_ast_node: Fix typo in as_string() method 2022-03-31 09:42:08 +02:00
Arthur Cohen
cf94fd8d51 single_ast_node: Add TYPE kind 2022-03-31 09:42:08 +02:00
bors[bot]
bd1f435b23 Merge #1059
1059: Add base for build job using older GCC version r=CohenArthur a=CohenArthur

Fixes #1058 

Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
2022-03-30 11:14:40 +00:00
Arthur Cohen
e824a0835b ci: Run tests with gccrs compiled under gcc-4.8 2022-03-29 10:22:53 +02:00
bors[bot]
e8b9587d3a Merge #1045
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>
2022-03-28 14:22:24 +00:00
bors[bot]
729bbacbd1 Merge #1066
1066: Fix warning of uninitialized delim_id variable r=CohenArthur a=CohenArthur



Co-authored-by: CohenArthur <arthur.cohen@epita.fr>
2022-03-27 14:15:10 +00:00
CohenArthur
1f8780be70 is_match_compatible: Fix warning of uninitialized delim_id variable
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>
2022-03-27 14:46:40 +02:00
bors[bot]
5a15694ee2 Merge #1063
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>
2022-03-25 11:46:24 +00:00
bors[bot]
a7e7234692 Merge #1055
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 #947 
Closes #947 

Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
2022-03-25 10:23:43 +00:00
Arthur Cohen
7fa6e72b1a macros: Parse :meta properly
This allows us to match attribute bodies in macro invocations, which we
can use later down the line to perform conditional compilation
2022-03-25 11:22:18 +01:00
Arthur Cohen
6c99a5a8f1 parser: Move outer attrs properly intoto AssignmentExpr
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
2022-03-25 11:22:17 +01:00
Arthur Cohen
2249a4d512 attributes: Allow stripping assignment expressions 2022-03-25 11:22:17 +01:00
Arthur Cohen
7ea35487a2 macros: Allow checking past zeroable matches for follow-set restrictions
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.
2022-03-25 10:28:42 +01:00
bors[bot]
89ad4f21f2 Merge #1062
1062: Properly perform follow set checking on matcher r=CohenArthur a=CohenArthur

Addresses #947 

Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
2022-03-25 07:55:29 +00:00
bors[bot]
0fa882160d Merge #1043 #1064
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>
2022-03-24 16:54:54 +00:00
David Faust
261c753e56 macros: implement include_bytes! and include_str! 2022-03-24 08:59:35 -07:00
bors[bot]
3a90596517 Merge #1054
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>
2022-03-24 15:58:07 +00:00
Arthur Cohen
5651331236 macros: Allow parsing :tt fragments
: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
2022-03-24 15:03:20 +01:00
Arthur Cohen
912b04216d macros: Check follow-set restrictions on matcher's first delimiter 2022-03-24 13:56:23 +01:00
Arthur Cohen
d859ab0146 macros: Allow repetitions of tokens in follow-set in follow-set
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.
2022-03-24 13:07:22 +01:00
bors[bot]
8283724bc2 Merge #1052
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>
2022-03-24 10:11:43 +00:00
Arthur Cohen
3e5090608d macros: Add hints for follow-set restrictions
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.
2022-03-24 11:11:11 +01:00
Arthur Cohen
14b0472fa4 hir-path-probe: Fix miscompilation on gcc-4.8 2022-03-24 11:05:27 +01:00
Arthur Cohen
c1cc931f97 ci: Add job for building gccrs with older gcc
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.
2022-03-24 11:05:27 +01:00
bors[bot]
ff5f3005d0 Merge #1051
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>
2022-03-24 09:34:19 +00:00
bors[bot]
90f938c2ec Merge #1056 #1057
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>
2022-03-23 21:07:53 +00:00
Thomas Schwinge
7af3505c97 For use as 'std::unordered_map' key, provide 'std::hash' for 'Rust::AST::MacroFragSpec::Kind' enum class
... 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
2022-03-23 21:58:13 +01:00
Thomas Schwinge
85ffe83ad7 Fix '#include <algorithm>' [#159]
... 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.
2022-03-23 18:36:52 +01:00
Arthur Cohen
6821a642ab macros: Add remaining restrictions for follow-set restrictions
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.
2022-03-23 14:35:47 +01:00
bors[bot]
eef1ee2638 Merge #1049
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>
2022-03-23 09:28:09 +00:00
bors[bot]
b9720caa10 Merge #1044
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>
2022-03-23 09:00:05 +00:00
Arthur Cohen
35ca685200 macros: Add base functions to check for follow-set ambiguities
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
2022-03-23 09:56:23 +01:00
bors[bot]
1d34c120c4 Merge #1026
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>
2022-03-22 21:58:02 +00:00
bors[bot]
fb886737e2 Merge #1047
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>
2022-03-22 20:57:05 +00:00
Arthur Cohen
ef56381862 parser: Add better restrictions around semicolons in statements
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.
2022-03-22 16:00:30 +01:00
Thomas Schwinge
f0b5ac2e82 Document 'Continuous Integration', 'Compiler Diagnostics' in 'README.md' 2022-03-22 14:51:53 +01:00
bors[bot]
cc6e405912 Merge #1041
1041: macros: Only expand merged repetitions if they contain the same amount r=CohenArthur a=CohenArthur

Depends on #1040 
Fixes #948 

Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
2022-03-22 11:30:04 +00:00
Thomas Schwinge
f91f637652 Tune '.github/workflows/ccpp.yml:jobs.build-and-check', 'Check for new warnings' step
Run it in scratch directory, too, to not pollute the pristine sources
directory.  Point to <https://github.com/Rust-GCC/gccrs/pull/1026> in case of
failure.
2022-03-22 12:17:23 +01:00
Thomas Schwinge
10ff5d5507 Merge 'Build logs' into 'Build' in '.github/workflows/ccpp.yml:jobs.build-and-check'
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'.
2022-03-22 12:17:23 +01:00
Thomas Schwinge
246fb48cbb Force 'LC_ALL=C.UTF-8' for all steps of '.github/workflows/ccpp.yml:jobs.build-and-check'
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".
2022-03-22 12:17:23 +01:00
bors[bot]
6ecd43c779 Merge #1040
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>
2022-03-22 11:02:45 +00:00
Thomas Schwinge
202e61bc2d Force 'LC_ALL=C' for all steps of '.github/workflows/ccpp.yml:jobs.build-and-check' 2022-03-22 09:55:43 +01:00
Arthur Cohen
651d9a77ce macros: Add helper debugging function for substituted tokens
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>
2022-03-21 16:52:31 +01:00
bors[bot]
32894e6986 Merge #1042
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>
2022-03-21 12:41:52 +00:00
Philip Herron
afa451b311 Add initial support for unsized method resolution
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
2022-03-21 12:40:20 +00:00
CastilloDel
60d1fd533c Add a check for new warnings to the CI
This should prevent new warnings from appearing silently

Signed-off-by: Daniel del Castillo delcastillodelarosadaniel@gmail.com
2022-03-20 09:42:41 +00:00
Arthur Cohen
80d9690242 parser: Parse reserved keywords as valid fragments identifiers
Per the reference, macro fragments actually accept all identifiers, not
NON_KEYWORD_IDENTIFIERS
2022-03-18 14:44:29 +01:00
Arthur Cohen
f8c550f7e1 macros: Only expand merged repetitions if they contain the same amount
of matches

Forbid merging repetitions if the matched fragments do not contain the
same amount of repetitions
2022-03-18 14:09:03 +01:00
Arthur Cohen
a64a5cf77c macros: Do not propagate parse errors in match repetitions
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.
2022-03-18 12:40:05 +01:00
bors[bot]
1bb9a29688 Merge #1029
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>
2022-03-17 16:04:23 +00:00
Arthur Cohen
a7ef6f98be macros: Allow macro calls in trait implementations
Just like inherent implementation blocks, trait implementation blocks
(`impl Trait for Type`) can also contain macro invocations.
2022-03-17 15:56:18 +01:00
Arthur Cohen
935b561e7f macros: Add test cases for remaining expansion contexts 2022-03-17 15:51:09 +01:00
Arthur Cohen
1a2ef9cae9 macros: Add remaining context and improve parsing macro dispatch
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.
2022-03-17 15:51:06 +01:00
bors[bot]
1a14348afe Merge #1035
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>
2022-03-17 13:15:45 +00:00
bors[bot]
b7baee8795 Merge #1037
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>
2022-03-17 12:47:18 +00:00
Arthur Cohen
e30d07de5c parser: Handle -fsyntax-only properly
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>
2022-03-17 13:29:38 +01:00
bors[bot]
e48bce446c Merge #1027 #1032
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 #1011 
Closes #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>
2022-03-17 11:25:48 +00:00
Philip Herron
f6c86fc8cd Support placeholders becoming slices
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
2022-03-17 11:02:58 +00:00
bors[bot]
3ada3d8365 Merge #1022 #1033
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>
2022-03-17 10:53:07 +00:00
bors[bot]
fe13ad49b1 Merge #1030
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>
2022-03-17 10:23:04 +00:00
Philip Herron
6e385d2f25 Fix bad copy-paste in can equal interface for pointer types
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
2022-03-17 09:51:39 +00:00
Arthur Cohen
1e873922f0 ast: Add Kind::MACRO_INVOCATION and cleanup fatal errors in lowering
macro invocations
2022-03-17 10:38:07 +01:00
Arthur Cohen
b776c4953c macros: Do not lower macro definitions to HIR
Avoid lowering block statements that should not be lowered, such as
macro-rules definitions
2022-03-17 10:22:44 +01:00
Arthur Cohen
14b99bed08 ast: Add base Node class with get_ast_kind() function
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.
2022-03-17 10:21:32 +01:00
bors[bot]
bb234b080a Merge #1021
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>
2022-03-17 08:27:03 +00:00
Philip Herron
8086790254 Fix unconstrained type parameter checks
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
2022-03-16 22:12:35 +00:00
Philip Herron
21cf0e67a6 Add missing location info on GenericArgs 2022-03-16 15:49:26 +00:00
Philip Herron
7ac9a76c89 Make TypeBoundPredicate a subclass of the SubstitutionRef
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.
2022-03-16 15:22:52 +00:00
Philip Herron
56a1571614 Keep track of substitution mappings as part of the TraitReference
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.
2022-03-16 14:34:26 +00:00
Philip Herron
9411c061aa Refactor TypeBoundPredicate to be below the definition for SubstitutionRef
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.
2022-03-16 14:24:41 +00:00
Arthur Cohen
b6b567171c attribute expansion: Fix spurious stripping of tail expression
This commit fixes the issue reported in #391, but highlights another
one, which will be reported.
2022-03-16 09:38:09 +01:00
Arthur Cohen
313e9890d8 parser: Allow parsing stmts without closing semicolon
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
2022-03-14 16:34:50 +01:00
bors[bot]
2dfc196477 Merge #1025
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>
2022-03-14 15:03:08 +00:00
Philip Herron
7d7bc2ce38 Fix memory corruption in generation of builtin functions
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
2022-03-14 12:57:01 +00:00
Arthur Cohen
02887c88f5 macros: Do not try and re-expand if depth has exceeded recursion limit
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
2022-03-14 11:21:20 +01:00
bors[bot]
41f402f0b1 Merge #1004
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>
2022-03-13 11:45:43 +00:00
M V V S Manoj Kumar
d9a5bddb4c Added column!() macro
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>
2022-03-13 11:42:22 +05:30
bors[bot]
8c88e8e0c9 Merge #1015 #1018
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>
2022-03-11 14:40:22 +00:00
bors[bot]
a50fcbc2eb Merge #1017
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>
2022-03-11 14:09:01 +00:00
Philip Herron
040b2ec9a6 Add code generation for the slice type
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
2022-03-11 13:54:21 +00:00
Arthur Cohen
c62e9eb5ee builtin-macros: Add more documentation for defining builtins 2022-03-11 14:19:56 +01:00
Arthur Cohen
63a214618a attr-visitor: Split in its own source and header
Split up the 4000 lines rust-macro-expand.cc file containing the
AttrVisitor class and the macro expander implementation
2022-03-11 13:33:59 +01:00
bors[bot]
e076823eda Merge #1016
1016: Add missing HIR lowering for SliceTypes r=philberty a=philberty

Addresses #849


Co-authored-by: Philip Herron <philip.herron@embecosm.com>
2022-03-11 12:08:30 +00:00
Philip Herron
47ae663a3e Add missing HIR lowering for SliceTypes
Addresses #849
2022-03-11 11:44:00 +00:00
bors[bot]
6e64e6636e Merge #1008 #1009
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>
2022-03-11 10:39:24 +00:00
bors[bot]
dbe59a3198 Merge #1007
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>
2022-03-11 10:10:58 +00:00
bors[bot]
ddd087b0ef Merge #1003
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>
2022-03-11 09:41:37 +00:00
bors[bot]
1f4e2deb31 Merge #1002
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>
2022-03-11 08:51:43 +00:00
bors[bot]
51c7cf4b97 Merge #998
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 #943 
Closes #959 
Closes #952 

Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
2022-03-11 08:24:43 +00:00
Arthur Cohen
f02392c8b3 macros: Replace macro invocations with expanded nodes
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>
2022-03-11 09:21:29 +01:00
Arthur Cohen
9f73e827ab macros: Add abstraction around multiple matches
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>
2022-03-10 21:45:34 +01:00
Philip Herron
894e9d29ad Handle generic Slices and Arrays
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.
2022-03-10 16:51:03 +00:00
Philip Herron
a620a228c1 Add missing type-checking for slice types 2022-03-10 16:50:56 +00:00
Philip Herron
a1b065050b Add const_ptr lang item mappings
const_ptr is a lang item used as part of the slice implemenation this
adds it to our mappings so we do not error with an unknown lang item.
2022-03-10 16:45:49 +00:00
Philip Herron
31413ebacf Add missing canonicalization of slices and raw pointer 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
2022-03-10 16:42:36 +00:00
Philip Herron
f057445119 Add size_of intrinsic
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
2022-03-10 11:47:28 +00:00
Philip Herron
796c978c48 Add builtin abort intrinsic
Addresses #658
2022-03-10 11:46:24 +00:00
Philip Herron
9e23c29cd0 Add builtin unreachable intrinsic mapping
This demonstrates how we can add in the simple intrinsics in a single
patch.

Addresses #658
2022-03-10 11:40:11 +00:00
Philip Herron
178cabde9f Add missing builtin mappings for never type 2022-03-10 11:40:11 +00:00
Philip Herron
94990a843b Refactor how we define simple intrinsics
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.
2022-03-10 11:40:11 +00:00
Philip Herron
a08ac0c27a Add support for the rust offset intrinsic
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
2022-03-10 11:40:02 +00:00
bors[bot]
77a4950744 Merge #999
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>
2022-03-09 17:17:25 +00:00
bors[bot]
39c0425830 Merge #994 #997
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>
2022-03-08 16:31:51 +00:00
Philip Herron
749a419a2e Refactor ABI options as part of HIR function qualifiers
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.
2022-03-08 16:09:05 +00:00
Arthur Cohen
d2a6a5eef4 macros: Allow any delimiters for invocation
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)
2022-03-08 13:33:19 +01:00
Arthur Cohen
dc2eab3952 macros: Add parentheses in repetition test case 2022-03-08 11:08:26 +01:00
Arthur Cohen
08b7516191 macros: Parse macro patterns properly in repetition
Co-authored-by: philberty <philip.herron@embecosm.com>
2022-03-08 11:08:26 +01:00
bors[bot]
865b6090a8 Merge #992
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>
2022-03-07 12:17:40 +00:00
Philip Herron
7820ff8b8b Remove old unused code pass this was too generic
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
2022-03-07 12:16:18 +00:00
Philip Herron
e00311aa9a Update the deadcode pass to scan into modules and respect underscores on type names 2022-03-07 12:06:20 +00:00
Philip Herron
be94ef6e2d Change unit-type to be an empty struct so that we do not disregard the
initilizer of variables
2022-03-07 12:06:20 +00:00
Philip Herron
7a3c935c0f Check if this constant item might already be compiled 2022-03-07 12:06:20 +00:00
bors[bot]
366c53371a Merge #991
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>
2022-03-07 08:47:19 +00:00
bors[bot]
b82408fd6a Merge #986
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>
2022-03-06 21:24:24 +00:00
bors[bot]
e2bccf43ed Merge #985
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>
2022-03-06 20:50:55 +00:00
bors[bot]
d89c8ccf32 Merge #990
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>
2022-03-04 11:58:45 +00:00
bors[bot]
b4bd389c66 Merge #984
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>
2022-03-04 11:30:52 +00:00
M V V S Manoj Kumar
3f2d5a720b Got rid of lambda in TyTy::FnPtr iterate_params
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>
2022-03-04 08:27:22 +05:30
Arthur Cohen
0c7e16e125 macros: Add test cases for macro repetition separators 2022-03-03 15:21:09 +01:00
Arthur Cohen
4fde21b37a macros: Substitute separator if necessary when expanding repetitions 2022-03-03 15:21:03 +01:00
Arthur Cohen
ab4533dab7 macros: Match repetition separator properly 2022-03-03 15:20:55 +01:00
Arthur Cohen
25a33b0739 macros: Add test cases for recursive macro invocation 2022-03-03 15:11:23 +01:00
Arthur Cohen
a498b2c5d6 macro-substitute: Do not substitute non-repetition fragments in sub-maps
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)
2022-03-03 15:11:23 +01:00
Philip Herron
d6e1771291 must use attribute support
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
2022-03-03 11:08:18 +00:00
Philip Herron
57b5060798 Add missing accessor for attributes on external items 2022-03-03 11:08:17 +00:00
Philip Herron
17d4a75971 Remove gcc abstraction for expression statement
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.
2022-03-03 11:08:17 +00:00
bors[bot]
e35da26d8e Merge #988
988: lexer: Add reference and warning documentation r=tschwinge a=CohenArthur

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>

Closes #987 

Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
2022-03-02 16:27:51 +00:00
Arthur Cohen
45eac56868 lexer: Add reference and warning documentation
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>
2022-03-02 15:18:40 +01:00
bors[bot]
6cf9f8c99c Merge #983
983: Parse proper cfg values r=CohenArthur a=CohenArthur

Closes #936 

Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
2022-03-01 17:26:07 +00:00
Arthur Cohen
f7ff6020f8 lexer: Improve safety by taking ownership of the tokenized string
Co-authored-by: philberty <philip.herron@embecosm.com>
2022-03-01 17:20:29 +01:00
Arthur Cohen
82fc107e3d macros: Add test cases for recursive macro invocation 2022-03-01 15:20:31 +01:00
Arthur Cohen
c8499831fd macro-substitute: Do not substitute non-repetition fragments in sub-maps
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)
2022-03-01 15:20:31 +01:00
bors[bot]
e82b59dfc9 Merge #981
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>
2022-03-01 11:36:13 +00:00
Arthur Cohen
58d1721529 macroinvocation: Only allow *stmt* visitors when semicoloned 2022-03-01 11:19:11 +01:00
Arthur Cohen
12d156566a parser: Allow parsing macro invocations as statements
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.
2022-03-01 11:19:11 +01:00
Arthur Cohen
49dcecd3b6 frust-cfg: Use proper parser to parse key-value pairs
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
2022-02-26 13:23:12 +01:00
Arthur Cohen
ede68b7ba6 lexer: Add ability to lex strings directly
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.
2022-02-26 13:21:46 +01:00
Arthur Cohen
27be628911 macro-expand: Add SubstitutionCtx class in its own file 2022-02-26 11:35:01 +01:00
bors[bot]
ed1a4dc33f Merge #954
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>
2022-02-25 21:43:04 +00:00
Marc Poulhiès
dffb1adabd HIR Visitor refactoring
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>
2022-02-25 20:37:37 +01:00
bors[bot]
b695eb8f0b Merge #970
970: Add file!() builtin r=CohenArthur a=CohenArthur



Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
2022-02-25 12:09:43 +00:00
bors[bot]
d3a4cf93b7 Merge #974
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>
2022-02-25 11:14:37 +00:00
Philip Herron
22c6bca60a Add support for index lang item overloads
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
2022-02-24 16:59:56 +00:00
Philip Herron
d8351d9168 Decouple the HIR::OperatorExpr from resolving operator overloads
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.
2022-02-24 16:39:12 +00:00
Philip Herron
5d5396d522 Refactor operator overloading code into cc file 2022-02-24 16:02:50 +00:00
Philip Herron
3b3079eba5 Cleanup error handling on array index expression type resolution 2022-02-24 15:55:35 +00:00
Philip Herron
7d6579c2fa Fix ICE as infered is nullptr at this point 2022-02-24 15:43:00 +00:00
Philip Herron
2975f11436 Add index and index_mut lang item mappings 2022-02-24 14:54:34 +00:00
Philip Herron
0033df1a52 Refactor ArrayIndexExpr typechecking into cc impl file 2022-02-24 14:30:15 +00:00
Philip Herron
833c439a50 Add boilerplate for the new SliceType 2022-02-24 12:47:57 +00:00
Philip Herron
a6dd242845 Refactor ArrayIndexExpr code into implementation cc file 2022-02-24 11:59:19 +00:00
Philip Herron
7d4845bc95 Add code generation for range expressions 2022-02-24 11:49:51 +00:00
Philip Herron
fa21267280 Fix TyTy::ADTType is_equals to always check the variants for equality 2022-02-24 11:20:19 +00:00
Philip Herron
a64983f86c Add typechecking for range expressions
This looks up the relevant lang items and constructs their algebraic data
types with the specified range types for the substitution argument.
2022-02-24 11:19:23 +00:00
Philip Herron
1c3af63eae Add missing range mapping lang item 2022-02-24 11:19:23 +00:00
Philip Herron
ac17ed5f5e Add HIR lowering for range expressions 2022-02-24 11:19:23 +00:00
Arthur Cohen
8cc50f2d23 builtin_macros: Add test for file!() 2022-02-23 15:53:15 +01:00
Arthur Cohen
62ab4d6bf1 builtin_macros: Add make_string helper 2022-02-23 15:53:15 +01:00
Arthur Cohen
986b8c3c60 builtins: Add file!() macro 2022-02-23 15:44:21 +01:00
bors[bot]
bf92a10122 Merge #969
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>
2022-02-23 13:37:07 +00:00
Arthur Cohen
48b3fe622e macros: Add optional builtin transcribers to MacroRulesDefinition 2022-02-23 14:36:11 +01:00
Arthur Cohen
0b46175fb8 macro: Add source containing builtin definitions
Co-authored-by: philberty <philip.herron@embecosm.com>
2022-02-23 14:36:11 +01:00
bors[bot]
10de9cf4f3 Merge #956
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 #960 
Closes #961 

Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
2022-02-23 09:17:08 +00:00
Arthur Cohen
92a62562c8 substitute_repetition: Correctly insert sub-fragments 2022-02-23 10:13:06 +01:00
Arthur Cohen
1f546e5e3a match_repetition: Set the correct amount of matches for each fragment
Co-authored-by: philberty <philip.herron@embecosm.com>
2022-02-23 10:13:06 +01:00
bors[bot]
e0f261f1ae Merge #953
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>
2022-02-22 16:25:07 +00:00
Philip Herron
865aa0aeb5 Add new Builtin attributes mappings
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.
2022-02-22 16:19:30 +00:00
Philip Herron
9bdc5462f2 Add mappings for range lang items 2022-02-22 15:17:36 +00:00
Philip Herron
bede822298 Refactor mapping any lang items to be done during HIR lowering
This extracts a common way of handling outer attributes on Items to improve
error handling and make lang item mappings more generic.
2022-02-22 15:17:36 +00:00
Philip Herron
87aeea2583 Refactor lang item mappings enum into its own header 2022-02-22 15:17:36 +00:00
Arthur Cohen
6db51e3936 subs_repetition: Add simple test cases 2022-02-22 12:06:27 +01:00
Arthur Cohen
ded1aca902 substitute_repetition: Substitute repetitions properly 2022-02-22 12:06:27 +01:00
Arthur Cohen
143aad62e1 substitute_repetition: Add parsing of repetition pattern 2022-02-22 12:05:58 +01:00
Arthur Cohen
ae1f91a698 transcribe: Move substitute_metavar in its own function 2022-02-22 11:57:19 +01:00
bors[bot]
265c223766 Merge #964 #965
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>
2022-02-22 10:05:34 +00:00
bors[bot]
133beb6d0f Merge #955
955: matched_fragment: Track and set fragment match amount r=CohenArthur a=CohenArthur



Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
2022-02-22 09:39:25 +00:00
Arthur Cohen
91aca2c19e matched_fragment: Track and set fragment match amount
Co-authored-by: philberty <philip.herron@embecosm.com>
2022-02-22 10:38:39 +01:00
Arthur Cohen
4e19c2f792 macro-invoc-lexer: Split implementation in its own file 2022-02-21 17:27:56 +01:00
Arthur Cohen
9b36f95366 testsuite: Add -fdump-tree-gimple to inline1.rs 2022-02-21 17:01:10 +01:00
Arthur Cohen
737873ca87 ci: Do not allow unresolved test cases 2022-02-21 16:39:06 +01:00
bors[bot]
796465596f Merge #950
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>
2022-02-20 14:34:37 +00:00
bors[bot]
4e096b1f14 Merge #951
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>
2022-02-20 14:03:54 +00:00
Arthur Cohen
d0d4dcfdb4 macro: Add repetition execution test cases 2022-02-18 16:46:10 +01:00
Arthur Cohen
af789a7079 macros: Add test cases for repetitions 2022-02-18 16:46:10 +01:00
Arthur Cohen
ad7e4bb6f8 macro-repetitions: Match repetitions properly 2022-02-18 16:46:10 +01:00
bors[bot]
31387e7609 Merge #944
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>
2022-02-18 14:43:08 +00:00
Philip Herron
3dd4ce76a6 Add name resolution to range expressions 2022-02-18 13:26:24 +00:00
Philip Herron
755d0e5adf Refactor AST::ResolveExpr into its own cc file 2022-02-18 13:07:13 +00:00
Philip Herron
de08987dc7 Add name resolution to AST::SliceType 2022-02-18 12:55:14 +00:00
Philip Herron
78cdc6ca31 Refactor type name resolution into their own .cc file 2022-02-18 12:46:44 +00:00
bors[bot]
425905b49a Merge #942
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>
2022-02-18 11:50:32 +00:00
Arthur Cohen
472c0a3057 macro-repetition: Rename enum variants to better reflect repetition kind 2022-02-18 11:18:03 +01:00
Arthur Cohen
5f35a8c637 parser: Add clear_errors() method 2022-02-18 09:19:04 +01:00
bors[bot]
fbe22e8768 Merge #940
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>
2022-02-18 08:14:30 +00:00
Arthur Cohen
0e15b89839 struct pattern: Add location on struct name 2022-02-18 09:10:55 +01:00
Arthur Cohen
425ebda243 type-path-fn: Add location info on start of Fn token 2022-02-18 09:10:52 +01:00
Arthur Cohen
ef06769781 path-id: Add location info on path identifier 2022-02-18 09:08:07 +01:00
Arthur Cohen
9e524a7f5a closure-arg: Add location info on arg name 2022-02-18 09:08:07 +01:00
Arthur Cohen
63538444fb struct-base: Add location info on .. token 2022-02-18 09:08:07 +01:00
Arthur Cohen
d120c9db18 array-copy-init: Add location info 2022-02-18 09:08:07 +01:00
Arthur Cohen
c6daece647 array-values: Add location info 2022-02-18 09:08:07 +01:00
Arthur Cohen
205a9cbf9e fn-arg: Add location on parameter name 2022-02-18 09:08:07 +01:00
bors[bot]
9fb06d66ce Merge #938
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>
2022-02-17 17:02:43 +00:00
M V V S Manoj Kumar
ee4131396e Removed Lambda Function within AST::PathPattern
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>
2022-02-17 22:11:23 +05:30
Philip Herron
37415eec77 Semicolon based macro invocation
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.
2022-02-17 16:41:15 +00:00
Philip Herron
4c70d7ec77 Support block expressions within macros
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.
2022-02-17 13:28:25 +00:00
Philip Herron
19c5dde80f When we expand a macro we must visit it to ensure any cfg expansions or recursive macro expansion is required 2022-02-17 13:28:25 +00:00
Philip Herron
2c03f34027 Add initial support for macro expansion
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
2022-02-17 13:28:25 +00:00
Philip Herron
ef626302f7 Add name-resolution helpers for looking up macros 2022-02-17 13:28:24 +00:00
Philip Herron
a026c166f0 Add mappings helpers for looking up macros definitions 2022-02-17 13:28:24 +00:00
Philip Herron
864df7901c Add missing copyright header to lexer header 2022-02-17 13:28:24 +00:00
bors[bot]
752bf6c80a Merge #935
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>
2022-02-17 10:58:07 +00:00
Arthur Cohen
766a9002a3 frust-cfg: Only allow double quoted values
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.
2022-02-17 11:23:25 +01:00
bors[bot]
6a6c217093 Merge #932
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>
2022-02-17 09:22:03 +00:00
Arthur Cohen
c1e72db48a macrorule: Add location information 2022-02-17 10:20:13 +01:00
bors[bot]
d81ba63f48 Merge #933
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>
2022-02-17 08:44:36 +00:00
Arthur Cohen
45ca46018f macrotranscriber: Add location info 2022-02-17 09:43:48 +01:00
bors[bot]
a5272f389b Merge #934 #937
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>
2022-02-16 18:38:44 +00:00
bors[bot]
733db624cf Merge #931
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>
2022-02-16 18:13:03 +00:00
Arthur Cohen
85d78c1b8d dockerfile: Install cargo-gccrs alongside gccrs 2022-02-16 18:47:36 +01:00
Arthur Cohen
3ac17160c8 macromatch: Add location to abstract MacroMatch class 2022-02-16 14:46:59 +01:00
Arthur Cohen
8848a76f83 rust-cfg: Quote option name when erroring out 2022-02-16 12:10:07 +01:00
bors[bot]
330b265134 Merge #926
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>
2022-02-16 09:48:58 +00:00
Arthur Cohen
08dbb4e322 macros: Add base for execution tests for macros 2022-02-16 02:14:03 +01:00
Arthur Cohen
29e07e06be macros: Add multiple macro syntax tests 2022-02-16 02:11:12 +01:00
bors[bot]
c7275a7fb8 Merge #922
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>
2022-02-13 15:01:35 +00:00
Philip Herron
112f2841ee Support inline never and always options
This maps over to DECL_UNINLINEABLE and to use the GCC attribute
always_inline.

Fixes #921
2022-02-13 14:27:01 +00:00
bors[bot]
b71cc52613 Merge #920
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>
2022-02-12 16:35:24 +00:00
Philip Herron
c0e5ca327b Support deref_mut lang item during method resolution
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
2022-02-11 15:34:17 +00:00
bors[bot]
9023bb8687 Merge #918
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>
2022-02-11 10:29:35 +00:00
Philip Herron
4242d45d3d refactor named_constant_expression out of the backend class 2022-02-11 10:27:55 +00:00
Philip Herron
5801e165b3 Fix warnings when including rust-target.h information 2022-02-11 10:18:24 +00:00
Philip Herron
d21ae24049 Cleanup header usage and remove void_type wrapper 2022-02-11 10:11:25 +00:00
Philip Herron
df2dbbc034 Remove error_mark_node wrappers from backend proxy class. 2022-02-11 10:02:46 +00:00
Philip Herron
b2aa172ff6 Refactor code to reuse a canonical way to compile functions and constants
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.
2022-02-10 19:28:10 +00:00
bors[bot]
e2823b6747 Merge #917
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>
2022-02-10 17:08:15 +00:00
Philip Herron
1b487d72cd Remove tree addressable flags from back-end local and fnparm decl creation 2022-02-10 16:07:28 +00:00
Philip Herron
e49dd22fc2 Remove unsued functions in the GCC wrapper 2022-02-10 15:52:37 +00:00
Philip Herron
859732e4d1 Remove AddressTakenContext
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.
2022-02-10 15:40:55 +00:00
bors[bot]
f6ba472caf Merge #916
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>
2022-02-10 12:50:30 +00:00
Philip Herron
c598bbbcc1 Support inline attribute by marking as DECL_DECLARED_INLINE_P
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
2022-02-09 18:00:00 +00:00
bors[bot]
6d1ff56808 Merge #912
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>
2022-02-08 17:56:41 +00:00
bors[bot]
055ca34daa Merge #911
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>
2022-02-08 17:30:04 +00:00
Philip Herron
257bf55827 Handle generic substitution on path expressions
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
2022-02-08 15:19:29 +00:00
Philip Herron
b7cdd81dbc Refactor to_string from header to impl file 2022-02-07 17:47:48 +00:00
bors[bot]
5619eea6f6 Merge #909
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>
2022-02-06 23:52:33 +00:00
bors[bot]
5c36d24c65 Merge #888
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>
2022-02-06 22:20:09 +00:00
bors[bot]
05cfe8f9fd Merge #908
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>
2022-02-06 20:44:45 +00:00
bors[bot]
2423c89dee Merge #751
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>
2022-02-05 15:54:33 +00:00
CohenArthur
bc47ace0ec selftest: Move C specific tests in c_family_test() 2022-02-05 16:02:50 +01:00
CohenArthur
2b1345a736 selftest: Enable unit testing for the rust frontend 2022-02-05 16:02:47 +01:00
Philip Herron
9173f062a9 Add support for key = value pairs on -frust-cfg=
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
2022-02-04 17:41:44 +00:00
Thomas Schwinge
42f49fa7da Fix '-Wformat-diag' issue in 'TypeCheckPattern::visit (HIR::TupleStructPattern &pattern)'
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
2022-02-04 13:52:31 +01:00
bors[bot]
83bfbf0746 Merge #907
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>
2022-02-04 09:38:43 +00:00
@mvvsmk
b92a9b80fa Upated parameterised constuctor of MatchArm to take location data
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>
2022-02-04 13:49:50 +05:30
Thomas Schwinge
7eef766dc5 Merge commit 'ff7aeceb6b3a476c3bac66a7f39a5ef4240206fc' [#247, #906] 2022-02-03 21:14:10 +01:00
Thomas Schwinge
5199ecb851 Revert code formatting changes of "Added MSP430 target hook (or at least provisional one)"
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.
2022-02-03 21:10:43 +01:00
bors[bot]
20ae602991 Merge #906
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>
2022-02-03 20:06:51 +00:00
Philip Herron
9f36d99b40 Support cfg expansions predicates
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
2022-02-03 15:56:56 +00:00
bors[bot]
3e6f9c2150 Merge #903
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>
2022-02-03 11:59:18 +00:00
Thomas Schwinge
5691503f11 GCC/Rust pieces of GCC upstream "Mass rename of C++ .c files to .cc suffix"
... in preparation of merge of the latter.
2022-02-03 12:44:54 +01:00
bors[bot]
016db703cb Merge #904
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>
2022-02-03 11:33:00 +00:00
Philip Herron
4d1ca35582 Apply the is_marked_for_strip check to the rest of the crate
We need to apply this to all levels of the crate:

Item
  impl-item
  trait-item
  Stmt
2022-02-02 16:47:19 +00:00
Philip Herron
d2a0fa7fc5 Add new RustIdent struct to track canonical-path and location info
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.
2022-02-02 15:50:13 +00:00
bors[bot]
f7f14de056 Merge #902
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>
2022-02-02 14:28:27 +00:00
Philip Herron
46ee20dbdb Fix enum variant discriminant values
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.
2022-02-02 14:06:25 +00:00
bors[bot]
6e5f8f76cb Merge #900
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>
2022-01-31 15:26:53 +00:00
Philip Herron
4c36c7c8d3 Fixup logic in canonical-path for impl-blocks
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.
2022-01-31 00:14:31 +00:00
bors[bot]
631f7ae7b9 Merge #894
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>
2022-01-29 15:00:30 +00:00
Philip Herron
2fbf9cb25e Track the cratenum for the respective canonical path
This means we can get the crate name to squash the warning in the V0 symbol
mangling scheme.
2022-01-29 14:56:27 +00:00
Philip Herron
a065f205c3 This updates our handling of canonical paths to contain the crate-name
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.
2022-01-29 14:27:20 +00:00
Philip Herron
63686e099b Refactor Mangling API crate name should be part of the CanonicalPath
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$.
2022-01-29 14:17:44 +00:00
Philip Herron
375d8b5900 Add helpers to access each segment of the canonical path 2022-01-29 14:17:44 +00:00
Philip Herron
63429653c1 Change default crate name to example 2022-01-29 14:17:44 +00:00
bors[bot]
bc7f518ac6 Merge #899
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>
2022-01-29 12:47:51 +00:00
bors[bot]
9346bddb10 Merge #897 #898
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>
2022-01-29 12:16:00 +00:00
Philip Herron
ebfbdf962f Add -frust-cfg=value option for adding config options
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
2022-01-28 10:08:44 +00:00
Philip Herron
a110fd152f Add deref_mut lang_item mappings 2022-01-27 12:01:49 +00:00
Philip Herron
959a076d6f Remove unused include 2022-01-27 11:06:03 +00:00
@mvvsmk
6508698504 Added location data to Match Arm and removed unused code
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>
2022-01-26 12:55:42 +05:30
bors[bot]
1fc2b54080 Merge #892
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>
2022-01-25 17:00:21 +00:00
bors[bot]
5f2973fe0e Merge #891
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>
2022-01-25 16:34:18 +00:00
Philip Herron
234816ac9d Remove bad assertion when resolving segments
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
2022-01-25 12:19:15 +00:00
Philip Herron
c8a0c6eb4b Remove hack to handle forward declared items
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.
2022-01-24 18:42:24 +00:00
Thomas Schwinge
3de87e620f Update GCC/Rust files per 'contrib/update-copyright.py --this-year' [#764] 2022-01-24 11:37:01 +01:00
Thomas Schwinge
21af490baa Merge commit '490e23032baaece71f2ec09fa1805064b150fbc2' [#247] 2022-01-24 10:06:43 +01:00
bors[bot]
2cce6b8919 Merge #873
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>
2022-01-22 13:07:05 +00:00
Philip Herron
ee794effe3 MethodResolution should respect the autoderef cycle
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
2022-01-22 12:11:41 +00:00
bors[bot]
6c9e57efa5 Merge #883
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>
2022-01-21 22:24:23 +00:00
bors[bot]
8c96ccceb2 Merge #885
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>
2022-01-21 21:59:42 +00:00
bors[bot]
c11048a764 Merge #880
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>
2022-01-21 21:08:32 +00:00
Philip Herron
d31c1bdaa8 Improve error message for failure in Method resolution
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
2022-01-21 20:49:55 +00:00
bors[bot]
d956be9933 Merge #881 #882
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>
2022-01-21 20:43:15 +00:00
Philip Herron
e77f051369 Extract AsyncConstStatus to be a shared enum between AST and HIR
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
2022-01-21 20:42:09 +00:00
Philip Herron
dfb7f9c123 Add Mappings::iterate_trait_items helper 2022-01-21 20:06:21 +00:00
Philip Herron
120967b80b Add TraitItemKind to HIR TraitItems
This allows us to safely switch and cast between the items without the
need for visitors.
2022-01-21 20:01:32 +00:00
Philip Herron
0f9257baae Covariant types should respect the get_name to pretty print the ir symbols 2022-01-21 19:55:24 +00:00
bors[bot]
a6c5dbadc3 Merge #879
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>
2022-01-21 16:19:30 +00:00
David Faust
b4587fb281 Record correct location when compiling ADT types
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
2022-01-20 12:53:23 -08:00
bors[bot]
b02824c6a7 Merge #874
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>
2022-01-15 11:20:18 +00:00
David Faust
7d456b882a Track end locus of BlockExpr
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
2022-01-14 10:28:11 -08:00
bors[bot]
b21caeb3af Merge #870
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>
2022-01-14 15:49:07 +00:00
Philip Herron
93554f3bce Add initial constant evaluation to blocks
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
2022-01-14 12:32:49 +00:00
Philip Herron
e9ffd4308d Add HIR::ExprType get_expression_type() const 2022-01-14 12:32:49 +00:00
Philip Herron
52780af660 Redesign constant folding from the typechecking pass to the backend
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
2022-01-14 12:32:40 +00:00
Philip Herron
06c2a74f55 Add HIR lowering for FunctionQualifiers 2022-01-13 21:29:22 +00:00
Philip Herron
f51d8fd538 Add ArrayElemsType enum to differentiate between the types 2022-01-13 21:28:42 +00:00
bors[bot]
03e56b5181 Merge #860
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>
2022-01-07 12:47:36 +00:00
bors[bot]
230b55bb53 Merge #868
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>
2022-01-07 11:57:24 +00:00
bors[bot]
bc27d11316 Merge #866
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>
2022-01-07 11:29:06 +00:00
bors[bot]
e082b6cfd0 Merge #859
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>
2022-01-07 10:28:29 +00:00
bors[bot]
754af6737a Merge #848
848: Add missing bitwise lang items for operator overloading r=philberty a=philberty

This adds the missing bitwise lang items:

- bitand: libcore/ops/bit.rs
- bitor: libcore/ops/bit.rs
- bitxor: libcore/ops/bit.rs
- shl: libcore/ops/bit.rs
- shr: libcore/ops/bit.rs
- bitand_assign: libcore/ops/bit.rs
- bitor_assign: libcore/ops/bit.rs
- bitxor_assign: libcore/ops/bit.rs
- shl_assign: libcore/ops/bit.rs
- shr_assign: libcore/ops/bit.rs

Addresses #742


Co-authored-by: Philip Herron <philip.herron@embecosm.com>
2022-01-06 17:27:28 +00:00
bors[bot]
0b0deb4ee9 Merge #847
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>
2022-01-06 17:01:49 +00:00
Philip Herron
34710b497e Add support for Wildcard pattern binding
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
2022-01-06 16:57:52 +00:00
Philip Herron
6d0892636e Add support for wildcard patterns within MatchExprs
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
2022-01-06 15:35:28 +00:00
Philip Herron
507dbac06d Add overflow checking on LiteralExpression
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
2022-01-06 10:48:10 +00:00
Philip Herron
5b369a6148 Fix ICE in generic subsitution of enums containing dataless variants
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
2022-01-04 16:15:26 +00:00
Philip Herron
41cdd94998 Add missing bitwise lang items for operator overloading
This adds the missing bitwise lang items:

- bitand: libcore/ops/bit.rs
- bitor: libcore/ops/bit.rs
- bitxor: libcore/ops/bit.rs
- shl: libcore/ops/bit.rs
- shr: libcore/ops/bit.rs
- bitand_assign: libcore/ops/bit.rs
- bitor_assign: libcore/ops/bit.rs
- bitxor_assign: libcore/ops/bit.rs
- shl_assign: libcore/ops/bit.rs
- shr_assign: libcore/ops/bit.rs

Addresses #742
2022-01-03 15:51:42 +00:00
Philip Herron
bfb7ef7fc8 HIR::ImplBlock items should mangle based from their canonical path's
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
2022-01-03 12:19:44 +00:00
bors[bot]
69f6be3ee4 Merge #846
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>
2021-12-29 15:17:03 +00:00
Marc Poulhiès
f9b6c0caf8 HIR visitor refactor
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>
2021-12-22 16:42:22 +01:00
bors[bot]
4c5ebc08e6 Merge #842
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>
2021-12-18 21:41:36 +00:00
bors[bot]
b06de309eb Merge #841
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>
2021-12-18 21:00:27 +00:00
Philip Herron
52ee02f401 Add support for enums on the match expression
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
2021-12-18 20:20:49 +00:00
Philip Herron
04c1f56974 add script to graph the changes over time 2021-12-17 16:28:48 +00:00
bors[bot]
a8a345642a Merge #839
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>
2021-12-16 15:23:39 +00:00
bors[bot]
e8d91e9e08 Merge #840
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>
2021-12-16 14:35:21 +00:00
Philip Herron
cd1814f927 Add missing abstract method HIR::Pattern::get_locus() const 2021-12-16 14:33:28 +00:00
Philip Herron
45edfc2b26 Add typechecking for match-expr 2021-12-16 14:29:08 +00:00
bors[bot]
de1ed2e805 Merge #838
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>
2021-12-16 13:08:09 +00:00
Philip Herron
4d70990b83 Add mssing mappings to HIR::Pattern 2021-12-16 13:02:40 +00:00
bors[bot]
8507a68883 Merge #837
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>
2021-12-16 12:04:43 +00:00
Philip Herron
3a8c585300 HIR::IdentifierPattern had all fields public
This makes the fields private again and adds the missing getter for the
identifier.
2021-12-16 11:40:11 +00:00
bors[bot]
7615df7812 Merge #836
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>
2021-12-16 11:38:58 +00:00
Philip Herron
c81eb14904 BugFix NodeId skew on AST::Patterns
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.
2021-12-16 11:37:40 +00:00
bors[bot]
83a984b1a1 Merge #835
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>
2021-12-16 10:47:11 +00:00
Philip Herron
a688913ac1 Add hir lowering for match-expr 2021-12-16 10:25:07 +00:00
Philip Herron
4dba290c35 Add initial name-resolution for match-expr 2021-12-16 10:25:01 +00:00
bors[bot]
768f926074 Merge #834
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>
2021-12-16 10:23:26 +00:00
Philip Herron
e0588300ad Add enum code generation
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
2021-12-16 10:17:08 +00:00
bors[bot]
3629645386 Merge #832 #833
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>
2021-12-15 23:02:03 +00:00
Philip Herron
91a5d085cb Refactor CallExpr and MethodCallExpr into rust-compile-expr.cc 2021-12-15 22:38:46 +00:00
Philip Herron
40aae6224b Refactor TyTy::ResolveCompile pass to be in its own file
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.
2021-12-15 22:37:10 +00:00
bors[bot]
de9bb86797 Merge #831
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>
2021-12-15 22:32:42 +00:00
Philip Herron
24dd9a6aef BugFix bad range in typechecking of enum ADTTypes
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
```
2021-12-15 22:28:12 +00:00
bors[bot]
310968874d Merge #829 #830
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: #714
Fixes: #715
Fixes: #716
Fixes: #720


Co-authored-by: Nirmal Patel <npate012@gmail.com>
Co-authored-by: David Faust <david.faust@oracle.com>
2021-12-14 11:34:32 +00:00
bors[bot]
88bf6bf78a Merge #828
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>
2021-12-14 11:04:19 +00:00
David Faust
a9a7654d85 Get rid of lambdas within AST::Union
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
2021-12-13 14:45:45 -08:00
David Faust
8c3ad67d19 Get rid of lambdas within AST::StructStruct
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
2021-12-13 14:45:44 -08:00
David Faust
946069f506 Get rid of lambdas within AST::TupleStruct
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
2021-12-13 14:45:44 -08:00
David Faust
e43a784dc8 Get rid of lambdas with AST::ArrayElemsValues
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
2021-12-13 14:34:45 -08:00
Nirmal Patel
f742bead5f Constant folder now returns error_mark_node instead of nullptr
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>
2021-12-11 14:05:06 -05:00
Philip Herron
854281e251 Add script to generate gource
This script tries to isolate our changes to GCC minus the changes to
gcc/config so that we can visualize our development history.
2021-12-10 00:01:46 +00:00
bors[bot]
0024bc2f02 Merge #818
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>
2021-11-26 09:19:08 +00:00
Philip Herron
c7af812802 Support dereference operator overloading
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
2021-11-26 09:14:10 +00:00
bors[bot]
3b8cbff816 Merge #823
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>
2021-11-25 16:41:44 +00:00
bors[bot]
cf913e7f29 Merge #821 #822
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>
2021-11-25 16:12:02 +00:00
bors[bot]
98fb902fb3 Merge #820
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>
2021-11-25 15:28:54 +00:00
bors[bot]
295f0ae166 Merge #817
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>
2021-11-25 15:01:01 +00:00
bors[bot]
bdfe6abe2b Merge #819
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>
2021-11-25 14:35:50 +00:00
Philip Herron
ec23757d36 Add support for generics within operator overloads
This ports over some code from the method-call expr to try and infer the
arguments in the function definition when required.

Addresses #809
2021-11-25 14:11:25 +00:00
Philip Herron
12b7154e90 improve the error handling on operator overload cases
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.
2021-11-25 14:11:10 +00:00
Philip Herron
d0e51dca2d Make TyTy::BaseType::contains_type_parameters non-virtual
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.
2021-11-25 13:37:52 +00:00
Philip Herron
e532893ba4 Always update the type context for monoprhized items except type params
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.
2021-11-25 13:36:27 +00:00
Philip Herron
a2f59f14ce Bug fix mutability checks in can_eq for autoderef
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.
2021-11-25 13:32:49 +00:00
Philip Herron
67f4a371e5 Update legacy mangling of names
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.
2021-11-25 13:27:14 +00:00
Philip Herron
e7e65bbdf3 Allow references to arrays for ArrayIndexExpr accessor's
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
2021-11-24 16:31:49 +00:00
Philip Herron
f967dd2779 Remove bad mutability lint
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
2021-11-24 16:06:55 +00:00
Philip Herron
4924160c27 Stop copying HIR::FunctionParams when during lowering
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.
2021-11-24 15:15:40 +00:00
bors[bot]
717b6da459 Merge #814
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>
2021-11-23 23:09:25 +00:00
Philip Herron
8b36f2b80e Set TREE_ADDRESSABLE when we need to borrow any expression
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
2021-11-23 23:01:04 +00:00
bors[bot]
a41851dfb5 Merge #813
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>
2021-11-23 11:54:25 +00:00
Philip Herron
88995535f6 Support QualifiedPathInType's within the same Trait
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
2021-11-23 11:29:50 +00:00
bors[bot]
a60de84632 Merge #812
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>
2021-11-23 11:29:35 +00:00
Philip Herron
0216a1a9a0 Remove the final hack for associated types
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.
2021-11-22 18:20:34 +00:00
Philip Herron
5a73de5ee9 Make mappings as part of the class 2021-11-22 17:31:20 +00:00
Philip Herron
76ca8b8dff Fix bad datastructure within name resolver
This set to a pair is simply a map and the added complexity here is
unnecessary.
2021-11-22 17:31:19 +00:00
Philip Herron
ddeb211801 Refactor naming of canonical path mappings
These names are poor and are easily conflated with the singleton mappings
which contain all mappings known in this compilation unit.
2021-11-22 17:31:19 +00:00
Philip Herron
a6cae6da51 Fix toplevel crate ribs id's
Toplevel ribs should be the same id of the Crate this allows is to scan
all toplevel ribs simply by knowing the crate number.
2021-11-22 17:31:19 +00:00
bors[bot]
87da9922e6 Merge #800
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>
2021-11-22 09:53:17 +00:00
@mvvsmk
1a03ecbe99 Removed markdown linting errors from README.md and CONTRIBUTING.md
Fixes #487
Signed-off-by: M V V S Manoj Kumar <mvvsmanojkumar@gamil.com>
2021-11-20 16:55:45 +05:30
M V V S Manoj Kumar
73a0903c15 Merge branch 'Rust-GCC:master' into master 2021-11-20 08:01:36 +05:30
bors[bot]
fece068309 Merge #811
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>
2021-11-19 16:14:04 +00:00
Philip Herron
0ecb6ea16b Remove implicit name hack for trait associated types
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
2021-11-18 13:53:47 +00:00
bors[bot]
0995184e26 Merge #810
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>
2021-11-18 00:16:47 +00:00
bors[bot]
63fc39600c Merge #805
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>
2021-11-17 21:22:20 +00:00
Philip Herron
db832831ed Probe for candidates on based on the actual receiver type
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
2021-11-17 19:44:58 +00:00
Philip Herron
e8695eee4f Add missing implict monomorphized types into the context 2021-11-17 17:25:01 +00:00
Philip Herron
649e2ec568 Unify the adjusted self argument to the self parameter on MethodCalls
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
2021-11-17 16:45:50 +00:00
Philip Herron
e584c6f8a7 Generic segments must be appended to the prefix and not override 2021-11-17 16:16:20 +00:00
Philip Herron
2547e60d2f Fix ICE assertion on bad duplicate name
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
2021-11-17 16:16:20 +00:00
David Faust
5c87e61f96 clang-format and minor cleanup 2021-11-16 13:15:56 -08:00
David Faust
01a52df944 Replace Blabel with GCC tree 2021-11-16 13:15:55 -08:00
David Faust
a4e5aee586 Replace Bblock with GCC tree 2021-11-16 13:15:54 -08:00
David Faust
95048daaff Replace Bfunction with GCC tree 2021-11-16 13:12:53 -08:00
David Faust
553e88f1dd Replace Bstatement with GCC tree 2021-11-16 13:10:41 -08:00
David Faust
b52a68d2d8 Replace Bexpression with GCC tree 2021-11-16 13:04:58 -08:00
David Faust
7a751f354a Replace Btype use with GCC tree 2021-11-16 13:02:11 -08:00
David Faust
97c98deec7 rust-backend.h: remove unused function prototypes
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 ()
2021-11-16 13:00:32 -08:00
bors[bot]
5514d9cec5 Merge #801
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: 0f74fe23c6

Fixes #249



Co-authored-by: Philip Herron <philip.herron@embecosm.com>
2021-11-16 15:18:49 +00:00
Philip Herron
6d1333ef46 LazyBooleanExpr does not need a nullptr check 2021-11-16 15:10:48 +00:00
Philip Herron
04a49acfa3 Add negation operator overload support
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
2021-11-16 15:09:53 +00:00
Philip Herron
0f74fe23c6 Refactor operator overloading work to be more reuseable 2021-11-16 14:19:22 +00:00
Philip Herron
a7fb60bb62 Add support compound assignment operator overloads
Fixes #249
2021-11-16 14:19:22 +00:00
Philip Herron
432add899f Revert desugaring of CompoundAssignment into arithmetic operation and assignment 2021-11-16 14:19:22 +00:00
Philip Herron
694cf02512 Fixup verify assigneee to be permissive of PathInExpression 2021-11-16 14:19:05 +00:00
Philip Herron
c47d5cbdee Initial support operator overloading on [lang = "add"]
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
2021-11-16 14:09:23 +00:00
Philip Herron
89e02f52d8 Update path probe with optional filter for specific associated trait
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.
2021-11-16 14:08:19 +00:00
Philip Herron
795d70d7e6 Support parsing LangItems on traits
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.
2021-11-16 14:06:27 +00:00
Philip Herron
df3e0ec232 Add new TypeCheckContextItem to track current context
FIXME
2021-11-16 14:06:11 +00:00
Philip Herron
0f3fc1983d Traits do allow TypeParameters with defaults
Core traits such as the arithmetic operations have generic arguments such
as: pub trait Add<Rhs = Self>

Addresses #249
2021-11-16 14:04:56 +00:00
Philip Herron
fdd69a69f8 Update AttrInput with AttrInputType
This allows us to switch based on the type which can be used for more complex usage of attributes such as lang_item parsing.

Addresses #742
2021-11-16 14:04:03 +00:00
Philip Herron
766f989251 Remove useless comments from HIR::MethodCallExpr 2021-11-16 14:03:58 +00:00
bors[bot]
dcd758595f Merge #803
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>
2021-11-09 22:08:36 +00:00
bors[bot]
328f2d79e5 Merge #802
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>
2021-11-09 21:06:28 +00:00
Marc Poulhiès
2a07016981 Partially disable clang-format in rust-diagnostics.h
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>
2021-11-09 21:14:47 +01:00
Marc Poulhiès
2b84783712 Update CONTRIBUTING.md
Split sentence.

Co-authored-by: CohenArthur <arthur.cohen@epita.fr>
2021-11-09 18:34:19 +01:00
Marc Poulhiès
8cc0140cf6 More help on running clang-format locally
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>
2021-11-09 09:16:47 +01:00
CohenArthur
07fee63db7 Merge pull request #792 from npate012/defid_to_struct
Change DefId type from uint64_t to be struct
2021-11-08 22:44:02 +01:00
Nirmal Patel
a7c31383de Changed DefId type from uint64_t to be struct
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>
2021-11-07 11:13:29 -05:00
bors[bot]
d11a50eca3 Merge #798
798: Add missing const folding r=philberty a=philberty

Add some more missing constant-folding operations

Co-authored-by: Philip Herron <philip.herron@embecosm.com>
2021-11-07 11:58:32 +00:00
bors[bot]
57b10aef62 Merge #795
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>
2021-11-07 11:21:04 +00:00
@mvvsmk
9c4e3db778 Added Remark.yml and .remarkrc
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>
2021-11-06 20:15:06 +05:30
bors[bot]
57c31311b3 Merge #796
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>
2021-11-05 17:42:34 +00:00
Philip Herron
5074f89f4f Remove clang-format from bors 2021-11-05 17:36:50 +00:00
Thomas Schwinge
6a1e79714c Tag 'rust_fatal_error' as 'noreturn'
... like GCC's underlying 'fatal_error'.

By definition, we cannot continue, upon having run into a fatal error.
2021-11-05 16:35:01 +00:00
Thomas Schwinge
864fd885fe Turn 'rust_error_at' plus always-failing 'rust_assert' into 'rust_internal_error_at'
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.
2021-11-05 16:34:22 +00:00
Thomas Schwinge
228240f321 Add 'rust_internal_error_at'
... corresponding to GCC's 'internal_error'.
2021-11-05 16:34:22 +00:00
Philip Herron
bc858da45c Add missing const-folding for (expr) 2021-11-05 14:17:30 +00:00
Philip Herron
b22ec92160 Const fold ref,pointer,borrow+deref 2021-11-05 14:05:22 +00:00
Philip Herron
17dc14cb4b Support forward declared items within blocks
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
2021-11-05 12:45:32 +00:00
Philip Herron
d2f92e6a73 Add is_item helper to AST and HIR
BlockExpr can contain Items and Stmts this allows us to differentiate
between them on the Stmt level.
2021-11-05 12:31:59 +00:00
bors[bot]
e73922ef9f Merge #794
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>
2021-11-05 11:38:05 +00:00
Philip Herron
f4c200fcfe Support computing the addresses of the object safe items in dyn objects
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
2021-11-05 11:33:04 +00:00
Thomas Schwinge
c936060b86 Running clang-format locally [#242]
Apparently everyone but me knows how to do that; I'm now documenting it for my
own future use.
2021-11-05 12:14:18 +01:00
Philip Herron
92a24fc3ae Enforce the is_concrete inferface to start cleaning up the needs_substitution helpers 2021-11-05 11:12:51 +00:00
Philip Herron
b7520628b4 Add missing generic arguments to type-bound-predicate on trait-objects 2021-11-05 11:12:51 +00:00
Philip Herron
d308ce83b9 Add generic-arguments to predicate as_string 2021-11-05 11:12:51 +00:00
Philip Herron
52ef760176 Remove duplicate accessors which can be const 2021-11-05 11:12:50 +00:00
Philip Herron
dfba45d0cd When we are resolving TypePaths default the result to ErrorType 2021-11-05 11:12:50 +00:00
Philip Herron
57acd1e208 Fix nullptr as the result is not setup in this case 2021-11-05 11:12:50 +00:00
Philip Herron
d9f5eddc5a Make self const when compiling trait-items 2021-11-05 11:12:50 +00:00
Philip Herron
c6dc53f9e2 Add a recursion-limit when resolving Parameter Types
This limit is likely way too low but its ok for now to get decent
backtraces for the test-cases we are working with right now.
2021-11-05 11:12:15 +00:00
Philip Herron
41d0e2fa96 Add missing bound to impl-type Self 2021-11-04 13:35:07 +00:00
Philip Herron
b3e884c3e9 Add ImplItemTypes enum to switch between HIR::ImplItem types 2021-11-04 12:12:15 +00:00
bors[bot]
8e992e371b Merge #785
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>
2021-11-03 18:00:24 +00:00
bors[bot]
674221a3b2 Merge #791
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>
2021-11-03 15:54:51 +00:00
Connor Lane Smith
c8ee62ed45 Replace TupleType::iterate_fields with get_fields
Fixes #735

Signed-off-by: Connor Lane Smith <cls@lubutu.com>
2021-11-03 14:08:22 +00:00
Philip Herron
3dccdb1d6c Desugar AST::TraitObjectTypeOneBound
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
2021-11-03 13:59:44 +00:00
Ben Boeckel
1657ee53d5 rust: track inline module scopes for module file resolution
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>
2021-11-03 07:09:01 -04:00
bors[bot]
5f0df4812c Merge #781
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>
2021-11-02 13:54:14 +00:00
bors[bot]
09af9b16b4 Merge #788
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>
2021-11-02 11:55:44 +00:00
Philip Herron
fc5f8d7463 Default type checking on CallExpr's to TyTy::ErrorType
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.
2021-11-02 11:48:06 +00:00
Philip Herron
e3defa10bc Support Typechecking of ADT's of enums
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
2021-11-02 11:26:23 +00:00
Ben Boeckel
2fc460a644 gccrs: add the -frust-crate= option to set the crate name
Signed-off-by: Ben Boeckel <mathstuf@gmail.com>
2021-11-02 07:09:54 -04:00
Philip Herron
5e8043380b Refactor struct-expr typechecking into its own impl file 2021-11-02 10:10:58 +00:00
bors[bot]
9b46e47908 Merge #787
787: gha: save `check-rust` results as artifacts r=philberty a=mathstuf

They will stick around for 90 days (as per GitHub default limits).

     https://docs.github.com/en/actions/advanced-guides/storing-workflow-data-as-artifacts

Signed-off-by: Ben Boeckel <mathstuf@gmail.com>

Fixes: #634 


Co-authored-by: Ben Boeckel <mathstuf@gmail.com>
2021-11-02 09:12:12 +00:00
Ben Boeckel
e0d9dde2f2 gha: save check-rust results as artifacts
They will stick around for 90 days (as per GitHub default limits).

     https://docs.github.com/en/actions/advanced-guides/storing-workflow-data-as-artifacts

Signed-off-by: Ben Boeckel <mathstuf@gmail.com>
2021-11-01 19:44:23 -04:00
Philip Herron
e8d57d424b Add missing ID to variant ids 2021-11-01 15:48:54 +00:00
Philip Herron
56e4a9db1e Add TypePath resolution for enum ctor
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
2021-11-01 13:12:48 +00:00
Philip Herron
919a5a4c5a Get rid of bad gcc_unreachable 2021-11-01 13:12:48 +00:00
Mark Wielaard
d18672f220 Add type-resolution for enum items
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
2021-11-01 13:12:48 +00:00
Philip Herron
faa1a005e9 Refactor ADTType to consist of multiple variants
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
2021-11-01 13:12:47 +00:00
Mark Wielaard
82f3dd40d2 Extract reuseable function to handle substitutions for struct fields 2021-11-01 13:12:47 +00:00
Mark Wielaard
6e69ab6d08 Get rid of lambda get_fields in struct 2021-11-01 13:12:47 +00:00
Mark Wielaard
3c02a29f57 Add missing accessors for enum items 2021-11-01 13:12:47 +00:00
bors[bot]
1be610afab Merge #783
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>
2021-11-01 11:52:51 +00:00
Kadoi Takemaru
66832f312a Get rid of lambda within AST::TypePath and provide a method to return a reference
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>
2021-11-01 20:05:18 +09:00
bors[bot]
ca0b06f86f Merge #780
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>
2021-10-30 12:30:50 +00:00
bors[bot]
a9daecd2a3 Merge #778
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>
2021-10-30 12:02:17 +00:00
Thomas Schwinge
f569984bb8 No side effects in 'assert' expressions
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?
2021-10-30 00:11:25 +02:00
Nirmal Patel
a66dd96413 Add location info in AST::TypeBoundWhereClauseItem and HIR::TypeBoundWhereClauseItem
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>
2021-10-29 14:27:50 -04:00
bors[bot]
cba61d8dcb Merge #774
774: Removed lambda in iterate_params within CallExpr and MethodCallExpr r=tschwinge a=npate012

Signed-off-by: Nirmal Patel <npate012@gmail.com>

Removed iterate_params from AST::CallExpr and AST::MethodCallExpr.

Fixes #722 #723 


Co-authored-by: Nirmal Patel <npate012@gmail.com>
2021-10-28 18:46:18 +00:00
Nirmal Patel
08b83163db Remove iterate_params from AST::CallExpr and AST::MethodCallExpr
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>
2021-10-28 13:58:03 -04:00
bors[bot]
a2ce3ef6b0 Merge #775
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>
2021-10-28 10:13:12 +00:00
Philip Herron
0114e3e5b3 Add constant folding to ArrayIndexExpr
This ensures that constexpr is enforced for array-index-exprs resulting in
gimple like this:

```rust
fn main() {
    const A: [i32; 3] = [1, 2, 3];
    const B: i32 = A[1];
    const C: usize = 42;
    const D: i32 = 7;

    let _a = C;
    let _b: [i32; C] = [0; C];
    let _c = B + D;
}
```

```c
void main ()
{
  const usize _a;
  i32 _b[42];
  const i32 _c;

  try
    {
      _a = 42;
      _b = {};
      _1 = 2;
      _c = _1 + 7;
    }
  finally
    {
      _b = {CLOBBER};
    }
}
```
2021-10-28 11:07:13 +01:00
Philip Herron
657a973533 Add support for constants within blocks
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
2021-10-28 10:57:37 +01:00
bors[bot]
e28c43f2f4 Merge #771
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>
2021-10-27 15:12:05 +00:00
Philip Herron
7604b6430c Fix parser error for lifetime arguments
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
2021-10-27 16:08:20 +01:00
Philip Herron
4c873251e7 Add support for higher ranked trait bounds
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
2021-10-27 16:05:59 +01:00
Philip Herron
1b9ddc7240 TyTy add bounds in debug string 2021-10-27 10:27:54 +01:00
Philip Herron
1a8479839e Remove assertion for has_where_clause
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.
2021-10-27 10:26:32 +01:00
Philip Herron
1a97460323 Add HIR lowering for where clause items 2021-10-27 10:18:33 +01:00
Philip Herron
b01e62c136 Add WhereClauseItem::ItemType specifier to differentiate between items 2021-10-27 10:18:33 +01:00
Philip Herron
7dc21da4d0 Add name resolution to higher ranked trait bounds 2021-10-27 10:18:33 +01:00
Philip Herron
be717fca2f Add missing node mappings to HIR::WhereClauseItems 2021-10-26 15:10:56 +01:00
Philip Herron
b0e9cea1ae Add missing NodeId to where clause items 2021-10-26 15:05:59 +01:00
bors[bot]
161a690d21 Merge #770
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>
2021-10-26 09:25:44 +00:00
bors[bot]
d4bfbb0b06 Merge #772
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>
2021-10-26 08:58:39 +00:00
Nirmal Patel
10122cbf21 Converted FnType preprocessor defines into constants
Signed-off-by: Nirmal Patel <npate012@gmail.com>
2021-10-25 21:55:04 -04:00
Ben Boeckel
fbc7f0e51b TraitImpl: track the polarity of the impl
The internal representation now tracks whether a trait impl is a
positive or negative impl.

Signed-off-by: Ben Boeckel <mathstuf@gmail.com>
2021-10-25 13:05:42 -04:00
bors[bot]
78ed354283 Merge #769
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>
2021-10-25 17:01:37 +00:00
Ben Boeckel
7661713e07 LifetimeWhereClauseItem: store the location of the item
Signed-off-by: Ben Boeckel <mathstuf@gmail.com>
2021-10-25 12:45:25 -04:00
bors[bot]
d2b12ea889 Merge #768
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>
2021-10-25 15:22:35 +00:00
Ben Boeckel
5d65ef58a9 CompileExpr: fix copy pasta error message
Also downgrade from a fatal error to a compilation error.

Signed-off-by: Ben Boeckel <mathstuf@gmail.com>
2021-10-25 09:40:23 -04:00
bors[bot]
aefdb4d036 Merge #767
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>
2021-10-25 13:26:21 +00:00
Ben Boeckel
1d3a36276a gccrs: StructExprStructFields: remove iterate method
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>
2021-10-25 08:14:55 -04:00
bors[bot]
868d3125d3 Merge #764
764: Update GCC/Rust files per 'contrib/update-copyright.py --this-year' r=philberty a=tschwinge

As noted by `@dkm/@CohenArthur` in <https://github.com/Rust-GCC/gccrs/pull/747#issuecomment-945581716>/<https://github.com/Rust-GCC/gccrs/issues/747#issuecomment-945585735>.


Co-authored-by: Thomas Schwinge <thomas@codesourcery.com>
2021-10-22 16:46:54 +00:00
bors[bot]
a51180ca2d Merge #762
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>
2021-10-22 16:07:18 +00:00
bors[bot]
94b1da7d97 Merge #763
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>
2021-10-22 15:42:12 +00:00
Thomas Schwinge
f4b4676d0a Update GCC/Rust files per 'contrib/update-copyright.py --this-year' 2021-10-22 16:59:16 +02:00
Thomas Schwinge
ddf02f1750 Fix copyright/licensing information in 'gcc/rust/rust-linemap.h'
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.
2021-10-22 16:48:45 +02:00
Philip Herron
fb1d2a2ef2 Cleanup IR symbol names in gimple
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
2021-10-22 13:45:21 +01:00
Philip Herron
e0b43ccd05 Add missing coercion site code to MethodCallExpr's
Arguments to methods are coercion sites and may have implicit conversions
to be performed this adds this missing code for this case.

Fixes #755
2021-10-22 13:32:20 +01:00
bors[bot]
8e6c5a32b6 Merge #752
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>
2021-10-22 11:08:44 +00:00
Philip Herron
92a3196977 Support generic arguments on TypeBounds
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
2021-10-22 11:48:43 +01:00
Philip Herron
f3bd3f0dd8 Decouple the loop from processing a potential candidate in a path
Code cleanup to extract the body out of the loop to make the code more
testable and reuseable.
2021-10-22 11:48:42 +01:00
Philip Herron
b3b37e2c5c Extract const helper method is_receiver_generic for path probes. 2021-10-22 11:48:42 +01:00
Philip Herron
243e5d800d Ensure autoderef for generic recivers in method calls
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
2021-10-22 11:48:42 +01:00
Philip Herron
fe77d2d574 Fix ICE when trying to resolve associated type from type bounds
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
2021-10-22 11:48:42 +01:00
bors[bot]
df61b8f0ee Merge #761
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>
2021-10-22 10:44:54 +00:00
Philip Herron
4eb4684eba Squash unused parameter warning.
Fixes #750
2021-10-22 11:22:21 +01:00
bors[bot]
86ec0383d4 Merge #757 #758 #759 #760
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>
2021-10-22 10:15:12 +00:00
bors[bot]
2cd9855d91 Merge #756
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>
2021-10-22 09:51:12 +00:00
Philip Herron
ef70f0310a Add FIXME comment for inheriting bounds 2021-10-22 10:49:37 +01:00
Philip Herron
7d988344f7 Cleanup interfaces for associated impl mappings
This changes the lookups to return boolean if they are found rather than
default UNKNOWN_HIRID which is more ambigious.
2021-10-22 10:49:29 +01:00
Philip Herron
e9b10b3d29 Error handling is done via the TyTy::ErrorType instead of nullptr's 2021-10-22 10:49:22 +01:00
Philip Herron
3f67bb999b Refactor fill_param_ty into cc file
This also changes the signiture to take a fat pointer instead of raw
pointer for the substitution.
2021-10-22 10:49:14 +01:00
Philip Herron
d17b799df7 Remove second lookup for query compiled functions
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
2021-10-22 10:40:20 +01:00
Philip Herron
b538aa9105 The number of required substituions is offset from the already substituted
When doing HIR::GenericArgs substitutions we must offset from the already
partially substituted arguments.
2021-10-22 10:38:17 +01:00
Philip Herron
d755769bd1 BugFix: TypePath resolution to handle associated types
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
2021-10-22 10:34:31 +01:00
Philip Herron
a80bcfc5b1 Remove bad prefix from RelativeTypePath resolution
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
2021-10-22 10:34:23 +01:00
Philip Herron
a1b0df0241 Constify BaseType::get_root since this should not change ownership 2021-10-22 10:13:06 +01:00
Philip Herron
5f19fb535c Constify SubstitutionArgumentMappings::solve_mappings_from_receiver_for_self 2021-10-22 10:13:06 +01:00
Philip Herron
e59ec1a592 Constify autoderef ajustments expected type field 2021-10-22 10:13:06 +01:00
Philip Herron
9cdaff9f5a Constify GetUsedSubstArgs
This mapper class does not need mutability and can easily be made const
enforcing ownership.
2021-10-22 10:13:06 +01:00
Philip Herron
3eea0076f2 Constify SubstitutionArg field SubstitutionParamMapping
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.
2021-10-22 10:13:06 +01:00
Philip Herron
ff5c248140 Constify the Backend resolve compile interface
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.
2021-10-22 10:13:05 +01:00
bors[bot]
9edda15723 Merge #754
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>
2021-10-22 09:05:50 +00:00
Nirmal Patel
4d19ffcd4a Fixed formatting issues
Signed-off-by: Nirmal Patel <npate012@gmail.com>
2021-10-21 19:45:08 -04:00
Nirmal Patel
8d8ab48b47 Implement unsafety enum and replaced boolean variable has_unsafe with a variable of unsafety enum type
Signed-off-by: Nirmal Patel <npate012@gmail.com>
2021-10-20 21:14:00 -04:00
bors[bot]
649e3e074b Merge #747
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>
2021-10-18 09:24:56 +00:00
CohenArthur
fd9d37c68c util: Add rust-base62 implementation from rustc 2021-10-18 11:21:36 +02:00
bors[bot]
a1a4506410 Merge #748
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>
2021-10-18 08:53:50 +00:00
Rodrigo Valle
bb32b21a21 Const fold ArrayElemsCopied
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>
2021-10-17 20:06:02 -07:00
CohenArthur
35f6d0ffa6 v0-mangling: Add base functions for mangling scheme 2021-10-17 18:05:46 +02:00
CohenArthur
a2484d5101 v0-mangling: Add base for base62 encoding 2021-10-17 12:00:12 +02:00
bors[bot]
ec1e7c2868 Merge #725
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>
2021-10-16 19:28:45 +00:00
Rodrigo Valle
14a0f2ce31 Add array constant folding
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>
2021-10-15 19:54:57 -07:00
bors[bot]
b5e389241d Merge #740
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>
2021-10-15 14:50:15 +00:00
Philip Herron
b7bb6a9832 Add boiler plate for TyTy::ClosureType
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
2021-10-14 12:32:43 +01:00
bors[bot]
eb29257b21 Merge #730
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>
2021-10-14 09:31:20 +00:00
bors[bot]
e5a7ee4856 Merge #738
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>
2021-10-14 09:08:10 +00:00
Thomas Schwinge
36088fa7df Update 'README.md' for DCO
... using the same wording as in 'CONTRIBUTING.md'.
2021-10-14 10:39:18 +02:00
Thomas Schwinge
5d9d3e32df Some polishing of DCO wording
<https://github.com/Rust-GCC/gccrs/pull/730/files#r728027852>.
2021-10-14 10:35:24 +02:00
Thomas Schwinge
8545a93929 Align DCO wording in '.github/PULL_REQUEST_TEMPLATE.md'
... to that used in 'CONTRIBUTING.md'.
2021-10-14 10:32:55 +02:00
David Faust
c0669ceb14 Refactor HIR to use new Mutability enum
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
2021-10-13 13:49:25 -07:00
Philip Herron
535a824bf7 GCC allows for the DCO sign-off.
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>
2021-10-13 14:28:23 +01:00
bors[bot]
3057d98a4e Merge #728
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>
2021-10-13 11:34:46 +00:00
wan-nyan-wan
61db846ac9 remove AST::BlockExpr lambda and add get_statements
Signed-off-by: Kazuki Hanai <distributed.system.love@gmail.com>
2021-10-13 19:47:00 +09:00
bors[bot]
7a341772dc Merge #710 #727
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: #703 
Fixes: #704 
Fixes: #705 
Fixes: #706 
Fixes: #707

Co-authored-by: Philip Herron <philip.herron@embecosm.com>
Co-authored-by: David Faust <david.faust@oracle.com>
2021-10-13 09:31:52 +00:00
bors[bot]
6355d05a65 Merge #729
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>
2021-10-13 09:07:09 +00:00
David Faust
a2c76651c9 Refactor TyTy with new Mutability enum
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
2021-10-12 10:51:56 -07:00
David Faust
85338a7f1c Remove lambda iterators in various HIR classes
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
2021-10-11 10:46:40 -07:00
Philip Herron
f6a04f38d5 Ensure we emit the code for coercion sites on CallExpr and MethodCallExpr
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
2021-10-05 15:09:09 +01:00
Philip Herron
591b43e42e Coercion site type checking in CallExprs must hold onto the argument type
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
2021-10-05 14:43:24 +01:00
Philip Herron
6cd07341b1 Remove lambda iterator from HIR::MethodCallExpr
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
2021-10-05 14:30:58 +01:00
Philip Herron
579d76f771 Remove lambda iterator from HIR::CallExpr
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
2021-10-05 14:19:05 +01:00
bors[bot]
99c28309d3 Merge #698 #701
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>
2021-10-04 09:26:20 +00:00
bors[bot]
e0b9673a7c Merge #699
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>
2021-10-04 08:58:18 +00:00
Mark Wielaard
23475a8131 Fix lexer to not produce bad unicode escape values
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.
2021-10-02 23:03:54 +02:00
Mark Wielaard
31b999c5c7 Remove raw string and raw byte string references from ast and hir
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.
2021-09-30 12:52:30 +01:00
Philip Herron
65d06d56e8 Implement 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>
2021-09-30 11:38:52 +01:00
bors[bot]
fdcad086e1 Merge #695
695: Fix raw byte string parsing of zero and out of range bytes r=philberty a=CohenArthur

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.

Patch: https://code.wildebeest.org/git/user/mjw/gccrs/commit/?h=parse-raw-byte-string
Email: https://gcc.gnu.org/pipermail/gcc-rust/2021-September/000227.html

Co-authored-by: Mark Wielaard <mark@klomp.org>
2021-09-30 09:31:29 +00:00
Mark Wielaard
e6e1cc117e Fix raw byte string parsing of zero and out of range bytes
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.
2021-09-29 22:03:34 +02:00
Thomas Schwinge
28f527c959 Merge commit '2961ac45b9e19523958757e607d11c5893d6368b' [#247] 2021-09-24 18:20:21 +02:00
Philip Herron
1eb4d0d3ba Try again for docker image build workflow 2021-09-24 14:51:29 +01:00
Philip Herron
faafe0fb11 Update docker build workflow 2021-09-24 14:47:05 +01:00
bors[bot]
8a0dd2bd98 Merge #689
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>
2021-09-24 08:29:43 +00:00
bors[bot]
f3da612f98 Merge #690
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>
2021-09-24 08:06:51 +00:00
Thomas Schwinge
4c386aaaa7 A bit of 'RichLocation' C++ tuning [#247], [#97, #374]
... 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".
2021-09-24 08:35:49 +02:00
Thomas Schwinge
ac2d117861 x86: Instead of 'TARGET_ISA_[...]', 'TARGET_ISA2_[...]', use 'TARGET_[...]' [#247]
... in preparation for a merge from GCC upstream, where the former disappear.
2021-09-23 23:20:57 +02:00
bors[bot]
4abf34c2b6 Merge #688
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>
2021-09-23 12:25:07 +00:00
Mark Wielaard
7a92e0ca3c Remove warnings from v0_mangle functions in rust-mangle.cc
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.
2021-09-23 12:55:45 +01:00
bors[bot]
75be042627 Merge #687
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: #336 
Fixes: #343, #344


Co-authored-by: Mark Wielaard <mark@klomp.org>
2021-09-23 11:39:06 +00:00
Mark Wielaard
d68a9eaceb Fix byte char and byte string lexing code
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.
2021-09-22 00:44:03 +02:00
bors[bot]
98359f20cd Merge #685
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>
2021-09-19 21:13:36 +00:00
CohenArthur
6c1a482c9b v0-mangling: Add type prefixing for simple types 2021-09-18 10:29:06 +02:00
bors[bot]
de43a0ac6d Merge #684
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>
2021-09-17 21:35:13 +00:00
Philip Herron
fabaf7d6ca Initial Dynamic dispatch support
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
2021-09-17 22:29:02 +01:00
Philip Herron
a6e15ff5f0 Add method resolution to Dynamic objects
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
2021-09-17 17:51:23 +01:00
Philip Herron
c674e168eb Add object safety checks for dynamic objects
You cannot create dynamic objects that contain non object safe trait items.
This adds checks to ensure that all items are object safe so code
generation does not need to care.

see: https://doc.rust-lang.org/reference/items/traits.html#object-safety

Addresses: #197
2021-09-17 17:41:01 +01:00
Philip Herron
aa019b251e Default to TyTy::Error node on TypePath resolution failure
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.
2021-09-17 17:35:09 +01:00
Philip Herron
d9a0a5f864 Allow for coercion of structures over to dynamic objects in type system
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
2021-09-17 16:41:25 +01:00
Philip Herron
d144eea862 Type coercions are recursive
Reference types are covariants like arrays or pointers and thus this needs
to be recurisve to support all coercions possible.

Addresses: #197
2021-09-17 15:59:31 +01:00
Philip Herron
26fe2f57bc remove some debug 2021-09-17 15:46:43 +01:00
Philip Herron
135807db03 When calling functions the arguments are a coercion site
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.
2021-09-17 15:46:43 +01:00
Philip Herron
e29a8a4172 Cleanup error handling for CallExpr
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
2021-09-17 15:46:42 +01:00
Philip Herron
ecb777cc8d Add building blocks for Dynamic object types
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
2021-09-17 15:46:42 +01:00
bors[bot]
384cc64dab Merge #680
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>
2021-09-15 18:09:54 +00:00
Philip Herron
b3d5577b59 Add HIR Lowering for TraitObjectTypeOneBound
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
2021-09-15 18:14:02 +01:00
Philip Herron
57ebfd300b Add initial name-resolution for dyn trait objects
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
2021-09-15 18:14:02 +01:00
bors[bot]
887598b92f Merge #679
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>
2021-09-15 15:29:42 +00:00
Philip Herron
04549bf8c3 Fix bug when calling method from generic reciever type-bound
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
2021-09-15 16:27:21 +01:00
bors[bot]
af472f5931 Merge #674
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>
2021-09-15 11:13:27 +00:00
Philip Herron
b74d42f43d Add test case to close out generics bug
This was fixed during the traits milestone likely around: 58637abaea

Fixes #368
2021-09-14 17:42:10 +01:00
bors[bot]
4493f1c927 Merge #673
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>
2021-09-14 15:22:37 +00:00
bors[bot]
c8ffaa101c Merge #672
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>
2021-09-14 15:00:47 +00:00
Philip Herron
9b95c50829 Allow GCC to decide and perofmr inline optimizations
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.
2021-09-14 15:36:44 +01:00
Philip Herron
002313b343 Initial autoderef support for method calls
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
2021-09-14 13:23:56 +01:00
bors[bot]
c644ee4c43 Merge #671
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>
2021-09-13 16:12:45 +00:00
Philip Herron
9464066111 Support indirection for struct and tuple field access
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
2021-09-13 16:33:58 +01:00
bors[bot]
e3b7eb5884 Merge #669
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>
2021-09-10 14:44:42 +00:00
Philip Herron
0c409fcf56 Fix bug with monomorphizing of trait items
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
2021-09-10 15:31:10 +01:00
bors[bot]
2bf19c1b20 Merge #666
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>
2021-09-10 14:21:43 +00:00
bors[bot]
c0254d7efe Merge #661 #663
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>
2021-09-10 13:53:54 +00:00
bors[bot]
d52030df14 Merge #664
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>
2021-09-10 13:30:14 +00:00
Philip Herron
a1c87bfea6 Add initial support to specify Super Traits
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 { }
2021-09-10 13:47:51 +01:00
Philip Herron
e68a772a4a Make override context permissive when the TypeParam cannot resolve
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.
2021-09-10 13:38:18 +01:00
Philip Herron
454b78dd04 Add getter for Trait TypeBounds 2021-09-10 12:18:54 +01:00
Philip Herron
ba31a24ddc Fix formatting in HIR::Trait 2021-09-10 12:18:54 +01:00
CohenArthur
d5b259a3fd modules: Fix usage of path attributes and early returns
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)
2021-09-10 10:53:16 +02:00
CohenArthur
0de1b5646c modules: Move test case from compile/ to execute/
Co-authored-by: Thomas Schwinge <thomas@schwinge.name>
2021-09-10 09:49:28 +02:00
bors[bot]
e93393d007 Merge #662
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>
2021-09-09 16:11:53 +00:00
Philip Herron
0f85a94213 Add HIR lowering for Trait Bounds
Super trait bounds need to be lowered to HIR.
2021-09-09 16:30:07 +01:00
Philip Herron
fefc0b3ffb Add name resolution for Trait bounds
Trait bounds signify super-traits this adds name resolution for them.
2021-09-09 16:29:30 +01:00
Philip Herron
49c9a88b3e type-bounds wip 2021-09-09 15:43:53 +01:00
Philip Herron
995bc1c983 Add support for choosing stdcall fastcall and cdecl in the extern options
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.
2021-09-09 15:25:24 +01:00
bors[bot]
55f60bd6fe Merge #659
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>
2021-09-09 13:45:33 +00:00
bors[bot]
38f2795947 Merge #639
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>
2021-09-09 13:22:33 +00:00
CohenArthur
8cd6306905 module: Rename get_filename() -> process_file_path() 2021-09-09 14:48:22 +02:00
Thomas Schwinge
4faa7d7765 Turn 'rust/execute/torture/sinf32.rs', 'rust/execute/torture/sqrtf32.rs' into 'rust/compile/torture/intrinsics-1.rs'
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'.
2021-09-09 14:17:57 +02:00
Thomas Schwinge
e17824d3c3 Merge commit 'bca1debe33bf477df850db5979e4206627b3790b' into HEAD 2021-09-09 14:17:41 +02:00
bors[bot]
4c4241b4c8 Merge #660
660: Support '-fdump-tree-original' before 'cgraph_node::finalize_function' r=tschwinge a=tschwinge



Co-authored-by: Thomas Schwinge <thomas@codesourcery.com>
2021-09-09 12:16:26 +00:00
CohenArthur
5a6341a623 module: Add two test cases for external modules 2021-09-09 13:44:44 +02:00
Thomas Schwinge
bca1debe33 Support '-fdump-tree-original' before 'cgraph_node::finalize_function' 2021-09-09 13:26:41 +02:00
Philip Herron
a8fb0fd650 Add builting block for simple intrinsics
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.
2021-09-09 09:54:09 +01:00
Philip Herron
782cbcdee4 Keep track of the ABI in function types
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.
2021-09-08 15:01:38 +01:00
bors[bot]
52fb10b1e0 Merge #656
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>
2021-09-08 12:23:49 +00:00
bors[bot]
8a9271e192 Merge #657
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>
2021-09-06 16:52:46 +00:00
CohenArthur
6aff3e33a0 module: Load items if module is unloaded and not marked for strip 2021-09-06 16:25:13 +02:00
CohenArthur
2fe5d6c32a module: Add load_items() function 2021-09-06 16:18:34 +02:00
CohenArthur
b6f69bf136 parser: Expose get_errors() function 2021-09-06 16:18:23 +02:00
CohenArthur
37f3b02bf8 mangling: Use Enum(frust_mangling) for option instead of string
Co-authored-by: Marc Poulhies <dkm@kataplop.net>
2021-09-06 12:07:50 +02:00
Mark Wielaard
eaf5bc5c38 Add EnumItem HIR lowering
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.
2021-09-06 11:07:35 +01:00
Mark Wielaard
a3ac857349 Resolve Enums and EnumItems
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.
2021-09-06 10:31:43 +01:00
Mark Wielaard
2bbe1af01d Parse optional visibility for enum item
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.
2021-09-06 10:31:35 +01:00
CohenArthur
04ea1955ee mangling: Add option to choose mangling version 2021-09-05 20:52:55 +02:00
CohenArthur
9150707650 name_mangling: Add Mangler class with multiple versions 2021-09-05 17:21:40 +02:00
bors[bot]
5062389999 Merge #655
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.html

Fixes #434 

Co-authored-by: Philip Herron <philip.herron@embecosm.com>
2021-09-05 00:14:00 +00:00
Philip Herron
0798add3d3 Support Generic Traits in qualified paths
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.
2021-09-05 00:42:24 +01:00
Philip Herron
07b354c31d Fix name resolution for generic trait references
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.
2021-09-05 00:17:20 +01:00
Philip Herron
9c56ecf32c Add helpers to as clause of QualifiedPaths to get the generic args
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.
2021-09-05 00:13:25 +01:00
Philip Herron
3438ea39e3 Ensure the implicit Self is first in the generic arguments
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.
2021-09-05 00:11:22 +01:00
bors[bot]
c33c6f3676 Merge #654
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>
2021-09-01 10:37:18 +00:00
Mark Wielaard
3b5c0f65ef Remove Enumeration Expression, EnumExpr, classes
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.
2021-09-01 02:19:25 +02:00
Mark Wielaard
c998198c66 StructExprUnit doesn't really exist
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.
2021-08-31 22:17:31 +02:00
Mark Wielaard
34969c14be StructExprTuple doesn't really exist
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.
2021-08-31 21:51:14 +02:00
Philip Herron
58637abaea Add type resolution for qualified-type-paths
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.
2021-08-31 13:31:58 +01:00
Philip Herron
5e7108c358 Placeholder is not a unit-type
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.
2021-08-31 12:25:14 +01:00
Philip Herron
bd90c95ac7 Add HIR lowering for QualifiedPathInType 2021-08-31 12:24:33 +01:00
Philip Herron
2ab6f9ee9f Add name resolution for QualifiedPathInType
Qualified path types allow for TypePaths qualified with a paticular
associated impl and type;
2021-08-31 12:22:18 +01:00
Philip Herron
0e3030707b Add iterate helper for TypePaths 2021-08-31 12:22:06 +01:00
bors[bot]
82e1061579 Merge #651
651: Qualified paths have a mandatory initial segment r=philberty a=philberty

see https://doc.rust-lang.org/reference/paths.html#qualified-paths

The initial segment is mandatory this changes the AST to reflect this
it simplifies error handling down the line.

Co-authored-by: Philip Herron <philip.herron@embecosm.com>
2021-08-31 10:46:24 +00:00
bors[bot]
de02471870 Merge #652
652: A few more location patches  r=philberty a=dkm

From Mark Wieelard: https://gcc.gnu.org/pipermail/gcc-rust/2021-August/000160.html

> Here are a couple of little patches to improve or simplify locations a
> bit

Co-authored-by: Mark Wielaard <mark@klomp.org>
2021-08-30 10:35:50 +00:00
Mark Wielaard
69728c5955 Remove GetLocusFromImplItem visitor
Simply use get_locus () on the ImplItem.
Both the generics7.rs and generics8.rs testcase still pass.
2021-08-29 02:01:59 +02:00
Mark Wielaard
f16e3af9ad Replace HIRItem::get_impl_locus with HirItem::get_locus
HIRItem::get_impl_locus wasn't used and all subclasses already
implement get_locus.
2021-08-29 02:01:59 +02:00
Mark Wielaard
d12be0a643 Use location when lowering TupleField 2021-08-29 02:01:58 +02:00
Philip Herron
46e8bf357c Qualified paths have a mandatory initial segment
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.
2021-08-27 18:17:30 +01:00
bors[bot]
58f2f624ef Merge #650
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>
2021-08-27 15:26:06 +00:00
Philip Herron
1fc2a7fe7e Stop shadowing of hir mappings with substitution mappings
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.
2021-08-27 14:17:34 +01:00
bors[bot]
6b42381685 Merge #648 #649
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>
2021-08-27 11:03:07 +00:00
bors[bot]
a5a0287f52 Merge #646
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>
2021-08-27 10:37:29 +00:00
Mark Wielaard
f9e5e53039 Get rid of get_locus_slow
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.
2021-08-26 21:03:20 +02:00
Philip Herron
8c6a2f1dbf Fix issue with mangled name on function items with substitutions
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
2021-08-26 10:00:48 +01:00
CohenArthur
602f5e90c2 raii-file: Fix filename member initialization 2021-08-25 14:18:01 +02:00
CohenArthur
cc1a2c8699 expand: Add debug line for showing the path of an external module 2021-08-25 14:18:01 +02:00
CohenArthur
c3f146d98d module: Allow external module path to come from #[path] attribute 2021-08-25 14:18:01 +02:00
CohenArthur
5b509a775f modules: Add test case for #[path] modules 2021-08-25 14:18:00 +02:00
bors[bot]
40042ce11f Merge #642
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>
2021-08-22 20:09:47 +00:00
Mark Wielaard
5a73179005 Reject duplicate field names in structs and unions.
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.
2021-08-22 16:53:25 +02:00
bors[bot]
b3bb2e194c Merge #641
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>
2021-08-22 14:48:08 +00:00
Philip Herron
2d681bdeda Ignore impl trait blocks in overlap pass
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.
2021-08-22 15:47:20 +01:00
bors[bot]
ac3be517de Merge #640
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>
2021-08-22 13:59:00 +00:00
Philip Herron
5a0e34b74a Qualified paths can be fully resolved sometimes
This means we need to be permissive to overload the resolved name to
something other than the trait item if we can.
2021-08-22 14:56:27 +01:00
Philip Herron
db24e859d8 Path resolution is done in two phases
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.
2021-08-22 14:56:27 +01:00
Philip Herron
cbfc0ee239 This allows for query based compilation
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.
2021-08-22 14:56:27 +01:00
Philip Herron
79092784f2 Refactor the function query compilation function out
This is an initial stab to refactor the query based compilation for paths.
2021-08-22 14:56:27 +01:00
Philip Herron
a6c8bd136d Add impl-trait path probe helper
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.
2021-08-22 14:56:26 +01:00
Philip Herron
d5dd96322b Add Trait Resolver simple type-path lookup
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.
2021-08-22 14:56:26 +01:00
Philip Herron
d609accab7 add trait_reference is_equal helper method
We need to be able to detect if trait references are equal which can be
based on the DefId mapping which takes into account crate and local defid
2021-08-22 14:56:26 +01:00
Philip Herron
95ad46b905 Extract header Path type-check code into cc file
Part of the ongoing effort to extract code into cc files to help
compilation times.
2021-08-22 14:56:26 +01:00
bors[bot]
e9746f445c Merge #638
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>
2021-08-21 20:47:52 +00:00
CohenArthur
abaec43778 hir: Merge both module classes in one
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
2021-08-21 14:03:02 +02:00
bors[bot]
79754bd20b Merge #626
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>
2021-08-20 12:34:35 +00:00
Philip Herron
048261647a Add qualified path support
Qualified paths need to lookup the associated trait item and mangle the
names apropriatly.
2021-08-20 13:32:14 +01:00
Philip Herron
1dc7184740 optional trait item with associated types 2021-08-19 15:39:21 +01:00
Philip Herron
c25cdc8460 Initial Typechecking for projections
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.
2021-08-19 15:39:18 +01:00
Philip Herron
fe9dd83b41 ProjectionType this is a special TyTy initial boiler plate
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.
2021-08-19 15:36:37 +01:00
Philip Herron
1e74f08c14 Add QualifiedTypePath HIR lowering
QualifiedTypePath resolution differs from normal PathInExpressions and can
resolve to trait items this adds the hir lowering for this.
2021-08-19 15:30:23 +01:00
Philip Herron
3475f10cbf Add QualifiedPathInExpression name resolution
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.
2021-08-19 15:30:19 +01:00
Philip Herron
71cf0d44d3 Add support for optional trait functions in method calls
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
2021-08-19 14:36:11 +01:00
Philip Herron
3f877a690d Add missing mappings for trait-items 2021-08-19 14:36:10 +01:00
Philip Herron
b9c1a73e6d Trait item functions contain a block expression for its body 2021-08-19 14:36:10 +01:00
Philip Herron
2148d2f974 refactor code into cc file 2021-08-19 14:36:10 +01:00
bors[bot]
387f73626a Merge #509 #636
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>
2021-08-19 09:18:09 +00:00
bors[bot]
24838285ad Merge #637
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>
2021-08-19 08:56:45 +00:00
Marc Poulhiès
b34ea0af5e tests: add tests for Module
Add tests for Module support.

ref #432
2021-08-18 22:59:54 +02:00
Marc Poulhiès
ed9a473c74 typecheck + backend: add module support
Typechecking and backend for Modules.

ref #432

Co-authored-by: Philip Herron <philip.herron@embecosm.com>
2021-08-18 22:59:48 +02:00
Marc Poulhiès
fd1d9c1af7 hir: lower Module
Lower AST::Module to HIR::ModuleBodied.
Add HIR::ModuleBodied::get_items to access module's items.

Fix tests that are already using module.

ref #432
2021-08-18 22:59:43 +02:00
Marc Poulhiès
37a6b4ae78 resolve: add support for Module
Implement required visitor methods for resolving names in modules.

ref #432

Co-authored-by: Philip Herron <philip.herron@embecosm.com>
2021-08-18 22:59:37 +02:00
Marc Poulhiès
76ed248287 ast: add AST::Module::get_name method
Allow for getting a module's name.

ref #432
2021-08-18 22:59:36 +02:00
Marc Poulhiès
fc0c2dcf34 Add module map in HIR maps
Add module map and required methods to access it.

refs #432
2021-08-18 22:59:36 +02:00
Mark Wielaard
9d30105d75 Use default type_for_size langhook
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.
2021-08-18 22:59:35 +02:00
Mark Wielaard
eb5e504ec2 Allow bool and char to be cast as any integer type
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
2021-08-18 22:59:35 +02:00
bors[bot]
3a944e1b7a Merge #632
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>
2021-08-17 15:44:38 +00:00
bors[bot]
335cd53dda Merge #633
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>
2021-08-17 15:24:24 +00:00
bors[bot]
d9082b50a9 Merge #631
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>
2021-08-17 08:01:46 +00:00
Mark Wielaard
5b229ddbf4 Use builtin bool instead of creating new bool types for ComparisonExpr
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.
2021-08-16 23:30:49 +02:00
Mark Wielaard
4f02b38f6a Allow bool and char to be cast as any integer type
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
2021-08-16 18:44:47 +02:00
Mark Wielaard
c4bab97a99 Use default type_for_size langhook
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.
2021-08-15 23:56:25 +02:00
Mark Wielaard
bb52e25b2d Add support for const bool and const float
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.
2021-08-15 21:43:19 +02:00
Mark Wielaard
6109a6b4b1 Suppress uninitialized candidate_type warning in process_traits_for_candidates
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]
2021-08-15 17:57:48 +02:00
bors[bot]
52c1cdc9c6 Merge #630
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>
2021-08-14 22:22:15 +00:00
Mark Wielaard
ee3d0b09dc parse if expression with unary minus or not expression
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.
2021-08-14 20:42:24 +02:00
bors[bot]
e53f1acb28 Merge #628
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>
2021-08-12 20:59:44 +00:00
Marc Poulhiès
8208beaf1e typecheck: add assert on resolve_root_path return value
resolve_root_path can return nullptr in case of error.
Better raise an error than dereference the pointer.
2021-08-12 22:39:25 +02:00
bors[bot]
3610c9b202 Merge #613
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>
2021-08-12 15:06:52 +00:00
CohenArthur
b4993a6293 module: Add basic filename discovery 2021-08-12 16:55:14 +02:00
CohenArthur
53756e1a01 lexer: Add function to get original filename
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`
2021-08-12 16:52:22 +02:00
bors[bot]
7be0232c68 Merge #625
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>
2021-08-12 10:54:28 +00:00
Marc Poulhiès
da72de4d89 Change name resolver's iterate_* functions to allow early exit
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).
2021-08-12 11:17:58 +02:00
bors[bot]
a0ba86c3be Merge #623
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>
2021-08-11 14:44:18 +00:00
Philip Herron
06ce0a6655 Lookup the canonical path for code-generation
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.
2021-08-11 13:38:04 +01:00
Philip Herron
5c828514d7 Keep track of canonical paths in the mappings
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
2021-08-11 12:54:25 +01:00
Philip Herron
06bfea60dd Refactor and extract CanonicalPath into a common header
CanonicalPath class and the node types are a common type which when split
from the hir-mapping class decouples the headers and cleans things up.
2021-08-11 12:53:33 +01:00
bors[bot]
ed64f39213 Merge #622
622: Update REDME.md for Docker builds r=philberty a=philberty



Co-authored-by: Philip Herron <philip.herron@embecosm.com>
2021-08-11 10:47:09 +00:00
Philip Herron
c8220239c3 Update REDME.md for Docker builds
Dockerhub has stopped automated builds this adds the github badge instead
2021-08-11 11:46:16 +01:00
bors[bot]
ae3b9072a9 Merge #621
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>
2021-08-11 09:56:51 +00:00
Philip Herron
8bb47bcaf1 Add docker image builds though github actions.
Recently dockerhub is now charging for automated builds on dockerhub. This
means we no longer have regular updated docker builds of gccrs.
2021-08-11 10:43:27 +01:00
bors[bot]
b1b59b1250 Merge #620
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>
2021-08-11 09:34:58 +00:00
Mark Wielaard
02424cf671 Pass pratt parsed location to expr parser functions to fix expr locus
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);
      |                 ^
2021-08-11 10:31:10 +01:00
bors[bot]
0c2c4d3f28 Merge #619
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>
2021-08-10 23:44:33 +00:00
Marc Poulhiès
7e1813b56d Rename CanonicalPath::is_error to is_empty
`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.
2021-08-10 22:12:29 +02:00
bors[bot]
e10f3d6556 Merge #618
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>
2021-08-10 12:22:25 +00:00
Philip Herron
226f2e4f13 Make insert_new_definition permissive of the same mapping.
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.
2021-08-10 12:46:26 +01:00
bors[bot]
5e723d0b7a Merge #611
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>
2021-08-08 22:22:21 +00:00
bors[bot]
fa2aec10e6 Merge #615
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>
2021-08-08 21:57:02 +00:00
Philip Herron
72483b1ca9 Improve the error message for bad type bounds
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>();
      |                               ^
2021-08-08 22:29:55 +01:00
Philip Herron
3f544652b4 Fix memory issues with multiple type-bounds 2021-08-08 21:12:03 +01:00
Philip Herron
49a498f28b refactor error_node to be part of the type not the resolver 2021-08-08 20:00:43 +01:00
Philip Herron
43c1ab08f0 add missing copy constructors and equality interfaces 2021-08-08 20:00:26 +01:00
Mark Wielaard
007e6ecefb lex: accept zero codepoints in strings
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.
2021-08-08 14:57:25 +02:00
bors[bot]
6bd42365fa Merge #612
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>
2021-08-07 20:48:23 +00:00
bors[bot]
f44e5cf628 Merge #614
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>
2021-08-07 20:27:50 +00:00
Michael Karcher
ba75fe35b5 rust to gcc glue layer: Remove excess precision when done
Signed-off-by: Michael Karcher <debian@mkarcher.dialup.fu-berlin.de>
2021-08-07 20:27:41 +02:00
CohenArthur
d80f411c8a session: Turn Session class into basic singleton 2021-08-06 22:47:39 +02:00
Philip Herron
c434e5fffc Add check for TypeBounds on argument substitutions
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
2021-08-06 19:35:16 +01:00
bors[bot]
41e3fb5d20 Merge #610
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>
2021-08-06 14:57:33 +00:00
Mark Wielaard
8389c018e5 More rustspec.cc cleanups
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.
2021-08-06 01:25:13 +02:00
bors[bot]
935f1d7da3 Merge #609
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>
2021-08-05 21:33:47 +00:00
Philip Herron
65ef30eb84 Support TypeBounds on Generic functions
TypeBounds are what make generics useful in Rust. They act in some ways
similar to interfaces in modern Java.

Fixes #583
2021-08-05 19:07:11 +01:00
Philip Herron
0db1c80456 Add missing mappings required for type resolution
Add Trait item mappings for trait resolving purposes. This allows us to
lookup the trait with a trait item belongs to and vice versa.
2021-08-05 18:20:56 +01:00
Philip Herron
4845c77684 Mark clone with const
TyTy::Clone should be const to enforce compiler checks that we do not
change the object.
2021-08-05 18:19:51 +01:00
Philip Herron
874b783748 Add type bound name resolution
Resolve the type-bound to the trait.
2021-08-05 18:19:26 +01:00
Philip Herron
443d4d1f7c Fix clone on TypeBounds
Covariance was causing issues for the default clone on these classes. Such that the NodeId became messed up. This causes name resolution issues.
2021-08-05 18:18:35 +01:00
Philip Herron
b333711461 Add lowering for TypeBounds on Generic Parameters
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.
2021-08-05 18:17:40 +01:00
bors[bot]
074c070c02 Merge #608
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>
2021-08-05 11:34:51 +00:00
CohenArthur
af7cd8a985 parser: Implement parse_items() as separate public function 2021-08-05 12:25:57 +02:00
bors[bot]
15635e68bb Merge #605
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>
2021-08-04 14:26:10 +00:00
bors[bot]
7bdd8599b9 Merge #606
606: Always check the result of expect_token while parsing r=dkm a=dkm

From Mark Wielaard : https://gcc.gnu.org/pipermail/gcc-rust/2021-August/000111.html

> 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

Co-authored-by: Mark Wielaard <mark@klomp.org>
Co-authored-by: Thomas Schwinge <thomas@codesourcery.com>
2021-08-04 12:34:29 +00:00
bors[bot]
73271c4ce5 Merge #607
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>
2021-08-04 07:41:58 +00:00
Thomas Schwinge
0209c8f662 Add 'rust/compile/torture/identifier-missing-impl-1.rs' [#603] 2021-08-04 09:33:19 +02:00
Mark Wielaard
d04886a4ea Always check the result of expect_token while parsing
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
2021-08-04 00:34:38 +02:00
Mark Wielaard
4292110a0a Remove split-stack from backend
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.
2021-08-03 23:13:18 +02:00
CohenArthur
c4077cc2a8 expand: Merge both implementations for both module types 2021-08-03 17:55:23 +02:00
CohenArthur
4a5af75e32 parser: Use Module constructor instead of both versions 2021-08-03 17:55:23 +02:00
CohenArthur
af152cbda5 ast-visitors: Remove declaration for both module types 2021-08-03 17:55:23 +02:00
CohenArthur
2e45247314 module: Merge both as_string() implementations 2021-08-03 17:55:22 +02:00
CohenArthur
76d9871594 ast: Merge both Module kinds in one class 2021-08-03 17:55:22 +02:00
bors[bot]
c707190b29 Merge #602
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>
2021-08-02 16:50:26 +00:00
bors[bot]
2fe7fb7ce5 Merge #604
604: Handle 'UnsafeBlockExpr' in liveness analysis r=philberty a=tschwinge

We may then remove the '{ dg-options "-w" }' as discussed in
<http://mid.mail-archive.com/YQciMeKNpCH+ZMsJ@wildebeest.org> and #601.


Co-authored-by: Thomas Schwinge <thomas@codesourcery.com>
2021-08-02 16:23:31 +00:00
Thomas Schwinge
a0628a62ad Handle 'UnsafeBlockExpr' in liveness analysis
We may then remove the '{ dg-options "-w" }' as discussed in
<http://mid.mail-archive.com/YQciMeKNpCH+ZMsJ@wildebeest.org> and #601.
2021-08-02 14:18:24 +02:00
bors[bot]
b56c6fdfaa Merge #601
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>
2021-08-02 09:13:20 +00:00
Mark Wielaard
cd67e5d5f1 Add locus to TupleField and pass it and union variants to HIR class
TupleField was missing a Location field and we dropped to locus when
lowering Union fields to HIR.
2021-08-02 00:33:08 +02:00
Mark Wielaard
389fd74a3f union support for hir type checking and gcc backend
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).
2021-08-01 12:57:33 +02:00
bors[bot]
06a65591eb Merge #600
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>
2021-07-31 10:36:17 +00:00
Alexey Sakovets
86a46d7973 Use correct lookahead to peek after 'while' token when parsing expression with block (parse_expr_with_block). 2021-07-30 23:44:40 +03:00
bors[bot]
f76ddb42f8 Merge #598
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>
2021-07-27 13:36:51 +00:00
Philip Herron
7f8adccb50 Add support for varadic extern "c" functions like printf
Varadic functions are only allowed in extern functions as far as I know.
2021-07-27 14:33:52 +01:00
Philip Herron
2818017d36 Adds support for compilation of extern "C" functions.
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
2021-07-27 14:33:43 +01:00
bors[bot]
9526e6d621 Merge #599
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>
2021-07-27 12:23:09 +00:00
Philip Herron
a9174d87f5 Fix assertion for trait item mappings 2021-07-27 12:41:17 +01:00
Philip Herron
b176f38916 Add flags for FnType FNTYPE_IS_METHOD_FLAG FNTYPE_IS_EXTERN_FLAG 2021-07-27 12:32:25 +01:00
Philip Herron
defe97ea4d Add mappings for external items 2021-07-27 12:32:25 +01:00
Philip Herron
f3bf1f293d Add resolution for extern function items 2021-07-26 22:15:41 +01:00
bors[bot]
b992c8058c Merge #597
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>
2021-07-26 16:54:12 +00:00
Philip Herron
5f238bc0fd Add name-resolution and HIR lowering for extern blocks
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
2021-07-26 17:38:51 +01:00
bors[bot]
5b3909dd74 Merge #596
596: Fix crash when extern function item has no return type r=philberty a=philberty

Addresses #421
Fixes #595


Co-authored-by: Philip Herron <philip.herron@embecosm.com>
2021-07-26 14:29:28 +00:00
Philip Herron
bb351c7a73 Fix crash when extern function item has no return type
Return types are optional in rust and extern fn items can be a ZST for the
result.

Addresses #421
Fixes #595
2021-07-26 15:18:42 +01:00
bors[bot]
f4dd2434cf Merge #592
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>
2021-07-26 14:08:28 +00:00
Philip Herron
5313e4fbe7 Initial TypeCast Rules
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
2021-07-26 14:56:29 +01:00
Philip Herron
6822e1b3e4 Add GENERIC support for TypeCastExpr to call fold_convert_loc 2021-07-26 14:13:35 +01:00
Mark Wielaard
75750d58ce Lowering Cast Expressions from AST to HIR.
This allows for type resolution for TypeCasts.
2021-07-26 14:13:35 +01:00
Philip Herron
5bf96284dd Add name resolution for TypeCastExpr
This adds name checking and lookups in side tables for the expression
and types involved in the compiler pipeline.
2021-07-26 14:13:35 +01:00
bors[bot]
a4e3ffd376 Merge #593
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>
2021-07-25 21:38:24 +00:00
bors[bot]
4447dba7c8 Merge #594
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>
2021-07-25 21:13:35 +00:00
Mark Wielaard
f2ce41608a Support RangeFrom ([x..]) and RangeFromTo ([x..y]) in the parser
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].
2021-07-25 15:31:19 +02:00
Mark Wielaard
df2b3b15dc Support byte and byte string literals
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].
2021-07-25 14:54:13 +02:00
bors[bot]
314b62ec78 Merge #591
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>
2021-07-23 14:21:43 +00:00
Mark Wielaard
4d841a49dd Remove error handling in parse_type_no_bounds for PLUS token
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.
2021-07-23 15:03:34 +01:00
bors[bot]
afd9db6f6b Merge #590
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>
2021-07-23 13:55:51 +00:00
Mark Wielaard
17fcb1a3ba Better union support in the parser
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.
2021-07-23 14:54:36 +01:00
bors[bot]
44472c580c Merge #587 #589
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>
2021-07-22 14:23:06 +00:00
bors[bot]
06a2ec7e93 Merge #585 #586
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>
2021-07-22 14:01:37 +00:00
Philip Herron
d0b2cd241c Support dereference of pointers
Dereference expressions can also be pointer types not just references.

Fixes #588
2021-07-22 12:37:10 +01:00
Philip Herron
b830b3523e Add testcase to cover parse errors in unsafe expressions
We had a bug in the parser with unsafe expression this adds a test case to
cover the parser issue.

Fixes #584
2021-07-22 12:28:25 +01:00
Philip Herron
1dc68e40f2 Add mappings for trait items 2021-07-22 12:24:50 +01:00
bors[bot]
dd825b9b5d Merge #582
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>
2021-07-22 10:45:23 +00:00
Mark Wielaard
1709592fbf unsafe blocks can be used in expressions
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.
2021-07-22 11:17:45 +01:00
Philip Herron
1c5fef82c0 Add iterate impl_blocks helper 2021-07-21 13:12:10 +01:00
bors[bot]
6dfde8225f Merge #579
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>
2021-07-20 19:47:26 +00:00
bors[bot]
1c63988eab Merge #581
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>
2021-07-20 19:20:36 +00:00
Philip Herron
857953b3c7 HIR and GENERIC lowering for unsafe blocks
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
2021-07-20 20:06:14 +01:00
Philip Herron
aa4feb8867 Raw pointer support
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
2021-07-20 18:46:04 +01:00
bors[bot]
869b328c5c Merge #578
578: Remove unused code r=philberty a=philberty

Remove unused code

Co-authored-by: Philip Herron <philip.herron@embecosm.com>
2021-07-20 15:35:56 +00:00
Philip Herron
c76df9b8ee Remove unused code
This was part of basing the rust front-end off the gccgo and this was a dup
of rust-object-export.c.
2021-07-20 13:53:33 +01:00
bors[bot]
02713d245a Merge #577
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>
2021-07-20 08:17:09 +00:00
Philip Herron
f56781662f Assignments are a coercion site in rust
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 #434
Fixes #576
2021-07-19 19:38:51 +01:00
Philip Herron
0cbd3afc71 Initial coercion rules
Lets keep the same unify pattern for coercion rules to keep the code as
readable as possible.

Addresses #434
2021-07-19 19:38:29 +01:00
Philip Herron
f82bf003ce Add comment to can_eq 2021-07-19 19:38:29 +01:00
Philip Herron
4a966c3b7f Reference Types can be mutable
We need to track mutability on Reference Types and check wether they
actually match up.

Addresses #576
2021-07-19 19:38:19 +01:00
Philip Herron
2f7b803bcc Refs should be used in the base ctor of BaseType
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
2021-07-19 19:36:39 +01:00
bors[bot]
eea221e39e Merge #572
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>
2021-07-16 14:57:55 +00:00
Philip Herron
40ab687d56 Make TyTy::BaseType::can_eq const
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.
2021-07-16 13:07:17 +01:00
Philip Herron
ff137b6261 Keep track of impl blocks via mappings
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.
2021-07-16 13:07:17 +01:00
Philip Herron
f813b33098 Track the parent impl a probe candidate comes from.
This change keeps an enum for the candidate type and the parent impl block
this probed candidate originates from.
2021-07-16 13:07:17 +01:00
bors[bot]
d57f3b8af1 Merge #571
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>
2021-07-16 08:04:06 +00:00
Thomas Young
20c8a85c2f call accept_vis directly instead of call it after get 2021-07-16 13:03:17 +08:00
bors[bot]
41a6819f7f Merge #568
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>
2021-07-15 21:05:42 +00:00
bors[bot]
b322f221ce Merge #569 #570
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>
2021-07-15 20:45:21 +00:00
bors[bot]
2404e4841d Merge #567
567: warn the unused associated functions r=philberty a=thomasyonug

warn the unused associated functions

Co-authored-by: Thomas Young <wenzhang5800@gmail.com>
2021-07-15 15:33:18 +00:00
Philip Herron
9783726c85 Add missing test case to close out unit-structs
Unit structs can be initilized in two ways this test case will cover
future updates to catch any regressions.

Fixes #155
2021-07-15 14:18:42 +01:00
Philip Herron
ebdf933621 Only error for missing trait items.
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.
2021-07-15 14:13:49 +01:00
Philip Herron
ea04a9ff1d Add DefId mappings to TyTy::FnType
This adds the def id to trait items and nested items, this will help with
optional trait item compilation.
2021-07-15 13:49:30 +01:00
Thomas Young
9bebd1e79c warn the unused associated functions 2021-07-15 19:51:19 +08:00
Philip Herron
73ac7c5a1e Impl items should have a DefID
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.
2021-07-15 11:12:57 +01:00
bors[bot]
089e62f33c Merge #566
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>
2021-07-14 20:48:41 +00:00
bors[bot]
51f66ab136 Merge #564
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>
2021-07-14 19:19:38 +00:00
Philip Herron
05b5eec7ab Add check for missing items in impl of trait
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
2021-07-14 20:18:09 +01:00
Philip Herron
6e0c46b86a Trait item consts can have an optional expr
When we are checking for trait constants their expression can be optional
which will cause an ICE when ignored.

Fixes #471
2021-07-14 18:57:27 +01:00
Philip Herron
60b1209d64 Fix Placeholder type checking
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
2021-07-14 18:57:17 +01:00
Thomas Young
e25ef1ec86 Add some comments about wha's kind of unused item will be warned 2021-07-14 14:08:37 +08:00
bors[bot]
b4ea3a1946 Merge #562
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>
2021-07-13 11:33:26 +00:00
Thomas Young
29d84b2c14 add some comments about how scan dead code pass handle PathInExpression and PathExprSegment 2021-07-13 15:41:04 +08:00
bors[bot]
9415a4b712 Merge #561
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>
2021-07-12 11:10:07 +00:00
Mark Wielaard
876f70e905 Remove HIR MacroItem and other hir macro forward declarations
Almost all HIR Macro related trees were already removed by
https://github.com/Rust-GCC/gccrs/pull/492

But there was still one MacroItem class left in rust-hir.h and several
(unused) forward declarations in various other hir .h files. Remove
them all.

Resolves: https://github.com/Rust-GCC/gccrs/issues/69
2021-07-12 10:50:45 +01:00
bors[bot]
7cecfe983b Merge #559
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>
2021-07-12 08:36:08 +00:00
bors[bot]
6d2a3d03ad Merge #560
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>
2021-07-12 08:11:55 +00:00
Mark Wielaard
36bd4a5c85 Remove HIR MacroItem and other hir macro forward declarations
Almost all HIR Macro related trees were already removed by
https://github.com/Rust-GCC/gccrs/pull/492

But there was still one MacroItem class left in rust-hir.h and several
(unused) forward declarations in various other hir .h files. Remove
them all.

Resolves: https://github.com/Rust-GCC/gccrs/issues/69
2021-07-12 09:09:47 +01:00
Mark Wielaard
e1e14958a9 Handle doc comment strings in lexer and parser
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.
2021-07-11 21:09:21 +02:00
Thomas Young
200fcaad46 add some comments about FindEntryPoints and MarkLive in dead code scan pass 2021-07-11 14:21:05 +08:00
bors[bot]
4560f469ee Merge #551
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>
2021-07-10 21:02:06 +00:00
bors[bot]
f090e7ca9f Merge #558
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>
2021-07-10 20:39:35 +00:00
Philip Herron
defb583203 Add support for TypeAliases on Traits
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
2021-07-10 21:36:09 +01:00
Philip Herron
7ebf5d62d2 Ensure adding references adds it for all declarations with that ID
In the case for implicit declarations we must ensure all declarations
have the reference appended.
2021-07-10 21:34:15 +01:00
Philip Herron
0352605f4a Add path probe and impl overlapping updates for TypeAliases
With the desuagaring of AST::TraitImpl and AST::InherentImpl into a generic
HIR::ImplBlock we must ensure the existing passes can support TypeAliases
accordingly.
2021-07-10 21:33:08 +01:00
Philip Herron
213bc11225 canonical path enhancements
This refactors the canonical path to enforce the segment ids.
2021-07-10 21:32:44 +01:00
Philip Herron
8bfeef998f Add node-ids to type-path-segments in AST
We must track the type path segments ids within the Canonical path.
2021-07-10 21:32:26 +01:00
Philip Herron
97b917f8d2 Traits must inherit the prefix trait path
TraitItems must inherent the Trait name such that the items are prefixed
accordingly:

  trait foo {  // Path foo
    fn bar().. // Path foo::bar
  }
2021-07-10 21:31:35 +01:00
Philip Herron
99355534ef The type system has a function can_eq this adds a with_errors flag
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
2021-07-10 21:28:51 +01:00
Philip Herron
e3390f5602 Introduce placeholder type
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
2021-07-10 21:27:44 +01:00
Philip Herron
91aa2cba1c Refactor CanonicalPath so we can iterate the segments
This adds the associated NodeId into each CanonicalPath segment which
references their respective TypePathSegment or PathExprSegment.
2021-07-10 21:26:58 +01:00
Philip Herron
bb51a9de35 Add toplevel resolution for type alias
TypeAliases can be contained within ImplBlocks and need their full
canonical path to be resolved.
2021-07-10 21:26:17 +01:00
Philip Herron
c5ce98cbb8 ImplBlocks can contain TypeAlias's
This lowers TypeAliases into ImplItem for HIR::ImplBlocks.
2021-07-10 21:25:38 +01:00
Philip Herron
30ca362420 Assert that impl items are non null when translated to hir
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
2021-07-10 21:24:14 +01:00
Thomas Young
4586903233 call mark live symbols in ScanDeadcode instead of session::parse_file 2021-07-10 09:29:04 +08:00
bors[bot]
9a58a5c256 Merge #555
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>
2021-07-09 11:13:07 +00:00
Thomas Young
7dceca5480 replace all variable name ret to ok 2021-07-09 14:52:31 +08:00
Thomas Young
f3a345f0eb revert visit_path_segment return type to bool 2021-07-09 09:09:26 +08:00
Thomas Young
e750295b60 rust_assert to check return value 2021-07-07 15:07:19 +08:00
Thomas Young
1e0b4e71a1 use rust_assert in dead code pass instead of rust_error_at 2021-07-07 13:20:48 +08:00
bors[bot]
3670b0ef05 Merge #548
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>
2021-07-06 09:26:19 +00:00
bors[bot]
32c9b09fdb Merge #554
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>
2021-07-06 09:02:11 +00:00
Thomas Young
4fd6415421 make the warning msg be searched easier 2021-07-06 15:42:23 +08:00
bors[bot]
630efc56d1 Merge #552
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>
2021-07-06 07:04:19 +00:00
Mark Wielaard
94ada647bf Remove has_utf8bom flag from AST and HIR Crate classes
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.
2021-07-05 21:27:51 +02:00
Mark Wielaard
29192293fd Handle UTF-8 BOM in lexer
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.
2021-07-05 21:11:03 +02:00
bors[bot]
27b3d34428 Merge #546
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>
2021-07-05 14:49:56 +00:00
bors[bot]
3c7c2f427c Merge #544
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>
2021-07-05 14:29:04 +00:00
Philip Herron
dc5e018327 Fix bad naming of primitive types such as u64 which ended up as usize
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.
2021-07-05 12:48:11 +01:00
Mark Wielaard
afe6eb7d16 Remove has_shebang flag from AST and HIR Crate classes
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.
2021-07-04 23:56:21 +02:00
Mark Wielaard
ff35f162da Handle shebang line, plus any whitespace and comment skipping in lexer
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.
2021-07-04 23:56:06 +02:00
Thomas Young
2e00415a11 mark live symbol support type alias and tuple struct 2021-07-04 20:13:52 +08:00
bors[bot]
210ae4f7b0 Merge #543
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>
2021-07-03 16:26:15 +00:00
Thomas Young
e1aedf6ec7 mark live symbol in if expr family except if let expr 2021-07-03 23:58:47 +08:00
bors[bot]
2b1d687d6a Merge #534
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>
2021-07-02 13:26:14 +00:00
Thomas Young
d882a0c97f detect unused struct field. 2021-07-02 21:12:39 +08:00
Thomas Young
6d7b87f9dd make struct field carry the location info 2021-07-02 12:37:54 +08:00
bors[bot]
458f7a5459 Merge #540
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>
2021-07-01 16:22:57 +00:00
Philip Herron
5e4505e162 Remove HIR::Method this finishes the desugaring of methods into HIR
Methods are just functions with a self param. This simplifies typecheck
and GENERIC generation code.

Addresses #470 #473
2021-07-01 15:53:09 +01:00
Philip Herron
9e7e6b3b87 Implicit Self on Traits
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
2021-06-30 17:31:41 +01:00
bors[bot]
0163ca4b6f Merge #538
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>
2021-06-30 14:06:58 +00:00
Thomas Young
5aa2188c89 exit immediately when the type checker find a error 2021-06-30 21:51:25 +08:00
bors[bot]
bb95f8f5ca Merge #536
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>
2021-06-30 10:00:19 +00:00
bors[bot]
1738bb8c76 Merge #537
537: Minor warning cleanup r=philberty a=dkm

Pushing 2 commit for Mark, cleaning up some warning.

Co-authored-by: Mark Wielaard <mark@klomp.org>
2021-06-30 09:35:11 +00:00
Mark Wielaard
ce5aab47af Remove unused have_more_segments from TypeCheckExpr::resolve_root_path
It isn't necessary to know whether there are more segments while
iteration through the expression segments.
2021-06-30 08:51:21 +02:00
Mark Wielaard
4860de6ae9 Remove unused default_ty_param from TypeResolveGenericParam::visit
The default_ty_param was set, but not used. We do need to call TypeCheckType::Resolve
on the default param, but don't need the result.
2021-06-29 23:30:04 +02:00
Philip Herron
59897751aa Revert change to ScanUnused to not scan Types
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.
2021-06-29 21:24:47 +01:00
bors[bot]
2d11bfd88c Merge #535
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>
2021-06-29 20:06:05 +00:00
bors[bot]
e0c0ef46d2 Merge #532
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>
2021-06-29 14:01:12 +00:00
Thomas Young
e2a40e08e2 Marking live symbol for struct construction.
Comment iterate_type_ribs of UnusedScan in order to resolve multiple struct unused report.
2021-06-29 21:56:23 +08:00
Mark Wielaard
1eb53a9d7a Suppress warning in rust-ast-lower-type.h ASTLowerGenericParam.visit.
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.
2021-06-28 23:30:58 +02:00
bors[bot]
bab6f6bcb2 Merge #530
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>
2021-06-27 22:47:58 +00:00
bors[bot]
f4668ee7ea Merge #502
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>
2021-06-27 22:24:13 +00:00
Philip Herron
b81ef441b8 Initial Trait Obligations to enforce trait-impl-items are part of the trait
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
2021-06-27 23:18:02 +01:00
Mark Wielaard
69ed5eaef4 Fix inner attribute parsing
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
2021-06-27 16:59:57 +02:00
bors[bot]
54e0d01719 Merge #529
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>
2021-06-27 12:00:22 +00:00
Thomas Young
5ff37842fb mark live symbol in for expr without test case 2021-06-27 01:19:12 +08:00
Thomas Young
5386fcdf20 mark live symbol in whilelet expr without test case 2021-06-27 01:19:12 +08:00
Thomas Young
348c893f9c mark live symbol in while expr 2021-06-27 01:18:59 +08:00
Thomas Young
a89ee61180 mark live symbol in return expr 2021-06-27 01:08:22 +08:00
Thomas Young
6952f9871f mark live symbol in break expr 2021-06-27 01:08:22 +08:00
bors[bot]
51d86210d3 Merge #527
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>
2021-06-26 15:49:23 +00:00
bors[bot]
387d69cdf3 Merge #528
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>
2021-06-26 15:29:25 +00:00
Thomas Young
5e63d163fe mark live symbol in tuple expr 2021-06-26 12:00:08 +08:00
Thomas Young
c9cb0c3d44 mark live symbol in array expr 2021-06-26 12:00:08 +08:00
Thomas Young
8a458543eb mark live symbol in groupedExpr 2021-06-26 12:00:08 +08:00
Thomas Young
476f0c67db mark live symbol in type cast expr 2021-06-26 12:00:08 +08:00
Thomas Young
0f486127e1 mark live symbol in lazyBooleanExpr 2021-06-26 11:59:54 +08:00
Mark Wielaard
60cb8cc43b Reject non-pure decimal tuple indexes.
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
2021-06-25 21:50:37 +02:00
bors[bot]
99bc27d278 Merge #526
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>
2021-06-25 12:53:24 +00:00
Philip Herron
f089723609 Add support for empty struct initilizer
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.
2021-06-25 13:51:50 +01:00
Philip Herron
cb0db310b3 Add support for unit-struct
IdentifierExpr's can reference types like a unit-struct, referencing other
structs actually form a function item type which is not supported yet.
2021-06-25 12:28:22 +01:00
Philip Herron
3ede4ff311 ADT types can be empty signifying a unit-struct
struct S; Turns into an ADT type which is a type of unit-struct.
2021-06-25 12:23:49 +01:00
Philip Herron
13fd4d31da Add TypeKindString to tyty debug
Adding the to_string for type kind will improve the debug message for
type wrappers.
2021-06-25 12:21:34 +01:00
bors[bot]
08e3ae7fce Merge #525
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>
2021-06-25 09:16:59 +00:00
Thomas Young
b111e6305a mark live symbol in NegationExpr 2021-06-25 13:27:25 +08:00
Thomas Young
4d786b72b5 make the method get_expr of NegationExpr keep consistant with other HIR. 2021-06-25 13:26:27 +08:00
Thomas Young
862722c688 mark live symbol in deref exp 2021-06-25 13:11:18 +08:00
Thomas Young
1a05bb190e borrowed function should not be unreachable function 2021-06-25 13:11:18 +08:00
bors[bot]
07b7486e2c Merge #524
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>
2021-06-24 15:40:08 +00:00
Philip Herron
71c644f430 Change unit-type from void_type_node to a zero sized unsigned integer
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
2021-06-24 16:03:18 +01:00
bors[bot]
c87f2c72dc Merge #523
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>
2021-06-24 13:50:44 +00:00
Philip Herron
92a434a339 Add support for nested functions
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.
2021-06-24 12:36:08 +01:00
bors[bot]
23e748d7a6 Merge #522
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>
2021-06-24 10:11:22 +00:00
Mark Wielaard
c41d5a20d3 Handle empty/unit tuple enum variants in the parser.
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.
2021-06-24 11:07:37 +01:00
bors[bot]
595ae7743c Merge #521
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>
2021-06-23 16:24:39 +00:00
Mark Wielaard
23f622047e Handle empty/unit tuple structs in the parser.
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
2021-06-23 17:22:35 +01:00
bors[bot]
4e5baf7e67 Merge #520
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>
2021-06-23 13:14:49 +00:00
Philip Herron
012401ab1c Add support for struct definitions to be within a block
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
2021-06-23 14:10:45 +01:00
bors[bot]
ce545f5318 Merge #518
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>
2021-06-23 09:24:50 +00:00
bors[bot]
40b9e46abe Merge #517
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>
2021-06-22 21:12:49 +00:00
Tom Tromey
2fb749c5f4 Fix RAIIFile buglet
RAIIFile's implementation of operator= can leak a file, because it
doesn't handle the case where the assignee holds an open file handle.
2021-06-22 13:43:08 -06:00
Tom Tromey
9bedf77e05 Require moves in Token constructors
This avoids some string copies by changing the Token constructors to
require any std::string argument to be transferred via std::move.
2021-06-22 12:06:17 -06:00
Tom Tromey
3ebfb4d422 Use unique_ptr in Token
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.
2021-06-21 17:26:25 -06:00
bors[bot]
f2d9faf386 Merge #514
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>
2021-06-21 21:08:26 +00:00
bors[bot]
470e5144f6 Merge #512
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>
2021-06-21 20:26:22 +00:00
Tom Tromey
30d844bf11 Rename tuple field names
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.
2021-06-21 14:07:20 -06:00
Marc Poulhiès
c14fad2318 Fix various Wformat-diag diagnostics
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.
2021-06-21 22:04:41 +02:00
bors[bot]
7d3157eec8 Merge #513
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>
2021-06-21 09:33:55 +00:00
Tom Tromey
485f4cf7a6 Fix up test suite buglets
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.
2021-06-20 17:23:52 -06:00
Marc Poulhiès
8528f4b25f Update PULL_REQUEST_TEMPLATE.md
Reverting previous change.
Github is smart enough to filter out this block, but bors is not and pastes it in its commit message.
2021-06-19 22:59:01 +02:00
bors[bot]
4f31d4bbe9 Merge #506 #507 #508
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>
2021-06-19 20:25:18 +00:00
bors[bot]
ace501018b Merge #505
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>
2021-06-19 19:49:13 +00:00
Marc Poulhiès
c143022ebe Add more info in HIR dump for struct
Make struct fields more visible in dumps and add the mapping in the dump string.
2021-06-19 14:50:51 +02:00
Marc Poulhiès
09d26b3e0b Make 3 error messages slightly more informational
Add more context to some internal error messages (ie. not intended for user)
2021-06-19 14:49:09 +02:00
Marc Poulhiès
213b638b32 Fix: do not use object after it has been moved
After std::move(mapping), mapping is unspecified
2021-06-19 07:41:48 +02:00
Tom Tromey
8dd844ad0a Use DW_ATE_UTF for the Rust 'char' type
The Rust 'char' type should use the DWARF DW_ATE_UTF encoding.
2021-06-18 13:47:51 -06:00
Tom Tromey
231de190d1 Use correct DWARF encoding for i8 and u8 types
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.
2021-06-18 13:47:51 -06:00
bors[bot]
a0c1c0b400 Merge #504
504: Update PULL_REQUEST_TEMPLATE.md r=philberty a=dkm

Make template content invisible.


Co-authored-by: Marc Poulhiès <dkm@kataplop.net>
2021-06-18 19:38:57 +00:00
bors[bot]
e200b89c0f Merge #503
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>
2021-06-18 19:18:01 +00:00
Marc Poulhiès
bb0f91cad3 Update PULL_REQUEST_TEMPLATE.md
Make template content invisible.
2021-06-18 19:12:06 +02:00
Tom Tromey
c16652f3e4 Use DW_LANG_Rust in DWARF
This changes the GCC DWARF emitterto use DW_LANG_Rust or
DW_LANG_Rust_old as appropriate.
2021-06-18 10:10:29 -06:00
bors[bot]
7a47eb66a2 Merge #501
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>
2021-06-18 13:43:39 +00:00
Thomas Young
abdb744aec Update README.md for building steps on MacOS. 2021-06-18 20:03:16 +08:00
bors[bot]
d1fc48f20f Merge #499
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>
2021-06-17 14:33:15 +00:00
Philip Herron
59a5602637 Ensure rust_debug has printf specifier checks
This adds a macro wrapper over rust_debug_loc to inject a default location
so calls can maintain printf specifier checks.
2021-06-17 15:31:15 +01:00
Philip Herron
1a3f878dc3 Mark function as override to squash warning 2021-06-17 15:03:18 +01:00
bors[bot]
f8ae675c10 Merge #498
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>
2021-06-17 12:47:04 +00:00
Philip Herron
5290a82434 Remove HIR::TraitItemMethod this can be represented by TraitItemFunction
Methods are simply functions with a self param, this simplifies the paths
in HIR to avoid duplication as much as possible.
2021-06-17 13:44:00 +01:00
bors[bot]
3ab773c57c Merge #497
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>
2021-06-17 09:15:50 +00:00
Thomas Young
be78228790 avoid abort macro override the abort of std 2021-06-17 01:38:08 +08:00
bors[bot]
eeee6c73f0 Merge #496
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>
2021-06-16 17:16:27 +00:00
bors[bot]
350b0e5951 Merge #495
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>
2021-06-16 16:50:03 +00:00
Philip Herron
9474a0f4a5 TraitImpl blocks have a different CanonicalPath to normal impl blocks
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
}
```
2021-06-16 17:45:05 +01:00
Philip Herron
9d9ba03360 Impl blocks can have a trait reference
This refactors Type HIR lowering to extract TypePath AST -> HIR lowering
function, as Trait References are simply TypePaths.
2021-06-16 15:17:07 +01:00
Philip Herron
730a2174b9 Refactor HIR::InherentImpl to become HIR::ImplBlock
This folds the abstract Impl class directly into HIR::ImplBlock since the
TraitImplBlock is removed. It also refactors InherentImplItem to become
simply ImplItem.
2021-06-16 13:23:31 +01:00
Philip Herron
44481c1c2b Cleanup HIR to canonicalize TraitImpl to be treated as an impl block
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.
2021-06-16 12:09:07 +01:00
bors[bot]
59f09fd5a4 Merge #494
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>
2021-06-15 08:48:48 +00:00
Thomas Young
ba9728b401 replace analysis dir with lint dir and rename liveness to marklive 2021-06-15 10:26:49 +08:00
bors[bot]
59f8d7a234 Merge #492 #493
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>
2021-06-14 16:13:49 +00:00
Philip Herron
b3090f174b Add comment about modules and paths
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
2021-06-14 16:31:46 +01:00
Philip Herron
de454a17cf Fix PathExpression type resolution
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
2021-06-14 16:31:46 +01:00
Philip Herron
75c44883db Name resolver should try to resolve each segment in turn
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
2021-06-14 16:31:34 +01:00
Philip Herron
d8d7deb335 HIR should not contain any macros
This removes the macros tree's from HIR. HIR should be an expanded and
simplifed representation of the compilation unit.

Fixes #70
2021-06-11 18:05:52 +01:00
bors[bot]
df36e6b9ab Merge #488
488: Build fixes for 32-bit ARM r=philberty a=glaubitz

Fixes #483

Co-authored-by: John Paul Adrian Glaubitz <glaubitz@physik.fu-berlin.de>
2021-06-07 10:12:09 +00:00
John Paul Adrian Glaubitz
f1d080c601 arm: rust: Remove unsupported baselines arm_arch8_5 and arm_arch8_6 2021-06-07 09:30:19 +00:00
John Paul Adrian Glaubitz
41869028ea arm: rust: Fix typo: hasBaseLine8MPreReqs => hasBaseline8MPreReqs 2021-06-07 09:28:02 +00:00
bors[bot]
fcfbd8f9e0 Merge #484 #485 #486
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>
2021-06-05 16:26:06 +00:00
Mark Wielaard
b2fd4346a6 Use PRIx64 to print 64bit hex values in legacy_hash
* 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.
2021-06-05 17:18:39 +01:00
bors[bot]
bc4c1ef45d Merge #455
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>
2021-06-05 16:02:16 +00:00
Philip Herron
8564e93111 Update CONTRIBUTING.md
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>
2021-06-05 17:01:06 +01:00
Philip Herron
7222dcb2bb All toplevel items must respect the prefix for their path
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
2021-06-05 16:52:44 +01:00
Philip Herron
1c0f8d6d2a This is the initial building blocks for Traits
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
2021-06-05 16:40:19 +01:00
Philip Herron
69b3e48880 Add AST to HIR lowering for traits and trait impls.
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
2021-06-05 16:40:19 +01:00
Philip Herron
f1526062d9 Add initial name resolution for traits and trait impls
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
2021-06-05 16:40:13 +01:00
Philip Herron
1b3d621f21 Add NodeMappings to HIR::Trait Items
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
2021-06-05 16:40:06 +01:00
Philip Herron
1c0d6ea02a Add AST node_id to AST Trait Items
NodeIds are ids to map back to the AST from HIR. This is the building block
to begin name resolution for traits.

Addresses #395
2021-06-05 16:39:49 +01:00
bors[bot]
1f1d9ed87d Merge #482
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>
2021-06-04 13:07:44 +00:00
John Paul Adrian Glaubitz
c1728c27cb arm: Override TARGET_RUST_OS_INFO in bpabi.h
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.
2021-06-04 11:07:08 +00:00
bors[bot]
f408033d52 Merge #480
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>
2021-06-04 10:50:08 +00:00
Thomas Schwinge
4e43d678e2 Use '-frust-debug' to control dumping of various Rust front end internals
... as discussed in #479, and elsewhere.
2021-06-04 09:48:30 +02:00
bors[bot]
ff4715d79e Merge #479
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>
2021-06-04 07:12:37 +00:00
Thomas Schwinge
535d89c34f Remove diagnostics pruning from 'rust_target_compile' [#301, #466]
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.
2021-06-03 23:33:07 +02:00
bors[bot]
432c5f9c65 Merge #466
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>
2021-06-03 16:45:42 +00:00
CohenArthur
665df329a2 rust_debug: Replace fprintf (stderr) with rust_debug
Co-authored-by: tschwinge <thomas@schwinge.name>
2021-06-03 18:04:57 +02:00
CohenArthur
51cbf184f3 rust_debug: Expose function in header and add inline overloaded alternative
Co-authored-by: tschwinge <thomas@schwinge.name>
2021-06-03 18:33:51 +02:00
bors[bot]
4414e8a4c2 Merge #478
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>
2021-06-03 14:42:10 +00:00
John Paul Adrian Glaubitz
f37acd0067 mips: Fix incorrect name for target feature flag TARGET_ODD_SPREG
Fixes #476
2021-06-03 12:09:17 +00:00
bors[bot]
324dfb828c Merge #475
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>
2021-06-02 22:10:29 +00:00
John Paul Adrian Glaubitz
6b6fcbb6a4 rs6000: Override TARGET_RUST_OS_INFO in linux.h
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
2021-06-02 21:57:37 +00:00
bors[bot]
59b417323b Merge #469
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>
2021-06-02 16:30:47 +00:00
Thomas Young
2840815dc4 lowering attribute by copying attribute from AST to HIR directly
Addresses #459
2021-06-02 21:11:02 +08:00
bors[bot]
325ef69b13 Merge #465
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>
2021-06-02 09:54:27 +00:00
Thomas Schwinge
688f589b9f Re-organize GCC/Rust testsuites
... 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.
2021-06-02 11:05:44 +02:00
bors[bot]
fd9e53249c Merge #462
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>
2021-06-01 17:10:27 +00:00
bors[bot]
6b91184a26 Merge #463
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>
2021-06-01 16:48:43 +00:00
CohenArthur
40d7462051 debug: Always print compiler debug info on stderr 2021-06-01 18:58:17 +02:00
Philip Herron
7b89a2e3b9 Update README.md with GCC mailing list
GCC Rust now has an associated mailing list and irc channel on the usual GCC locations.
2021-06-01 16:47:49 +01:00
bors[bot]
2a644a5ebb Merge #460
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>
2021-06-01 10:27:39 +00:00
CohenArthur
7fb247dce4 raiifile: Allow dash-prefixed files to be parsed 2021-06-01 12:57:25 +02:00
bors[bot]
4b13e27087 Merge #458
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>
2021-05-31 20:38:09 +00:00
CohenArthur
5b0433b4be stdin: Allow compilation from standard input 2021-05-31 22:32:56 +02:00
bors[bot]
75de60e68b Merge #453
453: reusing AST::Attribute and remove HIR::Attribute r=philberty a=thomasyonug

Deleting HIR::Attribute and reusing AST::Attribute. 

Some relative reusing classes below:
1. DelimTokenTree
2. AttrInputMetaItemContainer
3. AttrInputLiteral
4. MetaItemLitExpr
5. MetaItemPathLit
6. MetaItemPath
7. MetaItemSeq
8. MetaWord
9. MetaNameValueStr
10. MetaListPath
11. MetaListNameValueStr
12. Attrbute
13. AttrInput
14. MacroParser

Co-authored-by: Thomas Young <wenzhang5800@gmail.com>
2021-05-31 16:54:37 +00:00
Thomas Young
a3539302cd Reusing AST::Attribute and removing HIR::Attribute.
Introducing AttrVec type to replace std::vector<Attribute>.
2021-05-31 21:44:55 +08:00
bors[bot]
0a3696a4a8 Merge #454
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>
2021-05-28 11:44:48 +00:00
Thomas Fitzsimmons
83c161d0b8 rs6000: Recognize GNU Rust when producing epilogue
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>
2021-05-28 13:14:49 +02:00
Thomas Fitzsimmons
13f995c199 rs6000: Override TARGET_RUST_OS_INFO in linux64.h
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.
2021-05-28 13:14:44 +02:00
bors[bot]
8f5b38ebde Merge #451
451: include memmodel.h above tm_p.h in order to build success in SPARC64 r=philberty a=thomasyonug

Fixes #450

Include "memmodel.h" above "tm_p.h" in order to build success in SPARC64

I had built rust1 in SPARC64 but got some fail tests. It's another independent issue I think.
```
Running target unix
Using /usr/share/dejagnu/baseboards/unix.exp as board description file for target.
Using /usr/share/dejagnu/config/unix.exp as generic interface file for target.
Using /home/thomasyoung/gccrs/gcc/testsuite/config/default.exp as tool-and-target-specific interface file.
Running /home/thomasyoung/gccrs/gcc/testsuite/rust.test/compile/compile.exp ...
FAIL: rust.test/compile/generics11.rs   -O0  (internal compiler error)
FAIL: rust.test/compile/generics11.rs   -O0  (test for excess errors)
FAIL: rust.test/compile/generics11.rs   -O1  (internal compiler error)
FAIL: rust.test/compile/generics11.rs   -O1  (test for excess errors)
FAIL: rust.test/compile/generics11.rs   -O2  (internal compiler error)
FAIL: rust.test/compile/generics11.rs   -O2  (test for excess errors)
FAIL: rust.test/compile/generics11.rs   -O3 -g  (internal compiler error)
FAIL: rust.test/compile/generics11.rs   -O3 -g  (test for excess errors)
FAIL: rust.test/compile/generics11.rs   -Os  (internal compiler error)
FAIL: rust.test/compile/generics11.rs   -Os  (test for excess errors)
FAIL: rust.test/compile/generics11.rs   -O2 -flto -fno-use-linker-plugin -flto-partition=none  (internal compiler error)
FAIL: rust.test/compile/generics11.rs   -O2 -flto -fno-use-linker-plugin -flto-partition=none  (test for excess errors)
FAIL: rust.test/compile/generics11.rs   -O2 -flto -fuse-linker-plugin -fno-fat-lto-objects  (internal compiler error)
FAIL: rust.test/compile/generics11.rs   -O2 -flto -fuse-linker-plugin -fno-fat-lto-objects  (test for excess errors)
FAIL: rust.test/compile/struct_init_2.rs   -O0  (internal compiler error)
FAIL: rust.test/compile/struct_init_2.rs   -O0   (test for warnings, line 4)
FAIL: rust.test/compile/struct_init_2.rs   -O0  (test for excess errors)
FAIL: rust.test/compile/struct_init_2.rs   -O1  (internal compiler error)
FAIL: rust.test/compile/struct_init_2.rs   -O1   (test for warnings, line 4)
FAIL: rust.test/compile/struct_init_2.rs   -O1  (test for excess errors)
FAIL: rust.test/compile/struct_init_2.rs   -O2  (internal compiler error)
FAIL: rust.test/compile/struct_init_2.rs   -O2   (test for warnings, line 4)
FAIL: rust.test/compile/struct_init_2.rs   -O2  (test for excess errors)
FAIL: rust.test/compile/struct_init_2.rs   -O3 -g  (internal compiler error)
FAIL: rust.test/compile/struct_init_2.rs   -O3 -g   (test for warnings, line 4)
FAIL: rust.test/compile/struct_init_2.rs   -O3 -g  (test for excess errors)
FAIL: rust.test/compile/struct_init_2.rs   -Os  (internal compiler error)
FAIL: rust.test/compile/struct_init_2.rs   -Os   (test for warnings, line 4)
FAIL: rust.test/compile/struct_init_2.rs   -Os  (test for excess errors)
FAIL: rust.test/compile/struct_init_2.rs   -O2 -flto -fno-use-linker-plugin -flto-partition=none  (internal compiler error)
FAIL: rust.test/compile/struct_init_2.rs   -O2 -flto -fno-use-linker-plugin -flto-partition=none   (test for warnings, line 4)
FAIL: rust.test/compile/struct_init_2.rs   -O2 -flto -fno-use-linker-plugin -flto-partition=none  (test for excess errors)
FAIL: rust.test/compile/struct_init_2.rs   -O2 -flto -fuse-linker-plugin -fno-fat-lto-objects  (internal compiler error)
FAIL: rust.test/compile/struct_init_2.rs   -O2 -flto -fuse-linker-plugin -fno-fat-lto-objects   (test for warnings, line 4)
FAIL: rust.test/compile/struct_init_2.rs   -O2 -flto -fuse-linker-plugin -fno-fat-lto-objects  (test for excess errors)
FAIL: rust.test/compile/struct_init_3.rs   -O0  (internal compiler error)
FAIL: rust.test/compile/struct_init_3.rs   -O0   (test for warnings, line 9)
FAIL: rust.test/compile/struct_init_3.rs   -O0  (test for excess errors)
FAIL: rust.test/compile/struct_init_3.rs   -O1  (internal compiler error)
FAIL: rust.test/compile/struct_init_3.rs   -O1   (test for warnings, line 9)
FAIL: rust.test/compile/struct_init_3.rs   -O1  (test for excess errors)
FAIL: rust.test/compile/struct_init_3.rs   -O2  (internal compiler error)
FAIL: rust.test/compile/struct_init_3.rs   -O2   (test for warnings, line 9)
FAIL: rust.test/compile/struct_init_3.rs   -O2  (test for excess errors)
FAIL: rust.test/compile/struct_init_3.rs   -O3 -g  (internal compiler error)
FAIL: rust.test/compile/struct_init_3.rs   -O3 -g   (test for warnings, line 9)
FAIL: rust.test/compile/struct_init_3.rs   -O3 -g  (test for excess errors)
FAIL: rust.test/compile/struct_init_3.rs   -Os  (internal compiler error)
FAIL: rust.test/compile/struct_init_3.rs   -Os   (test for warnings, line 9)
FAIL: rust.test/compile/struct_init_3.rs   -Os  (test for excess errors)
FAIL: rust.test/compile/struct_init_3.rs   -O2 -flto -fno-use-linker-plugin -flto-partition=none  (internal compiler error)
FAIL: rust.test/compile/struct_init_3.rs   -O2 -flto -fno-use-linker-plugin -flto-partition=none   (test for warnings, line 9)
FAIL: rust.test/compile/struct_init_3.rs   -O2 -flto -fno-use-linker-plugin -flto-partition=none  (test for excess errors)
FAIL: rust.test/compile/struct_init_3.rs   -O2 -flto -fuse-linker-plugin -fno-fat-lto-objects  (internal compiler error)
FAIL: rust.test/compile/struct_init_3.rs   -O2 -flto -fuse-linker-plugin -fno-fat-lto-objects   (test for warnings, line 9)
FAIL: rust.test/compile/struct_init_3.rs   -O2 -flto -fuse-linker-plugin -fno-fat-lto-objects  (test for excess errors)
FAIL: rust.test/compile/struct_init_8.rs   -O0  (internal compiler error)
FAIL: rust.test/compile/struct_init_8.rs   -O0   (test for warnings, line 5)
FAIL: rust.test/compile/struct_init_8.rs   -O0  (test for excess errors)
FAIL: rust.test/compile/struct_init_8.rs   -O1  (internal compiler error)
FAIL: rust.test/compile/struct_init_8.rs   -O1   (test for warnings, line 5)
FAIL: rust.test/compile/struct_init_8.rs   -O1  (test for excess errors)
FAIL: rust.test/compile/struct_init_8.rs   -O2  (internal compiler error)
FAIL: rust.test/compile/struct_init_8.rs   -O2   (test for warnings, line 5)
FAIL: rust.test/compile/struct_init_8.rs   -O2  (test for excess errors)
FAIL: rust.test/compile/struct_init_8.rs   -O3 -g  (internal compiler error)
FAIL: rust.test/compile/struct_init_8.rs   -O3 -g   (test for warnings, line 5)
FAIL: rust.test/compile/struct_init_8.rs   -O3 -g  (test for excess errors)
FAIL: rust.test/compile/struct_init_8.rs   -Os  (internal compiler error)
FAIL: rust.test/compile/struct_init_8.rs   -Os   (test for warnings, line 5)
FAIL: rust.test/compile/struct_init_8.rs   -Os  (test for excess errors)
FAIL: rust.test/compile/struct_init_8.rs   -O2 -flto -fno-use-linker-plugin -flto-partition=none  (internal compiler error)
FAIL: rust.test/compile/struct_init_8.rs   -O2 -flto -fno-use-linker-plugin -flto-partition=none   (test for warnings, line 5)
FAIL: rust.test/compile/struct_init_8.rs   -O2 -flto -fno-use-linker-plugin -flto-partition=none  (test for excess errors)
FAIL: rust.test/compile/struct_init_8.rs   -O2 -flto -fuse-linker-plugin -fno-fat-lto-objects  (internal compiler error)
FAIL: rust.test/compile/struct_init_8.rs   -O2 -flto -fuse-linker-plugin -fno-fat-lto-objects   (test for warnings, line 5)
FAIL: rust.test/compile/struct_init_8.rs   -O2 -flto -fuse-linker-plugin -fno-fat-lto-objects  (test for excess errors)
Running /home/thomasyoung/gccrs/gcc/testsuite/rust.test/execute/execute.exp ...
Running /home/thomasyoung/gccrs/gcc/testsuite/rust.test/unsupported/unsupported.exp ...
Running /home/thomasyoung/gccrs/gcc/testsuite/rust.test/xfail_compile/xfail_compile.exp ...
FAIL: rust.test/xfail_compile/struct_init1.rs (internal compiler error)
FAIL: rust.test/xfail_compile/struct_init1.rs  (test for errors, line 7)
FAIL: rust.test/xfail_compile/struct_init1.rs  (test for errors, line 7)
FAIL: rust.test/xfail_compile/struct_init1.rs (test for excess errors)

		=== rust Summary ===

# of expected passes		2284
# of unexpected failures	81
# of expected failures		26
```

Co-authored-by: Thomas Young <wenzhang5800@gmail.com>
2021-05-25 14:43:08 +00:00
Thomas Young
9cfe5c4aee include memmodel.h above tm_p.h in order to build success in SPARC64
Fixes #450
2021-05-25 21:40:33 +08:00
bors[bot]
0f24dfab17 Merge #448
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>
2021-05-24 08:12:13 +00:00
Mark Wielaard
a177913290 Fix v8.1a typo in gcc/config/aarch64/aarch64-rust.c
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".
2021-05-23 22:43:03 +02:00
bors[bot]
0cad21085b Merge #443 #444 #447
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>
2021-05-23 14:40:17 +00:00
Mark Wielaard
fd95c6cec3 Mention the identifier that was unused in ScanUnused.
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.
2021-05-23 16:26:26 +02:00
Mark Wielaard
5467ac12d7 Fix raw identifier parsing.
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
2021-05-23 16:21:05 +02:00
bors[bot]
251536cdb2 Merge #445 #446
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>
2021-05-23 14:15:14 +00:00
Mark Wielaard
d9a5f670bb Fix assert in rust-buffered-queue peek
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.
2021-05-23 16:10:52 +02:00
Mark Wielaard
9ca4faebe1 Initialize crateNumItr in rust-hir-map to zero.
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.
2021-05-23 12:05:13 +02:00
Mark Wielaard
dcb3a7b62b Fix aarch64 config for rust
Define aarch64_rust_target_cpu_info in aarch64-protos.h.
AARCH64_ISA_V8_1 isn't defined directly, check aarch64_isa_flags.
2021-05-22 03:11:39 +02:00
bors[bot]
99b73780e6 Merge #438
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>
2021-05-21 13:49:46 +00:00
Philip Herron
586d1d8066 DefId is a bit mask of CrateNum & LocalDefId
The DefId was being constructed wrongly by not fully shifting the CrateNum
over to be masked correctly.

Fixes #437
2021-05-21 14:37:33 +01:00
bors[bot]
6e808c647e Merge #436
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>
2021-05-21 10:25:20 +00:00
Thomas Young
41fbeec90c only parse inner_attributes if it start with #! not only #
Fixed #419
2021-05-21 17:59:48 +08:00
bors[bot]
937352288b Merge #372
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>
2021-05-20 11:05:43 +00:00
Philip Herron
4153a8a99b Create CODE_OF_CONDUCT.md
Adding a code of conduct lays out rules that we can all follow in the project.
2021-05-20 12:03:38 +01:00
bors[bot]
ca206dd3bb Merge #393 #431
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>
2021-05-20 08:56:46 +00:00
bors[bot]
05f9e179a8 Merge #433
433: Allow unused underscore identifiers r=philberty a=CohenArthur

This fixes #361 

Co-authored-by: CohenArthur <arthur.cohen@epita.fr>
2021-05-20 08:35:16 +00:00
Marc Poulhiès
033c1a83ab 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.
2021-05-18 21:13:22 +02:00
CohenArthur
f33f618e35 resolve-unused: Check for underscore before warning about unused
identifiers
2021-05-18 19:31:06 +02:00
CohenArthur
30e9cfbf6a name-resolver: Add NodeId to CanonicalPath lookup and reverse mappings 2021-05-18 19:30:20 +02:00
Philip Herron
d89249208a Add issue templates ported from rust-clippy 2021-05-14 15:14:27 +01:00
Philip Herron
39ff3ddc23 Add PR template 2021-05-14 13:45:34 +01:00
Philip Herron
cd7b7ca274 Add link to contributing guidlines 2021-05-14 13:40:18 +01:00
Philip Herron
a027e84a71 remove greetings yml 2021-05-14 13:37:08 +01:00
bors[bot]
4d71539414 Merge #430
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: #305
Fixes: #428

Co-authored-by: Philip Herron <philip.herron@embecosm.com>
2021-05-14 12:13:29 +00:00
bors[bot]
b27c694ae9 Merge #373
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>
2021-05-14 11:51:46 +00:00
Philip Herron
ee53f17812 Create CONTRIBUTING.md
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.
2021-05-14 12:48:34 +01:00
Philip Herron
9bcbfee5f3 Add FNV-128 hash for legacy symbol mangling
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: #305
Fixes: #428
2021-05-14 12:34:24 +01:00
bors[bot]
5d7fbc4a78 Merge #427
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>
2021-05-13 14:36:25 +00:00
Philip Herron
fcd4ed4312 Fix format security warnings
Giving the %s format specifier fixes compiler warnings about the message.
2021-05-13 13:45:03 +01:00
Philip Herron
d326288aa4 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.

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
2021-05-13 12:56:30 +01:00
Philip Herron
a1c148518d Add the identifier to part of fntype signitures
Tracking the identifier helps ensure fntypes are distinct and do not
overlap.
2021-05-12 17:50:57 +01:00
Philip Herron
17258c94f8 Enhance TyTy::ParamType::is_equal
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.
2021-05-12 17:44:03 +01:00
Philip Herron
decdb126e5 Enhance the is_equal for TyTy::FnTypes to account for substitutions
FnTypes signiture might accidently overlap without taking into account
generic type parameters.
2021-05-12 17:24:28 +01:00
bors[bot]
5134aaa9f0 Merge #425
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>
2021-05-11 17:46:10 +00:00
Philip Herron
58e108c7c6 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
2021-05-11 18:09:57 +01:00
Philip Herron
c04343dbab Explicitly track crate names within the mappings
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.
2021-05-11 15:37:19 +01:00
bors[bot]
299d98d8e6 Merge #422
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>
2021-05-11 10:05:43 +00:00
bors[bot]
7c45fcb6e2 Merge #424
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>
2021-05-11 09:40:31 +00:00
Philip Herron
99d1330b79 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
2021-05-10 23:31:49 +01:00
Philip Herron
3ff2b34d5b Types need substitution check needs hardened
When we need to check if a type needs substituted needs to take into
account if all substitutions have been mapped.
2021-05-10 23:27:54 +01:00
Philip Herron
a0e53ef9d1 Resolve method generic arguments
Method calls can have generic arguments which will need resolved before
they can be used.
2021-05-10 21:12:38 +01:00
Philip Herron
338b20ed37 Ensure method resolution resolves to an actual method
We need to check for rustc --explain E0599 so when we have a method call
that it must resolve to an actual method impl item.
2021-05-10 20:19:29 +01:00
Philip Herron
f396811a97 Add testcase to cover case where type param cannot be infered
When the Type paramater is not used we cannot infer the type and we should
error this was fixed in #375.

Fixes #420
2021-05-10 14:22:40 +01:00
Philip Herron
e0c5afe70d Only infer substitutions for type parameters which need it
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.
2021-05-10 13:55:42 +01:00
Philip Herron
02f08eef46 Ensure generic arguments are resolved for MethodCallExpr
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.
2021-05-10 12:24:50 +01:00
Philip Herron
4fa08ea79c Add is method flag for FnTypes
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.
2021-05-10 12:21:11 +01:00
Philip Herron
4fd7b3c089 Ensure we lower the generic params for impl items
Inherit impl items can have generic parameters and must be preserved into
the HIR trees in order for the type params to be resolved.

Fixes #417
2021-05-10 12:08:14 +01:00
bors[bot]
7e66d68318 Merge #416
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>
2021-05-07 16:38:55 +00:00
Philip Herron
9428db6328 We need to monomorphize tuples as well as ADT's
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
2021-05-07 16:52:06 +01:00
bors[bot]
9fdb4b6aff Merge #410
410: Fix #407, #409 testcases r=philberty a=tschwinge

@teromene, for your information/learning.  ;-D

Co-authored-by: Thomas Schwinge <thomas@codesourcery.com>
2021-05-06 09:28:35 +00:00
bors[bot]
0824b2ed1f Merge #411
411: A little bit of testsuite tuning r=philberty a=tschwinge



Co-authored-by: Thomas Schwinge <thomas@codesourcery.com>
2021-05-06 08:42:20 +00:00
Thomas Schwinge
9a0a655cd0 Fix 'dg-error' directive in 'rust.test/xfail_compile/func2.rs' [#301]
This allows removing the 'dg-excess-errors' directive, yay!
2021-05-05 23:17:27 +02:00
Thomas Schwinge
949d9de3f4 Fix 'dg-error' directive in 'rust.test/xfail_compile/break2.rs' [#301]
This allows removing the 'dg-excess-errors' directive, yay!
2021-05-05 23:17:27 +02:00
Thomas Schwinge
03e30ba43a Fix (and XFAIL) 'dg-error' directives in 'rust.test/xfail_compile/generics6.rs' [#358] 2021-05-05 23:17:18 +02:00
Thomas Schwinge
e4a4ebd316 In DejaGnu directives, simplify 'target { *-*-* }' to 'target *-*-*'
No change in behavior.
2021-05-05 23:03:18 +02:00
Thomas Schwinge
97dddb606f Add 'rust.test/xfail_compile/issue-407-2.rs' [#407, #409]
This adds the testcase originally presented in #407, which is fixed by the #409
code changes.
2021-05-05 22:36:29 +02:00
Thomas Schwinge
613eeee78a Add note to 'rust.test/xfail_compile/issue-407.rs' [#407, #409] 2021-05-05 22:36:23 +02:00
Thomas Schwinge
d29b5c5ac3 Use standard 'dg-excess-errors' directive comment in 'rust.test/xfail_compile/issue-407.rs' [#409] 2021-05-05 22:36:19 +02:00
Thomas Schwinge
843547eb48 Fix 'dg-error' directive in 'rust.test/xfail_compile/issue-407.rs' [#409]
..., so that this actually does verify the error diagnostic.
2021-05-05 22:35:54 +02:00
bors[bot]
b96ab2e1a9 Merge #409
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>
2021-05-05 18:24:20 +00:00
Lyra
09ec48621f Fix clang formatting and include a test 2021-05-05 19:47:27 +02:00
Lyra
e355d22a21 Throw error instead of crashing when a whitespace is encountered within an assignment operation 2021-05-05 19:00:33 +02:00
bors[bot]
082161121c Merge #406
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>
2021-05-05 10:01:14 +00:00
Philip Herron
fad543c8b8 Add locations to implicit inference variables and partially revert 91c5b94
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
2021-05-05 10:52:32 +01:00
bors[bot]
b1dcbc3d8e Merge #401
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>
2021-04-30 16:16:38 +00:00
Philip Herron
2216cab0c9 Defaults to type params are not allowed here 2021-04-30 17:10:00 +01:00
Philip Herron
feaafdfecf Apply defaults if available to type substitutions
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
2021-04-30 15:50:16 +01:00
bors[bot]
0276ec39a9 Merge #399
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>
2021-04-30 10:58:23 +00:00
Philip Herron
b7d95ea80b Add initial support for defaults on generic parameters
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
2021-04-30 11:57:48 +01:00
Marc Poulhiès
91ca22c7b9 Basic support for lifetime parameter
This change allow for basic lifetime usage. Only syntax is checked, nothing
more. Goal is to be able to compile known-to-be-valid code.

Addresses #359
2021-04-30 10:39:39 +01:00
Philip Herron
ffa45bed5e Typecheck the default type on TypeParam 2021-04-30 10:08:15 +01:00
Philip Herron
682cae549a Add missing comment for override_context 2021-04-29 18:38:51 +01:00
Philip Herron
5d9855c69a Refactor to GenericParam to TypeParam in parameter mappings
When we have Parameter mappings these _must_ be TypeParams this allows us
to access the specified defaults if they exist.
2021-04-29 18:32:15 +01:00
Philip Herron
c1296bc68e Add HIR lowering for GenericBindingArgs
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.
2021-04-29 14:44:51 +01:00
Philip Herron
eb2c6124c4 Improve error messages of unexpected arguments
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.
2021-04-29 14:19:36 +01:00
bors[bot]
f189f5bbab Merge #398
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>
2021-04-28 12:22:11 +00:00
Philip Herron
e547f7da58 Tuples can contain TypeParameters
TypeParameters can be behind held within Tuples which need substitution but
these types cannot hold substitution mappings.

Fixes #396
2021-04-28 12:49:41 +01:00
Philip Herron
ff1676e277 Reference types can contain TypeParameters
TypeParameters can be behind ReferenceTypes which needs substitution but
these types cannot hold substitution mappings.

Fixes #396
2021-04-28 12:47:44 +01:00
bors[bot]
62bcc93ece Merge #397
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>
2021-04-28 10:32:35 +00:00
Philip Herron
3539a0392f Name resolve any specified types in TypeParams
Type parameters can have defaults these need to be name resolved.

Addresses: #307
2021-04-27 17:43:07 +01:00
bors[bot]
6647bc65b1 Merge #394
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>
2021-04-27 14:39:54 +00:00
Philip Herron
3df65d5b4e Support partial substitution's
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
2021-04-27 13:52:34 +01:00
Philip Herron
f1c6f7da67 When we resolve a Path to Self we cannot infer any substitions
In rust ParamTy represents type parameters and this works in this context
if we infer all parameters it breaks type checking here.
2021-04-27 13:41:53 +01:00
bors[bot]
a24a14371b Merge #390
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>
2021-04-25 17:14:16 +00:00
lrh2000
e57b6895de Clean up the compilation of block expressions 2021-04-25 23:51:33 +08:00
bors[bot]
e5aedbbb24 Merge #388
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>
2021-04-25 15:37:51 +00:00
bors[bot]
041003da86 Merge #387
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>
2021-04-25 15:10:08 +00:00
CohenArthur
8ee80abd2f IfLetExpr: Assign outer_attrs in constructor
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.
2021-04-25 17:07:34 +02:00
lrh2000
f48c7e87c5 Don't remove unreachable statements at HIR lowering 2021-04-24 15:21:31 +08:00
bors[bot]
de9af784e7 Merge #380
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>
2021-04-23 09:13:59 +00:00
lrh2000
28895c1265 Merge branch 'origin/master' 2021-04-22 22:05:12 +08:00
Philip Herron
dd3c58b2ce Remove old libgrust lib this needs to be redone later on. 2021-04-22 13:41:37 +01:00
bors[bot]
bb85500ecc Merge #383
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>
2021-04-22 12:04:06 +00:00
bors[bot]
dd194669e3 Merge #384
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>
2021-04-21 18:03:15 +00:00
Marc Poulhiès
de5d648043 Fix dg-ice handling in rust testsuite
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
2021-04-21 19:54:43 +02:00
Philip Herron
393b783549 Reuse fold-const.c from GCC to enforce const array capacities
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
2021-04-20 18:56:53 +01:00
bors[bot]
ee5afc03f9 Merge #381
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>
2021-04-20 10:22:59 +00:00
Philip Herron
bb103b62d4 Add missing testcase 2021-04-19 16:52:04 +01:00
Philip Herron
b3dfc9f1f9 Fix crash on empty parameters to generic data type
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
2021-04-19 16:29:18 +01:00
lrh2000
3aeb9f4718 Introduce limited support for the never type 2021-04-18 10:21:37 +08:00
lrh2000
c5fdf8cc54 The trailing expression is not necessarily without a block 2021-04-18 10:11:53 +08:00
bors[bot]
498758a1c2 Merge #374
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: #97 
Fixes: #327 

Co-authored-by: Philip Herron <philip.herron@embecosm.com>
2021-04-17 16:53:30 +00:00
Philip Herron
5b8de2be3a Fix testcase to add missing dg-error since rebase against master
We are getting an extra emition of an error since the rebase and changes to
can_eq.
2021-04-17 17:52:04 +01:00
Philip Herron
2b7807f0ac Enable RichLocations for multiple candidate errors in Path resolution
This means we get a single error for the failure but still see the location
for each dup.
2021-04-17 17:51:25 +01:00
Philip Herron
01486c1413 Remove fatal error
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
2021-04-17 16:45:43 +01:00
Philip Herron
ed651fcdec Add basic wrapper over gcc rich_location
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
2021-04-17 16:45:43 +01:00
bors[bot]
f958d17177 Merge #378
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>
2021-04-17 14:42:02 +00:00
bors[bot]
3ee4bf774c Merge #377
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>
2021-04-17 14:13:12 +00:00
Philip Herron
9c53eb530a Add Check for unconstrained type parameters
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
2021-04-16 17:07:56 +01:00
Philip Herron
ee247029ac Fix crash when mapping of Generic argument changes.
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
2021-04-16 16:08:55 +01:00
bors[bot]
935aff52a6 Merge #369
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>
2021-04-14 15:16:16 +00:00
YizhePKU
f5f32fb4a3 Implement the inline visitor 2021-04-13 12:58:41 +00:00
Philip Herron
ce593f09f4 Add BORS badge to README.md 2021-04-13 12:25:43 +01:00
bors[bot]
636ad7d95e Merge #358
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>
2021-04-13 10:50:13 +00:00
Philip Herron
4ee35b6edb Add missing dg-warning annotations
Adding extra annotations means changes in compiler behaviour are caught
faster so as to avoid regressions more aggressively.
2021-04-13 09:50:10 +01:00
Philip Herron
2f62f936ab Add check for duplicate overlapping impl-items
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
2021-04-12 22:39:45 +01:00
Philip Herron
7e4ca97cac Refactor Method resolution to take advantage of PathProbe
This canonicalizes method resolution to the Path Probe used for Path expr
resolution. So any errors will gain the same diagnostics.
2021-04-12 22:39:45 +01:00
Philip Herron
85f5874106 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:

  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 #353

Fixes #355 #335 #325
2021-04-12 22:39:45 +01:00
Philip Herron
5fe4984806 Add path probe for inherent impl item candidates
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.
2021-04-12 22:39:45 +01:00
Philip Herron
f98ccb3a0b Refactor backend PathInExpr
This method only ever should accept HIR::PathInExpressions.
2021-04-12 22:39:45 +01:00
Philip Herron
826ce3c92d Add impl mappings to inherent impl items
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.
2021-04-12 22:39:45 +01:00
Philip Herron
3fa740f4ff Add TyTy::BaseType::can_eq method to tyty module
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.
2021-04-12 22:39:45 +01:00
Philip Herron
0c5a6af749 Unify ADTRules needs to check identifier
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.
2021-04-12 22:39:45 +01:00
Philip Herron
c3499198a9 Seperate look for undetermined types post type resolution
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.
2021-04-12 22:39:45 +01:00
bors[bot]
ca8744db3e Merge #362
362: [testsuite] Scan for warning diagnostics, too r=philberty a=tschwinge



Co-authored-by: Thomas Schwinge <thomas@codesourcery.com>
2021-04-12 20:32:05 +00:00
Thomas Schwinge
4a2e0fc882 [testsuite] Scan for warning diagnostics, too
..., 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".
2021-04-12 22:16:37 +02:00
Thomas Schwinge
be8828307f [testsuite] In 'additional_prunes' look for explicit 'error: ' instead of 'error' [#281, #301]
... so that if the filename contains 'error', this doesn't anymore trigger for
the current 'Attempting to parse file: [...]' diagnostic.
2021-04-12 21:53:19 +02:00
Thomas Schwinge
ec12749925 [testsuite] Append to 'additional_prunes' [#281, #301]
... to not overwrite what might already have been added elsewhere.
2021-04-12 21:53:19 +02:00
bors[bot]
5439d353fe Merge #365
365: add more path to collect live symbols r=tschwinge a=thomasyonug

Addresses #363

Co-authored-by: Thomas Young <wenzhang5800@gmail.com>
2021-04-12 19:49:44 +00:00
Thomas Young
5b9f4f94b8 add more path to collect live symbols
Addresses #363
2021-04-12 22:11:19 +08:00
bors[bot]
edc4a95491 Merge #348
348: Address miscellaneous '-Werror=unused-parameter' diagnostics [#336] r=philberty a=tschwinge

#336

    In file included from [...]/gcc/rust/ast/rust-ast-full.h:23,
                     from [...]/gcc/rust/parse/rust-parse.h:21,
                     from [...]/gcc/rust/rust-session-manager.cc:34:
    [...]/gcc/rust/ast/rust-expr.h: In member function ‘virtual void Rust::AST::RangeExpr::set_outer_attrs(std::vector<Rust::AST::Attribute>)’:
    [...]/gcc/rust/ast/rust-expr.h:3220:48: error: unused parameter ‘new_attrs’ [-Werror=unused-parameter]
     3220 |   void set_outer_attrs (std::vector<Attribute> new_attrs) override
          |                         ~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~
    [...]/gcc/rust/ast/rust-expr.h: In constructor ‘Rust::AST::IfLetExpr::IfLetExpr(std::vector<std::unique_ptr<Rust::AST::Pattern> >, std::unique_ptr<Rust::AST::Expr>, std::unique_ptr<Rust::AST::BlockExpr>, std::vector<Rust::AST::Attribute>, Location)’:
    [...]/gcc/rust/ast/rust-expr.h:4380:37: error: unused parameter ‘outer_attrs’ [-Werror=unused-parameter]
     4380 |              std::vector<Attribute> outer_attrs, Location locus)
          |              ~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~

    In file included from [...]/gcc/rust/backend/rust-compile-context.h:27,
                     from [...]/gcc/rust/backend/rust-compile.h:24,
                     from [...]/gcc/rust/rust-session-manager.cc:41:
    [...]/gcc/rust/backend/rust-compile-tyty.h: In member function ‘virtual void Rust::Compile::TyTyCompile::visit(Rust::TyTy::FnPtr&)’:
    [...]/gcc/rust/backend/rust-compile-tyty.h:67:28: error: unused parameter ‘type’ [-Werror=unused-parameter]
       67 |   void visit (TyTy::FnPtr &type) override { gcc_unreachable (); }
          |               ~~~~~~~~~~~~~^~~~

    [...]/gcc/rust/rust-gcc.cc: In member function ‘virtual Btype* Gcc_backend::function_ptr_type(Btype*, const std::vector<Btype*>&, Location)’:
    [...]/gcc/rust/rust-gcc.cc:998:42: error: unused parameter ‘locus’ [-Werror=unused-parameter]
      998 |                                 Location locus)
          |                                 ~~~~~~~~~^~~~~

    [...]/gcc/rust/rust-lang.cc: In function ‘void grs_langhook_init_options_struct(gcc_options*)’:
    [...]/gcc/rust/rust-lang.cc:153:55: error: unused parameter ‘opts’ [-Werror=unused-parameter]
      153 | grs_langhook_init_options_struct (struct gcc_options *opts)
          |                                   ~~~~~~~~~~~~~~~~~~~~^~~~

Co-authored-by: Thomas Schwinge <thomas@codesourcery.com>
2021-04-10 16:59:05 +00:00
bors[bot]
9c97c85883 Merge #357
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>
2021-04-09 20:32:21 +00:00
Thomas Young
acb0062081 Add unused code pass
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
2021-04-09 18:10:41 +08:00
bors[bot]
85bd4cef64 Merge #288
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>
2021-04-09 09:32:30 +00:00
YizhePKU
90d5337d97 Fix typo 2021-04-09 02:59:41 +00:00
YizhePKU
f2941c7d59 Fix formatting 2021-04-09 02:54:10 +00:00
YizhePKU
5c14e5f9c7 Merge branch 'master' into fix-zero-length-array-2 2021-04-09 10:37:53 +08:00
YizhePKU
5da07eb33b Use TyVar::get_implict_infer_var to cleanup 2021-04-08 04:02:50 +00:00
bors[bot]
4937562f7c Merge #331
331: Initial bors-ng integration r=philberty a=dkm

Github Action only triggered on bors-ng controlled branches (trying/staging).
Fixes #324

Co-authored-by: Marc Poulhiès <dkm@kataplop.net>
2021-04-06 09:22:58 +00:00
Marc Poulhiès
777ef8a74c Initial bors-ng integration
Github Action only triggered on bors-ng controlled branches (trying/staging).
Fixes #324
2021-04-05 19:59:27 +02:00
Philip Herron
2800f4499f Add GCC bootstrap badge 2021-04-05 14:27:42 +01:00
Philip Herron
112495e257 Add bootstrap build based off our normal build which tests the status of bootstrap builds 2021-04-05 11:10:02 +01:00
Philip Herron
6acea40379 Fix formatting of files from bootstrap fixes 2021-04-05 11:05:44 +01:00
Thomas Schwinge
9de710767f Address '[...]/gcc/rust/rust-target.h:23: error: "DEFHOOK" redefined' diagnostic [#336] 2021-04-05 11:03:55 +01:00
Thomas Schwinge
da8f950b26 Address 'gcc/rust/typecheck/rust-tyty.h' '-Werror=unused-parameter' diagnostics [#336]
In file included from [...]/gcc/rust/typecheck/rust-hir-type-check.h:24,
                     from [...]/gcc/rust/resolve/rust-name-resolver.h:24,
                     from [...]/gcc/rust/resolve/rust-ast-resolve.h:22,
                     from [...]/gcc/rust/rust-session-manager.cc:36:
    [...]/gcc/rust/typecheck/rust-tyty.h: In constructor ‘Rust::TyTy::USizeType::USizeType(Rust::HirId, std::set<unsigned int>)’:
    [...]/gcc/rust/typecheck/rust-tyty.h:972:41: error: unused parameter ‘refs’ [-Werror=unused-parameter]
      972 |   USizeType (HirId ref, std::set<HirId> refs = std::set<HirId> ())
          |                         ~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~
    [...]/gcc/rust/typecheck/rust-tyty.h: In constructor ‘Rust::TyTy::USizeType::USizeType(Rust::HirId, Rust::HirId, std::set<unsigned int>)’:
    [...]/gcc/rust/typecheck/rust-tyty.h:976:55: error: unused parameter ‘refs’ [-Werror=unused-parameter]
      976 |   USizeType (HirId ref, HirId ty_ref, std::set<HirId> refs = std::set<HirId> ())
          |                                       ~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~
    [...]/gcc/rust/typecheck/rust-tyty.h: In constructor ‘Rust::TyTy::ISizeType::ISizeType(Rust::HirId, std::set<unsigned int>)’:
    [...]/gcc/rust/typecheck/rust-tyty.h:994:41: error: unused parameter ‘refs’ [-Werror=unused-parameter]
      994 |   ISizeType (HirId ref, std::set<HirId> refs = std::set<HirId> ())
          |                         ~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~
    [...]/gcc/rust/typecheck/rust-tyty.h: In constructor ‘Rust::TyTy::ISizeType::ISizeType(Rust::HirId, Rust::HirId, std::set<unsigned int>)’:
    [...]/gcc/rust/typecheck/rust-tyty.h:998:55: error: unused parameter ‘refs’ [-Werror=unused-parameter]
      998 |   ISizeType (HirId ref, HirId ty_ref, std::set<HirId> refs = std::set<HirId> ())
          |                                       ~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~
    [...]/gcc/rust/typecheck/rust-tyty.h: In constructor ‘Rust::TyTy::CharType::CharType(Rust::HirId, std::set<unsigned int>)’:
    [...]/gcc/rust/typecheck/rust-tyty.h:1016:40: error: unused parameter ‘refs’ [-Werror=unused-parameter]
     1016 |   CharType (HirId ref, std::set<HirId> refs = std::set<HirId> ())
          |                        ~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~
    [...]/gcc/rust/typecheck/rust-tyty.h: In constructor ‘Rust::TyTy::CharType::CharType(Rust::HirId, Rust::HirId, std::set<unsigned int>)’:
    [...]/gcc/rust/typecheck/rust-tyty.h:1020:54: error: unused parameter ‘refs’ [-Werror=unused-parameter]
     1020 |   CharType (HirId ref, HirId ty_ref, std::set<HirId> refs = std::set<HirId> ())
          |                                      ~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~
    [...]/gcc/rust/typecheck/rust-tyty.h: In constructor ‘Rust::TyTy::ReferenceType::ReferenceType(Rust::HirId, Rust::TyTy::TyVar, std::set<unsigned int>)’:
    [...]/gcc/rust/typecheck/rust-tyty.h:1040:34: error: unused parameter ‘refs’ [-Werror=unused-parameter]
     1040 |                  std::set<HirId> refs = std::set<HirId> ())
          |                  ~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~
    [...]/gcc/rust/typecheck/rust-tyty.h: In constructor ‘Rust::TyTy::ReferenceType::ReferenceType(Rust::HirId, Rust::HirId, Rust::TyTy::TyVar, std::set<unsigned int>)’:
    [...]/gcc/rust/typecheck/rust-tyty.h:1045:34: error: unused parameter ‘refs’ [-Werror=unused-parameter]
     1045 |                  std::set<HirId> refs = std::set<HirId> ())
          |                  ~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~
    [...]/gcc/rust/typecheck/rust-tyty.h: In constructor ‘Rust::TyTy::StrType::StrType(Rust::HirId, std::set<unsigned int>)’:
    [...]/gcc/rust/typecheck/rust-tyty.h:1070:39: error: unused parameter ‘refs’ [-Werror=unused-parameter]
     1070 |   StrType (HirId ref, std::set<HirId> refs = std::set<HirId> ())
          |                       ~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~
    [...]/gcc/rust/typecheck/rust-tyty.h: In constructor ‘Rust::TyTy::StrType::StrType(Rust::HirId, Rust::HirId, std::set<unsigned int>)’:
    [...]/gcc/rust/typecheck/rust-tyty.h:1074:53: error: unused parameter ‘refs’ [-Werror=unused-parameter]
     1074 |   StrType (HirId ref, HirId ty_ref, std::set<HirId> refs = std::set<HirId> ())
          |                                     ~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~
2021-04-05 11:01:47 +01:00
Philip Herron
cb8b27a423 Fix formatting of file from merge of bootstrapping build fixes 2021-04-05 10:57:11 +01:00
Thomas Schwinge
21522a8141 Address 'error: ‘*<unknown>.Rust::HIR::ArrayType::<anonymous>.Rust::HIR::TypeNoBounds::<anonymous>.Rust::HIR::Type::mappings’ is used uninitialized [-Werror=uninitialized]' diagnostic [#336]
... 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 ()),
          |                     ^~~~~~~~
2021-04-05 10:54:13 +01:00
Thomas Schwinge
f0ad7aefdc Address '[...]/gcc/rust/expand/rust-macro-expand.cc:3228:1: error: control reaches end of non-void function [-Werror=return-type]' diagnostic [#336]
The only caller is currently '#if 0'ed, too.
2021-04-05 10:48:43 +01:00
Thomas Schwinge
419b492b39 Address '[...]/gcc/rust/parse/rust-parse-impl.h:8575:8: error: variable ‘has_leading_pipe’ set but not used [-Werror=unused-but-set-variable]' diagnostic [#336] 2021-04-05 10:46:27 +01:00
Thomas Schwinge
106f622600 Placate GCC 4.8
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;
                 ^
2021-04-05 10:45:58 +01:00
Thomas Schwinge
d1cbfc670f Address '[...]/gcc/rust/rust-diagnostics.cc:198:38: error: function ‘void rust_debug(Location, const char*, ...)’ might be a candidate for ‘gnu_printf’ format attribute [-Werror=suggest-attribute=format]' diagnostic [#336] 2021-04-05 10:45:25 +01:00
Thomas Schwinge
6b03dff440 Address 'error: ‘kind’ may be used uninitialized in this function [-Werror=maybe-uninitialized]' diagnostic [#336]
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;
          |                                         ^~~~
2021-04-05 10:44:33 +01:00
Thomas Schwinge
348a883eb8 Address 'error: ‘*<unknown>.Rust::HIR::QualifiedPathInType::<anonymous>.Rust::HIR::TypeNoBounds::<anonymous>.Rust::HIR::Type::mappings’ is used uninitialized [-Werror=uninitialized]' diagnostic [#336]
... 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)
          |                     ^~~~~~~~
2021-04-05 10:44:15 +01:00
Thomas Schwinge
2e1a7f6a72 Address '[...]/gcc/rust/lex/rust-lex.cc:433:30: error: too many arguments for format [-Werror=format-extra-args]' diagnostic [#336] 2021-04-05 10:42:32 +01:00
Thomas Schwinge
868ce1ffdd Address 'error: ‘op’ may be used uninitialized in this function [-Werror=maybe-uninitialized]' diagnostic [#336]
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;
          |                                 ^~
2021-04-05 10:38:57 +01:00
Thomas Schwinge
c896b25539 Address '[...]/gcc/rust/rust-session-manager.cc:124:15: error: unused variable ‘target’ [-Werror=unused-variable]' diagnostic [#336] 2021-04-05 10:38:18 +01:00
Thomas Schwinge
7d3616a63b Address '[...]/gcc/rust/parse/rust-parse-impl.h:4896:8: error: variable ‘has_colon’ set but not used [-Werror=unused-but-set-variable]' diagnostic [#336] 2021-04-05 10:37:11 +01:00
Thomas Schwinge
62550489ce Merge commit '7c1e856bedb4ae190c420ec2d2ca5e08730cf21d' [#247] 2021-04-02 22:56:26 +02:00
Thomas Schwinge
114bd7b45e Address miscellaneous '-Werror=unused-parameter' diagnostics [#336]
In file included from [...]/gcc/rust/ast/rust-ast-full.h:23,
                     from [...]/gcc/rust/parse/rust-parse.h:21,
                     from [...]/gcc/rust/rust-session-manager.cc:34:
    [...]/gcc/rust/ast/rust-expr.h: In member function ‘virtual void Rust::AST::RangeExpr::set_outer_attrs(std::vector<Rust::AST::Attribute>)’:
    [...]/gcc/rust/ast/rust-expr.h:3220:48: error: unused parameter ‘new_attrs’ [-Werror=unused-parameter]
     3220 |   void set_outer_attrs (std::vector<Attribute> new_attrs) override
          |                         ~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~
    [...]/gcc/rust/ast/rust-expr.h: In constructor ‘Rust::AST::IfLetExpr::IfLetExpr(std::vector<std::unique_ptr<Rust::AST::Pattern> >, std::unique_ptr<Rust::AST::Expr>, std::unique_ptr<Rust::AST::BlockExpr>, std::vector<Rust::AST::Attribute>, Location)’:
    [...]/gcc/rust/ast/rust-expr.h:4380:37: error: unused parameter ‘outer_attrs’ [-Werror=unused-parameter]
     4380 |              std::vector<Attribute> outer_attrs, Location locus)
          |              ~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~

    In file included from [...]/gcc/rust/backend/rust-compile-context.h:27,
                     from [...]/gcc/rust/backend/rust-compile.h:24,
                     from [...]/gcc/rust/rust-session-manager.cc:41:
    [...]/gcc/rust/backend/rust-compile-tyty.h: In member function ‘virtual void Rust::Compile::TyTyCompile::visit(Rust::TyTy::FnPtr&)’:
    [...]/gcc/rust/backend/rust-compile-tyty.h:67:28: error: unused parameter ‘type’ [-Werror=unused-parameter]
       67 |   void visit (TyTy::FnPtr &type) override { gcc_unreachable (); }
          |               ~~~~~~~~~~~~~^~~~

    [...]/gcc/rust/rust-gcc.cc: In member function ‘virtual Btype* Gcc_backend::function_ptr_type(Btype*, const std::vector<Btype*>&, Location)’:
    [...]/gcc/rust/rust-gcc.cc:998:42: error: unused parameter ‘locus’ [-Werror=unused-parameter]
      998 |                                 Location locus)
          |                                 ~~~~~~~~~^~~~~

    [...]/gcc/rust/rust-lang.cc: In function ‘void grs_langhook_init_options_struct(gcc_options*)’:
    [...]/gcc/rust/rust-lang.cc:153:55: error: unused parameter ‘opts’ [-Werror=unused-parameter]
      153 | grs_langhook_init_options_struct (struct gcc_options *opts)
          |                                   ~~~~~~~~~~~~~~~~~~~~^~~~
2021-04-02 21:39:39 +02:00
YizhePKU
a707707b97 Add dg-error directive to tests 2021-04-02 17:41:42 +00:00
YizhePKU
85a3a9866c Add tests 2021-04-02 17:12:41 +00:00
Yizhe
4b995062b7 Fix formatting 2021-04-02 17:11:12 +00:00
Yizhe
dac1de7fde Fix include 2021-04-02 17:10:47 +00:00
Yizhe
63697c37cf Add the new InferType to lookup table 2021-04-02 17:10:46 +00:00
Yizhe
f12d8b770b Fix out-of-bound-array-access in type checking 2021-04-02 17:10:45 +00:00
Yizhe
2ba543eb04 Modify parser to generate empty ArrayElemsValues instead of nullptr 2021-04-02 17:10:44 +00:00
Yizhe
d71750b782 Remove ArrayExpr::has_array_elems
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.
2021-04-02 17:10:43 +00:00
Yizhe
0a63f6d619 Disallow nullptr in ArrayExpr
We'll maintain it as an invariant.
2021-04-02 17:10:42 +00:00
Yizhe
d4f8f92142 Backport std::unique_ptr
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.
2021-04-02 17:10:41 +00:00
Marc Poulhiès
e997db0443 Add dg-error to generics4.rs xfail test
Having at least one dg-error and not only dg-excess-error should avoid silent
regression.
2021-04-01 10:42:29 +01:00
Marc Poulhiès
c044fda54b Fix CI checks
Checking for 'unexpected' will also catch XFAIL tests being PASS.
2021-04-01 10:34:35 +01:00
Thomas Schwinge
16b1b9579d 'rust.test/xfail_compile/cfg_attr.rs' -> 'rust.test/compile/cfg_attr.rs' [#319]
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'.
2021-04-01 10:27:12 +02:00
Philip Herron
4aa5396e5c Fixed bug TyTy::SubstitutionRef::needs_substitution
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
2021-03-31 18:22:02 +01:00
Philip Herron
d7593fec92 Add support for TypeAlias
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
2021-03-31 09:45:07 +01:00
Philip Herron
67ed1e36ce Fix bad tracking on used substitutions on generic types.
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.
2021-03-31 09:45:07 +01:00
Marc Poulhiès
f3275df08d Minor changes in README.md
Fix minor mistakes.
2021-03-30 12:18:12 +01:00
Marc Poulhiès
6241824197 Minor change in README.md
Add some details that can help during debugging.
fixes #309
2021-03-29 20:09:23 +01:00
CohenArthur
ff1eca9a57 Fix infinite loop when expanding cfg attributes (#319)
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
2021-03-29 20:08:21 +01:00
Philip Herron
099fcbd107 Add missing testcase for generics 2021-03-29 12:04:21 +01:00
Marc Poulhiès
cf10b02588 Fix tests after several PR were merged
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.
2021-03-28 11:02:34 +02:00
Philip Herron
e4ea09d6b8 Add Generic Impl block support
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
2021-03-27 18:55:14 +00:00
Philip Herron
380c829505 Init NodeId for NodeMappings on HIR::MethodCallExpr
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
2021-03-27 18:55:14 +00:00
Philip Herron
573120551a Add generics for impl blocks
Generics paramters to impl blocks allows each impl-item to inherit these
and get handled in a similar way as to normal functions.

Fixes #237
2021-03-27 18:55:14 +00:00
Philip Herron
e9bb91b4a7 Fix bad merge of test case to new TestSuite structure 2021-03-27 18:15:43 +00:00
Marc Poulhiès
e77c44ef26 Fix error while unexpected EOF when scanning for end of comment
Emit an error when EOF is reached before end of C-style comment.
Add corresponding test for non regression.

fix #300
2021-03-27 18:07:49 +00:00
Marc Poulhiès
fabb3894d5 WIP for #252
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.
2021-03-27 18:03:34 +00:00
Marc Poulhiès
f9f1f1d721 Refactor DejaGNU testsuite
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
2021-03-27 18:02:51 +00:00
Philip Herron
6be4ce99d5 Add missing location info into TypePath
This improves errors messages with the source location info for the error.
2021-03-25 17:37:14 +00:00
Philip Herron
08b49a3e52 Cleanup TypeKindFormat
There is no need to break after a return in this switch statement.
2021-03-23 11:09:24 +00:00
Ansh Tyagi
aca7b5d26b added to_string() for TyTy::TypeKind
This is a building block to improve debugging of the TyTy module.

Fixes: #284
2021-03-23 09:51:55 +00:00
George Liakopoulos
eaeeb78a8b update README.md (#299)
Add example to extend your PATH for GCC installs
2021-03-23 09:46:49 +00:00
Philip Herron
280ac5bd99 Generics continued this adds more type resolution to ADT and Functions
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
2021-03-22 20:01:30 +00:00
Thomas Young
eb33139efa refactor TypeResolution Resolve with new InferType::default_type and defaulting float to f64 2021-03-22 09:36:59 +00:00
Philip Herron
0b061cb099 Reduce nesting to cleanup formatting of the unify function.
If there is a failure in type resolution we can return early to reduce
nesting
2021-03-19 08:44:25 +00:00
Philip Herron
1b0076675d Pop return type context after resolving the block.
If type inference fails on the BlockExpr vs the expected return type,
we will accidently leave trailing context on the return type stack.
2021-03-19 08:44:25 +00:00
Philip Herron
f0750d7091 Fix type unification for Inference Variables and return types
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
2021-03-19 08:44:25 +00:00
Philip Herron
196476601e Add TyTy::BaseType::debug interface
Calling debug() will printf akin to ctx->backend()->debug(tree). This
makes debug information simpler when it comes to GDB sessions.
2021-03-19 08:44:25 +00:00
Marc Poulhiès
da073ad52c Fix last remaining Woverloaded-virtual
Add using clause for UnitRules.

Add -Werror=overloaded-virtual to avoid regressing on this warning.
2021-03-18 10:03:11 +00:00
The Other
3f361bd362 Modify parser error message reporting system to allow recovery (#290)
Added new parser Error struct

This is to make the parser reusable for macro expansion.
2021-03-18 09:27:01 +00:00
Marc Poulhiès
0581e64df9 Fix Backend:: mark 2 methods pure
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.
2021-03-18 09:21:13 +00:00
Marc Poulhiès
837e9d75b7 Typo fix in substition
Replace all occurences of [Ss]ubstition[s] by [Ss]ubstition[s].
2021-03-18 09:18:07 +00:00
George Liakopoulos
fbe9e08d95 Add more examples for compiler usage via Docker
Add examples to create an executable, emit assembly and emit the internal debug outputs from the compiler.

Fixes #279
2021-03-15 15:34:08 +00:00
therealansh
73c0f6ab2b refactored class TyCtx to TyVar 2021-03-15 10:15:15 +00:00
Serentty
6255b77717 Fix typo in README 2021-03-15 09:40:20 +00:00
therealansh
b563491f40 CI: build using -j (nproc)
Signed-off-by: therealansh <tyagiansh23@hotmail.com>
2021-03-14 18:35:55 +00:00
Marc Poulhiès
173bff7f12 Fix Woverloaded-virtual warnings.
Fix warnings from -Woverloaded-virtual.
Fix #274
2021-03-14 18:35:34 +00:00
Marc Poulhiès
b854955612 Remove unused header inclusions.
Both headers are not used and trigger warning on DEFHOOK macros redefinitions.
2021-03-10 09:51:56 +00:00
Philip Herron
049d0cba8e Cleanup HIR::Function to make fields private
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.
2021-03-09 18:18:35 +00:00
Philip Herron
01898e7cf2 Separate function definitions from function pointers.
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
2021-03-09 18:18:35 +00:00
Philip Herron
0b35f5f10d Cleanup Formatting for is_equal on TupleTypes 2021-03-09 18:18:35 +00:00
Philip Herron
6212572b23 Introduce TyCtx wrapper over TyTy Types with elements than can change.
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.
2021-03-09 18:18:35 +00:00
Philip Herron
99980cbb5e Missing const on method
Getting mappings can be const in order to get mappings info on Types.
2021-03-09 18:18:35 +00:00
Philip Herron
537f59bdef Fix bug when using general 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
2021-03-09 18:18:35 +00:00
Marc Poulhiès
670da01832 Remove useless file.
fix #98
2021-03-05 17:48:26 +00:00
Philip Herron
a886a9c06e Add in TyTy support for an initial String Literal
This gives the apropriate reference type over const char *.

Fixes #85
2021-03-03 22:46:24 +00:00
Philip Herron
e76855ab40 Add missing copright header 2021-03-02 18:20:01 +00:00
Philip Herron
65e06883b0 Fix bad type resolution on deadcode1.rs and implicit_return_err1.rs
There was a subtle tweak to checking wether this is the actual final
statement of the block to verify the types.
2021-03-01 12:41:45 +00:00
Philip Herron
2a7cbe4fd9 Ensure compilation fails when Struct is constructed with CallExpr
CallExpr is only used for TupleStructs, so this needs to refelect rustc
behaviour.
2021-03-01 12:41:45 +00:00
Philip Herron
f879526899 Fix bug when assembling function names with :: in the symbol
When the assembler comes along Foo::new as a symbol name it will fail
we need name mangling to fix this properly.
2021-03-01 12:41:45 +00:00
Yizhe
0c13515af7 If the compiler crashes we fail the test 2021-03-01 10:43:13 +00:00
Yizhe
6f10357376 Fix formatting 2021-03-01 10:42:27 +00:00
Yizhe
4ebeb3165c Modify the parser to use the new enums 2021-03-01 10:42:27 +00:00
Yizhe
875bda0637 Modify AST and HIR code to use the new enums 2021-03-01 10:42:27 +00:00
Yizhe
1b857e339d Cleanup AST-to-HIR lowering
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.
2021-03-01 10:42:27 +00:00
Yizhe
5625e07187 Remove the last trace of the Operator enum #2
Missed a few lines in the last attempt. Whoops.
2021-03-01 10:42:27 +00:00
Yizhe
f0b7bd4138 Fix typo 2021-03-01 10:42:27 +00:00
Yizhe
c8af098859 Remove the last trace of the Operator enum
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.
2021-03-01 10:42:27 +00:00
Yizhe
6c5b2a6326 Rewrite backend to accept the new enum
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.
2021-03-01 10:42:27 +00:00
Yizhe
63dabd8161 Extract enums into the global namespace
`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.
2021-03-01 10:42:27 +00:00
Nala Ginrut
3aa4bce824 Fix to parse inner attribute correctly 2021-03-01 10:36:42 +00:00
Philip Herron
1c6eaa1907 Add some more error handling to generics
Check for wrong number of arguments and fix crash with invalid Type
specified as generic argument.
2021-03-01 10:35:07 +00:00
Philip Herron
ec9ead44a4 Adds the same support from generic structs in #235 onto tuple structs
Type binding still not supported here but the same generic support is added
to tuples.

Fixes #236
2021-03-01 10:35:07 +00:00
Philip Herron
9af2ae0ff9 Support Generic arguments to Structs
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
2021-03-01 10:35:07 +00:00
Nala Ginrut
06bb1d6542 Update default configs in ExpansionCfg 2021-03-01 10:34:45 +00:00
Marc Poulhiès
684123ebc4 Trivial typo fix 2021-03-01 10:34:28 +00:00
Akshat Agarwal
27df0c9f95 Run clang-format CI on every push on master branch
Signed-off-by: Akshat Agarwal <humancalico@disroot.org>
2021-02-22 17:11:21 +00:00
Akshat Agarwal
7f518fb584 Reformat all files in gcc/rust/typecheck
Signed-off-by: Akshat Agarwal <humancalico@disroot.org>
2021-02-22 17:11:21 +00:00
Yizhe
3673b0b3b7 Fixed unsigned and signed comparision 2021-02-19 10:34:59 +00:00
Yizhe
6dc2bfb1d0 Removed base field from BaseRules
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.
2021-02-19 10:34:59 +00:00
Yizhe
f37f3d3a98 Renamed BaseRules::equals back to BaseRules::is_equal
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.
2021-02-19 10:34:59 +00:00
Yizhe
496f773bda Added equals method to BaseType
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.
2021-02-19 10:34:59 +00:00
Yizhe
3f2906e5e4 Added some doc for BaseRules and BaseType 2021-02-19 10:34:59 +00:00
Yizhe
59ce2a981b Renamed combine to unify 2021-02-19 10:34:59 +00:00
Yizhe
68a2f3d7ea Renamed TyBase to BaseType 2021-02-19 10:34:59 +00:00
Akshat Agarwal
642cc5ed4f Add clang format GitHub Action
Signed-off-by: Akshat Agarwal <humancalico@disroot.org>
2021-02-19 10:31:39 +00:00
Akshat Agarwal
8a580f9152 Format all files in gcc/rust/ using clang-format
Signed-off-by: Akshat Agarwal <humancalico@disroot.org>

This commit formats all files in gcc/rust using clang-format.
2021-02-19 10:31:39 +00:00
Philip Herron
df5ef68888 Add debug interface to GCC debug_tree on GENERIC graphs
This adds in a debugging interface for the backend IR to help diagnose
issues with the tree.
2021-02-18 19:00:48 +00:00
Akshat Agarwal
107674522d remove ast/clone-test.h
Signed-off-by: Akshat Agarwal <humancalico@disroot.org>

Fixes: #99
2021-02-18 19:00:30 +00:00
Philip Herron
ca51478471 Add ReferenceType with BorrowExpr and DereferenceExpr
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
2021-02-13 10:08:03 +00:00
Philip Herron
3ae8d55860 Add char type
This might need changes in the Lexer to allow for wchar_t to be preserved.

Addresses #85
2021-02-13 09:54:47 +00:00
Philip Herron
fac8276f73 Fix parsing of Char literals 2021-02-13 09:54:47 +00:00
Philip Herron
ebb5de2343 Add in ContinueExpr support
We made an implicit loop begin label that can be referenced in a goto to
restart the loop.

Fixes #188
2021-02-13 09:54:32 +00:00
Philip Herron
7366f6decf Add in while loop support
We create a LoopExpr comprising of:

  LOOP_EXPR {
     EXIT_EXPR (while loop predicate)
     {
       <LOOP_BODY>
     }
  }

Fixes #109
2021-02-13 09:54:32 +00:00
Philip Herron
92898b2903 Fix bug parsing while loop expressions
If a while loop is part of an expression it needs to know it does not need
to skip token.
2021-02-13 09:54:32 +00:00
Philip Herron
a6405f1438 Merge pull request #227 from SimplyTheOther/master
Changes to AST structure in preparation for macro expansion and cleanup
2021-02-11 10:25:01 +00:00
SimplyTheOther
7d4ed9d38c Merge branch 'master' of https://github.com/redbrain/gccrs 2021-02-11 12:15:39 +08:00
Philip Herron
0c7d013566 Add support to break from loops with a value
This adds support to make the break value assignable such that the loop
now becomes akin to a BlockExpr

Fixes #108 #106
2021-02-10 18:10:57 +00:00
Philip Herron
d02ab5925b Add check for break outside of a loop.
This will be needed to stop the compiler proceding to continue and break
expressions without a loop context.
2021-02-10 18:10:57 +00:00
Philip Herron
06c9fd97bf Support LoopLabels and break to label.
This allows for the Rust refernece example for loop labels to be compiled.

Fixes #107
2021-02-10 18:10:57 +00:00
Philip Herron
f10e695fc5 Return expressions can be empty which us unit-type
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
2021-02-10 18:10:57 +00:00
Philip Herron
ae273ffac9 Support Break without label and expression
This reuses GENERICS LOOP_EXPR and EXIT_EXPR to implement the infinite
loop.

Addresses: #106 #108
2021-02-10 18:10:57 +00:00
Philip Herron
016c40bedc Introduce new label namesapce for name resolution
Labels are in their own namesapce so they do not affect types and normal
values within a program.

Addresses #107
2021-02-10 18:10:57 +00:00
Philip Herron
a3a343c885 Give ParseRestriction option to allow for null parse_expr.
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
2021-02-10 18:10:57 +00:00
Philip Herron
1a2c0911f0 Support Simple LoopExpr
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
2021-02-10 18:10:57 +00:00
Philip Herron
cb9998216d Fix parse of LoopExpr as part of a normal expression
For example this fixes the form of: let x = loop { ... };

Fixes #219
2021-02-10 18:10:57 +00:00
Philip Herron
9355fb29fc Enable -frust-dump-all option for debugging
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.
2021-02-10 13:21:16 +00:00
Philip Herron
c8b9c41bf2 Fix parsing |= as a compound assignment expression.
Fixes #173
2021-02-10 13:21:00 +00:00
Philip Herron
b96299b0b9 Fix bad type resolution for CallExpr when fn is not simply PathInExpression
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
2021-02-09 09:47:35 +00:00
Philip Herron
60cccd8e58 Fixes parsing if expressions as part of an expression.
This allows for rust style ternery expressions.

Fixes #214
2021-02-09 09:47:13 +00:00
Philip Herron
9f3ddb3595 Conditional blocks with else can resolve into a non unit type expression.
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
2021-02-09 09:46:54 +00:00
SimplyTheOther
cfd1d805ff Unified Tokens partially in preparation for macro expansion 2021-02-09 16:40:23 +08:00
Philip Herron
0ccc245a06 With the merge of BlockExprs
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.
2021-02-07 18:21:53 +00:00
SimplyTheOther
8f97711dce General cleanup of AST and macro expansion-related things 2021-02-07 15:03:07 +08:00
SimplyTheOther
94be91d615 Merge branch 'master' of https://github.com/redbrain/gccrs 2021-02-07 12:40:19 +08:00
Philip Herron
db71343534 Fix overloaded virtual and unused parameters warnings 2021-02-06 18:03:42 +00:00
Philip Herron
34a39466b2 Add in support to compile Methods and MethodCallExpr
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
2021-02-06 15:45:51 +00:00
Philip Herron
59a8fa1a80 Support Self used within impl blocks
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
2021-02-06 15:45:51 +00:00
Philip Herron
7098b37317 Fix unreachable crash when a struct contains another algebraic data type
When we have a nested struct this must resolve to the existing compiled
struct and not create a new record type.
2021-02-06 15:45:51 +00:00
Philip Herron
75b6fc46bd Move scan for unused names to be after type resolution
Methods are resolved as part of type resolution so scanning ribs early
on will results in false warnings about unused methods.
2021-02-06 15:29:01 +00:00
Philip Herron
599b04aa7d This adds support for basic BlockExpressions
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
2021-02-06 15:17:08 +00:00
Philip Herron
c4be77f7e0 Enforce Duplicate definition rules
Rust does not allow functions/methods/constants/static definitions to
shadow otherwise you end up with unuseable items.
2021-02-06 15:16:23 +00:00
SimplyTheOther
27eef5b7a0 Rewrote MetaNameValueStr to store raw string rather than quoted string 2021-02-06 20:22:33 +08:00
SimplyTheOther
83ca728584 Added more debug for cfg expansion 2021-02-06 18:30:14 +08:00
SimplyTheOther
feaa2074d8 Added even more debug for cfg predicate checking 2021-02-06 18:10:57 +08:00
SimplyTheOther
3571e99747 Added more debug for cfg predicate checking 2021-02-06 16:25:10 +08:00
SimplyTheOther
d0e1051788 Fixed bad cfg predicate string interpolation 2021-02-06 15:51:57 +08:00
SimplyTheOther
5c7dacd845 Added some debug for cfg stripping and improved dump messages 2021-02-05 21:49:35 +08:00
SimplyTheOther
7c7c76f27f Merge branch 'master' of https://github.com/redbrain/gccrs 2021-02-04 12:43:59 +08:00
Philip Herron
9abf073381 Fix type resolution null pointer crash
This also enhance ArithmeticOrLogicalExpr rules and associated error
handling to propagate up the stack.
2021-02-03 10:38:13 +00:00
Philip Herron
419677348e Add support for impl blocks for functions and constants.
This is the building block in adding support for methods and the self
keyword.

Fixes: #111
2021-02-03 10:38:13 +00:00
SimplyTheOther
877e7ac6c7 Readded outer attributes to if and if let exprs 2021-02-03 18:23:00 +08:00
Philip Herron
36ac7b7971 Split out the integer inference variable tests
Seperated test cases and one to combine them to help navigate any
potential failures later on.
2021-02-03 10:11:35 +00:00
SimplyTheOther
14aacf472d Removed testcase that apparently didn't compile on CI 2021-02-03 13:48:20 +08:00
SimplyTheOther
a48d424e4c Fixed compile error 2021-02-03 12:06:29 +08:00
SimplyTheOther
61b498895b Merge with upstream 2021-02-02 17:13:10 +08:00
SimplyTheOther
3a0c8ca215 Cleanup of AST - moved outer_attrs to child classes
Fixed compile errors

Fixed more compile errors
2021-02-02 15:55:58 +08:00
Philip Herron
e0e49f4344 Add a recursive function test case
This greatest common divisor function demonstrates that recursion is
working.
2021-01-27 11:04:19 +00:00
Philip Herron
244c2d2ea1 Support binding functions to LetStmts.
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
2021-01-27 10:42:43 +00:00
Philip Herron
8578c61be5 Add mutablity checks and left hand size assignee checker
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
2021-01-27 10:42:25 +00:00
Philip Herron
854aad3b58 Add usize and isize types
Arrays can only be indexed by usize and this enforces that rule. These
types are sized based on the pointer size of the host arch.

Fixes #87
2021-01-26 11:59:39 +00:00
Philip Herron
0817c29a42 Add Integer and Float InterenceVariable
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.
2021-01-26 11:59:39 +00:00
Philip Herron
5294dfe7dc Remove TyTy::ParamType this was wrongly used to represent FunctionParams
TyTy::ParamType is meant to be used to represent Generic Types which is
not handled yet as part of this current milestone.
2021-01-26 11:59:39 +00:00
Philip Herron
be371b9f49 Add backend support to create immutable types
GCC uses qualified types to create const immutability.
2021-01-26 11:59:23 +00:00
Philip Herron
be10fafbb6 Add warning to the README
The compiler is not ready to compile real rust programs, yet this will warn potential users.
2021-01-22 14:44:32 +00:00
Philip Herron
93b991e604 Add FAQ link to README 2021-01-21 12:00:58 +00:00
Philip Herron
9e733f4de4 Fix usage of parameters and the type resolver
Parameter types can be resolved to their base type in combination rules.
2021-01-20 10:31:26 +00:00
Philip Herron
e2b761b13e Implement CompoundAssignmentExpressions
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.
2021-01-20 10:15:56 +00:00
Philip Herron
85d8754632 Implement NegationExpression
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.
2021-01-20 10:03:50 +00:00
Philip Herron
6e09093f1f Enforce the rules for arithmetic operations
This adds test cases and enforces the type rules for ArithmeticOrLogical
Operators.
2021-01-20 10:02:41 +00:00
Philip Herron
76b308af7e ComparisonExprs and LazyBoolExprs are bools
This fixes the expression type resolution to coerce these into bools. For
LazyBoolExprs && and || the lhs and rhs are bools.
2021-01-20 10:02:14 +00:00
Philip Herron
23edde6fef Fixes the ^= and %= compound expression parsing.
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.
2021-01-20 10:01:43 +00:00
Philip Herron
f6d33adc66 Fix bug using ADT types as return types to functions
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.
2021-01-20 09:59:22 +00:00
Philip Herron
cb44a8feb8 When we construct the fields can be in any order.
The gimple interface requires us to have the fields in order as to the
Algebraic Data Type which it references.
2021-01-20 09:59:22 +00:00
Philip Herron
4f6f18fe29 Support struct base reference in constructors
This creates implicit FieldAccessExpr or TupleIndexExprs for the missing
fields in the constructor using the base struct as the receiver.
2021-01-20 09:59:22 +00:00
Philip Herron
12f7bd0fc4 Support struct initializers using Identifiers
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.
2021-01-20 09:59:22 +00:00
Philip Herron
6e2acd529f Support Struct field index initialisation
For TupleStructs the constructor can take field indexes to support
change or ordering of the fields.
2021-01-20 09:59:22 +00:00
Philip Herron
f8d41b7e8a Add TupleIndexExpressions
Now we can type resolve and reference the results from TupleIndexExpr's.
2021-01-20 09:59:22 +00:00
Philip Herron
9a942d6fbd Add in TupleStruct support
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.
2021-01-20 09:59:22 +00:00
Philip Herron
89631998d2 Delcare first case for ADT types field access fail to type resolve.
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.
2021-01-19 12:53:02 +00:00
Thomas Schwinge
3713577c36 Turn brace-enclosed initializer list into actual assignments
... 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};
                                                                            ^
2021-01-18 17:46:17 +00:00
Thomas Schwinge
c55cd0e10c Fix '#include <algorithm>'
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.
2021-01-18 17:45:59 +00:00
Philip Herron
2b7518cf8a Add struct_field_expression support
This adds in struct field expressions and should be generic enough for
tuples later on.
2021-01-18 10:01:57 +00:00
Philip Herron
02132139ef Fix the naming of VAR_DECLS within gimple nodes.
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.
2021-01-17 15:59:36 +00:00
Philip Herron
659ade1611 Handle forward references in backend compilation
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.
2021-01-17 15:58:07 +00:00
Philip Herron
7066c0eca1 Support GroupedExpr's
This makes the expression handling support exprs within parens. Such as:
  x = (2*a) + 3;
2021-01-17 14:21:59 +00:00
Philip Herron
a79e3b31be grouped expr wip 2021-01-17 14:21:59 +00:00
Philip Herron
b06df5d4a9 This adds supports for tuples
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.
2021-01-17 14:20:45 +00:00
Philip Herron
e4a2a52b35 Enforce type checking on implicit returns
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.
2021-01-16 14:15:09 +00:00
Philip Herron
d96e1594dd This brings in resolution and type checking of the unit-type.
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.
2021-01-16 14:07:50 +00:00
SimplyTheOther
b3a39d99c1 Merge branch 'master' of https://github.com/redbrain/gccrs 2021-01-13 21:25:20 +08:00
Philip Herron
05b9f23556 Fix link to build status shield
The repository was moved into the Rust-GCC organization from philberty
2021-01-13 12:09:07 +00:00
Vlad Doster
da3e15f13f (docs) update README.md
- Correct grammar/spelling
- Add language syntax for code fences
- Link to test-suite file
2021-01-12 13:33:12 +00:00
Philip Herron
5a9ceba8fd Mark DECL_PUBLIC for main fn or functions with visibility.
This change will need more thought later when it comes to traits and
generics etc.

Fixes #136
2021-01-11 20:00:03 +00:00
SimplyTheOther
bc94b7de46 Merge branch 'master' of https://github.com/redbrain/gccrs 2021-01-11 16:33:01 +08:00
Philip Herron
9a3ad294e0 Add in a check for unused decls within ribs.
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.
2021-01-10 15:59:22 +00:00
SimplyTheOther
aa487ef271 Cleanup - remove old for loop implementations in AttrVisitor 2021-01-10 14:40:56 +08:00
SimplyTheOther
b247c0d5aa Merge branch 'master' of https://github.com/redbrain/gccrs 2021-01-10 14:30:39 +08:00
Philip Herron
0f42a240e5 Functions with parameters much receive their own scoping Rib
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.
2021-01-09 14:47:50 +00:00
Philip Herron
6d7a53b684 Fix crash when compiling BlockExpr's
This ensures the compiler respects scoping and shadowing rules of
blocks added within an enclosing scope.
2021-01-09 14:47:04 +00:00
Philip Herron
705b8b73aa There was a bug with LetStmts where we name resolved the identifier
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.
2021-01-09 14:47:04 +00:00
Philip Herron
5a11dd79fc Make TyTyVisitor a pure abstract class
This will help enforce consistency of visitors to fix issues with
TyTy unification rules.
2021-01-09 14:46:32 +00:00
SimplyTheOther
ee85db852a Added type hint to literal creation for cfg! macro 2021-01-08 22:05:03 +08:00
Philip Herron
06d946d522 Respect the f32 and f64 suffix on literals
Rust is permissive for integers being marked as floats so the check in the
lexer can be removed here.
2021-01-08 11:37:22 +00:00
Philip Herron
4e0189ed28 Implicit Returns support.
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.
2021-01-08 11:36:54 +00:00
Philip Herron
290fc4f416 Add test to cover handling hex, binary and octal number literals.
This also ensure the type suffix is respected against the number.
2021-01-08 10:05:40 +00:00
SimplyTheOther
238a31b33f Merge branch 'master' of https://github.com/redbrain/gccrs 2021-01-08 15:09:08 +08:00
SimplyTheOther
b5f86dca7e Added final to some overriden methods for optimisation, planned macro parsing 2021-01-08 15:08:14 +08:00
Philip Herron
af04ea2222 Change CI to look for any unexpected failures to fail the build. 2021-01-06 10:52:56 +00:00
Philip Herron
c2cc8df0b5 Add in support to compile static variables. Still requires name mangling
for the ASM name similar to functions.
2021-01-06 10:28:45 +00:00
Philip Herron
82d80bf20e Fix bad naming of f64 named type in GIMPLE. 2021-01-06 10:21:20 +00:00
Philip Herron
aef9821d9b Add in F32 and F64 types builtin types.
We need to ensure all suffix of literals are handled in a subsequent PR.
2021-01-06 10:19:10 +00:00
Philip Herron
1a97dbc6b5 Examine the Suffix hint on integers to apply apropriate TyTy type.
This change propagates the PrimitiveCoreType to AST and HIR so
the suffix can be examined.
2021-01-06 10:13:39 +00:00
Philip Herron
4d590e5d21 Create new Greetings automation on github
This should make sure people are aware about copyright assignment on their first PR.
2021-01-06 10:03:06 +00:00
Philip Herron
36ebe9a038 This brings structs back in post HIR changes. It supports structs
where no base struct is referenced and the constructor is in order.
2021-01-06 10:01:17 +00:00
Philip Herron
467141184a Implement constant expressions 2020-12-25 18:23:22 +00:00
SimplyTheOther
faf78e75e4 Merge branch 'master' of https://github.com/redbrain/gccrs 2020-12-25 18:00:23 +08:00
SimplyTheOther
8597209374 Rewrote SingleASTNode representation 2020-12-25 17:16:25 +08:00
SimplyTheOther
7299d6d84a Test a new ASTFragment union representation 2020-12-25 16:25:40 +08:00
Philip Herron
8d34ac3c16 Add logo to README 2020-12-23 15:02:02 +00:00
Philip Herron
a56656e26e Remove impl_block test. This is part of the next milestone and we want
to turn on CI build failure if any test fails and this will block that
change until the next milestone if not removed.
2020-12-23 15:01:40 +00:00
Philip Herron
379e594ce9 Update README with more content 2020-12-23 15:00:47 +00:00
Philip Herron
d1afbb7ead Implement compilation of ArrayElemsCopied to GIMPLE
let mut array = [123; 5]
2020-12-23 14:47:34 +00:00
Philip Herron
f701ad5352 This brings arrays back into the new framework. It resolves ArrayType
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.
2020-12-23 14:47:34 +00:00
Philip Herron
aa2fbb5e48 Bring conditionals back since the HIR change. 2020-12-23 13:04:50 +00:00
Nym Seddon
b021811ab7 Add missing license text
Add GPL license text to files without the header
2020-12-23 13:02:24 +00:00
Philip Herron
a4e20cf765 Shadowing rules are done as part of name resolution.
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.
2020-12-23 12:32:15 +00:00
Philip Herron
04bcc692f5 Seperate build and Test steps in the build 2020-12-23 12:31:48 +00:00
Nym Seddon
c4f1a7aa81 Fix minor typo in visibility as_string 2020-12-23 12:31:21 +00:00
SimplyTheOther
627121b699 Added code to expand cfg! macros
Moved function body to prevent compile issues

Moved around some definitions in rust-ast.h in attempt to prevent compile error
2020-12-22 19:24:37 +08:00
SimplyTheOther
30dd20c009 Merge branch 'master' of https://github.com/redbrain/gccrs 2020-12-21 10:00:20 +08:00
Philip Herron
671cefe612 When compiling a block it might reference a GIMPLE node that is not
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
2020-12-19 19:33:03 +00:00
Philip Herron
3a10d1f159 Add type unification as part of typecheck.
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.
2020-12-19 19:32:41 +00:00
SimplyTheOther
aa283484a3 Merge branch 'master' of https://github.com/redbrain/gccrs 2020-12-18 21:33:09 +08:00
SimplyTheOther
f764eeb8ab Unified representation of macro invocation internal data - will be better for processing 2020-12-18 21:07:04 +08:00
accusitive
bc14d9a0cd Fix the spelling of contribute in README.md. 2020-12-17 17:50:56 +00:00
Philip Herron
6136f0aebb This is a new HIR -> GIMPLE pass it reuses the mappings from hir,
name resolution and type resolution to simplify the generation of
gimple.
2020-12-17 17:23:46 +00:00
Philip Herron
a621e19365 Remove old analysis framework and strip the AST->GIMPLE pass this needs
to use the new name and type resolution pass contexts.
2020-12-17 17:23:46 +00:00
Philip Herron
44d10d9547 TypeResolution pass now with a TyTy module
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.
2020-12-17 17:23:46 +00:00
Philip Herron
4fb0ab7e63 This sets up a name resolution framework trying to follow rust-dev guide
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.
2020-12-17 17:23:46 +00:00
Philip Herron
2cfc6276da Add AST->HIR lowering pass
This is the initial pass to move the AST to HIR. It is very extensible and
easy to maintain now.
2020-12-17 17:23:46 +00:00
Philip Herron
5f2dd6de5b Add in HIR Tree
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.
2020-12-17 17:23:46 +00:00
Philip Herron
97d2003e8c Add generated NodeId's to the AST
NodeIds are going to be used for Hir->Ast lookups later on.
2020-12-17 17:23:46 +00:00
Philip Herron
6c89617fc9 Cleanup Makefile for Rust
This adds some extra Flags to ignore unused warnings and no
overloaded-virtuals. This helps with compilation error diagnosis.
2020-12-17 17:23:46 +00:00
Philip Herron
3514168b99 Introduce HIR Mapping
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
2020-12-17 17:23:46 +00:00
Philip Herron
29fb9e4d93 tweak to rust-system.h includes 2020-12-17 17:23:46 +00:00
Philip Herron
b472eeeeb2 Merge pull request #65 from Rust-GCC/phil/dejagnu
Add missing Dejagnu dependancy to run test suite.
2020-12-16 14:23:26 +00:00
Philip Herron
442b9caa12 Add zulip chat badge 2020-12-16 11:18:07 +00:00
Philip Herron
503eb9b354 Add missing Dejagnu dependancy to run test suite.
Fixes #63
2020-12-16 11:14:59 +00:00
SimplyTheOther
0496b05eaf Merge branch 'master' of https://github.com/redbrain/gccrs 2020-12-15 14:35:02 +08:00
SimplyTheOther
3e45922616 Changed more index for loops to iterator for loops 2020-12-15 14:33:30 +08:00
SimplyTheOther
f0cc1df591 Changed some for index loops to for iterator loops that can deal with representation changes 2020-12-15 14:05:17 +08:00
Philip Herron
6e4b74fb77 Merge pull request #62 from SimplyTheOther/master
Expansion code for cfg attributes, bug fixes and minor enhancements in parser
2020-12-14 15:40:17 +00:00
SimplyTheOther
52cc571b30 Prevented several warnings about unused parameters 2020-12-14 15:41:48 +08:00
SimplyTheOther
2969162618 Improved use tree parsing 2020-12-14 15:09:08 +08:00
SimplyTheOther
6d9b6db945 Added location storage for struct expr fields
Fixed typo in an enum expr field class
2020-12-13 20:19:37 +08:00
SimplyTheOther
a697962166 Modified binding power used when parsing expression inside index expr 2020-12-13 17:21:38 +08:00
SimplyTheOther
4490d49331 Fixed SimplePath's operator == not being const 2020-12-13 16:20:57 +08:00
SimplyTheOther
6ee2c06c47 Attempt to fix array parsing errors 2020-12-13 15:47:32 +08:00
SimplyTheOther
e21c9fe165 Enhanced dumping of expansion 2020-12-10 20:53:26 +08:00
SimplyTheOther
4232e46d87 Fixed BlockExpr not being allowed to be empty 2020-12-10 18:32:07 +08:00
SimplyTheOther
53ddea7a26 Fixed formatting to fit gcc style 2020-12-09 17:42:16 +08:00
SimplyTheOther
b343d117f5 Fixed rust-compile.cc compile error 2020-12-09 16:01:35 +08:00
SimplyTheOther
41c14b45ac Merge branch 'master' of https://github.com/redbrain/gccrs 2020-12-09 15:29:51 +08:00
SimplyTheOther
815c9e8b07 Fixed rust-type-resolution.cc compile error 2020-12-09 14:07:05 +08:00
SimplyTheOther
0e5d54bcb0 Changed compiled files in makefile to be identical with upstream - hopefully prevents compile error 2020-12-09 10:59:13 +08:00
SimplyTheOther
c7080f178a Added more cfg stripping code 2020-12-08 21:10:36 +08:00
SimplyTheOther
db39766514 Added new pattern stripping
Fixed get_locus_slow call in StructPatternField compile error

Added and improved cfg stripping

Fixed compilation errors
2020-12-08 21:10:34 +08:00
SimplyTheOther
9b252167a7 Added more expression cfg stripping
Fixed compile errors
2020-12-08 21:10:32 +08:00
SimplyTheOther
4ec3b8d62b Added more expr cfg stripping
Fixed compile errors

Fixed compile errors relating to block expr visibility changes
2020-12-08 21:10:31 +08:00
SimplyTheOther
25de39b1f0 Added more expr stripping 2020-12-08 21:10:29 +08:00
SimplyTheOther
f5ae278182 Added more expression stripping
Fixed compile errors and started on enum expr stripping
2020-12-08 21:10:28 +08:00
SimplyTheOther
37bbf2b8cb Added cfg stripping for some expressions
Attempt to fix compile error
2020-12-08 21:10:26 +08:00
SimplyTheOther
164e38246f Added more cfg-stripping 2020-12-08 21:10:24 +08:00
SimplyTheOther
1271b77203 Added more trait item stripping
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
2020-12-08 21:10:20 +08:00
SimplyTheOther
69048af187 Added cfg stripping for ExternalItems
Fixed non-renaming of has_variadic_outer_attrs()

Fixed old as_string function for ExternalItem

Fixed parse_named_function_param arguments
2020-12-08 21:10:18 +08:00
SimplyTheOther
98d429466b Added strip-marking to statements, items and expressions (to allow them to be stripped from their parents)
Fixed compile errors and added more stripping behaviour for extern blocks
2020-12-08 21:10:16 +08:00
SimplyTheOther
eb644945a4 Added cfg stripping code (will top-level strip currently)
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
2020-12-08 21:10:15 +08:00
SimplyTheOther
423462fb67 Added proper cfg_attr expansion 2020-12-08 21:10:13 +08:00
Philip Herron
cef34bd730 Fix typo in README.md 2020-12-07 10:13:16 +00:00
Philip Herron
21d0a20c77 Update Automations to only build rust to improve build times 2020-12-07 10:13:16 +00:00
Philip Herron
80e2ebd8d7 Only need to compile the Rust language 2020-12-07 10:13:16 +00:00
Philip Herron
3fa79a6dc5 Update GDB command to remove bad test.s source 2020-12-07 10:13:16 +00:00
Philip Herron
c5a1da3944 Add Twitter link 2020-12-07 10:13:16 +00:00
Philip Herron
064c6e4815 Type Resolve ReturnExpr's to ensure they match the function type.
This an implementation to check return types for functions it needs work
to handle structs and other data structures later on.
2020-12-03 17:25:24 +00:00
Philip Herron
03fc0e389f We cannot lookup types to ensure they are known as AST::Type differs
to how struct AST Types. We need to move to HIR to avoid this issue via
name resolution.
2020-12-03 17:25:05 +00:00
Philip Herron
0394164f3d Add failure tests to rust testsuite
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.
2020-12-03 16:36:05 +00:00
Philip Herron
8993741f97 GIMPLE coversions for ArrayIndexExpr and Arrays with values
This compiles the ArrayIndexExpressions and Arrays such as:
  let x = [1,2,3];
  let a = x[0];

Addresses: #55
2020-12-01 17:50:50 +00:00
Philip Herron
3f491614f6 Fix README.md with updated GDB command
The -auxbase-strip command has been removed from compiler proper's, since rebase against master GCC.
2020-12-01 17:50:50 +00:00
Philip Herron
5296354451 Mark this as a FIXME memory leak 2020-12-01 17:50:50 +00:00
Philip Herron
8567160538 Ensure the array index is of integer type.
The index expression must be validated to ensure it is an integer.

Addresses: #27 #55
2020-12-01 17:50:50 +00:00
Philip Herron
efbe8cc4d9 Resolve the type from an ArrayIndexExpression
Adds new TypeVisitor to resolve Types from the AST via Visitor Pattern, so
the element type can be extracted.

Addresses: #27 #55
2020-12-01 17:50:50 +00:00
Philip Herron
886b230d42 Add Type resolution to Array expressions
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
2020-12-01 17:50:50 +00:00
Philip Herron
37560f930d Add Docker badges to README 2020-11-30 15:09:38 +00:00
Philip Herron
e6ebbcc6dd Turn on make check-rust
This will turn on the test-suite which does have a currently failing test
lets see what happens the workflow in github.
2020-11-30 12:41:59 +00:00
Philip Herron
5878919d03 Added GCC Rust Zulip channel link - please feel free to join :^) 2020-11-30 12:38:16 +00:00
Philip Herron
ac742ebc79 Linemap and Backend are both singletons
We can only create on linemap instance to avoid missing locations in error
diagnostics. We also only need one instance of the backend.
2020-11-30 10:42:13 +00:00
Philip Herron
4a9f0d53b8 Updated README.md to add more info to fellow Rustaceans. 2020-11-29 20:38:51 +00:00
Philip Herron
b27c4a4986 No need to declare Type as inferedType when it is already defined
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.
2020-11-28 21:14:26 +00:00
Philip Herron
ed45224958 Use ifdef guards instead of pragma once 2020-11-28 21:13:22 +00:00
Philip Herron
7b352d63e1 Fix formatting in Makefile 2020-11-28 21:13:22 +00:00
Philip Herron
4e475efeb4 Add Docker file for automated images to allow for easier testing
Example usage:

docker build . -t gccrs-dev
docker run --rm -v "$PWD":/usr/src/myapp -w /usr/src/myapp \
    gccrs-dev:latest gccrs -g -O2 -c \
    gcc/testsuite/rust.test/compilable/type_infer1.rs -o type_infer1.o
2020-11-28 21:13:22 +00:00
Philip Herron
f28325125b Initial TestSuite setup for make check-rust
This is an initial basic testsuite with one file with expected failures
for now.
2020-11-28 21:13:22 +00:00
Philip Herron
0db8774645 Remove unused and add FIXME
We need to ensure in type resolution pass we fix up the ordering for
a struct initilization and give defaults to missing fields.
2020-11-28 21:13:22 +00:00
SimplyTheOther
e7cf2f7789 Added skeleton for macro expansion and added way to convert MetaItems back to Attributes (e.g. for cfg_attr use) 2020-11-28 21:13:21 +00:00
SimplyTheOther
2ed062a0be Improved parsing of MatchExpr (and AST structure)
Fixed compilation errors

Fixed accidental break out of loop when expr_with_block when parsing match expr
2020-11-28 21:13:21 +00:00
SimplyTheOther
4cfd937462 Testing some more algorithmic changes
Fixed syntax errors
2020-11-28 21:13:21 +00:00
SimplyTheOther
5fbc20189d Test even more generic algorithm for parsing in for lifetimes 2020-11-28 21:13:21 +00:00
SimplyTheOther
41b1bad402 Added more error_at formatting fixes
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()
2020-11-28 21:13:21 +00:00
SimplyTheOther
636b163018 Attempt to significantly reduce warning count by modifying error message format 2020-11-28 21:13:21 +00:00
SimplyTheOther
c7440d88c7 Working on consolidating some other parsing functions 2020-11-28 21:13:21 +00:00
SimplyTheOther
2109985cb4 Attempt to consolidate CompoundAssignmentExpr parsing 2020-11-28 21:13:21 +00:00
SimplyTheOther
fd68a282ed Attempt consolidation of ArithmeticOrLogicalExpr parsing
Fixed typo of MODULUS as MODULO
2020-11-28 21:13:21 +00:00
SimplyTheOther
2f7007a777 Attempt to fix the ExprWithoutBlock in ExprStmtWithoutBlock issue
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
2020-11-28 21:13:21 +00:00
SimplyTheOther
e0db6e13f0 Converted Parser to template in preparation for macro expansion 2020-11-28 21:13:21 +00:00
SimplyTheOther
daedbe3476 Potential modifications to buffered_queue to move when resizing instead of copying - test if works properly
Added messages to buffered_queue to debug assertion failure

Attempt to fix the buffered_queue issue

Removed some debug in buffered_queue
2020-11-28 21:13:20 +00:00
SimplyTheOther
8a633e3ca4 Attempt to modify buffered_queue to take ownership of a source rather than reference, other cleanup
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
2020-11-28 21:13:20 +00:00
SimplyTheOther
318a91e6ba Massive lexer cleanup and refactoring - moved lots of stuff out of main method
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
2020-11-28 21:13:20 +00:00
SimplyTheOther
ce72a38e08 Attempted to solve string escape vs null character location issues 2020-11-28 21:13:20 +00:00
SimplyTheOther
b758ec724c Lexer cleanup 2020-11-28 21:13:20 +00:00
SimplyTheOther
c26f60f6a2 Miscellaneous improvements to various target hooks 2020-11-28 21:13:20 +00:00
Philip Herron
9dd2cdd833 i386 build fix against latest gcc 2020-11-28 21:13:20 +00:00
SimplyTheOther
f74f9d4b25 Improvements to aarch64 target hook 2020-11-28 21:13:20 +00:00
SimplyTheOther
9f82c8a919 Improved and tidied up ARM target hook 2020-11-28 21:13:20 +00:00
SimplyTheOther
610c1678de Enhancements to x86 target hook, should be feature complete with llvm to the greatest extent possible 2020-11-28 21:13:20 +00:00
SimplyTheOther
2f12a7eba2 Added Xtensa target hook (or provisional one at least) 2020-11-28 21:13:20 +00:00
SimplyTheOther
113f2b15c4 Added Visium target hook (or at least provisional one) 2020-11-28 21:13:19 +00:00
SimplyTheOther
05e57eac43 Added VAX target hook (or provisional one at least) 2020-11-28 21:13:19 +00:00
SimplyTheOther
1bedf7bfc1 Added NEC V850 target hook (or provisional one at least) 2020-11-28 21:13:19 +00:00
SimplyTheOther
e6bc704968 Added TILEPro target hook 2020-11-28 21:13:19 +00:00
SimplyTheOther
cc2880c408 Added TILE-Gx target hook 2020-11-28 21:13:19 +00:00
Philip Herron
ffb8dbc16a Compile AST::StructExprStructFields into a constructor tree.
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};
  }
2020-11-28 21:13:19 +00:00
SimplyTheOther
aac6645c22 Added provisional SPARC target hook 2020-11-28 21:13:19 +00:00
SimplyTheOther
a058ca33b0 Added target hook for Renesas SH (or provisional one at least) 2020-11-28 21:13:19 +00:00
SimplyTheOther
e8bf48baaf Added extremely provisional S/390 and zSeries target hook 2020-11-28 21:13:19 +00:00
SimplyTheOther
fed3fd6054 Added Renesas RX target hook (or at least provisional one) 2020-11-28 21:13:19 +00:00
SimplyTheOther
51e1554100 Added RL78 target hook (or at least provisional one) 2020-11-28 21:13:19 +00:00
SimplyTheOther
ba0c8e0c36 Added RISC-V target hook (or at least provisional one) 2020-11-28 21:13:19 +00:00
SimplyTheOther
1bb2b31af2 Added PRU target hook (or provisional one at least) 2020-11-28 21:13:18 +00:00
SimplyTheOther
7cd87ee2da Added PDP-11 target hook (or provisional one at least) 2020-11-28 21:13:18 +00:00
SimplyTheOther
b92289909d Added HPPA target hook (or provisional one at least) 2020-11-28 21:13:18 +00:00
SimplyTheOther
1434904329 Added OpenRISC target hook (or at least provisional one) 2020-11-28 21:13:18 +00:00
SimplyTheOther
76376bd726 Minor Nios II tweaks based on new information found 2020-11-28 21:13:18 +00:00
SimplyTheOther
c54f4e711e Added (very bad and provisional) Nvidia PTX target hook 2020-11-28 21:13:18 +00:00
SimplyTheOther
9e9c2eb329 Added Nios II target hook (or provisional one at least) 2020-11-28 21:13:18 +00:00
Philip Herron
8f0507ad9e Type Resolve Struct initializtion of their fields 2020-11-28 21:13:18 +00:00
SimplyTheOther
1d7ab6b109 Added NDS32 target hook (or at least provisional one) 2020-11-28 21:13:18 +00:00
SimplyTheOther
ea5e2aff4e Added MSP430 target hook (or at least provisional one) 2020-11-28 21:13:18 +00:00
SimplyTheOther
888c584e06 Added moxie target hook (or at least provisional one) 2020-11-28 21:13:18 +00:00
SimplyTheOther
40eb6d5496 Added MN10300 target hook (or provisional one at least) 2020-11-28 21:13:18 +00:00
SimplyTheOther
2c9687c2df Added MMIX target hook (or provisional one at least) 2020-11-28 21:13:17 +00:00
SimplyTheOther
27029ad4df Added MIPS target hook (provisional at least) 2020-11-28 21:13:17 +00:00
SimplyTheOther
493cf535ec Modifications to tm.texi so that build should work 2020-11-28 21:13:17 +00:00
SimplyTheOther
5f3f4b1077 Added M*Core target hook (or provisional one at least) 2020-11-28 21:13:17 +00:00
SimplyTheOther
0195559c0e Added provisional Motorola 68K target hook 2020-11-28 21:13:17 +00:00
SimplyTheOther
695a885813 Added M32C target hook (provisional one at least) 2020-11-28 21:13:17 +00:00
SimplyTheOther
e742ebec78 Added Lico32 target hook (or at least provisional one) 2020-11-28 21:13:17 +00:00
SimplyTheOther
e58a5c9854 Added IQ2000 target hook 2020-11-28 21:13:17 +00:00
SimplyTheOther
6206176647 Added IA-64 target hook (should be okay but still should have some later attention) 2020-11-28 21:13:17 +00:00
SimplyTheOther
3e34ae54b0 Added (really crappy) GCN target hook 2020-11-28 21:13:17 +00:00
SimplyTheOther
72b91a85f0 Added FT32 target hook (or at least provisional one) 2020-11-28 21:13:17 +00:00
SimplyTheOther
b0eb8fb147 Added FRV target hook (or at least provisional one) 2020-11-28 21:13:17 +00:00
SimplyTheOther
3faf45fcf6 Added fr30 target hook (at least provisional one) 2020-11-28 21:13:16 +00:00
SimplyTheOther
158a1e0776 Added Epiphany target hook (or at least provisional one) 2020-11-28 21:13:16 +00:00
SimplyTheOther
03bc3cd682 Added C-SKY target hook (at least provisional one) 2020-11-28 21:13:16 +00:00
SimplyTheOther
f1d19b06d1 Added CR16 target hook (or provisional one at least) 2020-11-28 21:13:16 +00:00
SimplyTheOther
fad970a5ec Added TI C6X target hook (or a basic one at least) 2020-11-28 21:13:16 +00:00
Philip Herron
821da3d3a2 Refactor type resolution scoping to use a simple class akin to backend code 2020-11-28 21:13:16 +00:00
Philip Herron
15280699c1 Struct record compilation and type resolution 2020-11-28 21:13:16 +00:00
Nala Ginrut
84ed897a9b Remove redundant virtual functions in Resolution class
All these virtual functions are inherited from AST::ASTVisitor class
2020-11-28 21:13:16 +00:00
Nala Ginrut
0ec260e760 Add basic functions of name resolution 2020-11-28 21:13:16 +00:00
Nala Ginrut
c9658f9784 Add function signature in rust-name-resolution.h 2020-11-28 21:13:16 +00:00
Nala Ginrut
4433aa086a Add comments on the algorithm of name resolution 2020-11-28 21:13:16 +00:00
Philip Herron
de6bc4da46 Lower NegationExprs 2020-11-28 21:13:15 +00:00
Philip Herron
f230adf617 Compile conditional expressions if/if-else/if-elif-else 2020-11-28 21:13:15 +00:00
Philip Herron
6a9ddc7198 Ensure number of arguments match number of parameters to function before type analysis 2020-11-28 21:13:15 +00:00
Philip Herron
121ebe3f83 Compile LazyBooleans and ComparisonExpr to gimple 2020-11-28 21:13:15 +00:00
Philip Herron
ab24b0549e Fix up returns and call expressions to actually work 2020-11-28 21:13:15 +00:00
Philip Herron
6f772d2297 need access to the fields in AssignmentExpr and ReturnExpr 2020-11-28 21:13:15 +00:00
Philip Herron
d24bacfe4c More AST conversion to GIMPLE 2020-11-28 21:13:15 +00:00
Philip Herron
bcfe32f59d This creates the initial design for the pass to compile to GIMPLE by managing blocks in the scope 2020-11-28 21:13:15 +00:00
Philip Herron
c37f462746 Need access to the LHS of the expression 2020-11-28 21:13:15 +00:00
Philip Herron
0840906b74 Add a compilation unit scope to unitify how scoping is done in GIMPLE conversion 2020-11-28 21:13:15 +00:00
Philip Herron
b26c1f617c compile locals per block 2020-11-28 21:13:15 +00:00
Philip Herron
d3cb8c3cd9 We need to analyse and store the locals per block for compilation 2020-11-28 21:13:15 +00:00
Nala Ginrut
f641587ed0 Remove scoping in TypeResolution destructor 2020-11-28 21:13:14 +00:00
Nala Ginrut
323caf74be Remove scoping in NameResolution destructor 2020-11-28 21:13:14 +00:00
Nala Ginrut
a98e889e9a Move scoping to Resolution class 2020-11-28 21:13:14 +00:00
Philip Herron
e83e46cd08 add type resolution to parameters and return types of functions 2020-11-28 21:13:14 +00:00
Philip Herron
3601bdbe25 Start compilation of parameters and return type to functions 2020-11-28 21:13:14 +00:00
Philip Herron
484a4c96a2 Don't continue to compilation to GIMPLE phase if we saw errors 2020-11-28 21:13:14 +00:00
Philip Herron
cb00023bcb Need access to TypePath fields 2020-11-28 21:13:14 +00:00
Philip Herron
2c6cb7e543 Add the referenced function to the CallExpr when resolved 2020-11-28 21:13:14 +00:00
Philip Herron
1acf8eba36 Add type resolution to CallExpr
More work will be added here but there is enough to start working
on the initial AST -> Gimple transformations now.
2020-11-28 21:13:14 +00:00
Nala Ginrut
2be82f24b4 Add rust-name-resolution 2020-11-28 21:13:14 +00:00
Nala Ginrut
f26ccc9a6e Add rust-type-resolution 2020-11-28 21:13:14 +00:00
Nala Ginrut
de950d07f4 Refactor Resolution class 2020-11-28 21:13:14 +00:00
Nala Ginrut
0fee2a060b Change rust-session-manager for resolution refactoring 2020-11-28 21:13:13 +00:00
Philip Herron
0833b2d55e For tuple structs the constructor is just a regular function call
This is a hack to get the AST to become a CallExpr more changes might
occur later to cleanup this side of the AST.
2020-11-28 21:13:13 +00:00
Philip Herron
40a5081072 Add in a toplevel pass to grab global declarations for analysis pass 2020-11-28 21:13:13 +00:00
Philip Herron
b681de371e Reuse typeComparison checks in assignments and expressions 2020-11-28 21:13:13 +00:00
Philip Herron
89f624877d Initial type comparison code for error: E0308 2020-11-28 21:13:13 +00:00
Philip Herron
e8cff6a9da Need public access to Expr locus and rhs 2020-11-28 21:13:13 +00:00
Philip Herron
ae07b534e2 Template the scope class 2020-11-28 21:13:13 +00:00
Philip Herron
837cc2b5c4 Need access to function and params for CallExpr 2020-11-28 21:13:13 +00:00
Philip Herron
1d4a355a01 Infer types for AssignmentExpr 2020-11-28 21:13:13 +00:00
Philip Herron
289cbcc7e6 Infer types to scope for FunctionParams 2020-11-28 19:13:36 +00:00
Philip Herron
821e1fb4a6 Need to be able to visit LHS and RHS of AssignmentExpr 2020-11-28 19:13:35 +00:00
Philip Herron
d02f55c388 Need public to access locus and param name in FunctionParam 2020-11-28 19:13:35 +00:00
Philip Herron
b3c690081f Do inferencing on Expressions needs type match checking 2020-11-28 19:13:04 +00:00
Philip Herron
70f49c655b need public access to locus on OperatorExpr 2020-11-28 19:12:57 +00:00
Philip Herron
41b6aa7046 Need public access to IdentifierExpr ident and locus 2020-11-28 19:12:38 +00:00
Philip Herron
2f3980d416 make ArithmeticOrLogicalExpr visitable 2020-11-28 19:12:31 +00:00
Philip Herron
d0a1fcccb5 Add missing bool builtin 2020-11-28 19:12:22 +00:00
Philip Herron
fffedd1840 Add a basic lookup for builtin types 2020-11-28 19:12:14 +00:00
Philip Herron
b9289b5969 Add error E0282 when the LetStmt cannot be infered 2020-11-28 19:12:04 +00:00
Philip Herron
60cc2cf64b WIP more type inferencing code for LetStmt
Addresses: #12
2020-11-28 19:11:55 +00:00
Philip Herron
e62655562f need public access on the Literal from LiteralExpr 2020-11-28 19:11:46 +00:00
Philip Herron
ae88a9f49e Setup error handling for infering types in declarations 2020-11-28 19:11:30 +00:00
Philip Herron
0a75153ea0 need access to the expression for analysis 2020-11-28 19:11:23 +00:00
Philip Herron
b7eef6648b This will now compile a void function declaration to gimple
-fdump-tree-gimple should provide output of the skeleton function

Addresses #19
2020-11-28 19:11:10 +00:00
Nala Ginrut
3f37e20a37 Fix params printing in DelimTokenTree 2020-11-28 19:10:47 +00:00
Nala Ginrut
a4c6b7b751 Fix string literal printing in AST dump 2020-11-28 19:10:37 +00:00
Nala Ginrut
4bbfea1e41 Enhance let statement in AST dump 2020-11-28 19:10:27 +00:00
Philip Herron
9fec18623e This sets up the conversion from AST to GCC
It will crash when compiling but its the code setup i want to get in sooner
than later.

Addresses #15
2020-11-28 19:09:39 +00:00
Philip Herron
8e2f81b35a Revert "Test a clang-format lint"
This reverts commit 3a3c3ca4314534d03db6f6bb8acef24e091285e1.
2020-11-28 19:09:39 +00:00
Philip Herron
2c40a7f3c0 Test a clang-format lint 2020-11-28 19:09:39 +00:00
Philip Herron
16a1e8af9d This setups an initial frame work for our resolution step for the pipeline
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
2020-11-28 19:09:39 +00:00
SimplyTheOther
c7c6f785c8 Adding Rust target hook documentation
Added powerpc target hook and improved aarch64 feature handling
Added DEC Alpha target hook
Added ARC target hook
Created ARM target hook (at least preliminary support)
2020-11-28 19:09:39 +00:00
Nala Ginrut
7266d66d23 Fix indentation 2020-11-27 18:07:04 +00:00
SimplyTheOther
89d78a4a9e Initial target hook construction
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
2020-11-27 17:54:43 +00:00
Nala Ginrut
3835d919db Enhance AST dump 2020-11-27 17:07:11 +00:00
Nala Ginrut
9eb6439210 Fix typo in README.md 2020-11-27 17:06:53 +00:00
Nala Ginrut
a58bfa5308 Add rust_OBJS to fix compiling error 2020-11-27 17:06:40 +00:00
SimplyTheOther
6b779bad39 Fixed the compiler name in another place in Make-lang.in 2020-11-27 17:04:34 +00:00
SimplyTheOther
55750e277c Changed compiler name in Make-lang.in to be consistent with other files 2020-11-27 17:04:34 +00:00
SimplyTheOther
5a2eebc292 Cleanup and fixes to retain desired behaviour 2020-11-27 17:04:31 +00:00
Philip Herron
1ff5f98ee6 Fix broken build 2020-11-27 17:02:36 +00:00
Philip Herron
52243e9b39 Remove unused compilation code to GCC GENERIC.
Wire up Linemap abstraction object and location_t to Location
2020-11-27 17:02:35 +00:00
Philip Herron
3a2b1a2084 paralellized builds causes problems in workflow 2020-11-27 17:02:35 +00:00
Philip Herron
a4efcf829f Missing plugin-dev to provide insn-modes.h for workflow github env 2020-11-27 17:02:35 +00:00
Philip Herron
7a6059df73 Missing g++-multilib for workflow github env 2020-11-27 17:02:31 +00:00
Philip Herron
70137b4ec6 Update README for more instructions 2020-11-27 17:02:06 +00:00
Philip Herron
ead24ec624 Rebase GCCRS against SimplyTheOthers c++11 AST.
We can use this as a common base to build upon. It contains a fully
object orientated c++11 AST.
2020-11-27 16:57:47 +00:00
SimplyTheOther
9ccce9982b Fixed data structure for storing target data 2020-11-27 14:57:04 +00:00
SimplyTheOther
bc4080fb5d Added more type no bounds parsing 2020-11-27 14:52:51 +00:00
Philip Herron
a2ea9f7e70 Original rust code from 2014/2015 2020-11-27 14:51:23 +00:00
1181 changed files with 189542 additions and 16616 deletions

View File

@@ -1,24 +0,0 @@
## Contributing to GCC
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.
Perhaps one day it will be possible to use [GitGitGadget](https://gitgitgadget.github.io/)
to conveniently send Pull Requests commits to GCC's mailing list, the way that the Git
project currently allows it to be used to send PRs to their mailing list, but until that
day arrives, please send your patches to the mailing list manually.
Please read ["Contributing to GCC"](https://gcc.gnu.org/contribute.html) on the main GCC
website to learn how the GCC project is managed, and how you can work with it.
In addition, we highly recommend you to read
[our guidelines for read-write Git access](https://gcc.gnu.org/gitwrite.html).
Or, you can follow the
["Contributing to GCC in 10 easy steps"](https://gcc.gnu.org/wiki/GettingStarted#Basics:_Contributing_to_GCC_in_10_easy_steps)
section of the ["Getting Started" page](https://gcc.gnu.org/wiki/GettingStarted) on
[the wiki](https://gcc.gnu.org/wiki) for another example of the contribution process.
Your friendly GCC community!

4
.github/ISSUE_TEMPLATE/blank_issue.md vendored Normal file
View File

@@ -0,0 +1,4 @@
---
name: Blank Issue
about: Create a blank issue.
---

64
.github/ISSUE_TEMPLATE/bug_report.yml vendored Normal file
View File

@@ -0,0 +1,64 @@
name: Bug Report
description: Create a bug report
body:
- type: markdown
attributes:
value: Thank you for filing a bug report! 🐛
- type: textarea
id: problem
attributes:
label: Summary
description: >
Please provide a short summary of the bug, along with any information
you feel relevant to replicate the bug.
validations:
required: true
- type: textarea
id: reproducer
attributes:
label: Reproducer
description: Please provide the code and steps to reproduce the bug
value: |
I tried this code:
```rust
<code>
```
- type: checkboxes
id: nightly-features
attributes:
label: Does the code make use of any (1.49) nightly feature ?
options:
- label: Nightly
- type: input
id: godbolt
attributes:
label: Godbolt link
description: Optional link to godbolt snippet
placeholder: |
https://godbolt.org/z/vnK433Wox
- type: textarea
id: obtained
attributes:
label: Actual behavior
description: Please describe the actual behavior
value: |
The current behavior is...
validations:
required: true
- type: textarea
id: expected
attributes:
label: Expected behavior
description: Please describe the expected behavior
value: |
I expected to see...
- type: input
id: version
attributes:
label: GCC Version
description: "GCC version (`gcc --version`) or commit SHA"
placeholder: |
commit-hash: c4fecaf3c4fec4f3caf3c4fec4f3cafec4fecaf3
validations:
required: true

42
.github/ISSUE_TEMPLATE/ice.md vendored Normal file
View File

@@ -0,0 +1,42 @@
---
name: Internal Compiler Error
about: Create a report for an internal compiler error in Rust GCC.
labels: bug, ICE
---
<!--
Thank you for finding an Internal Compiler Error! 🧊 If possible, try to provide
a minimal verifiable example. You can read "Rust Bug Minimization Patterns" for
how to create smaller examples.
http://blog.pnkfx.org/blog/2019/11/18/rust-bug-minimization-patterns/
-->
### Code
```rust
<code>
```
### Meta
- What version of Rust GCC were you using, git sha if possible.
### Error output
```
<output>
```
<!--
Include a backtrace if available.
-->
<details><summary>Backtrace</summary>
<p>
```
<backtrace>
```
</p>
</details>

View File

@@ -1,5 +1,22 @@
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
that will be part of the merge commit.

77
.github/alpine_32bit_log_warnings vendored Normal file
View File

@@ -0,0 +1,77 @@
../../../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'

25
.github/emit_test_errors.pl vendored Executable file
View File

@@ -0,0 +1,25 @@
#!/bin/perl -n
sub analyze_errors() {
/^(FAIL|ERROR|XPASS):\s([^:\s]+):?\s+(.+)/;
my $type = $1;
my $filename = $2;
my $message = $3;
my $line;
if ( !$type ) { return; }
if ( $message =~ /(at line (\d+))?.+(test for \w+, line (\d+))/g ) {
$line = $2 || $4;
}
my $command = "::error file=gcc/testsuite/$filename";
if ($line) {
$command = "$command,line=$line";
}
print "$command,title=Test failure ($type)::$message\n";
}
analyze_errors();

View File

@@ -0,0 +1,132 @@
../../../../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'

154
.github/log_expected_warnings vendored Normal file
View File

@@ -0,0 +1,154 @@
../../../../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'

7
.github/no-bootstrap-asan.mk vendored Normal file
View File

@@ -0,0 +1,7 @@
# This option enables -fsanitize=address for stage1.
# Suppress LeakSanitizer in bootstrap.
export ASAN_OPTIONS=detect_leaks=0:use_odr_indicator=1
STAGE1_CFLAGS += -fsanitize=address
STAGE1_LDFLAGS += -fsanitize=address -static-libasan

30
.github/workflows/Remark.yml vendored Normal file
View File

@@ -0,0 +1,30 @@
name: Remark
on:
push:
branches:
- master
pull_request:
branches:
- master
jobs:
remark:
runs-on: ubuntu-latest
steps:
# Setup
- name: Checkout
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '16.x'
- name: Install remark
run: npm install remark-cli remark-lint remark-lint-maximum-line-length remark-preset-lint-recommended remark-gfm
# Run
- name: Check *.md files
run: git ls-files -z *.md | xargs -0 -n 1 npx remark -u lint -f > /dev/null

67
.github/workflows/bootstrap.yml vendored Normal file
View File

@@ -0,0 +1,67 @@
name: GCC Bootstrap Build
on:
schedule:
- cron: '0 0 * * *'
jobs:
build:
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v4
- name: Install Deps
run: |
sudo apt-get update;
sudo apt-get install -y \
automake \
autoconf \
libtool \
autogen \
bison \
flex \
libgmp3-dev \
libmpfr-dev \
libmpc-dev \
build-essential \
gcc-multilib \
g++-multilib \
dejagnu
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain=1.72.0;
- name: Configure
run: |
mkdir -p gccrs-build;
cd gccrs-build;
../configure \
--enable-languages=rust \
--enable-multilib
- name: Build
run: |
cd gccrs-build; \
# Build without network access
unshare --net --ipc -r /bin/bash -c "make -j $(nproc)"
- name: Run Tests
run: |
cd gccrs-build; \
make check-rust
- name: Archive check-rust results
uses: actions/upload-artifact@v4
with:
name: check-rust-logs
path: |
gccrs-build/gcc/testsuite/rust/
- name: Check regressions
run: |
cd gccrs-build; \
if grep "# of unexpected" gcc/testsuite/rust/rust.sum;\
then \
echo "some tests are not correct"; \
exit 1; \
else \
exit 0; \
fi

515
.github/workflows/ccpp.yml vendored Normal file
View File

@@ -0,0 +1,515 @@
name: GCC Rust build and test
on:
push:
branches:
- trying
- staging
pull_request:
branches: [ master ]
merge_group:
env:
ACTIONS_ALLOW_USE_UNSECURE_NODE_VERSION: true
jobs:
build-and-check-ubuntu-64bit:
env:
# Force locale, in particular for reproducible results re '.github/log_expected_warnings' (see below).
LC_ALL: C.UTF-8
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v4
- name: Install Deps
run: |
sudo apt-get update;
sudo apt-get install -y \
automake \
autoconf \
libtool \
autogen \
bison \
flex \
libgmp3-dev \
libmpfr-dev \
libmpc-dev \
build-essential \
gcc-multilib \
g++-multilib \
dejagnu;
# install Rust directly using rustup
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain=1.72.0;
- name: Make Source Read-Only
run: chmod -R a-w ./*
- name: Configure
run: |
mkdir -p gccrs-build;
cd gccrs-build;
../configure \
--enable-languages=rust \
--disable-bootstrap \
--enable-multilib
- name: Build
shell: bash
run: |
cd gccrs-build; \
# Add cargo to our path quickly
. "$HOME/.cargo/env"; \
# Build without network access
unshare --net --ipc -r /bin/bash -c "make -Otarget -j $(nproc) 2>&1 | tee log ; exit \${PIPESTATUS[0]}"
- name: Check for new warnings
run: |
cd gccrs-build
< log grep 'warning: ' | sort > log_warnings
if diff -U0 ../.github/log_expected_warnings log_warnings; then
:
else
echo 'See <https://github.com/Rust-GCC/gccrs/pull/1026>.'
exit 1
fi >&2
- name: Run Tests
run: |
cd gccrs-build; \
make check-rust RUNTESTFLAGS="--target_board=unix\{-m64}"
- name: Archive check-rust results
uses: actions/upload-artifact@v4
with:
name: check-rust-logs-ubuntu-64
path: |
gccrs-build/gcc/testsuite/rust/
- name: Check regressions
run: |
cd gccrs-build; \
if grep -e "unexpected" -e "unresolved" -e "ERROR:" gcc/testsuite/rust/rust.sum;\
then \
echo "::error title=Regression test failed::some tests are not correct"; \
perl -n ../.github/emit_test_errors.pl < gcc/testsuite/rust/rust.sum; \
exit 1; \
else \
exit 0; \
fi
build-and-check-ubuntu-64bit-glibcxx:
env:
# Force locale, in particular for reproducible results re '.github/log_expected_warnings' (see below).
LC_ALL: C.UTF-8
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v4
- name: Install Deps
run: |
sudo apt-get update;
sudo apt-get install -y \
automake \
autoconf \
libtool \
autogen \
bison \
flex \
libgmp3-dev \
libmpfr-dev \
libmpc-dev \
build-essential \
gcc-multilib \
g++-multilib \
dejagnu;
# install Rust directly using rustup
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain=1.72.0;
- name: Make Source Read-Only
run: chmod -R a-w ./*
- name: Configure
run: |
mkdir -p gccrs-build;
cd gccrs-build;
export CXXFLAGS="$CXXFLAGS -D_GLIBCXX_ASSERTIONS"
../configure \
--enable-languages=rust \
--disable-bootstrap \
--enable-multilib
- name: Build
shell: bash
run: |
cd gccrs-build; \
# Add cargo to our path quickly
. "$HOME/.cargo/env";
make -Otarget -j $(nproc) 2>&1 | tee log
- name: Check for new warnings
run: |
cd gccrs-build
< log grep 'warning: ' | sort > log_warnings
if diff -U0 ../.github/glibcxx_ubuntu64b_log_expected_warnings log_warnings; then
:
else
echo 'See <https://github.com/Rust-GCC/gccrs/pull/1026>.'
exit 1
fi >&2
- name: Run Tests
run: |
cd gccrs-build; \
make check-rust RUNTESTFLAGS="--target_board=unix\{-m64}"
- name: Archive check-rust results
uses: actions/upload-artifact@v4
with:
name: check-rust-logs-ubuntu-64-glibcxx
path: |
gccrs-build/gcc/testsuite/rust/
- name: Check regressions
run: |
cd gccrs-build; \
if grep -e "unexpected" -e "unresolved" -e "ERROR:" gcc/testsuite/rust/rust.sum;\
then \
echo "::error title=Regression test failed::some tests are not correct"; \
perl -n ../.github/emit_test_errors.pl < gcc/testsuite/rust/rust.sum; \
exit 1; \
else \
exit 0; \
fi
build-and-check-ubuntu-32bit:
env:
# Force locale, in particular for reproducible results re '.github/log_expected_warnings' (see below).
LC_ALL: C.UTF-8
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v4
- name: Install Deps
run: |
sudo apt-get update;
sudo apt-get install -y \
automake \
autoconf \
libtool \
autogen \
bison \
flex \
libgmp3-dev \
libmpfr-dev \
libmpc-dev \
build-essential \
gcc-multilib \
g++-multilib \
dejagnu;
# install Rust directly using rustup
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain=1.72.0;
- name: Make Source Read-Only
run: chmod -R a-w ./*
- name: Configure
run: |
mkdir -p gccrs-build;
cd gccrs-build;
../configure \
--enable-languages=rust \
--disable-bootstrap \
--enable-multilib
- name: Build
shell: bash
run: |
cd gccrs-build; \
# Add cargo to our path quickly
. "$HOME/.cargo/env";
make -Otarget -j $(nproc) 2>&1 | tee log
- name: Check for new warnings
run: |
cd gccrs-build
< log grep 'warning: ' | sort > log_warnings
if diff -U0 ../.github/log_expected_warnings log_warnings; then
:
else
echo 'See <https://github.com/Rust-GCC/gccrs/pull/1026>.'
exit 1
fi >&2
- name: Run Tests
run: |
cd gccrs-build; \
make check-rust RUNTESTFLAGS="--target_board=unix\{-m32}"
- name: Archive check-rust results
uses: actions/upload-artifact@v4
with:
name: check-rust-logs-ubuntu-32
path: |
gccrs-build/gcc/testsuite/rust/
- name: Check regressions
run: |
cd gccrs-build; \
if grep -e "unexpected" -e "unresolved" -e "ERROR:" gcc/testsuite/rust/rust.sum;\
then \
echo "::error title=Regression test failed::some tests are not correct"; \
perl -n ../.github/emit_test_errors.pl < gcc/testsuite/rust/rust.sum; \
exit 1; \
else \
exit 0; \
fi
build-and-check-gcc-5:
runs-on: ubuntu-22.04
env:
# otherwise we hang when installing tzdata
DEBIAN_FRONTEND: noninteractive
steps:
- uses: actions/checkout@v4
- name: Install Deps
run: |
sudo apt-get update;
sudo apt-get install -y \
curl \
automake \
autoconf \
libtool \
autogen \
bison \
flex \
libc6-dev \
libc6-dev-i386 \
libgmp3-dev \
libmpfr-dev \
libmpc-dev \
build-essential \
dejagnu;
# install Rust directly using rustup
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain=1.72.0;
- name: Restore cached gcc-5.4
id: restore-gcc5
uses: actions/cache/restore@v4
with:
key: ce-tar-gcc-5
path: ~/gcc-5.4.0/
- name: Download and install gcc5.4
if: ${{ steps.restore-gcc5.outputs.cache-hit != 'true' }}
run: |
curl "https://s3.amazonaws.com/compiler-explorer/opt/gcc-5.4.0.tar.xz" -o /tmp/gcc.tar.xz;
cd ~;
tar xvf /tmp/gcc.tar.xz
- name: Store gcc-5.4 to cache
id: cache-gcc5
if: always() && steps.restore-gcc5.outputs.cache-hit != 'true'
uses: actions/cache/save@v4
with:
key: ce-tar-gcc-5
path: ~/gcc-5.4.0/
- name: Make Source Read-Only
run: chmod -R a-w ./*
- name: Configure
run: |
mkdir -p gccrs-build;
cd gccrs-build;
# Add cargo to our path quickly
. "$HOME/.cargo/env";
PATH=$HOME/gcc-5.4.0/bin:$PATH \
../configure \
--enable-languages=rust \
--disable-bootstrap \
--enable-multilib
- name: Build
shell: bash
run: |
# Add cargo to our path quickly
. "$HOME/.cargo/env";
PATH=$HOME/gcc-5.4.0/bin:$PATH \
make -C gccrs-build -j $(nproc)
- name: Run Tests
run: |
cd gccrs-build; \
PATH=$HOME/gcc-5.4.0/bin:$PATH \
make check-rust RUNTESTFLAGS="--target_board=unix\{-m32,-m64}"
- name: Archive check-rust results
uses: actions/upload-artifact@v4
with:
name: check-rust-logs-5
path: |
gccrs-build/gcc/testsuite/rust/
- name: Check regressions
run: |
cd gccrs-build; \
if grep -e "unexpected" -e "unresolved" -e "ERROR:" gcc/testsuite/rust/rust.sum;\
then \
echo "::error title=Regression test failed::some tests are not correct"; \
exit 1; \
else \
exit 0; \
fi
# build-and-check-clang-macos:
# env:
# # Force CC/CXX to be explicitly clang to make it clear which compiler is used
# CC: clang
# CXX: clang++
# runs-on: macos-13
# steps:
# - uses: actions/checkout@v4
# - name: Install Deps
# run: |
# brew install dejagnu mpfr libmpc gmp;
# # install Rust directly using rustup
# curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain=1.72.0;
# - name: Make Source Read-Only
# run: chmod -R a-w ./*
# - name: Configure
# run: |
# mkdir -p gccrs-build;
# cd gccrs-build;
# ../configure \
# --enable-languages=rust \
# --disable-bootstrap \
# --enable-multilib \
# --with-native-system-header-dir=/usr/include \
# --with-sysroot=$(xcrun --show-sdk-path)
# - name: Build
# shell: bash
# run: |
# cd gccrs-build; \
# make -j $(sysctl -n hw.ncpu) 2>&1 | tee log
# - name: Run Tests
# run: |
# cd gccrs-build; \
# make check-rust
# - name: Archive check-rust results
# uses: actions/upload-artifact@v4
# with:
# name: check-rust-logs-macos
# path: |
# gccrs-build/gcc/testsuite/rust/
# - name: Check regressions
# run: |
# cd gccrs-build; \
# if grep -e "unexpected" -e "unresolved" -e "ERROR:" gcc/testsuite/rust/rust.sum;\
# then \
# echo "::error title=Regression test failed::some tests are not correct"; \
# exit 1; \
# else \
# exit 0; \
# fi
build-and-check-asan:
env:
# Force locale, in particular for reproducible results re '.github/log_expected_warnings' (see below).
LC_ALL: C.UTF-8
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v4
- name: Install Deps
run: |
sudo apt-get update;
sudo apt-get install -y \
automake \
autoconf \
libtool \
autogen \
bison \
flex \
libgmp3-dev \
libmpfr-dev \
libmpc-dev \
build-essential \
gcc-multilib \
g++-multilib \
dejagnu;
# install Rust directly using rustup
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain=1.72.0;
- name: Make Source Read-Only
run: chmod -R a-w ./*
- name: Configure
run: |
mkdir -p gccrs-build;
cd gccrs-build;
../configure \
--enable-languages=rust \
--disable-bootstrap \
--enable-multilib \
--with-build-config=../.github/no-bootstrap-asan
- name: Build
shell: bash
run: |
cd gccrs-build; \
# Add cargo to our path quickly
. "$HOME/.cargo/env";
make -Otarget -j $(nproc) 2>&1 | tee log
# Skip warnings check
# - name: Check for new warnings
# run: |
# cd gccrs-build
# < log grep 'warning: ' | sort > log_warnings
# if diff -U0 ../.github/log_expected_warnings log_warnings; then
# :
# else
# echo 'See <https://github.com/Rust-GCC/gccrs/pull/1026>.'
# exit 1
# fi >&2
- name: Run Tests
run: |
cd gccrs-build; \
ASAN_OPTIONS=detect_leaks=0:use_odr_indicator=1 \
make check-rust RUNTESTFLAGS="--target_board=unix\{-m64}"
- name: Archive check-rust results
uses: actions/upload-artifact@v4
with:
name: check-rust-logs-asan
path: |
gccrs-build/gcc/testsuite/rust/
- name: Check regressions
run: |
cd gccrs-build; \
if grep -e "unexpected" -e "unresolved" -e "ERROR:" gcc/testsuite/rust/rust.sum;\
then \
echo "::error title=Regression test failed::some tests are not correct"; \
perl -n ../.github/emit_test_errors.pl < gcc/testsuite/rust/rust.sum; \
exit 1; \
else \
exit 0; \
fi

129
.github/workflows/ccpp32alpine.yml vendored Normal file
View File

@@ -0,0 +1,129 @@
name: GCC Rust build and test (Alpine 32-bit)
on:
push:
branches:
- trying
- staging
pull_request:
branches: [ master ]
merge_group:
env:
ACTIONS_ALLOW_USE_UNSECURE_NODE_VERSION: true
jobs:
build-alpine-32bit-and-check-alpine-32bit:
env:
# Force locale, in particular for reproducible results re '.github/log_expected_warnings' (see below).
LC_ALL: C.UTF-8
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v4
- name: Setup Alpine Linux (32-bit)
uses: jirutka/setup-alpine@v1
with:
arch: x86
packages: >
automake
autoconf
libtool
bison
flex
gmp-dev
mpfr-dev
mpc1-dev
build-base
dejagnu
curl
gcompat
libc6-compat
libc-dev
libc++-dev
cargo
# - name: Install gcc dependency
# run: |
# sudo apt install gcc-multilib g++-multilib libc6-dev-i386
# - name: Install Rust
# run: |
# curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain=1.72.0
# shell: alpine.sh {0}
- name: Install dependencies with gcc
run: |
./contrib/download_prerequisites
shell: alpine.sh {0}
- name: Configure
run: |
mkdir -p gccrs-build;
cd gccrs-build;
../configure \
--host=i586-alpine-linux-musl --build=i586-alpine-linux-musl --target=i586-alpine-linux-musl \
--enable-languages=rust \
--disable-bootstrap \
--disable-multilib # Try to disable multilib on alpine https://github.com/conan-io/conan/issues/14307#issuecomment-1652433132
shell: alpine.sh {0}
- name: Build
run: |
cd gccrs-build; \
# Add cargo to our path quickly
# . "$HOME/.cargo/env";
make -Otarget -j $(nproc) 2>&1 | tee log
shell: alpine.sh {0}
- name: Produce warning logs
run: |
cd gccrs-build
< log grep 'warning: ' | sort > log_warnings
cat log_warnings
shell: alpine.sh {0}
- name: Archive warnings logs
uses: actions/upload-artifact@v4
with:
name: warnings
path: |
gccrs-build/log_warnings
- name: Check for new warnings
run: |
cd gccrs-build
< log grep 'warning: ' | sort > log_warnings
if diff -U0 ../.github/alpine_32bit_log_warnings log_warnings; then
:
else
echo 'See <https://github.com/Rust-GCC/gccrs/pull/1026>.'
exit 1
fi >&2
shell: alpine.sh {0}
- name: Run Tests
run: |
cd gccrs-build; \
make check-rust RUNTESTFLAGS="--target_board=unix\{-m32}"
shell: alpine.sh {0}
- name: Archive check-rust results
uses: actions/upload-artifact@v4
with:
name: check-rust-logs
path: |
gccrs-build/gcc/testsuite/rust/
- name: Check regressions
run: |
cd gccrs-build; \
if grep -e "unexpected" -e "unresolved" -e "ERROR:" gcc/testsuite/rust/rust.sum;\
then \
echo "::error title=Regression test failed::some tests are not correct"; \
perl -n ../.github/emit_test_errors.pl < gcc/testsuite/rust/rust.sum; \
exit 1; \
else \
exit 0; \
fi
shell: alpine.sh {0}

26
.github/workflows/clang-format.yml vendored Normal file
View File

@@ -0,0 +1,26 @@
name: Clang Format Lint
on:
push:
branches:
- trying
- staging
pull_request:
branches: [ master ]
merge_group:
jobs:
clang-format:
runs-on: ubuntu-latest
steps:
# If updating these steps, please also correspondingly update '../../CONTRIBUTING.md', "Running `clang-format` locally".
- uses: actions/checkout@v4
- name: Copy .clang-format file
run: cp contrib/clang-format .clang-format
- name: Check clang-format
uses: DoozyX/clang-format-lint-action@v0.18.2
with:
source: 'gcc/rust/ libgrust/'
extensions: 'h,cc'
clangFormatVersion: 10

140
.github/workflows/commit-format.yml vendored Normal file
View File

@@ -0,0 +1,140 @@
name: GNU Commit Format Checker
on:
pull_request:
branches:
- master
- gcc-patch-dev
merge_group:
jobs:
check-commit-changelogs:
runs-on: ubuntu-latest
name: check-changelogs
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.head.sha }}
fetch-depth: 0
- name: Install Deps
run: |
sudo apt-get update;
sudo apt-get install -y \
python3 \
python3-git
- name: GCC check PR Commits
run: |
if ${{ github.event_name == 'pull_request' }}; then
python3 contrib/gcc-changelog/git_check_commit.py origin/${{ github.event.pull_request.base.ref }}..${{ github.event.pull_request.head.sha }}
fi
check-commit-prefixes:
runs-on: ubuntu-latest
name: check-gccrs-prefix
if: ${{ github.base_ref == 'gcc-patch-dev' }} # master commits don't need the gccrs prefix
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.head.sha }}
fetch-depth: 0
- name: Check for `gccrs` prefix
run: |
retval=0
for commit in $(git rev-list origin/${{ github.event.pull_request.base.ref }}..${{ github.event.pull_request.head.sha }});
do
echo -n "Checking gccrs prefix for $commit: " >> results
if [[ $(git log -1 --format="%s" $commit) = gccrs:* ]]; then
echo "OK" >> results
else
retval=1
echo "KO" >> results
fi
done
exit $retval
check-commit-signoff:
runs-on: ubuntu-latest
name: check-commit-signoff
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.head.sha }}
fetch-depth: 0
- name: Check for DCO Sign-Off line/possible FSF Copyright Assignment
run: |
retval=0;
rev_list="origin/${{ github.event.pull_request.base.ref }}..${{ github.event.pull_request.head.sha }}"
for commit in $(git rev-list --reverse "$rev_list"); do
echo -n "Checking for DCO Sign-Off for commit $commit... ";
if [[ $(git log "$commit" -1 --format="%B" | tail -n 2) = Signed-off-by:* ]]; then
echo "OK";
continue;
fi
author=$(git log -1 --format=%an "$commit");
if [[ "$(( $(git log --author="$author"|wc -l) - $(git log --author="$author" --grep='Signed-off-by'|wc -l )))" -ne 0 ]]; then
echo "OK"
echo "$author probably has FSF Copyright Assignment. Check manually that the lack of DCO Sign-Off is allowed."
else
echo "KO"
retval=1;
fi
done;
## check no Signed-off-by in the middle.
while read -r f; do
echo -n "$f : "
if awk 'BEGIN { in_footer = 0; error = 0;}
{ DEFAULT = 1; }
/^(Signed-off|Co-authored|Reviewed|Tested)-by/ { in_footer = 1; DEFAULT = 0;}
/^\s*$/ { DEFAULT = 0; }
DEFAULT { if (in_footer == 1) { printf $0 " appears after some Signed-off-by/Co-authored-by/Tested-by/Reviewed-by line "; error = 1; exit (1);} }';
then
echo OK
else
echo KO
retval=1
fi < <(git log "$f" -1 --format="%B")
done < <(git rev-list --reverse "$rev_list" )
exit $retval;
check-issue-reference:
runs-on: ubuntu-latest
continue-on-error: true # We do not want to block merge if it is a legitimate GCC bugzilla reference.
name: check-issue-reference
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.head.sha }}
fetch-depth: 0
- name: Check for issue number reference in commit messages
run: |
retval=0;
rev_list="origin/${{ github.event.pull_request.base.ref }}..${{ github.event.pull_request.head.sha }}"
for commit in $(git rev-list --reverse "$rev_list"); do
if [ "$(git log --format=%B -n 1 \"$commit\" | grep '#[0-9]*' | grep -v -i 'Rust-GCC/gccrs#[0-9]*' | wc -l)" -ne 0 ]; then
echo "$commit: KO"
retval=1
else
echo "$commit: OK"
fi
done;
if [ "$retval" -ne 0 ]; then
echo "Some raw issue references were found (eg. #4242)."
echo "You shall rewrite the faulty commit message with this format: Rust-GCC/gccrs#4242"
echo "You may ignore this CI step if it represents a valid GCC bugzilla or external repository reference instead."
fi
exit $retval;

34
.github/workflows/docker.yml vendored Normal file
View File

@@ -0,0 +1,34 @@
name: Build Docker image
on:
push:
branches:
- 'master'
jobs:
docker:
runs-on: ubuntu-latest
steps:
-
name: Checkout
uses: actions/checkout@v4
-
name: Set up QEMU
uses: docker/setup-qemu-action@v2
-
name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2
-
name: Login to DockerHub
uses: docker/login-action@v2
if: github.repository == 'Rust-GCC/gccrs'
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
-
name: Build and push
uses: docker/build-push-action@v4
with:
context: .
push: ${{ github.repository == 'Rust-GCC/gccrs' }}
tags: philberty/gccrs:latest

7
.gitignore vendored
View File

@@ -70,3 +70,10 @@ stamp-*
/gmp*
/isl*
/gettext*
# ADDITIONS from GCCRS front-end
.vscode/*
test.code-workspace
gcc/rust/test3-tiny/*
.clang-format.swap

14
.remarkrc Normal file
View File

@@ -0,0 +1,14 @@
{
"plugins": [
"remark-preset-lint-recommended",
"remark-gfm",
["remark-lint-maximum-line-length", 120],
["remark-lint-list-item-indent", false],
["remark-lint-no-literal-urls", false],
["remark-lint-no-shortcut-reference-link", false]
],
"settings": {
"commonmark": true
}
}

128
CODE_OF_CONDUCT.md Normal file
View File

@@ -0,0 +1,128 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, religion, or sexual identity
and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our
community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the
overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or
advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email
address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.
Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
https://github.com/orgs/Rust-GCC/people.
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the
reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series
of actions.
**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or
permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within
the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.0, available at
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
Community Impact Guidelines were inspired by [Mozilla's code of conduct
enforcement ladder](https://github.com/mozilla/diversity).
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations.

View File

@@ -4,7 +4,8 @@
* **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)

72
Dockerfile Normal file
View File

@@ -0,0 +1,72 @@
FROM debian:12 AS gcc-builder
RUN apt-get update; \
DEBIAN_FRONTEND="noninteractive" apt-get install -y --no-install-recommends \
autoconf \
automake \
bzip2\
dpkg-dev \
file \
wget \
curl \
build-essential \
imagemagick \
libbz2-dev \
libc6-dev \
libcurl4-openssl-dev \
libdb-dev \
libevent-dev \
libffi-dev \
libgdbm-dev \
libglib2.0-dev \
libgmp-dev \
libjpeg-dev \
libkrb5-dev \
liblzma-dev \
libmagickcore-dev \
libmagickwand-dev \
libmaxminddb-dev \
libncurses5-dev \
libncursesw5-dev \
libpng-dev \
libpq-dev \
libreadline-dev \
libsqlite3-dev \
libssl-dev \
libtool \
libwebp-dev \
libxml2-dev \
libxslt-dev \
libyaml-dev \
make \
patch \
unzip \
xz-utils \
zlib1g-dev \
flex \
bison \
git
ADD . /usr/src/gcc
RUN /bin/sh -c set -ex; \
cd /usr/src/gcc; \
git log -1 --format="%h" > /GCCRS_BUILD; \
./contrib/download_prerequisites; { rm *.tar.* || true; }; \
mkdir -p /usr/src/gcc/gcc-build; \
cd /usr/src/gcc/gcc-build; \
/usr/src/gcc/configure --disable-bootstrap --disable-multilib --enable-languages=rust; \
make -j "$(nproc)"; \
make install-strip; \
cd /root; \
rm -rf /usr/src/gcc
RUN /bin/sh -c set -ex; \
echo '/usr/local/lib64' > /etc/ld.so.conf.d/local-lib64.conf; \
ldconfig -v
FROM rust:latest
COPY --from=gcc-builder /usr/ /usr/
COPY --from=gcc-builder /GCCRS_BUILD /GCCRS_BUILD
RUN cargo install --git https://github.com/Rust-GCC/cargo-gccrs cargo-gccrs
CMD ["bash"]

View File

@@ -197,6 +197,7 @@ HOST_EXPORTS = \
$(BASE_EXPORTS) \
CC="$(CC)"; export CC; \
ADA_CFLAGS="$(ADA_CFLAGS)"; export ADA_CFLAGS; \
CRAB1_LIBS="$(CRAB1_LIBS)"; export CRAB1_LIBS; \
CFLAGS="$(CFLAGS)"; export CFLAGS; \
CONFIG_SHELL="$(SHELL)"; export CONFIG_SHELL; \
CXX="$(CXX)"; export CXX; \
@@ -450,6 +451,8 @@ GOCFLAGS = $(CFLAGS)
GDCFLAGS = @GDCFLAGS@
GM2FLAGS = $(CFLAGS)
CRAB1_LIBS = @CRAB1_LIBS@
PKG_CONFIG_PATH = @PKG_CONFIG_PATH@
GUILE = guile

View File

@@ -200,6 +200,7 @@ HOST_EXPORTS = \
$(BASE_EXPORTS) \
CC="$(CC)"; export CC; \
ADA_CFLAGS="$(ADA_CFLAGS)"; export ADA_CFLAGS; \
CRAB1_LIBS="$(CRAB1_LIBS)"; export CRAB1_LIBS; \
CFLAGS="$(CFLAGS)"; export CFLAGS; \
CONFIG_SHELL="$(SHELL)"; export CONFIG_SHELL; \
CXX="$(CXX)"; export CXX; \
@@ -453,6 +454,8 @@ GOCFLAGS = $(CFLAGS)
GDCFLAGS = @GDCFLAGS@
GM2FLAGS = $(CFLAGS)
CRAB1_LIBS = @CRAB1_LIBS@
PKG_CONFIG_PATH = @PKG_CONFIG_PATH@
GUILE = guile

View File

@@ -3,7 +3,7 @@
[![Build Docker image](https://github.com/Rust-GCC/gccrs/actions/workflows/docker.yml/badge.svg)](https://github.com/Rust-GCC/gccrs/actions/workflows/docker.yml)
![Docker Pulls](https://img.shields.io/docker/pulls/philberty/gccrs)
[![project chat](https://img.shields.io/badge/zulip-join_chat-brightgreen.svg)](https://gcc-rust.zulipchat.com/)
[![Bors enabled](https://bors.tech/images/badge_small.svg)](https://app.bors.tech/repositories/32890)
[![justforfunnoreally.dev badge](https://img.shields.io/badge/justforfunnoreally-dev-9ff)](https://justforfunnoreally.dev)
# GCC Rust
![GCC Rust](logo.png?raw=true "GCC rust Logo")
@@ -45,6 +45,12 @@ Fetch dependencies for Ubuntu:
$ apt install build-essential libgmp3-dev libmpfr-dev libmpc-dev flex bison autogen gcc-multilib dejagnu
```
Fetch dependencies for Fedora:
```bash
$ dnf install autoconf automake dejagnu flex bison glibc-devel.{x86_64,i686} gmp-devel libmpc-devel mpfr-devel
```
Clone the repository
```bash
@@ -74,12 +80,18 @@ $ make
```
Alternatively, a docker environment is available for ARM-based Mac contributors.
Please visit [gccrs-workspace](https://github.com/badumbatish/gccrs-workspace).
The image is based on Ubuntu ARM and comes with dependencies all fetched.
#### Running GCC Rust
Running the compiler itself without make install we can simply invoke the compiler proper:
```bash
$ ./gcc/crab1 test.rs -frust-debug -frust-dump-parse -Warray-bounds -dumpbase test.rs -mtune=generic -march=x86-64 -O0 -version -fdump-tree-gimple -o test.s -L/lib/x86_64-linux-gnu -L/lib/../lib64 -L/usr/lib/x86_64-linux-gnu -L/usr/lib/../lib64 -frust-incomplete-and-experimental-compiler-do-not-use
$ ./gcc/crab1 test.rs -frust-debug -frust-dump-ast-pretty -Warray-bounds -dumpbase test.rs -mtune=generic -march=x86-64 -O0 -version -fdump-tree-gimple -o test.s -L/lib/x86_64-linux-gnu -L/lib/../lib64 -L/usr/lib/x86_64-linux-gnu -L/usr/lib/../lib64 -frust-incomplete-and-experimental-compiler-do-not-use
```
To invoke the compiler driver (gccrs) we need to:
@@ -91,8 +103,8 @@ $ make install
Then invoke the compiler from the installation directory:
```bash
$ $HOME/gccrs-install/gccrs -g -O2 -c test.rs -o test.o
$ $HOME/gccrs-install/gccrs -o test test.o
$ $HOME/gccrs-install/bin/gccrs -g -O2 -c test.rs -o test.o -frust-incomplete-and-experimental-compiler-do-not-use
$ $HOME/gccrs-install/bin/gccrs -o test test.o
```
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.

987
configure vendored

File diff suppressed because it is too large Load Diff

View File

@@ -1456,16 +1456,16 @@ case "$have_compiler:$host:$target:$enable_bootstrap" in
;;
esac
# When bootstrapping with GCC, build stage 1 in C++11 mode to ensure that a
# C++11 compiler can still start the bootstrap. Otherwise, if building GCC,
# require C++11 (or higher).
# When bootstrapping with GCC, build stage 1 in C++14 mode to ensure that a
# C++14 compiler can still start the bootstrap. Otherwise, if building GCC,
# require C++14 (or higher).
if test "$enable_bootstrap:$GXX" = "yes:yes"; then
CXX="$CXX -std=c++11"
CXX="$CXX -std=c++14"
elif test "$have_compiler" = yes; then
AX_CXX_COMPILE_STDCXX(11)
AX_CXX_COMPILE_STDCXX(14)
if test "${build}" != "${host}"; then
AX_CXX_COMPILE_STDCXX(11, [], [], [_FOR_BUILD])
AX_CXX_COMPILE_STDCXX(14, [], [], [_FOR_BUILD])
fi
fi
@@ -2036,6 +2036,29 @@ fi
AC_SUBST(PICFLAG)
# Rust requires -ldl and -lpthread if you are using an old glibc that does not include them by
# default, so we check for them here
# We are doing the test here and not in the gcc/configure to be able to nicely disable the
# build of the Rust frontend in case a dep is missing.
missing_rust_dynlibs=none
save_LIBS="$LIBS"
LIBS=
AC_SEARCH_LIBS([dlopen], [dl])
AC_SEARCH_LIBS([pthread_create], [pthread])
CRAB1_LIBS="$LIBS"
LIBS="$save_LIBS"
if test "$ac_cv_search_dlopen" = no; then
missing_rust_dynlibs="libdl"
fi
if test "$ac_cv_search_pthread_create" = no; then
missing_rust_dynlibs="$missing_rust_dynlibs, libpthread"
fi
AC_SUBST(CRAB1_LIBS, "$CRAB1_LIBS")
# If we are building PIC/PIE host executables, and we are building dependent
# libs (e.g. GMP) in-tree those libs need to be configured to generate PIC
# code.
@@ -2273,6 +2296,25 @@ if test -d ${srcdir}/gcc; then
;;
esac
# Disable Rust if we are missing some required C libraries for the Rust runtime.
case ${add_this_lang}:${language}:${missing_rust_dynlibs} in
*:rust:none)
# Nothing to do - we're not missing any C libraries
;;
yes:rust:*)
AC_MSG_ERROR([some C libraries are required to build $language: $missing_rust_dynlibs])
add_this_lang=unsupported
;;
all:rust:*)
AC_MSG_WARN([some C libraries are required to build $language: $missing_rust_dynlibs])
add_this_lang=unsupported
;;
*:rust:*)
# Silently disable.
add_this_lang=unsupported
;;
esac
# Disable jit if -enable-host-shared not specified
# but not if building for Mingw. All code in Windows
# is position independent code (PIC).

View File

@@ -156,6 +156,7 @@ libgomp/config.h.in: libgomp/configure.ac libgomp/aclocal.m4
libgrust/Makefile.in: libgrust/Makefile.am libgrust/aclocal.m4
libgrust/aclocal.m4: libgrust/configure.ac
libgrust/configure: libgrust/configure.ac libgrust/aclocal.m4
libgrust/libformat_parser/Makefile.in: libgrust/libformat_parser/Makefile.am libgrust/aclocal.m4
libgrust/libproc_macro_internal/Makefile.in: libgrust/libproc_macro_internal/Makefile.am libgrust/aclocal.m4
libitm/aclocal.m4: libitm/configure.ac libitm/acinclude.m4
libitm/Makefile.in: libitm/Makefile.am libitm/aclocal.m4

View File

@@ -779,6 +779,7 @@ class GCCCmdLine (CmdLine):
self.add_dir ('libgfortran')
# libgo is imported from upstream.
self.add_dir ('libgomp')
self.add_dir ('libgrust')
self.add_dir ('libiberty')
self.add_dir ('libitm')
self.add_dir ('libobjc')
@@ -806,6 +807,7 @@ class GCCCmdLine (CmdLine):
'libgcc',
'libgfortran',
'libgomp',
'libgrust',
'libiberty',
'libitm',
'libobjc',

View File

@@ -0,0 +1,93 @@
if (TARGET_64BIT)
ADD_TARGET_INFO ("target_arch", "x86_64");
else
ADD_TARGET_INFO ("target_arch", "x86");
// features officially "stabilised" in rustc
if (TARGET_MMX)
ADD_TARGET_INFO ("target_feature", "mmx");
if (TARGET_SSE)
ADD_TARGET_INFO ("target_feature", "sse");
if (TARGET_SSE2)
ADD_TARGET_INFO ("target_feature", "sse2");
if (TARGET_SSE3)
ADD_TARGET_INFO ("target_feature", "sse3");
if (TARGET_SSSE3)
ADD_TARGET_INFO ("target_feature", "ssse3");
if (TARGET_SSE4_1)
ADD_TARGET_INFO ("target_feature", "sse4.1");
if (TARGET_SSE4_2)
ADD_TARGET_INFO ("target_feature", "sse4.2");
if (TARGET_AES)
ADD_TARGET_INFO ("target_feature", "aes");
if (TARGET_SHA)
ADD_TARGET_INFO ("target_feature", "sha");
if (TARGET_AVX)
ADD_TARGET_INFO ("target_feature", "avx");
if (TARGET_AVX2)
ADD_TARGET_INFO ("target_feature", "avx2");
if (TARGET_AVX512F)
ADD_TARGET_INFO ("target_feature", "avx512f");
if (TARGET_AVX512CD)
ADD_TARGET_INFO ("target_feature", "avx512cd");
if (TARGET_AVX512DQ)
ADD_TARGET_INFO ("target_feature", "avx512dq");
if (TARGET_AVX512BW)
ADD_TARGET_INFO ("target_feature", "avx512bw");
if (TARGET_AVX512VL)
ADD_TARGET_INFO ("target_feature", "avx512vl");
if (TARGET_AVX512VBMI)
ADD_TARGET_INFO ("target_feature", "avx512vbmi");
if (TARGET_AVX512IFMA)
ADD_TARGET_INFO ("target_feature", "avx512ifma");
if (TARGET_AVX512VPOPCNTDQ)
ADD_TARGET_INFO ("target_feature", "avx512vpopcntdq");
if (TARGET_FMA)
ADD_TARGET_INFO ("target_feature", "fma");
if (TARGET_RTM)
ADD_TARGET_INFO ("target_feature", "rtm");
if (TARGET_SSE4A)
ADD_TARGET_INFO ("target_feature", "sse4a");
if (TARGET_BMI)
{
ADD_TARGET_INFO ("target_feature", "bmi1");
ADD_TARGET_INFO ("target_feature", "bmi");
}
if (TARGET_BMI2)
ADD_TARGET_INFO ("target_feature", "bmi2");
if (TARGET_LZCNT)
ADD_TARGET_INFO ("target_feature", "lzcnt");
if (TARGET_TBM)
ADD_TARGET_INFO ("target_feature", "tbm");
if (TARGET_POPCNT)
ADD_TARGET_INFO ("target_feature", "popcnt");
if (TARGET_RDRND)
{
ADD_TARGET_INFO ("target_feature", "rdrand");
ADD_TARGET_INFO ("target_feature", "rdrnd");
}
if (TARGET_F16C)
ADD_TARGET_INFO ("target_feature", "f16c");
if (TARGET_RDSEED)
ADD_TARGET_INFO ("target_feature", "rdseed");
if (TARGET_ADX)
ADD_TARGET_INFO ("target_feature", "adx");
if (TARGET_FXSR)
ADD_TARGET_INFO ("target_feature", "fxsr");
if (TARGET_XSAVE)
ADD_TARGET_INFO ("target_feature", "xsave");
if (TARGET_XSAVEOPT)
ADD_TARGET_INFO ("target_feature", "xsaveopt");
if (TARGET_XSAVEC)
ADD_TARGET_INFO ("target_feature", "xsavec");
if (TARGET_XSAVES)
ADD_TARGET_INFO ("target_feature", "xsaves");
if (TARGET_VPCLMULQDQ)
{
ADD_TARGET_INFO ("target_feature", "pclmulqdq");
ADD_TARGET_INFO ("target_feature", "vpclmulqdq");
}
if (TARGET_CMPXCHG16B)
ADD_TARGET_INFO ("target_feature", "cmpxchg16b");
if (TARGET_MOVBE)
ADD_TARGET_INFO ("target_feature", "movbe");

View File

@@ -29,101 +29,7 @@ along with GCC; see the file COPYING3. If not see
void
ix86_rust_target_cpu_info (void)
{
if (TARGET_64BIT)
rust_add_target_info ("target_arch", "x86_64");
else
rust_add_target_info ("target_arch", "x86");
// features officially "stabilised" in rustc
if (TARGET_MMX)
rust_add_target_info ("target_feature", "mmx");
if (TARGET_SSE)
rust_add_target_info ("target_feature", "sse");
if (TARGET_SSE2)
rust_add_target_info ("target_feature", "sse2");
if (TARGET_SSE3)
rust_add_target_info ("target_feature", "sse3");
if (TARGET_SSSE3)
rust_add_target_info ("target_feature", "ssse3");
if (TARGET_SSE4_1)
rust_add_target_info ("target_feature", "sse4.1");
if (TARGET_SSE4_2)
rust_add_target_info ("target_feature", "sse4.2");
if (TARGET_AES)
rust_add_target_info ("target_feature", "aes");
if (TARGET_SHA)
rust_add_target_info ("target_feature", "sha");
if (TARGET_AVX)
rust_add_target_info ("target_feature", "avx");
if (TARGET_AVX2)
rust_add_target_info ("target_feature", "avx2");
if (TARGET_AVX512F)
rust_add_target_info ("target_feature", "avx512f");
if (TARGET_AVX512ER)
rust_add_target_info ("target_feature", "avx512er");
if (TARGET_AVX512CD)
rust_add_target_info ("target_feature", "avx512cd");
if (TARGET_AVX512PF)
rust_add_target_info ("target_feature", "avx512pf");
if (TARGET_AVX512DQ)
rust_add_target_info ("target_feature", "avx512dq");
if (TARGET_AVX512BW)
rust_add_target_info ("target_feature", "avx512bw");
if (TARGET_AVX512VL)
rust_add_target_info ("target_feature", "avx512vl");
if (TARGET_AVX512VBMI)
rust_add_target_info ("target_feature", "avx512vbmi");
if (TARGET_AVX512IFMA)
rust_add_target_info ("target_feature", "avx512ifma");
if (TARGET_AVX512VPOPCNTDQ)
rust_add_target_info ("target_feature", "avx512vpopcntdq");
if (TARGET_FMA)
rust_add_target_info ("target_feature", "fma");
if (TARGET_RTM)
rust_add_target_info ("target_feature", "rtm");
if (TARGET_SSE4A)
rust_add_target_info ("target_feature", "sse4a");
if (TARGET_BMI)
{
rust_add_target_info ("target_feature", "bmi1");
rust_add_target_info ("target_feature", "bmi");
}
if (TARGET_BMI2)
rust_add_target_info ("target_feature", "bmi2");
if (TARGET_LZCNT)
rust_add_target_info ("target_feature", "lzcnt");
if (TARGET_TBM)
rust_add_target_info ("target_feature", "tbm");
if (TARGET_POPCNT)
rust_add_target_info ("target_feature", "popcnt");
if (TARGET_RDRND)
{
rust_add_target_info ("target_feature", "rdrand");
rust_add_target_info ("target_feature", "rdrnd");
}
if (TARGET_F16C)
rust_add_target_info ("target_feature", "f16c");
if (TARGET_RDSEED)
rust_add_target_info ("target_feature", "rdseed");
if (TARGET_ADX)
rust_add_target_info ("target_feature", "adx");
if (TARGET_FXSR)
rust_add_target_info ("target_feature", "fxsr");
if (TARGET_XSAVE)
rust_add_target_info ("target_feature", "xsave");
if (TARGET_XSAVEOPT)
rust_add_target_info ("target_feature", "xsaveopt");
if (TARGET_XSAVEC)
rust_add_target_info ("target_feature", "xsavec");
if (TARGET_XSAVES)
rust_add_target_info ("target_feature", "xsaves");
if (TARGET_VPCLMULQDQ)
{
rust_add_target_info ("target_feature", "pclmulqdq");
rust_add_target_info ("target_feature", "vpclmulqdq");
}
if (TARGET_CMPXCHG16B)
rust_add_target_info ("target_feature", "cmpxchg16b");
if (TARGET_MOVBE)
rust_add_target_info ("target_feature", "movbe");
#define ADD_TARGET_INFO rust_add_target_info
#include "i386-rust-and-jit.inc"
#undef ADD_TARGET_INFO
}

View File

@@ -222,20 +222,19 @@ described below.
@heading Tools/packages necessary for building GCC
@table @asis
@item ISO C++11 compiler
Necessary to bootstrap GCC. GCC 4.8.3 or newer has sufficient
support for used C++11 features, with earlier GCC versions you
might run into implementation bugs.
@item ISO C++14 compiler
Necessary to bootstrap GCC. GCC 5.4 or newer has sufficient support
for used C++14 features.
Versions of GCC prior to 11 also allow bootstrapping with an ISO C++98
compiler, versions of GCC prior to 4.8 also allow bootstrapping with a
ISO C89 compiler, and versions of GCC prior to 3.4 also allow
bootstrapping with a traditional (K&R) C compiler.
Versions of GCC prior to 15 allow bootstrapping with an ISO C++11
compiler, versions prior to 11 allow bootstrapping with an ISO C++98
compiler, and versions prior to 4.8 allow bootstrapping with an ISO
C89 compiler.
To build all languages in a cross-compiler or other configuration where
3-stage bootstrap is not performed, you need to start with an existing
GCC binary (version 4.8.3 or later) because source code for language
frontends other than C might use GCC extensions.
If you need to build an intermediate version of GCC in order to
bootstrap current GCC, consider GCC 9.5: it can build the current Ada
and D compilers, and was also the version that declared C++17 support
stable.
@item C standard library and headers
@@ -313,6 +312,12 @@ documentation including the target @code{SYSTEM} definition module.
If Python3 is unavailable Modula-2 documentation will include a target
independent version of the SYSTEM modules.
@item @anchor{gccrs-prerequisite}gccrs
The official Rust compiler and Rust build system (cargo) are required for
building various parts of the gccrs frontend, until gccrs can compile them
by itself. The minimum supported Rust version is 1.49.
@item A ``working'' POSIX compatible shell, or GNU bash
Necessary when running @command{configure} because some

View File

@@ -92,21 +92,37 @@ GRS_OBJS = \
rust/rust-cfg-strip.o \
rust/rust-expand-visitor.o \
rust/rust-ast-builder.o \
rust/rust-ast-builder-type.o \
rust/rust-derive.o \
rust/rust-derive-clone.o \
rust/rust-derive-copy.o \
rust/rust-derive-debug.o \
rust/rust-derive-default.o \
rust/rust-derive-partial-eq.o \
rust/rust-derive-eq.o \
rust/rust-derive-hash.o \
rust/rust-proc-macro.o \
rust/rust-macro-invoc-lexer.o \
rust/rust-proc-macro-invoc-lexer.o \
rust/rust-macro-substitute-ctx.o \
rust/rust-macro-builtins.o \
rust/rust-macro-builtins-helpers.o \
rust/rust-macro-builtins-asm.o \
rust/rust-macro-builtins-trait.o \
rust/rust-macro-builtins-utility.o \
rust/rust-macro-builtins-log-debug.o \
rust/rust-macro-builtins-test-bench.o \
rust/rust-macro-builtins-format-args.o \
rust/rust-macro-builtins-location.o \
rust/rust-macro-builtins-include.o \
rust/rust-token-tree-desugar.o \
rust/rust-fmt.o \
rust/rust-hir.o \
rust/rust-hir-map.o \
rust/rust-attributes.o \
rust/rust-keyword-values.o \
rust/rust-abi.o \
rust/rust-token-converter.o \
rust/rust-macro.o \
rust/rust-ast-lower.o \
rust/rust-ast-lower-base.o \
rust/rust-ast-lower-pattern.o \
@@ -115,12 +131,16 @@ GRS_OBJS = \
rust/rust-ast-lower-expr.o \
rust/rust-ast-lower-type.o \
rust/rust-ast-lower-stmt.o \
rust/rust-ast-lower-format-args.o \
rust/rust-rib.o \
rust/rust-name-resolution-context.o \
rust/rust-default-resolver.o \
rust/rust-toplevel-name-resolver-2.0.o \
rust/rust-early-name-resolver-2.0.o \
rust/rust-finalize-imports-2.0.o \
rust/rust-ice-finalizer.o \
rust/rust-late-name-resolver-2.0.o \
rust/rust-immutable-name-resolution-context.o \
rust/rust-early-name-resolver.o \
rust/rust-name-resolver.o \
rust/rust-ast-resolve.o \
@@ -132,6 +152,7 @@ GRS_OBJS = \
rust/rust-ast-resolve-path.o \
rust/rust-ast-resolve-stmt.o \
rust/rust-ast-resolve-struct-expr-field.o \
rust/rust-forever-stack.o \
rust/rust-hir-type-check.o \
rust/rust-privacy-check.o \
rust/rust-privacy-ctx.o \
@@ -143,6 +164,7 @@ GRS_OBJS = \
rust/rust-tyty-util.o \
rust/rust-tyty-call.o \
rust/rust-tyty-subst.o \
rust/rust-tyty-variance-analysis.o \
rust/rust-typecheck-context.o \
rust/rust-tyty-bounds.o \
rust/rust-hir-trait-resolve.o \
@@ -156,10 +178,20 @@ GRS_OBJS = \
rust/rust-hir-type-check-enumitem.o \
rust/rust-hir-type-check-implitem.o \
rust/rust-borrow-checker.o \
rust/rust-borrow-checker-diagnostics.o\
rust/rust-bir-builder-expr-stmt.o \
rust/rust-bir-builder-pattern.o \
rust/rust-bir-dump.o \
rust/rust-polonius.o\
rust/rust-hir-dot-operator.o \
rust/rust-hir-path-probe.o \
rust/rust-hir-path.o \
rust/rust-hir-type.o \
rust/rust-hir-expr.o \
rust/rust-hir-type-abstract.o \
rust/rust-hir-item.o \
rust/rust-hir-stmt.o \
rust/rust-hir-generic-param.o \
rust/rust-type-util.o \
rust/rust-coercion.o \
rust/rust-casts.o \
@@ -173,6 +205,7 @@ GRS_OBJS = \
rust/rust-readonly-check.o \
rust/rust-hir-type-check-path.o \
rust/rust-unsafe-checker.o \
rust/rust-hir-pattern-analysis.o \
rust/rust-compile-intrinsic.o \
rust/rust-compile-pattern.o \
rust/rust-compile-fnparam.o \
@@ -181,6 +214,7 @@ GRS_OBJS = \
rust/rust-compile-item.o \
rust/rust-compile-implitem.o \
rust/rust-compile-stmt.o \
rust/rust-compile-asm.o \
rust/rust-compile-expr.o \
rust/rust-compile-type.o \
rust/rust-compile-block.o \
@@ -200,6 +234,14 @@ GRS_OBJS = \
rust/rust-dir-owner.o \
rust/rust-unicode.o \
rust/rust-punycode.o \
rust/rust-unwrap-segment.o \
rust/rust-edition.o \
rust/rust-expand-format-args.o \
rust/rust-lang-item.o \
rust/rust-collect-lang-items.o \
rust/rust-desugar-for-loops.o \
rust/rust-desugar-question-mark.o \
rust/rust-desugar-apit.o \
$(END)
# removed object files from here
@@ -208,14 +250,17 @@ RUST_ALL_OBJS = $(GRS_OBJS) $(RUST_TARGET_OBJS)
rust_OBJS = $(RUST_ALL_OBJS) rust/rustspec.o
RUST_LDFLAGS = $(LDFLAGS) -L./../libgrust/libproc_macro_internal
RUST_LIBDEPS = $(LIBDEPS) ../libgrust/libproc_macro_internal/libproc_macro_internal.a
LIBPROC_MACRO_INTERNAL = ../libgrust/libproc_macro_internal/libproc_macro_internal.a
LIBFORMAT_PARSER = ../libgrust/libformat_parser/debug/liblibformat_parser.a
LIBFFI_POLONIUS = rust/libffi_polonius.a
# The compiler itself is called crab1
crab1$(exeext): $(RUST_ALL_OBJS) attribs.o $(BACKEND) $(RUST_LIBDEPS) $(rust.prev)
crab1$(exeext): $(RUST_ALL_OBJS) attribs.o $(BACKEND) $(LIBDEPS) $(LIBPROC_MACRO_INTERNAL) $(LIBFORMAT_PARSER) $(LIBFFI_POLONIUS) $(rust.prev)
@$(call LINK_PROGRESS,$(INDEX.rust),start)
+$(LLINKER) $(ALL_LINKERFLAGS) $(RUST_LDFLAGS) -o $@ \
$(RUST_ALL_OBJS) attribs.o $(BACKEND) $(LIBS) ../libgrust/libproc_macro_internal/libproc_macro_internal.a $(BACKENDLIBS)
+$(LLINKER) $(ALL_LINKERFLAGS) $(LDFLAGS) -o $@ \
$(RUST_ALL_OBJS) attribs.o $(BACKEND) \
$(LIBS) $(CRAB1_LIBS) $(LIBPROC_MACRO_INTERNAL) $(LIBFORMAT_PARSER) $(LIBFFI_POLONIUS) \
$(BACKENDLIBS)
@$(call LINK_PROGRESS,$(INDEX.rust),end)
# Build hooks.
@@ -249,6 +294,7 @@ rust.srcman:
# Clean hooks.
rust.mostlyclean:
rm -rf rust/ffi-polonius/release libffi_polonius.a
# cd $(srcdir)/rust; rm -f *.o y.tab.h y.tab.c lex.yy.c
rust.clean: rust.mostlyclean
@@ -466,7 +512,19 @@ rust/%.o: rust/checks/errors/borrowck/%.cc
$(COMPILE) $(RUST_CXXFLAGS) $(RUST_INCLUDES) $<
$(POSTCOMPILE)
# build borrow checking pass polonius files in rust folder
rust/%.o: rust/checks/errors/borrowck/polonius/%.cc
$(COMPILE) $(RUST_CXXFLAGS) $(RUST_INCLUDES) $<
$(POSTCOMPILE)
# build rust/metadata files in rust folder
rust/%.o: rust/metadata/%.cc
$(COMPILE) $(RUST_CXXFLAGS) $(RUST_INCLUDES) $<
$(POSTCOMPILE)
rust/libffi_polonius.a: \
rust/checks/errors/borrowck/ffi-polonius/Cargo.toml \
$(wildcard $(srcdir)/rust/checks/errors/borrowck/ffi-polonius/src/*)
cd $(srcdir)/rust/checks/errors/borrowck/ffi-polonius/ && cargo build --offline --release --target-dir $(objdir)/rust/ffi-polonius
cp rust/ffi-polonius/release/libffi_polonius.a rust/libffi_polonius.a

View File

@@ -0,0 +1,163 @@
// Copyright (C) 2020-2024 Free Software Foundation, Inc.
// This file is part of GCC.
// GCC is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 3, or (at your option) any later
// version.
// GCC is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
// for more details.
// You should have received a copy of the GNU General Public License
// along with GCC; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
#include "rust-ast-builder-type.h"
#include "rust-ast-builder.h"
#include "rust-ast-full.h"
#include "rust-common.h"
namespace Rust {
namespace AST {
ASTTypeBuilder::ASTTypeBuilder () : translated (nullptr) {}
Type *
ASTTypeBuilder::build (Type &type)
{
ASTTypeBuilder builder;
type.accept_vis (builder);
rust_assert (builder.translated != nullptr);
return builder.translated;
}
void
ASTTypeBuilder::visit (BareFunctionType &fntype)
{
/* TODO */
}
void
ASTTypeBuilder::visit (TupleType &tuple)
{
std::vector<std::unique_ptr<Type> > elems;
for (auto &elem : tuple.get_elems ())
{
Type *t = ASTTypeBuilder::build (*elem.get ());
std::unique_ptr<Type> ty (t);
elems.push_back (std::move (ty));
}
translated = new TupleType (std::move (elems), tuple.get_locus ());
}
void
ASTTypeBuilder::visit (TypePath &path)
{
std::vector<std::unique_ptr<TypePathSegment> > segments;
for (auto &seg : path.get_segments ())
{
switch (seg->get_type ())
{
case TypePathSegment::REG: {
const TypePathSegment &segment
= (const TypePathSegment &) (*seg.get ());
TypePathSegment *s
= new TypePathSegment (segment.get_ident_segment (),
segment.get_separating_scope_resolution (),
segment.get_locus ());
std::unique_ptr<TypePathSegment> sg (s);
segments.push_back (std::move (sg));
}
break;
case TypePathSegment::GENERIC: {
TypePathSegmentGeneric &generic
= (TypePathSegmentGeneric &) (*seg.get ());
GenericArgs args
= Builder::new_generic_args (generic.get_generic_args ());
TypePathSegmentGeneric *s
= new TypePathSegmentGeneric (generic.get_ident_segment (), false,
std::move (args),
generic.get_locus ());
std::unique_ptr<TypePathSegment> sg (s);
segments.push_back (std::move (sg));
}
break;
case TypePathSegment::FUNCTION: {
rust_unreachable ();
// TODO
// const TypePathSegmentFunction &fn
// = (const TypePathSegmentFunction &) (*seg.get ());
}
break;
}
}
translated = new TypePath (std::move (segments), path.get_locus (),
path.has_opening_scope_resolution_op ());
}
void
ASTTypeBuilder::visit (QualifiedPathInType &path)
{
/* TODO */
}
void
ASTTypeBuilder::visit (ArrayType &type)
{
/* TODO */
}
void
ASTTypeBuilder::visit (ReferenceType &type)
{
/* TODO */
}
void
ASTTypeBuilder::visit (RawPointerType &type)
{
/* TODO */
}
void
ASTTypeBuilder::visit (SliceType &type)
{
Type *t = ASTTypeBuilder::build (type.get_elem_type ());
std::unique_ptr<Type> ty (t);
translated = new SliceType (std::move (ty), type.get_locus ());
}
void
ASTTypeBuilder::visit (InferredType &type)
{
translated = new InferredType (type.get_locus ());
}
void
ASTTypeBuilder::visit (NeverType &type)
{
translated = new NeverType (type.get_locus ());
}
void
ASTTypeBuilder::visit (TraitObjectTypeOneBound &type)
{
/* TODO */
}
void
ASTTypeBuilder::visit (TraitObjectType &type)
{
/* TODO */
}
} // namespace AST
} // namespace Rust

View File

@@ -0,0 +1,57 @@
// Copyright (C) 2020-2024 Free Software Foundation, Inc.
// This file is part of GCC.
// GCC is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 3, or (at your option) any later
// version.
// GCC is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
// for more details.
// You should have received a copy of the GNU General Public License
// along with GCC; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
#ifndef RUST_AST_BUILDER_TYPE
#define RUST_AST_BUILDER_TYPE
#include "rust-ast-visitor.h"
namespace Rust {
namespace AST {
class ASTTypeBuilder : public DefaultASTVisitor
{
protected:
using DefaultASTVisitor::visit;
public:
static Type *build (Type &type);
void visit (BareFunctionType &fntype) override;
void visit (TupleType &tuple) override;
void visit (TypePath &path) override;
void visit (QualifiedPathInType &path) override;
void visit (ArrayType &type) override;
void visit (ReferenceType &type) override;
void visit (RawPointerType &type) override;
void visit (SliceType &type) override;
void visit (InferredType &type) override;
void visit (NeverType &type) override;
void visit (TraitObjectTypeOneBound &type) override;
void visit (TraitObjectType &type) override;
private:
ASTTypeBuilder ();
Type *translated;
};
} // namespace AST
} // namespace Rust
#endif // RUST_AST_BUILDER_TYPE

View File

@@ -17,53 +17,195 @@
// <http://www.gnu.org/licenses/>.
#include "rust-ast-builder.h"
#include "rust-ast-full.h"
#include "optional.h"
#include "rust-ast-builder-type.h"
#include "rust-ast.h"
#include "rust-common.h"
#include "rust-expr.h"
#include "rust-keyword-values.h"
#include "rust-path.h"
#include "rust-item.h"
#include "rust-path.h"
#include "rust-pattern.h"
#include "rust-system.h"
#include "rust-token.h"
#include <memory>
namespace Rust {
namespace AST {
std::unique_ptr<Stmt>
Builder::statementify (std::unique_ptr<Expr> &&value,
bool semicolon_followed) const
{
return std::make_unique<ExprStmt> (std::move (value), loc,
semicolon_followed);
}
std::unique_ptr<Expr>
AstBuilder::call (std::unique_ptr<Expr> &&path,
std::vector<std::unique_ptr<Expr>> &&args)
Builder::literal_string (std::string &&content) const
{
return std::unique_ptr<Expr> (
new AST::LiteralExpr (std::move (content), Literal::LitType::STRING,
PrimitiveCoreType::CORETYPE_STR, {}, loc));
}
std::unique_ptr<Expr>
Builder::literal_bool (bool b) const
{
auto str
= b ? Values::Keywords::TRUE_LITERAL : Values::Keywords::FALSE_LITERAL;
return std::unique_ptr<Expr> (
new AST::LiteralExpr (std::move (str), Literal::LitType::BOOL,
PrimitiveCoreType::CORETYPE_BOOL, {}, loc));
}
std::unique_ptr<Expr>
Builder::call (std::unique_ptr<Expr> &&path,
std::vector<std::unique_ptr<Expr>> &&args) const
{
return std::unique_ptr<Expr> (
new CallExpr (std::move (path), std::move (args), {}, loc));
}
std::unique_ptr<Expr>
AstBuilder::identifier (std::string name)
Builder::call (std::unique_ptr<Expr> &&path, std::unique_ptr<Expr> &&arg) const
{
auto args = std::vector<std::unique_ptr<Expr>> ();
args.emplace_back (std::move (arg));
return call (std::move (path), std::move (args));
}
std::unique_ptr<Expr>
Builder::array (std::vector<std::unique_ptr<Expr>> &&members) const
{
auto elts = std::make_unique<ArrayElemsValues> (std::move (members), loc);
return std::unique_ptr<Expr> (new ArrayExpr (std::move (elts), {}, {}, loc));
}
std::unique_ptr<Expr>
Builder::qualified_path_in_expression (std::unique_ptr<Type> &&type,
TypePath trait,
PathExprSegment segment) const
{
auto segments = {segment};
return qualified_path_in_expression (std::move (type), trait, segments);
}
std::unique_ptr<Expr>
Builder::qualified_path_in_expression (
std::unique_ptr<Type> &&type, TypePath trait,
std::vector<PathExprSegment> &&segments) const
{
auto qual_type = QualifiedPathType (std::move (type), loc, trait);
return std::unique_ptr<QualifiedPathInExpression> (
new QualifiedPathInExpression (qual_type, std::move (segments), {}, loc));
}
std::unique_ptr<Expr>
Builder::identifier (std::string name) const
{
return std::unique_ptr<Expr> (new IdentifierExpr (name, {}, loc));
}
std::unique_ptr<Pattern>
Builder::identifier_pattern (std::string name, bool mut) const
{
return std::unique_ptr<Pattern> (
new IdentifierPattern (name, loc, false, mut));
}
std::unique_ptr<Expr>
AstBuilder::tuple_idx (std::string receiver, int idx)
Builder::tuple_idx (std::string receiver, int idx) const
{
return std::unique_ptr<Expr> (
new TupleIndexExpr (identifier (receiver), idx, {}, loc));
}
std::unique_ptr<Expr>
Builder::tuple (std::vector<std::unique_ptr<Expr>> &&values) const
{
return std::unique_ptr<TupleExpr> (
new TupleExpr (std::move (values), {}, {}, loc));
}
std::unique_ptr<Param>
Builder::self_ref_param (bool mutability) const
{
return std::make_unique<SelfParam> (tl::nullopt, mutability, loc);
}
std::unique_ptr<Param>
Builder::function_param (std::unique_ptr<Pattern> &&pattern,
std::unique_ptr<Type> &&type) const
{
return std::unique_ptr<FunctionParam> (
new FunctionParam (std::move (pattern), std::move (type), {}, loc));
}
FunctionQualifiers
AstBuilder::fn_qualifiers ()
Builder::fn_qualifiers () const
{
return FunctionQualifiers (loc, Async::No, Const::No, Unsafety::Normal);
}
std::unique_ptr<Function>
Builder::function (std::string function_name,
std::vector<std::unique_ptr<Param>> params,
std::unique_ptr<Type> return_type,
std::unique_ptr<BlockExpr> block,
std::vector<std::unique_ptr<GenericParam>> generic_params,
FunctionQualifiers qualifiers, WhereClause where_clause,
Visibility visibility) const
{
return std::unique_ptr<Function> (
new Function (function_name, qualifiers, std::move (generic_params),
std::move (params), std::move (return_type), where_clause,
std::move (block), visibility, {}, loc));
}
PathExprSegment
AstBuilder::path_segment (std::string seg)
Builder::path_segment (std::string seg) const
{
return PathExprSegment (PathIdentSegment (seg, loc), loc);
}
std::unique_ptr<TypePathSegment>
AstBuilder::type_path_segment (std::string seg)
Builder::type_path_segment (std::string seg) const
{
return std::unique_ptr<TypePathSegment> (
new TypePathSegment (seg, false, loc));
}
std::unique_ptr<TypePathSegment>
Builder::type_path_segment (LangItem::Kind lang_item) const
{
return std::unique_ptr<TypePathSegment> (
new TypePathSegment (lang_item, loc));
}
std::unique_ptr<TypePathSegment>
Builder::type_path_segment_generic (std::string seg, GenericArgs args) const
{
return std::unique_ptr<TypePathSegment> (
new TypePathSegmentGeneric (PathIdentSegment (seg, loc), false, args, loc));
}
std::unique_ptr<TypePathSegment>
Builder::type_path_segment_generic (LangItem::Kind lang_item,
GenericArgs args) const
{
return std::unique_ptr<TypePathSegment> (
new TypePathSegmentGeneric (lang_item, args, loc));
}
std::unique_ptr<Type>
AstBuilder::single_type_path (std::string type)
Builder::single_type_path (std::string type) const
{
auto segments = std::vector<std::unique_ptr<TypePathSegment>> ();
segments.emplace_back (type_path_segment (type));
@@ -71,83 +213,509 @@ AstBuilder::single_type_path (std::string type)
return std::unique_ptr<Type> (new TypePath (std::move (segments), loc));
}
std::unique_ptr<Type>
Builder::single_type_path (LangItem::Kind lang_item) const
{
return std::unique_ptr<Type> (new TypePath (lang_item, {}, loc));
}
std::unique_ptr<Type>
Builder::single_generic_type_path (std::string type, GenericArgs args) const
{
auto segments = std::vector<std::unique_ptr<TypePathSegment>> ();
segments.emplace_back (type_path_segment_generic (type, args));
return std::unique_ptr<Type> (new TypePath (std::move (segments), loc));
}
std::unique_ptr<Type>
Builder::single_generic_type_path (LangItem::Kind lang_item,
GenericArgs args) const
{
auto segments = std::vector<std::unique_ptr<TypePathSegment>> ();
segments.emplace_back (type_path_segment_generic (lang_item, args));
return std::unique_ptr<Type> (new TypePath (std::move (segments), loc));
}
TypePath
Builder::type_path (std::vector<std::unique_ptr<TypePathSegment>> &&segments,
bool opening_scope) const
{
return TypePath (std::move (segments), loc, opening_scope);
}
TypePath
Builder::type_path (std::vector<std::string> &&segments,
bool opening_scope) const
{
auto type_segments = std::vector<std::unique_ptr<TypePathSegment>> ();
for (auto &&segment : segments)
type_segments.emplace_back (type_path_segment (segment));
return TypePath (std::move (type_segments), loc, opening_scope);
}
TypePath
Builder::type_path (std::unique_ptr<TypePathSegment> &&segment) const
{
auto segments = std::vector<std::unique_ptr<TypePathSegment>> ();
segments.emplace_back (std::move (segment));
return type_path (std::move (segments));
}
TypePath
Builder::type_path (std::string type) const
{
return type_path (type_path_segment (type));
}
TypePath
Builder::type_path (LangItem::Kind lang_item) const
{
return type_path (type_path_segment (lang_item));
}
std::unique_ptr<Type>
Builder::reference_type (std::unique_ptr<TypeNoBounds> &&inner_type,
bool mutability) const
{
return std::make_unique<ReferenceType> (mutability, std::move (inner_type),
loc);
}
PathInExpression
AstBuilder::path_in_expression (std::vector<std::string> &&segments)
Builder::path_in_expression (std::vector<std::string> &&segments,
bool opening_scope) const
{
auto path_segments = std::vector<PathExprSegment> ();
for (auto &seg : segments)
path_segments.emplace_back (path_segment (seg));
return PathInExpression (std::move (path_segments), {}, loc);
return PathInExpression (std::move (path_segments), {}, loc, opening_scope);
}
PathInExpression
Builder::path_in_expression (LangItem::Kind lang_item) const
{
return PathInExpression (lang_item, {}, loc);
}
PathInExpression
Builder::variant_path (const std::string &enum_path,
const std::string &variant) const
{
return PathInExpression ({path_segment (enum_path), path_segment (variant)},
{}, loc, false);
}
std::unique_ptr<BlockExpr>
Builder::block (tl::optional<std::unique_ptr<Stmt>> &&stmt,
std::unique_ptr<Expr> &&tail_expr) const
{
auto stmts = std::vector<std::unique_ptr<Stmt>> ();
if (stmt)
stmts.emplace_back (std::move (*stmt));
return block (std::move (stmts), std::move (tail_expr));
}
std::unique_ptr<BlockExpr>
Builder::block () const
{
auto stmts = std::vector<std::unique_ptr<Stmt>> ();
return block (std::move (stmts));
}
std::unique_ptr<BlockExpr>
Builder::block (std::vector<std::unique_ptr<Stmt>> &&stmts,
std::unique_ptr<Expr> &&tail_expr) const
{
return std::unique_ptr<BlockExpr> (new BlockExpr (std::move (stmts),
std::move (tail_expr), {},
{}, tl::nullopt, loc, loc));
}
std::unique_ptr<Expr>
AstBuilder::block (std::vector<std::unique_ptr<Stmt>> &&stmts,
std::unique_ptr<Expr> &&tail_expr)
Builder::return_expr (std::unique_ptr<Expr> &&to_return)
{
return std::unique_ptr<Expr> (new BlockExpr (std::move (stmts),
std::move (tail_expr), {}, {},
LoopLabel::error (), loc, loc));
return std::unique_ptr<Expr> (
new ReturnExpr (std::move (to_return), {}, loc));
}
std::unique_ptr<Stmt>
AstBuilder::let (std::unique_ptr<Pattern> pattern, std::unique_ptr<Type> type,
std::unique_ptr<Expr> init)
Builder::let (std::unique_ptr<Pattern> &&pattern, std::unique_ptr<Type> &&type,
std::unique_ptr<Expr> &&init) const
{
return std::unique_ptr<Stmt> (new LetStmt (std::move (pattern),
std::move (init), std::move (type),
{}, loc));
tl::nullopt, {}, loc));
}
std::unique_ptr<Expr>
AstBuilder::ref (std::unique_ptr<Expr> &&of, bool mut)
Builder::ref (std::unique_ptr<Expr> &&of, bool mut) const
{
auto mutability = mut ? Mutability::Mut : Mutability::Imm;
return std::unique_ptr<Expr> (
new BorrowExpr (std::move (of), mut, /* is double */ false, {}, loc));
new BorrowExpr (std::move (of), mutability,
/* raw */ false, /* is double */ false, {}, loc));
}
std::unique_ptr<Expr>
AstBuilder::deref (std::unique_ptr<Expr> &&of)
Builder::deref (std::unique_ptr<Expr> &&of) const
{
return std::unique_ptr<Expr> (new DereferenceExpr (std::move (of), {}, loc));
}
std::unique_ptr<Expr>
AstBuilder::struct_expr_struct (std::string struct_name)
Builder::comparison_expr (std::unique_ptr<Expr> &&lhs,
std::unique_ptr<Expr> &&rhs,
ComparisonOperator op) const
{
return std::make_unique<ComparisonExpr> (std::move (lhs), std::move (rhs), op,
loc);
}
std::unique_ptr<Expr>
Builder::boolean_operation (std::unique_ptr<Expr> &&lhs,
std::unique_ptr<Expr> &&rhs,
LazyBooleanOperator op) const
{
return std::make_unique<LazyBooleanExpr> (std::move (lhs), std::move (rhs),
op, loc);
}
std::unique_ptr<Stmt>
Builder::struct_struct (std::string struct_name,
std::vector<std::unique_ptr<GenericParam>> &&generics,
std::vector<StructField> &&fields)
{
auto is_unit = fields.empty ();
return std::unique_ptr<Stmt> (
new StructStruct (std::move (fields), struct_name, std::move (generics),
WhereClause::create_empty (), is_unit,
Visibility::create_private (), {}, loc));
}
std::unique_ptr<Expr>
Builder::struct_expr_struct (std::string struct_name) const
{
return std::unique_ptr<Expr> (
new StructExprStruct (path_in_expression ({struct_name}), {}, {}, loc));
}
std::unique_ptr<Expr>
AstBuilder::struct_expr (std::string struct_name,
std::vector<std::unique_ptr<StructExprField>> &&fields)
Builder::struct_expr (
std::string struct_name,
std::vector<std::unique_ptr<StructExprField>> &&fields) const
{
return struct_expr (path_in_expression ({struct_name}), std::move (fields));
}
std::unique_ptr<Expr>
Builder::struct_expr (
PathInExpression struct_name,
std::vector<std::unique_ptr<StructExprField>> &&fields) const
{
return std::unique_ptr<Expr> (
new StructExprStructFields (path_in_expression ({struct_name}),
std::move (fields), loc));
new StructExprStructFields (struct_name, std::move (fields), loc));
}
std::unique_ptr<StructExprField>
AstBuilder::struct_expr_field (std::string field_name,
std::unique_ptr<Expr> &&value)
Builder::struct_expr_field (std::string field_name,
std::unique_ptr<Expr> &&value) const
{
return std::unique_ptr<StructExprField> (
new StructExprFieldIdentifierValue (field_name, std::move (value), loc));
}
std::unique_ptr<Expr>
AstBuilder::field_access (std::unique_ptr<Expr> &&instance, std::string field)
Builder::field_access (std::unique_ptr<Expr> &&instance,
std::string field) const
{
return std::unique_ptr<Expr> (
new FieldAccessExpr (std::move (instance), field, {}, loc));
}
std::unique_ptr<StructPatternField>
Builder::struct_pattern_ident_pattern (std::string field_name,
std::unique_ptr<Pattern> &&pattern)
{
return std::make_unique<StructPatternFieldIdentPat> (
field_name, std::move (pattern), std::vector<Attribute> (), loc);
}
std::unique_ptr<Pattern>
AstBuilder::wildcard ()
Builder::wildcard () const
{
return std::unique_ptr<Pattern> (new WildcardPattern (loc));
}
std::unique_ptr<Pattern>
Builder::ref_pattern (std::unique_ptr<Pattern> &&inner) const
{
return std::make_unique<ReferencePattern> (std::move (inner), false, false,
loc);
}
std::unique_ptr<Path>
Builder::lang_item_path (LangItem::Kind kind) const
{
return std::unique_ptr<Path> (new PathInExpression (kind, {}, loc));
}
std::unique_ptr<Expr>
Builder::match (std::unique_ptr<Expr> &&scrutinee,
std::vector<MatchCase> &&cases)
{
return std::unique_ptr<Expr> (
new MatchExpr (std::move (scrutinee), std::move (cases), {}, {}, loc));
}
MatchArm
Builder::match_arm (std::unique_ptr<Pattern> &&pattern)
{
auto patterns = std::vector<std::unique_ptr<Pattern>> ();
patterns.emplace_back (std::move (pattern));
return MatchArm (std::move (patterns), loc);
}
MatchCase
Builder::match_case (std::unique_ptr<Pattern> &&pattern,
std::unique_ptr<Expr> &&expr)
{
return MatchCase (match_arm (std::move (pattern)), std::move (expr));
}
std::unique_ptr<Expr>
Builder::loop (std::vector<std::unique_ptr<Stmt>> &&stmts)
{
auto block_expr = block (std::move (stmts), nullptr);
return std::unique_ptr<Expr> (new LoopExpr (std::move (block_expr), loc));
}
std::unique_ptr<TypeParamBound>
Builder::trait_bound (TypePath bound)
{
return std::make_unique<TraitBound> (bound, loc);
}
std::unique_ptr<Item>
Builder::trait_impl (TypePath trait_path, std::unique_ptr<Type> target,
std::vector<std::unique_ptr<AssociatedItem>> trait_items,
std::vector<std::unique_ptr<GenericParam>> generics,
WhereClause where_clause, Visibility visibility) const
{
return std::unique_ptr<Item> (
new TraitImpl (trait_path, /* unsafe */ false,
/* exclam */ false, std::move (trait_items),
std::move (generics), std::move (target), where_clause,
visibility, {}, {}, loc));
}
std::unique_ptr<GenericParam>
Builder::generic_type_param (
std::string type_representation,
std::vector<std::unique_ptr<TypeParamBound>> &&bounds,
std::unique_ptr<Type> &&type)
{
return std::make_unique<TypeParam> (type_representation, loc,
std::move (bounds), std::move (type),
std::vector<Attribute> ());
}
std::unique_ptr<Type>
Builder::new_type (Type &type)
{
Type *t = ASTTypeBuilder::build (type);
return std::unique_ptr<Type> (t);
}
std::unique_ptr<GenericParam>
Builder::new_lifetime_param (LifetimeParam &param)
{
Lifetime l = new_lifetime (param.get_lifetime ());
std::vector<Lifetime> lifetime_bounds;
for (auto b : param.get_lifetime_bounds ())
{
Lifetime bl = new_lifetime (b);
lifetime_bounds.push_back (bl);
}
auto p = new LifetimeParam (l, std::move (lifetime_bounds),
param.get_outer_attrs (), param.get_locus ());
return std::unique_ptr<GenericParam> (p);
}
std::unique_ptr<GenericParam>
Builder::new_type_param (
TypeParam &param, std::vector<std::unique_ptr<TypeParamBound>> extra_bounds)
{
location_t locus = param.get_locus ();
AST::AttrVec outer_attrs = param.get_outer_attrs ();
Identifier type_representation = param.get_type_representation ();
std::vector<std::unique_ptr<TypeParamBound>> type_param_bounds;
std::unique_ptr<Type> type = nullptr;
if (param.has_type ())
type = new_type (param.get_type ());
for (auto &&extra_bound : extra_bounds)
type_param_bounds.emplace_back (std::move (extra_bound));
for (const auto &b : param.get_type_param_bounds ())
{
switch (b->get_bound_type ())
{
case TypeParamBound::TypeParamBoundType::TRAIT: {
const TraitBound &tb = (const TraitBound &) *b.get ();
const TypePath &path = tb.get_type_path ();
std::vector<LifetimeParam> for_lifetimes;
for (const auto &lifetime : tb.get_for_lifetimes ())
{
std::vector<Lifetime> lifetime_bounds;
for (const auto &b : lifetime.get_lifetime_bounds ())
{
Lifetime bl = new_lifetime (b);
lifetime_bounds.push_back (std::move (bl));
}
Lifetime nl = new_lifetime (lifetime.get_lifetime ());
LifetimeParam p (std::move (nl), std::move (lifetime_bounds),
{}, lifetime.get_locus ());
for_lifetimes.push_back (std::move (p));
}
std::vector<std::unique_ptr<TypePathSegment>> segments;
for (auto &seg : path.get_segments ())
{
switch (seg->get_type ())
{
case TypePathSegment::REG: {
const TypePathSegment &segment
= (const TypePathSegment &) (*seg.get ());
TypePathSegment *s = new TypePathSegment (
segment.get_ident_segment (),
segment.get_separating_scope_resolution (),
segment.get_locus ());
std::unique_ptr<TypePathSegment> sg (s);
segments.push_back (std::move (sg));
}
break;
case TypePathSegment::GENERIC: {
TypePathSegmentGeneric &generic
= (TypePathSegmentGeneric &) (*seg.get ());
GenericArgs args
= new_generic_args (generic.get_generic_args ());
TypePathSegmentGeneric *s = new TypePathSegmentGeneric (
generic.get_ident_segment (), false, std::move (args),
generic.get_locus ());
std::unique_ptr<TypePathSegment> sg (s);
segments.push_back (std::move (sg));
}
break;
case TypePathSegment::FUNCTION: {
rust_unreachable ();
// TODO
// const TypePathSegmentFunction &fn
// = (const TypePathSegmentFunction &) (*seg.get ());
}
break;
}
}
TypePath p (std::move (segments), path.get_locus (),
path.has_opening_scope_resolution_op ());
TraitBound *b = new TraitBound (std::move (p), tb.get_locus (),
tb.is_in_parens (),
tb.has_opening_question_mark (),
std::move (for_lifetimes));
std::unique_ptr<TypeParamBound> bound (b);
type_param_bounds.push_back (std::move (bound));
}
break;
case TypeParamBound::TypeParamBoundType::LIFETIME: {
const Lifetime &l = (const Lifetime &) *b.get ();
auto bl = new Lifetime (l.get_lifetime_type (),
l.get_lifetime_name (), l.get_locus ());
std::unique_ptr<TypeParamBound> bound (bl);
type_param_bounds.push_back (std::move (bound));
}
break;
}
}
auto type_param
= new TypeParam (type_representation, locus, std::move (type_param_bounds),
std::move (type), std::move (outer_attrs));
return std::unique_ptr<GenericParam> (type_param);
}
Lifetime
Builder::new_lifetime (const Lifetime &lifetime)
{
return Lifetime (lifetime.get_lifetime_type (), lifetime.get_lifetime_name (),
lifetime.get_locus ());
}
GenericArgs
Builder::new_generic_args (GenericArgs &args)
{
std::vector<Lifetime> lifetime_args;
std::vector<GenericArg> generic_args;
std::vector<GenericArgsBinding> binding_args;
location_t locus = args.get_locus ();
for (const auto &lifetime : args.get_lifetime_args ())
{
Lifetime l = new_lifetime (lifetime);
lifetime_args.push_back (std::move (l));
}
for (auto &binding : args.get_binding_args ())
{
Type &t = *binding.get_type_ptr ().get ();
std::unique_ptr<Type> ty = new_type (t);
GenericArgsBinding b (binding.get_identifier (), std::move (ty),
binding.get_locus ());
binding_args.push_back (std::move (b));
}
for (auto &arg : args.get_generic_args ())
{
switch (arg.get_kind ())
{
case GenericArg::Kind::Type: {
std::unique_ptr<Type> ty = new_type (arg.get_type ());
GenericArg arg = GenericArg::create_type (std::move (ty));
}
break;
default:
// FIXME
rust_unreachable ();
break;
}
}
return GenericArgs (std::move (lifetime_args), std::move (generic_args),
std::move (binding_args), locus);
}
} // namespace AST
} // namespace Rust

View File

@@ -20,88 +20,287 @@
#define AST_BUILDER_H
#include "rust-ast-full.h"
#include "rust-expr.h"
#include "rust-ast.h"
#include "rust-item.h"
#include "rust-operators.h"
namespace Rust {
namespace AST {
template <typename T>
std::vector<std::unique_ptr<T>>
vec (std::unique_ptr<T> &&t)
{
auto v = std::vector<std::unique_ptr<T>> ();
v.emplace_back (std::move (t));
return v;
}
template <typename T>
std::vector<std::unique_ptr<T>>
vec (std::unique_ptr<T> &&t1, std::unique_ptr<T> &&t2)
{
auto v = std::vector<std::unique_ptr<T>> ();
v.emplace_back (std::move (t1));
v.emplace_back (std::move (t2));
return v;
}
/* Pointer-ify something */
template <typename T>
static std::unique_ptr<T>
ptrify (T value)
{
return std::unique_ptr<T> (new T (value));
}
// TODO: Use this builder when expanding regular macros
/* Builder class with helper methods to create AST nodes. This builder is
* tailored towards generating multiple AST nodes from a single location, and
* may not be suitable to other purposes */
class AstBuilder
class Builder
{
public:
AstBuilder (location_t loc) : loc (loc) {}
Builder (location_t loc) : loc (loc) {}
/* Create an expression statement from an expression */
std::unique_ptr<Stmt> statementify (std::unique_ptr<Expr> &&value,
bool semicolon_followed = true) const;
/* Create a string literal expression ("content") */
std::unique_ptr<Expr> literal_string (std::string &&content) const;
/* Create a boolean literal expression (true) */
std::unique_ptr<Expr> literal_bool (bool b) const;
/* Create an identifier expression (`variable`) */
std::unique_ptr<Expr> identifier (std::string name);
std::unique_ptr<Expr> identifier (std::string name) const;
std::unique_ptr<Pattern> identifier_pattern (std::string name,
bool mut = false) const;
/* Create a tuple index expression (`receiver.0`) */
std::unique_ptr<Expr> tuple_idx (std::string receiver, int idx);
std::unique_ptr<Expr> tuple_idx (std::string receiver, int idx) const;
/* Create a tuple expression (`(a1, a2, a3)`) */
std::unique_ptr<Expr> tuple (std::vector<std::unique_ptr<Expr>> &&values
= {}) const;
/* Create a reference to an expression (`&of`) */
std::unique_ptr<Expr> ref (std::unique_ptr<Expr> &&of, bool mut = false);
std::unique_ptr<Expr> ref (std::unique_ptr<Expr> &&of,
bool mut = false) const;
/* Create a dereference of an expression (`*of`) */
std::unique_ptr<Expr> deref (std::unique_ptr<Expr> &&of);
std::unique_ptr<Expr> deref (std::unique_ptr<Expr> &&of) const;
/* Build a comparison expression (`lhs == rhs`) */
std::unique_ptr<Expr> comparison_expr (std::unique_ptr<Expr> &&lhs,
std::unique_ptr<Expr> &&rhs,
ComparisonOperator op) const;
/* Build a lazy boolean operator expression (`lhs && rhs`) */
std::unique_ptr<Expr> boolean_operation (std::unique_ptr<Expr> &&lhs,
std::unique_ptr<Expr> &&rhs,
LazyBooleanOperator op) const;
/* Create a block with an optional tail expression */
std::unique_ptr<Expr> block (std::vector<std::unique_ptr<Stmt>> &&stmts,
std::unique_ptr<Expr> &&tail_expr = nullptr);
std::unique_ptr<BlockExpr> block (std::vector<std::unique_ptr<Stmt>> &&stmts,
std::unique_ptr<Expr> &&tail_expr
= nullptr) const;
std::unique_ptr<BlockExpr> block (tl::optional<std::unique_ptr<Stmt>> &&stmt,
std::unique_ptr<Expr> &&tail_expr
= nullptr) const;
/* Create an empty block */
std::unique_ptr<BlockExpr> block () const;
/* Create an early return expression with an optional expression */
std::unique_ptr<Expr> return_expr (std::unique_ptr<Expr> &&to_return
= nullptr);
/* Create a let binding with an optional type and initializer (`let <name> :
* <type> = <init>`) */
std::unique_ptr<Stmt> let (std::unique_ptr<Pattern> pattern,
std::unique_ptr<Type> type = nullptr,
std::unique_ptr<Expr> init = nullptr);
std::unique_ptr<Stmt> let (std::unique_ptr<Pattern> &&pattern,
std::unique_ptr<Type> &&type = nullptr,
std::unique_ptr<Expr> &&init = nullptr) const;
/**
* Create a call expression to a function, struct or enum variant, given its
* arguments (`path(arg0, arg1, arg2)`)
*/
std::unique_ptr<Expr> call (std::unique_ptr<Expr> &&path,
std::vector<std::unique_ptr<Expr>> &&args);
std::vector<std::unique_ptr<Expr>> &&args
= {}) const;
std::unique_ptr<Expr> call (std::unique_ptr<Expr> &&path,
std::unique_ptr<Expr> &&arg) const;
/**
* Create an array expression (`[member0, member1, member2]`)
*/
std::unique_ptr<Expr>
array (std::vector<std::unique_ptr<Expr>> &&members) const;
/* Create a qualified path in expression (`<type as Trait>::seg::expr`) */
std::unique_ptr<Expr>
qualified_path_in_expression (std::unique_ptr<Type> &&type, TypePath trait,
PathExprSegment segment) const;
std::unique_ptr<Expr>
qualified_path_in_expression (std::unique_ptr<Type> &&type, TypePath trait,
std::vector<PathExprSegment> &&segments
= {}) const;
/* Self parameter for a function definition (`&self`) */
std::unique_ptr<Param> self_ref_param (bool mutability = false) const;
/* A regular named function parameter for a definition (`a: type`) */
std::unique_ptr<Param> function_param (std::unique_ptr<Pattern> &&pattern,
std::unique_ptr<Type> &&type) const;
/* Empty function qualifiers, with no specific qualifiers */
FunctionQualifiers fn_qualifiers ();
FunctionQualifiers fn_qualifiers () const;
std::unique_ptr<Function>
function (std::string function_name,
std::vector<std::unique_ptr<Param>> params,
std::unique_ptr<Type> return_type, std::unique_ptr<BlockExpr> block,
std::vector<std::unique_ptr<GenericParam>> generic_params = {},
FunctionQualifiers qualifiers
= FunctionQualifiers (UNKNOWN_LOCATION, Async::No, Const::No,
Unsafety::Normal),
WhereClause where_clause = WhereClause::create_empty (),
Visibility visibility = Visibility::create_private ()) const;
/* Create a single path segment from one string */
PathExprSegment path_segment (std::string seg);
PathExprSegment path_segment (std::string seg) const;
/* And similarly for type path segments */
std::unique_ptr<TypePathSegment> type_path_segment (std::string seg);
std::unique_ptr<TypePathSegment> type_path_segment (std::string seg) const;
std::unique_ptr<TypePathSegment>
type_path_segment (LangItem::Kind lang_item) const;
std::unique_ptr<TypePathSegment>
type_path_segment_generic (std::string seg, GenericArgs args) const;
std::unique_ptr<TypePathSegment>
type_path_segment_generic (LangItem::Kind lang_item, GenericArgs args) const;
/* Create a Type from a single string - the most basic kind of type in our AST
*/
std::unique_ptr<Type> single_type_path (std::string type);
std::unique_ptr<Type> single_type_path (std::string type) const;
std::unique_ptr<Type> single_type_path (LangItem::Kind lang_item) const;
std::unique_ptr<Type> single_generic_type_path (std::string type,
GenericArgs args) const;
std::unique_ptr<Type> single_generic_type_path (LangItem::Kind lang_item,
GenericArgs args) const;
TypePath type_path (std::vector<std::unique_ptr<TypePathSegment>> &&segment,
bool opening_scope = false) const;
TypePath type_path (std::vector<std::string> &&segments,
bool opening_scope = false) const;
TypePath type_path (std::unique_ptr<TypePathSegment> &&segment) const;
TypePath type_path (std::string type) const;
TypePath type_path (LangItem::Kind lang_item) const;
std::unique_ptr<Type>
reference_type (std::unique_ptr<TypeNoBounds> &&inner_type,
bool mutability = false) const;
/**
* Create a path in expression from multiple segments (`Clone::clone`). You
* do not need to separate the segments using `::`, you can simply provide a
* vector of strings to the functions which will get turned into path segments
*/
PathInExpression path_in_expression (std::vector<std::string> &&segments);
PathInExpression path_in_expression (std::vector<std::string> &&segments,
bool opening_scope = false) const;
/**
* Create a path in expression from a lang item.
*/
PathInExpression path_in_expression (LangItem::Kind lang_item) const;
/* Create the path to an enum's variant (`Result::Ok`) */
PathInExpression variant_path (const std::string &enum_path,
const std::string &variant) const;
/* Create a new struct */
std::unique_ptr<Stmt>
struct_struct (std::string struct_name,
std::vector<std::unique_ptr<GenericParam>> &&generics,
std::vector<StructField> &&fields);
/* Create a struct expression for unit structs (`S`) */
std::unique_ptr<Expr> struct_expr_struct (std::string struct_name);
std::unique_ptr<Expr> struct_expr_struct (std::string struct_name) const;
/**
* Create an expression for struct instantiation with fields (`S { a, b: c }`)
* Named tuple expressions (`S(a, b, c)`) are call expressions and can thus be
* constructed with `call`
*/
std::unique_ptr<Expr>
struct_expr (std::string struct_name,
std::vector<std::unique_ptr<StructExprField>> &&fields);
std::vector<std::unique_ptr<StructExprField>> &&fields) const;
std::unique_ptr<Expr>
struct_expr (PathInExpression struct_name,
std::vector<std::unique_ptr<StructExprField>> &&fields) const;
/* Create a field expression for struct instantiation (`field_name: value`) */
std::unique_ptr<StructExprField>
struct_expr_field (std::string field_name, std::unique_ptr<Expr> &&value);
struct_expr_field (std::string field_name,
std::unique_ptr<Expr> &&value) const;
/* Create a field access expression (`instance.field`) */
std::unique_ptr<Expr> field_access (std::unique_ptr<Expr> &&instance,
std::string field);
std::string field) const;
std::unique_ptr<StructPatternField>
struct_pattern_ident_pattern (std::string field_name,
std::unique_ptr<Pattern> &&pattern);
/* Create a wildcard pattern (`_`) */
std::unique_ptr<Pattern> wildcard ();
std::unique_ptr<Pattern> wildcard () const;
/* Create a reference pattern (`&pattern`) */
std::unique_ptr<Pattern> ref_pattern (std::unique_ptr<Pattern> &&inner) const;
/* Create a lang item path usable as a general path */
std::unique_ptr<Path> lang_item_path (LangItem::Kind) const;
/* Create match expressions and their components */
std::unique_ptr<Expr> match (std::unique_ptr<Expr> &&scrutinee,
std::vector<MatchCase> &&cases);
MatchArm match_arm (std::unique_ptr<Pattern> &&pattern);
MatchCase match_case (std::unique_ptr<Pattern> &&pattern,
std::unique_ptr<Expr> &&expr);
/* Create a loop expression */
std::unique_ptr<Expr> loop (std::vector<std::unique_ptr<Stmt>> &&stmts);
std::unique_ptr<TypeParamBound> trait_bound (TypePath bound);
std::unique_ptr<Item>
trait_impl (TypePath trait_path, std::unique_ptr<Type> target,
std::vector<std::unique_ptr<AssociatedItem>> trait_items = {},
std::vector<std::unique_ptr<GenericParam>> generics = {},
WhereClause where_clause = WhereClause::create_empty (),
Visibility visibility = Visibility::create_private ()) const;
std::unique_ptr<GenericParam>
generic_type_param (std::string type_representation,
std::vector<std::unique_ptr<TypeParamBound>> &&bounds,
std::unique_ptr<Type> &&type = nullptr);
static std::unique_ptr<Type> new_type (Type &type);
static std::unique_ptr<GenericParam>
new_lifetime_param (LifetimeParam &param);
static std::unique_ptr<GenericParam> new_type_param (
TypeParam &param,
std::vector<std::unique_ptr<TypeParamBound>> extra_trait_bounds = {});
static Lifetime new_lifetime (const Lifetime &lifetime);
static GenericArgs new_generic_args (GenericArgs &args);
private:
/**

View File

@@ -15,9 +15,17 @@
// You should have received a copy of the GNU General Public License
// along with GCC; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
#include "rust-ast-collector.h"
#include "rust-ast.h"
#include "rust-diagnostics.h"
#include "rust-expr.h"
#include "rust-item.h"
#include "rust-keyword-values.h"
#include "rust-location.h"
#include "rust-path.h"
#include "rust-system.h"
#include "rust-token.h"
namespace Rust {
namespace AST {
@@ -245,29 +253,6 @@ TokenCollector::visit (Visibility &vis)
}
}
void
TokenCollector::visit (NamedFunctionParam &param)
{
auto name = param.get_name ();
if (!param.is_variadic ())
{
push (
Rust::Token::make_identifier (param.get_locus (), std::move (name)));
push (Rust::Token::make (COLON, UNDEF_LOCATION));
visit (param.get_type ());
}
else
{
if (name != "")
{
push (Rust::Token::make_identifier (param.get_locus (),
std::move (name)));
push (Rust::Token::make (COLON, UNDEF_LOCATION));
}
push (Rust::Token::make (ELLIPSIS, UNDEF_LOCATION));
}
}
void
TokenCollector::visit (std::vector<std::unique_ptr<GenericParam>> &params)
{
@@ -394,6 +379,9 @@ TokenCollector::visit (Token &tok)
case BYTE_STRING_LITERAL:
push (Rust::Token::make_byte_string (tok.get_locus (), std::move (data)));
break;
case RAW_STRING_LITERAL:
push (Rust::Token::make_raw_string (tok.get_locus (), std::move (data)));
break;
case INNER_DOC_COMMENT:
push (Rust::Token::make_inner_doc_comment (tok.get_locus (),
std::move (data)));
@@ -473,6 +461,7 @@ TokenCollector::visit (LifetimeParam &lifetime_param)
// TODO what to do with outer attr? They are not mentioned in the reference.
visit_items_as_lines (lifetime_param.get_outer_attrs ());
auto lifetime = lifetime_param.get_lifetime ();
visit (lifetime);
@@ -492,6 +481,7 @@ TokenCollector::visit (ConstGenericParam &param)
// Syntax:
// const IDENTIFIER : Type ( = Block | IDENTIFIER | -?LITERAL )?
visit_items_as_lines (param.get_outer_attrs ());
push (Rust::Token::make (CONST, param.get_locus ()));
auto id = param.get_name ().as_string ();
push (Rust::Token::make_identifier (UNDEF_LOCATION, std::move (id)));
@@ -501,7 +491,7 @@ TokenCollector::visit (ConstGenericParam &param)
if (param.has_default_value ())
{
push (Rust::Token::make (EQUAL, UNDEF_LOCATION));
visit (param.get_default_value ());
visit (param.get_default_value_unchecked ());
}
}
@@ -543,11 +533,23 @@ TokenCollector::visit (PathExprSegment &segment)
void
TokenCollector::visit (PathInExpression &path)
{
if (path.opening_scope_resolution ())
if (path.is_lang_item ())
{
push (Rust::Token::make (SCOPE_RESOLUTION, path.get_locus ()));
push (Rust::Token::make (TokenId::HASH, path.get_locus ()));
push (Rust::Token::make (TokenId::LEFT_SQUARE, path.get_locus ()));
push (Rust::Token::make_identifier (path.get_locus (), "lang"));
push (Rust::Token::make (TokenId::EQUAL, path.get_locus ()));
push (
Rust::Token::make_string (path.get_locus (),
LangItem::ToString (path.get_lang_item ())));
push (Rust::Token::make (TokenId::RIGHT_SQUARE, path.get_locus ()));
return;
}
if (path.opening_scope_resolution ())
push (Rust::Token::make (SCOPE_RESOLUTION, path.get_locus ()));
visit_items_joined_by_separator (path.get_segments (), SCOPE_RESOLUTION);
}
@@ -556,10 +558,14 @@ TokenCollector::visit (TypePathSegment &segment)
{
// Syntax:
// PathIdentSegment
auto ident_segment = segment.get_ident_segment ();
auto id = ident_segment.as_string ();
push (
Rust::Token::make_identifier (ident_segment.get_locus (), std::move (id)));
auto locus = segment.is_lang_item ()
? segment.get_locus ()
: segment.get_ident_segment ().get_locus ();
auto segment_string = segment.is_lang_item ()
? LangItem::PrettyString (segment.get_lang_item ())
: segment.get_ident_segment ().as_string ();
push (Rust::Token::make_identifier (locus, std::move (segment_string)));
}
void
@@ -571,10 +577,13 @@ TokenCollector::visit (TypePathSegmentGeneric &segment)
// `<` `>`
// | `<` ( GenericArg `,` )* GenericArg `,`? `>`
auto ident_segment = segment.get_ident_segment ();
auto id = ident_segment.as_string ();
push (
Rust::Token::make_identifier (ident_segment.get_locus (), std::move (id)));
auto locus = segment.is_lang_item ()
? segment.get_locus ()
: segment.get_ident_segment ().get_locus ();
auto segment_string = segment.is_lang_item ()
? LangItem::PrettyString (segment.get_lang_item ())
: segment.get_ident_segment ().as_string ();
push (Rust::Token::make_identifier (locus, std::move (segment_string)));
if (segment.get_separating_scope_resolution ())
push (Rust::Token::make (SCOPE_RESOLUTION, UNDEF_LOCATION));
@@ -630,8 +639,6 @@ TokenCollector::visit (GenericArg &arg)
push (Rust::Token::make_identifier (UNDEF_LOCATION, std::move (path)));
}
break;
case GenericArg::Kind::Error:
rust_unreachable ();
}
}
@@ -688,19 +695,19 @@ TokenCollector::visit (TypePath &path)
void
TokenCollector::visit (PathIdentSegment &segment)
{
if (segment.is_super_segment ())
if (segment.is_super_path_seg ())
{
push (Rust::Token::make (SUPER, segment.get_locus ()));
}
else if (segment.is_crate_segment ())
else if (segment.is_crate_path_seg ())
{
push (Rust::Token::make (CRATE, segment.get_locus ()));
}
else if (segment.is_lower_self ())
else if (segment.is_lower_self_seg ())
{
push (Rust::Token::make (SELF, segment.get_locus ()));
}
else if (segment.is_big_self ())
else if (segment.is_big_self_seg ())
{
push (Rust::Token::make (SELF_ALIAS, segment.get_locus ()));
}
@@ -771,6 +778,9 @@ TokenCollector::visit (Literal &lit, location_t locus)
case Literal::LitType::BYTE_STRING:
push (Rust::Token::make_byte_string (locus, std::move (value)));
break;
case Literal::LitType::RAW_STRING:
push (Rust::Token::make_raw_string (locus, std::move (value)));
break;
case Literal::LitType::INT:
push (
Rust::Token::make_int (locus, std::move (value), lit.get_type_hint ()));
@@ -838,8 +848,21 @@ TokenCollector::visit (BorrowExpr &expr)
push (Rust::Token::make (AMP, expr.get_locus ()));
if (expr.get_is_double_borrow ())
push (Rust::Token::make (AMP, UNDEF_LOCATION));
if (expr.get_is_mut ())
push (Rust::Token::make (MUT, UNDEF_LOCATION));
if (expr.is_raw_borrow ())
{
push (Rust::Token::make_identifier (expr.get_locus (),
Values::WeakKeywords::RAW));
if (expr.get_is_mut ())
push (Rust::Token::make (MUT, UNDEF_LOCATION));
else
push (Rust::Token::make (CONST, UNDEF_LOCATION));
}
else
{
if (expr.get_is_mut ())
push (Rust::Token::make (MUT, UNDEF_LOCATION));
}
visit (expr.get_borrowed_expr ());
}
@@ -1094,8 +1117,7 @@ TokenCollector::visit (StructExprStruct &expr)
void
TokenCollector::visit (StructExprFieldIdentifier &expr)
{
// TODO: Add attributes
// visit_items_as_lines (expr.get_attrs ());
visit_items_as_lines (expr.get_outer_attrs ());
auto id = expr.get_field_name ().as_string ();
push (Rust::Token::make_identifier (expr.get_locus (), std::move (id)));
}
@@ -1103,8 +1125,7 @@ TokenCollector::visit (StructExprFieldIdentifier &expr)
void
TokenCollector::visit (StructExprFieldIdentifierValue &expr)
{
// TODO: Add attributes
// visit_items_as_lines (expr.get_attrs ());
visit_items_as_lines (expr.get_outer_attrs ());
auto id = expr.get_field_name ();
push (Rust::Token::make_identifier (expr.get_locus (), std::move (id)));
push (Rust::Token::make (COLON, UNDEF_LOCATION));
@@ -1114,8 +1135,7 @@ TokenCollector::visit (StructExprFieldIdentifierValue &expr)
void
TokenCollector::visit (StructExprFieldIndexValue &expr)
{
// TODO: Add attributes
// visit_items_as_lines (expr.get_attrs ());
visit_items_as_lines (expr.get_outer_attrs ());
push (Rust::Token::make_int (expr.get_locus (),
std::to_string (expr.get_index ())));
push (Rust::Token::make (COLON, UNDEF_LOCATION));
@@ -1243,6 +1263,22 @@ TokenCollector::visit (BlockExpr &expr)
newline ();
}
void
TokenCollector::visit (AnonConst &expr)
{
visit (expr.get_inner_expr ());
}
void
TokenCollector::visit (ConstBlock &expr)
{
push (Rust::Token::make (CONST, expr.get_locus ()));
// The inner expression is already a block expr, so we don't need to add
// curlies
visit (expr.get_const_expr ());
}
void
TokenCollector::visit (ClosureExprInnerTyped &expr)
{
@@ -1257,7 +1293,7 @@ TokenCollector::visit (ContinueExpr &expr)
{
push (Rust::Token::make (CONTINUE, expr.get_locus ()));
if (expr.has_label ())
visit (expr.get_label ());
visit (expr.get_label_unchecked ());
}
void
@@ -1265,7 +1301,7 @@ TokenCollector::visit (BreakExpr &expr)
{
push (Rust::Token::make (BREAK, expr.get_locus ()));
if (expr.has_label ())
visit (expr.get_label ());
visit (expr.get_label_unchecked ());
if (expr.has_break_expr ())
visit (expr.get_break_expr ());
}
@@ -1313,6 +1349,13 @@ TokenCollector::visit (RangeToInclExpr &expr)
visit (expr.get_to_expr ());
}
void
TokenCollector::visit (BoxExpr &expr)
{
push (Rust::Token::make (BOX, expr.get_locus ()));
visit (expr.get_boxed_expr ());
}
void
TokenCollector::visit (ReturnExpr &expr)
{
@@ -1489,6 +1532,132 @@ TokenCollector::visit (AsyncBlockExpr &expr)
visit (expr.get_block_expr ());
}
void
TokenCollector::visit (InlineAsm &expr)
{
push (Rust::Token::make_identifier (expr.get_locus (), "asm"));
push (Rust::Token::make (EXCLAM, expr.get_locus ()));
push (Rust::Token::make (LEFT_PAREN, expr.get_locus ()));
for (auto &template_str : expr.get_template_strs ())
push (Rust::Token::make_string (template_str.get_locus (),
std::move (template_str.symbol)));
push (Rust::Token::make (COLON, expr.get_locus ()));
for (auto &operand : expr.get_operands ())
{
using RegisterType = AST::InlineAsmOperand::RegisterType;
switch (operand.get_register_type ())
{
case RegisterType::In: {
visit (operand.get_in ().expr);
break;
}
case RegisterType::Out: {
visit (operand.get_out ().expr);
break;
}
case RegisterType::InOut: {
visit (operand.get_in_out ().expr);
break;
}
case RegisterType::SplitInOut: {
auto split = operand.get_split_in_out ();
visit (split.in_expr);
visit (split.out_expr);
break;
}
case RegisterType::Const: {
visit (operand.get_const ().anon_const.get_inner_expr ());
break;
}
case RegisterType::Sym: {
visit (operand.get_sym ().expr);
break;
}
case RegisterType::Label: {
visit (operand.get_label ().expr);
break;
}
}
push (Rust::Token::make (COMMA, expr.get_locus ()));
}
push (Rust::Token::make (COLON, expr.get_locus ()));
for (auto &clobber : expr.get_clobber_abi ())
{
push (Rust::Token::make_string (expr.get_locus (),
std::move (clobber.symbol)));
push (Rust::Token::make (COMMA, expr.get_locus ()));
}
push (Rust::Token::make (COLON, expr.get_locus ()));
for (auto it = expr.named_args.begin (); it != expr.named_args.end (); ++it)
{
auto &arg = *it;
push (
Rust::Token::make_identifier (expr.get_locus (), arg.first.c_str ()));
push (Rust::Token::make (EQUAL, expr.get_locus ()));
push (Rust::Token::make_identifier (expr.get_locus (),
std::to_string (arg.second)));
push (Rust::Token::make (COMMA, expr.get_locus ()));
}
push (Rust::Token::make (COLON, expr.get_locus ()));
for (auto &option : expr.get_options ())
{
push (Rust::Token::make_identifier (
expr.get_locus (), InlineAsm::option_to_string (option).c_str ()));
push (Rust::Token::make (COMMA, expr.get_locus ()));
}
push (Rust::Token::make (RIGHT_PAREN, expr.get_locus ()));
}
void
TokenCollector::visit (LlvmInlineAsm &expr)
{
push (Rust::Token::make_identifier (expr.get_locus (), "llvm_asm"));
push (Rust::Token::make (EXCLAM, expr.get_locus ()));
push (Rust::Token::make (LEFT_PAREN, expr.get_locus ()));
for (auto &template_str : expr.get_templates ())
push (Rust::Token::make_string (template_str.get_locus (),
std::move (template_str.symbol)));
push (Rust::Token::make (COLON, expr.get_locus ()));
for (auto output : expr.get_outputs ())
{
push (Rust::Token::make_string (expr.get_locus (),
std::move (output.constraint)));
visit (output.expr);
push (Rust::Token::make (COMMA, expr.get_locus ()));
}
push (Rust::Token::make (COLON, expr.get_locus ()));
for (auto input : expr.get_inputs ())
{
push (Rust::Token::make_string (expr.get_locus (),
std::move (input.constraint)));
visit (input.expr);
push (Rust::Token::make (COMMA, expr.get_locus ()));
}
push (Rust::Token::make (COLON, expr.get_locus ()));
for (auto &clobber : expr.get_clobbers ())
{
push (Rust::Token::make_string (expr.get_locus (),
std::move (clobber.symbol)));
push (Rust::Token::make (COMMA, expr.get_locus ()));
}
push (Rust::Token::make (COLON, expr.get_locus ()));
// Dump options
push (Rust::Token::make (RIGHT_PAREN, expr.get_locus ()));
}
// rust-item.h
void
@@ -1499,6 +1668,7 @@ TokenCollector::visit (TypeParam &param)
// TypeParamBounds :
// TypeParamBound ( + TypeParamBound )* +?
visit_items_as_lines (param.get_outer_attrs ());
auto id = param.get_type_representation ().as_string ();
push (Rust::Token::make_identifier (param.get_locus (), std::move (id)));
if (param.has_type_param_bounds ())
@@ -2082,31 +2252,6 @@ TokenCollector::visit (ExternalStaticItem &item)
push (Rust::Token::make (SEMICOLON, UNDEF_LOCATION));
}
void
TokenCollector::visit (ExternalFunctionItem &function)
{
visit_items_as_lines (function.get_outer_attrs ());
visit (function.get_visibility ());
auto id = function.get_identifier ().as_string ();
push (Rust::Token::make (FN_KW, function.get_locus ()));
push (Rust::Token::make_identifier (UNDEF_LOCATION, std::move (id)));
if (function.has_generics ())
visit (function.get_generic_params ());
push (Rust::Token::make (LEFT_PAREN, UNDEF_LOCATION));
visit_items_joined_by_separator (function.get_function_params ());
push (Rust::Token::make (RIGHT_PAREN, UNDEF_LOCATION));
if (function.has_return_type ())
{
push (Rust::Token::make (RETURN_TYPE, UNDEF_LOCATION));
visit (function.get_return_type ());
}
push (Rust::Token::make (SEMICOLON, UNDEF_LOCATION));
}
void
TokenCollector::visit (ExternBlock &block)
{
@@ -2476,10 +2621,7 @@ TokenCollector::visit (StructPattern &pattern)
void
TokenCollector::visit (TupleStructItemsNoRange &pattern)
{
for (auto &pat : pattern.get_patterns ())
{
visit (pat);
}
visit_items_joined_by_separator (pattern.get_patterns ());
}
void
@@ -2501,8 +2643,7 @@ TokenCollector::visit (TupleStructPattern &pattern)
{
visit (pattern.get_path ());
push (Rust::Token::make (LEFT_PAREN, pattern.get_locus ()));
if (pattern.has_items ())
visit (pattern.get_items ());
visit (pattern.get_items ());
push (Rust::Token::make (RIGHT_PAREN, UNDEF_LOCATION));
}
@@ -2570,8 +2711,7 @@ TokenCollector::visit (LetStmt &stmt)
{
push (Rust::Token::make (LET, stmt.get_locus ()));
auto &pattern = stmt.get_pattern ();
if (pattern)
visit (pattern);
visit (pattern);
if (stmt.has_type ())
{
@@ -2584,6 +2724,13 @@ TokenCollector::visit (LetStmt &stmt)
push (Rust::Token::make (EQUAL, UNDEF_LOCATION));
visit (stmt.get_init_expr ());
}
if (stmt.has_else_expr ())
{
push (Rust::Token::make (ELSE, UNDEF_LOCATION));
visit (stmt.get_else_expr ());
}
push (Rust::Token::make (SEMICOLON, UNDEF_LOCATION));
}
@@ -2805,5 +2952,12 @@ TokenCollector::visit (BareFunctionType &type)
}
}
void
TokenCollector::visit (AST::FormatArgs &fmt)
{
rust_sorry_at (fmt.get_locus (), "%s:%u: unimplemented FormatArgs visitor",
__FILE__, __LINE__);
}
} // namespace AST
} // namespace Rust

View File

@@ -210,7 +210,6 @@ public:
void visit (TupleField &field);
void visit (StructField &field);
void visit (SimplePathSegment &segment);
void visit (NamedFunctionParam &param);
void visit (MacroRule &rule);
void visit (WhereClause &rule);
void visit (std::vector<LifetimeParam> &for_lifetimes);
@@ -278,6 +277,8 @@ public:
void visit (ClosureParam &param);
void visit (ClosureExprInner &expr);
void visit (BlockExpr &expr);
void visit (AnonConst &expr);
void visit (ConstBlock &expr);
void visit (ClosureExprInnerTyped &expr);
void visit (ContinueExpr &expr);
void visit (BreakExpr &expr);
@@ -288,6 +289,7 @@ public:
void visit (RangeFromToInclExpr &expr);
void visit (RangeToInclExpr &expr);
void visit (ReturnExpr &expr);
void visit (BoxExpr &expr);
void visit (UnsafeBlockExpr &expr);
void visit (LoopExpr &expr);
void visit (WhileLoopExpr &expr);
@@ -302,7 +304,8 @@ public:
void visit (MatchExpr &expr);
void visit (AwaitExpr &expr);
void visit (AsyncBlockExpr &expr);
void visit (InlineAsm &expr);
void visit (LlvmInlineAsm &expr);
// rust-item.h
void visit (TypeParam &param);
void visit (LifetimeWhereClauseItem &item);
@@ -333,7 +336,6 @@ public:
void visit (TraitImpl &impl);
void visit (ExternalTypeItem &item);
void visit (ExternalStaticItem &item);
void visit (ExternalFunctionItem &item);
void visit (ExternBlock &block);
// rust-macro.h
@@ -398,6 +400,8 @@ public:
void visit (SliceType &type);
void visit (InferredType &type);
void visit (BareFunctionType &type);
void visit (FormatArgs &fmt);
};
} // namespace AST

View File

@@ -123,12 +123,25 @@ private:
void assert_single_fragment (SingleASTNode::NodeType expected) const;
};
enum class InvocKind
{
Expr,
Semicoloned,
};
enum class AsmKind
{
Global,
Inline
};
/**
* This is the type for transcriber functions found in
* rust-macro-builtins.{h,cc}.
*/
using MacroTranscriberFunc
= std::function<tl::optional<Fragment> (location_t, MacroInvocData &)>;
= std::function<tl::optional<Fragment> (location_t, MacroInvocData &,
InvocKind semicolon)>;
} // namespace AST
} // namespace Rust

View File

@@ -61,7 +61,7 @@ class PathIdentSegment;
struct GenericArgsBinding;
struct GenericArgs;
class PathExprSegment;
class PathPattern;
class Path;
class PathInExpression;
class TypePathSegment;
class TypePathSegmentGeneric;
@@ -115,6 +115,8 @@ struct ClosureParam;
class ClosureExpr;
class ClosureExprInner;
class BlockExpr;
class AnonConst;
class ConstBlock;
class ClosureExprInnerTyped;
class ContinueExpr;
class BreakExpr;
@@ -145,10 +147,9 @@ struct MatchCase;
class MatchExpr;
class AwaitExpr;
class AsyncBlockExpr;
enum class InlineAsmOptions;
struct AnonConst;
enum class InlineAsmOption;
struct InlineAsmRegOrRegClass;
struct InlineAsmOperand;
class InlineAsmOperand;
struct InlineAsmPlaceHolder;
struct InlineAsmTemplatePiece;
struct TupleClobber;
@@ -202,8 +203,6 @@ class TraitImpl;
class ExternalItem;
class ExternalTypeItem;
class ExternalStaticItem;
class NamedFunctionParam;
class ExternalFunctionItem;
class ExternBlock;
// rust-macro.h
@@ -267,6 +266,9 @@ class SliceType;
class InferredType;
struct MaybeNamedParam;
class BareFunctionType;
// rust-builtin-ast-nodes.h
class FormatArgs;
} // namespace AST
} // namespace Rust

View File

@@ -28,5 +28,6 @@
#include "rust-stmt.h"
#include "rust-type.h"
#include "rust-macro.h"
#include "rust-builtin-ast-nodes.h"
#endif

View File

@@ -69,7 +69,7 @@ DefaultASTVisitor::visit (AST::Lifetime &lifetime)
void
DefaultASTVisitor::visit (AST::LifetimeParam &lifetime_param)
{
visit (lifetime_param.get_outer_attribute ());
visit_outer_attrs (lifetime_param);
visit (lifetime_param.get_lifetime ());
for (auto &lifetime_bound : lifetime_param.get_lifetime_bounds ())
visit (lifetime_bound);
@@ -78,19 +78,21 @@ DefaultASTVisitor::visit (AST::LifetimeParam &lifetime_param)
void
DefaultASTVisitor::visit (AST::ConstGenericParam &const_param)
{
visit (const_param.get_outer_attribute ());
visit_outer_attrs (const_param);
if (const_param.has_type ())
visit (const_param.get_type ());
if (const_param.has_default_value ())
visit (const_param.get_default_value ());
visit (const_param.get_default_value_unchecked ());
}
void
DefaultASTVisitor::visit (AST::PathInExpression &path)
{
visit_outer_attrs (path);
for (auto &segment : path.get_segments ())
visit (segment);
if (!path.is_lang_item ())
for (auto &segment : path.get_segments ())
visit (segment);
}
void
@@ -106,7 +108,8 @@ DefaultASTVisitor::visit (GenericArgsBinding &binding)
void
DefaultASTVisitor::visit (AST::TypePathSegmentGeneric &segment)
{
visit (segment.get_generic_args ());
if (segment.has_generic_args ())
visit (segment.get_generic_args ());
}
void
@@ -390,6 +393,7 @@ DefaultASTVisitor::visit (AST::StructExprStructFields &expr)
{
visit_outer_attrs (expr);
visit_inner_attrs (expr);
visit (expr.get_struct_name ());
if (expr.has_struct_base ())
visit (expr.get_struct_base ());
for (auto &field : expr.get_fields ())
@@ -401,6 +405,7 @@ DefaultASTVisitor::visit (AST::StructExprStructBase &expr)
{
visit_outer_attrs (expr);
visit_inner_attrs (expr);
visit (expr.get_struct_name ());
visit (expr.get_struct_base ());
}
@@ -450,6 +455,18 @@ DefaultASTVisitor::visit (AST::BlockExpr &expr)
visit (expr.get_tail_expr ());
}
void
DefaultASTVisitor::visit (AST::ConstBlock &expr)
{
visit (expr.get_const_expr ());
}
void
DefaultASTVisitor::visit (AST::AnonConst &expr)
{
visit (expr.get_inner_expr ());
}
void
DefaultASTVisitor::visit (AST::ClosureExprInnerTyped &expr)
{
@@ -473,7 +490,8 @@ void
DefaultASTVisitor::visit (AST::ContinueExpr &expr)
{
visit_outer_attrs (expr);
visit (expr.get_label ());
if (expr.has_label ())
visit (expr.get_label_unchecked ());
}
void
@@ -481,7 +499,7 @@ DefaultASTVisitor::visit (AST::BreakExpr &expr)
{
visit_outer_attrs (expr);
if (expr.has_label ())
visit (expr.get_label ());
visit (expr.get_label_unchecked ());
if (expr.has_break_expr ())
visit (expr.get_break_expr ());
@@ -531,6 +549,13 @@ DefaultASTVisitor::visit (AST::ReturnExpr &expr)
visit (expr.get_returned_expr ());
}
void
DefaultASTVisitor::visit (AST::BoxExpr &expr)
{
visit_outer_attrs (expr);
visit (expr.get_boxed_expr ());
}
void
DefaultASTVisitor::visit (AST::UnsafeBlockExpr &expr)
{
@@ -548,7 +573,8 @@ void
DefaultASTVisitor::visit (AST::LoopExpr &expr)
{
visit_outer_attrs (expr);
visit (expr.get_loop_label ());
if (expr.has_loop_label ())
visit (expr.get_loop_label ());
visit (expr.get_loop_block ());
}
@@ -556,8 +582,9 @@ void
DefaultASTVisitor::visit (AST::WhileLoopExpr &expr)
{
visit_outer_attrs (expr);
if (expr.has_loop_label ())
visit (expr.get_loop_label ());
visit (expr.get_predicate_expr ());
visit (expr.get_loop_label ());
visit (expr.get_loop_block ());
}
@@ -567,8 +594,8 @@ DefaultASTVisitor::visit (AST::WhileLetLoopExpr &expr)
visit_outer_attrs (expr);
for (auto &pattern : expr.get_patterns ())
visit (pattern);
visit (expr.get_scrutinee_expr ());
visit (expr.get_loop_label ());
visit (expr.get_scrutinee_expr ());
visit (expr.get_loop_block ());
}
@@ -578,7 +605,8 @@ DefaultASTVisitor::visit (AST::ForLoopExpr &expr)
visit_outer_attrs (expr);
visit (expr.get_pattern ());
visit (expr.get_iterator_expr ());
visit (expr.get_loop_label ());
if (expr.has_loop_label ())
visit (expr.get_loop_label ());
visit (expr.get_loop_block ());
}
@@ -655,10 +683,63 @@ DefaultASTVisitor::visit (AST::AsyncBlockExpr &expr)
visit (expr.get_block_expr ());
}
void
DefaultASTVisitor::visit (AST::InlineAsm &expr)
{
visit_outer_attrs (expr);
using RegisterType = AST::InlineAsmOperand::RegisterType;
for (auto &operand : expr.get_operands ())
{
switch (operand.get_register_type ())
{
case RegisterType::In: {
visit (operand.get_in ().expr);
break;
}
case RegisterType::Out: {
visit (operand.get_out ().expr);
break;
}
case RegisterType::InOut: {
visit (operand.get_in_out ().expr);
break;
}
case RegisterType::SplitInOut: {
auto split = operand.get_split_in_out ();
visit (split.in_expr);
visit (split.out_expr);
break;
}
case RegisterType::Const: {
visit (operand.get_const ().anon_const.get_inner_expr ());
break;
}
case RegisterType::Sym: {
visit (operand.get_sym ().expr);
break;
}
case RegisterType::Label: {
visit (operand.get_label ().expr);
break;
}
}
}
}
void
DefaultASTVisitor::visit (AST::LlvmInlineAsm &expr)
{
for (auto &output : expr.get_outputs ())
visit (output.expr);
for (auto &input : expr.get_inputs ())
visit (input.expr);
}
void
DefaultASTVisitor::visit (AST::TypeParam &param)
{
visit (param.get_outer_attribute ());
visit_outer_attrs (param);
for (auto &bound : param.get_type_param_bounds ())
visit (bound);
if (param.has_type ())
@@ -686,7 +767,8 @@ DefaultASTVisitor::visit (AST::TypeBoundWhereClauseItem &item)
void
DefaultASTVisitor::visit (AST::Visibility &vis)
{
visit (vis.get_path ());
if (vis.has_path ())
visit (vis.get_path ());
}
void
@@ -759,9 +841,17 @@ DefaultASTVisitor::visit (AST::UseTreeRebind &use_tree)
void
DefaultASTVisitor::visit (AST::UseDeclaration &use_decl)
{
visit (use_decl.get_visibility ());
visit (use_decl.get_tree ());
}
void
DefaultASTVisitor::visit_function_params (AST::Function &function)
{
for (auto &param : function.get_function_params ())
visit (param);
}
void
DefaultASTVisitor::visit (AST::Function &function)
{
@@ -770,10 +860,9 @@ DefaultASTVisitor::visit (AST::Function &function)
visit (function.get_qualifiers ());
for (auto &generic : function.get_generic_params ())
visit (generic);
if (function.has_self_param ())
visit (function.get_self_param ());
for (auto &param : function.get_function_params ())
visit (param);
visit_function_params (function);
if (function.has_return_type ())
visit (function.get_return_type ());
if (function.has_where_clause ())
@@ -846,7 +935,7 @@ DefaultASTVisitor::visit (AST::EnumItem &item)
void
DefaultASTVisitor::visit (AST::EnumItemTuple &item)
{
visit (reinterpret_cast<EnumItem &> (item));
DefaultASTVisitor::visit (reinterpret_cast<EnumItem &> (item));
for (auto &field : item.get_tuple_fields ())
visit (field);
}
@@ -854,7 +943,7 @@ DefaultASTVisitor::visit (AST::EnumItemTuple &item)
void
DefaultASTVisitor::visit (AST::EnumItemStruct &item)
{
visit (reinterpret_cast<EnumItem &> (item));
DefaultASTVisitor::visit (reinterpret_cast<EnumItem &> (item));
for (auto &field : item.get_struct_fields ())
visit (field);
}
@@ -862,7 +951,7 @@ DefaultASTVisitor::visit (AST::EnumItemStruct &item)
void
DefaultASTVisitor::visit (AST::EnumItemDiscriminant &item)
{
visit (reinterpret_cast<EnumItem &> (item));
DefaultASTVisitor::visit (reinterpret_cast<EnumItem &> (item));
visit (item.get_expr ());
}
@@ -936,6 +1025,8 @@ DefaultASTVisitor::visit (AST::Trait &trait)
visit_inner_attrs (trait);
visit (trait.get_implicit_self ());
for (auto &generic : trait.get_generic_params ())
visit (generic);
@@ -976,6 +1067,7 @@ DefaultASTVisitor::visit (AST::TraitImpl &impl)
if (impl.has_where_clause ())
visit (impl.get_where_clause ());
visit (impl.get_type ());
visit (impl.get_trait_path ());
visit_inner_attrs (impl);
for (auto &item : impl.get_impl_items ())
visit (item);
@@ -996,32 +1088,6 @@ DefaultASTVisitor::visit (AST::ExternalStaticItem &item)
visit (item.get_type ());
}
void
DefaultASTVisitor::visit (AST::NamedFunctionParam &param)
{
visit_outer_attrs (param);
if (!param.is_variadic ())
visit (param.get_type ());
}
void
DefaultASTVisitor::visit (AST::ExternalFunctionItem &item)
{
visit_outer_attrs (item);
visit (item.get_visibility ());
for (auto &generic : item.get_generic_params ())
visit (generic);
if (item.has_where_clause ())
visit (item.get_where_clause ());
for (auto &param : item.get_function_params ())
visit (param);
if (item.has_return_type ())
visit (item.get_return_type ());
}
void
DefaultASTVisitor::visit (AST::ExternBlock &block)
{
@@ -1225,8 +1291,7 @@ void
DefaultASTVisitor::visit (AST::TupleStructPattern &pattern)
{
visit (pattern.get_path ());
if (pattern.has_items ())
visit (pattern.get_items ());
visit (pattern.get_items ());
}
void
@@ -1395,6 +1460,12 @@ DefaultASTVisitor::visit (AST::BareFunctionType &type)
visit (type.get_return_type ());
}
void
DefaultASTVisitor::visit (AST::FormatArgs &)
{
// FIXME: Do we have anything to do? any subnodes to visit? Probably, right?
}
void
DefaultASTVisitor::visit (AST::VariadicParam &param)
{
@@ -1405,33 +1476,33 @@ DefaultASTVisitor::visit (AST::VariadicParam &param)
void
ContextualASTVisitor::visit (AST::Crate &crate)
{
push_context (Context::CRATE);
ctx.enter (Kind::CRATE);
DefaultASTVisitor::visit (crate);
pop_context ();
ctx.exit ();
}
void
ContextualASTVisitor::visit (AST::InherentImpl &impl)
{
push_context (Context::INHERENT_IMPL);
ctx.enter (Kind::INHERENT_IMPL);
DefaultASTVisitor::visit (impl);
pop_context ();
ctx.exit ();
}
void
ContextualASTVisitor::visit (AST::TraitImpl &impl)
{
push_context (Context::TRAIT_IMPL);
ctx.enter (Kind::TRAIT_IMPL);
DefaultASTVisitor::visit (impl);
pop_context ();
ctx.exit ();
}
void
ContextualASTVisitor::visit (AST::Trait &trait)
{
push_context (Context::TRAIT);
ctx.enter (Kind::TRAIT);
DefaultASTVisitor::visit (trait);
pop_context ();
ctx.exit ();
}
} // namespace AST

View File

@@ -24,7 +24,9 @@
#include "rust-ast-full-decls.h"
#include "rust-ast.h"
#include "rust-item.h"
#include "rust-path.h"
#include "rust-system.h"
#include "rust-stacked-contexts.h"
namespace Rust {
namespace AST {
@@ -102,6 +104,8 @@ public:
virtual void visit (FieldAccessExpr &expr) = 0;
virtual void visit (ClosureExprInner &expr) = 0;
virtual void visit (BlockExpr &expr) = 0;
virtual void visit (AnonConst &expr) = 0;
virtual void visit (ConstBlock &expr) = 0;
virtual void visit (ClosureExprInnerTyped &expr) = 0;
virtual void visit (ContinueExpr &expr) = 0;
virtual void visit (BreakExpr &expr) = 0;
@@ -112,6 +116,7 @@ public:
virtual void visit (RangeFromToInclExpr &expr) = 0;
virtual void visit (RangeToInclExpr &expr) = 0;
virtual void visit (ReturnExpr &expr) = 0;
virtual void visit (BoxExpr &expr) = 0;
virtual void visit (UnsafeBlockExpr &expr) = 0;
virtual void visit (LoopExpr &expr) = 0;
virtual void visit (WhileLoopExpr &expr) = 0;
@@ -127,6 +132,8 @@ public:
virtual void visit (MatchExpr &expr) = 0;
virtual void visit (AwaitExpr &expr) = 0;
virtual void visit (AsyncBlockExpr &expr) = 0;
virtual void visit (InlineAsm &expr) = 0;
virtual void visit (LlvmInlineAsm &expr) = 0;
// rust-item.h
virtual void visit (TypeParam &param) = 0;
@@ -164,7 +171,6 @@ public:
// virtual void visit(ExternalItem& item) = 0;
virtual void visit (ExternalTypeItem &type) = 0;
virtual void visit (ExternalStaticItem &item) = 0;
virtual void visit (ExternalFunctionItem &item) = 0;
virtual void visit (ExternBlock &block) = 0;
// rust-macro.h
@@ -229,15 +235,19 @@ public:
virtual void visit (InferredType &type) = 0;
virtual void visit (BareFunctionType &type) = 0;
// special AST nodes for certain builtin macros such as `asm!()`
virtual void visit (FormatArgs &fmt) = 0;
// TODO: rust-cond-compilation.h visiting? not currently used
};
class DefaultASTVisitor : public ASTVisitor
{
public:
virtual void visit_function_params (AST::Function &function);
virtual void visit (AST::Crate &crate);
protected:
virtual void visit (AST::Token &tok) override;
virtual void visit (AST::DelimTokenTree &delim_tok_tree) override;
virtual void visit (AST::AttrInputMetaItemContainer &input) override;
@@ -285,6 +295,8 @@ protected:
virtual void visit (AST::FieldAccessExpr &expr) override;
virtual void visit (AST::ClosureExprInner &expr) override;
virtual void visit (AST::BlockExpr &expr) override;
virtual void visit (AST::AnonConst &expr) override;
virtual void visit (AST::ConstBlock &expr) override;
virtual void visit (AST::ClosureExprInnerTyped &expr) override;
virtual void visit (AST::ContinueExpr &expr) override;
virtual void visit (AST::BreakExpr &expr) override;
@@ -295,6 +307,7 @@ protected:
virtual void visit (AST::RangeFromToInclExpr &expr) override;
virtual void visit (AST::RangeToInclExpr &expr) override;
virtual void visit (AST::ReturnExpr &expr) override;
virtual void visit (AST::BoxExpr &expr) override;
virtual void visit (AST::UnsafeBlockExpr &expr) override;
virtual void visit (AST::LoopExpr &expr) override;
virtual void visit (AST::WhileLoopExpr &expr) override;
@@ -307,6 +320,9 @@ protected:
virtual void visit (AST::MatchExpr &expr) override;
virtual void visit (AST::AwaitExpr &expr) override;
virtual void visit (AST::AsyncBlockExpr &expr) override;
virtual void visit (InlineAsm &expr) override;
virtual void visit (LlvmInlineAsm &expr) override;
virtual void visit (AST::TypeParam &param) override;
virtual void visit (AST::LifetimeWhereClauseItem &item) override;
virtual void visit (AST::TypeBoundWhereClauseItem &item) override;
@@ -335,7 +351,6 @@ protected:
virtual void visit (AST::TraitImpl &impl) override;
virtual void visit (AST::ExternalTypeItem &item) override;
virtual void visit (AST::ExternalStaticItem &item) override;
virtual void visit (AST::ExternalFunctionItem &item) override;
virtual void visit (AST::ExternBlock &block) override;
virtual void visit (AST::MacroMatchFragment &match) override;
virtual void visit (AST::MacroMatchRepetition &match) override;
@@ -390,6 +405,7 @@ protected:
virtual void visit (AST::SelfParam &self) override;
virtual void visit (AST::FunctionParam &param) override;
virtual void visit (AST::VariadicParam &param) override;
virtual void visit (AST::FormatArgs &fmt) override;
template <typename T> void visit (T &node) { node.accept_vis (*this); }
@@ -416,12 +432,12 @@ protected:
virtual void visit (AST::WhereClause &where);
virtual void visit (AST::StructField &field);
virtual void visit (AST::TupleField &field);
virtual void visit (AST::NamedFunctionParam &param);
virtual void visit (AST::MacroRule &rule);
virtual void visit (AST::MacroInvocData &data);
virtual void visit (AST::MacroTranscriber &transcriber);
virtual void visit (AST::StructPatternElements &spe);
virtual void visit (AST::MaybeNamedParam &param);
void visit (AST::Attribute &attribute) {}
template <typename T> void visit_outer_attrs (T &node)
@@ -440,7 +456,7 @@ protected:
class ContextualASTVisitor : public DefaultASTVisitor
{
protected:
enum class Context
enum class Kind
{
FUNCTION,
INHERENT_IMPL,
@@ -449,6 +465,7 @@ protected:
MODULE,
CRATE,
};
using DefaultASTVisitor::visit;
virtual void visit (AST::Crate &crate) override;
@@ -464,11 +481,7 @@ protected:
DefaultASTVisitor::visit (item);
}
std::vector<Context> context;
void push_context (Context ctx) { context.push_back (ctx); }
void pop_context () { context.pop_back (); }
StackedContexts<Kind> ctx;
};
} // namespace AST

View File

@@ -19,6 +19,9 @@ along with GCC; see the file COPYING3. If not see
#include "rust-ast.h"
#include "optional.h"
#include "rust-builtin-ast-nodes.h"
#include "rust-common.h"
#include "rust-expr.h"
#include "rust-system.h"
#include "rust-ast-full.h"
#include "rust-diagnostics.h"
@@ -269,8 +272,8 @@ Attribute::get_traits_to_derive ()
case AST::MetaItem::ItemKind::Word: {
auto word = static_cast<AST::MetaWord *> (meta_item);
// Convert current word to path
current
= make_unique<AST::MetaItemPath> (AST::MetaItemPath (
current = std::make_unique<AST::MetaItemPath> (
AST::MetaItemPath (
AST::SimplePath (word->get_ident ())));
auto path
= static_cast<AST::MetaItemPath *> (current.get ());
@@ -308,7 +311,8 @@ Attribute::get_traits_to_derive ()
// Copy constructor must deep copy attr_input as unique pointer
Attribute::Attribute (Attribute const &other)
: path (other.path), locus (other.locus)
: path (other.path), locus (other.locus),
inner_attribute (other.inner_attribute)
{
// guard to protect from null pointer dereference
if (other.attr_input != nullptr)
@@ -321,6 +325,7 @@ Attribute::operator= (Attribute const &other)
{
path = other.path;
locus = other.locus;
inner_attribute = other.inner_attribute;
// guard to protect from null pointer dereference
if (other.attr_input != nullptr)
attr_input = other.attr_input->clone_attr_input ();
@@ -1060,9 +1065,11 @@ Union::as_string () const
}
Function::Function (Function const &other)
: VisItem (other), qualifiers (other.qualifiers),
function_name (other.function_name), where_clause (other.where_clause),
locus (other.locus), is_default (other.is_default)
: VisItem (other), ExternalItem (other.get_node_id ()),
qualifiers (other.qualifiers), function_name (other.function_name),
where_clause (other.where_clause), locus (other.locus),
has_default (other.has_default),
is_external_function (other.is_external_function)
{
// guard to prevent null dereference (always required)
if (other.return_type != nullptr)
@@ -1093,7 +1100,8 @@ Function::operator= (Function const &other)
// visibility = other.visibility->clone_visibility();
// outer_attrs = other.outer_attrs;
locus = other.locus;
is_default = other.is_default;
has_default = other.has_default;
is_external_function = other.is_external_function;
// guard to prevent null dereference (always required)
if (other.return_type != nullptr)
@@ -1263,6 +1271,18 @@ BlockExpr::as_string () const
return str;
}
std::string
AnonConst::as_string () const
{
return "AnonConst: " + expr->as_string ();
}
std::string
ConstBlock::as_string () const
{
return "ConstBlock: " + expr.as_string ();
}
std::string
TraitImpl::as_string () const
{
@@ -1566,17 +1586,36 @@ BorrowExpr::as_string () const
std::string str ("&");
if (double_borrow)
str += "&";
if (is_mut)
str += "mut ";
if (raw_borrow)
{
str += "raw ";
str += get_is_mut () ? "const " : "mut ";
}
else
{
if (double_borrow)
str += "&";
if (get_is_mut ())
str += "mut ";
}
str += main_or_left_expr->as_string ();
return str;
}
std::string
BoxExpr::as_string () const
{
return "box " + expr->as_string ();
}
void
BoxExpr::accept_vis (ASTVisitor &vis)
{
vis.visit (*this);
}
std::string
ReturnExpr::as_string () const
{
@@ -1604,7 +1643,7 @@ ContinueExpr::as_string () const
std::string str ("continue ");
if (has_label ())
str += label.as_string ();
str += get_label_unchecked ().as_string ();
return str;
}
@@ -2068,7 +2107,7 @@ WhileLoopExpr::as_string () const
if (!has_loop_label ())
str += "none";
else
str += loop_label.as_string ();
str += get_loop_label ().as_string ();
str += "\n Conditional expr: " + condition->as_string ();
@@ -2088,7 +2127,7 @@ WhileLetLoopExpr::as_string () const
if (!has_loop_label ())
str += "none";
else
str += loop_label.as_string ();
str += get_loop_label ().as_string ();
str += "\n Match arm patterns: ";
if (match_arm_patterns.empty ())
@@ -2119,7 +2158,7 @@ LoopExpr::as_string () const
if (!has_loop_label ())
str += "none";
else
str += loop_label.as_string ();
str += get_loop_label ().as_string ();
str += "\n Loop block: " + loop_block->as_string ();
@@ -2156,7 +2195,7 @@ BreakExpr::as_string () const
std::string str ("break ");
if (has_label ())
str += label.as_string () + " ";
str += get_label_unchecked ().as_string () + " ";
if (has_break_expr ())
str += break_expr->as_string ();
@@ -2287,7 +2326,7 @@ std::string
VariadicParam::as_string () const
{
if (has_pattern ())
return get_pattern ()->as_string () + " : ...";
return get_pattern ().as_string () + " : ...";
else
return "...";
}
@@ -2383,11 +2422,11 @@ LifetimeParam::as_string () const
{
std::string str ("LifetimeParam: ");
str += "\n Outer attribute: ";
str += "\n Outer attribute:";
if (!has_outer_attribute ())
str += "none";
else
str += outer_attr.as_string ();
for (auto &attr : outer_attrs)
str += " " + attr.as_string ();
str += "\n Lifetime: " + lifetime.as_string ();
@@ -2458,9 +2497,6 @@ MacroMatchRepetition::as_string () const
std::string
Lifetime::as_string () const
{
if (is_error ())
return "error lifetime";
switch (lifetime_type)
{
case NAMED:
@@ -2479,11 +2515,11 @@ TypeParam::as_string () const
{
std::string str ("TypeParam: ");
str += "\n Outer attribute: ";
str += "\n Outer attribute:";
if (!has_outer_attribute ())
str += "none";
else
str += outer_attr.as_string ();
for (auto &attr : outer_attrs)
str += " " + attr.as_string ();
str += "\n Identifier: " + type_representation.as_string ();
@@ -2518,7 +2554,7 @@ ForLoopExpr::as_string () const
if (!has_loop_label ())
str += "none";
else
str += loop_label.as_string ();
str += get_loop_label ().as_string ();
str += "\n Pattern: " + pattern->as_string ();
@@ -2585,7 +2621,7 @@ ReferenceType::as_string () const
std::string str ("&");
if (has_lifetime ())
str += lifetime.as_string () + " ";
str += get_lifetime ().as_string () + " ";
if (has_mut)
str += "mut ";
@@ -2690,7 +2726,7 @@ ImplTraitTypeOneBound::as_string () const
{
std::string str ("ImplTraitTypeOneBound: \n TraitBound: ");
return str + trait_bound.as_string ();
return str + trait_bound->as_string ();
}
std::string
@@ -2970,85 +3006,6 @@ ExternalStaticItem::as_string () const
return str;
}
std::string
ExternalFunctionItem::as_string () const
{
// outer attributes
std::string str = append_attributes (outer_attrs, OUTER);
// start visibility on new line and with a space
str += "\n" + visibility.as_string () + " ";
str += "fn ";
// add name
str += item_name.as_string ();
// generic params
str += "\n Generic params: ";
if (generic_params.empty ())
{
str += "none";
}
else
{
for (const auto &param : generic_params)
{
// DEBUG: null pointer check
if (param == nullptr)
{
rust_debug (
"something really terrible has gone wrong - null pointer "
"generic param in external function item.");
return "NULL_POINTER_MARK";
}
str += "\n " + param->as_string ();
}
}
// function params
str += "\n Function params: ";
if (function_params.empty ())
{
str += "none";
}
else
{
for (const auto &param : function_params)
str += "\n " + param.as_string ();
}
// add type on new line
str += "\n (return) Type: "
+ (has_return_type () ? return_type->as_string () : "()");
// where clause
str += "\n Where clause: ";
if (has_where_clause ())
str += where_clause.as_string ();
else
str += "none";
return str;
}
std::string
NamedFunctionParam::as_string () const
{
std::string str = append_attributes (outer_attrs, OUTER);
if (has_name ())
str += "\n" + name;
if (is_variadic ())
str += "...";
else
str += "\n Type: " + param_type->as_string ();
return str;
}
std::string
TraitItemConst::as_string () const
{
@@ -3122,7 +3079,7 @@ SelfParam::as_string () const
else if (has_lifetime ())
{
// ref and lifetime
std::string str = "&" + lifetime.as_string () + " ";
std::string str = "&" + get_lifetime ().as_string () + " ";
if (is_mut)
str += "mut ";
@@ -3544,6 +3501,7 @@ AttributeParser::parse_meta_item_inner ()
case STRING_LITERAL:
case BYTE_CHAR_LITERAL:
case BYTE_STRING_LITERAL:
case RAW_STRING_LITERAL:
case INT_LITERAL:
case FLOAT_LITERAL:
case TRUE_LITERAL:
@@ -3826,6 +3784,10 @@ AttributeParser::parse_literal ()
skip_token ();
return Literal (tok->as_string (), Literal::BYTE_STRING,
tok->get_type_hint ());
case RAW_STRING_LITERAL:
skip_token ();
return Literal (tok->as_string (), Literal::RAW_STRING,
tok->get_type_hint ());
case INT_LITERAL:
skip_token ();
return Literal (tok->as_string (), Literal::INT, tok->get_type_hint ());
@@ -4317,7 +4279,7 @@ BlockExpr::normalize_tail_expr ()
if (!stmt.is_semicolon_followed ())
{
expr = std::move (stmt.get_expr ());
expr = stmt.take_expr ();
statements.pop_back ();
}
}
@@ -4562,6 +4524,18 @@ BlockExpr::accept_vis (ASTVisitor &vis)
vis.visit (*this);
}
void
AnonConst::accept_vis (ASTVisitor &vis)
{
vis.visit (*this);
}
void
ConstBlock::accept_vis (ASTVisitor &vis)
{
vis.visit (*this);
}
void
ClosureExprInnerTyped::accept_vis (ASTVisitor &vis)
{
@@ -4694,6 +4668,18 @@ AsyncBlockExpr::accept_vis (ASTVisitor &vis)
vis.visit (*this);
}
void
InlineAsm::accept_vis (ASTVisitor &vis)
{
vis.visit (*this);
}
void
LlvmInlineAsm::accept_vis (ASTVisitor &vis)
{
vis.visit (*this);
}
void
TypeParam::accept_vis (ASTVisitor &vis)
{
@@ -4862,12 +4848,6 @@ ExternalStaticItem::accept_vis (ASTVisitor &vis)
vis.visit (*this);
}
void
ExternalFunctionItem::accept_vis (ASTVisitor &vis)
{
vis.visit (*this);
}
void
ExternBlock::accept_vis (ASTVisitor &vis)
{
@@ -5048,6 +5028,62 @@ MetaWord::accept_vis (ASTVisitor &vis)
vis.visit (*this);
}
void
FormatArgs::accept_vis (ASTVisitor &vis)
{
vis.visit (*this);
}
std::string
FormatArgs::as_string () const
{
// FIXME(Arthur): Improve
return "FormatArgs";
}
location_t
FormatArgs::get_locus () const
{
return loc;
}
bool
FormatArgs::is_expr_without_block () const
{
return false;
}
void
FormatArgs::mark_for_strip ()
{
marked_for_strip = true;
}
bool
FormatArgs::is_marked_for_strip () const
{
return marked_for_strip;
}
std::vector<Attribute> &
FormatArgs::get_outer_attrs ()
{
rust_unreachable ();
}
void FormatArgs::set_outer_attrs (std::vector<Attribute>)
{
rust_unreachable ();
}
Expr *
FormatArgs::clone_expr_impl () const
{
std::cerr << "[ARTHUR] cloning FormatArgs! " << std::endl;
return new FormatArgs (*this);
}
} // namespace AST
std::ostream &

View File

@@ -57,6 +57,11 @@ public:
bool empty () const { return ident.empty (); }
bool operator== (const Identifier &other) const
{
return ident == other.ident;
}
private:
std::string ident;
location_t loc;
@@ -70,16 +75,6 @@ namespace AST {
class ASTVisitor;
using AttrVec = std::vector<Attribute>;
// The available kinds of AST Nodes
enum class Kind
{
UNKNOWN,
MODULE,
MACRO_RULES_DEFINITION,
MACRO_INVOCATION,
IDENTIFIER,
};
class Visitable
{
public:
@@ -87,20 +82,6 @@ public:
virtual void accept_vis (ASTVisitor &vis) = 0;
};
// Abstract base class for all AST elements
class Node : public Visitable
{
public:
/**
* Get the kind of Node this is. This is used to differentiate various AST
* elements with very little overhead when extracting the derived type
* through static casting is not necessary.
*/
// FIXME: Mark this as `= 0` in the future to make sure every node
// implements it
virtual Kind get_ast_kind () const { return Kind::UNKNOWN; }
};
// Delimiter types - used in macros and whatever.
enum DelimType
{
@@ -250,6 +231,7 @@ public:
{
case STRING_LITERAL:
case BYTE_STRING_LITERAL:
case RAW_STRING_LITERAL:
return true;
default:
return false;
@@ -311,6 +293,7 @@ public:
STRING,
BYTE,
BYTE_STRING,
RAW_STRING,
INT,
FLOAT,
BOOL,
@@ -374,7 +357,7 @@ public:
// TODO: put checks in constructor to enforce this rule?
SimplePathSegment (std::string segment_name, location_t locus)
: segment_name (std::move (segment_name)), locus (locus),
node_id (Analysis::Mappings::get ()->get_next_node_id ())
node_id (Analysis::Mappings::get ().get_next_node_id ())
{}
/* Returns whether simple path segment is in an invalid state (currently, if
@@ -420,19 +403,19 @@ class SimplePath
public:
// Constructor
SimplePath (std::vector<SimplePathSegment> path_segments,
bool has_opening_scope_resolution = false,
location_t locus = UNDEF_LOCATION)
explicit SimplePath (std::vector<SimplePathSegment> path_segments,
bool has_opening_scope_resolution = false,
location_t locus = UNDEF_LOCATION)
: opening_scope_resolution (has_opening_scope_resolution),
segments (std::move (path_segments)), locus (locus),
node_id (Analysis::Mappings::get ()->get_next_node_id ())
node_id (Analysis::Mappings::get ().get_next_node_id ())
{}
SimplePath (Identifier ident)
explicit SimplePath (Identifier ident)
: opening_scope_resolution (false),
segments ({SimplePathSegment (ident.as_string (), ident.get_locus ())}),
locus (ident.get_locus ()),
node_id (Analysis::Mappings::get ()->get_next_node_id ())
node_id (Analysis::Mappings::get ().get_next_node_id ())
{}
// Creates an empty SimplePath.
@@ -679,6 +662,9 @@ public:
// Returns whether the attribute is considered an "empty" attribute.
bool is_empty () const { return attr_input == nullptr && path.is_empty (); }
// Returns whether the attribute has no input
bool empty_input () const { return !attr_input; }
location_t get_locus () const { return locus; }
AttrInput &get_attr_input () const { return *attr_input; }
@@ -1037,6 +1023,7 @@ public:
}
DelimType get_delim_type () const { return delim_type; }
location_t get_locus () const { return locus; }
};
/* Forward decl - definition moved to rust-expr.h as it requires LiteralExpr
@@ -1090,7 +1077,7 @@ class MetaListNameValueStr;
/* Base statement abstract class. Note that most "statements" are not allowed
* in top-level module scope - only a subclass of statements called "items"
* are. */
class Stmt : public Node
class Stmt : public Visitable
{
public:
enum class Kind
@@ -1127,7 +1114,7 @@ public:
virtual void add_semicolon () {}
protected:
Stmt () : node_id (Analysis::Mappings::get ()->get_next_node_id ()) {}
Stmt () : node_id (Analysis::Mappings::get ().get_next_node_id ()) {}
// Clone function implementation as pure virtual method
virtual Stmt *clone_stmt_impl () const = 0;
@@ -1139,6 +1126,28 @@ protected:
class Item : public Stmt
{
public:
enum class Kind
{
MacroRulesDefinition,
MacroInvocation,
Module,
ExternCrate,
UseDeclaration,
Function,
TypeAlias,
Struct,
EnumItem,
Enum,
Union,
ConstantItem,
StaticItem,
Trait,
Impl,
ExternBlock,
};
virtual Kind get_item_kind () const = 0;
// Unique pointer custom clone function
std::unique_ptr<Item> clone_item () const
{
@@ -1219,14 +1228,67 @@ public:
{
return outer_attrs;
}
virtual Item::Kind get_item_kind () const override = 0;
};
// forward decl of ExprWithoutBlock
class ExprWithoutBlock;
// Base expression AST node - abstract
class Expr : public Node
class Expr : public Visitable
{
public:
enum class Kind
{
PathInExpression,
QualifiedPathInExpression,
Literal,
Operator,
Grouped,
Array,
ArrayIndex,
Tuple,
TupleIndex,
Struct,
Call,
MethodCall,
FieldAccess,
Closure,
Block,
ConstExpr,
ConstBlock,
Continue,
Break,
Range,
Box,
Return,
UnsafeBlock,
Loop,
If,
IfLet,
Match,
Await,
AsyncBlock,
InlineAsm,
LlvmInlineAsm,
Identifier,
FormatArgs,
MacroInvocation,
Borrow,
Dereference,
ErrorPropagation,
Negation,
ArithmeticOrLogical,
Comparison,
LazyBoolean,
TypeCast,
Assignment,
CompoundAssignment,
};
virtual Kind get_expr_kind () const = 0;
// Unique pointer custom clone function
std::unique_ptr<Expr> clone_expr () const
{
@@ -1264,7 +1326,7 @@ public:
protected:
// Constructor
Expr () : node_id (Analysis::Mappings::get ()->get_next_node_id ()) {}
Expr () : node_id (Analysis::Mappings::get ().get_next_node_id ()) {}
// Clone function implementation as pure virtual method
virtual Expr *clone_expr_impl () const = 0;
@@ -1341,7 +1403,7 @@ public:
outer_attrs = std::move (new_attrs);
}
Kind get_ast_kind () const override { return Kind::IDENTIFIER; }
Expr::Kind get_expr_kind () const override { return Expr::Kind::Identifier; }
protected:
// Clone method implementation
@@ -1360,12 +1422,32 @@ protected:
class Pattern : public Visitable
{
public:
enum class Kind
{
Literal,
Identifier,
Wildcard,
Rest,
Range,
Reference,
Struct,
TupleStruct,
Tuple,
Grouped,
Slice,
Alt,
Path,
MacroInvocation,
};
// Unique pointer custom clone function
std::unique_ptr<Pattern> clone_pattern () const
{
return std::unique_ptr<Pattern> (clone_pattern_impl ());
}
virtual Kind get_pattern_kind () = 0;
// possible virtual methods: is_refutable()
virtual ~Pattern () {}
@@ -1388,7 +1470,7 @@ protected:
class TraitBound;
// Base class for types as represented in AST - abstract
class Type : public Node
class Type : public Visitable
{
public:
// Unique pointer custom clone function
@@ -1417,7 +1499,7 @@ public:
NodeId get_node_id () const { return node_id; }
protected:
Type () : node_id (Analysis::Mappings::get ()->get_next_node_id ()) {}
Type () : node_id (Analysis::Mappings::get ().get_next_node_id ()) {}
// Clone function implementation as pure virtual method
virtual Type *clone_type_impl () const = 0;
@@ -1455,6 +1537,12 @@ protected:
class TypeParamBound : public Visitable
{
public:
enum TypeParamBoundType
{
TRAIT,
LIFETIME
};
virtual ~TypeParamBound () {}
// Unique pointer custom clone function
@@ -1469,6 +1557,8 @@ public:
virtual location_t get_locus () const = 0;
virtual TypeParamBoundType get_bound_type () const = 0;
protected:
// Clone function implementation as pure virtual method
virtual TypeParamBound *clone_type_param_bound_impl () const = 0;
@@ -1499,7 +1589,7 @@ public:
// Constructor
Lifetime (LifetimeType type, std::string name = std::string (),
location_t locus = UNDEF_LOCATION)
: TypeParamBound (Analysis::Mappings::get ()->get_next_node_id ()),
: TypeParamBound (Analysis::Mappings::get ().get_next_node_id ()),
lifetime_type (type), lifetime_name (std::move (name)), locus (locus)
{}
@@ -1509,27 +1599,24 @@ public:
lifetime_name (std::move (name)), locus (locus)
{}
// Creates an "error" lifetime.
static Lifetime error () { return Lifetime (NAMED, ""); }
static Lifetime elided () { return Lifetime (WILDCARD, ""); }
// Returns true if the lifetime is in an error state.
bool is_error () const
{
return lifetime_type == NAMED && lifetime_name.empty ();
}
std::string as_string () const override;
void accept_vis (ASTVisitor &vis) override;
LifetimeType get_lifetime_type () { return lifetime_type; }
LifetimeType get_lifetime_type () const { return lifetime_type; }
location_t get_locus () const override final { return locus; }
std::string get_lifetime_name () const { return lifetime_name; }
TypeParamBoundType get_bound_type () const override
{
return TypeParamBound::TypeParamBoundType::LIFETIME;
}
protected:
/* Use covariance to implement clone function as returning this object
* rather than base */
@@ -1565,10 +1652,10 @@ public:
virtual Kind get_kind () const = 0;
NodeId get_node_id () { return node_id; }
NodeId get_node_id () const { return node_id; }
protected:
GenericParam () : node_id (Analysis::Mappings::get ()->get_next_node_id ()) {}
GenericParam () : node_id (Analysis::Mappings::get ().get_next_node_id ()) {}
GenericParam (NodeId node_id) : node_id (node_id) {}
// Clone function implementation as pure virtual method
@@ -1582,7 +1669,7 @@ class LifetimeParam : public GenericParam
{
Lifetime lifetime;
std::vector<Lifetime> lifetime_bounds;
Attribute outer_attr;
AST::AttrVec outer_attrs;
location_t locus;
public:
@@ -1590,32 +1677,27 @@ public:
Lifetime &get_lifetime () { return lifetime; }
Attribute &get_outer_attribute () { return outer_attr; }
AST::AttrVec &get_outer_attrs () { return outer_attrs; }
// Returns whether the lifetime param has any lifetime bounds.
bool has_lifetime_bounds () const { return !lifetime_bounds.empty (); }
std::vector<Lifetime> &get_lifetime_bounds () { return lifetime_bounds; }
// Returns whether the lifetime param has an outer attribute.
bool has_outer_attribute () const { return !outer_attr.is_empty (); }
// Creates an error state lifetime param.
static LifetimeParam create_error ()
const std::vector<Lifetime> &get_lifetime_bounds () const
{
return LifetimeParam (Lifetime::error (), {}, Attribute::create_empty (),
UNDEF_LOCATION);
return lifetime_bounds;
}
// Returns whether the lifetime param is in an error state.
bool is_error () const { return lifetime.is_error (); }
// Returns whether the lifetime param has an outer attribute.
bool has_outer_attribute () const { return !outer_attrs.empty (); }
// Constructor
LifetimeParam (Lifetime lifetime, std::vector<Lifetime> lifetime_bounds,
Attribute outer_attr, location_t locus)
AST::AttrVec outer_attrs, location_t locus)
: lifetime (std::move (lifetime)),
lifetime_bounds (std::move (lifetime_bounds)),
outer_attr (std::move (outer_attr)), locus (locus)
outer_attrs (std::move (outer_attrs)), locus (locus)
{}
std::string as_string () const override;
@@ -1662,12 +1744,12 @@ class TraitItem : public AssociatedItem
{
protected:
TraitItem (location_t locus)
: node_id (Analysis::Mappings::get ()->get_next_node_id ()),
: node_id (Analysis::Mappings::get ().get_next_node_id ()),
vis (Visibility::create_private ()), locus (locus)
{}
TraitItem (Visibility vis, location_t locus)
: node_id (Analysis::Mappings::get ()->get_next_node_id ()), vis (vis),
: node_id (Analysis::Mappings::get ().get_next_node_id ()), vis (vis),
locus (locus)
{}
@@ -1693,7 +1775,9 @@ public:
class ExternalItem : public Visitable
{
public:
ExternalItem () : node_id (Analysis::Mappings::get ()->get_next_node_id ()) {}
ExternalItem () : node_id (Analysis::Mappings::get ().get_next_node_id ()) {}
ExternalItem (NodeId node_id) : node_id (node_id) {}
virtual ~ExternalItem () {}
@@ -1708,7 +1792,7 @@ public:
virtual void mark_for_strip () = 0;
virtual bool is_marked_for_strip () const = 0;
NodeId get_node_id () const { return node_id; }
virtual NodeId get_node_id () const { return node_id; }
protected:
// Clone function implementation as pure virtual method
@@ -1907,13 +1991,6 @@ public:
return std::move (item);
}
std::unique_ptr<AssociatedItem> take_trait_item ()
{
rust_assert (!is_error ());
return std::unique_ptr<AssociatedItem> (
static_cast<AssociatedItem *> (assoc_item.release ()));
}
std::unique_ptr<ExternalItem> take_external_item ()
{
rust_assert (!is_error ());
@@ -1926,16 +2003,6 @@ public:
return std::move (assoc_item);
}
std::unique_ptr<AssociatedItem> take_impl_item ()
{
return take_assoc_item ();
}
std::unique_ptr<AssociatedItem> take_trait_impl_item ()
{
return take_assoc_item ();
}
std::unique_ptr<Type> take_type ()
{
rust_assert (!is_error ());
@@ -1965,7 +2032,7 @@ public:
Crate (std::vector<std::unique_ptr<Item>> items,
std::vector<Attribute> inner_attrs)
: inner_attrs (std::move (inner_attrs)), items (std::move (items)),
node_id (Analysis::Mappings::get ()->get_next_node_id ())
node_id (Analysis::Mappings::get ().get_next_node_id ())
{}
// Copy constructor with vector clone
@@ -2025,10 +2092,6 @@ public:
}
};
// Base path expression AST node - abstract
class PathExpr : public ExprWithoutBlock
{
};
} // namespace AST
} // namespace Rust
@@ -2041,6 +2104,19 @@ template <> struct less<Rust::Identifier>
return lhs.as_string () < rhs.as_string ();
}
};
template <> struct hash<Rust::Identifier>
{
std::size_t operator() (const Rust::Identifier &k) const
{
using std::hash;
using std::size_t;
using std::string;
return hash<string> () (k.as_string ()) ^ (hash<int> () (k.get_locus ()));
}
};
} // namespace std
#endif

View File

@@ -0,0 +1,231 @@
// Copyright (C) 2024 Free Software Foundation, Inc.
// This file is part of GCC.
// GCC is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 3, or (at your option) any later
// version.
// GCC is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
// for more details.
// You should have received a copy of the GNU General Public License
// along with GCC; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
#ifndef RUST_AST_BUILTIN_NODES_H
#define RUST_AST_BUILTIN_NODES_H
#include "rust-system.h"
#include "line-map.h"
#include "optional.h"
#include "rust-ast.h"
#include "rust-fmt.h"
namespace Rust {
namespace AST {
// Definitions, from rustc's `FormatArgs` AST struct
// https://github.com/rust-lang/rust/blob/1be468815c/compiler/rustc_ast/src/format.rs
//
// format_args!("hello {abc:.xyz$}!!", abc="world");
// └──────────────────────────────────────────────┘
// FormatArgs
//
// format_args!("hello {abc:.xyz$}!!", abc="world");
// └─────────┘
// argument
//
// format_args!("hello {abc:.xyz$}!!", abc="world");
// └───────────────────┘
// template
//
// format_args!("hello {abc:.xyz$}!!", abc="world");
// └────┘└─────────┘└┘
// pieces
//
// format_args!("hello {abc:.xyz$}!!", abc="world");
// └────┘ └┘
// literal pieces
//
// format_args!("hello {abc:.xyz$}!!", abc="world");
// └─────────┘
// placeholder
//
// format_args!("hello {abc:.xyz$}!!", abc="world");
// └─┘ └─┘
// positions (could be names, numbers, empty, or `*`)
// FIXME: Merge with the class below this one?
class FormatArgumentKind
{
public:
enum class Kind
{
Normal,
Named,
Captured,
} kind;
Identifier &get_ident ()
{
rust_assert (kind == Kind::Captured || kind == Kind::Named);
return ident.value ();
}
FormatArgumentKind (Kind kind, tl::optional<Identifier> ident)
: kind (kind), ident (ident)
{}
FormatArgumentKind (const FormatArgumentKind &other)
{
kind = other.kind;
ident = other.ident;
}
FormatArgumentKind operator= (const FormatArgumentKind &other)
{
kind = other.kind;
ident = other.ident;
return *this;
}
private:
tl::optional<Identifier> ident;
};
class FormatArgument
{
public:
static FormatArgument normal (std::unique_ptr<Expr> expr)
{
return FormatArgument (FormatArgumentKind::Kind::Normal, tl::nullopt,
std::move (expr));
}
static FormatArgument named (Identifier ident, std::unique_ptr<Expr> expr)
{
return FormatArgument (FormatArgumentKind::Kind::Named, ident,
std::move (expr));
}
static FormatArgument captured (Identifier ident, std::unique_ptr<Expr> expr)
{
return FormatArgument (FormatArgumentKind::Kind::Captured, ident,
std::move (expr));
}
FormatArgument (const FormatArgument &other)
: kind (other.kind), expr (other.expr->clone_expr ())
{}
FormatArgument operator= (const FormatArgument &other)
{
kind = other.kind;
expr = other.expr->clone_expr ();
return *this;
}
FormatArgumentKind get_kind () const { return kind; }
const Expr &get_expr () const { return *expr; }
private:
FormatArgument (FormatArgumentKind::Kind kind, tl::optional<Identifier> ident,
std::unique_ptr<Expr> expr)
: kind (FormatArgumentKind (kind, ident)), expr (std::move (expr))
{}
FormatArgumentKind kind;
std::unique_ptr<Expr> expr;
};
class FormatArguments
{
public:
FormatArguments () {}
FormatArguments (FormatArguments &&) = default;
FormatArguments (const FormatArguments &other)
{
args = std::vector<FormatArgument> ();
args.reserve (other.args.size ());
for (const auto &arg : other.args)
args.emplace_back (arg);
};
FormatArguments &operator= (const FormatArguments &other) = default;
void push (FormatArgument &&elt) { args.emplace_back (std::move (elt)); }
const FormatArgument at (size_t idx) const { return args.at (idx); }
private:
std::vector<FormatArgument> args;
};
// TODO: Format documentation better
// Having a separate AST node for `format_args!()` expansion allows some
// important optimizations which help reduce generated code a lot. For example,
// turning `format_args!("a {} {} {}", 15, "hey", 'a')` directly into
// `format_args!("a 15 hey a")`, since all arguments are literals. Or,
// flattening imbricated `format_args!()` calls: `format_args!("heyo {}",
// format_args!("result: {}", some_result))` -> `format_args!("heyo result: {}",
// some_result)`
// FIXME: Move to rust-macro.h
class FormatArgs : public Expr
{
public:
enum class Newline
{
Yes,
No
};
FormatArgs (location_t loc, Fmt::Pieces &&template_str,
FormatArguments &&arguments)
: loc (loc), template_pieces (std::move (template_str)),
arguments (std::move (arguments))
{}
FormatArgs (FormatArgs &&other) = default;
FormatArgs (const FormatArgs &other) = default;
FormatArgs &operator= (const FormatArgs &other) = default;
void accept_vis (AST::ASTVisitor &vis) override;
const Fmt::Pieces &get_template () const { return template_pieces; }
const FormatArguments &get_arguments () const { return arguments; }
virtual location_t get_locus () const override;
Expr::Kind get_expr_kind () const override { return Expr::Kind::FormatArgs; }
private:
location_t loc;
// FIXME: This probably needs to be a separate type - it is one in rustc's
// expansion of format_args!(). There is extra handling associated with it.
// we can maybe do that in rust-fmt.cc? in collect_pieces()? like do the
// transformation into something we can handle better
Fmt::Pieces template_pieces;
FormatArguments arguments;
bool marked_for_strip = false;
protected:
virtual std::string as_string () const override;
virtual bool is_expr_without_block () const override;
virtual void mark_for_strip () override;
virtual bool is_marked_for_strip () const override;
virtual std::vector<Attribute> &get_outer_attrs () override;
virtual void set_outer_attrs (std::vector<Attribute>) override;
virtual Expr *clone_expr_impl () const override;
};
} // namespace AST
} // namespace Rust
#endif // ! RUST_AST_BUILTIN_NODES_H

View File

@@ -0,0 +1,137 @@
// Copyright (C) 2024 Free Software Foundation, Inc.
// This file is part of GCC.
// GCC is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 3, or (at your option) any later
// version.
// GCC is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
// for more details.
// You should have received a copy of the GNU General Public License
// along with GCC; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
#include "rust-collect-lang-items.h"
#include "optional.h"
#include "rust-ast-collector.h"
#include "rust-ast-visitor.h"
#include "rust-ast.h"
#include "rust-attribute-values.h"
#include "rust-attributes.h"
#include "rust-hir-map.h"
#include "rust-item.h"
namespace Rust {
namespace AST {
template <typename T>
tl::optional<LangItem::Kind>
get_lang_item_attr (const T &maybe_lang_item)
{
for (const auto &attr : maybe_lang_item.get_outer_attrs ())
{
const auto &str_path = attr.get_path ().as_string ();
if (!Analysis::Attributes::is_known (str_path))
{
rust_error_at (attr.get_locus (), "unknown attribute %qs",
str_path.c_str ());
continue;
}
bool is_lang_item = str_path == Values::Attributes::LANG
&& attr.has_attr_input ()
&& attr.get_attr_input ().get_attr_input_type ()
== AST::AttrInput::AttrInputType::LITERAL;
if (is_lang_item)
{
auto &literal
= static_cast<AST::AttrInputLiteral &> (attr.get_attr_input ());
const auto &lang_item_type_str = literal.get_literal ().as_string ();
return LangItem::Parse (lang_item_type_str);
}
}
return tl::nullopt;
}
template <typename T>
void
CollectLangItems::maybe_add_lang_item (const T &item)
{
if (auto lang_item = get_lang_item_attr (item))
mappings.insert_lang_item_node (lang_item.value (), item.get_node_id ());
}
void
CollectLangItems::visit (AST::Trait &item)
{
maybe_add_lang_item (item);
DefaultASTVisitor::visit (item);
}
void
CollectLangItems::visit (AST::TraitItemType &item)
{
maybe_add_lang_item (item);
DefaultASTVisitor::visit (item);
}
void
CollectLangItems::visit (AST::Function &item)
{
maybe_add_lang_item (item);
DefaultASTVisitor::visit (item);
}
void
CollectLangItems::visit (AST::StructStruct &item)
{
maybe_add_lang_item (item);
DefaultASTVisitor::visit (item);
}
void
CollectLangItems::visit (AST::EnumItem &item)
{
maybe_add_lang_item (item);
DefaultASTVisitor::visit (item);
}
void
CollectLangItems::visit (AST::EnumItemTuple &item)
{
maybe_add_lang_item (item);
DefaultASTVisitor::visit (item);
}
void
CollectLangItems::visit (AST::EnumItemStruct &item)
{
maybe_add_lang_item (item);
DefaultASTVisitor::visit (item);
}
void
CollectLangItems::visit (AST::EnumItemDiscriminant &item)
{
maybe_add_lang_item (item);
DefaultASTVisitor::visit (item);
}
} // namespace AST
} // namespace Rust

View File

@@ -0,0 +1,64 @@
// Copyright (C) 2024 Free Software Foundation, Inc.
// This file is part of GCC.
// GCC is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 3, or (at your option) any later
// version.
// GCC is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
// for more details.
// You should have received a copy of the GNU General Public License
// along with GCC; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
#ifndef RUST_COLLECT_LANG_ITEMS_H
#define RUST_COLLECT_LANG_ITEMS_H
#include "rust-ast-visitor.h"
#include "rust-ast.h"
#include "rust-hir-map.h"
#include "rust-item.h"
namespace Rust {
namespace AST {
// This class collects lang items ahead of lowering, as they are now needed for
// some parts of name resolution
class CollectLangItems : public DefaultASTVisitor
{
public:
CollectLangItems () : mappings (Analysis::Mappings::get ()){};
void go (AST::Crate &crate) { DefaultASTVisitor::visit (crate); }
Analysis::Mappings &mappings;
// We must implement visitors for all constructs that could be lang items.
// Lang items can be traits, but also enums, and even enum variants.
//
// https://github.com/rust-lang/rust/blob/master/compiler/rustc_hir/src/lang_items.rs
using DefaultASTVisitor::visit;
void visit (AST::Trait &item) override;
void visit (AST::TraitItemType &item) override;
void visit (AST::Function &item) override;
void visit (AST::StructStruct &item) override;
void visit (AST::EnumItem &item) override;
void visit (AST::EnumItemTuple &item) override;
void visit (AST::EnumItemStruct &item) override;
void visit (AST::EnumItemDiscriminant &item) override;
private:
template <typename T> void maybe_add_lang_item (const T &item);
};
} // namespace AST
} // namespace Rust
#endif // ! RUST_COLLECT_LANG_ITEMS_H

View File

@@ -0,0 +1,518 @@
// Copyright (C) 2025 Free Software Foundation, Inc.
// This file is part of GCC.
// GCC is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 3, or (at your option) any later
// version.
// GCC is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
// for more details.
// You should have received a copy of the GNU General Public License
// along with GCC; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
#include "rust-desugar-apit.h"
#include "rust-ast.h"
#include "rust-type.h"
namespace Rust {
namespace AST {
class DesugarApitType : public DefaultASTVisitor
{
using DefaultASTVisitor::visit;
public:
static std::pair<AST::Type *, std::vector<std::unique_ptr<GenericParam>>>
Desugar (AST::Type &type)
{
DesugarApitType visitor (&type);
type.accept_vis (visitor);
rust_assert (visitor.translated != nullptr);
return std::make_pair (visitor.translated,
std::move (visitor.implicit_generic_params));
}
// Generate a unique impl trait parameter name
static Identifier get_impl_name ()
{
static size_t counter = 0;
return Identifier ("Impl_" + std::to_string (counter++));
}
// these can hold other types
void visit (AST::TupleType &tuple) override
{
for (auto &elem : tuple.get_elems ())
{
auto &type = *elem.get ();
auto desugar = Desugar (type);
auto tt = desugar.first;
auto &implicit_generics = desugar.second;
if (implicit_generics.empty ())
continue;
if (tt != elem.get ())
elem = std::unique_ptr<Type> (tt);
for (auto &implicit_generic : implicit_generics)
implicit_generic_params.push_back (std::move (implicit_generic));
}
}
void visit (AST::ArrayType &type) override
{
auto &element_type = type.get_element_type ();
auto desugar = Desugar (*element_type);
auto tt = desugar.first;
auto &implicit_generics = desugar.second;
if (implicit_generics.empty ())
return;
if (tt != element_type.get ())
element_type = std::unique_ptr<AST::Type> (tt);
for (auto &implicit_generic : implicit_generics)
implicit_generic_params.push_back (std::move (implicit_generic));
}
void visit (AST::ReferenceType &type) override
{
// Get a reference to the current type for in-place modification
auto &referenced_type = type.get_type_referenced ();
auto desugar = Desugar (referenced_type);
auto tt = desugar.first;
auto &implicit_generics = desugar.second;
if (implicit_generics.empty ())
return;
// Update the reference type's contents rather than creating a new one
if (&referenced_type != tt)
{
std::unique_ptr<AST::TypeNoBounds> new_type_no_bounds (
static_cast<AST::TypeNoBounds *> (tt));
type.get_type_ptr () = std::move (new_type_no_bounds);
}
// Collect all the implicit generic parameters we found
for (auto &implicit_generic : implicit_generics)
implicit_generic_params.push_back (std::move (implicit_generic));
}
void visit (AST::RawPointerType &type) override
{
auto &pointed_type = type.get_type_pointed_to ();
auto desugar = Desugar (pointed_type);
auto tt = desugar.first;
auto &implicit_generics = desugar.second;
if (implicit_generics.empty ())
return;
// Update the pointer's inner type directly using the new accessor
if (&pointed_type != tt)
{
std::unique_ptr<AST::TypeNoBounds> new_type_no_bounds (
static_cast<AST::TypeNoBounds *> (tt));
type.get_type_ptr () = std::move (new_type_no_bounds);
}
// Collect all the implicit generic parameters we found
for (auto &implicit_generic : implicit_generics)
implicit_generic_params.push_back (std::move (implicit_generic));
}
void visit (AST::SliceType &type) override
{
auto &element_type = type.get_elem_type ();
auto desugar = Desugar (element_type);
auto tt = desugar.first;
auto &implicit_generics = desugar.second;
if (implicit_generics.empty ())
return;
if (&element_type != tt)
{
std::unique_ptr<AST::Type> new_elem_type (tt);
type.get_elem_type_ptr () = std::move (new_elem_type);
}
// Collect all the implicit generic parameters we found
for (auto &implicit_generic : implicit_generics)
implicit_generic_params.push_back (std::move (implicit_generic));
}
void visit (AST::ParenthesisedType &type) override
{
auto &inner_type_ptr = type.get_type_in_parens ();
auto desugar = Desugar (*inner_type_ptr);
auto tt = desugar.first;
auto &implicit_generics = desugar.second;
if (implicit_generics.empty ())
return;
if (inner_type_ptr.get () != tt)
{
std::unique_ptr<AST::Type> new_inner_type (tt);
inner_type_ptr = std::move (new_inner_type);
}
// Collect all the implicit generic parameters we found
for (auto &implicit_generic : implicit_generics)
implicit_generic_params.push_back (std::move (implicit_generic));
}
// this is where the desugar happens
void visit (AST::ImplTraitType &type) override
{
// Generate a unique name using the static method
auto ident = get_impl_name ();
// Create a type path for the new generic parameter
// Create a SimplePathSegment with the identifier string
auto simple_seg = SimplePathSegment (ident.as_string (), type.get_locus ());
// Create a vector of SimplePathSegments for SimplePath constructor
std::vector<SimplePathSegment> simple_segs = {simple_seg};
// Create a SimplePath
auto simple_path = SimplePath (simple_segs, false, type.get_locus ());
// Convert to TypePath by creating path segments
std::vector<std::unique_ptr<TypePathSegment>> segments;
segments.push_back (std::unique_ptr<TypePathSegment> (new TypePathSegment (
PathIdentSegment (ident.as_string (), type.get_locus ()), false,
type.get_locus ())));
// Create TypePath from segments
auto type_path
= new TypePath (std::move (segments), type.get_locus (), false);
// Convert bounds from impl trait to generic parameter bounds
std::vector<std::unique_ptr<TypeParamBound>> bounds;
for (auto &bound : type.get_type_param_bounds ())
bounds.push_back (bound->clone_type_param_bound ());
// Create the new generic parameter
auto generic_param = std::unique_ptr<TypeParam> (
new TypeParam (ident, type.get_locus (), std::move (bounds), nullptr, {},
true /*from impl trait*/));
// Store the generic parameter to be added to the function signature
implicit_generic_params.push_back (std::move (generic_param));
// Replace impl trait with the new type parameter
translated = type_path;
}
void visit (AST::ImplTraitTypeOneBound &type) override
{
// Generate a unique name using the static method
auto ident = get_impl_name ();
// Create a type path for the new generic parameter
// Create a SimplePathSegment with the identifier string
auto simple_seg = SimplePathSegment (ident.as_string (), type.get_locus ());
// Create a vector of SimplePathSegments for SimplePath constructor
std::vector<SimplePathSegment> simple_segs = {simple_seg};
// Create a SimplePath
auto simple_path = SimplePath (simple_segs, false, type.get_locus ());
// Convert to TypePath by creating path segments
std::vector<std::unique_ptr<TypePathSegment>> segments;
segments.push_back (std::unique_ptr<TypePathSegment> (new TypePathSegment (
PathIdentSegment (ident.as_string (), type.get_locus ()), false,
type.get_locus ())));
// Create TypePath from segments
auto type_path
= new TypePath (std::move (segments), type.get_locus (), false);
// Convert the bound to a generic parameter bound
std::vector<std::unique_ptr<TypeParamBound>> bounds;
bounds.push_back (std::move (type.get_trait_bound ()));
// Create the new generic parameter
auto generic_param = std::unique_ptr<TypeParam> (
new TypeParam (ident, type.get_locus (), std::move (bounds), nullptr, {},
true /*from impl trait*/));
// Store the generic parameter to be added to the function signature
implicit_generic_params.push_back (std::move (generic_param));
// Replace impl trait with the new type parameter
translated = type_path;
}
private:
DesugarApitType (AST::Type *base)
: translated (base), implicit_generic_params ()
{}
AST::Type *translated;
std::vector<std::unique_ptr<GenericParam>> implicit_generic_params;
};
// ---------
class ApitBoundProcessor
{
public:
ApitBoundProcessor (
WhereClause &where_clause,
std::vector<std::unique_ptr<GenericParam>> &generic_params)
: where_clause (where_clause), generic_params (generic_params)
{}
void go (std::vector<std::unique_ptr<GenericParam>> &implicit_generics)
{
// some desugars are more complex so imagine this case
//
// pub fn foo(_value: impl Bar<Baz = impl Foo>) -> i32 {
// 15
// }
//
// this needs to become:
//
// pub fn foo<T, U>(_value: T) -> i32
// where
// T: Bar<Baz = U>,
// U: Foo,
// {
// 15
// }
//
// so we need to walk all the implicit generics and the trait bounds paths
// for more generics
for (auto &implicit_generic : implicit_generics)
{
switch (implicit_generic->get_kind ())
{
case GenericParam::Kind::Type: {
TypeParam &p
= *static_cast<TypeParam *> (implicit_generic.get ());
process_type_param (p);
generic_params.push_back (std::move (implicit_generic));
for (auto &synth : synthetic_params)
generic_params.push_back (std::move (synth));
synthetic_params.clear ();
}
break;
default:
generic_params.push_back (std::move (implicit_generic));
break;
}
}
}
private:
void process_type_param (TypeParam &p)
{
auto &bounds = p.get_type_param_bounds ();
std::vector<size_t> bounds_to_remove;
for (size_t i = 0; i < bounds.size (); i++)
{
auto &tb = bounds[i];
switch (tb->get_bound_type ())
{
case TypeParamBound::TypeParamBoundType::TRAIT: {
TraitBound &ttb = *static_cast<TraitBound *> (tb.get ());
TypePath &path = ttb.get_type_path ();
bool deusgared = process_type_path (p, ttb, path);
if (deusgared)
bounds_to_remove.push_back (i);
}
default:
break;
}
}
for (auto it = bounds_to_remove.rbegin (); it != bounds_to_remove.rend ();
++it)
bounds.erase (bounds.begin () + *it);
}
bool process_type_path (TypeParam &p, TraitBound &parent, TypePath &path)
{
bool desugared = false;
for (auto &segment : path.get_segments ())
{
switch (segment->get_type ())
{
case TypePathSegment::SegmentType::GENERIC: {
TypePathSegmentGeneric &seg
= *static_cast<TypePathSegmentGeneric *> (segment.get ());
desugared |= process_generic_segment (p, parent, path, seg);
}
default:
break;
}
}
return desugared;
}
bool process_generic_segment (TypeParam &p, TraitBound &parent,
TypePath &path, TypePathSegmentGeneric &seg)
{
// we need to look for any impl types as default arguments in any generics
// and remove this index from the generic arguments by using a where
// constraint instead
std::vector<std::unique_ptr<WhereClauseItem>> new_clauses;
GenericArgs &generic_args = seg.get_generic_args ();
std::vector<std::reference_wrapper<const GenericArgsBinding>>
bindings_desugared;
std::vector<GenericArgsBinding> &bindings
= generic_args.get_binding_args ();
for (auto &generic : bindings)
{
auto &t = generic.get_type ();
auto translated = DesugarApitType::Desugar (t);
auto tt = translated.first;
auto &implicit_generics = translated.second;
if (implicit_generics.empty ())
continue;
if (tt != &t)
{
bindings_desugared.push_back (generic);
generic.get_type_ptr () = std::unique_ptr<Type> (tt);
}
for (auto &implicit_generic : implicit_generics)
{
switch (implicit_generic->get_kind ())
{
case GenericParam::Kind::Type: {
TypeParam &tp
= *static_cast<TypeParam *> (implicit_generic.get ());
std::vector<std::unique_ptr<TypeParamBound>>
type_param_bounds;
for (auto &b : tp.get_type_param_bounds ())
type_param_bounds.push_back (std::move (b));
tp.get_type_param_bounds ().clear ();
// add synthetic parameter for this
synthetic_params.push_back (std::move (implicit_generic));
auto bound_type_path
= get_type_for_identifier (tp.get_type_representation ());
auto clause = new TypeBoundWhereClauseItem (
{}, std::move (bound_type_path),
std::move (type_param_bounds), tp.get_locus ());
std::unique_ptr<WhereClauseItem> clause_item
= std::unique_ptr<WhereClauseItem> (clause);
new_clauses.push_back (std::move (clause_item));
}
break;
default:
synthetic_params.push_back (std::move (implicit_generic));
break;
}
}
}
std::vector<std::unique_ptr<TypeParamBound>> type_param_bounds;
auto bound = std::unique_ptr<TypeParamBound> (new TraitBound (parent));
type_param_bounds.push_back (std::move (bound));
auto parent_type_path
= get_type_for_identifier (p.get_type_representation ());
auto clause
= new TypeBoundWhereClauseItem ({}, std::move (parent_type_path),
std::move (type_param_bounds),
parent.get_locus ());
std::unique_ptr<WhereClauseItem> clause_item
= std::unique_ptr<WhereClauseItem> (clause);
where_clause.get_items ().push_back (std::move (clause_item));
for (auto &where_item : new_clauses)
where_clause.get_items ().push_back (std::move (where_item));
return !bindings_desugared.empty ();
}
static std::unique_ptr<Type> get_type_for_identifier (const Identifier &ident)
{
auto simple_seg
= SimplePathSegment (ident.as_string (), ident.get_locus ());
std::vector<SimplePathSegment> simple_segs = {simple_seg};
auto simple_path = SimplePath (simple_segs, false, ident.get_locus ());
std::vector<std::unique_ptr<TypePathSegment>> segments;
segments.push_back (std::unique_ptr<TypePathSegment> (new TypePathSegment (
PathIdentSegment (ident.as_string (), ident.get_locus ()), false,
ident.get_locus ())));
auto type_path = new TypePath (std::move (segments), ident.get_locus ());
return std::unique_ptr<Type> (type_path);
}
private:
WhereClause &where_clause;
std::vector<std::unique_ptr<GenericParam>> &generic_params;
// mutates
std::vector<std::unique_ptr<GenericParam>> synthetic_params;
};
// ---------
DesugarApit::DesugarApit () {}
void
DesugarApit::go (AST::Crate &crate)
{
DefaultASTVisitor::visit (crate);
}
void
DesugarApit::visit (AST::Function &function)
{
if (!function.has_function_params ())
return;
auto &fn_params = function.get_function_params ();
for (auto &param : fn_params)
{
if (param->is_variadic () || param->is_self ())
continue;
auto *p = param.get ();
auto &fp = *static_cast<AST::FunctionParam *> (p);
auto &type = fp.get_type ();
auto translated = DesugarApitType::Desugar (type);
auto tt = translated.first;
auto &implicit_generics = translated.second;
if (implicit_generics.empty ())
continue;
if (fp.get_type_ptr ().get () != tt)
{
fp.get_type_ptr () = std::unique_ptr<AST::Type> (tt);
}
ApitBoundProcessor processor (function.get_where_clause (),
function.get_generic_params ());
processor.go (implicit_generics);
}
}
} // namespace AST
} // namespace Rust

View File

@@ -0,0 +1,42 @@
// Copyright (C) 2025 Free Software Foundation, Inc.
// This file is part of GCC.
// GCC is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 3, or (at your option) any later
// version.
// GCC is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
// for more details.
// You should have received a copy of the GNU General Public License
// along with GCC; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
#ifndef RUST_DESUGAR_APIT_H
#define RUST_DESUGAR_APIT_H
#include "rust-ast-visitor.h"
namespace Rust {
namespace AST {
class DesugarApit : public DefaultASTVisitor
{
using DefaultASTVisitor::visit;
public:
DesugarApit ();
void go (AST::Crate &);
private:
void visit (AST::Function &) override;
};
} // namespace AST
} // namespace Rust
#endif // ! RUST_DESUGAR_APIT_H

View File

@@ -0,0 +1,204 @@
// Copyright (C) 2025 Free Software Foundation, Inc.
// This file is part of GCC.
// GCC is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 3, or (at your option) any later
// version.
// GCC is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
// for more details.
// You should have received a copy of the GNU General Public License
// along with GCC; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
#include "rust-desugar-for-loops.h"
#include "rust-ast-visitor.h"
#include "rust-ast.h"
#include "rust-hir-map.h"
#include "rust-path.h"
#include "rust-pattern.h"
#include "rust-stmt.h"
#include "rust-expr.h"
#include "rust-ast-builder.h"
namespace Rust {
namespace AST {
DesugarForLoops::DesugarForLoops () {}
void
DesugarForLoops::go (AST::Crate &crate)
{
DefaultASTVisitor::visit (crate);
}
static void
replace_for_loop (std::unique_ptr<Expr> &for_loop,
std::unique_ptr<Expr> &&expanded)
{
for_loop = std::move (expanded);
}
MatchArm
DesugarForLoops::DesugarCtx::make_match_arm (std::unique_ptr<Pattern> &&path)
{
auto patterns = std::vector<std::unique_ptr<Pattern>> ();
patterns.emplace_back (std::move (path));
return MatchArm (std::move (patterns), loc);
}
MatchCase
DesugarForLoops::DesugarCtx::make_break_arm ()
{
auto arm = make_match_arm (std::unique_ptr<Pattern> (new PathInExpression (
builder.path_in_expression (LangItem::Kind::OPTION_NONE))));
auto break_expr
= std::unique_ptr<Expr> (new BreakExpr (tl::nullopt, nullptr, {}, loc));
return MatchCase (std::move (arm), std::move (break_expr));
}
MatchCase
DesugarForLoops::DesugarCtx::make_continue_arm ()
{
auto val = builder.identifier_pattern (DesugarCtx::continue_pattern_id);
auto patterns = std::vector<std::unique_ptr<Pattern>> ();
patterns.emplace_back (std::move (val));
auto pattern_item = std::unique_ptr<TupleStructItems> (
new TupleStructItemsNoRange (std::move (patterns)));
auto pattern = std::unique_ptr<Pattern> (new TupleStructPattern (
builder.path_in_expression (LangItem::Kind::OPTION_SOME),
std::move (pattern_item)));
auto val_arm = make_match_arm (std::move (pattern));
auto next = builder.identifier (DesugarCtx::next_value_id);
auto assignment = std::unique_ptr<Expr> (
new AssignmentExpr (std::move (next),
builder.identifier (DesugarCtx::continue_pattern_id),
{}, loc));
return MatchCase (std::move (val_arm), std::move (assignment));
}
std::unique_ptr<Stmt>
DesugarForLoops::DesugarCtx::statementify (std::unique_ptr<Expr> &&expr)
{
return std::unique_ptr<Stmt> (new ExprStmt (std::move (expr), loc, true));
}
std::unique_ptr<Expr>
DesugarForLoops::desugar (AST::ForLoopExpr &expr)
{
auto ctx = DesugarCtx (expr.get_locus ());
auto into_iter = std::make_unique<PathInExpression> (
ctx.builder.path_in_expression (LangItem::Kind::INTOITER_INTOITER));
auto next = std::make_unique<PathInExpression> (
ctx.builder.path_in_expression (LangItem::Kind::ITERATOR_NEXT));
// IntoIterator::into_iter(<head>)
auto into_iter_call
= ctx.builder.call (std::move (into_iter),
expr.get_iterator_expr ().clone_expr ());
// Iterator::next(iter)
auto next_call = ctx.builder.call (
std::move (next),
ctx.builder.ref (ctx.builder.identifier (DesugarCtx::iter_id), true));
// None => break,
auto break_arm = ctx.make_break_arm ();
// Some(val) => __next = val; },
auto continue_arm = ctx.make_continue_arm ();
// match <next_call> {
// <continue_arm>
// <break_arm>
// }
auto match_next
= ctx.builder.match (std::move (next_call),
{std::move (continue_arm), std::move (break_arm)});
// let mut __next;
auto let_next = ctx.builder.let (
ctx.builder.identifier_pattern (DesugarCtx::next_value_id, true));
// let <pattern> = __next;
auto let_pat
= ctx.builder.let (expr.get_pattern ().clone_pattern (), nullptr,
ctx.builder.identifier (DesugarCtx::next_value_id));
auto loop_stmts = std::vector<std::unique_ptr<Stmt>> ();
loop_stmts.emplace_back (std::move (let_next));
loop_stmts.emplace_back (ctx.statementify (std::move (match_next)));
loop_stmts.emplace_back (std::move (let_pat));
loop_stmts.emplace_back (
ctx.statementify (expr.get_loop_block ().clone_expr ()));
// loop {
// <let_next>;
// <match_next>;
// <let_pat>;
//
// <body>;
// }
auto loop = ctx.builder.loop (std::move (loop_stmts));
auto mut_iter_pattern
= ctx.builder.identifier_pattern (DesugarCtx::iter_id, true);
auto match_iter
= ctx.builder.match (std::move (into_iter_call),
{ctx.builder.match_case (std::move (mut_iter_pattern),
std::move (loop))});
auto let_result
= ctx.builder.let (ctx.builder.identifier_pattern (DesugarCtx::result_id),
nullptr, std::move (match_iter));
auto result_return = ctx.builder.identifier (DesugarCtx::result_id);
return ctx.builder.block (std::move (let_result), std::move (result_return));
}
void
DesugarForLoops::maybe_desugar_expr (std::unique_ptr<Expr> &expr)
{
if (expr->get_expr_kind () == AST::Expr::Kind::Loop)
{
auto &loop = static_cast<AST::BaseLoopExpr &> (*expr);
if (loop.get_loop_kind () == AST::BaseLoopExpr::Kind::For)
{
auto &for_loop = static_cast<AST::ForLoopExpr &> (loop);
auto desugared = desugar (for_loop);
replace_for_loop (expr, std::move (desugared));
}
}
}
void
DesugarForLoops::visit (AST::BlockExpr &block)
{
for (auto &stmt : block.get_statements ())
if (stmt->get_stmt_kind () == AST::Stmt::Kind::Expr)
maybe_desugar_expr (static_cast<AST::ExprStmt &> (*stmt).get_expr_ptr ());
if (block.has_tail_expr ())
maybe_desugar_expr (block.get_tail_expr_ptr ());
DefaultASTVisitor::visit (block);
}
} // namespace AST
} // namespace Rust

View File

@@ -0,0 +1,108 @@
// Copyright (C) 2025 Free Software Foundation, Inc.
// This file is part of GCC.
// GCC is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 3, or (at your option) any later
// version.
// GCC is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
// for more details.
// You should have received a copy of the GNU General Public License
// along with GCC; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
#ifndef RUST_DESUGAR_FOR_LOOPS_H
#define RUST_DESUGAR_FOR_LOOPS_H
#include "rust-ast-builder.h"
#include "rust-ast-visitor.h"
#include "rust-expr.h"
namespace Rust {
namespace AST {
// Desugar for-loops into a set of other AST nodes. The desugar is of the
// following form:
//
// ```
// for <pat> in <head> <body>
// ```
//
// becomes:
//
// ```
// {
// let result = match ::std::iter::IntoIterator::into_iter(<head>) {
// mut iter => {
// loop {
// let mut __next;
// match ::std::iter::Iterator::next(&mut iter) {
// ::std::option::Option::Some(val) => __next = val,
// ::std::option::Option::None => break
// };
// let <pat> = __next;
//
// <body>;
// }
// }
// };
// result
// }
// ```
//
// NOTE: In a perfect world, this would be an immutable visitor which would take
// ownership of the AST node and return a new one, instead of mutating this one
// in place. Nevertheless, this isn't Rust, and doing immutable visitors in C++
// sucks, and the world isn't perfect, so we are impure and sad.
//
// NOTE: This class could eventually be removed in favor of
// an HIR desugar. This would avoid mutating the AST and would be cleaner.
// However, it requires multiple changes in the way we do typechecking and name
// resolution, as this desugar creates new bindings. Because of this, these new
// bindings need to be inserted into the name-resolution context outside of the
// name resolution pass, which is difficult. Those bindings are needed because
// of the way the typechecker is currently structured, where it will fetch name
// resolution information in order to typecheck paths - which technically isn't
// necessary.
class DesugarForLoops : public DefaultASTVisitor
{
using DefaultASTVisitor::visit;
public:
DesugarForLoops ();
void go (AST::Crate &);
private:
struct DesugarCtx
{
DesugarCtx (location_t loc) : builder (Builder (loc)), loc (loc) {}
Builder builder;
location_t loc;
MatchArm make_match_arm (std::unique_ptr<Pattern> &&pattern);
MatchCase make_break_arm ();
MatchCase make_continue_arm ();
std::unique_ptr<Stmt> statementify (std::unique_ptr<Expr> &&expr);
constexpr static const char *continue_pattern_id = "#val";
constexpr static const char *next_value_id = "#__next";
constexpr static const char *iter_id = "#iter";
constexpr static const char *result_id = "#result";
};
std::unique_ptr<Expr> desugar (AST::ForLoopExpr &expr);
void maybe_desugar_expr (std::unique_ptr<Expr> &expr);
void visit (AST::BlockExpr &) override;
};
} // namespace AST
} // namespace Rust
#endif // ! RUST_DESUGAR_FOR_LOOPS_H

View File

@@ -0,0 +1,167 @@
// Copyright (C) 2025 Free Software Foundation, Inc.
// This file is part of GCC.
// GCC is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 3, or (at your option) any later
// version.
// GCC is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
// for more details.
// You should have received a copy of the GNU General Public License
// along with GCC; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
#include "rust-desugar-question-mark.h"
#include "rust-ast-builder.h"
#include "rust-ast-visitor.h"
namespace Rust {
namespace AST {
DesugarQuestionMark::DesugarQuestionMark () {}
void
DesugarQuestionMark::go (AST::Crate &crate)
{
DesugarQuestionMark::visit (crate);
}
void
DesugarQuestionMark::visit (ExprStmt &stmt)
{
if (stmt.get_expr ().get_expr_kind () == Expr::Kind::ErrorPropagation)
desugar_and_replace (stmt.get_expr_ptr ());
DefaultASTVisitor::visit (stmt);
}
void
DesugarQuestionMark::visit (CallExpr &call)
{
if (call.get_function_expr ().get_expr_kind ()
== Expr::Kind::ErrorPropagation)
desugar_and_replace (call.get_function_expr_ptr ());
for (auto &arg : call.get_params ())
if (arg->get_expr_kind () == Expr::Kind::ErrorPropagation)
desugar_and_replace (arg);
DefaultASTVisitor::visit (call);
}
void
DesugarQuestionMark::visit (LetStmt &stmt)
{
if (stmt.has_init_expr ()
&& stmt.get_init_expr ().get_expr_kind () == Expr::Kind::ErrorPropagation)
desugar_and_replace (stmt.get_init_expr_ptr ());
DefaultASTVisitor::visit (stmt);
}
MatchArm
make_match_arm (std::unique_ptr<Pattern> &&pattern)
{
auto loc = pattern->get_locus ();
auto patterns = std::vector<std::unique_ptr<Pattern>> ();
patterns.emplace_back (std::move (pattern));
return MatchArm (std::move (patterns), loc);
}
MatchCase
ok_case (Builder &builder)
{
auto val = builder.identifier_pattern ("val");
auto patterns = std::vector<std::unique_ptr<Pattern>> ();
patterns.emplace_back (std::move (val));
auto pattern_item = std::unique_ptr<TupleStructItems> (
new TupleStructItemsNoRange (std::move (patterns)));
auto pattern = std::unique_ptr<Pattern> (new TupleStructPattern (
builder.path_in_expression (LangItem::Kind::RESULT_OK),
std::move (pattern_item)));
auto arm = make_match_arm (std::move (pattern));
auto ret_val = builder.identifier ("val");
return MatchCase (std::move (arm), std::move (ret_val));
}
MatchCase
err_case (Builder &builder)
{
auto val = builder.identifier_pattern ("err");
auto patterns = std::vector<std::unique_ptr<Pattern>> ();
patterns.emplace_back (std::move (val));
auto pattern_item = std::unique_ptr<TupleStructItems> (
new TupleStructItemsNoRange (std::move (patterns)));
auto pattern = std::unique_ptr<Pattern> (new TupleStructPattern (
builder.path_in_expression (LangItem::Kind::RESULT_ERR),
std::move (pattern_item)));
auto arm = make_match_arm (std::move (pattern));
auto try_from_err = std::make_unique<PathInExpression> (
builder.path_in_expression (LangItem::Kind::TRY_FROM_ERROR));
auto from_from = std::make_unique<PathInExpression> (
builder.path_in_expression (LangItem::Kind::FROM_FROM));
auto early_return = builder.return_expr (
builder.call (std::move (try_from_err),
builder.call (std::move (from_from),
builder.identifier ("err"))));
return MatchCase (std::move (arm), std::move (early_return));
}
std::unique_ptr<Expr>
DesugarQuestionMark::desugar (ErrorPropagationExpr &expr)
{
auto builder = Builder (expr.get_locus ());
// Try::into_result(<expr>)
auto try_into = std::make_unique<PathInExpression> (
builder.path_in_expression (LangItem::Kind::TRY_INTO_RESULT));
auto call = builder.call (std::move (try_into),
expr.get_propagating_expr ().clone_expr ());
// Ok(val) => val,
auto ok_match_case = ok_case (builder);
// Err(err) => return Try::from_error(From::from(err)),
auto err_match_case = err_case (builder);
auto cases = std::vector<MatchCase> ();
cases.emplace_back (ok_match_case);
cases.emplace_back (err_match_case);
// match <call> {
// <ok_arm>
// <err_arm>
// }
return std::unique_ptr<MatchExpr> (new MatchExpr (std::move (call),
std::move (cases), {}, {},
expr.get_locus ()));
}
void
DesugarQuestionMark::desugar_and_replace (std::unique_ptr<Expr> &ptr)
{
auto original = static_cast<ErrorPropagationExpr &> (*ptr);
auto desugared = desugar (original);
ptr = std::move (desugared);
}
} // namespace AST
} // namespace Rust

View File

@@ -0,0 +1,79 @@
// Copyright (C) 2025 Free Software Foundation, Inc.
// This file is part of GCC.
// GCC is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 3, or (at your option) any later
// version.
// GCC is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
// for more details.
// You should have received a copy of the GNU General Public License
// along with GCC; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
#ifndef RUST_DESUGAR_QUESTION_MARK
#define RUST_DESUGAR_QUESTION_MARK
#include "rust-ast-visitor.h"
#include "rust-expr.h"
#include "rust-stmt.h"
namespace Rust {
namespace AST {
// NOTE: One more complexity compare to desugaring for-loops is that we need to
// desugar every possible expression... should we do that during lowering
// instead? but would it get resolved and expanded etc? Not sure...
// The goal of this desugar is to go from this:
//
// ```
// <expr>?
// ```
//
// to this:
//
// ```
// match Try::into_result(<expr>) {
// Ok(val) => val,
// Err(err) => return Try::from_err(From::from(err))
// }
// ```
//
// We use lang items for almost everything, so the actual desugared code looks
// more like this:
//
// ```
// match #[lang = "into_result"](<expr>) {
// #[lang = "Ok"](val) => val,
// #[lang = "Err"](err) => {
// return #[lang = "from_error"](#[lang ="from"](err))
// }
// }
// ```
class DesugarQuestionMark : public DefaultASTVisitor
{
using DefaultASTVisitor::visit;
public:
DesugarQuestionMark ();
void go (AST::Crate &);
private:
void desugar_and_replace (std::unique_ptr<Expr> &ptr);
std::unique_ptr<Expr> desugar (ErrorPropagationExpr &);
void visit (AST::ExprStmt &) override;
void visit (AST::CallExpr &) override;
void visit (AST::LetStmt &) override;
};
} // namespace AST
} // namespace Rust
#endif // ! RUST_DESUGAR_QUESTION_MARK

File diff suppressed because it is too large Load Diff

72
gcc/rust/ast/rust-fmt.cc Normal file
View File

@@ -0,0 +1,72 @@
// Copyright (C) 2020-2024 Free Software Foundation, Inc.
// This file is part of GCC.
// GCC is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 3, or (at your option) any later
// version.
// GCC is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
// for more details.
// You should have received a copy of the GNU General Public License
// along with GCC; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
#include "rust-fmt.h"
#include "rust-diagnostics.h"
namespace Rust {
namespace Fmt {
std::string
ffi::RustHamster::to_string () const
{
return std::string (ptr, len);
}
Pieces
Pieces::collect (const std::string &to_parse, bool append_newline,
ffi::ParseMode parse_mode)
{
auto handle
= ffi::collect_pieces (to_parse.c_str (), append_newline, parse_mode);
// this performs multiple copies, can we avoid them maybe?
// TODO: Instead of just creating a vec of, basically, `ffi::Piece`s, we
// should transform them into the proper C++ type which we can work with. so
// transform all the strings into C++ strings? all the Option<T> into
// tl::optional<T>?
auto pieces_vector = std::vector<ffi::Piece> (handle.piece_slice.base_ptr,
handle.piece_slice.base_ptr
+ handle.piece_slice.len);
return Pieces (handle, std::move (pieces_vector));
}
Pieces::~Pieces () { ffi::destroy_pieces (handle); }
Pieces::Pieces (const Pieces &other) : pieces_vector (other.pieces_vector)
{
handle = ffi::clone_pieces (other.handle);
}
Pieces &
Pieces::operator= (const Pieces &other)
{
handle = ffi::clone_pieces (other.handle);
pieces_vector = other.pieces_vector;
return *this;
}
Pieces::Pieces (Pieces &&other)
: pieces_vector (std::move (other.pieces_vector)),
handle (clone_pieces (other.handle))
{}
} // namespace Fmt
} // namespace Rust

317
gcc/rust/ast/rust-fmt.h Normal file
View File

@@ -0,0 +1,317 @@
// Copyright (C) 2023-2024 Free Software Foundation, Inc.
// This file is part of GCC.
// GCC is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 3, or (at your option) any later
// version.
// GCC is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
// for more details.
// You should have received a copy of the GNU General Public License
// along with GCC; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
#ifndef RUST_FMT_H
#define RUST_FMT_H
#include "rust-system.h"
// FIXME: How to encode Option?
namespace Rust {
namespace Fmt {
namespace ffi {
struct RustHamster
{
const char *ptr;
size_t len;
std::string to_string () const;
};
/// Enum of alignments which are supported.
enum class Alignment
{
/// The value will be aligned to the left.
AlignLeft,
/// The value will be aligned to the right.
AlignRight,
/// The value will be aligned in the center.
AlignCenter,
/// The value will take on a default alignment.
AlignUnknown,
};
/// Enum for the debug hex flags.
enum class DebugHex
{
/// The `x` flag in `{:x?}`.
Lower,
/// The `X` flag in `{:X?}`.
Upper,
};
/// Enum for the sign flags.
enum class Sign
{
/// The `+` flag.
Plus,
/// The `-` flag.
Minus,
};
/// Enum describing where an argument for a format can be located.
struct Position
{
enum class Tag
{
/// The argument is implied to be located at an index
ArgumentImplicitlyIs,
/// The argument is located at a specific index given in the format,
ArgumentIs,
/// The argument has a name.
ArgumentNamed,
};
struct ArgumentImplicitlyIs_Body
{
size_t _0;
};
struct ArgumentIs_Body
{
size_t _0;
};
struct ArgumentNamed_Body
{
RustHamster _0;
};
Tag tag;
union
{
ArgumentImplicitlyIs_Body argument_implicitly_is;
ArgumentIs_Body argument_is;
ArgumentNamed_Body argument_named;
};
};
/// Range inside of a `Span` used for diagnostics when we only have access to
/// relative positions.
struct InnerSpan
{
size_t start;
size_t end;
};
/// A count is used for the precision and width parameters of an integer, and
/// can reference either an argument or a literal integer.
struct Count
{
enum class Tag
{
/// The count is specified explicitly.
CountIs,
/// The count is specified by the argument with the given name.
CountIsName,
/// The count is specified by the argument at the given index.
CountIsParam,
/// The count is specified by a star (like in `{:.*}`) that refers to the
/// argument at the given index.
CountIsStar,
/// The count is implied and cannot be explicitly specified.
CountImplied,
};
struct CountIs_Body
{
size_t _0;
};
struct CountIsName_Body
{
RustHamster _0;
InnerSpan _1;
};
struct CountIsParam_Body
{
size_t _0;
};
struct CountIsStar_Body
{
size_t _0;
};
Tag tag;
union
{
CountIs_Body count_is;
CountIsName_Body count_is_name;
CountIsParam_Body count_is_param;
CountIsStar_Body count_is_star;
};
};
/// Specification for the formatting of an argument in the format string.
struct FormatSpec
{
/// Optionally specified character to fill alignment with.
const uint32_t *fill;
/// Span of the optionally specified fill character.
const InnerSpan *fill_span;
/// Optionally specified alignment.
Alignment align;
/// The `+` or `-` flag.
const Sign *sign;
/// The `#` flag.
bool alternate;
/// The `0` flag.
bool zero_pad;
/// The `x` or `X` flag. (Only for `Debug`.)
const DebugHex *debug_hex;
/// The integer precision to use.
Count precision;
/// The span of the precision formatting flag (for diagnostics).
const InnerSpan *precision_span;
/// The string width requested for the resulting format.
Count width;
/// The span of the width formatting flag (for diagnostics).
const InnerSpan *width_span;
/// The descriptor string representing the name of the format desired for
/// this argument, this can be empty or any number of characters, although
/// it is required to be one word.
RustHamster ty;
/// The span of the descriptor string (for diagnostics).
const InnerSpan *ty_span;
};
/// Representation of an argument specification.
struct Argument
{
/// Where to find this argument
Position position;
/// The span of the position indicator. Includes any whitespace in implicit
/// positions (`{ }`).
InnerSpan position_span;
/// How to format the argument
FormatSpec format;
};
/// A piece is a portion of the format string which represents the next part
/// to emit. These are emitted as a stream by the `Parser` class.
struct Piece
{
enum class Tag
{
/// A literal string which should directly be emitted
String,
/// This describes that formatting should process the next argument (as
/// specified inside) for emission.
NextArgument,
};
struct String_Body
{
RustHamster _0;
};
struct NextArgument_Body
{
Argument _0;
};
Tag tag;
union
{
String_Body string;
NextArgument_Body next_argument;
};
};
struct PieceSlice
{
const Piece *base_ptr;
size_t len;
size_t cap;
};
struct RustString
{
const unsigned char *ptr;
size_t len;
size_t cap;
};
struct FormatArgsHandle
{
PieceSlice piece_slice;
RustString rust_string;
};
enum ParseMode
{
Format = 0,
InlineAsm,
};
extern "C" {
FormatArgsHandle
collect_pieces (const char *input, bool append_newline, ParseMode parse_mode);
FormatArgsHandle
clone_pieces (const FormatArgsHandle &);
void destroy_pieces (FormatArgsHandle);
} // extern "C"
} // namespace ffi
struct Pieces
{
static Pieces collect (const std::string &to_parse, bool append_newline,
ffi::ParseMode parse_mode);
~Pieces ();
Pieces (const Pieces &other);
Pieces &operator= (const Pieces &other);
Pieces (Pieces &&other);
const std::vector<ffi::Piece> &get_pieces () const { return pieces_vector; }
// {
// slice = clone_pieces (&other.slice);
// to_parse = other.to_parse;
// return *this;
// }
private:
Pieces (ffi::FormatArgsHandle handle, std::vector<ffi::Piece> &&pieces_vector)
: pieces_vector (std::move (pieces_vector)), handle (handle)
{}
std::vector<ffi::Piece> pieces_vector;
// this memory is held for FFI reasons - it needs to be released and cloned
// precisely, so try to not access it/modify it if possible. you should
// instead work with `pieces_vector`
ffi::FormatArgsHandle handle;
};
} // namespace Fmt
} // namespace Rust
#endif // !RUST_FMT_H

File diff suppressed because it is too large Load Diff

View File

@@ -24,11 +24,11 @@
#include "rust-ast-fragment.h"
#include "rust-location.h"
#include "rust-item.h"
#include "rust-make-unique.h"
#include "rust-macro-builtins.h"
namespace Rust {
namespace AST {
class MacroFragSpec
{
public:
@@ -482,7 +482,7 @@ private:
* should make use of the actual rules. If the macro is builtin, then another
* associated transcriber should be used
*/
static Fragment dummy_builtin (location_t, MacroInvocData &)
static Fragment dummy_builtin (location_t, MacroInvocData &, AST::InvocKind)
{
rust_unreachable ();
return Fragment::create_error ();
@@ -521,7 +521,7 @@ public:
mbe (Identifier rule_name, DelimType delim_type, std::vector<MacroRule> rules,
std::vector<Attribute> outer_attrs, location_t locus)
{
return Rust::make_unique<MacroRulesDefinition> (
return std::make_unique<MacroRulesDefinition> (
MacroRulesDefinition (rule_name, delim_type, rules, outer_attrs, locus,
AST::MacroRulesDefinition::MacroKind::MBE,
AST::Visibility::create_error ()));
@@ -532,7 +532,7 @@ public:
std::vector<Attribute> outer_attrs, location_t locus,
Visibility vis)
{
return Rust::make_unique<MacroRulesDefinition> (MacroRulesDefinition (
return std::make_unique<MacroRulesDefinition> (MacroRulesDefinition (
rule_name, AST::DelimType::CURLY, rules, outer_attrs, locus,
AST::MacroRulesDefinition::MacroKind::DeclMacro, vis));
}
@@ -572,13 +572,13 @@ public:
is_builtin_rule = true;
}
AST::Kind get_ast_kind () const override
{
return AST::Kind::MACRO_RULES_DEFINITION;
}
MacroKind get_kind () const { return kind; }
Item::Kind get_item_kind () const override
{
return Item::Kind::MacroRulesDefinition;
}
protected:
/* Use covariance to implement clone function as returning this object rather
* than base */
@@ -672,11 +672,6 @@ public:
return ExprWithoutBlock::get_node_id ();
}
AST::Kind get_ast_kind () const override
{
return AST::Kind::MACRO_INVOCATION;
}
NodeId get_macro_node_id () const { return node_id; }
MacroInvocData &get_invoc_data () { return invoc_data; }
@@ -715,17 +710,18 @@ private:
location_t locus, bool is_semi_coloned,
std::vector<std::unique_ptr<MacroInvocation>> &&pending_eager_invocs)
: TraitItem (locus), outer_attrs (std::move (outer_attrs)), locus (locus),
node_id (Analysis::Mappings::get ()->get_next_node_id ()),
node_id (Analysis::Mappings::get ().get_next_node_id ()),
invoc_data (std::move (invoc_data)), is_semi_coloned (is_semi_coloned),
kind (kind), builtin_kind (builtin_kind),
pending_eager_invocs (std::move (pending_eager_invocs))
{}
MacroInvocation (const MacroInvocation &other)
: TraitItem (other.locus), outer_attrs (other.outer_attrs),
locus (other.locus), node_id (other.node_id),
invoc_data (other.invoc_data), is_semi_coloned (other.is_semi_coloned),
kind (other.kind), builtin_kind (other.builtin_kind)
: TraitItem (other.locus), ExternalItem (other.node_id),
outer_attrs (other.outer_attrs), locus (other.locus),
node_id (other.node_id), invoc_data (other.invoc_data),
is_semi_coloned (other.is_semi_coloned), kind (other.kind),
builtin_kind (other.builtin_kind)
{
if (other.kind == InvocKind::Builtin)
for (auto &pending : other.pending_eager_invocs)
@@ -794,6 +790,21 @@ public:
void add_semicolon () override { is_semi_coloned = true; }
Pattern::Kind get_pattern_kind () override
{
return Pattern::Kind::MacroInvocation;
}
Expr::Kind get_expr_kind () const override
{
return Expr::Kind::MacroInvocation;
}
Item::Kind get_item_kind () const override
{
return Item::Kind::MacroInvocation;
}
protected:
Item *clone_item_impl () const override
{

View File

@@ -17,6 +17,7 @@ You should have received a copy of the GNU General Public License
along with GCC; see the file COPYING3. If not see
<http://www.gnu.org/licenses/>. */
#include "rust-path.h"
#include "rust-system.h"
#include "rust-ast-full.h"
#include "rust-diagnostics.h"
@@ -118,7 +119,7 @@ ConstGenericParam::as_string () const
str += "const " + name.as_string () + ": " + type->as_string ();
if (has_default_value ())
str += " = " + get_default_value ().as_string ();
str += " = " + get_default_value_unchecked ().as_string ();
return str;
}
@@ -135,8 +136,11 @@ PathExprSegment::as_string () const
}
std::string
PathPattern::as_string () const
Path::as_string () const
{
// FIXME: Impl for lang items
rust_assert (kind == Kind::Regular);
std::string str;
for (const auto &segment : segments)
@@ -149,8 +153,10 @@ PathPattern::as_string () const
}
SimplePath
PathPattern::convert_to_simple_path (bool with_opening_scope_resolution) const
Path::convert_to_simple_path (bool with_opening_scope_resolution) const
{
rust_assert (kind == Kind::Regular);
if (!has_segments ())
return SimplePath::create_empty ();
@@ -197,7 +203,7 @@ PathInExpression::as_string () const
if (has_opening_scope_resolution)
str = "::";
return str + PathPattern::as_string ();
return str + Path::as_string ();
}
std::string
@@ -260,6 +266,27 @@ TypePath::as_simple_path () const
locus);
}
std::string
TypePath::make_debug_string () const
{
rust_assert (!segments.empty ());
std::string output;
for (const auto &segment : segments)
{
if (segment != nullptr && !segment->is_lang_item ()
&& !segment->is_error ())
{
if (!output.empty () || has_opening_scope_resolution_op ())
output.append ("::");
output.append (segment->get_ident_segment ().as_string ());
}
}
return output;
}
// hopefully definition here will prevent circular dependency issue
TraitBound *
TypePath::to_trait_bound (bool in_parens) const
@@ -297,7 +324,7 @@ TypePathFunction::as_string () const
std::string
QualifiedPathInExpression::as_string () const
{
return path_type.as_string () + "::" + PathPattern::as_string ();
return path_type.as_string () + "::" + Path::as_string ();
}
std::string

View File

@@ -21,7 +21,11 @@
/* "Path" (identifier within namespaces, essentially) handling. Required include
* for virtually all AST-related functionality. */
#include "optional.h"
#include "rust-ast.h"
#include "rust-hir-map.h"
#include "rust-mapping-common.h"
#include "rust-system.h"
#include "system.h"
namespace Rust {
@@ -52,10 +56,16 @@ public:
location_t get_locus () const { return locus; }
bool is_super_segment () const { return as_string ().compare ("super") == 0; }
bool is_crate_segment () const { return as_string ().compare ("crate") == 0; }
bool is_lower_self () const { return as_string ().compare ("self") == 0; }
bool is_big_self () const { return as_string ().compare ("Self") == 0; }
bool is_super_path_seg () const
{
return as_string ().compare ("super") == 0;
}
bool is_crate_path_seg () const
{
return as_string ().compare ("crate") == 0;
}
bool is_lower_self_seg () const { return as_string ().compare ("self") == 0; }
bool is_big_self_seg () const { return as_string ().compare ("Self") == 0; }
};
// A binding of an identifier to a type used in generic arguments in paths
@@ -120,7 +130,13 @@ public:
std::string as_string () const;
// TODO: is this better? Or is a "vis_pattern" better?
std::unique_ptr<Type> &get_type ()
Type &get_type ()
{
rust_assert (type != nullptr);
return *type;
}
std::unique_ptr<Type> &get_type_ptr ()
{
rust_assert (type != nullptr);
return type;
@@ -151,17 +167,11 @@ public:
*/
enum class Kind
{
Error,
Const, // A const value
Type, // A type argument (not discernable during parsing)
Either, // Either a type or a const value, cleared up during resolving
};
static GenericArg create_error ()
{
return GenericArg (nullptr, nullptr, {""}, Kind::Error, UNDEF_LOCATION);
}
static GenericArg create_const (std::unique_ptr<Expr> expression)
{
auto locus = expression->get_locus ();
@@ -206,8 +216,6 @@ public:
GenericArg (GenericArg &&other) = default;
GenericArg &operator= (GenericArg &&other) = default;
bool is_error () const { return kind == Kind::Error; }
Kind get_kind () const { return kind; }
location_t get_locus () const { return locus; }
@@ -216,26 +224,38 @@ public:
switch (get_kind ())
{
case Kind::Const:
get_expression ()->accept_vis (visitor);
get_expression ().accept_vis (visitor);
break;
case Kind::Type:
get_type ()->accept_vis (visitor);
get_type ().accept_vis (visitor);
break;
case Kind::Either:
break;
case Kind::Error:
rust_unreachable ();
}
}
std::unique_ptr<Expr> &get_expression ()
Expr &get_expression ()
{
rust_assert (kind == Kind::Const);
return *expression;
}
std::unique_ptr<Expr> &get_expression_ptr ()
{
rust_assert (kind == Kind::Const);
return expression;
}
std::unique_ptr<Type> &get_type ()
Type &get_type ()
{
rust_assert (kind == Kind::Type);
return *type;
}
std::unique_ptr<Type> &get_type_ptr ()
{
rust_assert (kind == Kind::Type);
@@ -253,8 +273,6 @@ public:
{
switch (get_kind ())
{
case Kind::Error:
rust_unreachable ();
case Kind::Either:
return "Ambiguous: " + path.as_string ();
case Kind::Const:
@@ -325,52 +343,52 @@ class ConstGenericParam : public GenericParam
/**
* Default value for the const generic parameter
*/
GenericArg default_value;
tl::optional<GenericArg> default_value;
Attribute outer_attr;
AST::AttrVec outer_attrs;
location_t locus;
public:
ConstGenericParam (Identifier name, std::unique_ptr<AST::Type> type,
GenericArg default_value, Attribute outer_attr,
location_t locus)
tl::optional<GenericArg> default_value,
AST::AttrVec outer_attrs, location_t locus)
: name (name), type (std::move (type)),
default_value (std::move (default_value)), outer_attr (outer_attr),
default_value (std::move (default_value)), outer_attrs (outer_attrs),
locus (locus)
{}
ConstGenericParam (const ConstGenericParam &other)
: GenericParam (), name (other.name), type (other.type->clone_type ()),
default_value (other.default_value), outer_attr (other.outer_attr),
default_value (other.default_value), outer_attrs (other.outer_attrs),
locus (other.locus)
{}
bool has_type () const { return type != nullptr; }
bool has_default_value () const { return !default_value.is_error (); }
bool has_default_value () const { return default_value.has_value (); }
const Identifier &get_name () const { return name; }
Attribute &get_outer_attribute () { return outer_attr; }
AST::AttrVec &get_outer_attrs () { return outer_attrs; }
std::unique_ptr<AST::Type> &get_type ()
AST::Type &get_type ()
{
rust_assert (has_type ());
return type;
return *type;
}
GenericArg &get_default_value ()
GenericArg &get_default_value_unchecked ()
{
rust_assert (has_default_value ());
return default_value;
return default_value.value ();
}
const GenericArg &get_default_value () const
const GenericArg &get_default_value_unchecked () const
{
rust_assert (has_default_value ());
return default_value;
return default_value.value ();
}
std::string as_string () const override;
@@ -456,15 +474,23 @@ public:
std::string as_string () const;
// TODO: is this better? Or is a "vis_pattern" better?
std::vector<GenericArg> &get_generic_args () { return generic_args; }
// TODO: is this better? Or is a "vis_pattern" better?
std::vector<GenericArgsBinding> &get_binding_args () { return binding_args; }
const std::vector<GenericArgsBinding> &get_binding_args () const
{
return binding_args;
}
std::vector<Lifetime> &get_lifetime_args () { return lifetime_args; };
location_t get_locus () { return locus; }
const std::vector<Lifetime> &get_lifetime_args () const
{
return lifetime_args;
};
location_t get_locus () const { return locus; }
};
/* A segment of a path in expression, including an identifier aspect and maybe
@@ -486,7 +512,7 @@ public:
GenericArgs generic_args = GenericArgs::create_empty ())
: segment_name (std::move (segment_name)),
generic_args (std::move (generic_args)), locus (locus),
node_id (Analysis::Mappings::get ()->get_next_node_id ())
node_id (Analysis::Mappings::get ().get_next_node_id ())
{}
/* Constructor for segment with generic arguments (from segment name and all
@@ -499,7 +525,7 @@ public:
generic_args (GenericArgs (std::move (lifetime_args),
std::move (generic_args),
std::move (binding_args))),
locus (locus), node_id (Analysis::Mappings::get ()->get_next_node_id ())
locus (locus), node_id (Analysis::Mappings::get ().get_next_node_id ())
{}
// Returns whether path expression segment is in an error state.
@@ -529,66 +555,102 @@ public:
bool is_super_path_seg () const
{
return !has_generic_args () && get_ident_segment ().is_super_segment ();
return !has_generic_args () && get_ident_segment ().is_super_path_seg ();
}
bool is_crate_path_seg () const
{
return !has_generic_args () && get_ident_segment ().is_crate_segment ();
return !has_generic_args () && get_ident_segment ().is_crate_path_seg ();
}
bool is_lower_self_seg () const
{
return !has_generic_args () && get_ident_segment ().is_lower_self ();
return !has_generic_args () && get_ident_segment ().is_lower_self_seg ();
}
};
// AST node representing a pattern that involves a "path" - abstract base
// class
class PathPattern : public Pattern
class Path : public Pattern
{
std::vector<PathExprSegment> segments;
public:
enum class Kind
{
LangItem,
Regular,
};
protected:
PathPattern (std::vector<PathExprSegment> segments)
: segments (std::move (segments))
Path (std::vector<PathExprSegment> segments)
: segments (std::move (segments)), lang_item (tl::nullopt),
kind (Kind::Regular)
{}
Path (LangItem::Kind lang_item)
: segments ({}), lang_item (lang_item), kind (Kind::LangItem)
{}
// Returns whether path has segments.
bool has_segments () const { return !segments.empty (); }
bool has_segments () const
{
rust_assert (kind == Kind::Regular);
return !segments.empty ();
}
/* Converts path segments to their equivalent SimplePath segments if
* possible, and creates a SimplePath from them. */
SimplePath convert_to_simple_path (bool with_opening_scope_resolution) const;
// Removes all segments of the path.
void remove_all_segments ()
{
segments.clear ();
segments.shrink_to_fit ();
}
public:
/* Returns whether the path is a single segment (excluding qualified path
* initial as segment). */
bool is_single_segment () const { return segments.size () == 1; }
bool is_single_segment () const
{
rust_assert (kind == Kind::Regular);
return segments.size () == 1;
}
std::string as_string () const override;
bool is_lang_item () const { return kind == Kind::LangItem; }
// TODO: this seems kinda dodgy
std::vector<PathExprSegment> &get_segments () { return segments; }
const std::vector<PathExprSegment> &get_segments () const { return segments; }
std::vector<PathExprSegment> &get_segments ()
{
rust_assert (kind == Kind::Regular);
return segments;
}
const std::vector<PathExprSegment> &get_segments () const
{
rust_assert (kind == Kind::Regular);
return segments;
}
LangItem::Kind get_lang_item () const
{
rust_assert (kind == Kind::LangItem);
return *lang_item;
}
Pattern::Kind get_pattern_kind () override { return Pattern::Kind::Path; }
Path::Kind get_path_kind () { return kind; }
protected:
std::vector<PathExprSegment> segments;
tl::optional<LangItem::Kind> lang_item;
Path::Kind kind;
};
/* AST node representing a path-in-expression pattern (path that allows
* generic arguments) */
class PathInExpression : public PathPattern, public PathExpr
class PathInExpression : public Path, public ExprWithoutBlock
{
std::vector<Attribute> outer_attrs;
bool has_opening_scope_resolution;
location_t locus;
NodeId _node_id;
bool marked_for_strip;
public:
std::string as_string () const override;
@@ -596,16 +658,25 @@ public:
PathInExpression (std::vector<PathExprSegment> path_segments,
std::vector<Attribute> outer_attrs, location_t locus,
bool has_opening_scope_resolution = false)
: PathPattern (std::move (path_segments)),
outer_attrs (std::move (outer_attrs)),
: Path (std::move (path_segments)), outer_attrs (std::move (outer_attrs)),
has_opening_scope_resolution (has_opening_scope_resolution),
locus (locus), _node_id (Analysis::Mappings::get ()->get_next_node_id ())
locus (locus), _node_id (Analysis::Mappings::get ().get_next_node_id ()),
marked_for_strip (false)
{}
PathInExpression (LangItem::Kind lang_item,
std::vector<Attribute> outer_attrs, location_t locus)
: Path (lang_item), outer_attrs (std::move (outer_attrs)),
has_opening_scope_resolution (false), locus (locus),
_node_id (Analysis::Mappings::get ().get_next_node_id ()),
marked_for_strip (false)
{}
// Creates an error state path in expression.
static PathInExpression create_error ()
{
return PathInExpression ({}, {}, UNDEF_LOCATION);
return PathInExpression (std::vector<PathExprSegment> (), {},
UNDEF_LOCATION);
}
// Returns whether path in expression is in an error state.
@@ -628,9 +699,8 @@ public:
void accept_vis (ASTVisitor &vis) override;
// Invalid if path is empty (error state), so base stripping on that.
void mark_for_strip () override { remove_all_segments (); }
bool is_marked_for_strip () const override { return is_error (); }
void mark_for_strip () override { marked_for_strip = true; }
bool is_marked_for_strip () const override { return marked_for_strip; }
bool opening_scope_resolution () const
{
@@ -647,14 +717,17 @@ public:
outer_attrs = std::move (new_attrs);
}
NodeId get_pattern_node_id () const { return get_node_id (); }
PathExprSegment &get_final_segment () { return get_segments ().back (); }
const PathExprSegment &get_final_segment () const
{
return get_segments ().back ();
}
Expr::Kind get_expr_kind () const override
{
return Expr::Kind::PathInExpression;
}
protected:
/* Use covariance to implement clone function as returning this object
* rather than base */
@@ -689,7 +762,8 @@ public:
};
private:
PathIdentSegment ident_segment;
tl::optional<LangItem::Kind> lang_item;
tl::optional<PathIdentSegment> ident_segment;
location_t locus;
protected:
@@ -719,21 +793,30 @@ public:
TypePathSegment (PathIdentSegment ident_segment,
bool has_separating_scope_resolution, location_t locus)
: ident_segment (std::move (ident_segment)), locus (locus),
: lang_item (tl::nullopt), ident_segment (std::move (ident_segment)),
locus (locus),
has_separating_scope_resolution (has_separating_scope_resolution),
node_id (Analysis::Mappings::get ()->get_next_node_id ())
node_id (Analysis::Mappings::get ().get_next_node_id ())
{}
TypePathSegment (LangItem::Kind lang_item, location_t locus)
: lang_item (lang_item), ident_segment (tl::nullopt), locus (locus),
has_separating_scope_resolution (false),
node_id (Analysis::Mappings::get ().get_next_node_id ())
{}
TypePathSegment (std::string segment_name,
bool has_separating_scope_resolution, location_t locus)
: ident_segment (PathIdentSegment (std::move (segment_name), locus)),
: lang_item (tl::nullopt),
ident_segment (PathIdentSegment (std::move (segment_name), locus)),
locus (locus),
has_separating_scope_resolution (has_separating_scope_resolution),
node_id (Analysis::Mappings::get ()->get_next_node_id ())
node_id (Analysis::Mappings::get ().get_next_node_id ())
{}
TypePathSegment (TypePathSegment const &other)
: ident_segment (other.ident_segment), locus (other.locus),
: lang_item (other.lang_item), ident_segment (other.ident_segment),
locus (other.locus),
has_separating_scope_resolution (other.has_separating_scope_resolution),
node_id (other.node_id)
{}
@@ -741,6 +824,7 @@ public:
TypePathSegment &operator= (TypePathSegment const &other)
{
ident_segment = other.ident_segment;
lang_item = other.lang_item;
locus = other.locus;
has_separating_scope_resolution = other.has_separating_scope_resolution;
node_id = other.node_id;
@@ -751,16 +835,28 @@ public:
TypePathSegment (TypePathSegment &&other) = default;
TypePathSegment &operator= (TypePathSegment &&other) = default;
virtual std::string as_string () const { return ident_segment.as_string (); }
virtual std::string as_string () const
{
if (lang_item.has_value ())
return LangItem::PrettyString (*lang_item);
return ident_segment->as_string ();
}
/* Returns whether the type path segment is in an error state. May be
* virtual in future. */
bool is_error () const { return ident_segment.is_error (); }
bool is_error () const
{
rust_assert (ident_segment);
return ident_segment->is_error ();
}
/* Returns whether segment is identifier only (as opposed to generic args or
* function). Overridden in derived classes with other segments. */
virtual bool is_ident_only () const { return true; }
bool is_lang_item () const { return lang_item.has_value (); }
location_t get_locus () const { return locus; }
// not pure virtual as class not abstract
@@ -771,23 +867,41 @@ public:
return has_separating_scope_resolution;
}
PathIdentSegment &get_ident_segment () { return ident_segment; };
const PathIdentSegment &get_ident_segment () const { return ident_segment; };
PathIdentSegment &get_ident_segment ()
{
rust_assert (!is_lang_item ());
return *ident_segment;
};
const PathIdentSegment &get_ident_segment () const
{
rust_assert (!is_lang_item ());
return *ident_segment;
};
LangItem::Kind get_lang_item () const
{
rust_assert (is_lang_item ());
return *lang_item;
}
NodeId get_node_id () const { return node_id; }
bool is_crate_path_seg () const
{
return get_ident_segment ().is_crate_segment ();
return get_ident_segment ().is_crate_path_seg ();
}
bool is_super_path_seg () const
{
return get_ident_segment ().is_super_segment ();
return get_ident_segment ().is_super_path_seg ();
}
bool is_big_self_seg () const
{
return get_ident_segment ().is_big_self_seg ();
}
bool is_big_self_seg () const { return get_ident_segment ().is_big_self (); }
bool is_lower_self_seg () const
{
return get_ident_segment ().is_lower_self ();
return get_ident_segment ().is_lower_self_seg ();
}
};
@@ -812,6 +926,12 @@ public:
generic_args (std::move (generic_args))
{}
TypePathSegmentGeneric (LangItem::Kind lang_item, GenericArgs generic_args,
location_t locus)
: TypePathSegment (lang_item, locus),
generic_args (std::move (generic_args))
{}
// Constructor from segment name and all args
TypePathSegmentGeneric (std::string segment_name,
bool has_separating_scope_resolution,
@@ -848,11 +968,7 @@ public:
void accept_vis (ASTVisitor &vis) override;
// TODO: is this better? Or is a "vis_pattern" better?
GenericArgs &get_generic_args ()
{
rust_assert (has_generic_args ());
return generic_args;
}
GenericArgs &get_generic_args () { return generic_args; }
// Use covariance to override base class method
TypePathSegmentGeneric *clone_type_path_segment_impl () const override
@@ -869,7 +985,7 @@ private:
/*bool has_inputs;
TypePathFnInputs inputs;*/
// inlined from TypePathFnInputs
std::vector<std::unique_ptr<Type> > inputs;
std::vector<std::unique_ptr<Type>> inputs;
// bool has_type;
std::unique_ptr<Type> return_type;
@@ -902,8 +1018,8 @@ public:
}
// Constructor
TypePathFunction (std::vector<std::unique_ptr<Type> > inputs,
location_t locus, std::unique_ptr<Type> type = nullptr)
TypePathFunction (std::vector<std::unique_ptr<Type>> inputs, location_t locus,
std::unique_ptr<Type> type = nullptr)
: inputs (std::move (inputs)), return_type (std::move (type)),
is_invalid (false), locus (locus)
{}
@@ -948,14 +1064,20 @@ public:
std::string as_string () const;
// TODO: this mutable getter seems really dodgy. Think up better way.
const std::vector<std::unique_ptr<Type> > &get_params () const
const std::vector<std::unique_ptr<Type>> &get_params () const
{
return inputs;
}
std::vector<std::unique_ptr<Type> > &get_params () { return inputs; }
std::vector<std::unique_ptr<Type>> &get_params () { return inputs; }
// TODO: is this better? Or is a "vis_pattern" better?
std::unique_ptr<Type> &get_return_type ()
Type &get_return_type ()
{
rust_assert (has_return_type ());
return *return_type;
}
std::unique_ptr<Type> &get_return_type_ptr ()
{
rust_assert (has_return_type ());
return return_type;
@@ -1010,11 +1132,10 @@ public:
}
};
// Path used inside types
class TypePath : public TypeNoBounds
{
bool has_opening_scope_resolution;
std::vector<std::unique_ptr<TypePathSegment> > segments;
std::vector<std::unique_ptr<TypePathSegment>> segments;
location_t locus;
protected:
@@ -1039,12 +1160,20 @@ public:
// Creates an error state TypePath.
static TypePath create_error ()
{
return TypePath (std::vector<std::unique_ptr<TypePathSegment> > (),
return TypePath (std::vector<std::unique_ptr<TypePathSegment>> (),
UNDEF_LOCATION);
}
// Constructor
TypePath (std::vector<std::unique_ptr<TypePathSegment> > segments,
TypePath (std::vector<std::unique_ptr<TypePathSegment>> segments,
location_t locus, bool has_opening_scope_resolution = false)
: TypeNoBounds (),
has_opening_scope_resolution (has_opening_scope_resolution),
segments (std::move (segments)), locus (locus)
{}
TypePath (LangItem::Kind lang_item,
std::vector<std::unique_ptr<TypePathSegment>> segments,
location_t locus, bool has_opening_scope_resolution = false)
: TypeNoBounds (),
has_opening_scope_resolution (has_opening_scope_resolution),
@@ -1082,6 +1211,8 @@ public:
std::string as_string () const override;
std::string make_debug_string () const;
/* Converts TypePath to SimplePath if possible (i.e. no generic or function
* arguments). Otherwise returns an empty SimplePath. */
SimplePath as_simple_path () const;
@@ -1090,15 +1221,19 @@ public:
TraitBound *to_trait_bound (bool in_parens) const override;
location_t get_locus () const override final { return locus; }
NodeId get_node_id () const { return node_id; }
void mark_for_strip () override {}
bool is_marked_for_strip () const override { return false; }
void accept_vis (ASTVisitor &vis) override;
// TODO: this seems kinda dodgy
std::vector<std::unique_ptr<TypePathSegment> > &get_segments ()
std::vector<std::unique_ptr<TypePathSegment>> &get_segments ()
{
return segments;
}
const std::vector<std::unique_ptr<TypePathSegment> > &get_segments () const
const std::vector<std::unique_ptr<TypePathSegment>> &get_segments () const
{
return segments;
}
@@ -1119,9 +1254,8 @@ public:
QualifiedPathType (std::unique_ptr<Type> invoke_on_type,
location_t locus = UNDEF_LOCATION,
TypePath trait_path = TypePath::create_error ())
: type_to_invoke_on (std::move (invoke_on_type)),
trait_path (std::move (trait_path)), locus (locus),
node_id (Analysis::Mappings::get ()->get_next_node_id ())
: type_to_invoke_on (std::move (invoke_on_type)), trait_path (trait_path),
locus (locus), node_id (Analysis::Mappings::get ().get_next_node_id ())
{}
// Copy constructor uses custom deep copy for Type to preserve polymorphism
@@ -1174,7 +1308,13 @@ public:
location_t get_locus () const { return locus; }
// TODO: is this better? Or is a "vis_pattern" better?
std::unique_ptr<Type> &get_type ()
Type &get_type ()
{
rust_assert (type_to_invoke_on != nullptr);
return *type_to_invoke_on;
}
std::unique_ptr<Type> &get_type_ptr ()
{
rust_assert (type_to_invoke_on != nullptr);
return type_to_invoke_on;
@@ -1192,7 +1332,7 @@ public:
/* AST node representing a qualified path-in-expression pattern (path that
* allows specifying trait functions) */
class QualifiedPathInExpression : public PathPattern, public PathExpr
class QualifiedPathInExpression : public Path, public ExprWithoutBlock
{
std::vector<Attribute> outer_attrs;
QualifiedPathType path_type;
@@ -1206,10 +1346,9 @@ public:
std::vector<PathExprSegment> path_segments,
std::vector<Attribute> outer_attrs,
location_t locus)
: PathPattern (std::move (path_segments)),
outer_attrs (std::move (outer_attrs)),
: Path (std::move (path_segments)), outer_attrs (std::move (outer_attrs)),
path_type (std::move (qual_path_type)), locus (locus),
_node_id (Analysis::Mappings::get ()->get_next_node_id ())
_node_id (Analysis::Mappings::get ().get_next_node_id ())
{}
/* TODO: maybe make a shortcut constructor that has QualifiedPathType
@@ -1253,6 +1392,11 @@ public:
NodeId get_node_id () const override { return _node_id; }
Expr::Kind get_expr_kind () const override
{
return Expr::Kind::QualifiedPathInExpression;
}
protected:
/* Use covariance to implement clone function as returning this object
* rather than base */
@@ -1282,7 +1426,7 @@ class QualifiedPathInType : public TypeNoBounds
{
QualifiedPathType path_type;
std::unique_ptr<TypePathSegment> associated_segment;
std::vector<std::unique_ptr<TypePathSegment> > segments;
std::vector<std::unique_ptr<TypePathSegment>> segments;
location_t locus;
protected:
@@ -1297,7 +1441,7 @@ public:
QualifiedPathInType (
QualifiedPathType qual_path_type,
std::unique_ptr<TypePathSegment> associated_segment,
std::vector<std::unique_ptr<TypePathSegment> > path_segments,
std::vector<std::unique_ptr<TypePathSegment>> path_segments,
location_t locus)
: path_type (std::move (qual_path_type)),
associated_segment (std::move (associated_segment)),
@@ -1344,7 +1488,7 @@ public:
{
return QualifiedPathInType (
QualifiedPathType::create_error (), nullptr,
std::vector<std::unique_ptr<TypePathSegment> > (), UNDEF_LOCATION);
std::vector<std::unique_ptr<TypePathSegment>> (), UNDEF_LOCATION);
}
std::string as_string () const override;
@@ -1364,11 +1508,11 @@ public:
}
// TODO: this seems kinda dodgy
std::vector<std::unique_ptr<TypePathSegment> > &get_segments ()
std::vector<std::unique_ptr<TypePathSegment>> &get_segments ()
{
return segments;
}
const std::vector<std::unique_ptr<TypePathSegment> > &get_segments () const
const std::vector<std::unique_ptr<TypePathSegment>> &get_segments () const
{
return segments;
}

View File

@@ -22,7 +22,6 @@ along with GCC; see the file COPYING3. If not see
#include "rust-diagnostics.h"
#include "rust-ast-visitor.h"
#include "rust-macro.h"
#include "rust-session-manager.h"
#include "rust-lex.h"
#include "rust-parse.h"
#include "rust-operators.h"
@@ -30,6 +29,22 @@ along with GCC; see the file COPYING3. If not see
namespace Rust {
namespace AST {
RangeKind
tokenid_to_rangekind (TokenId id)
{
switch (id)
{
case DOT_DOT_EQ:
return RangeKind::INCLUDED;
case ELLIPSIS:
return RangeKind::ELLIPSIS;
case DOT_DOT:
return RangeKind::EXCLUDED;
default:
rust_unreachable ();
}
}
std::string
LiteralPattern::as_string () const
{
@@ -73,10 +88,17 @@ std::string
RangePattern::as_string () const
{
// TODO: maybe rewrite to work with non-linearisable bounds
if (has_ellipsis_syntax)
return lower->as_string () + "..." + upper->as_string ();
else
return lower->as_string () + "..=" + upper->as_string ();
switch (range_kind)
{
case RangeKind::EXCLUDED:
return lower->as_string () + ".." + upper->as_string ();
case RangeKind::INCLUDED:
return lower->as_string () + "..=" + upper->as_string ();
case RangeKind::ELLIPSIS:
return lower->as_string () + "..." + upper->as_string ();
default:
rust_unreachable ();
}
}
std::string

View File

@@ -36,13 +36,13 @@ public:
// Constructor for a literal pattern
LiteralPattern (Literal lit, location_t locus)
: lit (std::move (lit)), locus (locus),
node_id (Analysis::Mappings::get ()->get_next_node_id ())
node_id (Analysis::Mappings::get ().get_next_node_id ())
{}
LiteralPattern (std::string val, Literal::LitType type, location_t locus,
PrimitiveCoreType type_hint)
: lit (Literal (std::move (val), type, type_hint)), locus (locus),
node_id (Analysis::Mappings::get ()->get_next_node_id ())
node_id (Analysis::Mappings::get ().get_next_node_id ())
{}
location_t get_locus () const override final { return locus; }
@@ -55,6 +55,8 @@ public:
const Literal &get_literal () const { return lit; }
Pattern::Kind get_pattern_kind () override { return Pattern::Kind::Literal; }
protected:
/* Use covariance to implement clone function as returning this object rather
* than base */
@@ -88,7 +90,7 @@ public:
std::unique_ptr<Pattern> to_bind = nullptr)
: Pattern (), variable_ident (std::move (ident)), is_ref (is_ref),
is_mut (is_mut), to_bind (std::move (to_bind)), locus (locus),
node_id (Analysis::Mappings::get ()->get_next_node_id ())
node_id (Analysis::Mappings::get ().get_next_node_id ())
{}
IdentifierPattern (NodeId node_id, Identifier ident, location_t locus,
@@ -136,10 +138,10 @@ public:
void accept_vis (ASTVisitor &vis) override;
// TODO: is this better? Or is a "vis_pattern" better?
std::unique_ptr<Pattern> &get_pattern_to_bind ()
Pattern &get_pattern_to_bind ()
{
rust_assert (has_pattern_to_bind ());
return to_bind;
return *to_bind;
}
Identifier get_ident () const { return variable_ident; }
@@ -149,6 +151,11 @@ public:
NodeId get_node_id () const override { return node_id; }
Pattern::Kind get_pattern_kind () override
{
return Pattern::Kind::Identifier;
}
protected:
/* Use covariance to implement clone function as returning this object rather
* than base */
@@ -168,7 +175,7 @@ public:
std::string as_string () const override { return std::string (1, '_'); }
WildcardPattern (location_t locus)
: locus (locus), node_id (Analysis::Mappings::get ()->get_next_node_id ())
: locus (locus), node_id (Analysis::Mappings::get ().get_next_node_id ())
{}
location_t get_locus () const override final { return locus; }
@@ -177,6 +184,8 @@ public:
NodeId get_node_id () const override { return node_id; }
Pattern::Kind get_pattern_kind () override { return Pattern::Kind::Wildcard; }
protected:
/* Use covariance to implement clone function as returning this object rather
* than base */
@@ -195,7 +204,7 @@ public:
std::string as_string () const override { return ".."; }
RestPattern (location_t locus)
: locus (locus), node_id (Analysis::Mappings::get ()->get_next_node_id ())
: locus (locus), node_id (Analysis::Mappings::get ().get_next_node_id ())
{}
location_t get_locus () const override final { return locus; }
@@ -204,6 +213,8 @@ public:
NodeId get_node_id () const override final { return node_id; }
Pattern::Kind get_pattern_kind () override { return Pattern::Kind::Rest; }
protected:
RestPattern *clone_pattern_impl () const override
{
@@ -357,13 +368,22 @@ protected:
}
};
enum class RangeKind
{
INCLUDED,
ELLIPSIS,
EXCLUDED,
};
RangeKind
tokenid_to_rangekind (TokenId id);
// AST node for matching within a certain range (range pattern)
class RangePattern : public Pattern
{
std::unique_ptr<RangePatternBound> lower;
std::unique_ptr<RangePatternBound> upper;
bool has_ellipsis_syntax;
RangeKind range_kind;
/* location only stored to avoid a dereference - lower pattern should give
* correct location so maybe change in future */
@@ -375,18 +395,18 @@ public:
// Constructor
RangePattern (std::unique_ptr<RangePatternBound> lower,
std::unique_ptr<RangePatternBound> upper, location_t locus,
bool has_ellipsis_syntax = false)
std::unique_ptr<RangePatternBound> upper, RangeKind range_kind,
location_t locus)
: lower (std::move (lower)), upper (std::move (upper)),
has_ellipsis_syntax (has_ellipsis_syntax), locus (locus),
node_id (Analysis::Mappings::get ()->get_next_node_id ())
range_kind (range_kind), locus (locus),
node_id (Analysis::Mappings::get ().get_next_node_id ())
{}
// Copy constructor with clone
RangePattern (RangePattern const &other)
: lower (other.lower->clone_range_pattern_bound ()),
upper (other.upper->clone_range_pattern_bound ()),
has_ellipsis_syntax (other.has_ellipsis_syntax), locus (other.locus),
range_kind (other.range_kind), locus (other.locus),
node_id (other.node_id)
{}
@@ -395,7 +415,7 @@ public:
{
lower = other.lower->clone_range_pattern_bound ();
upper = other.upper->clone_range_pattern_bound ();
has_ellipsis_syntax = other.has_ellipsis_syntax;
range_kind = other.range_kind;
locus = other.locus;
node_id = other.node_id;
@@ -408,29 +428,36 @@ public:
location_t get_locus () const override final { return locus; }
bool get_has_ellipsis_syntax () { return has_ellipsis_syntax; }
bool get_has_ellipsis_syntax () const
{
return range_kind == RangeKind::ELLIPSIS;
}
bool get_has_lower_bound () { return lower != nullptr; }
RangeKind get_range_kind () const { return range_kind; }
bool get_has_upper_bound () { return upper != nullptr; }
bool get_has_lower_bound () const { return lower != nullptr; }
bool get_has_upper_bound () const { return upper != nullptr; }
void accept_vis (ASTVisitor &vis) override;
// TODO: is this better? or is a "vis_bound" better?
std::unique_ptr<RangePatternBound> &get_lower_bound ()
RangePatternBound &get_lower_bound ()
{
rust_assert (lower != nullptr);
return lower;
return *lower;
}
std::unique_ptr<RangePatternBound> &get_upper_bound ()
RangePatternBound &get_upper_bound ()
{
rust_assert (upper != nullptr);
return upper;
return *upper;
}
NodeId get_node_id () const override { return node_id; }
Pattern::Kind get_pattern_kind () override { return Pattern::Kind::Range; }
protected:
/* Use covariance to implement clone function as returning this object rather
* than base */
@@ -456,7 +483,7 @@ public:
bool ref_has_two_amps, location_t locus)
: has_two_amps (ref_has_two_amps), is_mut (is_mut_reference),
pattern (std::move (pattern)), locus (locus),
node_id (Analysis::Mappings::get ()->get_next_node_id ())
node_id (Analysis::Mappings::get ().get_next_node_id ())
{}
// Copy constructor requires clone
@@ -487,10 +514,10 @@ public:
void accept_vis (ASTVisitor &vis) override;
// TODO: is this better? Or is a "vis_pattern" better?
std::unique_ptr<Pattern> &get_referenced_pattern ()
Pattern &get_referenced_pattern ()
{
rust_assert (pattern != nullptr);
return pattern;
return *pattern;
}
bool is_double_reference () const { return has_two_amps; }
@@ -499,6 +526,11 @@ public:
NodeId get_node_id () const override { return node_id; }
Pattern::Kind get_pattern_kind () override
{
return Pattern::Kind::Reference;
}
protected:
/* Use covariance to implement clone function as returning this object rather
* than base */
@@ -594,7 +626,7 @@ public:
std::vector<Attribute> outer_attribs,
location_t locus)
: StructPatternField (std::move (outer_attribs), locus,
Analysis::Mappings::get ()->get_next_node_id ()),
Analysis::Mappings::get ().get_next_node_id ()),
index (index), tuple_pattern (std::move (tuple_pattern))
{}
@@ -645,10 +677,10 @@ public:
TupleIndex get_index () { return index; }
// TODO: is this better? Or is a "vis_pattern" better?
std::unique_ptr<Pattern> &get_index_pattern ()
Pattern &get_index_pattern ()
{
rust_assert (tuple_pattern != nullptr);
return tuple_pattern;
return *tuple_pattern;
}
ItemType get_item_type () const override final { return ItemType::TUPLE_PAT; }
@@ -674,7 +706,7 @@ public:
std::vector<Attribute> outer_attrs,
location_t locus)
: StructPatternField (std::move (outer_attrs), locus,
Analysis::Mappings::get ()->get_next_node_id ()),
Analysis::Mappings::get ().get_next_node_id ()),
ident (std::move (ident)), ident_pattern (std::move (ident_pattern))
{}
@@ -725,10 +757,10 @@ public:
const Identifier &get_identifier () const { return ident; }
// TODO: is this better? Or is a "vis_pattern" better?
std::unique_ptr<Pattern> &get_ident_pattern ()
Pattern &get_ident_pattern ()
{
rust_assert (ident_pattern != nullptr);
return ident_pattern;
return *ident_pattern;
}
ItemType get_item_type () const override final { return ItemType::IDENT_PAT; }
@@ -753,7 +785,7 @@ public:
StructPatternFieldIdent (Identifier ident, bool is_ref, bool is_mut,
std::vector<Attribute> outer_attrs, location_t locus)
: StructPatternField (std::move (outer_attrs), locus,
Analysis::Mappings::get ()->get_next_node_id ()),
Analysis::Mappings::get ().get_next_node_id ()),
has_ref (is_ref), has_mut (is_mut), ident (std::move (ident))
{}
@@ -908,7 +940,7 @@ public:
StructPatternElements elems
= StructPatternElements::create_empty ())
: path (std::move (struct_path)), elems (std::move (elems)),
node_id (Analysis::Mappings::get ()->get_next_node_id ()), locus (locus)
node_id (Analysis::Mappings::get ().get_next_node_id ()), locus (locus)
{}
/* TODO: constructor to construct via elements included in
@@ -934,6 +966,8 @@ public:
NodeId get_node_id () const override { return node_id; }
Pattern::Kind get_pattern_kind () override { return Pattern::Kind::Struct; }
protected:
/* Use covariance to implement clone function as returning this object rather
* than base */
@@ -1123,22 +1157,22 @@ class TupleStructPattern : public Pattern
public:
std::string as_string () const override;
// Returns whether the pattern has tuple struct items.
bool has_items () const { return items != nullptr; }
TupleStructPattern (PathInExpression tuple_struct_path,
std::unique_ptr<TupleStructItems> items)
: path (std::move (tuple_struct_path)), items (std::move (items)),
node_id (Analysis::Mappings::get ()->get_next_node_id ())
{}
node_id (Analysis::Mappings::get ().get_next_node_id ())
{
rust_assert (this->items != nullptr);
}
// Copy constructor required to clone
TupleStructPattern (TupleStructPattern const &other) : path (other.path)
{
// guard to protect from null dereference
rust_assert (other.items != nullptr);
node_id = other.node_id;
if (other.items != nullptr)
items = other.items->clone_tuple_struct_items ();
items = other.items->clone_tuple_struct_items ();
}
// Operator overload assignment operator to clone
@@ -1148,10 +1182,9 @@ public:
node_id = other.node_id;
// guard to protect from null dereference
if (other.items != nullptr)
items = other.items->clone_tuple_struct_items ();
else
items = nullptr;
rust_assert (other.items != nullptr);
items = other.items->clone_tuple_struct_items ();
return *this;
}
@@ -1164,13 +1197,22 @@ public:
void accept_vis (ASTVisitor &vis) override;
std::unique_ptr<TupleStructItems> &get_items () { return items; }
TupleStructItems &get_items ()
{
rust_assert (items != nullptr);
return *items;
}
PathInExpression &get_path () { return path; }
const PathInExpression &get_path () const { return path; }
NodeId get_node_id () const override { return node_id; }
Pattern::Kind get_pattern_kind () override
{
return Pattern::Kind::TupleStruct;
}
protected:
/* Use covariance to implement clone function as returning this object rather
* than base */
@@ -1358,7 +1400,6 @@ protected:
// AST node representing a tuple pattern
class TuplePattern : public Pattern
{
// bool has_tuple_pattern_items;
std::unique_ptr<TuplePatternItems> items;
location_t locus;
NodeId node_id;
@@ -1366,21 +1407,21 @@ class TuplePattern : public Pattern
public:
std::string as_string () const override;
// Returns true if the tuple pattern has items
bool has_tuple_pattern_items () const { return items != nullptr; }
TuplePattern (std::unique_ptr<TuplePatternItems> items, location_t locus)
: items (std::move (items)), locus (locus),
node_id (Analysis::Mappings::get ()->get_next_node_id ())
{}
node_id (Analysis::Mappings::get ().get_next_node_id ())
{
rust_assert (this->items != nullptr);
}
// Copy constructor requires clone
TuplePattern (TuplePattern const &other) : locus (other.locus)
{
// guard to prevent null dereference
rust_assert (other.items != nullptr);
node_id = other.node_id;
if (other.items != nullptr)
items = other.items->clone_tuple_pattern_items ();
items = other.items->clone_tuple_pattern_items ();
}
// Overload assignment operator to clone
@@ -1390,11 +1431,9 @@ public:
node_id = other.node_id;
// guard to prevent null dereference
if (other.items != nullptr)
items = other.items->clone_tuple_pattern_items ();
else
items = nullptr;
rust_assert (other.items != nullptr);
items = other.items->clone_tuple_pattern_items ();
return *this;
}
@@ -1403,14 +1442,16 @@ public:
void accept_vis (ASTVisitor &vis) override;
// TODO: seems kinda dodgy. Think of better way.
std::unique_ptr<TuplePatternItems> &get_items ()
TuplePatternItems &get_items ()
{
rust_assert (has_tuple_pattern_items ());
return items;
rust_assert (items != nullptr);
return *items;
}
NodeId get_node_id () const override { return node_id; }
Pattern::Kind get_pattern_kind () override { return Pattern::Kind::Tuple; }
protected:
/* Use covariance to implement clone function as returning this object rather
* than base */
@@ -1435,7 +1476,7 @@ public:
GroupedPattern (std::unique_ptr<Pattern> pattern_in_parens, location_t locus)
: pattern_in_parens (std::move (pattern_in_parens)), locus (locus),
node_id (Analysis::Mappings::get ()->get_next_node_id ())
node_id (Analysis::Mappings::get ().get_next_node_id ())
{}
// Copy constructor uses clone
@@ -1463,14 +1504,16 @@ public:
void accept_vis (ASTVisitor &vis) override;
// TODO: seems kinda dodgy. Think of better way.
std::unique_ptr<Pattern> &get_pattern_in_parens ()
Pattern &get_pattern_in_parens ()
{
rust_assert (pattern_in_parens != nullptr);
return pattern_in_parens;
return *pattern_in_parens;
}
NodeId get_node_id () const override { return node_id; }
Pattern::Kind get_pattern_kind () override { return Pattern::Kind::Grouped; }
protected:
/* Use covariance to implement clone function as returning this object rather
* than base */
@@ -1492,7 +1535,7 @@ public:
SlicePattern (std::vector<std::unique_ptr<Pattern>> items, location_t locus)
: items (std::move (items)), locus (locus),
node_id (Analysis::Mappings::get ()->get_next_node_id ())
node_id (Analysis::Mappings::get ().get_next_node_id ())
{}
// Copy constructor with vector clone
@@ -1535,6 +1578,8 @@ public:
NodeId get_node_id () const override { return node_id; }
Pattern::Kind get_pattern_kind () override { return Pattern::Kind::Slice; }
protected:
/* Use covariance to implement clone function as returning this object rather
* than base */
@@ -1557,7 +1602,7 @@ public:
AltPattern (std::vector<std::unique_ptr<Pattern>> alts, location_t locus)
: alts (std::move (alts)), locus (locus),
node_id (Analysis::Mappings::get ()->get_next_node_id ())
node_id (Analysis::Mappings::get ().get_next_node_id ())
{}
// Copy constructor with vector clone
@@ -1600,6 +1645,8 @@ public:
NodeId get_node_id () const override { return node_id; }
Pattern::Kind get_pattern_kind () override { return Pattern::Kind::Alt; }
protected:
/* Use covariance to implement clone function as returning this object rather
* than base */
@@ -1610,7 +1657,7 @@ protected:
};
// Moved definition to rust-path.h
class PathPattern;
class Path;
// Forward decls for paths (defined in rust-path.h)
class PathInExpression;

View File

@@ -19,9 +19,11 @@
#ifndef RUST_AST_STATEMENT_H
#define RUST_AST_STATEMENT_H
#include "optional.h"
#include "rust-ast.h"
#include "rust-path.h"
#include "rust-expr.h"
#include "rust-system.h"
namespace Rust {
namespace AST {
@@ -71,6 +73,8 @@ class LetStmt : public Stmt
// bool has_init_expr;
std::unique_ptr<Expr> init_expr;
tl::optional<std::unique_ptr<Expr>> else_expr;
location_t locus;
public:
@@ -84,15 +88,18 @@ public:
// Returns whether let statement has an initialisation expression.
bool has_init_expr () const { return init_expr != nullptr; }
bool has_else_expr () const { return else_expr.has_value (); }
std::string as_string () const override;
LetStmt (std::unique_ptr<Pattern> variables_pattern,
std::unique_ptr<Expr> init_expr, std::unique_ptr<Type> type,
tl::optional<std::unique_ptr<Expr>> else_expr,
std::vector<Attribute> outer_attrs, location_t locus)
: outer_attrs (std::move (outer_attrs)),
variables_pattern (std::move (variables_pattern)),
type (std::move (type)), init_expr (std::move (init_expr)), locus (locus)
type (std::move (type)), init_expr (std::move (init_expr)),
else_expr (std::move (else_expr)), locus (locus)
{}
// Copy constructor with clone
@@ -106,6 +113,9 @@ public:
// guard to prevent null dereference (always required)
if (other.init_expr != nullptr)
init_expr = other.init_expr->clone_expr ();
if (other.else_expr.has_value ())
else_expr = other.else_expr.value ()->clone_expr ();
if (other.type != nullptr)
type = other.type->clone_type ();
}
@@ -127,6 +137,12 @@ public:
init_expr = other.init_expr->clone_expr ();
else
init_expr = nullptr;
if (other.else_expr != nullptr)
else_expr = other.else_expr.value ()->clone_expr ();
else
else_expr = tl::nullopt;
if (other.type != nullptr)
type = other.type->clone_type ();
else
@@ -155,19 +171,43 @@ public:
const std::vector<Attribute> &get_outer_attrs () const { return outer_attrs; }
// TODO: is this better? Or is a "vis_block" better?
std::unique_ptr<Expr> &get_init_expr ()
Expr &get_init_expr ()
{
rust_assert (has_init_expr ());
return *init_expr;
}
Expr &get_else_expr ()
{
rust_assert (has_else_expr ());
return *else_expr.value ();
}
std::unique_ptr<Expr> &get_init_expr_ptr ()
{
rust_assert (has_init_expr ());
return init_expr;
}
std::unique_ptr<Pattern> &get_pattern ()
std::unique_ptr<Expr> &get_else_expr_ptr ()
{
rust_assert (variables_pattern != nullptr);
return variables_pattern;
rust_assert (has_else_expr ());
return else_expr.value ();
}
std::unique_ptr<Type> &get_type ()
Pattern &get_pattern ()
{
rust_assert (variables_pattern != nullptr);
return *variables_pattern;
}
Type &get_type ()
{
rust_assert (has_type ());
return *type;
}
std::unique_ptr<Type> &get_type_ptr ()
{
rust_assert (has_type ());
return type;
@@ -249,12 +289,24 @@ public:
bool is_marked_for_strip () const override { return expr == nullptr; }
// TODO: is this better? Or is a "vis_block" better?
std::unique_ptr<Expr> &get_expr ()
Expr &get_expr ()
{
rust_assert (expr != nullptr);
return *expr;
}
std::unique_ptr<Expr> &get_expr_ptr ()
{
rust_assert (expr != nullptr);
return expr;
}
std::unique_ptr<Expr> take_expr ()
{
rust_assert (expr != nullptr);
return std::move (expr);
}
bool is_semicolon_followed () const { return semicolon_followed; }
protected:

View File

@@ -48,11 +48,16 @@ public:
std::vector<LifetimeParam> &get_for_lifetimes () { return for_lifetimes; }
const std::vector<LifetimeParam> &get_for_lifetimes () const
{
return for_lifetimes;
}
TraitBound (TypePath type_path, location_t locus, bool in_parens = false,
bool opening_question_mark = false,
std::vector<LifetimeParam> for_lifetimes
= std::vector<LifetimeParam> ())
: TypeParamBound (Analysis::Mappings::get ()->get_next_node_id ()),
: TypeParamBound (Analysis::Mappings::get ().get_next_node_id ()),
in_parens (in_parens), opening_question_mark (opening_question_mark),
for_lifetimes (std::move (for_lifetimes)),
type_path (std::move (type_path)), locus (locus)
@@ -68,6 +73,13 @@ public:
type_path (std::move (type_path)), locus (locus)
{}
TraitBound (TraitBound const &other)
: TypeParamBound (other.get_node_id ()), in_parens (other.in_parens),
opening_question_mark (other.opening_question_mark),
for_lifetimes (other.for_lifetimes), type_path (other.type_path),
locus (other.locus)
{}
std::string as_string () const override;
location_t get_locus () const override final { return locus; }
@@ -81,6 +93,11 @@ public:
bool is_in_parens () const { return in_parens; }
bool has_opening_question_mark () const { return opening_question_mark; }
TypeParamBoundType get_bound_type () const override
{
return TypeParamBound::TypeParamBoundType::TRAIT;
}
protected:
/* Use covariance to implement clone function as returning this object rather
* than base */
@@ -295,33 +312,31 @@ public:
// Impl trait with a single bound? Poor reference material here.
class ImplTraitTypeOneBound : public TypeNoBounds
{
TraitBound trait_bound;
std::unique_ptr<TypeParamBound> trait_bound;
location_t locus;
protected:
/* Use covariance to implement clone function as returning this object rather
* than base */
ImplTraitTypeOneBound *clone_type_no_bounds_impl () const override
{
return new ImplTraitTypeOneBound (*this);
}
public:
ImplTraitTypeOneBound (TraitBound trait_bound, location_t locus)
ImplTraitTypeOneBound (std::unique_ptr<TypeParamBound> trait_bound,
location_t locus)
: trait_bound (std::move (trait_bound)), locus (locus)
{}
ImplTraitTypeOneBound (ImplTraitTypeOneBound const &other)
: trait_bound (other.trait_bound->clone_type_param_bound ()),
locus (other.locus)
{}
std::string as_string () const override;
location_t get_locus () const override final { return locus; }
void accept_vis (ASTVisitor &vis) override;
// TODO: would a "vis_type" be better?
TraitBound &get_trait_bound ()
std::unique_ptr<TypeParamBound> &get_trait_bound () { return trait_bound; }
TypeNoBounds *clone_type_no_bounds_impl () const override
{
// TODO: check to ensure invariants are met?
return trait_bound;
return new ImplTraitTypeOneBound (*this);
}
};
@@ -513,12 +528,15 @@ public:
void accept_vis (ASTVisitor &vis) override;
// TODO: would a "vis_type" be better?
std::unique_ptr<TypeNoBounds> &get_type_pointed_to ()
TypeNoBounds &get_type_pointed_to ()
{
rust_assert (type != nullptr);
return type;
return *type;
}
// Getter for direct access to the type unique_ptr
std::unique_ptr<TypeNoBounds> &get_type_ptr () { return type; }
protected:
/* Use covariance to implement clone function as returning this object rather
* than base */
@@ -532,7 +550,7 @@ protected:
class ReferenceType : public TypeNoBounds
{
// bool has_lifetime; // TODO: handle in lifetime or something?
Lifetime lifetime;
tl::optional<Lifetime> lifetime;
bool has_mut;
std::unique_ptr<TypeNoBounds> type;
@@ -543,11 +561,12 @@ public:
bool is_mut () const { return has_mut; }
// Returns whether the reference has a lifetime.
bool has_lifetime () const { return !lifetime.is_error (); }
bool has_lifetime () const { return lifetime.has_value (); }
// Constructor
ReferenceType (bool is_mut, std::unique_ptr<TypeNoBounds> type_no_bounds,
location_t locus, Lifetime lifetime = Lifetime::elided ())
location_t locus,
tl::optional<Lifetime> lifetime = Lifetime::elided ())
: lifetime (std::move (lifetime)), has_mut (is_mut),
type (std::move (type_no_bounds)), locus (locus)
{}
@@ -580,17 +599,21 @@ public:
void accept_vis (ASTVisitor &vis) override;
// TODO: would a "vis_type" be better?
std::unique_ptr<TypeNoBounds> &get_type_referenced ()
TypeNoBounds &get_type_referenced ()
{
rust_assert (type != nullptr);
return type;
return *type;
}
bool get_has_mut () const { return has_mut; }
Lifetime &get_lifetime () { return lifetime; }
Lifetime &get_lifetime () { return lifetime.value (); }
const Lifetime &get_lifetime () const { return lifetime.value (); }
std::unique_ptr<TypeNoBounds> &get_base_type () { return type; }
TypeNoBounds &get_base_type () { return *type; }
// Getter for direct access to the type unique_ptr
std::unique_ptr<TypeNoBounds> &get_type_ptr () { return type; }
protected:
/* Use covariance to implement clone function as returning this object rather
@@ -641,19 +664,24 @@ public:
void accept_vis (ASTVisitor &vis) override;
// TODO: would a "vis_type" be better?
std::unique_ptr<Type> &get_elem_type ()
Type &get_elem_type ()
{
rust_assert (elem_type != nullptr);
return elem_type;
return *elem_type;
}
// TODO: would a "vis_expr" be better?
std::unique_ptr<Expr> &get_size_expr ()
Expr &get_size_expr ()
{
rust_assert (size != nullptr);
return size;
return *size;
}
std::unique_ptr<Type> &get_element_type () { return elem_type; }
// Additional getter for direct access to the size expr unique_ptr
std::unique_ptr<Expr> &get_size_ptr () { return size; }
protected:
/* Use covariance to implement clone function as returning this object rather
* than base */
@@ -701,12 +729,15 @@ public:
void accept_vis (ASTVisitor &vis) override;
// TODO: would a "vis_type" be better?
std::unique_ptr<Type> &get_elem_type ()
Type &get_elem_type ()
{
rust_assert (elem_type != nullptr);
return elem_type;
return *elem_type;
}
// Getter for direct access to the elem_type unique_ptr
std::unique_ptr<Type> &get_elem_type_ptr () { return elem_type; }
protected:
/* Use covariance to implement clone function as returning this object rather
* than base */
@@ -824,7 +855,13 @@ public:
const std::vector<Attribute> &get_outer_attrs () const { return outer_attrs; }
// TODO: would a "vis_type" be better?
std::unique_ptr<Type> &get_type ()
Type &get_type ()
{
rust_assert (param_type != nullptr);
return *param_type;
}
std::unique_ptr<Type> &get_type_ptr ()
{
rust_assert (param_type != nullptr);
return param_type;
@@ -935,10 +972,10 @@ public:
}
// TODO: would a "vis_type" be better?
std::unique_ptr<TypeNoBounds> &get_return_type ()
TypeNoBounds &get_return_type ()
{
rust_assert (has_return_type ());
return return_type;
return *return_type;
}
FunctionQualifiers &get_function_qualifiers () { return function_qualifiers; }

View File

@@ -0,0 +1,199 @@
#include "rust-compile-asm.h"
#include "rust-compile-expr.h"
#include "rust-system.h"
namespace Rust {
namespace Compile {
CompileAsm::CompileAsm (Context *ctx) : HIRCompileBase (ctx) {}
tree
CompileAsm::tree_codegen_asm (HIR::InlineAsm &expr)
{
auto asm_expr
= asm_build_stmt (expr.get_locus (), {asm_construct_string_tree (expr),
asm_construct_outputs (expr),
asm_construct_inputs (expr),
asm_construct_clobber_tree (expr),
asm_construct_label_tree (expr)});
ASM_INPUT_P (asm_expr) = expr.is_simple_asm ();
ASM_VOLATILE_P (asm_expr) = false;
ASM_INLINE_P (asm_expr) = expr.is_inline_asm ();
/*Backend::debug (asm_expr);*/
return asm_expr;
}
tree
CompileAsm::asm_build_stmt (
location_t loc,
const std::array<tree, CompileAsm::ASM_TREE_ARRAY_LENGTH> &trees)
{
// Prototype functiion for building an ASM_EXPR tree.
tree ret;
bool side_effects;
ret = make_node (ASM_EXPR);
TREE_TYPE (ret) = void_type_node;
SET_EXPR_LOCATION (ret, loc);
/* TREE_SIDE_EFFECTS will already be set for statements with
implicit side effects. Here we make sure it is set for other
expressions by checking whether the parameters have side
effects. */
// This is here because of c-typeck.cc's code
// I'm not sure what kind of effects it has
side_effects = false;
for (size_t i = 0; i < trees.size (); i++)
{
tree t = trees[i];
if (t && !TYPE_P (t))
side_effects |= TREE_SIDE_EFFECTS (t);
TREE_OPERAND (ret, i) = t;
}
TREE_SIDE_EFFECTS (ret) |= side_effects;
return ret;
}
tree
CompileAsm::asm_construct_string_tree (HIR::InlineAsm &expr)
{
// To construct an ASM_EXPR tree, we need to build a STRING_CST tree.
//
// We do this by concatenating all the template strings in the InlineAsm
// into one big std::string seperated by tabs and newlines. (For easier
// debugging and reading)
std::stringstream ss;
for (const auto &template_str : expr.template_strs)
ss << template_str.symbol << "\n";
std::string result = ss.str ();
return Backend::string_constant_expression (result);
}
tree
CompileAsm::asm_construct_outputs (HIR::InlineAsm &expr)
{
// TODO: Do i need to do this?
tree head = NULL_TREE;
for (auto &output : expr.get_operands ())
{
if (output.get_register_type ()
== AST::InlineAsmOperand::RegisterType::Out)
{
auto out = output.get_out ();
tree out_tree = CompileExpr::Compile (*out.expr, this->ctx);
// expects a tree list
// TODO: This assumes that the output is a register
std::string expr_name = "=r";
auto name = build_string (expr_name.size () + 1, expr_name.c_str ());
head
= chainon (head, build_tree_list (build_tree_list (NULL_TREE, name),
out_tree));
/*Backend::debug (head);*/
/*head = chainon (head, out_tree);*/
}
}
return head;
}
tree
CompileAsm::asm_construct_inputs (HIR::InlineAsm &expr)
{
// TODO: Do i need to do this?
tree head = NULL_TREE;
for (auto &input : expr.get_operands ())
{
if (input.get_register_type () == AST::InlineAsmOperand::RegisterType::In)
{
auto in = input.get_in ();
tree in_tree = CompileExpr::Compile (*in.expr, this->ctx);
// expects a tree list
// TODO: This assumes that the input is a register
std::string expr_name = "r";
auto name = build_string (expr_name.size () + 1, expr_name.c_str ());
head
= chainon (head, build_tree_list (build_tree_list (NULL_TREE, name),
in_tree));
/*head = chainon (head, out_tree);*/
}
}
return head;
}
tree
CompileAsm::asm_construct_clobber_tree (HIR::InlineAsm &expr)
{
// TODO: Do i need to do this?
return NULL_TREE;
}
tree
CompileAsm::asm_construct_label_tree (HIR::InlineAsm &expr)
{
// TODO: Do i need to do this?
return NULL_TREE;
}
CompileLlvmAsm::CompileLlvmAsm (Context *ctx) : HIRCompileBase (ctx) {}
tree
CompileLlvmAsm::construct_operands (std::vector<HIR::LlvmOperand> operands)
{
tree head = NULL_TREE;
for (auto &operand : operands)
{
tree t = CompileExpr::Compile (*operand.expr, this->ctx);
auto name = build_string (operand.constraint.size () + 1,
operand.constraint.c_str ());
head = chainon (head,
build_tree_list (build_tree_list (NULL_TREE, name), t));
}
return head;
}
tree
CompileLlvmAsm::construct_clobbers (std::vector<AST::TupleClobber> clobbers)
{
tree head = NULL_TREE;
for (auto &clobber : clobbers)
{
auto name
= build_string (clobber.symbol.size () + 1, clobber.symbol.c_str ());
head = chainon (head, build_tree_list (NULL_TREE, name));
}
return head;
}
tree
CompileLlvmAsm::tree_codegen_asm (HIR::LlvmInlineAsm &expr)
{
tree ret = make_node (ASM_EXPR);
TREE_TYPE (ret) = void_type_node;
SET_EXPR_LOCATION (ret, expr.get_locus ());
ASM_VOLATILE_P (ret) = expr.options.is_volatile;
std::stringstream ss;
for (const auto &template_str : expr.templates)
{
ss << template_str.symbol << "\n";
}
ASM_STRING (ret) = Backend::string_constant_expression (ss.str ());
ASM_INPUTS (ret) = construct_operands (expr.inputs);
ASM_OUTPUTS (ret) = construct_operands (expr.outputs);
ASM_CLOBBERS (ret) = construct_clobbers (expr.get_clobbers ());
return ret;
}
} // namespace Compile
} // namespace Rust

View File

@@ -0,0 +1,75 @@
// Copyright (C) 2020-2024 Free Software Foundation, Inc.
// This file is part of GCC.
// GCC is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 3, or (at your option) any later
// version.
// GCC is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
// for more details.
// You should have received a copy of the GNU General Public License
// along with GCC; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
#ifndef RUST_COMPILE_ASM
#define RUST_COMPILE_ASM
#include "rust-compile-base.h"
#include "rust-hir-visitor.h"
namespace Rust {
namespace Compile {
class CompileAsm : private HIRCompileBase
{
private:
// RELEVANT MEMBER FUNCTIONS
// The limit is 5 because it stands for the 5 things that the C version of
// build_asm_expr accepts: string, output, input, clobber and label.
// The function signature is
//
// tree
// build_asm_expr (location_t loc, tree string, tree outputs, tree inputs,
// tree clobbers, tree labels, bool simple, bool is_inline)
static const int ASM_TREE_ARRAY_LENGTH = 5;
tree asm_build_stmt (location_t,
const std::array<tree, ASM_TREE_ARRAY_LENGTH> &);
tree asm_construct_string_tree (HIR::InlineAsm &);
tree asm_construct_outputs (HIR::InlineAsm &);
tree asm_construct_inputs (HIR::InlineAsm &);
tree asm_construct_clobber_tree (HIR::InlineAsm &);
tree asm_construct_label_tree (HIR::InlineAsm &);
public:
// WE WILL OPEN THIS UP WHEN WE WANT TO ADD A DEDICATED PASS OF HIR'S ASM
// translation.
// static tree Compile (HIR::Expr *expr, Context *ctx);
CompileAsm (Context *ctx);
tree tree_codegen_asm (HIR::InlineAsm &);
};
class CompileLlvmAsm : private HIRCompileBase
{
private:
tree construct_operands (std::vector<HIR::LlvmOperand> operands);
tree construct_clobbers (std::vector<AST::TupleClobber>);
public:
CompileLlvmAsm (Context *ctx);
tree tree_codegen_asm (HIR::LlvmInlineAsm &);
};
} // namespace Compile
} // namespace Rust
#endif // RUST_COMPILE_ASM

View File

@@ -25,12 +25,14 @@
#include "rust-compile-type.h"
#include "rust-constexpr.h"
#include "rust-diagnostics.h"
#include "rust-expr.h" // for AST::AttrInputLiteral
#include "rust-expr.h" // for AST::AttrInputLiteral
#include "rust-hir-map.h"
#include "rust-macro.h" // for AST::MetaNameValueStr
#include "rust-hir-path-probe.h"
#include "rust-type-util.h"
#include "rust-compile-implitem.h"
#include "rust-attribute-values.h"
#include "rust-immutable-name-resolution-context.h"
#include "fold-const.h"
#include "stringpool.h"
@@ -38,6 +40,9 @@
#include "tree.h"
#include "print-tree.h"
// rust-name-resolution-2.0
#include "options.h"
namespace Rust {
namespace Compile {
@@ -544,7 +549,7 @@ HIRCompileBase::mark_addressable (tree exp, location_t locus)
}
tree
HIRCompileBase::address_expression (tree expr, location_t location)
HIRCompileBase::address_expression (tree expr, location_t location, tree ptrty)
{
if (expr == error_mark_node)
return error_mark_node;
@@ -552,7 +557,22 @@ HIRCompileBase::address_expression (tree expr, location_t location)
if (!mark_addressable (expr, location))
return error_mark_node;
return build_fold_addr_expr_loc (location, expr);
if (ptrty == NULL || ptrty == error_mark_node)
ptrty = build_pointer_type (TREE_TYPE (expr));
return build_fold_addr_expr_with_type_loc (location, expr, ptrty);
}
tree
HIRCompileBase::compile_constant_expr (
Context *ctx, HirId coercion_id, TyTy::BaseType *resolved_type,
TyTy::BaseType *expected_type, const Resolver::CanonicalPath &canonical_path,
HIR::Expr &const_value_expr, location_t locus, location_t expr_locus)
{
HIRCompileBase c (ctx);
return c.compile_constant_item (coercion_id, resolved_type, expected_type,
canonical_path, const_value_expr, locus,
expr_locus);
}
tree
@@ -581,8 +601,9 @@ HIRCompileBase::compile_function_body (tree fndecl,
if (function_body.has_expr ())
{
location_t locus = function_body.get_final_expr ()->get_locus ();
tree return_value = CompileExpr::Compile (function_body.expr.get (), ctx);
location_t locus = function_body.get_final_expr ().get_locus ();
tree return_value
= CompileExpr::Compile (function_body.get_final_expr (), ctx);
// we can only return this if non unit value return type
if (!fn_return_ty->is_unit ())
@@ -610,7 +631,7 @@ HIRCompileBase::compile_function_body (tree fndecl,
ctx->add_statement (return_value);
// now just return unit expression
tree unit_expr = unit_expression (ctx, locus);
tree unit_expr = unit_expression (locus);
tree return_stmt
= Backend::return_statement (fndecl, unit_expr, locus);
ctx->add_statement (return_stmt);
@@ -621,7 +642,7 @@ HIRCompileBase::compile_function_body (tree fndecl,
// we can only do this if the function is of unit type otherwise other
// errors should have occurred
location_t locus = function_body.get_locus ();
tree return_value = unit_expression (ctx, locus);
tree return_value = unit_expression (locus);
tree return_stmt
= Backend::return_statement (fndecl, return_value, locus);
ctx->add_statement (return_stmt);
@@ -645,20 +666,32 @@ get_abi (const AST::AttrVec &outer_attrs,
tree
HIRCompileBase::compile_function (
const std::string &fn_name, HIR::SelfParam &self_param,
bool is_root_item, const std::string &fn_name,
tl::optional<HIR::SelfParam> &self_param,
std::vector<HIR::FunctionParam> &function_params,
const HIR::FunctionQualifiers &qualifiers, HIR::Visibility &visibility,
AST::AttrVec &outer_attrs, location_t locus, HIR::BlockExpr *function_body,
const Resolver::CanonicalPath *canonical_path, TyTy::FnType *fntype)
const Resolver::CanonicalPath &canonical_path, TyTy::FnType *fntype)
{
tree compiled_fn_type = TyTyResolveCompile::compile (ctx, fntype);
std::string ir_symbol_name
= canonical_path->get () + fntype->subst_as_string ();
= canonical_path.get () + fntype->subst_as_string ();
// we don't mangle the main fn since we haven't implemented the main shim
bool is_main_fn = fn_name.compare ("main") == 0;
bool is_main_fn = fn_name.compare ("main") == 0 && is_root_item;
if (is_main_fn)
{
rust_assert (!main_identifier_node);
/* So that 'MAIN_NAME_P' works. */
main_identifier_node = get_identifier (ir_symbol_name.c_str ());
}
std::string asm_name = fn_name;
auto &mappings = Analysis::Mappings::get ();
if (flag_name_resolution_2_0)
ir_symbol_name = mappings.get_current_crate_name () + "::" + ir_symbol_name;
unsigned int flags = 0;
tree fndecl = Backend::function (compiled_fn_type, ir_symbol_name,
"" /* asm_name */, flags, locus);
@@ -670,7 +703,7 @@ HIRCompileBase::compile_function (
// conditionally mangle the function name
bool should_mangle = should_mangle_item (fndecl);
if (!is_main_fn && should_mangle)
asm_name = ctx->mangle_item (fntype, *canonical_path);
asm_name = ctx->mangle_item (fntype, canonical_path);
SET_DECL_ASSEMBLER_NAME (fndecl,
get_identifier_with_length (asm_name.data (),
asm_name.length ()));
@@ -681,39 +714,39 @@ HIRCompileBase::compile_function (
// setup the params
TyTy::BaseType *tyret = fntype->get_return_type ();
std::vector<Bvariable *> param_vars;
if (!self_param.is_error ())
if (self_param)
{
rust_assert (fntype->is_method ());
TyTy::BaseType *self_tyty_lookup = fntype->get_self_type ();
tree self_type = TyTyResolveCompile::compile (ctx, self_tyty_lookup);
Bvariable *compiled_self_param
= CompileSelfParam::compile (ctx, fndecl, self_param, self_type,
self_param.get_locus ());
= CompileSelfParam::compile (ctx, fndecl, self_param.value (),
self_type, self_param->get_locus ());
param_vars.push_back (compiled_self_param);
ctx->insert_var_decl (self_param.get_mappings ().get_hirid (),
ctx->insert_var_decl (self_param->get_mappings ().get_hirid (),
compiled_self_param);
}
// offset from + 1 for the TyTy::FnType being used when this is a method to
// skip over Self on the FnType
bool is_method = !self_param.is_error ();
bool is_method = self_param.has_value ();
size_t i = is_method ? 1 : 0;
for (auto &referenced_param : function_params)
{
auto tyty_param = fntype->param_at (i++);
auto param_tyty = tyty_param.second;
auto &tyty_param = fntype->param_at (i++);
auto param_tyty = tyty_param.get_type ();
auto compiled_param_type = TyTyResolveCompile::compile (ctx, param_tyty);
location_t param_locus = referenced_param.get_locus ();
Bvariable *compiled_param_var
= CompileFnParam::compile (ctx, fndecl, &referenced_param,
= CompileFnParam::compile (ctx, fndecl, referenced_param,
compiled_param_type, param_locus);
param_vars.push_back (compiled_param_var);
const HIR::Pattern &param_pattern = *referenced_param.get_param_name ();
const HIR::Pattern &param_pattern = referenced_param.get_param_name ();
ctx->insert_var_decl (param_pattern.get_mappings ().get_hirid (),
compiled_param_var);
}
@@ -760,15 +793,20 @@ HIRCompileBase::compile_function (
tree
HIRCompileBase::compile_constant_item (
TyTy::BaseType *resolved_type, const Resolver::CanonicalPath *canonical_path,
HIR::Expr *const_value_expr, location_t locus)
HirId coercion_id, TyTy::BaseType *resolved_type,
TyTy::BaseType *expected_type, const Resolver::CanonicalPath &canonical_path,
HIR::Expr &const_value_expr, location_t locus, location_t expr_locus)
{
const std::string &ident = canonical_path->get ();
const std::string &ident = canonical_path.get ();
tree type = TyTyResolveCompile::compile (ctx, resolved_type);
tree const_type = build_qualified_type (type, TYPE_QUAL_CONST);
tree actual_type = TyTyResolveCompile::compile (ctx, expected_type);
tree actual_const_type = build_qualified_type (actual_type, TYPE_QUAL_CONST);
bool is_block_expr
= const_value_expr->get_expression_type () == HIR::Expr::ExprType::Block;
= const_value_expr.get_expression_type () == HIR::Expr::ExprType::Block;
// in order to compile a block expr we want to reuse as much existing
// machineary that we already have. This means the best approach is to
@@ -782,14 +820,14 @@ HIRCompileBase::compile_constant_item (
TREE_READONLY (fndecl) = 1;
tree enclosing_scope = NULL_TREE;
location_t start_location = const_value_expr->get_locus ();
location_t end_location = const_value_expr->get_locus ();
location_t start_location = const_value_expr.get_locus ();
location_t end_location = const_value_expr.get_locus ();
if (is_block_expr)
{
HIR::BlockExpr *function_body
= static_cast<HIR::BlockExpr *> (const_value_expr);
start_location = function_body->get_locus ();
end_location = function_body->get_end_locus ();
HIR::BlockExpr &function_body
= static_cast<HIR::BlockExpr &> (const_value_expr);
start_location = function_body.get_locus ();
end_location = function_body.get_end_locus ();
}
tree code_block = Backend::block (fndecl, enclosing_scope, {} /*locals*/,
@@ -807,9 +845,9 @@ HIRCompileBase::compile_constant_item (
if (is_block_expr)
{
HIR::BlockExpr *function_body
= static_cast<HIR::BlockExpr *> (const_value_expr);
compile_function_body (fndecl, *function_body, resolved_type);
HIR::BlockExpr &function_body
= static_cast<HIR::BlockExpr &> (const_value_expr);
compile_function_body (fndecl, function_body, resolved_type);
}
else
{
@@ -817,7 +855,7 @@ HIRCompileBase::compile_constant_item (
tree return_expr
= Backend::return_statement (fndecl, value,
const_value_expr->get_locus ());
const_value_expr.get_locus ());
ctx->add_statement (return_expr);
}
@@ -834,7 +872,11 @@ HIRCompileBase::compile_constant_item (
tree call = build_call_array_loc (locus, const_type, fndecl, 0, NULL);
tree folded_expr = fold_expr (call);
return named_constant_expression (const_type, ident, folded_expr, locus);
// coercion site
tree coerced = coercion_site (coercion_id, folded_expr, resolved_type,
expected_type, locus, expr_locus);
return named_constant_expression (actual_const_type, ident, coerced, locus);
}
tree
@@ -870,19 +912,18 @@ HIRCompileBase::resolve_method_address (TyTy::FnType *fntype,
// Now we can try and resolve the address since this might be a forward
// declared function, generic function which has not be compiled yet or
// its an not yet trait bound function
HIR::Item *resolved_item = ctx->get_mappings ()->lookup_defid (id);
if (resolved_item != nullptr)
if (auto resolved_item = ctx->get_mappings ().lookup_defid (id))
{
if (!fntype->has_substitutions_defined ())
return CompileItem::compile (resolved_item, ctx);
return CompileItem::compile (*resolved_item, ctx);
return CompileItem::compile (resolved_item, ctx, fntype);
return CompileItem::compile (*resolved_item, ctx, fntype);
}
// it might be resolved to a trait item
HIR::TraitItem *trait_item
= ctx->get_mappings ()->lookup_trait_item_defid (id);
HIR::Trait *trait = ctx->get_mappings ()->lookup_trait_item_mapping (
= ctx->get_mappings ().lookup_trait_item_defid (id).value ();
HIR::Trait *trait = ctx->get_mappings ().lookup_trait_item_mapping (
trait_item->get_mappings ().get_hirid ());
Resolver::TraitReference *trait_ref
@@ -984,7 +1025,7 @@ HIRCompileBase::resolve_method_address (TyTy::FnType *fntype,
}
tree
HIRCompileBase::unit_expression (Context *ctx, location_t locus)
HIRCompileBase::unit_expression (location_t locus)
{
tree unit_type = TyTyResolveCompile::get_unit_type (ctx);
return Backend::constructor_expression (unit_type, false, {}, -1, locus);

View File

@@ -29,7 +29,14 @@ class HIRCompileBase
public:
virtual ~HIRCompileBase () {}
static tree address_expression (tree expr, location_t locus);
static tree address_expression (tree expr, location_t locus,
tree ptrty = NULL_TREE);
static tree compile_constant_expr (
Context *ctx, HirId coercion_id, TyTy::BaseType *resolved_type,
TyTy::BaseType *expected_type,
const Resolver::CanonicalPath &canonical_path, HIR::Expr &const_value_expr,
location_t locus, location_t expr_locus);
protected:
HIRCompileBase (Context *ctx) : ctx (ctx) {}
@@ -90,19 +97,22 @@ protected:
void compile_function_body (tree fndecl, HIR::BlockExpr &function_body,
TyTy::BaseType *fn_return_ty);
tree compile_constant_item (TyTy::BaseType *resolved_type,
const Resolver::CanonicalPath *canonical_path,
HIR::Expr *const_value_expr, location_t locus);
tree compile_constant_item (HirId coercion_id, TyTy::BaseType *resolved_type,
TyTy::BaseType *expected_type,
const Resolver::CanonicalPath &canonical_path,
HIR::Expr &const_value_expr, location_t locus,
location_t expr_locus);
tree compile_function (const std::string &fn_name, HIR::SelfParam &self_param,
tree compile_function (bool is_root_item, const std::string &fn_name,
tl::optional<HIR::SelfParam> &self_param,
std::vector<HIR::FunctionParam> &function_params,
const HIR::FunctionQualifiers &qualifiers,
HIR::Visibility &visibility, AST::AttrVec &outer_attrs,
location_t locus, HIR::BlockExpr *function_body,
const Resolver::CanonicalPath *canonical_path,
const Resolver::CanonicalPath &canonical_path,
TyTy::FnType *fntype);
static tree unit_expression (Context *ctx, location_t locus);
tree unit_expression (location_t locus);
void setup_fndecl (tree fndecl, bool is_main_entry_point, bool is_generic_fn,
HIR::Visibility &visibility,

View File

@@ -19,6 +19,7 @@
#include "rust-compile-block.h"
#include "rust-compile-stmt.h"
#include "rust-compile-expr.h"
#include "rust-hir-expr.h"
namespace Rust {
namespace Compile {
@@ -28,10 +29,10 @@ CompileBlock::CompileBlock (Context *ctx, Bvariable *result)
{}
tree
CompileBlock::compile (HIR::BlockExpr *expr, Context *ctx, Bvariable *result)
CompileBlock::compile (HIR::BlockExpr &expr, Context *ctx, Bvariable *result)
{
CompileBlock compiler (ctx, result);
compiler.visit (*expr);
compiler.visit (expr);
return compiler.translated;
}
@@ -60,10 +61,10 @@ CompileBlock::visit (HIR::BlockExpr &expr)
if (expr.has_expr ())
{
tree compiled_expr = CompileExpr::Compile (expr.expr.get (), ctx);
tree compiled_expr = CompileExpr::Compile (expr.get_final_expr (), ctx);
if (result != nullptr)
{
location_t locus = expr.get_final_expr ()->get_locus ();
location_t locus = expr.get_final_expr ().get_locus ();
tree result_reference = Backend::var_expression (result, locus);
tree assignment
@@ -75,7 +76,7 @@ CompileBlock::visit (HIR::BlockExpr &expr)
else if (result != nullptr)
{
location_t locus = expr.get_locus ();
tree compiled_expr = unit_expression (ctx, expr.get_locus ());
tree compiled_expr = unit_expression (expr.get_locus ());
tree result_reference = Backend::var_expression (result, locus);
tree assignment
@@ -93,10 +94,8 @@ CompileConditionalBlocks::visit (HIR::IfExpr &expr)
{
fncontext fnctx = ctx->peek_fn ();
tree fndecl = fnctx.fndecl;
tree condition_expr
= CompileExpr::Compile (expr.get_if_condition ().get (), ctx);
tree then_block
= CompileBlock::compile (expr.get_if_block ().get (), ctx, result);
tree condition_expr = CompileExpr::Compile (expr.get_if_condition (), ctx);
tree then_block = CompileBlock::compile (expr.get_if_block (), ctx, result);
translated = Backend::if_statement (fndecl, condition_expr, then_block, NULL,
expr.get_locus ());
@@ -107,23 +106,20 @@ CompileConditionalBlocks::visit (HIR::IfExprConseqElse &expr)
{
fncontext fnctx = ctx->peek_fn ();
tree fndecl = fnctx.fndecl;
tree condition_expr
= CompileExpr::Compile (expr.get_if_condition ().get (), ctx);
tree then_block
= CompileBlock::compile (expr.get_if_block ().get (), ctx, result);
tree condition_expr = CompileExpr::Compile (expr.get_if_condition (), ctx);
tree then_block = CompileBlock::compile (expr.get_if_block (), ctx, result);
// else block
std::vector<Bvariable *> locals;
location_t start_location = expr.get_else_block ()->get_locus ();
location_t end_location = expr.get_else_block ()->get_locus (); // FIXME
location_t start_location = expr.get_else_block ().get_locus ();
location_t end_location = expr.get_else_block ().get_locus (); // FIXME
tree enclosing_scope = ctx->peek_enclosing_scope ();
tree else_block = Backend::block (fndecl, enclosing_scope, locals,
start_location, end_location);
ctx->push_block (else_block);
tree else_stmt_decl
= CompileExprWithBlock::compile (expr.get_else_block ().get (), ctx,
result);
= CompileExprWithBlock::compile (&expr.get_else_block (), ctx, result);
ctx->add_statement (else_stmt_decl);

View File

@@ -28,7 +28,7 @@ namespace Compile {
class CompileBlock : private HIRCompileBase
{
public:
static tree compile (HIR::BlockExpr *expr, Context *ctx, Bvariable *result);
static tree compile (HIR::BlockExpr &expr, Context *ctx, Bvariable *result);
protected:
void visit (HIR::BlockExpr &expr);
@@ -83,6 +83,8 @@ public:
void visit (HIR::MethodCallExpr &) override {}
void visit (HIR::FieldAccessExpr &) override {}
void visit (HIR::BlockExpr &) override {}
void visit (HIR::AnonConst &) override {}
void visit (HIR::ConstBlock &) override {}
void visit (HIR::ContinueExpr &) override {}
void visit (HIR::BreakExpr &) override {}
void visit (HIR::RangeFromToExpr &) override {}
@@ -96,11 +98,11 @@ public:
void visit (HIR::LoopExpr &) override {}
void visit (HIR::WhileLoopExpr &) override {}
void visit (HIR::WhileLetLoopExpr &) override {}
void visit (HIR::IfLetExpr &) override {}
void visit (HIR::IfLetExprConseqElse &) override {}
void visit (HIR::MatchExpr &) override {}
void visit (HIR::AwaitExpr &) override {}
void visit (HIR::AsyncBlockExpr &) override {}
void visit (HIR::InlineAsm &) override {}
void visit (HIR::LlvmInlineAsm &) override {}
private:
CompileConditionalBlocks (Context *ctx, Bvariable *result)
@@ -135,7 +137,13 @@ public:
void visit (HIR::BlockExpr &expr) override
{
translated = CompileBlock::compile (&expr, ctx, result);
translated = CompileBlock::compile (expr, ctx, result);
}
void visit (HIR::ConstBlock &expr) override
{
rust_unreachable ();
// translated = CompileExpr::compile (expr, ctx, result);
}
// Empty visit for unused Expression HIR nodes.
@@ -179,11 +187,12 @@ public:
void visit (HIR::LoopExpr &) override {}
void visit (HIR::WhileLoopExpr &) override {}
void visit (HIR::WhileLetLoopExpr &) override {}
void visit (HIR::IfLetExpr &) override {}
void visit (HIR::IfLetExprConseqElse &) override {}
void visit (HIR::MatchExpr &) override {}
void visit (HIR::AwaitExpr &) override {}
void visit (HIR::AsyncBlockExpr &) override {}
void visit (HIR::InlineAsm &) override {}
void visit (HIR::LlvmInlineAsm &) override {}
void visit (HIR::AnonConst &) override {}
private:
CompileExprWithBlock (Context *ctx, Bvariable *result)

View File

@@ -33,19 +33,8 @@ Context::Context ()
void
Context::setup_builtins ()
{
auto builtins = resolver->get_builtin_types ();
for (auto it = builtins.begin (); it != builtins.end (); it++)
{
HirId ref;
bool ok = tyctx->lookup_type_by_node_id ((*it)->get_node_id (), &ref);
rust_assert (ok);
TyTy::BaseType *lookup;
ok = tyctx->lookup_type (ref, &lookup);
rust_assert (ok);
TyTyResolveCompile::compile (this, lookup);
}
for (auto &builtin : tyctx->get_builtins ())
TyTyResolveCompile::compile (this, builtin.get ());
}
hashval_t

View File

@@ -27,6 +27,7 @@
#include "rust-hir-full.h"
#include "rust-mangle.h"
#include "rust-tree.h"
#include "rust-immutable-name-resolution-context.h"
namespace Rust {
namespace Compile {
@@ -71,7 +72,10 @@ public:
return it->second;
compiled_type_map.insert ({h, type});
push_type (type);
if (TYPE_NAME (type) != NULL)
push_type (type);
return type;
}
@@ -88,7 +92,7 @@ public:
Resolver::Resolver *get_resolver () { return resolver; }
Resolver::TypeCheckContext *get_tyctx () { return tyctx; }
Analysis::Mappings *get_mappings () { return mappings; }
Analysis::Mappings &get_mappings () { return mappings; }
void push_block (tree scope)
{
@@ -389,7 +393,7 @@ public:
private:
Resolver::Resolver *resolver;
Resolver::TypeCheckContext *tyctx;
Analysis::Mappings *mappings;
Analysis::Mappings &mappings;
Mangler mangler;
// state

File diff suppressed because it is too large Load Diff

View File

@@ -28,7 +28,7 @@ namespace Compile {
class CompileExpr : private HIRCompileBase, protected HIR::HIRExpressionVisitor
{
public:
static tree Compile (HIR::Expr *expr, Context *ctx);
static tree Compile (HIR::Expr &expr, Context *ctx);
void visit (HIR::TupleIndexExpr &expr) override;
void visit (HIR::TupleExpr &expr) override;
@@ -48,6 +48,8 @@ public:
void visit (HIR::IfExpr &expr) override;
void visit (HIR::IfExprConseqElse &expr) override;
void visit (HIR::BlockExpr &expr) override;
void visit (HIR::AnonConst &expr) override;
void visit (HIR::ConstBlock &expr) override;
void visit (HIR::UnsafeBlockExpr &expr) override;
void visit (HIR::StructExprStruct &struct_expr) override;
void visit (HIR::StructExprStructFields &struct_expr) override;
@@ -68,6 +70,8 @@ public:
void visit (HIR::RangeFullExpr &expr) override;
void visit (HIR::RangeFromToInclExpr &expr) override;
void visit (HIR::ClosureExpr &expr) override;
void visit (HIR::InlineAsm &expr) override;
void visit (HIR::LlvmInlineAsm &expr) override;
// TODO
void visit (HIR::ErrorPropagationExpr &) override {}
@@ -76,8 +80,6 @@ public:
// TODO
// these need to be sugared in the HIR to if statements and a match
void visit (HIR::WhileLetLoopExpr &) override {}
void visit (HIR::IfLetExpr &) override {}
void visit (HIR::IfLetExprConseqElse &) override {}
// lets not worry about async yet....
void visit (HIR::AwaitExpr &) override {}
@@ -97,10 +99,12 @@ protected:
TyTy::BaseType *receiver, TyTy::FnType *fntype,
tree receiver_ref, location_t expr_locus);
tree
resolve_operator_overload (Analysis::RustLangItem::ItemType lang_item_type,
HIR::OperatorExprMeta expr, tree lhs, tree rhs,
HIR::Expr *lhs_expr, HIR::Expr *rhs_expr);
tree resolve_operator_overload (
LangItem::Kind lang_item_type, HIR::OperatorExprMeta expr, tree lhs,
tree rhs, HIR::Expr &lhs_expr,
tl::optional<std::reference_wrapper<HIR::Expr>> rhs_expr,
HIR::PathIdentSegment specified_segment
= HIR::PathIdentSegment::create_error ());
tree compile_bool_literal (const HIR::LiteralExpr &expr,
const TyTy::BaseType *tyty);

View File

@@ -22,6 +22,8 @@
#include "rust-compile-base.h"
#include "rust-compile-intrinsic.h"
#include "rust-compile-type.h"
#include "rust-diagnostics.h"
#include "rust-hir-full-decls.h"
namespace Rust {
namespace Compile {
@@ -32,16 +34,10 @@ class CompileExternItem : public HIRCompileBase,
public:
static tree compile (HIR::ExternalItem *item, Context *ctx,
TyTy::BaseType *concrete = nullptr,
bool is_query_mode = false,
location_t ref_locus = UNDEF_LOCATION)
{
CompileExternItem compiler (ctx, concrete, ref_locus);
item->accept_vis (compiler);
if (is_query_mode && compiler.reference == error_mark_node)
rust_internal_error_at (ref_locus, "failed to compile extern item: %s",
item->as_string ().c_str ());
return compiler.reference;
}
@@ -132,10 +128,8 @@ public:
if (fntype->get_abi () == ABI::RUST)
{
// then we need to get the canonical path of it and mangle it
const Resolver::CanonicalPath *canonical_path = nullptr;
bool ok = ctx->get_mappings ()->lookup_canonical_path (
function.get_mappings ().get_nodeid (), &canonical_path);
rust_assert (ok);
auto canonical_path = ctx->get_mappings ().lookup_canonical_path (
function.get_mappings ().get_nodeid ());
ir_symbol_name = canonical_path->get () + fntype->subst_as_string ();
asm_name = ctx->mangle_item (fntype, *canonical_path);
@@ -152,6 +146,11 @@ public:
reference = address_expression (fndecl, ref_locus);
}
void visit (HIR::ExternalTypeItem &type) override
{
rust_sorry_at (type.get_locus (), "extern types are not supported yet");
}
private:
CompileExternItem (Context *ctx, TyTy::BaseType *concrete,
location_t ref_locus)

View File

@@ -31,20 +31,20 @@ CompileFnParam::CompileFnParam (Context *ctx, tree fndecl, tree decl_type,
{}
Bvariable *
CompileFnParam::compile (Context *ctx, tree fndecl, HIR::FunctionParam *param,
CompileFnParam::compile (Context *ctx, tree fndecl, HIR::FunctionParam &param,
tree decl_type, location_t locus)
{
CompileFnParam compiler (ctx, fndecl, decl_type, locus);
param->get_param_name ()->accept_vis (compiler);
param.get_param_name ().accept_vis (compiler);
return compiler.compiled_param;
}
Bvariable *
CompileFnParam::compile (Context *ctx, tree fndecl, HIR::Pattern *param,
CompileFnParam::compile (Context *ctx, tree fndecl, HIR::Pattern &param,
tree decl_type, location_t locus)
{
CompileFnParam compiler (ctx, fndecl, decl_type, locus);
param->accept_vis (compiler);
param.accept_vis (compiler);
return compiler.compiled_param;
}
@@ -68,25 +68,36 @@ CompileFnParam::visit (HIR::WildcardPattern &pattern)
compiled_param = Backend::parameter_variable (fndecl, "_", decl_type, locus);
}
void
CompileFnParam::visit (HIR::TuplePattern &pattern)
{
compiled_param = create_tmp_param_var (decl_type);
CompilePatternBindings::Compile (
pattern, Backend::var_expression (compiled_param, locus), ctx);
}
void
CompileFnParam::visit (HIR::StructPattern &pattern)
{
tree tmp_param_var = create_tmp_param_var (decl_type);
CompilePatternBindings::Compile (&pattern, tmp_param_var, ctx);
compiled_param = create_tmp_param_var (decl_type);
CompilePatternBindings::Compile (
pattern, Backend::var_expression (compiled_param, locus), ctx);
}
void
CompileFnParam::visit (HIR::TupleStructPattern &pattern)
{
tree tmp_param_var = create_tmp_param_var (decl_type);
CompilePatternBindings::Compile (&pattern, tmp_param_var, ctx);
compiled_param = create_tmp_param_var (decl_type);
CompilePatternBindings::Compile (
pattern, Backend::var_expression (compiled_param, locus), ctx);
}
void
CompileFnParam::visit (HIR::ReferencePattern &pattern)
{
tree tmp_param_var = create_tmp_param_var (decl_type);
CompilePatternBindings::Compile (&pattern, tmp_param_var, ctx);
compiled_param = create_tmp_param_var (decl_type);
CompilePatternBindings::Compile (
pattern, Backend::var_expression (compiled_param, locus), ctx);
}
Bvariable *
@@ -102,7 +113,7 @@ CompileSelfParam::compile (Context *ctx, tree fndecl, HIR::SelfParam &self,
return Backend::parameter_variable (fndecl, "self", decl_type, locus);
}
tree
Bvariable *
CompileFnParam::create_tmp_param_var (tree decl_type)
{
// generate the anon param
@@ -110,10 +121,8 @@ CompileFnParam::create_tmp_param_var (tree decl_type)
std::string cpp_str_identifier = std::string (IDENTIFIER_POINTER (tmp_ident));
decl_type = Backend::immutable_type (decl_type);
compiled_param = Backend::parameter_variable (fndecl, cpp_str_identifier,
decl_type, locus);
return Backend::var_expression (compiled_param, locus);
return Backend::parameter_variable (fndecl, cpp_str_identifier, decl_type,
locus);
}
} // namespace Compile

View File

@@ -29,9 +29,9 @@ class CompileFnParam : private HIRCompileBase, protected HIR::HIRPatternVisitor
{
public:
static Bvariable *compile (Context *ctx, tree fndecl,
HIR::FunctionParam *param, tree decl_type,
HIR::FunctionParam &param, tree decl_type,
location_t locus);
static Bvariable *compile (Context *ctx, tree fndecl, HIR::Pattern *param,
static Bvariable *compile (Context *ctx, tree fndecl, HIR::Pattern &param,
tree decl_type, location_t locus);
void visit (HIR::IdentifierPattern &pattern) override;
@@ -47,12 +47,12 @@ public:
void visit (HIR::QualifiedPathInExpression &) override {}
void visit (HIR::RangePattern &) override {}
void visit (HIR::SlicePattern &) override {}
void visit (HIR::TuplePattern &) override {}
void visit (HIR::TuplePattern &) override;
private:
CompileFnParam (Context *ctx, tree fndecl, tree decl_type, location_t locus);
tree create_tmp_param_var (tree decl_type);
Bvariable *create_tmp_param_var (tree decl_type);
tree fndecl;
tree decl_type;

View File

@@ -27,15 +27,34 @@ CompileTraitItem::visit (HIR::TraitItemConst &constant)
rust_assert (concrete != nullptr);
TyTy::BaseType *resolved_type = concrete;
const Resolver::CanonicalPath *canonical_path = nullptr;
bool ok = ctx->get_mappings ()->lookup_canonical_path (
constant.get_mappings ().get_nodeid (), &canonical_path);
tl::optional<Resolver::CanonicalPath> canonical_path;
if (flag_name_resolution_2_0)
{
auto &nr_ctx
= Resolver2_0::ImmutableNameResolutionContext::get ().resolver ();
canonical_path = nr_ctx.values.to_canonical_path (
constant.get_mappings ().get_nodeid ());
}
else
{
canonical_path = ctx->get_mappings ().lookup_canonical_path (
constant.get_mappings ().get_nodeid ());
}
rust_assert (canonical_path);
HIR::Expr &const_value_expr = constant.get_expr ();
TyTy::BaseType *expr_type = nullptr;
bool ok = ctx->get_tyctx ()->lookup_type (
const_value_expr.get_mappings ().get_hirid (), &expr_type);
rust_assert (ok);
HIR::Expr *const_value_expr = constant.get_expr ().get ();
tree const_expr
= compile_constant_item (resolved_type, canonical_path, const_value_expr,
constant.get_locus ());
= compile_constant_item (constant.get_mappings ().get_hirid (), expr_type,
resolved_type, *canonical_path, const_value_expr,
constant.get_locus (),
const_value_expr.get_locus ());
ctx->push_const (const_expr);
ctx->insert_const_decl (constant.get_mappings ().get_hirid (), const_expr);
@@ -45,7 +64,7 @@ CompileTraitItem::visit (HIR::TraitItemConst &constant)
void
CompileTraitItem::visit (HIR::TraitItemFunc &func)
{
rust_assert (func.has_block_defined ());
rust_assert (func.has_definition ());
rust_assert (concrete->get_kind () == TyTy::TypeKind::FNDEF);
TyTy::FnType *fntype = static_cast<TyTy::FnType *> (concrete);
@@ -77,20 +96,32 @@ CompileTraitItem::visit (HIR::TraitItemFunc &func)
fntype->override_context ();
}
const Resolver::CanonicalPath *canonical_path = nullptr;
bool ok = ctx->get_mappings ()->lookup_canonical_path (
func.get_mappings ().get_nodeid (), &canonical_path);
rust_assert (ok);
tl::optional<Resolver::CanonicalPath> canonical_path;
if (flag_name_resolution_2_0)
{
auto &nr_ctx
= Resolver2_0::ImmutableNameResolutionContext::get ().resolver ();
canonical_path
= nr_ctx.values.to_canonical_path (func.get_mappings ().get_nodeid ());
}
else
{
canonical_path = ctx->get_mappings ().lookup_canonical_path (
func.get_mappings ().get_nodeid ());
}
rust_assert (canonical_path);
// FIXME: How do we get the proper visibility here?
auto vis = HIR::Visibility (HIR::Visibility::VisType::PUBLIC);
HIR::TraitFunctionDecl &function = func.get_decl ();
tree fndecl
= compile_function (function.get_function_name ().as_string (),
= compile_function (false, function.get_function_name ().as_string (),
function.get_self (), function.get_function_params (),
function.get_qualifiers (), vis,
func.get_outer_attrs (), func.get_locus (),
func.get_block_expr ().get (), canonical_path, fntype);
&func.get_block_expr (), *canonical_path, fntype);
reference = address_expression (fndecl, ref_locus);
}

View File

@@ -30,16 +30,10 @@ class CompileInherentImplItem : public CompileItem
public:
static tree Compile (HIR::ImplItem *item, Context *ctx,
TyTy::BaseType *concrete = nullptr,
bool is_query_mode = false,
location_t ref_locus = UNDEF_LOCATION)
{
CompileInherentImplItem compiler (ctx, concrete, ref_locus);
item->accept_vis (compiler);
if (is_query_mode && compiler.reference == error_mark_node)
rust_internal_error_at (ref_locus, "failed to compile impl item: %s",
item->as_string ().c_str ());
return compiler.reference;
}

View File

@@ -17,23 +17,19 @@
#include "rust-compile-intrinsic.h"
#include "rust-compile-context.h"
#include "rust-compile-type.h"
#include "rust-compile-expr.h"
#include "rust-compile-fnparam.h"
#include "rust-builtins.h"
#include "rust-diagnostics.h"
#include "rust-location.h"
#include "rust-constexpr.h"
#include "rust-session-manager.h"
#include "rust-tree.h"
#include "tree-core.h"
#include "rust-gcc.h"
#include "print-tree.h"
#include "fold-const.h"
#include "langhooks.h"
#include "rust-gcc.h"
#include "rust-constexpr.h"
#include "print-tree.h"
// declaration taken from "stringpool.h"
// the get_identifier macro causes compilation issues
extern tree
@@ -92,6 +88,10 @@ static tree
move_val_init_handler (Context *ctx, TyTy::FnType *fntype);
static tree
assume_handler (Context *ctx, TyTy::FnType *fntype);
static tree
discriminant_value_handler (Context *ctx, TyTy::FnType *fntype);
static tree
variant_count_handler (Context *ctx, TyTy::FnType *fntype);
enum class Prefetch
{
@@ -194,6 +194,17 @@ expect_handler (bool likely)
};
}
static tree
try_handler_inner (Context *ctx, TyTy::FnType *fntype, bool is_new_api);
const static std::function<tree (Context *, TyTy::FnType *)>
try_handler (bool is_new_api)
{
return [is_new_api] (Context *ctx, TyTy::FnType *fntype) {
return try_handler_inner (ctx, fntype, is_new_api);
};
}
inline tree
sorry_handler (Context *ctx, TyTy::FnType *fntype)
{
@@ -205,43 +216,46 @@ sorry_handler (Context *ctx, TyTy::FnType *fntype)
static const std::map<std::string,
std::function<tree (Context *, TyTy::FnType *)>>
generic_intrinsics = {
{"offset", offset_handler},
{"size_of", sizeof_handler},
{"transmute", transmute_handler},
{"rotate_left", rotate_left_handler},
{"rotate_right", rotate_right_handler},
{"wrapping_add", wrapping_op_handler (PLUS_EXPR)},
{"wrapping_sub", wrapping_op_handler (MINUS_EXPR)},
{"wrapping_mul", wrapping_op_handler (MULT_EXPR)},
{"add_with_overflow", op_with_overflow (PLUS_EXPR)},
{"sub_with_overflow", op_with_overflow (MINUS_EXPR)},
{"mul_with_overflow", op_with_overflow (MULT_EXPR)},
{"copy", copy_handler (true)},
{"copy_nonoverlapping", copy_handler (false)},
{"prefetch_read_data", prefetch_read_data},
{"prefetch_write_data", prefetch_write_data},
{"atomic_store_seqcst", atomic_store_handler (__ATOMIC_SEQ_CST)},
{"atomic_store_release", atomic_store_handler (__ATOMIC_RELEASE)},
{"atomic_store_relaxed", atomic_store_handler (__ATOMIC_RELAXED)},
{"atomic_store_unordered", atomic_store_handler (__ATOMIC_RELAXED)},
{"atomic_load_seqcst", atomic_load_handler (__ATOMIC_SEQ_CST)},
{"atomic_load_acquire", atomic_load_handler (__ATOMIC_ACQUIRE)},
{"atomic_load_relaxed", atomic_load_handler (__ATOMIC_RELAXED)},
{"atomic_load_unordered", atomic_load_handler (__ATOMIC_RELAXED)},
{"unchecked_add", unchecked_op_handler (PLUS_EXPR)},
{"unchecked_sub", unchecked_op_handler (MINUS_EXPR)},
{"unchecked_mul", unchecked_op_handler (MULT_EXPR)},
{"unchecked_div", unchecked_op_handler (TRUNC_DIV_EXPR)},
{"unchecked_rem", unchecked_op_handler (TRUNC_MOD_EXPR)},
{"unchecked_shl", unchecked_op_handler (LSHIFT_EXPR)},
{"unchecked_shr", unchecked_op_handler (RSHIFT_EXPR)},
{"uninit", uninit_handler},
{"move_val_init", move_val_init_handler},
{"likely", expect_handler (true)},
{"unlikely", expect_handler (false)},
{"assume", assume_handler},
};
generic_intrinsics
= {{"offset", offset_handler},
{"size_of", sizeof_handler},
{"transmute", transmute_handler},
{"rotate_left", rotate_left_handler},
{"rotate_right", rotate_right_handler},
{"wrapping_add", wrapping_op_handler (PLUS_EXPR)},
{"wrapping_sub", wrapping_op_handler (MINUS_EXPR)},
{"wrapping_mul", wrapping_op_handler (MULT_EXPR)},
{"add_with_overflow", op_with_overflow (PLUS_EXPR)},
{"sub_with_overflow", op_with_overflow (MINUS_EXPR)},
{"mul_with_overflow", op_with_overflow (MULT_EXPR)},
{"copy", copy_handler (true)},
{"copy_nonoverlapping", copy_handler (false)},
{"prefetch_read_data", prefetch_read_data},
{"prefetch_write_data", prefetch_write_data},
{"atomic_store_seqcst", atomic_store_handler (__ATOMIC_SEQ_CST)},
{"atomic_store_release", atomic_store_handler (__ATOMIC_RELEASE)},
{"atomic_store_relaxed", atomic_store_handler (__ATOMIC_RELAXED)},
{"atomic_store_unordered", atomic_store_handler (__ATOMIC_RELAXED)},
{"atomic_load_seqcst", atomic_load_handler (__ATOMIC_SEQ_CST)},
{"atomic_load_acquire", atomic_load_handler (__ATOMIC_ACQUIRE)},
{"atomic_load_relaxed", atomic_load_handler (__ATOMIC_RELAXED)},
{"atomic_load_unordered", atomic_load_handler (__ATOMIC_RELAXED)},
{"unchecked_add", unchecked_op_handler (PLUS_EXPR)},
{"unchecked_sub", unchecked_op_handler (MINUS_EXPR)},
{"unchecked_mul", unchecked_op_handler (MULT_EXPR)},
{"unchecked_div", unchecked_op_handler (TRUNC_DIV_EXPR)},
{"unchecked_rem", unchecked_op_handler (TRUNC_MOD_EXPR)},
{"unchecked_shl", unchecked_op_handler (LSHIFT_EXPR)},
{"unchecked_shr", unchecked_op_handler (RSHIFT_EXPR)},
{"uninit", uninit_handler},
{"move_val_init", move_val_init_handler},
{"likely", expect_handler (true)},
{"unlikely", expect_handler (false)},
{"assume", assume_handler},
{"try", try_handler (false)},
{"catch_unwind", try_handler (true)},
{"discriminant_value", discriminant_value_handler},
{"variant_count", variant_count_handler}};
Intrinsics::Intrinsics (Context *ctx) : ctx (ctx) {}
@@ -269,7 +283,7 @@ Intrinsics::compile (TyTy::FnType *fntype)
if (it != generic_intrinsics.end ())
return it->second (ctx, fntype);
location_t locus = ctx->get_mappings ()->lookup_location (fntype->get_ref ());
location_t locus = ctx->get_mappings ().lookup_location (fntype->get_ref ());
rust_error_at (locus, ErrorCode::E0093,
"unrecognized intrinsic function: %<%s%>",
fntype->get_identifier ().c_str ());
@@ -315,11 +329,11 @@ compile_fn_params (Context *ctx, TyTy::FnType *fntype, tree fndecl,
{
for (auto &parm : fntype->get_params ())
{
auto &referenced_param = parm.first;
auto &param_tyty = parm.second;
auto &referenced_param = parm.get_pattern ();
auto param_tyty = parm.get_type ();
auto compiled_param_type = TyTyResolveCompile::compile (ctx, param_tyty);
location_t param_locus = referenced_param->get_locus ();
location_t param_locus = referenced_param.get_locus ();
Bvariable *compiled_param_var
= CompileFnParam::compile (ctx, fndecl, referenced_param,
compiled_param_type, param_locus);
@@ -496,9 +510,10 @@ transmute_handler (Context *ctx, TyTy::FnType *fntype)
rust_error_at (fntype->get_locus (),
"cannot transmute between types of different sizes, or "
"dependently-sized types");
rust_inform (fntype->get_ident ().locus, "source type: %qs (%lu bits)",
fntype->get_params ().at (0).second->as_string ().c_str (),
(unsigned long) source_size);
rust_inform (
fntype->get_ident ().locus, "source type: %qs (%lu bits)",
fntype->get_params ().at (0).get_type ()->as_string ().c_str (),
(unsigned long) source_size);
rust_inform (fntype->get_ident ().locus, "target type: %qs (%lu bits)",
fntype->get_return_type ()->as_string ().c_str (),
(unsigned long) target_size);
@@ -1226,7 +1241,7 @@ assume_handler (Context *ctx, TyTy::FnType *fntype)
// TODO: make sure this is actually helping the compiler optimize
rust_assert (fntype->get_params ().size () == 1);
rust_assert (fntype->param_at (0).second->get_kind ()
rust_assert (fntype->param_at (0).get_type ()->get_kind ()
== TyTy::TypeKind::BOOL);
tree lookup = NULL_TREE;
@@ -1258,7 +1273,217 @@ assume_handler (Context *ctx, TyTy::FnType *fntype)
TREE_SIDE_EFFECTS (assume_expr) = 1;
ctx->add_statement (assume_expr);
// BUILTIN size_of FN BODY END
// BUILTIN assume FN BODY END
finalize_intrinsic_block (ctx, fndecl);
return fndecl;
}
static tree
try_handler_inner (Context *ctx, TyTy::FnType *fntype, bool is_new_api)
{
rust_assert (fntype->get_params ().size () == 3);
tree lookup = NULL_TREE;
if (check_for_cached_intrinsic (ctx, fntype, &lookup))
return lookup;
auto fndecl = compile_intrinsic_function (ctx, fntype);
enter_intrinsic_block (ctx, fndecl);
// The following tricks are needed to make sure the try-catch blocks are not
// optimized away
TREE_READONLY (fndecl) = 0;
DECL_DISREGARD_INLINE_LIMITS (fndecl) = 1;
DECL_ATTRIBUTES (fndecl) = tree_cons (get_identifier ("always_inline"),
NULL_TREE, DECL_ATTRIBUTES (fndecl));
// BUILTIN try_handler FN BODY BEGIN
// setup the params
std::vector<Bvariable *> param_vars;
compile_fn_params (ctx, fntype, fndecl, &param_vars);
if (!Backend::function_set_parameters (fndecl, param_vars))
return error_mark_node;
tree enclosing_scope = NULL_TREE;
bool panic_is_abort = Session::get_instance ().options.get_panic_strategy ()
== CompileOptions::PanicStrategy::Abort;
tree try_fn = Backend::var_expression (param_vars[0], UNDEF_LOCATION);
tree user_data = Backend::var_expression (param_vars[1], UNDEF_LOCATION);
tree catch_fn = Backend::var_expression (param_vars[2], UNDEF_LOCATION);
tree normal_return_stmt = NULL_TREE;
tree error_return_stmt = NULL_TREE;
tree try_call = Backend::call_expression (try_fn, {user_data}, nullptr,
BUILTINS_LOCATION);
tree catch_call = NULL_TREE;
tree try_block = Backend::block (fndecl, enclosing_scope, {}, UNDEF_LOCATION,
UNDEF_LOCATION);
if (is_new_api)
{
auto ret_type = TyTyResolveCompile::get_unit_type (ctx);
auto ret_expr = Backend::constructor_expression (ret_type, false, {}, -1,
UNDEF_LOCATION);
normal_return_stmt
= Backend::return_statement (fndecl, ret_expr, BUILTINS_LOCATION);
error_return_stmt
= Backend::return_statement (fndecl, ret_expr, BUILTINS_LOCATION);
}
else
{
normal_return_stmt = Backend::return_statement (fndecl, integer_zero_node,
BUILTINS_LOCATION);
error_return_stmt = Backend::return_statement (fndecl, integer_one_node,
BUILTINS_LOCATION);
}
Backend::block_add_statements (try_block,
std::vector<tree>{try_call,
normal_return_stmt});
if (panic_is_abort)
{
// skip building the try-catch construct
ctx->add_statement (try_block);
finalize_intrinsic_block (ctx, fndecl);
return fndecl;
}
tree eh_pointer
= build_call_expr (builtin_decl_explicit (BUILT_IN_EH_POINTER), 1,
integer_zero_node);
catch_call = Backend::call_expression (catch_fn, {user_data, eh_pointer},
NULL_TREE, BUILTINS_LOCATION);
tree catch_block = Backend::block (fndecl, enclosing_scope, {},
UNDEF_LOCATION, UNDEF_LOCATION);
Backend::block_add_statements (catch_block,
std::vector<tree>{catch_call,
error_return_stmt});
// emulate what cc1plus is doing for C++ try-catch
tree inner_eh_construct
= Backend::exception_handler_statement (catch_call, NULL_TREE,
error_return_stmt,
BUILTINS_LOCATION);
// TODO(liushuyu): eh_personality needs to be implemented as a runtime thing
auto eh_construct
= Backend::exception_handler_statement (try_block, inner_eh_construct,
NULL_TREE, BUILTINS_LOCATION);
ctx->add_statement (eh_construct);
// BUILTIN try_handler FN BODY END
finalize_intrinsic_block (ctx, fndecl);
return fndecl;
}
static tree
discriminant_value_handler (Context *ctx, TyTy::FnType *fntype)
{
rust_assert (fntype->get_params ().size () == 1);
rust_assert (fntype->get_return_type ()->is<TyTy::PlaceholderType> ());
rust_assert (fntype->has_substitutions ());
rust_assert (fntype->get_num_type_params () == 1);
auto &mapping = fntype->get_substs ().at (0);
auto param_ty = mapping.get_param_ty ();
rust_assert (param_ty->can_resolve ());
auto resolved = param_ty->resolve ();
auto p = static_cast<TyTy::PlaceholderType *> (fntype->get_return_type ());
TyTy::BaseType *return_type = nullptr;
bool ok = ctx->get_tyctx ()->lookup_builtin ("isize", &return_type);
rust_assert (ok);
bool is_adt = resolved->is<TyTy::ADTType> ();
bool is_enum = false;
if (is_adt)
{
const auto &adt = *static_cast<TyTy::ADTType *> (resolved);
return_type = adt.get_repr_options ().repr;
rust_assert (return_type != nullptr);
is_enum = adt.is_enum ();
}
p->set_associated_type (return_type->get_ref ());
tree lookup = NULL_TREE;
if (check_for_cached_intrinsic (ctx, fntype, &lookup))
return lookup;
auto fndecl = compile_intrinsic_function (ctx, fntype);
std::vector<Bvariable *> param_vars;
compile_fn_params (ctx, fntype, fndecl, &param_vars);
if (!Backend::function_set_parameters (fndecl, param_vars))
return error_mark_node;
enter_intrinsic_block (ctx, fndecl);
// BUILTIN disriminant_value FN BODY BEGIN
tree result = integer_zero_node;
if (is_enum)
{
tree val = Backend::var_expression (param_vars[0], UNDEF_LOCATION);
tree deref = build_fold_indirect_ref_loc (UNKNOWN_LOCATION, val);
result = Backend::struct_field_expression (deref, 0, UNKNOWN_LOCATION);
}
auto return_statement
= Backend::return_statement (fndecl, result, BUILTINS_LOCATION);
ctx->add_statement (return_statement);
// BUILTIN disriminant_value FN BODY END
finalize_intrinsic_block (ctx, fndecl);
return fndecl;
}
static tree
variant_count_handler (Context *ctx, TyTy::FnType *fntype)
{
rust_assert (fntype->get_num_type_params () == 1);
auto &mapping = fntype->get_substs ().at (0);
auto param_ty = mapping.get_param_ty ();
rust_assert (param_ty->can_resolve ());
auto resolved = param_ty->resolve ();
size_t variant_count = 0;
bool is_adt = resolved->is<TyTy::ADTType> ();
if (is_adt)
{
const auto &adt = *static_cast<TyTy::ADTType *> (resolved);
variant_count = adt.number_of_variants ();
}
tree lookup = NULL_TREE;
if (check_for_cached_intrinsic (ctx, fntype, &lookup))
return lookup;
auto fndecl = compile_intrinsic_function (ctx, fntype);
std::vector<Bvariable *> param_vars;
compile_fn_params (ctx, fntype, fndecl, &param_vars);
if (!Backend::function_set_parameters (fndecl, param_vars))
return error_mark_node;
enter_intrinsic_block (ctx, fndecl);
// BUILTIN disriminant_value FN BODY BEGIN
tree result_decl = DECL_RESULT (fndecl);
tree type = TREE_TYPE (result_decl);
mpz_t ival;
mpz_init_set_ui (ival, variant_count);
tree result = wide_int_to_tree (type, wi::from_mpz (type, ival, true));
mpz_clear (ival);
auto return_statement
= Backend::return_statement (fndecl, result, BUILTINS_LOCATION);
ctx->add_statement (return_statement);
// BUILTIN disriminant_value FN BODY END
finalize_intrinsic_block (ctx, fndecl);

View File

@@ -19,6 +19,9 @@
#include "rust-compile-item.h"
#include "rust-compile-implitem.h"
#include "rust-compile-extern.h"
#include "rust-substitution-mapper.h"
#include "rust-type-util.h"
#include "rust-immutable-name-resolution-context.h"
namespace Rust {
namespace Compile {
@@ -34,22 +37,42 @@ CompileItem::visit (HIR::StaticItem &var)
return;
}
HIR::Expr &const_value_expr = var.get_expr ();
TyTy::BaseType *resolved_type = nullptr;
TyTy::BaseType *expr_type = nullptr;
bool ok = ctx->get_tyctx ()->lookup_type (var.get_mappings ().get_hirid (),
&resolved_type);
rust_assert (ok);
ok = ctx->get_tyctx ()->lookup_type (
const_value_expr.get_mappings ().get_hirid (), &expr_type);
rust_assert (ok);
tree type = TyTyResolveCompile::compile (ctx, resolved_type);
const Resolver::CanonicalPath *canonical_path = nullptr;
ok = ctx->get_mappings ()->lookup_canonical_path (
var.get_mappings ().get_nodeid (), &canonical_path);
rust_assert (ok);
tl::optional<Resolver::CanonicalPath> canonical_path;
if (flag_name_resolution_2_0)
{
auto &nr_ctx
= Resolver2_0::ImmutableNameResolutionContext::get ().resolver ();
canonical_path
= nr_ctx.values.to_canonical_path (var.get_mappings ().get_nodeid ());
}
else
{
canonical_path = ctx->get_mappings ().lookup_canonical_path (
var.get_mappings ().get_nodeid ());
}
rust_assert (canonical_path.has_value ());
HIR::Expr *const_value_expr = var.get_expr ().get ();
ctx->push_const_context ();
tree value = compile_constant_item (resolved_type, canonical_path,
const_value_expr, var.get_locus ());
tree value
= compile_constant_item (var.get_mappings ().get_hirid (), expr_type,
resolved_type, *canonical_path, const_value_expr,
var.get_locus (), const_value_expr.get_locus ());
ctx->pop_const_context ();
std::string name = canonical_path->get ();
@@ -75,32 +98,52 @@ CompileItem::visit (HIR::StaticItem &var)
void
CompileItem::visit (HIR::ConstantItem &constant)
{
if (ctx->lookup_const_decl (constant.get_mappings ().get_hirid (),
&reference))
HIR::Expr &const_value_expr = constant.get_expr ();
auto &mappings = constant.get_mappings ();
if (ctx->lookup_const_decl (mappings.get_hirid (), &reference))
return;
// resolve the type
TyTy::BaseType *resolved_type = nullptr;
TyTy::BaseType *constant_type = nullptr;
TyTy::BaseType *expr_type = nullptr;
bool ok
= ctx->get_tyctx ()->lookup_type (constant.get_mappings ().get_hirid (),
&resolved_type);
= ctx->get_tyctx ()->lookup_type (mappings.get_hirid (), &constant_type);
rust_assert (ok);
ok = ctx->get_tyctx ()->lookup_type (
const_value_expr.get_mappings ().get_hirid (), &expr_type);
rust_assert (ok);
// canonical path
const Resolver::CanonicalPath *canonical_path = nullptr;
ok = ctx->get_mappings ()->lookup_canonical_path (
constant.get_mappings ().get_nodeid (), &canonical_path);
rust_assert (ok);
Resolver::CanonicalPath canonical_path
= Resolver::CanonicalPath::create_empty ();
if (flag_name_resolution_2_0)
{
auto &nr_ctx
= Resolver2_0::ImmutableNameResolutionContext::get ().resolver ();
canonical_path
= nr_ctx.values.to_canonical_path (mappings.get_nodeid ()).value ();
}
else
{
canonical_path = ctx->get_mappings ()
.lookup_canonical_path (mappings.get_nodeid ())
.value ();
}
HIR::Expr *const_value_expr = constant.get_expr ().get ();
ctx->push_const_context ();
tree const_expr
= compile_constant_item (resolved_type, canonical_path, const_value_expr,
constant.get_locus ());
= compile_constant_item (mappings.get_hirid (), expr_type, constant_type,
canonical_path, const_value_expr,
constant.get_locus (),
const_value_expr.get_locus ());
ctx->pop_const_context ();
ctx->push_const (const_expr);
ctx->insert_const_decl (constant.get_mappings ().get_hirid (), const_expr);
ctx->insert_const_decl (mappings.get_hirid (), const_expr);
reference = const_expr;
}
@@ -124,37 +167,71 @@ CompileItem::visit (HIR::Function &function)
// is given
if (concrete == nullptr)
return;
else
rust_assert (concrete->get_kind () == TyTy::TypeKind::FNDEF);
TyTy::FnType *concrete_fnty = static_cast<TyTy::FnType *> (concrete);
bool is_trait_item_concrete
= ctx->get_mappings ()
.lookup_trait_item_defid (concrete_fnty->get_id ())
.has_value ();
if (!is_trait_item_concrete)
{
rust_assert (concrete->get_kind () == TyTy::TypeKind::FNDEF);
fntype = static_cast<TyTy::FnType *> (concrete);
fntype->monomorphize ();
}
else
{
TyTy::BaseType *infer
= Resolver::SubstMapper::InferSubst (fntype, function.get_locus ());
TyTy::BaseType *resolved
= Resolver::unify_site (function.get_mappings ().get_hirid (),
TyTy::TyWithLocation (infer),
TyTy::TyWithLocation (concrete),
function.get_locus ());
rust_assert (resolved->is<TyTy::FnType> ());
fntype = resolved->as<TyTy::FnType> ();
}
fntype->monomorphize ();
}
else
{
// if this is part of a trait impl block which is not generic we need to
// ensure associated types are setup
HirId parent_impl_block = UNKNOWN_HIRID;
HirId id = function.get_mappings ().get_hirid ();
HIR::ImplItem *impl_item
= ctx->get_mappings ()->lookup_hir_implitem (id, &parent_impl_block);
if (impl_item != nullptr)
if (auto impl_item = ctx->get_mappings ().lookup_hir_implitem (id))
{
Resolver::AssociatedImplTrait *impl = nullptr;
bool found = ctx->get_tyctx ()->lookup_associated_trait_impl (
parent_impl_block, &impl);
impl_item->second, &impl);
if (found)
impl->setup_raw_associated_types ();
}
}
const Resolver::CanonicalPath *canonical_path = nullptr;
bool ok = ctx->get_mappings ()->lookup_canonical_path (
function.get_mappings ().get_nodeid (), &canonical_path);
rust_assert (ok);
Resolver::CanonicalPath canonical_path
= Resolver::CanonicalPath::create_empty ();
const std::string asm_name = ctx->mangle_item (fntype, *canonical_path);
if (flag_name_resolution_2_0)
{
auto &nr_ctx
= Resolver2_0::ImmutableNameResolutionContext::get ().resolver ();
auto path = nr_ctx.values.to_canonical_path (
function.get_mappings ().get_nodeid ());
canonical_path = path.value ();
}
else
{
auto path = ctx->get_mappings ().lookup_canonical_path (
function.get_mappings ().get_nodeid ());
canonical_path = *path;
}
const std::string asm_name = ctx->mangle_item (fntype, canonical_path);
// items can be forward compiled which means we may not need to invoke this
// code. We might also have already compiled this generic function as well.
@@ -175,14 +252,17 @@ CompileItem::visit (HIR::Function &function)
if (function.get_qualifiers ().is_const ())
ctx->push_const_context ();
auto lookup_root_item = ctx->get_mappings ().lookup_hir_item (
function.get_mappings ().get_hirid ());
bool is_root_item = lookup_root_item.has_value ();
tree fndecl
= compile_function (function.get_function_name ().as_string (),
= compile_function (is_root_item,
function.get_function_name ().as_string (),
function.get_self_param (),
function.get_function_params (),
function.get_qualifiers (), function.get_visibility (),
function.get_outer_attrs (), function.get_locus (),
function.get_definition ().get (), canonical_path,
fntype);
&function.get_definition (), canonical_path, fntype);
reference = address_expression (fndecl, ref_locus);
if (function.get_qualifiers ().is_const ())
@@ -194,7 +274,7 @@ CompileItem::visit (HIR::ImplBlock &impl_block)
{
TyTy::BaseType *self_lookup = nullptr;
if (!ctx->get_tyctx ()->lookup_type (
impl_block.get_type ()->get_mappings ().get_hirid (), &self_lookup))
impl_block.get_type ().get_mappings ().get_hirid (), &self_lookup))
{
rust_error_at (impl_block.get_locus (), "failed to resolve type of impl");
return;

View File

@@ -31,16 +31,10 @@ protected:
public:
static tree compile (HIR::Item *item, Context *ctx,
TyTy::BaseType *concrete = nullptr,
bool is_query_mode = false,
location_t ref_locus = UNDEF_LOCATION)
{
CompileItem compiler (ctx, concrete, ref_locus);
item->accept_vis (compiler);
if (is_query_mode && compiler.reference == error_mark_node)
rust_internal_error_at (ref_locus, "failed to compile item: %s",
item->as_string ().c_str ());
return compiler.reference;
}

View File

@@ -21,6 +21,12 @@
#include "rust-compile-resolve-path.h"
#include "rust-constexpr.h"
#include "rust-compile-type.h"
#include "print-tree.h"
#include "rust-diagnostics.h"
#include "rust-hir-pattern-abstract.h"
#include "rust-hir-pattern.h"
#include "rust-system.h"
#include "rust-tyty.h"
namespace Rust {
namespace Compile {
@@ -35,11 +41,16 @@ CompilePatternCheckExpr::visit (HIR::PathInExpression &pattern)
&lookup);
rust_assert (ok);
// this must be an enum
// TODO: might not be
// must be an ADT (?)
rust_assert (lookup->get_kind () == TyTy::TypeKind::ADT);
TyTy::ADTType *adt = static_cast<TyTy::ADTType *> (lookup);
rust_assert (adt->is_enum ());
// if this isn't an enum, always succeed
if (!adt->is_enum ())
{
check_expr = boolean_true_node;
return;
}
// lookup the variant
HirId variant_id;
@@ -52,17 +63,14 @@ CompilePatternCheckExpr::visit (HIR::PathInExpression &pattern)
rust_assert (ok);
// find discriminant field of scrutinee
tree scrutinee_record_expr
= Backend::struct_field_expression (match_scrutinee_expr, 0,
pattern.get_locus ());
tree scrutinee_expr_qualifier_expr
= Backend::struct_field_expression (scrutinee_record_expr, 0,
= Backend::struct_field_expression (match_scrutinee_expr, 0,
pattern.get_locus ());
// must be enum
match_scrutinee_expr = scrutinee_expr_qualifier_expr;
HIR::Expr *discrim_expr = variant->get_discriminant ();
HIR::Expr &discrim_expr = variant->get_discriminant ();
tree discrim_expr_node = CompileExpr::Compile (discrim_expr, ctx);
check_expr
@@ -75,10 +83,9 @@ void
CompilePatternCheckExpr::visit (HIR::LiteralPattern &pattern)
{
// Compile the literal
HIR::LiteralExpr *litexpr
= new HIR::LiteralExpr (pattern.get_mappings (), pattern.get_literal (),
pattern.get_locus (),
std::vector<AST::Attribute> ());
auto litexpr = std::make_unique<HIR::LiteralExpr> (
HIR::LiteralExpr (pattern.get_mappings (), pattern.get_literal (),
pattern.get_locus (), std::vector<AST::Attribute> ()));
// Note: Floating point literals are currently accepted but will likely be
// forbidden in LiteralPatterns in a future version of Rust.
@@ -90,7 +97,7 @@ CompilePatternCheckExpr::visit (HIR::LiteralPattern &pattern)
rust_sorry_at (pattern.get_locus (), "floating-point literal in pattern");
}
tree lit = CompileExpr::Compile (litexpr, ctx);
tree lit = CompileExpr::Compile (*litexpr, ctx);
check_expr = Backend::comparison_expression (ComparisonOperator::EQUAL,
match_scrutinee_expr, lit,
@@ -98,19 +105,17 @@ CompilePatternCheckExpr::visit (HIR::LiteralPattern &pattern)
}
static tree
compile_range_pattern_bound (HIR::RangePatternBound *bound,
compile_range_pattern_bound (HIR::RangePatternBound &bound,
Analysis::NodeMapping mappings, location_t locus,
Context *ctx)
{
tree result = NULL_TREE;
switch (bound->get_bound_type ())
switch (bound.get_bound_type ())
{
case HIR::RangePatternBound::RangePatternBoundType::LITERAL: {
HIR::RangePatternBoundLiteral &ref
= *static_cast<HIR::RangePatternBoundLiteral *> (bound);
auto &ref = static_cast<HIR::RangePatternBoundLiteral &> (bound);
HIR::LiteralExpr *litexpr
= new HIR::LiteralExpr (mappings, ref.get_literal (), locus,
HIR::LiteralExpr litexpr (mappings, ref.get_literal (), locus,
std::vector<AST::Attribute> ());
result = CompileExpr::Compile (litexpr, ctx);
@@ -118,8 +123,7 @@ compile_range_pattern_bound (HIR::RangePatternBound *bound,
break;
case HIR::RangePatternBound::RangePatternBoundType::PATH: {
HIR::RangePatternBoundPath &ref
= *static_cast<HIR::RangePatternBoundPath *> (bound);
auto &ref = static_cast<HIR::RangePatternBoundPath &> (bound);
result = ResolvePathRef::Compile (ref.get_path (), ctx);
@@ -129,8 +133,7 @@ compile_range_pattern_bound (HIR::RangePatternBound *bound,
break;
case HIR::RangePatternBound::RangePatternBoundType::QUALPATH: {
HIR::RangePatternBoundQualPath &ref
= *static_cast<HIR::RangePatternBoundQualPath *> (bound);
auto &ref = static_cast<HIR::RangePatternBoundQualPath &> (bound);
result = ResolvePathRef::Compile (ref.get_qualified_path (), ctx);
@@ -145,10 +148,10 @@ compile_range_pattern_bound (HIR::RangePatternBound *bound,
void
CompilePatternCheckExpr::visit (HIR::RangePattern &pattern)
{
tree upper = compile_range_pattern_bound (pattern.get_upper_bound ().get (),
tree upper = compile_range_pattern_bound (pattern.get_upper_bound (),
pattern.get_mappings (),
pattern.get_locus (), ctx);
tree lower = compile_range_pattern_bound (pattern.get_lower_bound ().get (),
tree lower = compile_range_pattern_bound (pattern.get_lower_bound (),
pattern.get_mappings (),
pattern.get_locus (), ctx);
@@ -170,7 +173,7 @@ CompilePatternCheckExpr::visit (HIR::ReferencePattern &pattern)
{
match_scrutinee_expr
= indirect_expression (match_scrutinee_expr, pattern.get_locus ());
pattern.get_referenced_pattern ()->accept_vis (*this);
pattern.get_referenced_pattern ().accept_vis (*this);
}
void
@@ -178,14 +181,13 @@ CompilePatternCheckExpr::visit (HIR::AltPattern &pattern)
{
auto &alts = pattern.get_alts ();
check_expr = CompilePatternCheckExpr::Compile (alts.at (0).get (),
check_expr = CompilePatternCheckExpr::Compile (*alts.at (0),
match_scrutinee_expr, ctx);
auto end = alts.end ();
for (auto i = alts.begin () + 1; i != end; i++)
{
tree next_expr
= CompilePatternCheckExpr::Compile (i->get (), match_scrutinee_expr,
ctx);
= CompilePatternCheckExpr::Compile (**i, match_scrutinee_expr, ctx);
check_expr = Backend::arithmetic_or_logical_expression (
ArithmeticOrLogicalOperator::BITWISE_OR, check_expr, next_expr,
(*i)->get_locus ());
@@ -207,6 +209,7 @@ CompilePatternCheckExpr::visit (HIR::StructPattern &pattern)
rust_assert (adt->number_of_variants () > 0);
TyTy::VariantDef *variant = nullptr;
tree variant_accesser_expr = nullptr;
if (adt->is_enum ())
{
// lookup the variant
@@ -221,18 +224,21 @@ CompilePatternCheckExpr::visit (HIR::StructPattern &pattern)
// find expected discriminant
// // need to access qualifier the field, if we use QUAL_UNION_TYPE this
// // would be DECL_QUALIFIER i think. For now this will just access the
// // first record field and its respective qualifier because it will
// // always be set because this is all a big special union
HIR::Expr *discrim_expr = variant->get_discriminant ();
// // would be DECL_QUALIFIER i think.
HIR::Expr &discrim_expr = variant->get_discriminant ();
tree discrim_expr_node = CompileExpr::Compile (discrim_expr, ctx);
// find discriminant field of scrutinee
tree scrutinee_record_expr
= Backend::struct_field_expression (match_scrutinee_expr, variant_index,
pattern.get_path ().get_locus ());
tree scrutinee_expr_qualifier_expr
= Backend::struct_field_expression (scrutinee_record_expr, 0,
= Backend::struct_field_expression (match_scrutinee_expr, 0,
pattern.get_path ().get_locus ());
// access variant data
tree scrutinee_union_expr
= Backend::struct_field_expression (match_scrutinee_expr, 1,
pattern.get_path ().get_locus ());
variant_accesser_expr
= Backend::struct_field_expression (scrutinee_union_expr, variant_index,
pattern.get_path ().get_locus ());
check_expr
@@ -241,11 +247,12 @@ CompilePatternCheckExpr::visit (HIR::StructPattern &pattern)
discrim_expr_node,
pattern.get_path ().get_locus ());
match_scrutinee_expr = scrutinee_record_expr;
match_scrutinee_expr = scrutinee_expr_qualifier_expr;
}
else
{
variant = adt->get_variants ().at (0);
variant_accesser_expr = match_scrutinee_expr;
check_expr = boolean_true_node;
}
@@ -269,19 +276,16 @@ CompilePatternCheckExpr::visit (HIR::StructPattern &pattern)
nullptr, &offs);
rust_assert (ok);
// we may be offsetting by + 1 here since the first field in the
// record is always the discriminator
offs += adt->is_enum ();
tree field_expr
= Backend::struct_field_expression (match_scrutinee_expr, offs,
= Backend::struct_field_expression (variant_accesser_expr, offs,
ident.get_locus ());
tree check_expr_sub
= CompilePatternCheckExpr::Compile (ident.get_pattern ().get (),
= CompilePatternCheckExpr::Compile (ident.get_pattern (),
field_expr, ctx);
check_expr = Backend::arithmetic_or_logical_expression (
ArithmeticOrLogicalOperator::BITWISE_AND, check_expr,
check_expr_sub, ident.get_pattern ()->get_locus ());
check_expr_sub, ident.get_pattern ().get_locus ());
}
break;
@@ -296,8 +300,6 @@ CompilePatternCheckExpr::visit (HIR::StructPattern &pattern)
void
CompilePatternCheckExpr::visit (HIR::TupleStructPattern &pattern)
{
size_t tuple_field_index;
// lookup the type
TyTy::BaseType *lookup = nullptr;
bool ok = ctx->get_tyctx ()->lookup_type (
@@ -308,6 +310,7 @@ CompilePatternCheckExpr::visit (HIR::TupleStructPattern &pattern)
rust_assert (lookup->get_kind () == TyTy::TypeKind::ADT);
TyTy::ADTType *adt = static_cast<TyTy::ADTType *> (lookup);
int variant_index = 0;
rust_assert (adt->number_of_variants () > 0);
TyTy::VariantDef *variant = nullptr;
if (adt->is_enum ())
@@ -318,20 +321,16 @@ CompilePatternCheckExpr::visit (HIR::TupleStructPattern &pattern)
pattern.get_path ().get_mappings ().get_hirid (), &variant_id);
rust_assert (ok);
int variant_index = 0;
ok = adt->lookup_variant_by_id (variant_id, &variant, &variant_index);
rust_assert (ok);
// find expected discriminant
HIR::Expr *discrim_expr = variant->get_discriminant ();
HIR::Expr &discrim_expr = variant->get_discriminant ();
tree discrim_expr_node = CompileExpr::Compile (discrim_expr, ctx);
// find discriminant field of scrutinee
tree scrutinee_record_expr
= Backend::struct_field_expression (match_scrutinee_expr, variant_index,
pattern.get_path ().get_locus ());
tree scrutinee_expr_qualifier_expr
= Backend::struct_field_expression (scrutinee_record_expr, 0,
= Backend::struct_field_expression (match_scrutinee_expr, 0,
pattern.get_path ().get_locus ());
check_expr
@@ -339,21 +338,15 @@ CompilePatternCheckExpr::visit (HIR::TupleStructPattern &pattern)
scrutinee_expr_qualifier_expr,
discrim_expr_node,
pattern.get_path ().get_locus ());
match_scrutinee_expr = scrutinee_record_expr;
// we are offsetting by + 1 here since the first field in the record
// is always the discriminator
tuple_field_index = 1;
}
else
{
variant = adt->get_variants ().at (0);
check_expr = boolean_true_node;
tuple_field_index = 0;
}
std::unique_ptr<HIR::TupleStructItems> &items = pattern.get_items ();
switch (items->get_item_type ())
HIR::TupleStructItems &items = pattern.get_items ();
switch (items.get_item_type ())
{
case HIR::TupleStructItems::RANGED: {
// TODO
@@ -363,21 +356,30 @@ CompilePatternCheckExpr::visit (HIR::TupleStructPattern &pattern)
case HIR::TupleStructItems::MULTIPLE: {
HIR::TupleStructItemsNoRange &items_no_range
= static_cast<HIR::TupleStructItemsNoRange &> (*items.get ());
= static_cast<HIR::TupleStructItemsNoRange &> (items);
rust_assert (items_no_range.get_patterns ().size ()
== variant->num_fields ());
size_t tuple_field_index = 0;
for (auto &pattern : items_no_range.get_patterns ())
{
// find payload union field of scrutinee
tree payload_ref
= Backend::struct_field_expression (match_scrutinee_expr, 1,
pattern->get_locus ());
tree variant_ref
= Backend::struct_field_expression (payload_ref, variant_index,
pattern->get_locus ());
tree field_expr
= Backend::struct_field_expression (match_scrutinee_expr,
= Backend::struct_field_expression (variant_ref,
tuple_field_index++,
pattern->get_locus ());
tree check_expr_sub
= CompilePatternCheckExpr::Compile (pattern.get (), field_expr,
ctx);
= CompilePatternCheckExpr::Compile (*pattern, field_expr, ctx);
check_expr = Backend::arithmetic_or_logical_expression (
ArithmeticOrLogicalOperator::BITWISE_AND, check_expr,
check_expr_sub, pattern->get_locus ());
@@ -392,7 +394,7 @@ CompilePatternCheckExpr::visit (HIR::TuplePattern &pattern)
{
check_expr = boolean_true_node;
switch (pattern.get_items ()->get_item_type ())
switch (pattern.get_items ().get_item_type ())
{
case HIR::TuplePatternItems::RANGED: {
// TODO
@@ -402,7 +404,7 @@ CompilePatternCheckExpr::visit (HIR::TuplePattern &pattern)
case HIR::TuplePatternItems::MULTIPLE: {
auto &items = static_cast<HIR::TuplePatternItemsMultiple &> (
*pattern.get_items ());
pattern.get_items ());
size_t tuple_field_index = 0;
for (auto &pat : items.get_patterns ())
@@ -413,7 +415,7 @@ CompilePatternCheckExpr::visit (HIR::TuplePattern &pattern)
pat->get_locus ());
tree check_expr_sub
= CompilePatternCheckExpr::Compile (pat.get (), field_expr, ctx);
= CompilePatternCheckExpr::Compile (*pat, field_expr, ctx);
check_expr = Backend::arithmetic_or_logical_expression (
ArithmeticOrLogicalOperator::BITWISE_AND, check_expr,
check_expr_sub, pat->get_locus ());
@@ -454,8 +456,8 @@ CompilePatternBindings::visit (HIR::TupleStructPattern &pattern)
rust_assert (variant->get_variant_type ()
== TyTy::VariantDef::VariantType::TUPLE);
std::unique_ptr<HIR::TupleStructItems> &items = pattern.get_items ();
switch (items->get_item_type ())
HIR::TupleStructItems &items = pattern.get_items ();
switch (items.get_item_type ())
{
case HIR::TupleStructItems::RANGED: {
// TODO
@@ -465,20 +467,22 @@ CompilePatternBindings::visit (HIR::TupleStructPattern &pattern)
case HIR::TupleStructItems::MULTIPLE: {
HIR::TupleStructItemsNoRange &items_no_range
= static_cast<HIR::TupleStructItemsNoRange &> (*items.get ());
= static_cast<HIR::TupleStructItemsNoRange &> (items);
rust_assert (items_no_range.get_patterns ().size ()
== variant->num_fields ());
if (adt->is_enum ())
{
// we are offsetting by + 1 here since the first field in the record
// is always the discriminator
size_t tuple_field_index = 1;
size_t tuple_field_index = 0;
for (auto &pattern : items_no_range.get_patterns ())
{
tree payload_accessor_union
= Backend::struct_field_expression (match_scrutinee_expr, 1,
pattern->get_locus ());
tree variant_accessor
= Backend::struct_field_expression (match_scrutinee_expr,
= Backend::struct_field_expression (payload_accessor_union,
variant_index,
pattern->get_locus ());
@@ -487,8 +491,7 @@ CompilePatternBindings::visit (HIR::TupleStructPattern &pattern)
tuple_field_index++,
pattern->get_locus ());
ctx->insert_pattern_binding (
pattern->get_mappings ().get_hirid (), binding);
CompilePatternBindings::Compile (*pattern, binding, ctx);
}
}
else
@@ -503,8 +506,7 @@ CompilePatternBindings::visit (HIR::TupleStructPattern &pattern)
tuple_field_index++,
pattern->get_locus ());
ctx->insert_pattern_binding (
pattern->get_mappings ().get_hirid (), binding);
CompilePatternBindings::Compile (*pattern, binding, ctx);
}
}
}
@@ -512,6 +514,71 @@ CompilePatternBindings::visit (HIR::TupleStructPattern &pattern)
}
}
tree
CompilePatternBindings::make_struct_access (TyTy::ADTType *adt,
TyTy::VariantDef *variant,
const Identifier &ident,
int variant_index)
{
size_t offs = 0;
auto ok = variant->lookup_field (ident.as_string (), nullptr, &offs);
rust_assert (ok);
if (adt->is_enum ())
{
tree payload_accessor_union
= Backend::struct_field_expression (match_scrutinee_expr, 1,
ident.get_locus ());
tree variant_accessor
= Backend::struct_field_expression (payload_accessor_union,
variant_index, ident.get_locus ());
return Backend::struct_field_expression (variant_accessor, offs,
ident.get_locus ());
}
else
{
tree variant_accessor = match_scrutinee_expr;
return Backend::struct_field_expression (variant_accessor, offs,
ident.get_locus ());
}
}
void
CompilePatternBindings::handle_struct_pattern_ident (
HIR::StructPatternField &pat, TyTy::ADTType *adt, TyTy::VariantDef *variant,
int variant_index)
{
HIR::StructPatternFieldIdent &ident
= static_cast<HIR::StructPatternFieldIdent &> (pat);
auto identifier = ident.get_identifier ();
tree binding = make_struct_access (adt, variant, identifier, variant_index);
ctx->insert_pattern_binding (ident.get_mappings ().get_hirid (), binding);
}
void
CompilePatternBindings::handle_struct_pattern_ident_pat (
HIR::StructPatternField &pat, TyTy::ADTType *adt, TyTy::VariantDef *variant,
int variant_index)
{
auto &pattern = static_cast<HIR::StructPatternFieldIdentPat &> (pat);
tree binding = make_struct_access (adt, variant, pattern.get_identifier (),
variant_index);
CompilePatternBindings::Compile (pattern.get_pattern (), binding, ctx);
}
void
CompilePatternBindings::handle_struct_pattern_tuple_pat (
HIR::StructPatternField &pat)
{
rust_unreachable ();
}
void
CompilePatternBindings::visit (HIR::StructPattern &pattern)
{
@@ -547,52 +614,14 @@ CompilePatternBindings::visit (HIR::StructPattern &pattern)
{
switch (field->get_item_type ())
{
case HIR::StructPatternField::ItemType::TUPLE_PAT: {
// TODO
rust_unreachable ();
}
case HIR::StructPatternField::ItemType::TUPLE_PAT:
handle_struct_pattern_tuple_pat (*field);
break;
case HIR::StructPatternField::ItemType::IDENT_PAT: {
// TODO
rust_unreachable ();
}
case HIR::StructPatternField::ItemType::IDENT_PAT:
handle_struct_pattern_ident_pat (*field, adt, variant, variant_index);
break;
case HIR::StructPatternField::ItemType::IDENT: {
HIR::StructPatternFieldIdent &ident
= static_cast<HIR::StructPatternFieldIdent &> (*field.get ());
size_t offs = 0;
ok = variant->lookup_field (ident.get_identifier ().as_string (),
nullptr, &offs);
rust_assert (ok);
tree binding = error_mark_node;
if (adt->is_enum ())
{
tree variant_accessor
= Backend::struct_field_expression (match_scrutinee_expr,
variant_index,
ident.get_locus ());
// we are offsetting by + 1 here since the first field in the
// record is always the discriminator
binding = Backend::struct_field_expression (variant_accessor,
offs + 1,
ident.get_locus ());
}
else
{
tree variant_accessor = match_scrutinee_expr;
binding
= Backend::struct_field_expression (variant_accessor, offs,
ident.get_locus ());
}
ctx->insert_pattern_binding (ident.get_mappings ().get_hirid (),
binding);
}
case HIR::StructPatternField::ItemType::IDENT:
handle_struct_pattern_ident (*field, adt, variant, variant_index);
break;
}
}
@@ -604,17 +633,111 @@ CompilePatternBindings::visit (HIR::ReferencePattern &pattern)
tree derefed
= indirect_expression (match_scrutinee_expr, pattern.get_locus ());
CompilePatternBindings::Compile (pattern.get_referenced_pattern ().get (),
derefed, ctx);
CompilePatternBindings::Compile (pattern.get_referenced_pattern (), derefed,
ctx);
}
void
CompilePatternBindings::visit (HIR::IdentifierPattern &pattern)
{
ctx->insert_pattern_binding (pattern.get_mappings ().get_hirid (),
match_scrutinee_expr);
if (!pattern.get_is_ref ())
{
ctx->insert_pattern_binding (pattern.get_mappings ().get_hirid (),
match_scrutinee_expr);
return;
}
tree ref = address_expression (match_scrutinee_expr,
EXPR_LOCATION (match_scrutinee_expr));
ctx->insert_pattern_binding (pattern.get_mappings ().get_hirid (), ref);
}
void
CompilePatternBindings::visit (HIR::TuplePattern &pattern)
{
rust_assert (pattern.has_tuple_pattern_items ());
// lookup the type
TyTy::BaseType *ty = nullptr;
bool ok
= ctx->get_tyctx ()->lookup_type (pattern.get_mappings ().get_hirid (),
&ty);
rust_assert (ok);
switch (pattern.get_items ().get_item_type ())
{
case HIR::TuplePatternItems::ItemType::RANGED: {
size_t tuple_idx = 0;
auto &items
= static_cast<HIR::TuplePatternItemsRanged &> (pattern.get_items ());
auto &items_lower = items.get_lower_patterns ();
auto &items_upper = items.get_upper_patterns ();
for (auto &sub : items_lower)
{
TyTy::BaseType *ty_sub = nullptr;
HirId sub_id = sub->get_mappings ().get_hirid ();
bool ok = ctx->get_tyctx ()->lookup_type (sub_id, &ty_sub);
rust_assert (ok);
tree sub_init
= Backend::struct_field_expression (match_scrutinee_expr,
tuple_idx, sub->get_locus ());
CompilePatternBindings::Compile (*sub.get (), sub_init, ctx);
tuple_idx++;
}
rust_assert (ty->get_kind () == TyTy::TypeKind::TUPLE);
tuple_idx = static_cast<TyTy::TupleType &> (*ty).num_fields ()
- items_upper.size ();
for (auto &sub : items_upper)
{
TyTy::BaseType *ty_sub = nullptr;
HirId sub_id = sub->get_mappings ().get_hirid ();
bool ok = ctx->get_tyctx ()->lookup_type (sub_id, &ty_sub);
rust_assert (ok);
tree sub_init
= Backend::struct_field_expression (match_scrutinee_expr,
tuple_idx, sub->get_locus ());
CompilePatternBindings::Compile (*sub.get (), sub_init, ctx);
tuple_idx++;
}
return;
}
case HIR::TuplePatternItems::ItemType::MULTIPLE: {
size_t tuple_idx = 0;
auto &items = static_cast<HIR::TuplePatternItemsMultiple &> (
pattern.get_items ());
for (auto &sub : items.get_patterns ())
{
TyTy::BaseType *ty_sub = nullptr;
HirId sub_id = sub->get_mappings ().get_hirid ();
bool ok = ctx->get_tyctx ()->lookup_type (sub_id, &ty_sub);
rust_assert (ok);
tree sub_init
= Backend::struct_field_expression (match_scrutinee_expr,
tuple_idx, sub->get_locus ());
CompilePatternBindings::Compile (*sub.get (), sub_init, ctx);
tuple_idx++;
}
return;
}
default: {
rust_unreachable ();
}
}
}
//
void
CompilePatternLet::visit (HIR::IdentifierPattern &pattern)
{
@@ -627,7 +750,7 @@ CompilePatternLet::visit (HIR::IdentifierPattern &pattern)
{
ctx->add_statement (init_expr);
auto unit_type_init_expr = unit_expression (ctx, rval_locus);
auto unit_type_init_expr = unit_expression (rval_locus);
auto s = Backend::init_statement (fnctx.fndecl, var, unit_type_init_expr);
ctx->add_statement (s);
}
@@ -665,12 +788,12 @@ CompilePatternLet::visit (HIR::TuplePattern &pattern)
tree access_expr = Backend::var_expression (tmp_var, pattern.get_locus ());
ctx->add_statement (init_stmt);
switch (pattern.get_items ()->get_item_type ())
switch (pattern.get_items ().get_item_type ())
{
case HIR::TuplePatternItems::ItemType::RANGED: {
size_t tuple_idx = 0;
auto &items
= static_cast<HIR::TuplePatternItemsRanged &> (*pattern.get_items ());
= static_cast<HIR::TuplePatternItemsRanged &> (pattern.get_items ());
auto &items_lower = items.get_lower_patterns ();
auto &items_upper = items.get_upper_patterns ();
@@ -714,7 +837,7 @@ CompilePatternLet::visit (HIR::TuplePattern &pattern)
case HIR::TuplePatternItems::ItemType::MULTIPLE: {
size_t tuple_idx = 0;
auto &items = static_cast<HIR::TuplePatternItemsMultiple &> (
*pattern.get_items ());
pattern.get_items ());
for (auto &sub : items.get_patterns ())
{

View File

@@ -17,7 +17,9 @@
// <http://www.gnu.org/licenses/>.
#include "rust-compile-base.h"
#include "rust-hir-pattern.h"
#include "rust-hir-visitor.h"
#include "rust-tyty.h"
namespace Rust {
namespace Compile {
@@ -26,11 +28,11 @@ class CompilePatternCheckExpr : public HIRCompileBase,
public HIR::HIRPatternVisitor
{
public:
static tree Compile (HIR::Pattern *pattern, tree match_scrutinee_expr,
static tree Compile (HIR::Pattern &pattern, tree match_scrutinee_expr,
Context *ctx)
{
CompilePatternCheckExpr compiler (ctx, match_scrutinee_expr);
pattern->accept_vis (compiler);
pattern.accept_vis (compiler);
rust_assert (compiler.check_expr);
return compiler.check_expr;
}
@@ -71,17 +73,31 @@ class CompilePatternBindings : public HIRCompileBase,
public HIR::HIRPatternVisitor
{
public:
static void Compile (HIR::Pattern *pattern, tree match_scrutinee_expr,
static void Compile (HIR::Pattern &pattern, tree match_scrutinee_expr,
Context *ctx)
{
CompilePatternBindings compiler (ctx, match_scrutinee_expr);
pattern->accept_vis (compiler);
pattern.accept_vis (compiler);
}
tree make_struct_access (TyTy::ADTType *adt, TyTy::VariantDef *variant,
const Identifier &ident, int variant_index);
void handle_struct_pattern_ident (HIR::StructPatternField &pat,
TyTy::ADTType *adt,
TyTy::VariantDef *variant,
int variant_index);
void handle_struct_pattern_ident_pat (HIR::StructPatternField &pat,
TyTy::ADTType *adt,
TyTy::VariantDef *variant,
int variant_index);
void handle_struct_pattern_tuple_pat (HIR::StructPatternField &pat);
void visit (HIR::StructPattern &pattern) override;
void visit (HIR::TupleStructPattern &pattern) override;
void visit (HIR::ReferencePattern &pattern) override;
void visit (HIR::IdentifierPattern &) override;
void visit (HIR::TuplePattern &pattern) override;
// Empty visit for unused Pattern HIR nodes.
void visit (HIR::AltPattern &) override {}
@@ -90,7 +106,6 @@ public:
void visit (HIR::QualifiedPathInExpression &) override {}
void visit (HIR::RangePattern &) override {}
void visit (HIR::SlicePattern &) override {}
void visit (HIR::TuplePattern &) override {}
void visit (HIR::WildcardPattern &) override {}
protected:

View File

@@ -17,96 +17,123 @@
// <http://www.gnu.org/licenses/>.
#include "rust-compile-resolve-path.h"
#include "options.h"
#include "rust-compile-intrinsic.h"
#include "rust-compile-item.h"
#include "rust-compile-implitem.h"
#include "rust-compile-expr.h"
#include "rust-hir-map.h"
#include "rust-hir-trait-resolve.h"
#include "rust-hir-path-probe.h"
#include "rust-compile-extern.h"
#include "rust-constexpr.h"
#include "rust-tyty.h"
namespace Rust {
namespace Compile {
void
ResolvePathRef::visit (HIR::QualifiedPathInExpression &expr)
tree
ResolvePathRef::Compile (HIR::QualifiedPathInExpression &expr, Context *ctx)
{
resolved = resolve (expr.get_final_segment ().get_segment (),
expr.get_mappings (), expr.get_locus (), true);
}
void
ResolvePathRef::visit (HIR::PathInExpression &expr)
{
resolved = resolve (expr.get_final_segment ().get_segment (),
expr.get_mappings (), expr.get_locus (), false);
ResolvePathRef resolver (ctx);
return resolver.resolve_path_like (expr);
}
tree
ResolvePathRef::resolve (const HIR::PathIdentSegment &final_segment,
const Analysis::NodeMapping &mappings,
location_t expr_locus, bool is_qualified_path)
ResolvePathRef::Compile (HIR::PathInExpression &expr, Context *ctx)
{
ResolvePathRef resolver (ctx);
return resolver.resolve_path_like (expr);
}
ResolvePathRef::ResolvePathRef (Context *ctx) : HIRCompileBase (ctx) {}
template <typename T>
tree
ResolvePathRef::resolve_path_like (T &expr)
{
if (expr.is_lang_item ())
{
auto lang_item
= Analysis::Mappings::get ().get_lang_item_node (expr.get_lang_item ());
// FIXME: Is that correct? :/
auto final_segment
= HIR::PathIdentSegment (LangItem::ToString (expr.get_lang_item ()));
return resolve_with_node_id (final_segment, expr.get_mappings (),
expr.get_locus (), true, lang_item);
}
return resolve (expr.get_final_segment ().get_segment (),
expr.get_mappings (), expr.get_locus (), true);
}
tree
ResolvePathRef::attempt_constructor_expression_lookup (
TyTy::BaseType *lookup, Context *ctx, const Analysis::NodeMapping &mappings,
location_t expr_locus)
{
// it might be an enum data-less enum variant
if (lookup->get_kind () != TyTy::TypeKind::ADT)
return error_mark_node;
TyTy::ADTType *adt = static_cast<TyTy::ADTType *> (lookup);
if (adt->is_unit ())
return unit_expression (expr_locus);
if (!adt->is_enum ())
return error_mark_node;
HirId variant_id;
if (!ctx->get_tyctx ()->lookup_variant_definition (mappings.get_hirid (),
&variant_id))
return error_mark_node;
int union_disriminator = -1;
TyTy::VariantDef *variant = nullptr;
if (!adt->lookup_variant_by_id (variant_id, &variant, &union_disriminator))
return error_mark_node;
// this can only be for discriminant variants the others are built up
// using call-expr or struct-init
rust_assert (variant->get_variant_type ()
== TyTy::VariantDef::VariantType::NUM);
// we need the actual gcc type
tree compiled_adt_type = TyTyResolveCompile::compile (ctx, adt);
// make the ctor for the union
HIR::Expr &discrim_expr = variant->get_discriminant ();
ctx->push_const_context ();
tree discrim_expr_node = CompileExpr::Compile (discrim_expr, ctx);
ctx->pop_const_context ();
tree folded_discrim_expr = fold_expr (discrim_expr_node);
tree qualifier = folded_discrim_expr;
// false for is enum but this is an enum but we have a new layout
return Backend::constructor_expression (compiled_adt_type, false, {qualifier},
-1, expr_locus);
}
tree
ResolvePathRef::resolve_with_node_id (
const HIR::PathIdentSegment &final_segment,
const Analysis::NodeMapping &mappings, location_t expr_locus,
bool is_qualified_path, NodeId resolved_node_id)
{
TyTy::BaseType *lookup = nullptr;
bool ok = ctx->get_tyctx ()->lookup_type (mappings.get_hirid (), &lookup);
rust_assert (ok);
// need to look up the reference for this identifier
NodeId ref_node_id = UNKNOWN_NODEID;
if (!ctx->get_resolver ()->lookup_resolved_name (mappings.get_nodeid (),
&ref_node_id))
{
// this can fail because it might be a Constructor for something
// in that case the caller should attempt ResolvePathType::Compile
// it might be an enum data-less enum variant
if (lookup->get_kind () != TyTy::TypeKind::ADT)
return error_mark_node;
TyTy::ADTType *adt = static_cast<TyTy::ADTType *> (lookup);
if (adt->is_unit ())
return unit_expression (ctx, expr_locus);
if (!adt->is_enum ())
return error_mark_node;
HirId variant_id;
if (!ctx->get_tyctx ()->lookup_variant_definition (mappings.get_hirid (),
&variant_id))
return error_mark_node;
int union_disriminator = -1;
TyTy::VariantDef *variant = nullptr;
if (!adt->lookup_variant_by_id (variant_id, &variant,
&union_disriminator))
return error_mark_node;
// this can only be for discriminant variants the others are built up
// using call-expr or struct-init
rust_assert (variant->get_variant_type ()
== TyTy::VariantDef::VariantType::NUM);
// we need the actual gcc type
tree compiled_adt_type = TyTyResolveCompile::compile (ctx, adt);
// make the ctor for the union
HIR::Expr *discrim_expr = variant->get_discriminant ();
tree discrim_expr_node = CompileExpr::Compile (discrim_expr, ctx);
tree folded_discrim_expr = fold_expr (discrim_expr_node);
tree qualifier = folded_discrim_expr;
return Backend::constructor_expression (compiled_adt_type, true,
{qualifier}, union_disriminator,
expr_locus);
}
HirId ref;
if (!ctx->get_mappings ()->lookup_node_to_hir (ref_node_id, &ref))
tl::optional<HirId> hid
= ctx->get_mappings ().lookup_node_to_hir (resolved_node_id);
if (!hid.has_value ())
{
rust_error_at (expr_locus, "reverse call path lookup failure");
return error_mark_node;
}
auto ref = hid.value ();
// might be a constant
tree constant_expr;
@@ -159,6 +186,11 @@ ResolvePathRef::resolve (const HIR::PathIdentSegment &final_segment,
}
}
// Handle unit struct
if (lookup->get_kind () == TyTy::TypeKind::ADT)
return attempt_constructor_expression_lookup (lookup, ctx, mappings,
expr_locus);
// let the query system figure it out
tree resolved_item = query_compile (ref, lookup, final_segment, mappings,
expr_locus, is_qualified_path);
@@ -166,39 +198,73 @@ ResolvePathRef::resolve (const HIR::PathIdentSegment &final_segment,
{
TREE_USED (resolved_item) = 1;
}
return resolved_item;
}
tree
ResolvePathRef::resolve (const HIR::PathIdentSegment &final_segment,
const Analysis::NodeMapping &mappings,
location_t expr_locus, bool is_qualified_path)
{
TyTy::BaseType *lookup = nullptr;
bool ok = ctx->get_tyctx ()->lookup_type (mappings.get_hirid (), &lookup);
rust_assert (ok);
// need to look up the reference for this identifier
// this can fail because it might be a Constructor for something
// in that case the caller should attempt ResolvePathType::Compile
NodeId ref_node_id = UNKNOWN_NODEID;
if (flag_name_resolution_2_0)
{
auto &nr_ctx
= Resolver2_0::ImmutableNameResolutionContext::get ().resolver ();
auto resolved = nr_ctx.lookup (mappings.get_nodeid ());
if (!resolved)
return attempt_constructor_expression_lookup (lookup, ctx, mappings,
expr_locus);
ref_node_id = *resolved;
}
else
{
if (!ctx->get_resolver ()->lookup_resolved_name (mappings.get_nodeid (),
&ref_node_id))
return attempt_constructor_expression_lookup (lookup, ctx, mappings,
expr_locus);
}
return resolve_with_node_id (final_segment, mappings, expr_locus,
is_qualified_path, ref_node_id);
}
tree
HIRCompileBase::query_compile (HirId ref, TyTy::BaseType *lookup,
const HIR::PathIdentSegment &final_segment,
const Analysis::NodeMapping &mappings,
location_t expr_locus, bool is_qualified_path)
{
HIR::Item *resolved_item = ctx->get_mappings ()->lookup_hir_item (ref);
HirId parent_block;
HIR::ExternalItem *resolved_extern_item
= ctx->get_mappings ()->lookup_hir_extern_item (ref, &parent_block);
bool is_hir_item = resolved_item != nullptr;
bool is_hir_extern_item = resolved_extern_item != nullptr;
bool is_fn = lookup->get_kind () == TyTy::TypeKind::FNDEF;
if (is_hir_item)
if (auto resolved_item = ctx->get_mappings ().lookup_hir_item (ref))
{
if (!lookup->has_substitutions_defined ())
return CompileItem::compile (resolved_item, ctx, nullptr, true,
expr_locus);
return CompileItem::compile (*resolved_item, ctx, nullptr, expr_locus);
else
return CompileItem::compile (resolved_item, ctx, lookup, true,
expr_locus);
return CompileItem::compile (*resolved_item, ctx, lookup, expr_locus);
}
else if (is_hir_extern_item)
else if (auto hir_extern_item
= ctx->get_mappings ().lookup_hir_extern_item (ref))
{
HIR::ExternalItem *resolved_extern_item = hir_extern_item->first;
if (!lookup->has_substitutions_defined ())
return CompileExternItem::compile (resolved_extern_item, ctx, nullptr,
true, expr_locus);
expr_locus);
else
return CompileExternItem::compile (resolved_extern_item, ctx, lookup,
true, expr_locus);
expr_locus);
}
else
{
@@ -216,26 +282,20 @@ HIRCompileBase::query_compile (HirId ref, TyTy::BaseType *lookup,
}
}
HirId parent_impl_id = UNKNOWN_HIRID;
HIR::ImplItem *resolved_item
= ctx->get_mappings ()->lookup_hir_implitem (ref, &parent_impl_id);
bool is_impl_item = resolved_item != nullptr;
if (is_impl_item)
if (auto resolved_item = ctx->get_mappings ().lookup_hir_implitem (ref))
{
if (!lookup->has_substitutions_defined ())
return CompileInherentImplItem::Compile (resolved_item, ctx,
nullptr, true, expr_locus);
return CompileInherentImplItem::Compile (resolved_item->first, ctx,
nullptr, expr_locus);
else
return CompileInherentImplItem::Compile (resolved_item, ctx, lookup,
true, expr_locus);
return CompileInherentImplItem::Compile (resolved_item->first, ctx,
lookup, expr_locus);
}
else
else if (auto trait_item
= ctx->get_mappings ().lookup_hir_trait_item (ref))
{
// it might be resolved to a trait item
HIR::TraitItem *trait_item
= ctx->get_mappings ()->lookup_hir_trait_item (ref);
HIR::Trait *trait = ctx->get_mappings ()->lookup_trait_item_mapping (
trait_item->get_mappings ().get_hirid ());
HIR::Trait *trait = ctx->get_mappings ().lookup_trait_item_mapping (
trait_item.value ()->get_mappings ().get_hirid ());
Resolver::TraitReference *trait_ref
= &Resolver::TraitReference::error_node ();
@@ -243,16 +303,41 @@ HIRCompileBase::query_compile (HirId ref, TyTy::BaseType *lookup,
trait->get_mappings ().get_defid (), &trait_ref);
rust_assert (ok);
TyTy::BaseType *receiver = nullptr;
ok = ctx->get_tyctx ()->lookup_receiver (mappings.get_hirid (),
&receiver);
rust_assert (ok);
receiver = receiver->destructure ();
if (trait_item.value ()->get_item_kind ()
== HIR::TraitItem::TraitItemKind::CONST)
{
auto &c
= *static_cast<HIR::TraitItemConst *> (trait_item.value ());
if (!c.has_expr ())
{
rich_location r (line_table, expr_locus);
r.add_range (trait->get_locus ());
r.add_range (c.get_locus ());
rust_error_at (r, "no default expression on trait constant");
return error_mark_node;
}
return CompileExpr::Compile (c.get_expr (), ctx);
}
if (trait_item.value ()->get_item_kind ()
!= HIR::TraitItem::TraitItemKind::FUNC)
return error_mark_node;
// the type resolver can only resolve type bounds to their trait
// item so its up to us to figure out if this path should resolve
// to an trait-impl-block-item or if it can be defaulted to the
// trait-impl-item's definition
//
// because we know this is resolved to a trait item we can actually
// just grab the Self type parameter here for the receiver to match
// the appropriate impl block
rust_assert (lookup->is<TyTy::FnType> ());
auto fn = lookup->as<TyTy::FnType> ();
rust_assert (fn->get_num_type_params () > 0);
auto &self = fn->get_substs ().at (0);
auto receiver = self.get_param_ty ();
auto candidates
= Resolver::PathProbeImplTrait::Probe (receiver, final_segment,
trait_ref);
@@ -261,7 +346,7 @@ HIRCompileBase::query_compile (HirId ref, TyTy::BaseType *lookup,
// this means we are defaulting back to the trait_item if
// possible
Resolver::TraitItemReference *trait_item_ref = nullptr;
bool ok = trait_ref->lookup_hir_trait_item (*trait_item,
bool ok = trait_ref->lookup_hir_trait_item (*trait_item.value (),
&trait_item_ref);
rust_assert (ok); // found
rust_assert (trait_item_ref->is_optional ()); // has definition
@@ -282,16 +367,15 @@ HIRCompileBase::query_compile (HirId ref, TyTy::BaseType *lookup,
TyTy::BaseType *self = nullptr;
bool ok = ctx->get_tyctx ()->lookup_type (
impl->get_type ()->get_mappings ().get_hirid (), &self);
impl->get_type ().get_mappings ().get_hirid (), &self);
rust_assert (ok);
if (!lookup->has_substitutions_defined ())
return CompileInherentImplItem::Compile (impl_item, ctx,
nullptr, true,
expr_locus);
nullptr, expr_locus);
else
return CompileInherentImplItem::Compile (impl_item, ctx, lookup,
true, expr_locus);
expr_locus);
}
}
}

View File

@@ -20,52 +20,44 @@
#define RUST_COMPILE_RESOLVE_PATH
#include "rust-compile-base.h"
#include "rust-hir-visitor.h"
namespace Rust {
namespace Compile {
class ResolvePathRef : public HIRCompileBase, public HIR::HIRPatternVisitor
class ResolvePathRef : public HIRCompileBase
{
public:
static tree Compile (HIR::QualifiedPathInExpression &expr, Context *ctx)
{
ResolvePathRef resolver (ctx);
expr.accept_vis (resolver);
return resolver.resolved;
}
static tree Compile (HIR::QualifiedPathInExpression &expr, Context *ctx);
static tree Compile (HIR::PathInExpression &expr, Context *ctx)
{
ResolvePathRef resolver (ctx);
expr.accept_vis (resolver);
return resolver.resolved;
}
static tree Compile (HIR::PathInExpression &expr, Context *ctx);
void visit (HIR::PathInExpression &expr) override;
void visit (HIR::QualifiedPathInExpression &expr) override;
ResolvePathRef (Context *ctx);
// Empty visit for unused Pattern HIR nodes.
void visit (HIR::IdentifierPattern &) override {}
void visit (HIR::LiteralPattern &) override {}
void visit (HIR::RangePattern &) override {}
void visit (HIR::ReferencePattern &) override {}
void visit (HIR::SlicePattern &) override {}
void visit (HIR::AltPattern &) override {}
void visit (HIR::StructPattern &) override {}
void visit (HIR::TuplePattern &) override {}
void visit (HIR::TupleStructPattern &) override {}
void visit (HIR::WildcardPattern &) override {}
ResolvePathRef (Context *ctx)
: HIRCompileBase (ctx), resolved (error_mark_node)
{}
/**
* Generic visitor for both PathInExpression and QualifiedPathInExpression
*/
template <typename T> tree resolve_path_like (T &expr);
/**
* Inner implementation of `resolve` - resolution with an already known NodeId
*/
tree resolve_with_node_id (const HIR::PathIdentSegment &final_segment,
const Analysis::NodeMapping &mappings,
location_t locus, bool is_qualified_path,
NodeId resolved_node_id);
/**
* Resolve a mappings' NodeId and call into `resolve_with_node_id` which
* performs the rest of the path resolution
*/
tree resolve (const HIR::PathIdentSegment &final_segment,
const Analysis::NodeMapping &mappings, location_t locus,
bool is_qualified_path);
tree resolved;
private:
tree
attempt_constructor_expression_lookup (TyTy::BaseType *lookup, Context *ctx,
const Analysis::NodeMapping &mappings,
location_t expr_locus);
};
} // namespace Compile

View File

@@ -40,13 +40,13 @@ CompileStmt::Compile (HIR::Stmt *stmt, Context *ctx)
void
CompileStmt::visit (HIR::ExprStmt &stmt)
{
translated = CompileExpr::Compile (stmt.get_expr ().get (), ctx);
translated = CompileExpr::Compile (stmt.get_expr (), ctx);
}
void
CompileStmt::visit (HIR::LetStmt &stmt)
{
HIR::Pattern &stmt_pattern = *stmt.get_pattern ();
HIR::Pattern &stmt_pattern = stmt.get_pattern ();
HirId stmt_id = stmt_pattern.get_mappings ().get_hirid ();
TyTy::BaseType *ty = nullptr;
@@ -68,7 +68,7 @@ CompileStmt::visit (HIR::LetStmt &stmt)
if (!stmt.has_init_expr ())
return;
tree init = CompileExpr::Compile (stmt.get_init_expr ().get (), ctx);
tree init = CompileExpr::Compile (stmt.get_init_expr (), ctx);
// FIXME use error_mark_node, check that CompileExpr returns error_mark_node
// on failure and make this an assertion
if (init == nullptr)
@@ -76,11 +76,11 @@ CompileStmt::visit (HIR::LetStmt &stmt)
TyTy::BaseType *actual = nullptr;
bool ok = ctx->get_tyctx ()->lookup_type (
stmt.get_init_expr ()->get_mappings ().get_hirid (), &actual);
stmt.get_init_expr ().get_mappings ().get_hirid (), &actual);
rust_assert (ok);
location_t lvalue_locus = stmt.get_pattern ()->get_locus ();
location_t rvalue_locus = stmt.get_init_expr ()->get_locus ();
location_t lvalue_locus = stmt.get_pattern ().get_locus ();
location_t rvalue_locus = stmt.get_init_expr ().get_locus ();
TyTy::BaseType *expected = ty;
init = coercion_site (stmt.get_mappings ().get_hirid (), init, actual,
expected, lvalue_locus, rvalue_locus);

View File

@@ -27,22 +27,22 @@ CompileStructExprField::CompileStructExprField (Context *ctx)
{}
tree
CompileStructExprField::Compile (HIR::StructExprField *field, Context *ctx)
CompileStructExprField::Compile (HIR::StructExprField &field, Context *ctx)
{
CompileStructExprField compiler (ctx);
switch (field->get_kind ())
switch (field.get_kind ())
{
case HIR::StructExprField::StructExprFieldKind::IDENTIFIER:
compiler.visit (static_cast<HIR::StructExprFieldIdentifier &> (*field));
compiler.visit (static_cast<HIR::StructExprFieldIdentifier &> (field));
break;
case HIR::StructExprField::StructExprFieldKind::IDENTIFIER_VALUE:
compiler.visit (
static_cast<HIR::StructExprFieldIdentifierValue &> (*field));
static_cast<HIR::StructExprFieldIdentifierValue &> (field));
break;
case HIR::StructExprField::StructExprFieldKind::INDEX_VALUE:
compiler.visit (static_cast<HIR::StructExprFieldIndexValue &> (*field));
compiler.visit (static_cast<HIR::StructExprFieldIndexValue &> (field));
break;
}
return compiler.translated;
@@ -51,13 +51,13 @@ CompileStructExprField::Compile (HIR::StructExprField *field, Context *ctx)
void
CompileStructExprField::visit (HIR::StructExprFieldIdentifierValue &field)
{
translated = CompileExpr::Compile (field.get_value ().get (), ctx);
translated = CompileExpr::Compile (field.get_value (), ctx);
}
void
CompileStructExprField::visit (HIR::StructExprFieldIndexValue &field)
{
translated = CompileExpr::Compile (field.get_value ().get (), ctx);
translated = CompileExpr::Compile (field.get_value (), ctx);
}
void
@@ -74,7 +74,7 @@ CompileStructExprField::visit (HIR::StructExprFieldIdentifier &field)
HIR::GenericArgs::create_empty ());
HIR::PathInExpression expr (mappings_copy2, {seg}, field.get_locus (), false,
{});
translated = CompileExpr::Compile (&expr, ctx);
translated = CompileExpr::Compile (expr, ctx);
}
} // namespace Compile

View File

@@ -27,7 +27,7 @@ namespace Compile {
class CompileStructExprField : private HIRCompileBase
{
public:
static tree Compile (HIR::StructExprField *field, Context *ctx);
static tree Compile (HIR::StructExprField &field, Context *ctx);
protected:
void visit (HIR::StructExprFieldIdentifierValue &field);

View File

@@ -22,6 +22,7 @@
#include "rust-gcc.h"
#include "tree.h"
#include "stor-layout.h"
namespace Rust {
namespace Compile {
@@ -54,7 +55,7 @@ TyTyResolveCompile::compile (Context *ctx, const TyTy::BaseType *ty,
// see: gcc/c/c-decl.cc:8230-8241
// https://github.com/Rust-GCC/gccrs/blob/0024bc2f028369b871a65ceb11b2fddfb0f9c3aa/gcc/c/c-decl.c#L8229-L8241
tree
TyTyResolveCompile::get_implicit_enumeral_node_type (Context *ctx)
TyTyResolveCompile::get_implicit_enumeral_node_type (TyTy::BaseType *repr)
{
// static tree enum_node = NULL_TREE;
// if (enum_node == NULL_TREE)
@@ -76,15 +77,7 @@ TyTyResolveCompile::get_implicit_enumeral_node_type (Context *ctx)
// }
// return enum_node;
static tree enum_node = NULL_TREE;
if (enum_node == NULL_TREE)
{
// equivalent to isize
enum_node = Backend::named_type (
"enumeral", Backend::integer_type (false, Backend::get_pointer_size ()),
BUILTINS_LOCATION);
}
return enum_node;
return compile (ctx, repr);
}
tree
@@ -93,8 +86,17 @@ TyTyResolveCompile::get_unit_type (Context *ctx)
static tree unit_type;
if (unit_type == nullptr)
{
auto cn = ctx->get_mappings ().get_current_crate ();
auto &c = ctx->get_mappings ().get_ast_crate (cn);
location_t locus = BUILTINS_LOCATION;
if (c.items.size () > 0)
{
auto &item = c.items[0];
locus = item->get_locus ();
}
auto unit_type_node = Backend::struct_type ({});
unit_type = Backend::named_type ("()", unit_type_node, BUILTINS_LOCATION);
unit_type = Backend::named_type ("()", unit_type_node, locus);
}
return unit_type;
}
@@ -147,7 +149,7 @@ TyTyResolveCompile::visit (const TyTy::PlaceholderType &type)
void
TyTyResolveCompile::visit (const TyTy::ClosureType &type)
{
auto mappings = ctx->get_mappings ();
auto &mappings = ctx->get_mappings ();
std::vector<Backend::typed_identifier> fields;
@@ -155,9 +157,9 @@ TyTyResolveCompile::visit (const TyTy::ClosureType &type)
for (const auto &capture : type.get_captures ())
{
// lookup the HirId
HirId ref = UNKNOWN_HIRID;
bool ok = mappings->lookup_node_to_hir (capture, &ref);
rust_assert (ok);
tl::optional<HirId> hid = mappings.lookup_node_to_hir (capture);
rust_assert (hid.has_value ());
auto ref = hid.value ();
// lookup the var decl type
TyTy::BaseType *lookup = nullptr;
@@ -201,20 +203,20 @@ TyTyResolveCompile::visit (const TyTy::FnType &type)
{
auto ret = TyTyResolveCompile::compile (ctx, hir_type, trait_object_mode);
location_t return_type_locus
= ctx->get_mappings ()->lookup_location (hir_type->get_ref ());
= ctx->get_mappings ().lookup_location (hir_type->get_ref ());
results.push_back (
Backend::typed_identifier ("_", ret, return_type_locus));
}
for (auto &param_pair : type.get_params ())
{
auto param_tyty = param_pair.second;
auto param_tyty = param_pair.get_type ();
auto compiled_param_type
= TyTyResolveCompile::compile (ctx, param_tyty, trait_object_mode);
auto compiled_param = Backend::typed_identifier (
param_pair.first->as_string (), compiled_param_type,
ctx->get_mappings ()->lookup_location (param_tyty->get_ref ()));
param_pair.get_pattern ().as_string (), compiled_param_type,
ctx->get_mappings ().lookup_location (param_tyty->get_ref ()));
parameters.push_back (compiled_param);
}
@@ -263,13 +265,13 @@ TyTyResolveCompile::visit (const TyTy::ADTType &type)
= TyTyResolveCompile::compile (ctx, field->get_field_type ());
Backend::typed_identifier f (field->get_name (), compiled_field_ty,
ctx->get_mappings ()->lookup_location (
ctx->get_mappings ().lookup_location (
type.get_ty_ref ()));
fields.push_back (std::move (f));
}
type_record = type.is_union () ? Backend::union_type (fields)
: Backend::struct_type (fields);
type_record = type.is_union () ? Backend::union_type (fields, false)
: Backend::struct_type (fields, false);
}
else
{
@@ -297,21 +299,39 @@ TyTyResolveCompile::visit (const TyTy::ADTType &type)
// Ada, qual_union_types might still work for this but I am not 100% sure.
// I ran into some issues lets reuse our normal union and ask Ada people
// about it.
//
// I think the above is actually wrong and it should actually be this
//
// struct {
// int RUST$ENUM$DISR; // take into account the repr for this TODO
// union {
// // Variant A
// struct {
// // No additional fields
// } A;
// // Variant B
// struct {
// // No additional fields
// } B;
// // Variant C
// struct {
// char c;
// } C;
// // Variant D
// struct {
// int64_t x;
// int64_t y;
// } D;
// } payload; // The union of all variant data
// };
std::vector<tree> variant_records;
for (auto &variant : type.get_variants ())
{
std::vector<Backend::typed_identifier> fields;
// add in the qualifier field for the variant
tree enumeral_type
= TyTyResolveCompile::get_implicit_enumeral_node_type (ctx);
Backend::typed_identifier f (RUST_ENUM_DISR_FIELD_NAME, enumeral_type,
ctx->get_mappings ()->lookup_location (
variant->get_id ()));
fields.push_back (std::move (f));
// compile the rest of the fields
for (size_t i = 0; i < variant->num_fields (); i++)
{
const TyTy::StructFieldType *field
@@ -326,7 +346,7 @@ TyTyResolveCompile::visit (const TyTy::ADTType &type)
Backend::typed_identifier f (
field_name, compiled_field_ty,
ctx->get_mappings ()->lookup_location (type.get_ty_ref ()));
ctx->get_mappings ().lookup_location (type.get_ty_ref ()));
fields.push_back (std::move (f));
}
@@ -335,9 +355,6 @@ TyTyResolveCompile::visit (const TyTy::ADTType &type)
= Backend::named_type (variant->get_ident ().path.get (),
variant_record, variant->get_ident ().locus);
// set the qualifier to be a builtin
DECL_ARTIFICIAL (TYPE_FIELDS (variant_record)) = 1;
// add them to the list
variant_records.push_back (named_variant_record);
}
@@ -353,13 +370,32 @@ TyTyResolveCompile::visit (const TyTy::ADTType &type)
std::string implicit_variant_name = variant->get_identifier ();
Backend::typed_identifier f (implicit_variant_name, variant_record,
ctx->get_mappings ()->lookup_location (
ctx->get_mappings ().lookup_location (
type.get_ty_ref ()));
enum_fields.push_back (std::move (f));
}
//
location_t locus = ctx->get_mappings ().lookup_location (type.get_ref ());
// finally make the union or the enum
type_record = Backend::union_type (enum_fields);
tree variants_union = Backend::union_type (enum_fields, false);
layout_type (variants_union);
tree named_union_record
= Backend::named_type ("payload", variants_union, locus);
// create the overall struct
tree enumeral_type = TyTyResolveCompile::get_implicit_enumeral_node_type (
type.get_repr_options ().repr);
Backend::typed_identifier discrim (RUST_ENUM_DISR_FIELD_NAME,
enumeral_type, locus);
Backend::typed_identifier variants_union_field ("payload",
named_union_record,
locus);
std::vector<Backend::typed_identifier> fields
= {discrim, variants_union_field};
type_record = Backend::struct_type (fields, false);
}
// Handle repr options
@@ -381,6 +417,7 @@ TyTyResolveCompile::visit (const TyTy::ADTType &type)
SET_TYPE_ALIGN (type_record, repr.align * 8);
TYPE_USER_ALIGN (type_record) = 1;
}
layout_type (type_record);
std::string named_struct_str
= type.get_ident ().path.get () + type.subst_as_string ();
@@ -411,13 +448,13 @@ TyTyResolveCompile::visit (const TyTy::TupleType &type)
// approach makes it simpler to use a C-only debugger, or
// GDB's C mode, when debugging Rust.
Backend::typed_identifier f ("__" + std::to_string (i), compiled_field_ty,
ctx->get_mappings ()->lookup_location (
ctx->get_mappings ().lookup_location (
type.get_ty_ref ()));
fields.push_back (std::move (f));
}
tree struct_type_record = Backend::struct_type (fields);
translated = Backend::named_type (type.as_string (), struct_type_record,
translated = Backend::named_type (type.get_name (), struct_type_record,
type.get_ident ().locus);
}
@@ -428,12 +465,24 @@ TyTyResolveCompile::visit (const TyTy::ArrayType &type)
= TyTyResolveCompile::compile (ctx, type.get_element_type ());
ctx->push_const_context ();
tree capacity_expr = CompileExpr::Compile (&type.get_capacity_expr (), ctx);
HIR::Expr &hir_capacity_expr = type.get_capacity_expr ();
TyTy::BaseType *capacity_expr_ty = nullptr;
bool ok = ctx->get_tyctx ()->lookup_type (
hir_capacity_expr.get_mappings ().get_hirid (), &capacity_expr_ty);
rust_assert (ok);
tree capacity_expr = HIRCompileBase::compile_constant_expr (
ctx, hir_capacity_expr.get_mappings ().get_hirid (), capacity_expr_ty,
capacity_expr_ty, Resolver::CanonicalPath::create_empty (),
hir_capacity_expr, type.get_locus (), hir_capacity_expr.get_locus ());
ctx->pop_const_context ();
tree folded_capacity_expr = fold_expr (capacity_expr);
translated = Backend::array_type (element_type, folded_capacity_expr);
if (translated != error_mark_node)
translated = ctx->insert_compiled_type (translated);
}
void
@@ -703,6 +752,14 @@ TyTyResolveCompile::visit (const TyTy::DynamicObjectType &type)
type.get_ident ().locus);
}
void
TyTyResolveCompile::visit (const TyTy::OpaqueType &type)
{
rust_assert (type.can_resolve ());
auto underlying = type.resolve ();
translated = TyTyResolveCompile::compile (ctx, underlying, trait_object_mode);
}
tree
TyTyResolveCompile::create_dyn_obj_record (const TyTy::DynamicObjectType &type)
{
@@ -714,14 +771,14 @@ TyTyResolveCompile::create_dyn_obj_record (const TyTy::DynamicObjectType &type)
tree uintptr_ty = build_pointer_type (uint);
Backend::typed_identifier f ("pointer", uintptr_ty,
ctx->get_mappings ()->lookup_location (
ctx->get_mappings ().lookup_location (
type.get_ty_ref ()));
fields.push_back (std::move (f));
tree vtable_size = build_int_cst (size_type_node, items.size ());
tree vtable_type = Backend::array_type (uintptr_ty, vtable_size);
Backend::typed_identifier vtf ("vtable", vtable_type,
ctx->get_mappings ()->lookup_location (
ctx->get_mappings ().lookup_location (
type.get_ty_ref ()));
fields.push_back (std::move (vtf));

View File

@@ -30,8 +30,6 @@ public:
static tree compile (Context *ctx, const TyTy::BaseType *ty,
bool trait_object_mode = false);
static tree get_implicit_enumeral_node_type (Context *ctx);
static tree get_unit_type (Context *ctx);
void visit (const TyTy::InferType &) override;
@@ -58,6 +56,7 @@ public:
void visit (const TyTy::ProjectionType &) override;
void visit (const TyTy::DynamicObjectType &) override;
void visit (const TyTy::ClosureType &) override;
void visit (const TyTy::OpaqueType &) override;
public:
static hashval_t type_hasher (tree type);
@@ -66,6 +65,7 @@ protected:
tree create_slice_type_record (const TyTy::SliceType &type);
tree create_str_type_record (const TyTy::StrType &type);
tree create_dyn_obj_record (const TyTy::DynamicObjectType &type);
tree get_implicit_enumeral_node_type (TyTy::BaseType *repr);
private:
TyTyResolveCompile (Context *ctx, bool trait_object_mode);

View File

@@ -68,12 +68,12 @@ public:
void visit (HIR::TuplePattern &pattern) override
{
switch (pattern.get_items ()->get_item_type ())
switch (pattern.get_items ().get_item_type ())
{
case HIR::TuplePatternItems::ItemType::MULTIPLE: {
rust_assert (TREE_CODE (translated_type) == RECORD_TYPE);
auto &items = static_cast<HIR::TuplePatternItemsMultiple &> (
*pattern.get_items ());
pattern.get_items ());
size_t offs = 0;
for (auto &sub : items.get_patterns ())

View File

@@ -189,7 +189,7 @@ HIRCompileBase::coerce_to_dyn_object (tree compiled_ref,
location_t locus)
{
// DST's get wrapped in a pseudo reference that doesnt exist...
const TyTy::ReferenceType r (ctx->get_mappings ()->get_next_hir_id (),
const TyTy::ReferenceType r (ctx->get_mappings ().get_next_hir_id (),
TyTy::TyVar (ty->get_ref ()), Mutability::Imm);
tree dynamic_object = TyTyResolveCompile::compile (ctx, &r);
@@ -241,100 +241,84 @@ HIRCompileBase::compute_address_for_trait_item (
&receiver_bounds,
const TyTy::BaseType *receiver, const TyTy::BaseType *root, location_t locus)
{
// There are two cases here one where its an item which has an implementation
// within a trait-impl-block. Then there is the case where there is a default
// implementation for this within the trait.
//
// The awkward part here is that this might be a generic trait and we need to
// figure out the correct monomorphized type for this so we can resolve the
// address of the function , this is stored as part of the
// type-bound-predicate
//
// Algo:
// check if there is an impl-item for this trait-item-ref first
// else assert that the trait-item-ref has an implementation
//
// FIXME this does not support super traits
TyTy::TypeBoundPredicateItem predicate_item
= predicate->lookup_associated_item (ref->get_identifier ());
rust_assert (!predicate_item.is_error ());
// this is the expected end type
// This is the expected end type
TyTy::BaseType *trait_item_type = predicate_item.get_tyty_for_receiver (root);
rust_assert (trait_item_type->get_kind () == TyTy::TypeKind::FNDEF);
TyTy::FnType *trait_item_fntype
= static_cast<TyTy::FnType *> (trait_item_type);
// find impl-block for this trait-item-ref
HIR::ImplBlock *associated_impl_block = nullptr;
const Resolver::TraitReference *predicate_trait_ref = predicate->get ();
// Loop through the list of trait references and impls that we satisfy.
// We are looking for one that has an implementation for "ref", a trait
// item.
for (auto &item : receiver_bounds)
{
Resolver::TraitReference *trait_ref = item.first;
HIR::ImplBlock *impl_block = item.second;
if (predicate_trait_ref->is_equal (*trait_ref))
{
associated_impl_block = impl_block;
break;
}
}
rust_assert (impl_block != nullptr);
// FIXME this probably should just return error_mark_node but this helps
// debug for now since we are wrongly returning early on type-resolution
// failures, until we take advantage of more error types and error_mark_node
rust_assert (associated_impl_block != nullptr);
// lookup self for the associated impl
std::unique_ptr<HIR::Type> &self_type_path
= associated_impl_block->get_type ();
TyTy::BaseType *self = nullptr;
bool ok = ctx->get_tyctx ()->lookup_type (
self_type_path->get_mappings ().get_hirid (), &self);
rust_assert (ok);
// lookup the predicate item from the self
TyTy::TypeBoundPredicate *self_bound = nullptr;
for (auto &bound : self->get_specified_bounds ())
{
const Resolver::TraitReference *bound_ref = bound.get ();
const Resolver::TraitReference *specified_ref = predicate->get ();
if (bound_ref->is_equal (*specified_ref))
{
self_bound = &bound;
break;
}
}
rust_assert (self_bound != nullptr);
// lookup the associated item from the associated impl block
TyTy::TypeBoundPredicateItem associated_self_item
= self_bound->lookup_associated_item (ref->get_identifier ());
rust_assert (!associated_self_item.is_error ());
// Lookup the impl-block for the associated impl_item if it exists
HIR::Function *associated_function = nullptr;
for (auto &impl_item : associated_impl_block->get_impl_items ())
{
bool is_function = impl_item->get_impl_item_type ()
== HIR::ImplItem::ImplItemType::FUNCTION;
if (!is_function)
// Checks for empty impl blocks, triggered by Sized trait.
if (!impl_block->has_type ())
continue;
HIR::Function *fn = static_cast<HIR::Function *> (impl_item.get ());
bool found_associated_item
= fn->get_function_name ().as_string ().compare (ref->get_identifier ())
== 0;
if (found_associated_item)
associated_function = fn;
}
// Lookup type for potentially associated impl.
HIR::Type &self_type_path = impl_block->get_type ();
// Convert HIR::Type to TyTy::BaseType
TyTy::BaseType *self = nullptr;
bool ok = ctx->get_tyctx ()->lookup_type (
self_type_path.get_mappings ().get_hirid (), &self);
rust_assert (ok);
// Look through the relevant bounds on our type, and find which one our
// impl block satisfies
TyTy::TypeBoundPredicate *self_bound = nullptr;
for (auto &bound : self->get_specified_bounds ())
{
const Resolver::TraitReference *bound_ref = bound.get ();
const Resolver::TraitReference *specified_ref = predicate->get ();
// If this impl is for one of our types or supertypes
if (specified_ref->satisfies_bound (*bound_ref))
{
self_bound = &bound;
break;
}
}
// This impl block doesn't help us
if (self_bound == nullptr)
continue;
// Find the specific function in the impl block that matches "ref".
// This is the one we want to compute the address for.
HIR::Function *associated_function = nullptr;
for (auto &impl_item : impl_block->get_impl_items ())
{
bool is_function = impl_item->get_impl_item_type ()
== HIR::ImplItem::ImplItemType::FUNCTION;
if (!is_function)
continue;
HIR::Function *fn = static_cast<HIR::Function *> (impl_item.get ());
bool found_associated_item
= fn->get_function_name ().as_string ().compare (
ref->get_identifier ())
== 0;
if (found_associated_item)
associated_function = fn;
}
// This impl block satisfies the bound, but doesn't contain the relevant
// function. This could happen because of supertraits.
if (associated_function == nullptr)
continue;
// we found an impl_item for this
if (associated_function != nullptr)
{
// lookup the associated type for this item
TyTy::BaseType *lookup = nullptr;
bool ok = ctx->get_tyctx ()->lookup_type (
ok = ctx->get_tyctx ()->lookup_type (
associated_function->get_mappings ().get_hirid (), &lookup);
rust_assert (ok);
rust_assert (lookup->get_kind () == TyTy::TypeKind::FNDEF);
@@ -354,7 +338,7 @@ HIRCompileBase::compute_address_for_trait_item (
}
return CompileInherentImplItem::Compile (associated_function, ctx,
lookup_fntype, true, locus);
lookup_fntype, locus);
}
// we can only compile trait-items with a body

View File

@@ -1901,6 +1901,9 @@ eval_constant_expression (const constexpr_ctx *ctx, tree t, bool lval,
location_t loc = EXPR_LOCATION (t);
if (t == NULL_TREE)
return NULL_TREE;
if (CONSTANT_CLASS_P (t))
{
if (TREE_OVERFLOW (t))
@@ -2697,10 +2700,8 @@ eval_store_expression (const constexpr_ctx *ctx, tree t, bool lval,
}
if (TREE_CODE (probe) == ARRAY_REF)
{
// TODO
rust_unreachable ();
// elt = eval_and_check_array_index (ctx, probe, false,
// non_constant_p, overflow_p);
elt = eval_and_check_array_index (ctx, probe, false,
non_constant_p, overflow_p);
if (*non_constant_p)
return t;
}
@@ -2929,8 +2930,13 @@ eval_store_expression (const constexpr_ctx *ctx, tree t, bool lval,
}
}
if (*non_constant_p)
return t;
/* Don't share a CONSTRUCTOR that might be changed later. */
init = unshare_constructor (init);
if (init == NULL_TREE)
return t;
if (*valp && TREE_CODE (*valp) == CONSTRUCTOR
&& TREE_CODE (init) == CONSTRUCTOR)
@@ -3585,9 +3591,6 @@ eval_call_expression (const constexpr_ctx *ctx, tree t, bool lval,
result = *ctx->global->values.get (res);
if (result == NULL_TREE && !*non_constant_p)
{
if (!ctx->quiet)
error ("%<constexpr%> call flows off the end "
"of the function");
*non_constant_p = true;
}
}

View File

@@ -21,7 +21,6 @@
#include "rust-unicode.h"
#include "rust-diagnostics.h"
#include "rust-system.h"
#include <sstream>
namespace Rust {
namespace Compile {

View File

@@ -25,7 +25,6 @@
#include "rust-unicode.h"
#include "rust-punycode.h"
#include "rust-compile-type.h"
#include <sstream>
namespace Rust {
namespace Compile {
@@ -279,16 +278,17 @@ v0_type_path (V0Path path, std::string ident)
}
static V0Path
v0_function_path (V0Path path, Rust::Compile::Context *ctx,
const TyTy::BaseType *ty, HIR::Function *fn,
std::string ident)
v0_function_path (
V0Path path, Rust::Compile::Context *ctx, const TyTy::BaseType *ty,
const std::vector<std::unique_ptr<HIR::GenericParam>> &generic_params,
std::string ident)
{
V0Path v0path;
v0path.prefix = "N";
v0path.ns = "v";
v0path.path = path.as_string ();
v0path.ident = ident;
if (!fn->get_generic_params ().empty ())
if (!generic_params.empty ())
{
v0path.generic_prefix = "I";
v0path.generic_postfix = v0_generic_args (ctx, ty) + "E";
@@ -327,7 +327,7 @@ v0_inherent_or_trait_impl_path (Rust::Compile::Context *ctx,
// lookup impl type
TyTy::BaseType *impl_ty = nullptr;
ok = ctx->get_tyctx ()->lookup_type (
impl_block->get_type ()->get_mappings ().get_hirid (), &impl_ty);
impl_block->get_type ().get_mappings ().get_hirid (), &impl_ty);
rust_assert (ok);
// FIXME: dummy value for now
@@ -341,7 +341,7 @@ v0_inherent_or_trait_impl_path (Rust::Compile::Context *ctx,
TyTy::BaseType *trait_ty = nullptr;
ok = ctx->get_tyctx ()->lookup_type (
impl_block->get_trait_ref ()->get_mappings ().get_hirid (), &trait_ty);
impl_block->get_trait_ref ().get_mappings ().get_hirid (), &trait_ty);
rust_assert (ok);
v0path.trait_type = v0_type_prefix (ctx, trait_ty);
@@ -369,34 +369,30 @@ static std::string
v0_path (Rust::Compile::Context *ctx, const TyTy::BaseType *ty,
const Resolver::CanonicalPath &cpath)
{
auto mappings = Analysis::Mappings::get ();
auto &mappings = Analysis::Mappings::get ();
V0Path v0path = {};
cpath.iterate_segs ([&] (const Resolver::CanonicalPath &seg) {
HirId hir_id;
bool ok = mappings->lookup_node_to_hir (seg.get_node_id (), &hir_id);
if (!ok)
tl::optional<HirId> hid = mappings.lookup_node_to_hir (seg.get_node_id ());
if (!hid.has_value ())
{
// FIXME: generic arg in canonical path? (e.g. <i32> in crate::S<i32>)
rust_unreachable ();
}
HirId parent_impl_id = UNKNOWN_HIRID;
HIR::ImplItem *impl_item
= mappings->lookup_hir_implitem (hir_id, &parent_impl_id);
HIR::TraitItem *trait_item = mappings->lookup_hir_trait_item (hir_id);
HIR::Item *item = mappings->lookup_hir_item (hir_id);
HIR::Expr *expr = mappings->lookup_hir_expr (hir_id);
auto hir_id = hid.value ();
if (impl_item != nullptr)
if (auto impl_item = mappings.lookup_hir_implitem (hir_id))
{
switch (impl_item->get_impl_item_type ())
switch (impl_item->first->get_impl_item_type ())
{
case HIR::ImplItem::FUNCTION: {
HIR::Function *fn = static_cast<HIR::Function *> (impl_item);
v0path = v0_function_path (v0path, ctx, ty, fn,
v0_identifier (seg.get ()));
HIR::Function *fn
= static_cast<HIR::Function *> (impl_item->first);
v0path
= v0_function_path (v0path, ctx, ty, fn->get_generic_params (),
v0_identifier (seg.get ()));
}
break;
case HIR::ImplItem::CONSTANT:
@@ -408,13 +404,15 @@ v0_path (Rust::Compile::Context *ctx, const TyTy::BaseType *ty,
break;
}
}
else if (trait_item != nullptr)
else if (auto trait_item = mappings.lookup_hir_trait_item (hir_id))
{
switch (trait_item->get_item_kind ())
switch (trait_item.value ()->get_item_kind ())
{
case HIR::TraitItem::FUNC: {
HIR::Function *fn = static_cast<HIR::Function *> (impl_item);
v0path = v0_function_path (v0path, ctx, ty, fn,
auto fn = static_cast<HIR::TraitItemFunc *> (*trait_item);
rust_unreachable ();
v0path = v0_function_path (v0path, ctx, ty,
fn->get_decl ().get_generic_params (),
v0_identifier (seg.get ()));
}
break;
@@ -427,13 +425,14 @@ v0_path (Rust::Compile::Context *ctx, const TyTy::BaseType *ty,
break;
}
}
else if (item != nullptr)
switch (item->get_item_kind ())
else if (auto item = mappings.lookup_hir_item (hir_id))
switch (item.value ()->get_item_kind ())
{
case HIR::Item::ItemKind::Function: {
HIR::Function *fn = static_cast<HIR::Function *> (item);
v0path = v0_function_path (v0path, ctx, ty, fn,
v0_identifier (seg.get ()));
HIR::Function *fn = static_cast<HIR::Function *> (*item);
v0path
= v0_function_path (v0path, ctx, ty, fn->get_generic_params (),
v0_identifier (seg.get ()));
}
break;
case HIR::Item::ItemKind::Module:
@@ -452,7 +451,7 @@ v0_path (Rust::Compile::Context *ctx, const TyTy::BaseType *ty,
case HIR::Item::ItemKind::Impl:
// Trait impl or inherent impl.
{
HIR::ImplBlock *impl_block = static_cast<HIR::ImplBlock *> (item);
HIR::ImplBlock *impl_block = static_cast<HIR::ImplBlock *> (*item);
v0path = v0_inherent_or_trait_impl_path (ctx, impl_block);
}
break;
@@ -465,9 +464,9 @@ v0_path (Rust::Compile::Context *ctx, const TyTy::BaseType *ty,
cpath.get ().c_str ());
break;
}
else if (expr != nullptr)
else if (auto expr = mappings.lookup_hir_expr (hir_id))
{
rust_assert (expr->get_expression_type ()
rust_assert (expr.value ()->get_expression_type ()
== HIR::Expr::ExprType::Closure);
// Use HIR ID as disambiguator.
v0path = v0_closure (v0path, hir_id);
@@ -490,7 +489,7 @@ v0_mangle_item (Rust::Compile::Context *ctx, const TyTy::BaseType *ty,
rust_debug ("Start mangling: %s", path.get ().c_str ());
// TODO: get Instanciating CrateNum
// auto mappings = Analysis::Mappings::get ();
// auto &mappings = Analysis::Mappings::get ();
// std::string crate_name;
// bool ok = mappings->get_crate_name (path.get_crate_num (), crate_name);
// rust_assert (ok);

View File

@@ -5371,8 +5371,8 @@ c_common_type_for_mode (machine_mode mode, int unsignedp)
else if (GET_MODE_CLASS (mode) == MODE_VECTOR_BOOL
&& valid_vector_subparts_p (GET_MODE_NUNITS (mode)))
{
unsigned int elem_bits
= vector_element_size (GET_MODE_PRECISION (mode), GET_MODE_NUNITS (mode));
unsigned int elem_bits = vector_element_size (GET_MODE_PRECISION (mode),
GET_MODE_NUNITS (mode));
tree bool_type = build_nonstandard_boolean_type (elem_bits);
return build_vector_type_for_mode (bool_type, mode);
}

View File

@@ -139,12 +139,6 @@
should be initialized.) */
#define CLASSTYPE_VBASECLASSES(NODE) (LANG_TYPE_CLASS_CHECK (NODE)->vbases)
/* A vector of BINFOs for the direct and indirect virtual base classes
that this type uses in a post-order depth-first left-to-right
order. (In other words, these bases appear in the order that they
should be initialized.) */
#define CLASSTYPE_VBASECLASSES(NODE) (LANG_TYPE_CLASS_CHECK (NODE)->vbases)
/* We used to have a variant type for lang_type. Keep the name of the
checking accessor for the sole survivor. */
#define LANG_TYPE_CLASS_CHECK(NODE) (TYPE_LANG_SPECIFIC (NODE))
@@ -783,12 +777,6 @@ extern GTY (()) tree cp_global_trees[CPTI_MAX];
#define CLASSTYPE_PRIMARY_BINFO(NODE) \
(LANG_TYPE_CLASS_CHECK (NODE)->primary_base)
/* A vector of BINFOs for the direct and indirect virtual base classes
that this type uses in a post-order depth-first left-to-right
order. (In other words, these bases appear in the order that they
should be initialized.) */
#define CLASSTYPE_VBASECLASSES(NODE) (LANG_TYPE_CLASS_CHECK (NODE)->vbases)
/* The type corresponding to NODE when NODE is used as a base class,
i.e., NODE without virtual base classes or tail padding. */
#define CLASSTYPE_AS_BASE(NODE) (LANG_TYPE_CLASS_CHECK (NODE)->as_base)

Some files were not shown because too many files have changed in this diff Show More